Skip to content

[fsdp] 2/n Expose backward-prefetch policy - #5675

Closed
shuhuayu wants to merge 1 commit into
mainfrom
shuhuayu/k3-dm-stack-02
Closed

shuhuayu wants to merge 1 commit into
mainfrom
shuhuayu/k3-dm-stack-02

Conversation

@shuhuayu

@shuhuayu shuhuayu commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

Part 2/n of the Kimi K3 / Dist-MoE training stack. Targets main after #5674 merged; the review diff contains only this feature.

human notes:

add an knob to expose backward-prefetch policy when ep is enabled. previously, backward-prefetch is always on when ep is on, after this pr, one can disable it to reduce peak memory.

Why

Expert-parallel decoder setup always wires explicit backward prefetch. Memory-constrained pipeline/CUDA-graph recipes cannot opt out of gathering the next parameter unit early. Leaving explicit targets empty does not disable prefetch: FSDP uses its implicit fallback.

Example:

ParallelismConfig(
    expert_parallel_degree=4,
    fsdp_enable_backward_prefetch=False,
)
# Current parameters are still gathered when backward needs them.
# Do not gather the next backward parameter unit early.
# Forward-prefetch and reshard/reduction policies are unchanged.

What changed

  • Add default-on fsdp_enable_backward_prefetch and propagate enable_backward_prefetch through common decoder and MTP FSDP setup.
  • Build neighboring source/target pairs when enabled, or self-pairs for every FSDP module when disabled. One shared loop applies the targets with the public FSDP setter.
  • A self-pair (A, A) becomes A.set_modules_to_backward_prefetch([A]). The nonempty target list suppresses implicit prefetch; A's parameters are already prepared by its own pre-backward hook, so the self-prefetch adds no all-gather.
  • Extend the existing wiring test to empty, one-layer, and multi-layer stages while retaining its forward-prefetch and decoder/MTP policy checks.

Alternatives considered

  • An empty target list retains FSDP's implicit fallback rather than disabling prefetch.
  • Disabling forward prefetch would change a separate overlap policy.
  • Calling private FSDP state APIs is unnecessary: self-targets use the existing public setter.

User-facing changes

Setting Behavior
Default fsdp_enable_backward_prefetch=True with EP Preserve the existing backward-prefetch target order.
fsdp_enable_backward_prefetch=False with EP Suppress explicit and implicit backward prefetch, trading overlap for lower peak unsharded-parameter memory.
Without EP This option has no effect.

The shorter knob name reflects its scope: disabling it suppresses both explicit and implicit backward prefetch, not only explicit targets.

Numerics

No model arithmetic, parameter layout, reduction dtype, forward-prefetch policy, or reshard policy changes.

Real two-rank GB300 checks compared the refactored setup against the preceding 2/n implementation at 3449bed04583bc21f37307b978ed2d268e20d191, with both prefetch settings. Three updates with two accumulation microbatches, seed 42, strict deterministic algorithms, FP32 resident state/reduction, and BF16 compute views produced exact loss, gradient-norm, local gradient-shard, and updated parameter-shard equality.

Workload GPUs Before/after result
Qwen3 EP2/FSDP2, no activation checkpointing, both policies 2 Bitwise identical.
FullAC Llama3 dense stage under an EP2/FSDP2 mesh, both policies 2 Bitwise identical.

These are small numerical checks, not full-scale memory/performance or fresh CUDA-graph replay acceptance. No isolated end-to-end speedup is claimed.

Testing

79 CPU checks passed for the current local amendment on main (ff96670a2):

CUDA_VISIBLE_DEVICES='' OMP_NUM_THREADS=1 python -m pytest -q -p no:cacheprovider --tb=short \
  tests/unit_tests/cpu/config/test_parallelism_config.py \
  tests/unit_tests/cpu/distributed/test_fsdp.py \
  tests/unit_tests/cpu/distributed/test_parallelism_context.py \
  tests/unit_tests/cpu/models/deepseek_v4/test_deepseek_v4_mtp.py \
  tests/unit_tests/cpu/observability/test_sdc_replayer.py

An additional local comparison passed 192 exact ordered target-plan cases against the preceding implementation: 0/1/3 layers, optional embedding/norm/head, tied/untied weights, EP1/EP2, both policies, and nested FSDP units.

All non-type pre-commit hooks and git diff --check passed. Type checking of the local amendment found no new FSDP errors.

Known issues / landing gates

The same three local Pyrefly errors were independently reproduced on unchanged upstream: missing torch_checkpointing.checkpoint_writer.CallbackArgs, its related callback signature mismatch, and optional video.stream.time_base multiplication. No unrelated source or dependency workaround is included.

Fresh CUDA-graph replay and large-scale memory/performance are not separately verified at this prefix. A maintainer still needs to review the core changes.

Stack

#5674 has merged. This PR now targets main. Next: #5676.

Full draft stack — review and land in this order
Position Draft PR
1/n #5674 — [distributed] 1/n Apply initialization timeouts to mesh process groups
2/n #5675 — [fsdp] 2/n Expose backward-prefetch policy
3/n #5676 — [fsdp] 3/n Support layer-scoped CPU offload
4/n #5677 — [optim] 4/n Bound optimizer memory ownership and allocation lifetimes
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 #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 Make startup and update-boundary cache release explicit
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

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-01 branch 3 times, most recently from ac9de47 to e548e1e Compare October 30, 2026 00:30
@shuhuayu
shuhuayu force-pushed the shuhuayu/k3-dm-stack-02 branch 2 times, most recently from 5bd76c1 to 7408602 Compare October 30, 2026 04:34
@shuhuayu
shuhuayu force-pushed the shuhuayu/k3-dm-stack-01 branch from e548e1e to 15fac46 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-02 branch from 7408602 to 3449bed Compare October 30, 2026 18:01
@shuhuayu
shuhuayu changed the base branch from shuhuayu/k3-dm-stack-01 to main October 30, 2026 18:01
Propagate the backward-prefetch policy through decoder and MTP FSDP setup. When disabled, suppress the implicit fallback without changing the default communication policy.
@shuhuayu
shuhuayu force-pushed the shuhuayu/k3-dm-stack-02 branch from 3449bed to 133871f Compare October 30, 2026 21:42
@shuhuayu shuhuayu changed the title [fsdp] 2/n Expose explicit backward-prefetch policy [fsdp] 2/n Expose backward-prefetch policy Oct 30, 2026
@shuhuayu

Copy link
Copy Markdown
Contributor Author

@claude review

@claude

claude Bot commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

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


Request changes -- see the review for details.

@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 -- No recipe in the repo or the stack turns the new knob off, and it silently does nothing without EP. The mechanism works, but it relies on undocumented FSDP2 behavior and has no upstream TODO.

What this PR does. It adds ParallelismConfig.fsdp_enable_backward_prefetch (default True) and passes it to apply_fsdp_to_decoder and the MTP wrapper. With EP on and the flag True, the existing backward-prefetch chain (lm_head -> last layer -> ... -> first layer -> tok_embeddings) is rebuilt as a list of pairs. I checked the order against main for 0, 1 and N layers and it is the same. With the flag False, every FSDP module gets itself as its only backward-prefetch target. The list is then nonempty, so FSDP skips its implicit prefetch, and the self-target finds its own parameters already unsharded, so no extra all-gather happens.

Example.

# EP=4, 3 layers, fsdp_enable_backward_prefetch=False
# main:  layers.2.pre_backward -> unshard(layers.2), prefetch unshard(layers.1)
#        => two layers' unsharded params live at once
# PR:    layers.2.set_modules_to_backward_prefetch([layers.2])
#        layers.2.pre_backward -> unshard(layers.2); self-target unshard() is a no-op
#        => one layer live; layers.1 is gathered only when its own pre_backward fires
# EP=1 with the same setting: early return at fsdp.py:517 -> implicit prefetch still runs, no error

Must fix

  1. PR description -- there is no "Summary (human-written)" section from .github/pull_request_template.md. The author needs to write it. The description also says it "extends the existing wiring test", but test_apply_fsdp_to_decoder_configures_backward_prefetch_policy is a new test function.
  2. No consumer and no value evidence. Nothing in this PR or later in the stack sets the flag to False: #5684 doesn't reference it, and #5676 only sets it in unit tests. The PR also gives no peak-memory number ("large-scale memory/performance ... not separately verified"). rules/config.md says to expose only options a verified recipe uses. Please name the recipe that will set it to False and give the measured peak-memory saving and throughput cost. Otherwise, hold the knob until that recipe lands.
  3. torchtitan/config/parallelism.py:69 -- the setting silently does nothing when EP=1. Apply it EP-independently or raise (inline).
  4. torchtitan/distributed/fsdp.py:555 -- the self-target trick works around a missing FSDP2 API and depends on FSDP2 internals. Add a TODO with an upstream issue link (inline).

Should consider

  • torchtitan/config/parallelism.py:64 -- new enable_* boolean; fsdp_backward_prefetch matches its siblings (inline).
  • torchtitan/distributed/fsdp.py:287 -- the internal default duplicates the config default; make it a required keyword-only argument (inline).
  • The numerics check compares against the earlier revision of this PR (3449bed), not main. The default-on path rewrites code that is on main, so the bitwise check should use main (ff96670) as its baseline. From reading the code I expect it to be identical.

Questions

  • Your motivation mentions memory-constrained PP/CUDA-graph recipes. Is dense (EP=1) PP also a target? If so, that supports applying the setting EP-independently.
Details
  • Equivalence of the default path. main sets: lm_head -> [layers[-1]] (only when norm and lm_head exist and there is at least one layer), each layers[i] -> [layers[i-1]], and layers[0] -> [tok_embeddings] when tok_embeddings exists. The new order list, [lm_head?] + reversed(layers) + [tok_embeddings?], built only when layers is nonempty, produces exactly these pairs. With weight tying, lm_head/norm/tok_embeddings share one FSDP state, as on main.
  • Disabled path. model.modules() filtered on FSDPModule covers the root, the embedding/norm/head units, every layer (including MTP layers temporarily inserted by apply_fsdp_to_mtp_decoder), and nested units added later in the stack (#5676). Under tying, the three modules write the same shared state, which is fine. tok_embeddings with unshard_in_backward=False stays un-gathered, because unshard() returns early in PRE_BACKWARD.
  • Smaller alternative for the EP gap. Move the else branch (self-pairs) above if ep_degree == 1: return, and keep the neighbor-pair branch where it is. About the same LoC, and the docstring caveats go away.
  • Test. It is a cheap CPU mock test. It guards the self-target wiring, which would otherwise regress silently as higher memory. It doesn't check the actual claim (no implicit prefetch and no extra all-gather), because that is upstream behavior. That gap is one more reason for the upstream TODO.

Not verified: FSDP2 internals (_pre_backward default-prefetch condition, unshard() early return) were checked from my knowledge of upstream source, not against the installed torch version, because torch isn't installed in this runner. A maintainer still needs to review the core changes.

Comment on lines +66 to +69

Disabling this also suppresses FSDP's implicit fallback prefetch, reducing
peak unsharded-parameter memory at the cost of communication overlap. It
has no effect when expert parallelism is off.

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.

If you set fsdp_enable_backward_prefetch=False without EP, it silently does nothing: apply_fsdp_to_decoder returns at if ep_degree == 1: (fsdp.py:517) before the new branch runs. A dense or EP=1 run with this setting still gets FSDP's implicit backward prefetch and the memory it costs, and nothing tells the user. CLAUDE.md principle 8 says an unsupported combination should raise, not be ignored.

The self-target mechanism doesn't depend on EP, and the motivation you give (memory-constrained PP/CUDA-graph recipes) isn't EP-specific either. The smallest fix is to apply the else branch for every decoder by moving it above the ep_degree == 1 return. That's about 5 moved lines, and the default path doesn't change. Then delete the "no effect without EP" sentence here and in the apply_fsdp_to_decoder docstring. If you really want it to stay EP-only, raise a ValueError in ParallelismConfig.__post_init__ when it is False and expert_parallel_degree == 1.

Comment on lines +552 to +555
# An empty explicit target list enables FSDP's implicit fallback
# prefetch. A self target keeps the list nonempty, but its own
# pre-backward hook has already prepared the parameters. This avoids
# an extra all-gather and live parameter unit.

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 self-target trick is a workaround for something FSDP2 doesn't provide: there is no public way to turn off implicit backward prefetch. It also leans on two undocumented internals. First, FSDPState._pre_backward computes default_prefetch = len(self._states_to_backward_prefetch) == 0. Second, FSDPParamGroup.unshard() returns early when the group is already unsharded (or when unshard_in_backward=False, as on tok_embeddings). If either of these changes upstream, this path would silently start all-gathering again, or would gather a unit twice.

Per CLAUDE.md principle 3, please add a TODO here that links an upstream pytorch/pytorch issue asking for a public way to disable it, for example making an explicit empty list mean "no prefetch", or a set_backward_prefetch(False). That way the trick can be deleted once upstream supports this.

fsdp_defer_gradient_reduction: bool = False
"""Defer FSDP gradient reduction until the last accumulation step."""

fsdp_enable_backward_prefetch: bool = True

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.

Naming: rules/config.md and direction.md say not to add new enable_* booleans. This field is a policy toggle, not an optional component, so the closest sibling is fsdp_defer_gradient_reduction: bool. Consider renaming it fsdp_backward_prefetch: bool = True, and the parameter in apply_fsdp_to_decoder/apply_fsdp_to_mtp_decoder to backward_prefetch.

pp_enabled: bool,
cpu_offload: bool = False,
reshard_after_forward_policy: str = "default",
enable_backward_prefetch: bool = True,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This = True repeats the config default. CLAUDE.md says internal functions shouldn't carry defaults that duplicate a config default. All three in-repo callers (decoder.py, deepseek_v3/mtp.py, deepseek_v4/model.py) already pass it explicitly. Consider making it a required keyword-only argument, here and in apply_fsdp_to_mtp_decoder (mtp.py:462). That way a new caller can't silently pick a value that differs from the config.

@shuhuayu shuhuayu closed this Nov 3, 2026
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 added a commit that referenced this pull request Nov 5, 2026
Part **4/n** of the Kimi K3 / Dist-MoE training stack. Based directly on
`main`: the review diff contains only the optimizer-memory changes
below.

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

## Why

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

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

**Example.**

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

## What changed

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

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

## User-facing behavior

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

## Numerics

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

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

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

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

## Memory evidence

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

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

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

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

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

## Testing

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

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

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

## Stack

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

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

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

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

</details>

After this PR lands, rebase the remaining suffix onto updated main and
retarget its next bottom PR to main. Keep the rest stacked; no automatic
landing is requested.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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.

1 participant