Skip to content

[FSDP2] Add FSDPModule.get_all_gather_copy_in_stream - #205180

Closed
anijain2305 wants to merge 1 commit into
gh/anijain2305/1362/basefrom
gh/anijain2305/1362/head
Closed

anijain2305 wants to merge 1 commit into
gh/anijain2305/1362/basefrom
gh/anijain2305/1362/head

Conversation

@anijain2305

@anijain2305 anijain2305 commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Code outside FSDP that issues its own host-to-device copies has no way to
order them against FSDP's: under CPUOffloadPolicy, each unshard's copy-in
first copies the parameter shards host-to-device on the all-gather copy-in
stream, which is only reachable through the private comm context.

The use case is activation offloading (pytorch/torchtitan#6020). In
backward, FSDP's pre-backward hook on a module's output prefetches the
previous module's parameters, and the offloader's hook on the same output
reloads that module's activations. Both host-to-device copies become ready
together and share the link's bandwidth, so the parameters arrive late and
the all-gather that still has to follow them starts late. Waiting on the
copy-in stream lets the reload go after FSDP's parameter copies, so the
all-gather overlaps the reload instead.

get_all_gather_copy_in_stream() returns that stream. It is created at
lazy initialization, so calling it earlier raises. With
set_unshard_in_current_stream, or a single rank, FSDP's copy-ins run on the
current stream and this stream carries none of them; waiting on it is then
a no-op, which keeps callers mode-agnostic.

Test plan:
test_fully_shard_training.py -k AllGatherCopyInStream (2 GPUs): before
lazy init it raises, for the root and a child; after a forward and backward,
every module under the root returns the same stream and every copy-in ran
on it; with set_unshard_in_current_stream, no copy-in ran on it.

[ghstack-poisoned]
@pytorch-bot pytorch-bot Bot added the release notes: distributed (fsdp) release notes category label Nov 16, 2026
@pytorch-bot

pytorch-bot Bot commented Nov 16, 2026 •

Copy link
Copy Markdown

PR Status: Approved 🚀

Please fix all CI failures and trigger merge by commenting "@pytorchbot merge".

✅ AUTOMATED REVIEW - Ready for human review:

The PR adds a public `FSDPModule.get_all_gather_copy_in_stream()`, which returns
FSDP's shared all-gather copy-in stream after lazy init, plus two 2-GPU tests.
The review found no blocking problems but says the new public contract is
inaccurate in three places (under `share_comm_ctx`, for unsharded groups, and
the "no-op" claim) and that some test assertions are weak. Recommendation:
Approve, with every point labeled non-blocking; the review still asks that the
`share_comm_ctx` staleness and the "no-op" wording be fixed before callers
depend on the contract.

Findings (8):

[minor] torch/distributed/fsdp/_fully_shard/_fully_shard.py:1222
The stream goes stale under `share_comm_ctx`, so a stream the caller saved stops
ordering anything (non-blocking, but worth fixing before callers depend on it).
The docstring says the stream "is shared by the FSDP modules under one root, and
created at lazy initialization, in the root module's first forward". With the
public `share_comm_ctx` (the pipeline-parallel setup), several roots share one
`FSDPCommContext`. Each root's `_lazy_init` calls
`self._comm_ctx.lazy_init(self._device)` (`_fsdp_state.py:252`), which has no
guard and always assigns a new `all_gather_copy_in_stream`
(`_fsdp_param_group.py:95-97`). Scenario: chunk 0 runs its first forward and the
caller saves the stream, then chunk 1's first forward replaces it, so waiting on
the saved stream silently orders nothing. Fix: make `FSDPCommContext.lazy_init`
keep streams it already created, or document that the stream is shared across
`share_comm_ctx` roots and must be fetched each time it is used (or only after
every sharing root has run forward).

[minor] torch/distributed/fsdp/_fully_shard/_fully_shard.py:1220
Waiting on the stream is not a no-op in current-stream or unsharded mode
(non-blocking). The PR body says waiting "is then a no-op", and "this stream
carries none of them" implies the same. But the copy-in stream still waits on
the compute stream at root pre-forward (`_fsdp_state.py:155-162`) and on every
copy-out event in the non-deferred branch (`_fsdp_param_group.py:577-578`),
which always runs with `set_unshard_in_current_stream` and when `world_size ==
1`. So a waiter is ordered after all current-stream work up to the latest
copy-out. That is neither free nor mode-agnostic. The stream also runs
`param_dtype` casts and `fsdp_pre_all_gather` extension compute, not only copies
(`_fsdp_param.py:1194-1242`). The docstring should state what a wait actually
orders after.

[minor] torch/distributed/fsdp/_fully_shard/_fully_shard.py:1219
"With a single rank" is the wrong condition (non-blocking). The early return
that skips `foreach_all_gather` is decided per param group
(`_fsdp_param_group.py:471-487`). It triggers when the shard group has size 1 or
when `mesh_info` is not an `FSDPMeshInfo`. That covers HSDP with shard size 1
and every `replicate()` module at any world size: `ReplicateModule(FSDPModule)`
inherits this method, and `DDPMeshInfo` is not an `FSDPMeshInfo`. Suggest "when
parameters are not sharded (shard group of size 1, e.g. `replicate()`)".

(5 more not shown, see the review run)

Reviewed commit: 85d8a2c

Review run

🐛 Report a bad review

🔗 Helpful Links

🧪 See artifacts and rendered test results at hud.pytorch.org/pr/205180

Note: Links to docs will display an error until the docs builds have been completed.

✅ No Failures

As of commit 85d8a2c with merge base bba8f39 (image):
💚 Looks good so far! There are no failures yet. 💚

🟡 GREEN LIGHT - PR requires human review:

  • Triviality
    • New feature: adds public method FSDPModule.get_all_gather_copy_in_stream in _fully_shard.py, which fits no trivial change class
    • FSDPModule is listed under autoclass with :members: in docs/source/distributed/fsdp.fully_shard.md, so this grows the documented public API
  • Inert addition
    • Only the new tests in test_fully_shard_training.py call it; the PR says its consumer is torchtitan, outside this repo
  • Contract design for a human
    • Under share_comm_ctx, each root's lazy init calls FSDPCommContext.lazy_init, which builds a new all_gather_copy_in_stream every time it runs, so a saved stream can go stale

reason: not_trivial
Reviewed commit: 85d8a2c

Inference job

🐛 Report a wrong verdict

This comment was automatically generated by Dr. CI and updates every 15 minutes.

@pytorch-bot pytorch-bot Bot added ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests labels Nov 16, 2026
@pytorchgreenlight pytorchgreenlight Bot added the GL/human GreenLight marked as needing human review label Nov 16, 2026
@pytorchbot pytorchbot added the in progress PR is being worked on by the author, until the automated review accepts it label Nov 16, 2026

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

Automated review of 85d8a2c: nothing blocking; ready for human review.

The PR adds a public FSDPModule.get_all_gather_copy_in_stream(), which returns FSDP's shared all-gather copy-in stream after lazy init, plus two 2-GPU tests. The review found no blocking problems but says the new public contract is inaccurate in three places (under share_comm_ctx, for unsharded groups, and the "no-op" claim) and that some test assertions are weak. Recommendation: Approve, with every point labeled non-blocking; the review still asks that the share_comm_ctx staleness and the "no-op" wording be fixed before callers depend on the contract.

⚪ 8 non-blocking findings

The stream is shared by the FSDP modules under one root, and created

The stream goes stale under share_comm_ctx, so a stream the caller saved stops ordering anything (non-blocking, but worth fixing before callers depend on it). The docstring says the stream "is shared by the FSDP modules under one root, and created at lazy initialization, in the root module's first forward". With the public share_comm_ctx (the pipeline-parallel setup), several roots share one FSDPCommContext. Each root's _lazy_init calls self._comm_ctx.lazy_init(self._device) (_fsdp_state.py:252), which has no guard and always assigns a new all_gather_copy_in_stream (_fsdp_param_group.py:95-97). Scenario: chunk 0 runs its first forward and the caller saves the stream, then chunk 1's first forward replaces it, so waiting on the saved stream silently orders nothing. Fix: make FSDPCommContext.lazy_init keep streams it already created, or document that the stream is shared across share_comm_ctx roots and must be fetched each time it is used (or only after every sharing root has run forward).


and this stream carries none of them.

Waiting on the stream is not a no-op in current-stream or unsharded mode (non-blocking). The PR body says waiting "is then a no-op", and "this stream carries none of them" implies the same. But the copy-in stream still waits on the compute stream at root pre-forward (_fsdp_state.py:155-162) and on every copy-out event in the non-deferred branch (_fsdp_param_group.py:577-578), which always runs with set_unshard_in_current_stream and when world_size == 1. So a waiter is ordered after all current-stream work up to the latest copy-out. That is neither free nor mode-agnostic. The stream also runs param_dtype casts and fsdp_pre_all_gather extension compute, not only copies (_fsdp_param.py:1194-1242). The docstring should state what a wait actually orders after.


with a single rank, those copy-ins run on the current stream instead,

"With a single rank" is the wrong condition (non-blocking). The early return that skips foreach_all_gather is decided per param group (_fsdp_param_group.py:471-487). It triggers when the shard group has size 1 or when mesh_info is not an FSDPMeshInfo. That covers HSDP with shard size 1 and every replicate() module at any world size: ReplicateModule(FSDPModule) inherits this method, and DDPMeshInfo is not an FSDPMeshInfo. Suggest "when parameters are not sharded (shard group of size 1, e.g. replicate())".


def get_all_gather_copy_in_stream(self) -> torch.Stream:

The method makes an internal stream a public contract without the guardrails similar APIs carry (non-blocking). The docstring guarantees one stream per root, which unshards use it, and that it carries nothing in current-stream mode, so merging streams or moving to per-group streams later would need a deprecation. set_custom_all_reduce and set_reduce_scatter_input_fn carry the .. warning:: This API is experimental... note; consider adding it here. Add one sentence saying callers should only wait on this stream and never enqueue work on it. Enqueued work delays FSDP's copy-ins (all_gather_stream.wait_stream(all_gather_copy_in_stream), _fsdp_collectives.py:394) and allocates into that stream's caching-allocator pool, the fragmentation set_unshard_in_current_stream was added to avoid. A narrower alternative, like set_post_optim_event: return an event recorded on the stream, or provide a wait_for_all_gather_copy_in(stream) helper.


"Call this after the root FSDP module's first forward."

The error message names the wrong module type and the wrong trigger (non-blocking). It hardcodes "root FSDP module", while neighbouring errors use state._state_name (_fully_shard.py:499-503, _fsdp_state.py:190,212), so a replicate() user would see "FSDP". Also, the fully_shard docstring says lazy init happens at "the first forward or FSDPModule.unshard", but unshard() only runs the param group's lazy_init, never state._lazy_init. A user who called unshard() first therefore gets "called before lazy initialization". Say "before the root module's first forward" in both the Raises: section and the message.


Weak assertion (non-blocking): test_get_all_gather_copy_in_stream only checks len(streams) > 0. It would still pass if no pre-backward unshard or prefetch recorded a copy-in, which is the use case the docstring presents. This model has four copy-ins: two in forward, plus model\[1\]'s pre-backward unshard and model\[0\]'s prefetch. Assert that count, or record the training state with each copy-in.


self.assertTrue(all(s != stream for s in copy_in_streams))

Weak assertion (non-blocking): test_get_all_gather_copy_in_stream_unshard_in_current_stream only checks all(s != stream ...), so it would pass if copy-ins moved to all_gather_stream or any other side stream. Assert that each recorded stream equals torch.get_device_module(device_type).current_stream(). Also, assertTrue(all(...)) (here and at line 421) prints only "False is not true" on failure. assertEqual(set(copy_in_streams), {stream}) would show which stream was wrong.


def test_get_all_gather_copy_in_stream_unshard_in_current_stream(self):

The two tests differ by one flag and each spawns its own processes. The file usually covers such variants with run_subtests (for example {"unshard_in_current_stream": \[False, True\]}), and a CPUOffloadPolicy case would fit there too.

This review is AI-generated and advisory. Each new automated review replaces the previous one. Report a bad review

"The all-gather copy-in stream is created at lazy initialization. "
"Call this after the root FSDP module's first forward."
)
return state._comm_ctx.all_gather_copy_in_stream

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.

@claude does state._comm_ctx.all_gather_copy_in_stream works no matter set_unshard_in_current_stream or not?

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.

Yes, copying from the agent output

Yes, it's always valid: FSDPCommContext.lazy_init creates all_gather_copy_in_stream unconditionally, and set_unshard_in_current_stream only flips unshard_async_op on the param groups, so the accessor returns the same stream either way (even if toggled after lazy init).

What changes is whether FSDP uses it: get_all_gather_streams returns the separate streams only for non-async pre-forward/pre-backward unshards, so with set_unshard_in_current_stream (or a single rank) the copy-ins run on the current stream and this stream carries none. Waiting on it then holds nothing back, while anything ordered after the current stream already follows those copy-ins, so callers can wait on it without knowing the mode. The docstring calls this out, and test_get_all_gather_copy_in_stream_unshard_in_current_stream checks that no copy-in runs on the returned stream in that mode.

@weifengpy

Copy link
Copy Markdown
Contributor

@claude does state._comm_ctx.all_gather_copy_in_stream works no matter set_unshard_in_current_stream or not?

@claude

claude Bot commented Nov 16, 2026 •

Copy link
Copy Markdown

Claude finished @weifengpy's task in 22s —— View job


Yes, the accessor returns a valid stream in both modes. With set_unshard_in_current_stream(True), FSDP doesn't put the copy-ins on it, but the stream is not idle and waiting on it is not free.

Details (AI-generated)

Why the stream is always valid

  • FSDPCommContext.lazy_init (_fsdp_param_group.py:95-97) creates all_gather_copy_in_stream every time it runs, whatever the mode.
  • set_unshard_in_current_stream only flips fsdp_param_group.unshard_async_op (_fully_shard.py:1203). It never touches the comm context, so toggling it before or after lazy init doesn't change what the accessor returns.

What changes with the mode

get_all_gather_streams (_fsdp_param_group.py:126-136) returns the side streams only when not async_op and the training state is FORWARD or PRE_BACKWARD. Otherwise it returns current_stream, current_stream. So with unshard_async_op=True, the copy-ins run on the current stream. The same is true for every group whose all-gather is skipped (world_size == 1, _fsdp_param_group.py:471-487), which includes replicate() and HSDP with a shard size of 1.

Caveat: the stream still receives waits

FSDP still makes this stream wait on other work in that mode:

  • At root pre-forward, it waits on the compute stream or the post-optim event (_fsdp_state.py:155-162).
  • After each copy-out, it waits on the copy-out event (_fsdp_param_group.py:577-578). This is the non-deferred branch, which always runs when async_op=True or world_size == 1.

So a caller that does s.wait_stream(copy_in_stream) ends up ordered after current-stream work up to the most recent copy-out. That is still correct; it just isn't a strict no-op. For the activation-offload use case, the reload would also follow FSDP's copy-ins anyway, because in this mode they are on the current stream. Two small wording changes would make the contract accurate:

  • In the PR body, replace "waiting on it is then a no-op" with something like "waiting on it still orders correctly, because the copy-ins already precede it on the current stream".
  • In the docstring, replace "with a single rank" with "when parameters are not sharded".

anijain2305 added a commit to pytorch/torchtitan that referenced this pull request Nov 17, 2026
## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why
     this approach, and what you checked yourself. -->

Depends on pytorch/pytorch#205180 (`FSDPModule.get_all_gather_copy_in_stream`).
Stacked on #6022.

## Why

With FSDP2 CPU parameter offload, block `i`'s backward boundary queues two
host-to-device copies for block `i - 1`: FSDP2's pre-backward queues its
parameter shards on `all_gather_copy_in_stream`, then the reload trigger
queues its activations on the reload stream. Both become ready when block
`i`'s copy-out finishes and share the link's bandwidth in no defined order.
The parameters still need the all-gather after their copy; the activations
need nothing more. So when the copies do not fit in block `i`'s backward,
sharing is the worst order: both finish after `(P + A) / BW`, and only then
does the all-gather start. Parameters first lets the all-gather overlap the
activation copy, saving up to `min(all-gather, A / BW)`.

**Before -> after**, at the block `i` boundary (FSDP2 default streams):

| | Shard H2D (block i-1) | Activation H2D (group i-1) | All-gather (block i-1) starts |
|---|---|---|---|
| before | starts after copy-out (i), shares bandwidth | starts after copy-out (i), shares bandwidth | after both copies |
| after | starts after copy-out (i), alone | starts after the shard H2D and pack | after the shard H2D, overlapping the reload |

![FSDP2 default streams at a backward block boundary](https://raw.githubusercontent.com/pytorch/torchtitan/activation-offload-fsdp-order/assets/images/activation_offload_fsdp_streams.png)

## What changed

- `ActivationOffloader._reload` also waits on
  `model_part.get_all_gather_copy_in_stream()` when the model part is an
  FSDP2 module. The hook order makes this precise: FSDP2's pre-backward (a
  tensor hook on `out_i`) has queued block `i - 1`'s copy-in just before the
  reload trigger (a pre-hook on `out_i.grad_fn`) runs. The stream is read at
  reload time, after FSDP2's lazy initialization in the first forward.
- Under `fsdp_unshard_in_current_stream` or a single rank, FSDP2 runs the
  copy-in on the compute stream, which the reload already waits on, and the
  copy-in stream is idle, so the new wait changes nothing there:

  ![FSDP2 unshard_in_current_stream at a backward block boundary](https://raw.githubusercontent.com/pytorch/torchtitan/activation-offload-fsdp-order/assets/images/activation_offload_fsdp_streams_current_stream.png)
- Without CPU offload the copy-in is only a GPU-to-GPU pack kernel, so the
  reload starts after that short kernel too.
- `ACTIVATION_OFFLOAD.md`: the FSDP2 section describes the ordering, with both
  diagrams (`assets/images/activation_offload_fsdp_streams*.png`); the TODO is
  gone.

## Alternatives considered

- Issue reloads on FSDP2's copy-in stream (an earlier version of #6020):
  same-stream FIFO would make FSDP2's next copy-in queue behind a long reload.
- An event recorded right after the shard H2D: tighter (skips the pack), but
  needs FSDP2 to record it inside copy-in.

## Numerics

Ordering only; loss and gradients are unchanged. The FSDP2 CPU-offload test
checks gradients bitwise against no activation offload.

## Testing

`tests/unit_tests/gpu/distributed/test_activation_offload.py` and
`test_activation_checkpoint.py` (36 tests, GB300), run against PyTorch main's
FSDP2 with pytorch/pytorch#205180 applied:

- The FSDP2 CPU-offload test (2 ranks) records the reload stream's waits:
  every reload waits on FSDP2's copy-in stream as well as the compute stream
  (fails without the change).

Not run: an end-to-end recipe with FSDP2 CPU offload measuring the overlap.
Until pytorch/pytorch#205180 reaches a nightly, CI's Pyrefly and this test
fail on the missing method.
anijain2305 added a commit to pytorch/torchtitan that referenced this pull request Nov 17, 2026
## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why
     this approach, and what you checked yourself. -->

Depends on pytorch/pytorch#205180 (`FSDPModule.get_all_gather_copy_in_stream`).
Stacked on #6022.

## Why

With FSDP2 CPU parameter offload, block `i`'s backward boundary queues two
host-to-device copies for block `i - 1`: FSDP2's pre-backward queues its
parameter shards on `all_gather_copy_in_stream`, then the reload trigger
queues its activations on the reload stream. Both become ready when block
`i`'s copy-out finishes and share the link's bandwidth in no defined order.
The parameters still need the all-gather after their copy; the activations
need nothing more. So when the copies do not fit in block `i`'s backward,
sharing is the worst order: both finish after `(P + A) / BW`, and only then
does the all-gather start. Parameters first lets the all-gather overlap the
activation copy, saving up to `min(all-gather, A / BW)`.

**Before -> after**, at the block `i` boundary (FSDP2 default streams):

| | Shard H2D (block i-1) | Activation H2D (group i-1) | All-gather (block i-1) starts |
|---|---|---|---|
| before | starts after copy-out (i), shares bandwidth | starts after copy-out (i), shares bandwidth | after both copies |
| after | starts after copy-out (i), alone | starts after the shard H2D and pack | after the shard H2D, overlapping the reload |

![FSDP2 default streams at a backward block boundary](https://raw.githubusercontent.com/pytorch/torchtitan/activation-offload-fsdp-order/assets/images/activation_offload_fsdp_streams.png)

## What changed

- `ActivationOffloader._reload` also waits on
  `model_part.get_all_gather_copy_in_stream()` when the model part is an
  FSDP2 module. The hook order makes this precise: FSDP2's pre-backward (a
  tensor hook on `out_i`) has queued block `i - 1`'s copy-in just before the
  reload trigger (a pre-hook on `out_i.grad_fn`) runs. The stream is read at
  reload time, after FSDP2's lazy initialization in the first forward.
- Under `fsdp_unshard_in_current_stream` or a single rank, FSDP2 runs the
  copy-in on the compute stream, which the reload already waits on, and the
  copy-in stream is idle, so the new wait changes nothing there:

  ![FSDP2 unshard_in_current_stream at a backward block boundary](https://raw.githubusercontent.com/pytorch/torchtitan/activation-offload-fsdp-order/assets/images/activation_offload_fsdp_streams_current_stream.png)
- Without CPU offload the copy-in is only a GPU-to-GPU pack kernel, so the
  reload starts after that short kernel too.
- `ACTIVATION_OFFLOAD.md`: the FSDP2 section describes the ordering, with both
  diagrams (`assets/images/activation_offload_fsdp_streams*.png`); the TODO is
  gone.

## Alternatives considered

- Issue reloads on FSDP2's copy-in stream (an earlier version of #6020):
  same-stream FIFO would make FSDP2's next copy-in queue behind a long reload.
- An event recorded right after the shard H2D: tighter (skips the pack), but
  needs FSDP2 to record it inside copy-in.

## Numerics

Ordering only; loss and gradients are unchanged. The FSDP2 CPU-offload test
checks gradients bitwise against no activation offload.

## Testing

`tests/unit_tests/gpu/distributed/test_activation_offload.py` and
`test_activation_checkpoint.py` (36 tests, GB300), run against PyTorch main's
FSDP2 with pytorch/pytorch#205180 applied:

- The FSDP2 CPU-offload test (2 ranks) records the reload stream's waits:
  every reload waits on FSDP2's copy-in stream as well as the compute stream
  (fails without the change).

Not run: an end-to-end recipe with FSDP2 CPU offload measuring the overlap.
Until pytorch/pytorch#205180 reaches a nightly, CI's Pyrefly and this test
fail on the missing method.
anijain2305 added a commit to pytorch/torchtitan that referenced this pull request Nov 17, 2026
## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why
     this approach, and what you checked yourself. -->

Depends on pytorch/pytorch#205180 (`FSDPModule.get_all_gather_copy_in_stream`).
Stacked on #6022.

## Why

With FSDP2 CPU parameter offload, block `i`'s backward boundary queues two
host-to-device copies for block `i - 1`: FSDP2's pre-backward queues its
parameter shards on `all_gather_copy_in_stream`, then the reload trigger
queues its activations on the reload stream. Both become ready when block
`i`'s copy-out finishes and share the link's bandwidth in no defined order.
The parameters still need the all-gather after their copy; the activations
need nothing more. So when the copies do not fit in block `i`'s backward,
sharing is the worst order: both finish after `(P + A) / BW`, and only then
does the all-gather start. Parameters first lets the all-gather overlap the
activation copy, saving up to `min(all-gather, A / BW)`.

**Before -> after**, at the block `i` boundary (FSDP2 default streams):

| | Shard H2D (block i-1) | Activation H2D (group i-1) | All-gather (block i-1) starts |
|---|---|---|---|
| before | starts after copy-out (i), shares bandwidth | starts after copy-out (i), shares bandwidth | after both copies |
| after | starts after copy-out (i), alone | starts after the shard H2D and pack | after the shard H2D, overlapping the reload |

![FSDP2 default streams at a backward block boundary](https://raw.githubusercontent.com/pytorch/torchtitan/activation-offload-fsdp-order/assets/images/activation_offload_fsdp_streams.png)

## What changed

- `ActivationOffloader._reload` also waits on
  `model_part.get_all_gather_copy_in_stream()` when the model part is an
  FSDP2 module. The hook order makes this precise: FSDP2's pre-backward (a
  tensor hook on `out_i`) has queued block `i - 1`'s copy-in just before the
  reload trigger (a pre-hook on `out_i.grad_fn`) runs. The stream is read at
  reload time, after FSDP2's lazy initialization in the first forward.
- Under `fsdp_unshard_in_current_stream` or a single rank, FSDP2 runs the
  copy-in on the compute stream, which the reload already waits on, and the
  copy-in stream is idle, so the new wait changes nothing there:

  ![FSDP2 unshard_in_current_stream at a backward block boundary](https://raw.githubusercontent.com/pytorch/torchtitan/activation-offload-fsdp-order/assets/images/activation_offload_fsdp_streams_current_stream.png)
- Without CPU offload the copy-in is only a GPU-to-GPU pack kernel, so the
  reload starts after that short kernel too.
- `ACTIVATION_OFFLOAD.md`: the FSDP2 section describes the ordering, with both
  diagrams (`assets/images/activation_offload_fsdp_streams*.png`); the TODO is
  gone.

## Alternatives considered

- Issue reloads on FSDP2's copy-in stream (an earlier version of #6020):
  same-stream FIFO would make FSDP2's next copy-in queue behind a long reload.
- An event recorded right after the shard H2D: tighter (skips the pack), but
  needs FSDP2 to record it inside copy-in.

## Numerics

Ordering only; loss and gradients are unchanged. The FSDP2 CPU-offload test
checks gradients bitwise against no activation offload.

## Testing

`tests/unit_tests/gpu/distributed/test_activation_offload.py` and
`test_activation_checkpoint.py` (36 tests, GB300), run against PyTorch main's
FSDP2 with pytorch/pytorch#205180 applied:

- The FSDP2 CPU-offload test (2 ranks) records the reload stream's waits:
  every reload waits on FSDP2's copy-in stream as well as the compute stream
  (fails without the change).

Not run: an end-to-end recipe with FSDP2 CPU offload measuring the overlap.
Until pytorch/pytorch#205180 reaches a nightly, CI's Pyrefly and this test
fail on the missing method.
anijain2305 added a commit to pytorch/torchtitan that referenced this pull request Nov 17, 2026
## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why
     this approach, and what you checked yourself. -->

Depends on pytorch/pytorch#205180 (`FSDPModule.get_all_gather_copy_in_stream`).
Stacked on #6022.

## Why

With FSDP2 CPU parameter offload, block `i`'s backward boundary queues two
host-to-device copies for block `i - 1`: FSDP2's pre-backward queues its
parameter shards on `all_gather_copy_in_stream`, then the reload trigger
queues its activations on the reload stream. Both become ready when block
`i`'s copy-out finishes and share the link's bandwidth in no defined order.
The parameters still need the all-gather after their copy; the activations
need nothing more. So when the copies do not fit in block `i`'s backward,
sharing is the worst order: both finish after `(P + A) / BW`, and only then
does the all-gather start. Parameters first lets the all-gather overlap the
activation copy, saving up to `min(all-gather, A / BW)`.

**Before -> after**, at the block `i` boundary (FSDP2 default streams):

| | Shard H2D (block i-1) | Activation H2D (group i-1) | All-gather (block i-1) starts |
|---|---|---|---|
| before | starts after copy-out (i), shares bandwidth | starts after copy-out (i), shares bandwidth | after both copies |
| after | starts after copy-out (i), alone | starts after the shard H2D and pack | after the shard H2D, overlapping the reload |

![FSDP2 default streams at a backward block boundary](https://raw.githubusercontent.com/pytorch/torchtitan/activation-offload-fsdp-order/assets/images/activation_offload_fsdp_streams.png)

## What changed

- `ActivationOffloader._reload` also waits on
  `model_part.get_all_gather_copy_in_stream()` when the model part is an
  FSDP2 module. The hook order makes this precise: FSDP2's pre-backward (a
  tensor hook on `out_i`) has queued block `i - 1`'s copy-in just before the
  reload trigger (a pre-hook on `out_i.grad_fn`) runs. The stream is read at
  reload time, after FSDP2's lazy initialization in the first forward.
- Under `fsdp_unshard_in_current_stream` or a single rank, FSDP2 runs the
  copy-in on the compute stream, which the reload already waits on, and the
  copy-in stream is idle, so the new wait changes nothing there:

  ![FSDP2 unshard_in_current_stream at a backward block boundary](https://raw.githubusercontent.com/pytorch/torchtitan/activation-offload-fsdp-order/assets/images/activation_offload_fsdp_streams_current_stream.png)
- Without CPU offload the copy-in is only a GPU-to-GPU pack kernel, so the
  reload starts after that short kernel too.
- `ACTIVATION_OFFLOAD.md`: the FSDP2 section describes the ordering, with both
  diagrams (`assets/images/activation_offload_fsdp_streams*.png`); the TODO is
  gone.

## Alternatives considered

- Issue reloads on FSDP2's copy-in stream (an earlier version of #6020):
  same-stream FIFO would make FSDP2's next copy-in queue behind a long reload.
- An event recorded right after the shard H2D: tighter (skips the pack), but
  needs FSDP2 to record it inside copy-in.

## Numerics

Ordering only; loss and gradients are unchanged. The FSDP2 CPU-offload test
checks gradients bitwise against no activation offload.

## Testing

`tests/unit_tests/gpu/distributed/test_activation_offload.py` and
`test_activation_checkpoint.py` (36 tests, GB300), run against PyTorch main's
FSDP2 with pytorch/pytorch#205180 applied:

- The FSDP2 CPU-offload test (2 ranks) records the reload stream's waits:
  every reload waits on FSDP2's copy-in stream as well as the compute stream
  (fails without the change).

Not run: an end-to-end recipe with FSDP2 CPU offload measuring the overlap.
Until pytorch/pytorch#205180 reaches a nightly, CI's Pyrefly and this test
fail on the missing method.
anijain2305 added a commit to pytorch/torchtitan that referenced this pull request Nov 18, 2026
## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why
     this approach, and what you checked yourself. -->

Depends on pytorch/pytorch#205180 (`FSDPModule.get_all_gather_copy_in_stream`).
Stacked on #6022.

## Why

With FSDP2 CPU parameter offload, block `i`'s backward boundary queues two
host-to-device copies for block `i - 1`: FSDP2's pre-backward queues its
parameter shards on `all_gather_copy_in_stream`, then the reload trigger
queues its activations on the reload stream. Both become ready when block
`i`'s copy-out finishes and share the link's bandwidth in no defined order.
The parameters still need the all-gather after their copy; the activations
need nothing more. So when the copies do not fit in block `i`'s backward,
sharing is the worst order: both finish after `(P + A) / BW`, and only then
does the all-gather start. Parameters first lets the all-gather overlap the
activation copy, saving up to `min(all-gather, A / BW)`.

**Before -> after**, at the block `i` boundary (FSDP2 default streams):

| | Shard H2D (block i-1) | Activation H2D (group i-1) | All-gather (block i-1) starts |
|---|---|---|---|
| before | starts after copy-out (i), shares bandwidth | starts after copy-out (i), shares bandwidth | after both copies |
| after | starts after copy-out (i), alone | starts after the shard H2D and pack | after the shard H2D, overlapping the reload |

![FSDP2 default streams at a backward block boundary](https://raw.githubusercontent.com/pytorch/torchtitan/activation-offload-fsdp-order/assets/images/activation_offload_fsdp_streams.png)

## What changed

- `ActivationOffloader._reload` also waits on
  `model_part.get_all_gather_copy_in_stream()` when the model part is an
  FSDP2 module. The hook order makes this precise: FSDP2's pre-backward (a
  tensor hook on `out_i`) has queued block `i - 1`'s copy-in just before the
  reload trigger (a pre-hook on `out_i.grad_fn`) runs. The stream is read at
  reload time, after FSDP2's lazy initialization in the first forward.
- Under `fsdp_unshard_in_current_stream` or a single rank, FSDP2 runs the
  copy-in on the compute stream, which the reload already waits on, and the
  copy-in stream is idle, so the new wait changes nothing there:

  ![FSDP2 unshard_in_current_stream at a backward block boundary](https://raw.githubusercontent.com/pytorch/torchtitan/activation-offload-fsdp-order/assets/images/activation_offload_fsdp_streams_current_stream.png)
- Without CPU offload the copy-in is only a GPU-to-GPU pack kernel, so the
  reload starts after that short kernel too.
- `ACTIVATION_OFFLOAD.md`: the FSDP2 section describes the ordering, with both
  diagrams (`assets/images/activation_offload_fsdp_streams*.png`); the TODO is
  gone.

## Alternatives considered

- Issue reloads on FSDP2's copy-in stream (an earlier version of #6020):
  same-stream FIFO would make FSDP2's next copy-in queue behind a long reload.
- An event recorded right after the shard H2D: tighter (skips the pack), but
  needs FSDP2 to record it inside copy-in.

## Numerics

Ordering only; loss and gradients are unchanged. The FSDP2 CPU-offload test
checks gradients bitwise against no activation offload.

## Testing

`tests/unit_tests/gpu/distributed/test_activation_offload.py` and
`test_activation_checkpoint.py` (36 tests, GB300), run against PyTorch main's
FSDP2 with pytorch/pytorch#205180 applied:

- The FSDP2 CPU-offload test (2 ranks) records the reload stream's waits:
  every reload waits on FSDP2's copy-in stream as well as the compute stream
  (fails without the change).

Not run: an end-to-end recipe with FSDP2 CPU offload measuring the overlap.
Until pytorch/pytorch#205180 reaches a nightly, CI's Pyrefly and this test
fail on the missing method.
@anijain2305

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge

@pytorch-bot pytorch-bot Bot added the ciflow/trunk Trigger trunk jobs on your pull request label Nov 18, 2026
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged once all checks pass (ETA 0-4 Hours).

Learn more about merging in the wiki.

Questions? Feedback? Please reach out to the PyTorch DevX Team

Advanced Debugging
Check the merge workflow status
here

anijain2305 added a commit to pytorch/torchtitan that referenced this pull request Nov 18, 2026
## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why
     this approach, and what you checked yourself. -->

Depends on pytorch/pytorch#205180 (`FSDPModule.get_all_gather_copy_in_stream`).
Stacked on #6022.

## Why

With FSDP2 CPU parameter offload, block `i`'s backward boundary queues two
host-to-device copies for block `i - 1`: FSDP2's pre-backward queues its
parameter shards on `all_gather_copy_in_stream`, then the reload trigger
queues its activations on the reload stream. Both become ready when block
`i`'s copy-out finishes and share the link's bandwidth in no defined order.
The parameters still need the all-gather after their copy; the activations
need nothing more. So when the copies do not fit in block `i`'s backward,
sharing is the worst order: both finish after `(P + A) / BW`, and only then
does the all-gather start. Parameters first lets the all-gather overlap the
activation copy, saving up to `min(all-gather, A / BW)`.

**Before -> after**, at the block `i` boundary (FSDP2 default streams):

| | Shard H2D (block i-1) | Activation H2D (group i-1) | All-gather (block i-1) starts |
|---|---|---|---|
| before | starts after copy-out (i), shares bandwidth | starts after copy-out (i), shares bandwidth | after both copies |
| after | starts after copy-out (i), alone | starts after the shard H2D and pack | after the shard H2D, overlapping the reload |

![FSDP2 default streams at a backward block boundary](https://raw.githubusercontent.com/pytorch/torchtitan/activation-offload-fsdp-order/assets/images/activation_offload_fsdp_streams.png)

## What changed

- `ActivationOffloader._reload` also waits on
  `model_part.get_all_gather_copy_in_stream()` when the model part is an
  FSDP2 module. The hook order makes this precise: FSDP2's pre-backward (a
  tensor hook on `out_i`) has queued block `i - 1`'s copy-in just before the
  reload trigger (a pre-hook on `out_i.grad_fn`) runs. The stream is read at
  reload time, after FSDP2's lazy initialization in the first forward.
- Under `fsdp_unshard_in_current_stream` or a single rank, FSDP2 runs the
  copy-in on the compute stream, which the reload already waits on, and the
  copy-in stream is idle, so the new wait changes nothing there:

  ![FSDP2 unshard_in_current_stream at a backward block boundary](https://raw.githubusercontent.com/pytorch/torchtitan/activation-offload-fsdp-order/assets/images/activation_offload_fsdp_streams_current_stream.png)
- Without CPU offload the copy-in is only a GPU-to-GPU pack kernel, so the
  reload starts after that short kernel too.
- `ACTIVATION_OFFLOAD.md`: the FSDP2 section describes the ordering, with both
  diagrams (`assets/images/activation_offload_fsdp_streams*.png`); the TODO is
  gone.

## Alternatives considered

- Issue reloads on FSDP2's copy-in stream (an earlier version of #6020):
  same-stream FIFO would make FSDP2's next copy-in queue behind a long reload.
- An event recorded right after the shard H2D: tighter (skips the pack), but
  needs FSDP2 to record it inside copy-in.

## Numerics

Ordering only; loss and gradients are unchanged. The FSDP2 CPU-offload test
checks gradients bitwise against no activation offload.

## Testing

`tests/unit_tests/gpu/distributed/test_activation_offload.py` and
`test_activation_checkpoint.py` (36 tests, GB300), run against PyTorch main's
FSDP2 with pytorch/pytorch#205180 applied:

- The FSDP2 CPU-offload test (2 ranks) records the reload stream's waits:
  every reload waits on FSDP2's copy-in stream as well as the compute stream
  (fails without the change).

Not run: an end-to-end recipe with FSDP2 CPU offload measuring the overlap.
Until pytorch/pytorch#205180 reaches a nightly, CI's Pyrefly and this test
fail on the missing method.
anijain2305 added a commit to pytorch/torchtitan that referenced this pull request Nov 19, 2026
## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why
     this approach, and what you checked yourself. -->

Depends on pytorch/pytorch#205180 (`FSDPModule.get_all_gather_copy_in_stream`).
Stacked on #6022.

## Why

With FSDP2 CPU parameter offload, block `i`'s backward boundary queues two
host-to-device copies for block `i - 1`: FSDP2's pre-backward queues its
parameter shards on `all_gather_copy_in_stream`, then the reload trigger
queues its activations on the reload stream. Both become ready when block
`i`'s copy-out finishes and share the link's bandwidth in no defined order.
The parameters still need the all-gather after their copy; the activations
need nothing more. So when the copies do not fit in block `i`'s backward,
sharing is the worst order: both finish after `(P + A) / BW`, and only then
does the all-gather start. Parameters first lets the all-gather overlap the
activation copy, saving up to `min(all-gather, A / BW)`.

**Before -> after**, at the block `i` boundary (FSDP2 default streams):

| | Shard H2D (block i-1) | Activation H2D (group i-1) | All-gather (block i-1) starts |
|---|---|---|---|
| before | starts after copy-out (i), shares bandwidth | starts after copy-out (i), shares bandwidth | after both copies |
| after | starts after copy-out (i), alone | starts after the shard H2D and pack | after the shard H2D, overlapping the reload |

![FSDP2 default streams at a backward block boundary](https://raw.githubusercontent.com/pytorch/torchtitan/activation-offload-fsdp-order/assets/images/activation_offload_fsdp_streams.png)

## What changed

- `ActivationOffloader._reload` also waits on
  `model_part.get_all_gather_copy_in_stream()` when the model part is an
  FSDP2 module. The hook order makes this precise: FSDP2's pre-backward (a
  tensor hook on `out_i`) has queued block `i - 1`'s copy-in just before the
  reload trigger (a pre-hook on `out_i.grad_fn`) runs. The stream is read at
  reload time, after FSDP2's lazy initialization in the first forward.
- Under `fsdp_unshard_in_current_stream` or a single rank, FSDP2 runs the
  copy-in on the compute stream, which the reload already waits on, and the
  copy-in stream is idle, so the new wait changes nothing there:

  ![FSDP2 unshard_in_current_stream at a backward block boundary](https://raw.githubusercontent.com/pytorch/torchtitan/activation-offload-fsdp-order/assets/images/activation_offload_fsdp_streams_current_stream.png)
- Without CPU offload the copy-in is only a GPU-to-GPU pack kernel, so the
  reload starts after that short kernel too.
- `ACTIVATION_OFFLOAD.md`: the FSDP2 section describes the ordering, with both
  diagrams (`assets/images/activation_offload_fsdp_streams*.png`); the TODO is
  gone.

## Alternatives considered

- Issue reloads on FSDP2's copy-in stream (an earlier version of #6020):
  same-stream FIFO would make FSDP2's next copy-in queue behind a long reload.
- An event recorded right after the shard H2D: tighter (skips the pack), but
  needs FSDP2 to record it inside copy-in.

## Numerics

Ordering only; loss and gradients are unchanged. The FSDP2 CPU-offload test
checks gradients bitwise against no activation offload.

## Testing

`tests/unit_tests/gpu/distributed/test_activation_offload.py` and
`test_activation_checkpoint.py` (36 tests, GB300), run against PyTorch main's
FSDP2 with pytorch/pytorch#205180 applied:

- The FSDP2 CPU-offload test (2 ranks) records the reload stream's waits:
  every reload waits on FSDP2's copy-in stream as well as the compute stream
  (fails without the change).

Not run: an end-to-end recipe with FSDP2 CPU offload measuring the overlap.
Until pytorch/pytorch#205180 reaches a nightly, CI's Pyrefly and this test
fail on the missing method.
anijain2305 added a commit to pytorch/torchtitan that referenced this pull request Nov 19, 2026
## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why
     this approach, and what you checked yourself. -->

Depends on pytorch/pytorch#205180 (`FSDPModule.get_all_gather_copy_in_stream`).
Stacked on #6022.

## Why

With FSDP2 CPU parameter offload, block `i`'s backward boundary queues two
host-to-device copies for block `i - 1`: FSDP2's pre-backward queues its
parameter shards on `all_gather_copy_in_stream`, then the reload trigger
queues its activations on the reload stream. Both become ready when block
`i`'s copy-out finishes and share the link's bandwidth in no defined order.
The parameters still need the all-gather after their copy; the activations
need nothing more. So when the copies do not fit in block `i`'s backward,
sharing is the worst order: both finish after `(P + A) / BW`, and only then
does the all-gather start. Parameters first lets the all-gather overlap the
activation copy, saving up to `min(all-gather, A / BW)`.

**Before -> after**, at the block `i` boundary (FSDP2 default streams):

| | Shard H2D (block i-1) | Activation H2D (group i-1) | All-gather (block i-1) starts |
|---|---|---|---|
| before | starts after copy-out (i), shares bandwidth | starts after copy-out (i), shares bandwidth | after both copies |
| after | starts after copy-out (i), alone | starts after the shard H2D and pack | after the shard H2D, overlapping the reload |

![FSDP2 default streams at a backward block boundary](https://raw.githubusercontent.com/pytorch/torchtitan/activation-offload-fsdp-order/assets/images/activation_offload_fsdp_streams.png)

## What changed

- `ActivationOffloader._reload` also waits on
  `model_part.get_all_gather_copy_in_stream()` when the model part is an
  FSDP2 module. The hook order makes this precise: FSDP2's pre-backward (a
  tensor hook on `out_i`) has queued block `i - 1`'s copy-in just before the
  reload trigger (a pre-hook on `out_i.grad_fn`) runs. The stream is read at
  reload time, after FSDP2's lazy initialization in the first forward.
- Under `fsdp_unshard_in_current_stream` or a single rank, FSDP2 runs the
  copy-in on the compute stream, which the reload already waits on, and the
  copy-in stream is idle, so the new wait changes nothing there:

  ![FSDP2 unshard_in_current_stream at a backward block boundary](https://raw.githubusercontent.com/pytorch/torchtitan/activation-offload-fsdp-order/assets/images/activation_offload_fsdp_streams_current_stream.png)
- Without CPU offload the copy-in is only a GPU-to-GPU pack kernel, so the
  reload starts after that short kernel too.
- `ACTIVATION_OFFLOAD.md`: the FSDP2 section describes the ordering, with both
  diagrams (`assets/images/activation_offload_fsdp_streams*.png`); the TODO is
  gone.

## Alternatives considered

- Issue reloads on FSDP2's copy-in stream (an earlier version of #6020):
  same-stream FIFO would make FSDP2's next copy-in queue behind a long reload.
- An event recorded right after the shard H2D: tighter (skips the pack), but
  needs FSDP2 to record it inside copy-in.

## Numerics

Ordering only; loss and gradients are unchanged. The FSDP2 CPU-offload test
checks gradients bitwise against no activation offload.

## Testing

`tests/unit_tests/gpu/distributed/test_activation_offload.py` and
`test_activation_checkpoint.py` (36 tests, GB300), run against PyTorch main's
FSDP2 with pytorch/pytorch#205180 applied:

- The FSDP2 CPU-offload test (2 ranks) records the reload stream's waits:
  every reload waits on FSDP2's copy-in stream as well as the compute stream
  (fails without the change).

Not run: an end-to-end recipe with FSDP2 CPU offload measuring the overlap.
Until pytorch/pytorch#205180 reaches a nightly, CI's Pyrefly and this test
fail on the missing method.
anijain2305 added a commit to pytorch/torchtitan that referenced this pull request Nov 19, 2026
## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why
     this approach, and what you checked yourself. -->

Depends on pytorch/pytorch#205180 (`FSDPModule.get_all_gather_copy_in_stream`).
Stacked on #6022.

## Why

With FSDP2 CPU parameter offload, block `i`'s backward boundary queues two
host-to-device copies for block `i - 1`: FSDP2's pre-backward queues its
parameter shards on `all_gather_copy_in_stream`, then the reload trigger
queues its activations on the reload stream. Both become ready when block
`i`'s copy-out finishes and share the link's bandwidth in no defined order.
The parameters still need the all-gather after their copy; the activations
need nothing more. So when the copies do not fit in block `i`'s backward,
sharing is the worst order: both finish after `(P + A) / BW`, and only then
does the all-gather start. Parameters first lets the all-gather overlap the
activation copy, saving up to `min(all-gather, A / BW)`.

**Before -> after**, at the block `i` boundary (FSDP2 default streams):

| | Shard H2D (block i-1) | Activation H2D (group i-1) | All-gather (block i-1) starts |
|---|---|---|---|
| before | starts after copy-out (i), shares bandwidth | starts after copy-out (i), shares bandwidth | after both copies |
| after | starts after copy-out (i), alone | starts after the shard H2D and pack | after the shard H2D, overlapping the reload |

![FSDP2 default streams at a backward block boundary](https://raw.githubusercontent.com/pytorch/torchtitan/activation-offload-fsdp-order/assets/images/activation_offload_fsdp_streams.png)

## What changed

- `ActivationOffloader._reload` also waits on
  `model_part.get_all_gather_copy_in_stream()` when the model part is an
  FSDP2 module. The hook order makes this precise: FSDP2's pre-backward (a
  tensor hook on `out_i`) has queued block `i - 1`'s copy-in just before the
  reload trigger (a pre-hook on `out_i.grad_fn`) runs. The stream is read at
  reload time, after FSDP2's lazy initialization in the first forward.
- Under `fsdp_unshard_in_current_stream` or a single rank, FSDP2 runs the
  copy-in on the compute stream, which the reload already waits on, and the
  copy-in stream is idle, so the new wait changes nothing there:

  ![FSDP2 unshard_in_current_stream at a backward block boundary](https://raw.githubusercontent.com/pytorch/torchtitan/activation-offload-fsdp-order/assets/images/activation_offload_fsdp_streams_current_stream.png)
- Without CPU offload the copy-in is only a GPU-to-GPU pack kernel, so the
  reload starts after that short kernel too.
- `ACTIVATION_OFFLOAD.md`: the FSDP2 section describes the ordering, with both
  diagrams (`assets/images/activation_offload_fsdp_streams*.png`); the TODO is
  gone.

## Alternatives considered

- Issue reloads on FSDP2's copy-in stream (an earlier version of #6020):
  same-stream FIFO would make FSDP2's next copy-in queue behind a long reload.
- An event recorded right after the shard H2D: tighter (skips the pack), but
  needs FSDP2 to record it inside copy-in.

## Numerics

Ordering only; loss and gradients are unchanged. The FSDP2 CPU-offload test
checks gradients bitwise against no activation offload.

## Testing

`tests/unit_tests/gpu/distributed/test_activation_offload.py` and
`test_activation_checkpoint.py` (36 tests, GB300), run against PyTorch main's
FSDP2 with pytorch/pytorch#205180 applied:

- The FSDP2 CPU-offload test (2 ranks) records the reload stream's waits:
  every reload waits on FSDP2's copy-in stream as well as the compute stream
  (fails without the change).

Not run: an end-to-end recipe with FSDP2 CPU offload measuring the overlap.
Until pytorch/pytorch#205180 reaches a nightly, CI's Pyrefly and this test
fail on the missing method.
anijain2305 added a commit to pytorch/torchtitan that referenced this pull request Nov 19, 2026
## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why
     this approach, and what you checked yourself. -->

Depends on pytorch/pytorch#205180 (`FSDPModule.get_all_gather_copy_in_stream`).
Stacked on #6022.

## Why

With FSDP2 CPU parameter offload, block `i`'s backward boundary queues two
host-to-device copies for block `i - 1`: FSDP2's pre-backward queues its
parameter shards on `all_gather_copy_in_stream`, then the reload trigger
queues its activations on the reload stream. Both become ready when block
`i`'s copy-out finishes and share the link's bandwidth in no defined order.
The parameters still need the all-gather after their copy; the activations
need nothing more. So when the copies do not fit in block `i`'s backward,
sharing is the worst order: both finish after `(P + A) / BW`, and only then
does the all-gather start. Parameters first lets the all-gather overlap the
activation copy, saving up to `min(all-gather, A / BW)`.

**Before -> after**, at the block `i` boundary (FSDP2 default streams):

| | Shard H2D (block i-1) | Activation H2D (group i-1) | All-gather (block i-1) starts |
|---|---|---|---|
| before | starts after copy-out (i), shares bandwidth | starts after copy-out (i), shares bandwidth | after both copies |
| after | starts after copy-out (i), alone | starts after the shard H2D and pack | after the shard H2D, overlapping the reload |

![FSDP2 default streams at a backward block boundary](https://raw.githubusercontent.com/pytorch/torchtitan/activation-offload-fsdp-order/assets/images/activation_offload_fsdp_streams.png)

## What changed

- `ActivationOffloader._reload` also waits on
  `model_part.get_all_gather_copy_in_stream()` when the model part is an
  FSDP2 module. The hook order makes this precise: FSDP2's pre-backward (a
  tensor hook on `out_i`) has queued block `i - 1`'s copy-in just before the
  reload trigger (a pre-hook on `out_i.grad_fn`) runs. The stream is read at
  reload time, after FSDP2's lazy initialization in the first forward.
- Under `fsdp_unshard_in_current_stream` or a single rank, FSDP2 runs the
  copy-in on the compute stream, which the reload already waits on, and the
  copy-in stream is idle, so the new wait changes nothing there:

  ![FSDP2 unshard_in_current_stream at a backward block boundary](https://raw.githubusercontent.com/pytorch/torchtitan/activation-offload-fsdp-order/assets/images/activation_offload_fsdp_streams_current_stream.png)
- Without CPU offload the copy-in is only a GPU-to-GPU pack kernel, so the
  reload starts after that short kernel too.
- `ACTIVATION_OFFLOAD.md`: the FSDP2 section describes the ordering, with both
  diagrams (`assets/images/activation_offload_fsdp_streams*.png`); the TODO is
  gone.

## Alternatives considered

- Issue reloads on FSDP2's copy-in stream (an earlier version of #6020):
  same-stream FIFO would make FSDP2's next copy-in queue behind a long reload.
- An event recorded right after the shard H2D: tighter (skips the pack), but
  needs FSDP2 to record it inside copy-in.

## Numerics

Ordering only; loss and gradients are unchanged. The FSDP2 CPU-offload test
checks gradients bitwise against no activation offload.

## Testing

`tests/unit_tests/gpu/distributed/test_activation_offload.py` and
`test_activation_checkpoint.py` (36 tests, GB300), run against PyTorch main's
FSDP2 with pytorch/pytorch#205180 applied:

- The FSDP2 CPU-offload test (2 ranks) records the reload stream's waits:
  every reload waits on FSDP2's copy-in stream as well as the compute stream
  (fails without the change).

Not run: an end-to-end recipe with FSDP2 CPU offload measuring the overlap.
Until pytorch/pytorch#205180 reaches a nightly, CI's Pyrefly and this test
fail on the missing method.
anijain2305 added a commit to pytorch/torchtitan that referenced this pull request Nov 19, 2026
## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why
     this approach, and what you checked yourself. -->

Depends on pytorch/pytorch#205180 (`FSDPModule.get_all_gather_copy_in_stream`).
Stacked on #6022.

## Why

With FSDP2 CPU parameter offload, block `i`'s backward boundary queues two
host-to-device copies for block `i - 1`: FSDP2's pre-backward queues its
parameter shards on `all_gather_copy_in_stream`, then the reload trigger
queues its activations on the reload stream. Both become ready when block
`i`'s copy-out finishes and share the link's bandwidth in no defined order.
The parameters still need the all-gather after their copy; the activations
need nothing more. So when the copies do not fit in block `i`'s backward,
sharing is the worst order: both finish after `(P + A) / BW`, and only then
does the all-gather start. Parameters first lets the all-gather overlap the
activation copy, saving up to `min(all-gather, A / BW)`.

**Before -> after**, at the block `i` boundary (FSDP2 default streams):

| | Shard H2D (block i-1) | Activation H2D (group i-1) | All-gather (block i-1) starts |
|---|---|---|---|
| before | starts after copy-out (i), shares bandwidth | starts after copy-out (i), shares bandwidth | after both copies |
| after | starts after copy-out (i), alone | starts after the shard H2D and pack | after the shard H2D, overlapping the reload |

![FSDP2 default streams at a backward block boundary](https://raw.githubusercontent.com/pytorch/torchtitan/activation-offload-fsdp-order/assets/images/activation_offload_fsdp_streams.png)

## What changed

- `ActivationOffloader._reload` also waits on
  `model_part.get_all_gather_copy_in_stream()` when the model part is an
  FSDP2 module. The hook order makes this precise: FSDP2's pre-backward (a
  tensor hook on `out_i`) has queued block `i - 1`'s copy-in just before the
  reload trigger (a pre-hook on `out_i.grad_fn`) runs. The stream is read at
  reload time, after FSDP2's lazy initialization in the first forward.
- Under `fsdp_unshard_in_current_stream` or a single rank, FSDP2 runs the
  copy-in on the compute stream, which the reload already waits on, and the
  copy-in stream is idle, so the new wait changes nothing there:

  ![FSDP2 unshard_in_current_stream at a backward block boundary](https://raw.githubusercontent.com/pytorch/torchtitan/activation-offload-fsdp-order/assets/images/activation_offload_fsdp_streams_current_stream.png)
- Without CPU offload the copy-in is only a GPU-to-GPU pack kernel, so the
  reload starts after that short kernel too.
- `ACTIVATION_OFFLOAD.md`: the FSDP2 section describes the ordering, with both
  diagrams (`assets/images/activation_offload_fsdp_streams*.png`); the TODO is
  gone.

## Alternatives considered

- Issue reloads on FSDP2's copy-in stream (an earlier version of #6020):
  same-stream FIFO would make FSDP2's next copy-in queue behind a long reload.
- An event recorded right after the shard H2D: tighter (skips the pack), but
  needs FSDP2 to record it inside copy-in.

## Numerics

Ordering only; loss and gradients are unchanged. The FSDP2 CPU-offload test
checks gradients bitwise against no activation offload.

## Testing

`tests/unit_tests/gpu/distributed/test_activation_offload.py` and
`test_activation_checkpoint.py` (36 tests, GB300), run against PyTorch main's
FSDP2 with pytorch/pytorch#205180 applied:

- The FSDP2 CPU-offload test (2 ranks) records the reload stream's waits:
  every reload waits on FSDP2's copy-in stream as well as the compute stream
  (fails without the change).

Not run: an end-to-end recipe with FSDP2 CPU offload measuring the overlap.
Until pytorch/pytorch#205180 reaches a nightly, CI's Pyrefly and this test
fail on the missing method.
anijain2305 added a commit to pytorch/torchtitan that referenced this pull request Nov 19, 2026
## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why
     this approach, and what you checked yourself. -->

Depends on pytorch/pytorch#205180 (`FSDPModule.get_all_gather_copy_in_stream`).
Stacked on #6022.

## Why

With FSDP2 CPU parameter offload, block `i`'s backward boundary queues two
host-to-device copies for block `i - 1`: FSDP2's pre-backward queues its
parameter shards on `all_gather_copy_in_stream`, then the reload trigger
queues its activations on the reload stream. Both become ready when block
`i`'s copy-out finishes and share the link's bandwidth in no defined order.
The parameters still need the all-gather after their copy; the activations
need nothing more. So when the copies do not fit in block `i`'s backward,
sharing is the worst order: both finish after `(P + A) / BW`, and only then
does the all-gather start. Parameters first lets the all-gather overlap the
activation copy, saving up to `min(all-gather, A / BW)`.

**Before -> after**, at the block `i` boundary (FSDP2 default streams):

| | Shard H2D (block i-1) | Activation H2D (group i-1) | All-gather (block i-1) starts |
|---|---|---|---|
| before | starts after copy-out (i), shares bandwidth | starts after copy-out (i), shares bandwidth | after both copies |
| after | starts after copy-out (i), alone | starts after the shard H2D and pack | after the shard H2D, overlapping the reload |

![FSDP2 default streams at a backward block boundary](https://raw.githubusercontent.com/pytorch/torchtitan/activation-offload-fsdp-order/assets/images/activation_offload_fsdp_streams.png)

## What changed

- `ActivationOffloader._reload` also waits on
  `model_part.get_all_gather_copy_in_stream()` when the model part is an
  FSDP2 module. The hook order makes this precise: FSDP2's pre-backward (a
  tensor hook on `out_i`) has queued block `i - 1`'s copy-in just before the
  reload trigger (a pre-hook on `out_i.grad_fn`) runs. The stream is read at
  reload time, after FSDP2's lazy initialization in the first forward.
- Under `fsdp_unshard_in_current_stream` or a single rank, FSDP2 runs the
  copy-in on the compute stream, which the reload already waits on, and the
  copy-in stream is idle, so the new wait changes nothing there:

  ![FSDP2 unshard_in_current_stream at a backward block boundary](https://raw.githubusercontent.com/pytorch/torchtitan/activation-offload-fsdp-order/assets/images/activation_offload_fsdp_streams_current_stream.png)
- Without CPU offload the copy-in is only a GPU-to-GPU pack kernel, so the
  reload starts after that short kernel too.
- `ACTIVATION_OFFLOAD.md`: the FSDP2 section describes the ordering, with both
  diagrams (`assets/images/activation_offload_fsdp_streams*.png`); the TODO is
  gone.

## Alternatives considered

- Issue reloads on FSDP2's copy-in stream (an earlier version of #6020):
  same-stream FIFO would make FSDP2's next copy-in queue behind a long reload.
- An event recorded right after the shard H2D: tighter (skips the pack), but
  needs FSDP2 to record it inside copy-in.

## Numerics

Ordering only; loss and gradients are unchanged. The FSDP2 CPU-offload test
checks gradients bitwise against no activation offload.

## Testing

`tests/unit_tests/gpu/distributed/test_activation_offload.py` and
`test_activation_checkpoint.py` (36 tests, GB300), run against PyTorch main's
FSDP2 with pytorch/pytorch#205180 applied:

- The FSDP2 CPU-offload test (2 ranks) records the reload stream's waits:
  every reload waits on FSDP2's copy-in stream as well as the compute stream
  (fails without the change).

Not run: an end-to-end recipe with FSDP2 CPU offload measuring the overlap.
Until pytorch/pytorch#205180 reaches a nightly, CI's Pyrefly and this test
fail on the missing method.
anijain2305 added a commit to pytorch/torchtitan that referenced this pull request Nov 19, 2026
## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why
     this approach, and what you checked yourself. -->

Depends on pytorch/pytorch#205180 (`FSDPModule.get_all_gather_copy_in_stream`).
Stacked on #6022.

## Why

With FSDP2 CPU parameter offload, block `i`'s backward boundary queues two
host-to-device copies for block `i - 1`: FSDP2's pre-backward queues its
parameter shards on `all_gather_copy_in_stream`, then the reload trigger
queues its activations on the reload stream. Both become ready when block
`i`'s copy-out finishes and share the link's bandwidth in no defined order.
The parameters still need the all-gather after their copy; the activations
need nothing more. So when the copies do not fit in block `i`'s backward,
sharing is the worst order: both finish after `(P + A) / BW`, and only then
does the all-gather start. Parameters first lets the all-gather overlap the
activation copy, saving up to `min(all-gather, A / BW)`.

**Before -> after**, at the block `i` boundary (FSDP2 default streams):

| | Shard H2D (block i-1) | Activation H2D (group i-1) | All-gather (block i-1) starts |
|---|---|---|---|
| before | starts after copy-out (i), shares bandwidth | starts after copy-out (i), shares bandwidth | after both copies |
| after | starts after copy-out (i), alone | starts after the shard H2D and pack | after the shard H2D, overlapping the reload |

![FSDP2 default streams at a backward block boundary](https://raw.githubusercontent.com/pytorch/torchtitan/activation-offload-fsdp-order/assets/images/activation_offload_fsdp_streams.png)

## What changed

- `ActivationOffloader._reload` also waits on
  `model_part.get_all_gather_copy_in_stream()` when the model part is an
  FSDP2 module. The hook order makes this precise: FSDP2's pre-backward (a
  tensor hook on `out_i`) has queued block `i - 1`'s copy-in just before the
  reload trigger (a pre-hook on `out_i.grad_fn`) runs. The stream is read at
  reload time, after FSDP2's lazy initialization in the first forward.
- Under `fsdp_unshard_in_current_stream` or a single rank, FSDP2 runs the
  copy-in on the compute stream, which the reload already waits on, and the
  copy-in stream is idle, so the new wait changes nothing there:

  ![FSDP2 unshard_in_current_stream at a backward block boundary](https://raw.githubusercontent.com/pytorch/torchtitan/activation-offload-fsdp-order/assets/images/activation_offload_fsdp_streams_current_stream.png)
- Without CPU offload the copy-in is only a GPU-to-GPU pack kernel, so the
  reload starts after that short kernel too.
- `ACTIVATION_OFFLOAD.md`: the FSDP2 section describes the ordering, with both
  diagrams (`assets/images/activation_offload_fsdp_streams*.png`); the TODO is
  gone.

## Alternatives considered

- Issue reloads on FSDP2's copy-in stream (an earlier version of #6020):
  same-stream FIFO would make FSDP2's next copy-in queue behind a long reload.
- An event recorded right after the shard H2D: tighter (skips the pack), but
  needs FSDP2 to record it inside copy-in.

## Numerics

Ordering only; loss and gradients are unchanged. The FSDP2 CPU-offload test
checks gradients bitwise against no activation offload.

## Testing

`tests/unit_tests/gpu/distributed/test_activation_offload.py` and
`test_activation_checkpoint.py` (36 tests, GB300), run against PyTorch main's
FSDP2 with pytorch/pytorch#205180 applied:

- The FSDP2 CPU-offload test (2 ranks) records the reload stream's waits:
  every reload waits on FSDP2's copy-in stream as well as the compute stream
  (fails without the change).

Not run: an end-to-end recipe with FSDP2 CPU offload measuring the overlap.
Until pytorch/pytorch#205180 reaches a nightly, CI's Pyrefly and this test
fail on the missing method.
anijain2305 added a commit to pytorch/torchtitan that referenced this pull request Nov 19, 2026
## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why
     this approach, and what you checked yourself. -->

Depends on pytorch/pytorch#205180 (`FSDPModule.get_all_gather_copy_in_stream`).
Stacked on #6022.

## Why

With FSDP2 CPU parameter offload, block `i`'s backward boundary queues two
host-to-device copies for block `i - 1`: FSDP2's pre-backward queues its
parameter shards on `all_gather_copy_in_stream`, then the reload trigger
queues its activations on the reload stream. Both become ready when block
`i`'s copy-out finishes and share the link's bandwidth in no defined order.
The parameters still need the all-gather after their copy; the activations
need nothing more. So when the copies do not fit in block `i`'s backward,
sharing is the worst order: both finish after `(P + A) / BW`, and only then
does the all-gather start. Parameters first lets the all-gather overlap the
activation copy, saving up to `min(all-gather, A / BW)`.

**Before -> after**, at the block `i` boundary (FSDP2 default streams):

| | Shard H2D (block i-1) | Activation H2D (group i-1) | All-gather (block i-1) starts |
|---|---|---|---|
| before | starts after copy-out (i), shares bandwidth | starts after copy-out (i), shares bandwidth | after both copies |
| after | starts after copy-out (i), alone | starts after the shard H2D and pack | after the shard H2D, overlapping the reload |

![FSDP2 default streams at a backward block boundary](https://raw.githubusercontent.com/pytorch/torchtitan/activation-offload-fsdp-order/assets/images/activation_offload_fsdp_streams.png)

## What changed

- `ActivationOffloader._reload` also waits on
  `model_part.get_all_gather_copy_in_stream()` when the model part is an
  FSDP2 module. The hook order makes this precise: FSDP2's pre-backward (a
  tensor hook on `out_i`) has queued block `i - 1`'s copy-in just before the
  reload trigger (a pre-hook on `out_i.grad_fn`) runs. The stream is read at
  reload time, after FSDP2's lazy initialization in the first forward.
- Under `fsdp_unshard_in_current_stream` or a single rank, FSDP2 runs the
  copy-in on the compute stream, which the reload already waits on, and the
  copy-in stream is idle, so the new wait changes nothing there:

  ![FSDP2 unshard_in_current_stream at a backward block boundary](https://raw.githubusercontent.com/pytorch/torchtitan/activation-offload-fsdp-order/assets/images/activation_offload_fsdp_streams_current_stream.png)
- Without CPU offload the copy-in is only a GPU-to-GPU pack kernel, so the
  reload starts after that short kernel too.
- `ACTIVATION_OFFLOAD.md`: the FSDP2 section describes the ordering, with both
  diagrams (`assets/images/activation_offload_fsdp_streams*.png`); the TODO is
  gone.

## Alternatives considered

- Issue reloads on FSDP2's copy-in stream (an earlier version of #6020):
  same-stream FIFO would make FSDP2's next copy-in queue behind a long reload.
- An event recorded right after the shard H2D: tighter (skips the pack), but
  needs FSDP2 to record it inside copy-in.

## Numerics

Ordering only; loss and gradients are unchanged. The FSDP2 CPU-offload test
checks gradients bitwise against no activation offload.

## Testing

`tests/unit_tests/gpu/distributed/test_activation_offload.py` and
`test_activation_checkpoint.py` (36 tests, GB300), run against PyTorch main's
FSDP2 with pytorch/pytorch#205180 applied:

- The FSDP2 CPU-offload test (2 ranks) records the reload stream's waits:
  every reload waits on FSDP2's copy-in stream as well as the compute stream
  (fails without the change).

Not run: an end-to-end recipe with FSDP2 CPU offload measuring the overlap.
Until pytorch/pytorch#205180 reaches a nightly, CI's Pyrefly and this test
fail on the missing method.
anijain2305 added a commit to pytorch/torchtitan that referenced this pull request Nov 19, 2026
## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why
     this approach, and what you checked yourself. -->

Depends on pytorch/pytorch#205180 (`FSDPModule.get_all_gather_copy_in_stream`).
Stacked on #6022.

## Why

With FSDP2 CPU parameter offload, block `i`'s backward boundary queues two
host-to-device copies for block `i - 1`: FSDP2's pre-backward queues its
parameter shards on `all_gather_copy_in_stream`, then the reload trigger
queues its activations on the reload stream. Both become ready when block
`i`'s copy-out finishes and share the link's bandwidth in no defined order.
The parameters still need the all-gather after their copy; the activations
need nothing more. So when the copies do not fit in block `i`'s backward,
sharing is the worst order: both finish after `(P + A) / BW`, and only then
does the all-gather start. Parameters first lets the all-gather overlap the
activation copy, saving up to `min(all-gather, A / BW)`.

**Before -> after**, at the block `i` boundary (FSDP2 default streams):

| | Shard H2D (block i-1) | Activation H2D (group i-1) | All-gather (block i-1) starts |
|---|---|---|---|
| before | starts after copy-out (i), shares bandwidth | starts after copy-out (i), shares bandwidth | after both copies |
| after | starts after copy-out (i), alone | starts after the shard H2D and pack | after the shard H2D, overlapping the reload |

![FSDP2 default streams at a backward block boundary](https://raw.githubusercontent.com/pytorch/torchtitan/activation-offload-fsdp-order/assets/images/activation_offload_fsdp_streams.png)

## What changed

- `ActivationOffloader._reload` also waits on
  `model_part.get_all_gather_copy_in_stream()` when the model part is an
  FSDP2 module. The hook order makes this precise: FSDP2's pre-backward (a
  tensor hook on `out_i`) has queued block `i - 1`'s copy-in just before the
  reload trigger (a pre-hook on `out_i.grad_fn`) runs. The stream is read at
  reload time, after FSDP2's lazy initialization in the first forward.
- Under `fsdp_unshard_in_current_stream` or a single rank, FSDP2 runs the
  copy-in on the compute stream, which the reload already waits on, and the
  copy-in stream is idle, so the new wait changes nothing there:

  ![FSDP2 unshard_in_current_stream at a backward block boundary](https://raw.githubusercontent.com/pytorch/torchtitan/activation-offload-fsdp-order/assets/images/activation_offload_fsdp_streams_current_stream.png)
- Without CPU offload the copy-in is only a GPU-to-GPU pack kernel, so the
  reload starts after that short kernel too.
- `ACTIVATION_OFFLOAD.md`: the FSDP2 section describes the ordering, with both
  diagrams (`assets/images/activation_offload_fsdp_streams*.png`); the TODO is
  gone.

## Alternatives considered

- Issue reloads on FSDP2's copy-in stream (an earlier version of #6020):
  same-stream FIFO would make FSDP2's next copy-in queue behind a long reload.
- An event recorded right after the shard H2D: tighter (skips the pack), but
  needs FSDP2 to record it inside copy-in.

## Numerics

Ordering only; loss and gradients are unchanged. The FSDP2 CPU-offload test
checks gradients bitwise against no activation offload.

## Testing

`tests/unit_tests/gpu/distributed/test_activation_offload.py` and
`test_activation_checkpoint.py` (36 tests, GB300), run against PyTorch main's
FSDP2 with pytorch/pytorch#205180 applied:

- The FSDP2 CPU-offload test (2 ranks) records the reload stream's waits:
  every reload waits on FSDP2's copy-in stream as well as the compute stream
  (fails without the change).

Not run: an end-to-end recipe with FSDP2 CPU offload measuring the overlap.
Until pytorch/pytorch#205180 reaches a nightly, CI's Pyrefly and this test
fail on the missing method.
anijain2305 added a commit to pytorch/torchtitan that referenced this pull request Nov 19, 2026
## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why
     this approach, and what you checked yourself. -->

Depends on pytorch/pytorch#205180 (`FSDPModule.get_all_gather_copy_in_stream`).
Stacked on #6022.

## Why

With FSDP2 CPU parameter offload, block `i`'s backward boundary queues two
host-to-device copies for block `i - 1`: FSDP2's pre-backward queues its
parameter shards on `all_gather_copy_in_stream`, then the reload trigger
queues its activations on the reload stream. Both become ready when block
`i`'s copy-out finishes and share the link's bandwidth in no defined order.
The parameters still need the all-gather after their copy; the activations
need nothing more. So when the copies do not fit in block `i`'s backward,
sharing is the worst order: both finish after `(P + A) / BW`, and only then
does the all-gather start. Parameters first lets the all-gather overlap the
activation copy, saving up to `min(all-gather, A / BW)`.

**Before -> after**, at the block `i` boundary (FSDP2 default streams):

| | Shard H2D (block i-1) | Activation H2D (group i-1) | All-gather (block i-1) starts |
|---|---|---|---|
| before | starts after copy-out (i), shares bandwidth | starts after copy-out (i), shares bandwidth | after both copies |
| after | starts after copy-out (i), alone | starts after the shard H2D and pack | after the shard H2D, overlapping the reload |

![FSDP2 default streams at a backward block boundary](https://raw.githubusercontent.com/pytorch/torchtitan/activation-offload-fsdp-order/assets/images/activation_offload_fsdp_streams.png)

## What changed

- `ActivationOffloader._reload` also waits on
  `model_part.get_all_gather_copy_in_stream()` when the model part is an
  FSDP2 module. The hook order makes this precise: FSDP2's pre-backward (a
  tensor hook on `out_i`) has queued block `i - 1`'s copy-in just before the
  reload trigger (a pre-hook on `out_i.grad_fn`) runs. The stream is read at
  reload time, after FSDP2's lazy initialization in the first forward.
- Under `fsdp_unshard_in_current_stream` or a single rank, FSDP2 runs the
  copy-in on the compute stream, which the reload already waits on, and the
  copy-in stream is idle, so the new wait changes nothing there:

  ![FSDP2 unshard_in_current_stream at a backward block boundary](https://raw.githubusercontent.com/pytorch/torchtitan/activation-offload-fsdp-order/assets/images/activation_offload_fsdp_streams_current_stream.png)
- Without CPU offload the copy-in is only a GPU-to-GPU pack kernel, so the
  reload starts after that short kernel too.
- `ACTIVATION_OFFLOAD.md`: the FSDP2 section describes the ordering, with both
  diagrams (`assets/images/activation_offload_fsdp_streams*.png`); the TODO is
  gone.

## Alternatives considered

- Issue reloads on FSDP2's copy-in stream (an earlier version of #6020):
  same-stream FIFO would make FSDP2's next copy-in queue behind a long reload.
- An event recorded right after the shard H2D: tighter (skips the pack), but
  needs FSDP2 to record it inside copy-in.

## Numerics

Ordering only; loss and gradients are unchanged. The FSDP2 CPU-offload test
checks gradients bitwise against no activation offload.

## Testing

`tests/unit_tests/gpu/distributed/test_activation_offload.py` and
`test_activation_checkpoint.py` (36 tests, GB300), run against PyTorch main's
FSDP2 with pytorch/pytorch#205180 applied:

- The FSDP2 CPU-offload test (2 ranks) records the reload stream's waits:
  every reload waits on FSDP2's copy-in stream as well as the compute stream
  (fails without the change).

Not run: an end-to-end recipe with FSDP2 CPU offload measuring the overlap.
Until pytorch/pytorch#205180 reaches a nightly, CI's Pyrefly and this test
fail on the missing method.
anijain2305 added a commit to pytorch/torchtitan that referenced this pull request Nov 19, 2026
## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the
problem, why
     this approach, and what you checked yourself. -->

Depends on pytorch/pytorch#205180
(`FSDPModule.get_all_gather_copy_in_stream`).
Stacked on #6022.

## Why

With FSDP2 CPU parameter offload, block `i`'s backward boundary queues
two
host-to-device copies for block `i - 1`: FSDP2's pre-backward queues its
parameter shards on `all_gather_copy_in_stream`, then the reload trigger
queues its activations on the reload stream. Both become ready when
block
`i`'s copy-out finishes and share the link's bandwidth in no defined
order.
The parameters still need the all-gather after their copy; the
activations
need nothing more. So when the copies do not fit in block `i`'s
backward,
sharing is the worst order: both finish after `(P + A) / BW`, and only
then
does the all-gather start. Parameters first lets the all-gather overlap
the
activation copy, saving up to `min(all-gather, A / BW)`.

**Before -> after**, at the block `i` boundary (FSDP2 default streams):

| | Shard H2D (block i-1) | Activation H2D (group i-1) | All-gather
(block i-1) starts |
|---|---|---|---|
| before | starts after copy-out (i), shares bandwidth | starts after
copy-out (i), shares bandwidth | after both copies |
| after | starts after copy-out (i), alone | starts after the shard H2D
and pack | after the shard H2D, overlapping the reload |

![FSDP2 default streams at a backward block
boundary](https://raw.githubusercontent.com/pytorch/torchtitan/activation-offload-fsdp-order/assets/images/activation_offload_fsdp_streams.png)

## What changed

- `ActivationOffloader._reload` also waits on
  `model_part.get_all_gather_copy_in_stream()` when the model part is an
FSDP2 module. The hook order makes this precise: FSDP2's pre-backward (a
tensor hook on `out_i`) has queued block `i - 1`'s copy-in just before
the
reload trigger (a pre-hook on `out_i.grad_fn`) runs. The stream is read
at
  reload time, after FSDP2's lazy initialization in the first forward.
- Under `fsdp_unshard_in_current_stream` or a single rank, FSDP2 runs
the
copy-in on the compute stream, which the reload already waits on, and
the
  copy-in stream is idle, so the new wait changes nothing there:

![FSDP2 unshard_in_current_stream at a backward block
boundary](https://raw.githubusercontent.com/pytorch/torchtitan/activation-offload-fsdp-order/assets/images/activation_offload_fsdp_streams_current_stream.png)
- Without CPU offload the copy-in is only a GPU-to-GPU pack kernel, so
the
  reload starts after that short kernel too.
- `ACTIVATION_OFFLOAD.md`: the FSDP2 section describes the ordering,
with both
diagrams (`assets/images/activation_offload_fsdp_streams*.png`); the
TODO is
  gone.

## Alternatives considered

- Issue reloads on FSDP2's copy-in stream (an earlier version of #6020):
same-stream FIFO would make FSDP2's next copy-in queue behind a long
reload.
- An event recorded right after the shard H2D: tighter (skips the pack),
but
  needs FSDP2 to record it inside copy-in.

## Numerics

Ordering only; loss and gradients are unchanged. The FSDP2 CPU-offload
test
checks gradients bitwise against no activation offload.

## Testing

`tests/unit_tests/gpu/distributed/test_activation_offload.py` and
`test_activation_checkpoint.py` (36 tests, GB300), run against PyTorch
main's
FSDP2 with pytorch/pytorch#205180 applied:

- The FSDP2 CPU-offload test (2 ranks) records the reload stream's
waits:
every reload waits on FSDP2's copy-in stream as well as the compute
stream
  (fails without the change).

Not run: an end-to-end recipe with FSDP2 CPU offload measuring the
overlap.
Until pytorch/pytorch#205180 reaches a nightly, CI's Pyrefly and this
test
fail on the missing method.
fegin added a commit to pytorch/torchtitan that referenced this pull request Nov 20, 2026
…ctivation offload

## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why
     this approach, and what you checked yourself. -->

## Why
Our fastest Muse Spark 816B runs on 64 GPUs cannot be reproduced from the repo. They start from the 64-GPU recipe and change it in an out-of-tree launcher: layout, forced routing, Dist-MoE budgets, remat and offload policy, Adam moment placement, the optimizer CUDA graph, and FSDP symmetric memory. The launch environment and the dependency versions are not written down anywhere either.

The 64-GPU recipe also all-gathers the K/V of the full 32K sequence in every layer. The sliding-window varlen layers (46 of 62 layers, 2048-token window) read only the blocks inside their window, so most of that K/V is never used.

**Example.**

```text
before: muse_spark_816b_a42b_dist_moe_mxfp8_spmd_64, then the launcher sets
        DP32/CP2, forced routing, scratch 2, slot factor 0, remat p3,
        offload attention + MoE projections, moments on GPU, optimizer graph,
        FSDP symmetric memory, c4_test, 100 steps
after:  --module torchtitan_recipes.models.muse_spark \
        --config muse_spark_816b_a42b_dist_moe_mxfp8_spmd_64_benchmark
```

## What changed
- The Muse K/V-gather CP transform maps `SlidingWindowVarlenInnerAttention` to `SelectiveGatherKVSlidingWindowVarlenInnerAttention`. Global layers keep `AllGatherKVVarlenInnerAttention`. This applies to every 64-GPU recipe.
- The Muse save region becomes `attention.inner_attention*`, so the selective-gather assembly region nested in attention is saved with it. torch_remat rejects a recomputed region inside a saved one. The 256- and 512-GPU and UltraData recipes have no region nested in attention, so the wildcard does not change them.
- `_muse_spark_816b_dist_moe_spmd_64` takes `context_parallel_degree`; FSDP gets the other 64 / CP ranks. The existing 64-GPU recipes pass 8, as before.
- New `muse_spark_816b_a42b_dist_moe_{bf16,mxfp8}_spmd_64_benchmark` recipes and their `_fake` variants. They are benchmark only: forced balanced routing does not train a usable model.

| Setting | BF16 | MXFP8 |
| --- | --- | --- |
| layout | DP32, CP2, EP64, 2 microbatches per step | same |
| routing | forced balanced (round robin) | same |
| Dist-MoE | scratch_capacity_factor 2, activation_slot_capacity_factor 0 | same |
| remat save regions | Dist-MoE defaults + `attention.*` | + pooler, unpooler, router |
| activation offload | block input + `attention.*`, not in the last block | + pooler, unpooler, router |
| Adam moments | GPU (pinned_host_moment_fraction 0.0) | same |
| CUDA graphs | per microbatch group + optimizer graph | same |
| FSDP symmetric memory | scope all (off in `_fake`) | same |
| data | c4_test, random init, 100 steps (10 in `_fake`) | same |

- The benchmark docstring lists the launch environment (`NCCL_NVLS_ENABLE=1`, `PYTORCH_ALLOC_CONF=pinned_max_round_threshold_mb:1`, one NVLink domain per CP group, skipping `destroy_process_group`) and the dependency versions.

## Dependencies
- PyTorch nightly from 2026-11-20 or later. Activation offload on main calls `FSDPModule.get_all_gather_copy_in_stream` (pytorch/pytorch#205180).
- Depends on meta-pytorch/attention-gym#651 (selective gather); the attention-gym pin bump lands separately.

## How to reproduce
Stage the Muse Spark Open tokenizer files at `./assets/hf/Muse-Spark-Open-816B-A42B`, then on each of 16 hosts (4 GPUs each, all in one NVLink domain):
```bash
NCCL_NVLS_ENABLE=1 PYTORCH_ALLOC_CONF=pinned_max_round_threshold_mb:1 \
  torchrun --nnodes 16 --nproc-per-node 4 --node-rank <i> \
  --master-addr <host 0> --master-port 29500 -m torchtitan.train \
  --module torchtitan_recipes.models.muse_spark \
  --config muse_spark_816b_a42b_dist_moe_mxfp8_spmd_64_benchmark
```
Use `..._bf16_spmd_64_benchmark` for BF16. Measure tps as the mean of steps 71-90.

## Numerics
No model or kernel change. Forced routing makes the loss meaningless for training quality; it is only a run-to-run check.

The benchmark recipes build the same effective config as the launcher-built reference runs, field by field, except: `offload_last_block=False` in the reference runs, which #6020 removed (the recipes keep the last block on GPU with a `BlockRematOverride`, the same per-block offload plan), the new `per_sample_pad_multiple=1` dataloader default from main, main's RoPE `scaling='none'` -> `scaling=None` refactor, the launcher's profiler settings, and the tokenizer path.

100-step runs on 64 GPUs vs the reference runs of the same precision:

| Recipe | Mean / max abs loss diff | Loss at step 100 (new / reference) |
| --- | --- | --- |
| BF16 | 0.0017 / 0.0057 | 6.92717 / 6.92149 |
| MXFP8, run 1 | 0.0034 / 0.0086 | 6.94351 / 6.95157 |
| MXFP8, run 2 | 0.00025 / 0.0012 | 6.95231 / 6.95157 |

The two MXFP8 runs of this recipe differ from each other by 0.0035, so the run 1 gap is run-to-run noise. Step 1 matches the references exactly, and step-1 and step-2 peak memory match to 0.01 GiB.

## Performance
64 GB300 GPUs (16 nodes x 4), 100 steps. tps and TFLOPs are per GPU as logged by torchtitan, mean of steps 71-90. These runs used the launcher-built reference config, which matches these recipes field by field (see Numerics), on an earlier revision of this stack and of activation offload (#6020).

| Recipe | tps | TFLOPs |
| --- | ---: | ---: |
| `muse_spark_816b_a42b_dist_moe_mxfp8_spmd_64_benchmark` | 5,166 | 1,691 |
| `muse_spark_816b_a42b_dist_moe_bf16_spmd_64_benchmark` | 3,869 | 1,267 |

Forced balanced routing makes these benchmark numbers, not real-training numbers.

## Testing
- `pytest tests/unit_tests/cpu/recipes`: the new recipes build; the MLA override tests also pass when run alone.
- Config build of all four benchmark recipes, diffed field by field as above.
- FakePG, logical 64 GPUs, rank 0, 10 steps, both `_fake` recipes: MXFP8 step-2 peak 239.52 allocated / 252.68 reserved GiB, the same as an earlier FakePG run of this config. Activation offload moves 124.73 GiB (MXFP8) and 100.90 GiB (BF16) per forward, the same as the reference real runs.
- 64 GPUs, 100 steps, both precisions (MXFP8 twice): all ranks exit 0; numerics above.

## Known issues / follow-ups
- The numbers predate #6137 (activation reloads wait on FSDP2's copy-in stream). Its effect on these recipes is not measured.
- torchtitan does not check that a CP group sits in one NVLink domain.
- With FSDP symmetric memory and EP, `destroy_process_group` can hang after training. The recipe cannot skip it; the launcher must.
- `pytorch/pytorch#204942` is required: without it step 1 runs out of memory. This was measured with DP8/CP8, not rechecked with DP32/CP2.

stack-info: PR: #6252, branch: fegin/stack/45
fegin added a commit to pytorch/torchtitan that referenced this pull request Nov 20, 2026
…ctivation offload

## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why
     this approach, and what you checked yourself. -->

## Why
Our fastest Muse Spark 816B runs on 64 GPUs cannot be reproduced from the repo. They start from the 64-GPU recipe and change it in an out-of-tree launcher: layout, forced routing, Dist-MoE budgets, remat and offload policy, Adam moment placement, the optimizer CUDA graph, and FSDP symmetric memory. The launch environment and the dependency versions are not written down anywhere either.

The 64-GPU recipe also all-gathers the K/V of the full 32K sequence in every layer. The sliding-window varlen layers (46 of 62 layers, 2048-token window) read only the blocks inside their window, so most of that K/V is never used.

**Example.**

```text
before: muse_spark_816b_a42b_dist_moe_mxfp8_spmd_64, then the launcher sets
        DP32/CP2, forced routing, scratch 2, slot factor 0, remat p3,
        offload attention + MoE projections, moments on GPU, optimizer graph,
        FSDP symmetric memory, c4_test, 100 steps
after:  --module torchtitan_recipes.models.muse_spark \
        --config muse_spark_816b_a42b_dist_moe_mxfp8_spmd_64_benchmark
```

## What changed
- The Muse K/V-gather CP transform maps `SlidingWindowVarlenInnerAttention` to `SelectiveGatherKVSlidingWindowVarlenInnerAttention`. Global layers keep `AllGatherKVVarlenInnerAttention`. This applies to every 64-GPU recipe.
- The Muse save region becomes `attention.inner_attention*`, so the selective-gather assembly region nested in attention is saved with it. torch_remat rejects a recomputed region inside a saved one. The 256- and 512-GPU and UltraData recipes have no region nested in attention, so the wildcard does not change them.
- `_muse_spark_816b_dist_moe_spmd_64` takes `context_parallel_degree`; FSDP gets the other 64 / CP ranks. The existing 64-GPU recipes pass 8, as before.
- New `muse_spark_816b_a42b_dist_moe_{bf16,mxfp8}_spmd_64_benchmark` recipes and their `_fake` variants. They are benchmark only: forced balanced routing does not train a usable model.

| Setting | BF16 | MXFP8 |
| --- | --- | --- |
| layout | DP32, CP2, EP64, 2 microbatches per step | same |
| routing | forced balanced (round robin) | same |
| Dist-MoE | scratch_capacity_factor 2, activation_slot_capacity_factor 0 | same |
| remat save regions | Dist-MoE defaults + `attention.*` | + pooler, unpooler, router |
| activation offload | block input + `attention.*`, not in the last block | + pooler, unpooler, router |
| Adam moments | GPU (pinned_host_moment_fraction 0.0) | same |
| CUDA graphs | per microbatch group + optimizer graph | same |
| FSDP symmetric memory | scope all (off in `_fake`) | same |
| data | c4_test, random init, 100 steps (10 in `_fake`) | same |

- The benchmark docstring lists the launch environment (`NCCL_NVLS_ENABLE=1`, `PYTORCH_ALLOC_CONF=pinned_max_round_threshold_mb:1`, one NVLink domain per CP group, skipping `destroy_process_group`) and the dependency versions.

## Dependencies
- PyTorch nightly from 2026-11-20 or later. Activation offload on main calls `FSDPModule.get_all_gather_copy_in_stream` (pytorch/pytorch#205180).
- Depends on meta-pytorch/attention-gym#651 (selective gather); the attention-gym pin bump lands separately.

## How to reproduce
Stage the Muse Spark Open tokenizer files at `./assets/hf/Muse-Spark-Open-816B-A42B`, then on each of 16 hosts (4 GPUs each, all in one NVLink domain):
```bash
NCCL_NVLS_ENABLE=1 PYTORCH_ALLOC_CONF=pinned_max_round_threshold_mb:1 \
  torchrun --nnodes 16 --nproc-per-node 4 --node-rank <i> \
  --master-addr <host 0> --master-port 29500 -m torchtitan.train \
  --module torchtitan_recipes.models.muse_spark \
  --config muse_spark_816b_a42b_dist_moe_mxfp8_spmd_64_benchmark
```
Use `..._bf16_spmd_64_benchmark` for BF16. Measure tps as the mean of steps 71-90.

## Numerics
No model or kernel change. Forced routing makes the loss meaningless for training quality; it is only a run-to-run check.

The benchmark recipes build the same effective config as the launcher-built reference runs, field by field, except: `offload_last_block=False` in the reference runs, which #6020 removed (the recipes keep the last block on GPU with a `BlockRematOverride`, the same per-block offload plan), the new `per_sample_pad_multiple=1` dataloader default from main, main's RoPE `scaling='none'` -> `scaling=None` refactor, the launcher's profiler settings, and the tokenizer path.

100-step runs on 64 GPUs vs the reference runs of the same precision:

| Recipe | Mean / max abs loss diff | Loss at step 100 (new / reference) |
| --- | --- | --- |
| BF16 | 0.0017 / 0.0057 | 6.92717 / 6.92149 |
| MXFP8, run 1 | 0.0034 / 0.0086 | 6.94351 / 6.95157 |
| MXFP8, run 2 | 0.00025 / 0.0012 | 6.95231 / 6.95157 |

The two MXFP8 runs of this recipe differ from each other by 0.0035, so the run 1 gap is run-to-run noise. Step 1 matches the references exactly, and step-1 and step-2 peak memory match to 0.01 GiB.

## Performance
64 GB300 GPUs (16 nodes x 4), 100 steps. tps and TFLOPs are per GPU as logged by torchtitan, mean of steps 71-90. These runs used the launcher-built reference config, which matches these recipes field by field (see Numerics), on an earlier revision of this stack and of activation offload (#6020).

| Recipe | tps | TFLOPs |
| --- | ---: | ---: |
| `muse_spark_816b_a42b_dist_moe_mxfp8_spmd_64_benchmark` | 5,166 | 1,691 |
| `muse_spark_816b_a42b_dist_moe_bf16_spmd_64_benchmark` | 3,869 | 1,267 |

Forced balanced routing makes these benchmark numbers, not real-training numbers.

## Testing
- `pytest tests/unit_tests/cpu/recipes`: the new recipes build; the MLA override tests also pass when run alone.
- Config build of all four benchmark recipes, diffed field by field as above.
- FakePG, logical 64 GPUs, rank 0, 10 steps, both `_fake` recipes: MXFP8 step-2 peak 239.52 allocated / 252.68 reserved GiB, the same as an earlier FakePG run of this config. Activation offload moves 124.73 GiB (MXFP8) and 100.90 GiB (BF16) per forward, the same as the reference real runs.
- 64 GPUs, 100 steps, both precisions (MXFP8 twice): all ranks exit 0; numerics above.

## Known issues / follow-ups
- The numbers predate #6137 (activation reloads wait on FSDP2's copy-in stream). Its effect on these recipes is not measured.
- torchtitan does not check that a CP group sits in one NVLink domain.
- With FSDP symmetric memory and EP, `destroy_process_group` can hang after training. The recipe cannot skip it; the launcher must.
- `pytorch/pytorch#204942` is required: without it step 1 runs out of memory. This was measured with DP8/CP8, not rechecked with DP32/CP2.

stack-info: PR: #6252, branch: fegin/stack/45
fegin added a commit to pytorch/torchtitan that referenced this pull request Nov 23, 2026
…ctivation offload

## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why
     this approach, and what you checked yourself. -->

## Why
Our fastest Muse Spark 816B runs on 64 GPUs cannot be reproduced from the repo. They start from the 64-GPU recipe and change it in an out-of-tree launcher: layout, forced routing, Dist-MoE budgets, remat and offload policy, Adam moment placement, the optimizer CUDA graph, and FSDP symmetric memory. The launch environment and the dependency versions are not written down anywhere either.

The 64-GPU recipe also all-gathers the K/V of the full 32K sequence in every layer. The sliding-window varlen layers (46 of 62 layers, 2048-token window) read only the blocks inside their window, so most of that K/V is never used.

**Example.**

```text
before: muse_spark_816b_a42b_dist_moe_mxfp8_spmd_64, then the launcher sets
        DP32/CP2, forced routing, scratch 2, slot factor 0, remat p3,
        offload attention + MoE projections, moments on GPU, optimizer graph,
        FSDP symmetric memory, c4_test, 100 steps
after:  --module torchtitan_recipes.models.muse_spark \
        --config muse_spark_816b_a42b_dist_moe_mxfp8_spmd_64_benchmark
```

## What changed
- The Muse K/V-gather CP transform maps `SlidingWindowVarlenInnerAttention` to `SelectiveGatherKVSlidingWindowVarlenInnerAttention`. Global layers keep `AllGatherKVVarlenInnerAttention`. This applies to every 64-GPU recipe.
- The Muse save region becomes `attention.inner_attention*`, so the selective-gather assembly region nested in attention is saved with it. torch_remat rejects a recomputed region inside a saved one. The 256- and 512-GPU and UltraData recipes have no region nested in attention, so the wildcard does not change them.
- `_muse_spark_816b_dist_moe_spmd_64` takes `context_parallel_degree`; FSDP gets the other 64 / CP ranks. The existing 64-GPU recipes pass 8, as before.
- New `muse_spark_816b_a42b_dist_moe_{bf16,mxfp8}_spmd_64_benchmark` recipes and their `_fake` variants. They are benchmark only: forced balanced routing does not train a usable model.

| Setting | BF16 | MXFP8 |
| --- | --- | --- |
| layout | DP32, CP2, EP64, 2 microbatches per step | same |
| routing | forced balanced (round robin) | same |
| Dist-MoE | scratch_capacity_factor 2, activation_slot_capacity_factor 0 | same |
| remat save regions | Dist-MoE defaults + `attention.*` | + pooler, unpooler, router |
| activation offload | block input + `attention.*`, not in the last block | + pooler, unpooler, router |
| Adam moments | GPU (moment_cpu_offload_fraction 0.0) | same |
| CUDA graphs | per microbatch group + optimizer graph | same |
| FSDP symmetric memory | scope all (off in `_fake`) | same |
| data | c4_test, random init, 100 steps (10 in `_fake`) | same |

- The benchmark docstring lists the launch environment (`NCCL_NVLS_ENABLE=1`, `PYTORCH_ALLOC_CONF=pinned_max_round_threshold_mb:1`, one NVLink domain per CP group, skipping `destroy_process_group`) and the dependency versions.

## Dependencies
- PyTorch nightly from 2026-11-20 or later. Activation offload on main calls `FSDPModule.get_all_gather_copy_in_stream` (pytorch/pytorch#205180).
- Depends on meta-pytorch/attention-gym#651 (selective gather); the attention-gym pin bump lands separately.

## How to reproduce
Stage the Muse Spark Open tokenizer files at `./assets/hf/Muse-Spark-Open-816B-A42B`, then on each of 16 hosts (4 GPUs each, all in one NVLink domain):
```bash
NCCL_NVLS_ENABLE=1 PYTORCH_ALLOC_CONF=pinned_max_round_threshold_mb:1 \
  torchrun --nnodes 16 --nproc-per-node 4 --node-rank <i> \
  --master-addr <host 0> --master-port 29500 -m torchtitan.train \
  --module torchtitan_recipes.models.muse_spark \
  --config muse_spark_816b_a42b_dist_moe_mxfp8_spmd_64_benchmark
```
Use `..._bf16_spmd_64_benchmark` for BF16. Measure tps as the mean of steps 71-90.

## Numerics
No model or kernel change. Forced routing makes the loss meaningless for training quality; it is only a run-to-run check.

The benchmark recipes build the same effective config as the launcher-built reference runs, field by field, except: `offload_last_block=False` in the reference runs, which #6020 removed (the recipes keep the last block on GPU with a `BlockRematOverride`, the same per-block offload plan), the new `per_sample_pad_multiple=1` dataloader default from main, main's RoPE `scaling='none'` -> `scaling=None` refactor, the launcher's profiler settings, and the tokenizer path.

100-step runs on 64 GPUs vs the reference runs of the same precision:

| Recipe | Mean / max abs loss diff | Loss at step 100 (new / reference) |
| --- | --- | --- |
| BF16 | 0.0017 / 0.0057 | 6.92717 / 6.92149 |
| MXFP8, run 1 | 0.0034 / 0.0086 | 6.94351 / 6.95157 |
| MXFP8, run 2 | 0.00025 / 0.0012 | 6.95231 / 6.95157 |

The two MXFP8 runs of this recipe differ from each other by 0.0035, so the run 1 gap is run-to-run noise. Step 1 matches the references exactly, and step-1 and step-2 peak memory match to 0.01 GiB.

## Performance
64 GB300 GPUs (16 nodes x 4), 100 steps. tps and TFLOPs are per GPU as logged by torchtitan, mean of steps 71-90. These runs used the launcher-built reference config, which matches these recipes field by field (see Numerics), on an earlier revision of this stack and of activation offload (#6020).

| Recipe | tps | TFLOPs |
| --- | ---: | ---: |
| `muse_spark_816b_a42b_dist_moe_mxfp8_spmd_64_benchmark` | 5,166 | 1,691 |
| `muse_spark_816b_a42b_dist_moe_bf16_spmd_64_benchmark` | 3,869 | 1,267 |

Forced balanced routing makes these benchmark numbers, not real-training numbers.

## Testing
- `pytest tests/unit_tests/cpu/recipes`: the new recipes build; the MLA override tests also pass when run alone.
- Config build of all four benchmark recipes, diffed field by field as above.
- FakePG, logical 64 GPUs, rank 0, 10 steps, both `_fake` recipes: MXFP8 step-2 peak 239.52 allocated / 252.68 reserved GiB, the same as an earlier FakePG run of this config. Activation offload moves 124.73 GiB (MXFP8) and 100.90 GiB (BF16) per forward, the same as the reference real runs.
- 64 GPUs, 100 steps, both precisions (MXFP8 twice): all ranks exit 0; numerics above.

## Known issues / follow-ups
- The numbers predate #6137 (activation reloads wait on FSDP2's copy-in stream). Its effect on these recipes is not measured.
- torchtitan does not check that a CP group sits in one NVLink domain.
- With FSDP symmetric memory and EP, `destroy_process_group` can hang after training. The recipe cannot skip it; the launcher must.
- `pytorch/pytorch#204942` is required: without it step 1 runs out of memory. This was measured with DP8/CP8, not rechecked with DP32/CP2.

stack-info: PR: #6252, branch: fegin/stack/45
fegin added a commit to pytorch/torchtitan that referenced this pull request Nov 23, 2026
…ctivation offload

## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why
     this approach, and what you checked yourself. -->

## Why
Our fastest Muse Spark 816B runs on 64 GPUs cannot be reproduced from the repo. They start from the 64-GPU recipe and change it in an out-of-tree launcher: layout, forced routing, Dist-MoE budgets, remat and offload policy, Adam moment placement, the optimizer CUDA graph, and FSDP symmetric memory. The launch environment and the dependency versions are not written down anywhere either.

The 64-GPU recipe also all-gathers the K/V of the full 32K sequence in every layer. The sliding-window varlen layers (46 of 62 layers, 2048-token window) read only the blocks inside their window, so most of that K/V is never used.

**Example.**

```text
before: muse_spark_816b_a42b_dist_moe_mxfp8_spmd_64, then the launcher sets
        DP32/CP2, forced routing, scratch 2, slot factor 0, remat p3,
        offload attention + MoE projections, moments on GPU, optimizer graph,
        FSDP symmetric memory, c4_test, 100 steps
after:  --module torchtitan_recipes.models.muse_spark \
        --config muse_spark_816b_a42b_dist_moe_mxfp8_spmd_64_benchmark
```

## What changed
- The Muse K/V-gather CP transform maps `SlidingWindowVarlenInnerAttention` to `SelectiveGatherKVSlidingWindowVarlenInnerAttention`. Global layers keep `AllGatherKVVarlenInnerAttention`. This applies to every 64-GPU recipe.
- The Muse save region becomes `attention.inner_attention*`, so the selective-gather assembly region nested in attention is saved with it. torch_remat rejects a recomputed region inside a saved one. The 256- and 512-GPU and UltraData recipes have no region nested in attention, so the wildcard does not change them.
- `_muse_spark_816b_dist_moe_spmd_64` takes `context_parallel_degree`; FSDP gets the other 64 / CP ranks. The existing 64-GPU recipes pass 8, as before.
- New `muse_spark_816b_a42b_dist_moe_{bf16,mxfp8}_spmd_64_benchmark` recipes and their `_fake` variants. They are benchmark only: forced balanced routing does not train a usable model.

| Setting | BF16 | MXFP8 |
| --- | --- | --- |
| layout | DP32, CP2, EP64, 2 microbatches per step | same |
| routing | forced balanced (round robin) | same |
| Dist-MoE | scratch_capacity_factor 2, activation_slot_capacity_factor 0 | same |
| remat save regions | Dist-MoE defaults + `attention.*` | + pooler, unpooler, router |
| activation offload | block input + `attention.*`, not in the last block | + pooler, unpooler, router |
| Adam moments | GPU (moment_cpu_offload_fraction 0.0) | same |
| CUDA graphs | per microbatch group + optimizer graph | same |
| FSDP symmetric memory | scope all (off in `_fake`) | same |
| data | c4_test, random init, 100 steps (10 in `_fake`) | same |

- The benchmark docstring lists the launch environment (`NCCL_NVLS_ENABLE=1`, `PYTORCH_ALLOC_CONF=pinned_max_round_threshold_mb:1`, one NVLink domain per CP group, skipping `destroy_process_group`) and the dependency versions.

## Dependencies
- PyTorch nightly from 2026-11-20 or later. Activation offload on main calls `FSDPModule.get_all_gather_copy_in_stream` (pytorch/pytorch#205180).
- Depends on meta-pytorch/attention-gym#651 (selective gather); the attention-gym pin bump lands separately.

## How to reproduce
Stage the Muse Spark Open tokenizer files at `./assets/hf/Muse-Spark-Open-816B-A42B`, then on each of 16 hosts (4 GPUs each, all in one NVLink domain):
```bash
NCCL_NVLS_ENABLE=1 PYTORCH_ALLOC_CONF=pinned_max_round_threshold_mb:1 \
  torchrun --nnodes 16 --nproc-per-node 4 --node-rank <i> \
  --master-addr <host 0> --master-port 29500 -m torchtitan.train \
  --module torchtitan_recipes.models.muse_spark \
  --config muse_spark_816b_a42b_dist_moe_mxfp8_spmd_64_benchmark
```
Use `..._bf16_spmd_64_benchmark` for BF16. Measure tps as the mean of steps 71-90.

## Numerics
No model or kernel change. Forced routing makes the loss meaningless for training quality; it is only a run-to-run check.

The benchmark recipes build the same effective config as the launcher-built reference runs, field by field, except: `offload_last_block=False` in the reference runs, which #6020 removed (the recipes keep the last block on GPU with a `BlockRematOverride`, the same per-block offload plan), the new `per_sample_pad_multiple=1` dataloader default from main, main's RoPE `scaling='none'` -> `scaling=None` refactor, the launcher's profiler settings, and the tokenizer path.

100-step runs on 64 GPUs vs the reference runs of the same precision:

| Recipe | Mean / max abs loss diff | Loss at step 100 (new / reference) |
| --- | --- | --- |
| BF16 | 0.0017 / 0.0057 | 6.92717 / 6.92149 |
| MXFP8, run 1 | 0.0034 / 0.0086 | 6.94351 / 6.95157 |
| MXFP8, run 2 | 0.00025 / 0.0012 | 6.95231 / 6.95157 |

The two MXFP8 runs of this recipe differ from each other by 0.0035, so the run 1 gap is run-to-run noise. Step 1 matches the references exactly, and step-1 and step-2 peak memory match to 0.01 GiB.

## Performance
64 GB300 GPUs (16 nodes x 4), 100 steps. tps and TFLOPs are per GPU as logged by torchtitan, mean of steps 71-90. These runs used the launcher-built reference config, which matches these recipes field by field (see Numerics), on an earlier revision of this stack and of activation offload (#6020).

| Recipe | tps | TFLOPs |
| --- | ---: | ---: |
| `muse_spark_816b_a42b_dist_moe_mxfp8_spmd_64_benchmark` | 5,166 | 1,691 |
| `muse_spark_816b_a42b_dist_moe_bf16_spmd_64_benchmark` | 3,869 | 1,267 |

Forced balanced routing makes these benchmark numbers, not real-training numbers.

## Testing
- `pytest tests/unit_tests/cpu/recipes`: the new recipes build; the MLA override tests also pass when run alone.
- Config build of all four benchmark recipes, diffed field by field as above.
- FakePG, logical 64 GPUs, rank 0, 10 steps, both `_fake` recipes: MXFP8 step-2 peak 239.52 allocated / 252.68 reserved GiB, the same as an earlier FakePG run of this config. Activation offload moves 124.73 GiB (MXFP8) and 100.90 GiB (BF16) per forward, the same as the reference real runs.
- 64 GPUs, 100 steps, both precisions (MXFP8 twice): all ranks exit 0; numerics above.

## Known issues / follow-ups
- The numbers predate #6137 (activation reloads wait on FSDP2's copy-in stream). Its effect on these recipes is not measured.
- torchtitan does not check that a CP group sits in one NVLink domain.
- With FSDP symmetric memory and EP, `destroy_process_group` can hang after training. The recipe cannot skip it; the launcher must.
- `pytorch/pytorch#204942` is required: without it step 1 runs out of memory. This was measured with DP8/CP8, not rechecked with DP32/CP2.

stack-info: PR: #6252, branch: fegin/stack/45
fegin added a commit to pytorch/torchtitan that referenced this pull request Nov 23, 2026
…ctivation offload

## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why
     this approach, and what you checked yourself. -->

## Why
Our fastest Muse Spark 816B runs on 64 GPUs cannot be reproduced from the repo. They start from the 64-GPU recipe and change it in an out-of-tree launcher: layout, forced routing, Dist-MoE budgets, remat and offload policy, Adam moment placement, the optimizer CUDA graph, and FSDP symmetric memory. The launch environment and the dependency versions are not written down anywhere either.

The 64-GPU recipe also all-gathers the K/V of the full 32K sequence in every layer. The sliding-window varlen layers (46 of 62 layers, 2048-token window) read only the blocks inside their window, so most of that K/V is never used.

**Example.**

```text
before: muse_spark_816b_a42b_dist_moe_mxfp8_spmd_64, then the launcher sets
        DP32/CP2, forced routing, scratch 2, slot factor 0, remat p3,
        offload attention + MoE projections, moments on GPU, optimizer graph,
        FSDP symmetric memory, c4_test, 100 steps
after:  --module torchtitan_recipes.models.muse_spark \
        --config muse_spark_816b_a42b_dist_moe_mxfp8_spmd_64_benchmark
```

## What changed
- The Muse K/V-gather CP transform maps `SlidingWindowVarlenInnerAttention` to `SelectiveGatherKVSlidingWindowVarlenInnerAttention`. Global layers keep `AllGatherKVVarlenInnerAttention`. This applies to every 64-GPU recipe.
- The Muse save region becomes `attention.inner_attention*`, so the selective-gather assembly region nested in attention is saved with it. torch_remat rejects a recomputed region inside a saved one. The 256- and 512-GPU and UltraData recipes have no region nested in attention, so the wildcard does not change them.
- `_muse_spark_816b_dist_moe_spmd_64` takes `context_parallel_degree`; FSDP gets the other 64 / CP ranks. The existing 64-GPU recipes pass 8, as before.
- New `muse_spark_816b_a42b_dist_moe_{bf16,mxfp8}_spmd_64_benchmark` recipes and their `_fake` variants. They are benchmark only: forced balanced routing does not train a usable model.

| Setting | BF16 | MXFP8 |
| --- | --- | --- |
| layout | DP32, CP2, EP64, 2 microbatches per step | same |
| routing | forced balanced (round robin) | same |
| Dist-MoE | scratch_capacity_factor 2, activation_slot_capacity_factor 0 | same |
| remat save regions | Dist-MoE defaults + `attention.*` | + pooler, unpooler, router |
| activation offload | block input + `attention.*`, not in the last block | + pooler, unpooler, router |
| Adam moments | GPU (moment_cpu_offload_fraction 0.0) | same |
| CUDA graphs | per microbatch group + optimizer graph | same |
| FSDP symmetric memory | scope all (off in `_fake`) | same |
| data | c4_test, random init, 100 steps (10 in `_fake`) | same |

- The benchmark docstring lists the launch environment (`NCCL_NVLS_ENABLE=1`, `PYTORCH_ALLOC_CONF=pinned_max_round_threshold_mb:1`, one NVLink domain per CP group, skipping `destroy_process_group`) and the dependency versions.

## Dependencies
- PyTorch nightly from 2026-11-20 or later. Activation offload on main calls `FSDPModule.get_all_gather_copy_in_stream` (pytorch/pytorch#205180).
- Depends on meta-pytorch/attention-gym#651 (selective gather); the attention-gym pin bump lands separately.

## How to reproduce
Stage the Muse Spark Open tokenizer files at `./assets/hf/Muse-Spark-Open-816B-A42B`, then on each of 16 hosts (4 GPUs each, all in one NVLink domain):
```bash
NCCL_NVLS_ENABLE=1 PYTORCH_ALLOC_CONF=pinned_max_round_threshold_mb:1 \
  torchrun --nnodes 16 --nproc-per-node 4 --node-rank <i> \
  --master-addr <host 0> --master-port 29500 -m torchtitan.train \
  --module torchtitan_recipes.models.muse_spark \
  --config muse_spark_816b_a42b_dist_moe_mxfp8_spmd_64_benchmark
```
Use `..._bf16_spmd_64_benchmark` for BF16. Measure tps as the mean of steps 71-90.

## Numerics
No model or kernel change. Forced routing makes the loss meaningless for training quality; it is only a run-to-run check.

The benchmark recipes build the same effective config as the launcher-built reference runs, field by field, except: `offload_last_block=False` in the reference runs, which #6020 removed (the recipes keep the last block on GPU with a `BlockRematOverride`, the same per-block offload plan), the new `per_sample_pad_multiple=1` dataloader default from main, main's RoPE `scaling='none'` -> `scaling=None` refactor, the launcher's profiler settings, and the tokenizer path.

100-step runs on 64 GPUs vs the reference runs of the same precision:

| Recipe | Mean / max abs loss diff | Loss at step 100 (new / reference) |
| --- | --- | --- |
| BF16 | 0.0017 / 0.0057 | 6.92717 / 6.92149 |
| MXFP8, run 1 | 0.0034 / 0.0086 | 6.94351 / 6.95157 |
| MXFP8, run 2 | 0.00025 / 0.0012 | 6.95231 / 6.95157 |

The two MXFP8 runs of this recipe differ from each other by 0.0035, so the run 1 gap is run-to-run noise. Step 1 matches the references exactly, and step-1 and step-2 peak memory match to 0.01 GiB.

## Performance
64 GB300 GPUs (16 nodes x 4), 100 steps. tps and TFLOPs are per GPU as logged by torchtitan, mean of steps 71-90. These runs used the launcher-built reference config, which matches these recipes field by field (see Numerics), on an earlier revision of this stack and of activation offload (#6020).

| Recipe | tps | TFLOPs |
| --- | ---: | ---: |
| `muse_spark_816b_a42b_dist_moe_mxfp8_spmd_64_benchmark` | 5,166 | 1,691 |
| `muse_spark_816b_a42b_dist_moe_bf16_spmd_64_benchmark` | 3,869 | 1,267 |

Forced balanced routing makes these benchmark numbers, not real-training numbers.

## Testing
- `pytest tests/unit_tests/cpu/recipes`: the new recipes build; the MLA override tests also pass when run alone.
- Config build of all four benchmark recipes, diffed field by field as above.
- FakePG, logical 64 GPUs, rank 0, 10 steps, both `_fake` recipes: MXFP8 step-2 peak 239.52 allocated / 252.68 reserved GiB, the same as an earlier FakePG run of this config. Activation offload moves 124.73 GiB (MXFP8) and 100.90 GiB (BF16) per forward, the same as the reference real runs.
- 64 GPUs, 100 steps, both precisions (MXFP8 twice): all ranks exit 0; numerics above.

## Known issues / follow-ups
- The numbers predate #6137 (activation reloads wait on FSDP2's copy-in stream). Its effect on these recipes is not measured.
- torchtitan does not check that a CP group sits in one NVLink domain.
- With FSDP symmetric memory and EP, `destroy_process_group` can hang after training. The recipe cannot skip it; the launcher must.
- `pytorch/pytorch#204942` is required: without it step 1 runs out of memory. This was measured with DP8/CP8, not rechecked with DP32/CP2.

stack-info: PR: #6252, branch: fegin/stack/45
fegin added a commit to pytorch/torchtitan that referenced this pull request Nov 30, 2026
…ctivation offload

## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why
     this approach, and what you checked yourself. -->

## Why
Our fastest Muse Spark 816B runs on 64 GPUs cannot be reproduced from the repo. They start from the 64-GPU recipe and change it in an out-of-tree launcher: layout, forced routing, Dist-MoE budgets, remat and offload policy, Adam moment placement, the optimizer CUDA graph, and FSDP symmetric memory. The launch environment and the dependency versions are not written down anywhere either.

The 64-GPU recipe also all-gathers the K/V of the full 32K sequence in every layer. The sliding-window varlen layers (46 of 62 layers, 2048-token window) read only the blocks inside their window, so most of that K/V is never used.

**Example.**

```text
before: muse_spark_816b_a42b_dist_moe_mxfp8_spmd_64, then the launcher sets
        DP32/CP2, forced routing, scratch 2, slot factor 0, remat p3,
        offload attention + MoE projections, moments on GPU, optimizer graph,
        FSDP symmetric memory, c4_test, 100 steps
after:  --module torchtitan_recipes.models.muse_spark \
        --config muse_spark_816b_a42b_dist_moe_mxfp8_spmd_64_benchmark
```

## What changed
- The Muse K/V-gather CP transform maps `SlidingWindowVarlenInnerAttention` to `SelectiveGatherKVSlidingWindowVarlenInnerAttention`. Global layers keep `AllGatherKVVarlenInnerAttention`. This applies to every 64-GPU recipe.
- The Muse save region becomes `attention.inner_attention*`, so the selective-gather assembly region nested in attention is saved with it. torch_remat rejects a recomputed region inside a saved one. The 256- and 512-GPU and UltraData recipes have no region nested in attention, so the wildcard does not change them.
- `_muse_spark_816b_dist_moe_spmd_64` takes `context_parallel_degree`; FSDP gets the other 64 / CP ranks. The existing 64-GPU recipes pass 8, as before.
- New `muse_spark_816b_a42b_dist_moe_{bf16,mxfp8}_spmd_64_benchmark` recipes and their `_fake` variants. They are benchmark only: forced balanced routing does not train a usable model.

| Setting | BF16 | MXFP8 |
| --- | --- | --- |
| layout | DP32, CP2, EP64, 2 microbatches per step | same |
| routing | forced balanced (round robin) | same |
| Dist-MoE | scratch_capacity_factor 2, activation_slot_capacity_factor 0 | same |
| remat save regions | Dist-MoE defaults + `attention.*` | + pooler, unpooler, router |
| activation offload | block input + `attention.*`, not in the last block | + pooler, unpooler, router |
| Adam moments | GPU (moment_cpu_offload_fraction 0.0) | same |
| CUDA graphs | per microbatch group + optimizer graph | same |
| FSDP symmetric memory | scope all (off in `_fake`) | same |
| data | c4_test, random init, 100 steps (10 in `_fake`) | same |

- The benchmark docstring lists the launch environment (`NCCL_NVLS_ENABLE=1`, `PYTORCH_ALLOC_CONF=pinned_max_round_threshold_mb:1`, one NVLink domain per CP group, skipping `destroy_process_group`) and the dependency versions.

## Dependencies
- PyTorch nightly from 2026-11-20 or later. Activation offload on main calls `FSDPModule.get_all_gather_copy_in_stream` (pytorch/pytorch#205180).
- Depends on meta-pytorch/attention-gym#651 (selective gather); the attention-gym pin bump lands separately.

## How to reproduce
Stage the Muse Spark Open tokenizer files at `./assets/hf/Muse-Spark-Open-816B-A42B`, then on each of 16 hosts (4 GPUs each, all in one NVLink domain):
```bash
NCCL_NVLS_ENABLE=1 PYTORCH_ALLOC_CONF=pinned_max_round_threshold_mb:1 \
  torchrun --nnodes 16 --nproc-per-node 4 --node-rank <i> \
  --master-addr <host 0> --master-port 29500 -m torchtitan.train \
  --module torchtitan_recipes.models.muse_spark \
  --config muse_spark_816b_a42b_dist_moe_mxfp8_spmd_64_benchmark
```
Use `..._bf16_spmd_64_benchmark` for BF16. Measure tps as the mean of steps 71-90.

## Numerics
No model or kernel change. Forced routing makes the loss meaningless for training quality; it is only a run-to-run check.

The benchmark recipes build the same effective config as the launcher-built reference runs, field by field, except: `offload_last_block=False` in the reference runs, which #6020 removed (the recipes keep the last block on GPU with a `BlockRematOverride`, the same per-block offload plan), the new `per_sample_pad_multiple=1` dataloader default from main, main's RoPE `scaling='none'` -> `scaling=None` refactor, the launcher's profiler settings, and the tokenizer path.

100-step runs on 64 GPUs vs the reference runs of the same precision:

| Recipe | Mean / max abs loss diff | Loss at step 100 (new / reference) |
| --- | --- | --- |
| BF16 | 0.0017 / 0.0057 | 6.92717 / 6.92149 |
| MXFP8, run 1 | 0.0034 / 0.0086 | 6.94351 / 6.95157 |
| MXFP8, run 2 | 0.00025 / 0.0012 | 6.95231 / 6.95157 |

The two MXFP8 runs of this recipe differ from each other by 0.0035, so the run 1 gap is run-to-run noise. Step 1 matches the references exactly, and step-1 and step-2 peak memory match to 0.01 GiB.

## Performance
64 GB300 GPUs (16 nodes x 4), 100 steps. tps and TFLOPs are per GPU as logged by torchtitan, mean of steps 71-90. These runs used the launcher-built reference config, which matches these recipes field by field (see Numerics), on an earlier revision of this stack and of activation offload (#6020). These runs used `max_num_documents=64`. #5882 raises it to 128, which removes the padding (10.7% of the tokens on C4) and lowers the reported tps, because tps counts padding tokens.

| Recipe | tps | TFLOPs |
| --- | ---: | ---: |
| `muse_spark_816b_a42b_dist_moe_mxfp8_spmd_64_benchmark` | 5,166 | 1,691 |
| `muse_spark_816b_a42b_dist_moe_bf16_spmd_64_benchmark` | 3,869 | 1,267 |

Forced balanced routing makes these benchmark numbers, not real-training numbers.

## Testing
- `pytest tests/unit_tests/cpu/recipes`: the new recipes build; the MLA override tests also pass when run alone.
- Config build of all four benchmark recipes, diffed field by field as above.
- FakePG, logical 64 GPUs, rank 0, 10 steps, both `_fake` recipes: MXFP8 step-2 peak 239.52 allocated / 252.68 reserved GiB, the same as an earlier FakePG run of this config. Activation offload moves 124.73 GiB (MXFP8) and 100.90 GiB (BF16) per forward, the same as the reference real runs.
- 64 GPUs, 100 steps, both precisions (MXFP8 twice): all ranks exit 0; numerics above.

## Known issues / follow-ups
- The numbers predate #6137 (activation reloads wait on FSDP2's copy-in stream). Its effect on these recipes is not measured.
- torchtitan does not check that a CP group sits in one NVLink domain.
- With FSDP symmetric memory and EP, `destroy_process_group` can hang after training. The recipe cannot skip it; the launcher must.
- `pytorch/pytorch#204942` is required: without it step 1 runs out of memory. This was measured with DP8/CP8, not rechecked with DP32/CP2.

stack-info: PR: #6252, branch: fegin/stack/45
fegin added a commit to pytorch/torchtitan that referenced this pull request Nov 30, 2026
…ctivation offload

## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why
     this approach, and what you checked yourself. -->

## Why
Our fastest Muse Spark 816B runs on 64 GPUs cannot be reproduced from the repo. They start from the 64-GPU recipe and change it in an out-of-tree launcher: layout, forced routing, Dist-MoE budgets, remat and offload policy, Adam moment placement, the optimizer CUDA graph, and FSDP symmetric memory. The launch environment and the dependency versions are not written down anywhere either.

The 64-GPU recipe also all-gathers the K/V of the full 32K sequence in every layer. The sliding-window varlen layers (46 of 62 layers, 2048-token window) read only the blocks inside their window, so most of that K/V is never used.

**Example.**

```text
before: muse_spark_816b_a42b_dist_moe_mxfp8_spmd_64, then the launcher sets
        DP32/CP2, forced routing, scratch 2, slot factor 0, remat p3,
        offload attention + MoE projections, moments on GPU, optimizer graph,
        FSDP symmetric memory, c4_test, 100 steps
after:  --module torchtitan_recipes.models.muse_spark \
        --config muse_spark_816b_a42b_dist_moe_mxfp8_spmd_64_benchmark
```

## What changed
- The Muse K/V-gather CP transform maps `SlidingWindowVarlenInnerAttention` to `SelectiveGatherKVSlidingWindowVarlenInnerAttention`. Global layers keep `AllGatherKVVarlenInnerAttention`. This applies to every 64-GPU recipe.
- The Muse save region becomes `attention.inner_attention*`, so the selective-gather assembly region nested in attention is saved with it. torch_remat rejects a recomputed region inside a saved one. The 256- and 512-GPU and UltraData recipes have no region nested in attention, so the wildcard does not change them.
- `_muse_spark_816b_dist_moe_spmd_64` takes `context_parallel_degree`; FSDP gets the other 64 / CP ranks. The existing 64-GPU recipes pass 8, as before.
- New `muse_spark_816b_a42b_dist_moe_{bf16,mxfp8}_spmd_64_benchmark` recipes and their `_fake` variants. They are benchmark only: forced balanced routing does not train a usable model.

| Setting | BF16 | MXFP8 |
| --- | --- | --- |
| layout | DP32, CP2, EP64, 2 microbatches per step | same |
| routing | forced balanced (round robin) | same |
| Dist-MoE | scratch_capacity_factor 2, activation_slot_capacity_factor 0 | same |
| remat save regions | Dist-MoE defaults + `attention.*` | + pooler, unpooler, router |
| activation offload | block input + `attention.*`, not in the last block | + pooler, unpooler, router |
| Adam moments | GPU (moment_cpu_offload_fraction 0.0) | same |
| CUDA graphs | per microbatch group + optimizer graph | same |
| FSDP symmetric memory | scope all (off in `_fake`) | same |
| data | c4_test, random init, 100 steps (10 in `_fake`) | same |

- The benchmark docstring lists the launch environment (`NCCL_NVLS_ENABLE=1`, `PYTORCH_ALLOC_CONF=pinned_max_round_threshold_mb:1`, one NVLink domain per CP group, skipping `destroy_process_group`) and the dependency versions.

## Dependencies
- PyTorch nightly from 2026-11-20 or later. Activation offload on main calls `FSDPModule.get_all_gather_copy_in_stream` (pytorch/pytorch#205180).
- Depends on meta-pytorch/attention-gym#651 (selective gather); the attention-gym pin bump lands separately.

## How to reproduce
Stage the Muse Spark Open tokenizer files at `./assets/hf/Muse-Spark-Open-816B-A42B`, then on each of 16 hosts (4 GPUs each, all in one NVLink domain):
```bash
NCCL_NVLS_ENABLE=1 PYTORCH_ALLOC_CONF=pinned_max_round_threshold_mb:1 \
  torchrun --nnodes 16 --nproc-per-node 4 --node-rank <i> \
  --master-addr <host 0> --master-port 29500 -m torchtitan.train \
  --module torchtitan_recipes.models.muse_spark \
  --config muse_spark_816b_a42b_dist_moe_mxfp8_spmd_64_benchmark
```
Use `..._bf16_spmd_64_benchmark` for BF16. Measure tps as the mean of steps 71-90.

## Numerics
No model or kernel change. Forced routing makes the loss meaningless for training quality; it is only a run-to-run check.

The benchmark recipes build the same effective config as the launcher-built reference runs, field by field, except: `offload_last_block=False` in the reference runs, which #6020 removed (the recipes keep the last block on GPU with a `BlockRematOverride`, the same per-block offload plan), the new `per_sample_pad_multiple=1` dataloader default from main, main's RoPE `scaling='none'` -> `scaling=None` refactor, the launcher's profiler settings, and the tokenizer path.

100-step runs on 64 GPUs vs the reference runs of the same precision:

| Recipe | Mean / max abs loss diff | Loss at step 100 (new / reference) |
| --- | --- | --- |
| BF16 | 0.0017 / 0.0057 | 6.92717 / 6.92149 |
| MXFP8, run 1 | 0.0034 / 0.0086 | 6.94351 / 6.95157 |
| MXFP8, run 2 | 0.00025 / 0.0012 | 6.95231 / 6.95157 |

The two MXFP8 runs of this recipe differ from each other by 0.0035, so the run 1 gap is run-to-run noise. Step 1 matches the references exactly, and step-1 and step-2 peak memory match to 0.01 GiB.

## Performance
64 GB300 GPUs (16 nodes x 4), 100 steps. tps and TFLOPs are per GPU as logged by torchtitan, mean of steps 71-90. These runs used the launcher-built reference config, which matches these recipes field by field (see Numerics), on an earlier revision of this stack and of activation offload (#6020). These runs used `max_num_documents=64`. #5882 raises it to 128, which removes the padding (10.7% of the tokens on C4) and lowers the reported tps, because tps counts padding tokens.

| Recipe | tps | TFLOPs |
| --- | ---: | ---: |
| `muse_spark_816b_a42b_dist_moe_mxfp8_spmd_64_benchmark` | 5,166 | 1,691 |
| `muse_spark_816b_a42b_dist_moe_bf16_spmd_64_benchmark` | 3,869 | 1,267 |

Forced balanced routing makes these benchmark numbers, not real-training numbers.

## Testing
- `pytest tests/unit_tests/cpu/recipes`: the new recipes build; the MLA override tests also pass when run alone.
- Config build of all four benchmark recipes, diffed field by field as above.
- FakePG, logical 64 GPUs, rank 0, 10 steps, both `_fake` recipes: MXFP8 step-2 peak 239.52 allocated / 252.68 reserved GiB, the same as an earlier FakePG run of this config. Activation offload moves 124.73 GiB (MXFP8) and 100.90 GiB (BF16) per forward, the same as the reference real runs.
- 64 GPUs, 100 steps, both precisions (MXFP8 twice): all ranks exit 0; numerics above.

## Known issues / follow-ups
- The numbers predate #6137 (activation reloads wait on FSDP2's copy-in stream). Its effect on these recipes is not measured.
- torchtitan does not check that a CP group sits in one NVLink domain.
- With FSDP symmetric memory and EP, `destroy_process_group` can hang after training. The recipe cannot skip it; the launcher must.
- `pytorch/pytorch#204942` is required: without it step 1 runs out of memory. This was measured with DP8/CP8, not rechecked with DP32/CP2.

stack-info: PR: #6252, branch: fegin/stack/45
fegin added a commit to pytorch/torchtitan that referenced this pull request Dec 1, 2026
…ctivation offload

## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why
     this approach, and what you checked yourself. -->

## Why
Our fastest Muse Spark 816B runs on 64 GPUs cannot be reproduced from the repo. They start from the 64-GPU recipe and change it in an out-of-tree launcher: layout, forced routing, Dist-MoE budgets, remat and offload policy, Adam moment placement, the optimizer CUDA graph, and FSDP symmetric memory. The launch environment and the dependency versions are not written down anywhere either.

The 64-GPU recipe also all-gathers the K/V of the full 32K sequence in every layer. The sliding-window varlen layers (46 of 62 layers, 2048-token window) read only the blocks inside their window, so most of that K/V is never used.

**Example.**

```text
before: muse_spark_816b_a42b_dist_moe_mxfp8_spmd_64, then the launcher sets
        DP32/CP2, forced routing, scratch 2, slot factor 0, remat p3,
        offload attention + MoE projections, moments on GPU, optimizer graph,
        FSDP symmetric memory, c4_test, 100 steps
after:  --module torchtitan_recipes.models.muse_spark \
        --config muse_spark_816b_a42b_dist_moe_mxfp8_spmd_64_benchmark
```

## What changed
- The Muse K/V-gather CP transform maps `SlidingWindowVarlenInnerAttention` to `SelectiveGatherKVSlidingWindowVarlenInnerAttention`. Global layers keep `AllGatherKVVarlenInnerAttention`. This applies to every 64-GPU recipe.
- The Muse save region becomes `attention.inner_attention*`, so the selective-gather assembly region nested in attention is saved with it. torch_remat rejects a recomputed region inside a saved one. The 256- and 512-GPU and UltraData recipes have no region nested in attention, so the wildcard does not change them.
- `_muse_spark_816b_dist_moe_spmd_64` takes `context_parallel_degree`; FSDP gets the other 64 / CP ranks. The existing 64-GPU recipes pass 8, as before.
- New `muse_spark_816b_a42b_dist_moe_{bf16,mxfp8}_spmd_64_benchmark` recipes and their `_fake` variants. They are benchmark only: forced balanced routing does not train a usable model.

| Setting | BF16 | MXFP8 |
| --- | --- | --- |
| layout | DP32, CP2, EP64, 2 microbatches per step | same |
| routing | forced balanced (round robin) | same |
| Dist-MoE | scratch_capacity_factor 2, activation_slot_capacity_factor 0 | same |
| remat save regions | Dist-MoE defaults + `attention.*` | + pooler, unpooler, router |
| activation offload | block input + `attention.*`, not in the last block | + pooler, unpooler, router |
| Adam moments | GPU (moment_cpu_offload_fraction 0.0) | same |
| CUDA graphs | per microbatch group + optimizer graph | same |
| FSDP symmetric memory | scope all (off in `_fake`) | same |
| data | c4_test, random init, 100 steps (10 in `_fake`) | same |

- The benchmark docstring lists the launch environment (`NCCL_NVLS_ENABLE=1`, `PYTORCH_ALLOC_CONF=pinned_max_round_threshold_mb:1`, one NVLink domain per CP group, skipping `destroy_process_group`) and the dependency versions.

## Dependencies
- PyTorch nightly from 2026-11-20 or later. Activation offload on main calls `FSDPModule.get_all_gather_copy_in_stream` (pytorch/pytorch#205180).
- Depends on meta-pytorch/attention-gym#651 (selective gather); the attention-gym pin bump lands separately.

## How to reproduce
Stage the Muse Spark Open tokenizer files at `./assets/hf/Muse-Spark-Open-816B-A42B`, then on each of 16 hosts (4 GPUs each, all in one NVLink domain):
```bash
NCCL_NVLS_ENABLE=1 PYTORCH_ALLOC_CONF=pinned_max_round_threshold_mb:1 \
  torchrun --nnodes 16 --nproc-per-node 4 --node-rank <i> \
  --master-addr <host 0> --master-port 29500 -m torchtitan.train \
  --module torchtitan_recipes.models.muse_spark \
  --config muse_spark_816b_a42b_dist_moe_mxfp8_spmd_64_benchmark
```
Use `..._bf16_spmd_64_benchmark` for BF16. Measure tps as the mean of steps 71-90.

## Numerics
No model or kernel change. Forced routing makes the loss meaningless for training quality; it is only a run-to-run check.

The benchmark recipes build the same effective config as the launcher-built reference runs, field by field, except: `offload_last_block=False` in the reference runs, which #6020 removed (the recipes keep the last block on GPU with a `BlockRematOverride`, the same per-block offload plan), the new `per_sample_pad_multiple=1` dataloader default from main, main's RoPE `scaling='none'` -> `scaling=None` refactor, the launcher's profiler settings, and the tokenizer path.

100-step runs on 64 GPUs vs the reference runs of the same precision:

| Recipe | Mean / max abs loss diff | Loss at step 100 (new / reference) |
| --- | --- | --- |
| BF16 | 0.0017 / 0.0057 | 6.92717 / 6.92149 |
| MXFP8, run 1 | 0.0034 / 0.0086 | 6.94351 / 6.95157 |
| MXFP8, run 2 | 0.00025 / 0.0012 | 6.95231 / 6.95157 |

The two MXFP8 runs of this recipe differ from each other by 0.0035, so the run 1 gap is run-to-run noise. Step 1 matches the references exactly, and step-1 and step-2 peak memory match to 0.01 GiB.

## Performance
64 GB300 GPUs (16 nodes x 4), 100 steps. tps and TFLOPs are per GPU as logged by torchtitan, mean of steps 71-90. These runs used the launcher-built reference config, which matches these recipes field by field (see Numerics), on an earlier revision of this stack and of activation offload (#6020). These runs used `max_num_documents=64`. #5882 raises it to 128, which removes the padding (10.7% of the tokens on C4) and lowers the reported tps, because tps counts padding tokens.

| Recipe | tps | TFLOPs |
| --- | ---: | ---: |
| `muse_spark_816b_a42b_dist_moe_mxfp8_spmd_64_benchmark` | 5,166 | 1,691 |
| `muse_spark_816b_a42b_dist_moe_bf16_spmd_64_benchmark` | 3,869 | 1,267 |

Forced balanced routing makes these benchmark numbers, not real-training numbers.

## Testing
- `pytest tests/unit_tests/cpu/recipes`: the new recipes build; the MLA override tests also pass when run alone.
- Config build of all four benchmark recipes, diffed field by field as above.
- FakePG, logical 64 GPUs, rank 0, 10 steps, both `_fake` recipes: MXFP8 step-2 peak 239.52 allocated / 252.68 reserved GiB, the same as an earlier FakePG run of this config. Activation offload moves 124.73 GiB (MXFP8) and 100.90 GiB (BF16) per forward, the same as the reference real runs.
- 64 GPUs, 100 steps, both precisions (MXFP8 twice): all ranks exit 0; numerics above.

## Known issues / follow-ups
- The numbers predate #6137 (activation reloads wait on FSDP2's copy-in stream). Its effect on these recipes is not measured.
- torchtitan does not check that a CP group sits in one NVLink domain.
- With FSDP symmetric memory and EP, `destroy_process_group` can hang after training. The recipe cannot skip it; the launcher must.
- `pytorch/pytorch#204942` is required: without it step 1 runs out of memory. This was measured with DP8/CP8, not rechecked with DP32/CP2.

stack-info: PR: #6252, branch: fegin/stack/45
fegin added a commit to pytorch/torchtitan that referenced this pull request Dec 1, 2026
…ctivation offload

## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why
     this approach, and what you checked yourself. -->

## Why
Our fastest Muse Spark 816B runs on 64 GPUs cannot be reproduced from the repo. They start from the 64-GPU recipe and change it in an out-of-tree launcher: layout, forced routing, Dist-MoE budgets, remat and offload policy, Adam moment placement, the optimizer CUDA graph, and FSDP symmetric memory. The launch environment and the dependency versions are not written down anywhere either.

The 64-GPU recipe also all-gathers the K/V of the full 32K sequence in every layer. The sliding-window varlen layers (46 of 62 layers, 2048-token window) read only the blocks inside their window, so most of that K/V is never used.

**Example.**

```text
before: muse_spark_816b_a42b_dist_moe_mxfp8_spmd_64, then the launcher sets
        DP32/CP2, forced routing, scratch 2, slot factor 0, remat p3,
        offload attention + MoE projections, moments on GPU, optimizer graph,
        FSDP symmetric memory, c4_test, 100 steps
after:  --module torchtitan_recipes.models.muse_spark \
        --config muse_spark_816b_a42b_dist_moe_mxfp8_spmd_64_benchmark
```

## What changed
- The Muse K/V-gather CP transform maps `SlidingWindowVarlenInnerAttention` to `SelectiveGatherKVSlidingWindowVarlenInnerAttention`. Global layers keep `AllGatherKVVarlenInnerAttention`. This applies to every 64-GPU recipe.
- The Muse save region becomes `attention.inner_attention*`, so the selective-gather assembly region nested in attention is saved with it. torch_remat rejects a recomputed region inside a saved one. The 256- and 512-GPU and UltraData recipes have no region nested in attention, so the wildcard does not change them.
- `_muse_spark_816b_dist_moe_spmd_64` takes `context_parallel_degree`; FSDP gets the other 64 / CP ranks. The existing 64-GPU recipes pass 8, as before.
- New `muse_spark_816b_a42b_dist_moe_{bf16,mxfp8}_spmd_64_benchmark` recipes and their `_fake` variants. They are benchmark only: forced balanced routing does not train a usable model.

| Setting | BF16 | MXFP8 |
| --- | --- | --- |
| layout | DP32, CP2, EP64, 2 microbatches per step | same |
| routing | forced balanced (round robin) | same |
| Dist-MoE | scratch_capacity_factor 2, activation_slot_capacity_factor 0 | same |
| remat save regions | Dist-MoE defaults + `attention.*` | + pooler, unpooler, router |
| activation offload | block input + `attention.*`, not in the last block | + pooler, unpooler, router |
| Adam moments | GPU (moment_cpu_offload_fraction 0.0) | same |
| CUDA graphs | per microbatch group + optimizer graph | same |
| FSDP symmetric memory | scope all (off in `_fake`) | same |
| data | c4_test, random init, 100 steps (10 in `_fake`) | same |

- The benchmark docstring lists the launch environment (`NCCL_NVLS_ENABLE=1`, `PYTORCH_ALLOC_CONF=pinned_max_round_threshold_mb:1`, one NVLink domain per CP group, skipping `destroy_process_group`) and the dependency versions.

## Dependencies
- PyTorch nightly from 2026-11-20 or later. Activation offload on main calls `FSDPModule.get_all_gather_copy_in_stream` (pytorch/pytorch#205180).
- Depends on meta-pytorch/attention-gym#651 (selective gather); the attention-gym pin bump lands separately.

## How to reproduce
Stage the Muse Spark Open tokenizer files at `./assets/hf/Muse-Spark-Open-816B-A42B`, then on each of 16 hosts (4 GPUs each, all in one NVLink domain):
```bash
NCCL_NVLS_ENABLE=1 PYTORCH_ALLOC_CONF=pinned_max_round_threshold_mb:1 \
  torchrun --nnodes 16 --nproc-per-node 4 --node-rank <i> \
  --master-addr <host 0> --master-port 29500 -m torchtitan.train \
  --module torchtitan_recipes.models.muse_spark \
  --config muse_spark_816b_a42b_dist_moe_mxfp8_spmd_64_benchmark
```
Use `..._bf16_spmd_64_benchmark` for BF16. Measure tps as the mean of steps 71-90.

## Numerics
No model or kernel change. Forced routing makes the loss meaningless for training quality; it is only a run-to-run check.

The benchmark recipes build the same effective config as the launcher-built reference runs, field by field, except: `offload_last_block=False` in the reference runs, which #6020 removed (the recipes keep the last block on GPU with a `BlockRematOverride`, the same per-block offload plan), the new `per_sample_pad_multiple=1` dataloader default from main, main's RoPE `scaling='none'` -> `scaling=None` refactor, the launcher's profiler settings, and the tokenizer path.

100-step runs on 64 GPUs vs the reference runs of the same precision:

| Recipe | Mean / max abs loss diff | Loss at step 100 (new / reference) |
| --- | --- | --- |
| BF16 | 0.0017 / 0.0057 | 6.92717 / 6.92149 |
| MXFP8, run 1 | 0.0034 / 0.0086 | 6.94351 / 6.95157 |
| MXFP8, run 2 | 0.00025 / 0.0012 | 6.95231 / 6.95157 |

The two MXFP8 runs of this recipe differ from each other by 0.0035, so the run 1 gap is run-to-run noise. Step 1 matches the references exactly, and step-1 and step-2 peak memory match to 0.01 GiB.

## Performance
64 GB300 GPUs (16 nodes x 4), 100 steps. tps and TFLOPs are per GPU as logged by torchtitan, mean of steps 71-90. These runs used the launcher-built reference config, which matches these recipes field by field (see Numerics), on an earlier revision of this stack and of activation offload (#6020). These runs used `max_num_documents=64`. #5882 raises it to 128, which removes the padding (10.7% of the tokens on C4) and lowers the reported tps, because tps counts padding tokens.

| Recipe | tps | TFLOPs |
| --- | ---: | ---: |
| `muse_spark_816b_a42b_dist_moe_mxfp8_spmd_64_benchmark` | 5,166 | 1,691 |
| `muse_spark_816b_a42b_dist_moe_bf16_spmd_64_benchmark` | 3,869 | 1,267 |

Forced balanced routing makes these benchmark numbers, not real-training numbers.

## Testing
- `pytest tests/unit_tests/cpu/recipes`: the new recipes build; the MLA override tests also pass when run alone.
- Config build of all four benchmark recipes, diffed field by field as above.
- FakePG, logical 64 GPUs, rank 0, 10 steps, both `_fake` recipes: MXFP8 step-2 peak 239.52 allocated / 252.68 reserved GiB, the same as an earlier FakePG run of this config. Activation offload moves 124.73 GiB (MXFP8) and 100.90 GiB (BF16) per forward, the same as the reference real runs.
- 64 GPUs, 100 steps, both precisions (MXFP8 twice): all ranks exit 0; numerics above.

## Known issues / follow-ups
- The numbers predate #6137 (activation reloads wait on FSDP2's copy-in stream). Its effect on these recipes is not measured.
- torchtitan does not check that a CP group sits in one NVLink domain.
- With FSDP symmetric memory and EP, `destroy_process_group` can hang after training. The recipe cannot skip it; the launcher must.
- `pytorch/pytorch#204942` is required: without it step 1 runs out of memory. This was measured with DP8/CP8, not rechecked with DP32/CP2.

stack-info: PR: #6252, branch: fegin/stack/45
fegin added a commit to pytorch/torchtitan that referenced this pull request Dec 1, 2026
…ctivation offload

## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why
     this approach, and what you checked yourself. -->

## Why
Our fastest Muse Spark 816B runs on 64 GPUs cannot be reproduced from the repo. They start from the 64-GPU recipe and change it in an out-of-tree launcher: layout, forced routing, Dist-MoE budgets, remat and offload policy, Adam moment placement, the optimizer CUDA graph, and FSDP symmetric memory. The launch environment and the dependency versions are not written down anywhere either.

The 64-GPU recipe also all-gathers the K/V of the full 32K sequence in every layer. The sliding-window varlen layers (46 of 62 layers, 2048-token window) read only the blocks inside their window, so most of that K/V is never used.

**Example.**

```text
before: muse_spark_816b_a42b_dist_moe_mxfp8_spmd_64, then the launcher sets
        DP32/CP2, forced routing, scratch 2, slot factor 0, remat p3,
        offload attention + MoE projections, moments on GPU, optimizer graph,
        FSDP symmetric memory, c4_test, 100 steps
after:  --module torchtitan_recipes.models.muse_spark \
        --config muse_spark_816b_a42b_dist_moe_mxfp8_spmd_64_benchmark
```

## What changed
- The Muse K/V-gather CP transform maps `SlidingWindowVarlenInnerAttention` to `SelectiveGatherKVSlidingWindowVarlenInnerAttention`. Global layers keep `AllGatherKVVarlenInnerAttention`. This applies to every 64-GPU recipe.
- The Muse save region becomes `attention.inner_attention*`, so the selective-gather assembly region nested in attention is saved with it. torch_remat rejects a recomputed region inside a saved one. The 256- and 512-GPU and UltraData recipes have no region nested in attention, so the wildcard does not change them.
- `_muse_spark_816b_dist_moe_spmd_64` takes `context_parallel_degree`; FSDP gets the other 64 / CP ranks. The existing 64-GPU recipes pass 8, as before.
- New `muse_spark_816b_a42b_dist_moe_{bf16,mxfp8}_spmd_64_benchmark` recipes and their `_fake` variants. They are benchmark only: forced balanced routing does not train a usable model.

| Setting | BF16 | MXFP8 |
| --- | --- | --- |
| layout | DP32, CP2, EP64, 2 microbatches per step | same |
| routing | forced balanced (round robin) | same |
| Dist-MoE | scratch_capacity_factor 2, activation_slot_capacity_factor 0 | same |
| remat save regions | Dist-MoE defaults + `attention.*` | + pooler, unpooler, router |
| activation offload | block input + `attention.*`, not in the last block | + pooler, unpooler, router |
| Adam moments | GPU (moment_cpu_offload_fraction 0.0) | same |
| CUDA graphs | per microbatch group + optimizer graph | same |
| FSDP symmetric memory | scope all (off in `_fake`) | same |
| data | c4_test, random init, 100 steps (10 in `_fake`) | same |

- The benchmark docstring lists the launch environment (`NCCL_NVLS_ENABLE=1`, `PYTORCH_ALLOC_CONF=pinned_max_round_threshold_mb:1`, one NVLink domain per CP group, skipping `destroy_process_group`) and the dependency versions.

## Dependencies
- PyTorch nightly from 2026-11-20 or later. Activation offload on main calls `FSDPModule.get_all_gather_copy_in_stream` (pytorch/pytorch#205180).
- Depends on meta-pytorch/attention-gym#651 (selective gather); the attention-gym pin bump lands separately.

## How to reproduce
Stage the Muse Spark Open tokenizer files at `./assets/hf/Muse-Spark-Open-816B-A42B`, then on each of 16 hosts (4 GPUs each, all in one NVLink domain):
```bash
NCCL_NVLS_ENABLE=1 PYTORCH_ALLOC_CONF=pinned_max_round_threshold_mb:1 \
  torchrun --nnodes 16 --nproc-per-node 4 --node-rank <i> \
  --master-addr <host 0> --master-port 29500 -m torchtitan.train \
  --module torchtitan_recipes.models.muse_spark \
  --config muse_spark_816b_a42b_dist_moe_mxfp8_spmd_64_benchmark
```
Use `..._bf16_spmd_64_benchmark` for BF16. Measure tps as the mean of steps 71-90.

## Numerics
No model or kernel change. Forced routing makes the loss meaningless for training quality; it is only a run-to-run check.

The benchmark recipes build the same effective config as the launcher-built reference runs, field by field, except: `offload_last_block=False` in the reference runs, which #6020 removed (the recipes keep the last block on GPU with a `BlockRematOverride`, the same per-block offload plan), the new `per_sample_pad_multiple=1` dataloader default from main, main's RoPE `scaling='none'` -> `scaling=None` refactor, the launcher's profiler settings, and the tokenizer path.

100-step runs on 64 GPUs vs the reference runs of the same precision:

| Recipe | Mean / max abs loss diff | Loss at step 100 (new / reference) |
| --- | --- | --- |
| BF16 | 0.0017 / 0.0057 | 6.92717 / 6.92149 |
| MXFP8, run 1 | 0.0034 / 0.0086 | 6.94351 / 6.95157 |
| MXFP8, run 2 | 0.00025 / 0.0012 | 6.95231 / 6.95157 |

The two MXFP8 runs of this recipe differ from each other by 0.0035, so the run 1 gap is run-to-run noise. Step 1 matches the references exactly, and step-1 and step-2 peak memory match to 0.01 GiB.

## Performance
64 GB300 GPUs (16 nodes x 4), 100 steps. tps and TFLOPs are per GPU as logged by torchtitan, mean of steps 71-90. These runs used the launcher-built reference config, which matches these recipes field by field (see Numerics), on an earlier revision of this stack and of activation offload (#6020). These runs used `max_num_documents=64`. #5882 raises it to 128, which removes the padding (10.7% of the tokens on C4) and lowers the reported tps, because tps counts padding tokens.

| Recipe | tps | TFLOPs |
| --- | ---: | ---: |
| `muse_spark_816b_a42b_dist_moe_mxfp8_spmd_64_benchmark` | 5,166 | 1,691 |
| `muse_spark_816b_a42b_dist_moe_bf16_spmd_64_benchmark` | 3,869 | 1,267 |

Forced balanced routing makes these benchmark numbers, not real-training numbers.

## Testing
- `pytest tests/unit_tests/cpu/recipes`: the new recipes build; the MLA override tests also pass when run alone.
- Config build of all four benchmark recipes, diffed field by field as above.
- FakePG, logical 64 GPUs, rank 0, 10 steps, both `_fake` recipes: MXFP8 step-2 peak 239.52 allocated / 252.68 reserved GiB, the same as an earlier FakePG run of this config. Activation offload moves 124.73 GiB (MXFP8) and 100.90 GiB (BF16) per forward, the same as the reference real runs.
- 64 GPUs, 100 steps, both precisions (MXFP8 twice): all ranks exit 0; numerics above.

## Known issues / follow-ups
- The numbers predate #6137 (activation reloads wait on FSDP2's copy-in stream). Its effect on these recipes is not measured.
- torchtitan does not check that a CP group sits in one NVLink domain.
- With FSDP symmetric memory and EP, `destroy_process_group` can hang after training. The recipe cannot skip it; the launcher must.
- `pytorch/pytorch#204942` is required: without it step 1 runs out of memory. This was measured with DP8/CP8, not rechecked with DP32/CP2.

stack-info: PR: #6252, branch: fegin/stack/45
fegin added a commit to pytorch/torchtitan that referenced this pull request Dec 2, 2026
…ctivation offload

## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why
     this approach, and what you checked yourself. -->

## Why
Our fastest Muse Spark 816B runs on 64 GPUs cannot be reproduced from the repo. They start from the 64-GPU recipe and change it in an out-of-tree launcher: layout, forced routing, Dist-MoE budgets, remat and offload policy, Adam moment placement, the optimizer CUDA graph, and FSDP symmetric memory. The launch environment and the dependency versions are not written down anywhere either.

The 64-GPU recipe also all-gathers the K/V of the full 32K sequence in every layer. The sliding-window varlen layers (46 of 62 layers, 2048-token window) read only the blocks inside their window, so most of that K/V is never used.

**Example.**

```text
before: muse_spark_816b_a42b_dist_moe_mxfp8_spmd_64, then the launcher sets
        DP32/CP2, forced routing, scratch 2, slot factor 0, remat p3,
        offload attention + MoE projections, moments on GPU, optimizer graph,
        FSDP symmetric memory, c4_test, 100 steps
after:  --module torchtitan_recipes.models.muse_spark \
        --config muse_spark_816b_a42b_dist_moe_mxfp8_spmd_64_benchmark
```

## What changed
- The Muse K/V-gather CP transform maps `SlidingWindowVarlenInnerAttention` to `SelectiveGatherKVSlidingWindowVarlenInnerAttention`. Global layers keep `AllGatherKVVarlenInnerAttention`. This applies to every 64-GPU recipe.
- The Muse save region becomes `attention.inner_attention*`, so the selective-gather assembly region nested in attention is saved with it. torch_remat rejects a recomputed region inside a saved one. The 256- and 512-GPU and UltraData recipes have no region nested in attention, so the wildcard does not change them.
- `_muse_spark_816b_dist_moe_spmd_64` takes `context_parallel_degree`; FSDP gets the other 64 / CP ranks. The existing 64-GPU recipes pass 8, as before.
- New `muse_spark_816b_a42b_dist_moe_{bf16,mxfp8}_spmd_64_benchmark` recipes and their `_fake` variants. They are benchmark only: forced balanced routing does not train a usable model.

| Setting | BF16 | MXFP8 |
| --- | --- | --- |
| layout | DP32, CP2, EP64, 2 microbatches per step | same |
| routing | forced balanced (round robin) | same |
| Dist-MoE | scratch_capacity_factor 2, activation_slot_capacity_factor 0 | same |
| remat save regions | Dist-MoE defaults + `attention.*` | + pooler, unpooler, router |
| activation offload | block input + `attention.*`, not in the last block | + pooler, unpooler, router |
| Adam moments | GPU (moment_cpu_offload_fraction 0.0) | same |
| CUDA graphs | per microbatch group + optimizer graph | same |
| FSDP symmetric memory | scope all (off in `_fake`) | same |
| data | c4_test, random init, 100 steps (10 in `_fake`) | same |

- The benchmark docstring lists the launch environment (`NCCL_NVLS_ENABLE=1`, `PYTORCH_ALLOC_CONF=pinned_max_round_threshold_mb:1`, one NVLink domain per CP group, skipping `destroy_process_group`) and the dependency versions.

## Dependencies
- PyTorch nightly from 2026-11-20 or later. Activation offload on main calls `FSDPModule.get_all_gather_copy_in_stream` (pytorch/pytorch#205180).
- Depends on meta-pytorch/attention-gym#651 (selective gather); the attention-gym pin bump lands separately.

## How to reproduce
Stage the Muse Spark Open tokenizer files at `./assets/hf/Muse-Spark-Open-816B-A42B`, then on each of 16 hosts (4 GPUs each, all in one NVLink domain):
```bash
NCCL_NVLS_ENABLE=1 PYTORCH_ALLOC_CONF=pinned_max_round_threshold_mb:1 \
  torchrun --nnodes 16 --nproc-per-node 4 --node-rank <i> \
  --master-addr <host 0> --master-port 29500 -m torchtitan.train \
  --module torchtitan_recipes.models.muse_spark \
  --config muse_spark_816b_a42b_dist_moe_mxfp8_spmd_64_benchmark
```
Use `..._bf16_spmd_64_benchmark` for BF16. Measure tps as the mean of steps 71-90.

## Numerics
No model or kernel change. Forced routing makes the loss meaningless for training quality; it is only a run-to-run check.

The benchmark recipes build the same effective config as the launcher-built reference runs, field by field, except: `offload_last_block=False` in the reference runs, which #6020 removed (the recipes keep the last block on GPU with a `BlockRematOverride`, the same per-block offload plan), the new `per_sample_pad_multiple=1` dataloader default from main, main's RoPE `scaling='none'` -> `scaling=None` refactor, the launcher's profiler settings, and the tokenizer path.

100-step runs on 64 GPUs vs the reference runs of the same precision:

| Recipe | Mean / max abs loss diff | Loss at step 100 (new / reference) |
| --- | --- | --- |
| BF16 | 0.0017 / 0.0057 | 6.92717 / 6.92149 |
| MXFP8, run 1 | 0.0034 / 0.0086 | 6.94351 / 6.95157 |
| MXFP8, run 2 | 0.00025 / 0.0012 | 6.95231 / 6.95157 |

The two MXFP8 runs of this recipe differ from each other by 0.0035, so the run 1 gap is run-to-run noise. Step 1 matches the references exactly, and step-1 and step-2 peak memory match to 0.01 GiB.

## Performance
64 GB300 GPUs (16 nodes x 4), 100 steps. tps and TFLOPs are per GPU as logged by torchtitan, mean of steps 71-90. These runs used the launcher-built reference config, which matches these recipes field by field (see Numerics), on an earlier revision of this stack and of activation offload (#6020). These runs used `max_num_documents=64`. #5882 raises it to 128, which removes the padding (10.7% of the tokens on C4) and lowers the reported tps, because tps counts padding tokens.

| Recipe | tps | TFLOPs |
| --- | ---: | ---: |
| `muse_spark_816b_a42b_dist_moe_mxfp8_spmd_64_benchmark` | 5,166 | 1,691 |
| `muse_spark_816b_a42b_dist_moe_bf16_spmd_64_benchmark` | 3,869 | 1,267 |

Forced balanced routing makes these benchmark numbers, not real-training numbers.

## Testing
- `pytest tests/unit_tests/cpu/recipes`: the new recipes build; the MLA override tests also pass when run alone.
- Config build of all four benchmark recipes, diffed field by field as above.
- FakePG, logical 64 GPUs, rank 0, 10 steps, both `_fake` recipes: MXFP8 step-2 peak 239.52 allocated / 252.68 reserved GiB, the same as an earlier FakePG run of this config. Activation offload moves 124.73 GiB (MXFP8) and 100.90 GiB (BF16) per forward, the same as the reference real runs.
- 64 GPUs, 100 steps, both precisions (MXFP8 twice): all ranks exit 0; numerics above.

## Known issues / follow-ups
- The numbers predate #6137 (activation reloads wait on FSDP2's copy-in stream). Its effect on these recipes is not measured.
- torchtitan does not check that a CP group sits in one NVLink domain.
- With FSDP symmetric memory and EP, `destroy_process_group` can hang after training. The recipe cannot skip it; the launcher must.
- `pytorch/pytorch#204942` is required: without it step 1 runs out of memory. This was measured with DP8/CP8, not rechecked with DP32/CP2.

stack-info: PR: #6252, branch: fegin/stack/45
fegin added a commit to pytorch/torchtitan that referenced this pull request Dec 2, 2026
…ctivation offload

## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why
     this approach, and what you checked yourself. -->

## Why
Our fastest Muse Spark 816B runs on 64 GPUs cannot be reproduced from the repo. They start from the 64-GPU recipe and change it in an out-of-tree launcher: layout, forced routing, Dist-MoE budgets, remat and offload policy, Adam moment placement, the optimizer CUDA graph, and FSDP symmetric memory. The launch environment and the dependency versions are not written down anywhere either.

The 64-GPU recipe also all-gathers the K/V of the full 32K sequence in every layer. The sliding-window varlen layers (46 of 62 layers, 2048-token window) read only the blocks inside their window, so most of that K/V is never used.

**Example.**

```text
before: muse_spark_816b_a42b_dist_moe_mxfp8_spmd_64, then the launcher sets
        DP32/CP2, forced routing, scratch 2, slot factor 0, remat p3,
        offload attention + MoE projections, moments on GPU, optimizer graph,
        FSDP symmetric memory, c4_test, 100 steps
after:  --module torchtitan_recipes.models.muse_spark \
        --config muse_spark_816b_a42b_dist_moe_mxfp8_spmd_64_benchmark
```

## What changed
- The Muse K/V-gather CP transform maps `SlidingWindowVarlenInnerAttention` to `SelectiveGatherKVSlidingWindowVarlenInnerAttention`. Global layers keep `AllGatherKVVarlenInnerAttention`. This applies to every 64-GPU recipe.
- The Muse save region becomes `attention.inner_attention*`, so the selective-gather assembly region nested in attention is saved with it. torch_remat rejects a recomputed region inside a saved one. The 256- and 512-GPU and UltraData recipes have no region nested in attention, so the wildcard does not change them.
- `_muse_spark_816b_dist_moe_spmd_64` takes `context_parallel_degree`; FSDP gets the other 64 / CP ranks. The existing 64-GPU recipes pass 8, as before.
- New `muse_spark_816b_a42b_dist_moe_{bf16,mxfp8}_spmd_64_benchmark` recipes and their `_fake` variants. They are benchmark only: forced balanced routing does not train a usable model.

| Setting | BF16 | MXFP8 |
| --- | --- | --- |
| layout | DP32, CP2, EP64, 2 microbatches per step | same |
| routing | forced balanced (round robin) | same |
| Dist-MoE | scratch_capacity_factor 2, activation_slot_capacity_factor 0 | same |
| remat save regions | Dist-MoE defaults + `attention.*` | + pooler, unpooler, router |
| activation offload | block input + `attention.*`, not in the last block | + pooler, unpooler, router |
| Adam moments | GPU (moment_cpu_offload_fraction 0.0) | same |
| CUDA graphs | per microbatch group + optimizer graph | same |
| FSDP symmetric memory | scope all (off in `_fake`) | same |
| data | c4_test, random init, 100 steps (10 in `_fake`) | same |

- The benchmark docstring lists the launch environment (`NCCL_NVLS_ENABLE=1`, `PYTORCH_ALLOC_CONF=pinned_max_round_threshold_mb:1`, one NVLink domain per CP group, skipping `destroy_process_group`) and the dependency versions.

## Dependencies
- PyTorch nightly from 2026-11-20 or later. Activation offload on main calls `FSDPModule.get_all_gather_copy_in_stream` (pytorch/pytorch#205180).
- Depends on meta-pytorch/attention-gym#651 (selective gather); the attention-gym pin bump lands separately.

## How to reproduce
Stage the Muse Spark Open tokenizer files at `./assets/hf/Muse-Spark-Open-816B-A42B`, then on each of 16 hosts (4 GPUs each, all in one NVLink domain):
```bash
NCCL_NVLS_ENABLE=1 PYTORCH_ALLOC_CONF=pinned_max_round_threshold_mb:1 \
  torchrun --nnodes 16 --nproc-per-node 4 --node-rank <i> \
  --master-addr <host 0> --master-port 29500 -m torchtitan.train \
  --module torchtitan_recipes.models.muse_spark \
  --config muse_spark_816b_a42b_dist_moe_mxfp8_spmd_64_benchmark
```
Use `..._bf16_spmd_64_benchmark` for BF16. Measure tps as the mean of steps 71-90.

## Numerics
No model or kernel change. Forced routing makes the loss meaningless for training quality; it is only a run-to-run check.

The benchmark recipes build the same effective config as the launcher-built reference runs, field by field, except: `offload_last_block=False` in the reference runs, which #6020 removed (the recipes keep the last block on GPU with a `BlockRematOverride`, the same per-block offload plan), the new `per_sample_pad_multiple=1` dataloader default from main, main's RoPE `scaling='none'` -> `scaling=None` refactor, the launcher's profiler settings, and the tokenizer path.

100-step runs on 64 GPUs vs the reference runs of the same precision:

| Recipe | Mean / max abs loss diff | Loss at step 100 (new / reference) |
| --- | --- | --- |
| BF16 | 0.0017 / 0.0057 | 6.92717 / 6.92149 |
| MXFP8, run 1 | 0.0034 / 0.0086 | 6.94351 / 6.95157 |
| MXFP8, run 2 | 0.00025 / 0.0012 | 6.95231 / 6.95157 |

The two MXFP8 runs of this recipe differ from each other by 0.0035, so the run 1 gap is run-to-run noise. Step 1 matches the references exactly, and step-1 and step-2 peak memory match to 0.01 GiB.

## Performance
64 GB300 GPUs (16 nodes x 4), 100 steps. tps and TFLOPs are per GPU as logged by torchtitan, mean of steps 71-90. These runs used the launcher-built reference config, which matches these recipes field by field (see Numerics), on an earlier revision of this stack and of activation offload (#6020). These runs used `max_num_documents=64`. #5882 raises it to 128, which removes the padding (10.7% of the tokens on C4) and lowers the reported tps, because tps counts padding tokens.

| Recipe | tps | TFLOPs |
| --- | ---: | ---: |
| `muse_spark_816b_a42b_dist_moe_mxfp8_spmd_64_benchmark` | 5,166 | 1,691 |
| `muse_spark_816b_a42b_dist_moe_bf16_spmd_64_benchmark` | 3,869 | 1,267 |

Forced balanced routing makes these benchmark numbers, not real-training numbers.

## Testing
- `pytest tests/unit_tests/cpu/recipes`: the new recipes build; the MLA override tests also pass when run alone.
- Config build of all four benchmark recipes, diffed field by field as above.
- FakePG, logical 64 GPUs, rank 0, 10 steps, both `_fake` recipes: MXFP8 step-2 peak 239.52 allocated / 252.68 reserved GiB, the same as an earlier FakePG run of this config. Activation offload moves 124.73 GiB (MXFP8) and 100.90 GiB (BF16) per forward, the same as the reference real runs.
- 64 GPUs, 100 steps, both precisions (MXFP8 twice): all ranks exit 0; numerics above.

## Known issues / follow-ups
- The numbers predate #6137 (activation reloads wait on FSDP2's copy-in stream). Its effect on these recipes is not measured.
- torchtitan does not check that a CP group sits in one NVLink domain.
- With FSDP symmetric memory and EP, `destroy_process_group` can hang after training. The recipe cannot skip it; the launcher must.
- `pytorch/pytorch#204942` is required: without it step 1 runs out of memory. This was measured with DP8/CP8, not rechecked with DP32/CP2.

stack-info: PR: #6252, branch: fegin/stack/45
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests ciflow/trunk Trigger trunk jobs on your pull request GL/human GreenLight marked as needing human review in progress PR is being worked on by the author, until the automated review accepts it Merged release notes: distributed (fsdp) release notes category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants