Skip to content

Schedule-driven activation offload for pipeline stages - #6022

Draft
anijain2305 wants to merge 2 commits into
activation-offloadfrom
activation-offload-pp
Draft

anijain2305 wants to merge 2 commits into
activation-offloadfrom
activation-offload-pp

Conversation

@anijain2305

@anijain2305 anijain2305 commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Summary (human-written)

Why

Under PP, every stage's last block is caught between its forward and its
backward: the forward leaves the stage right after it, and its backward
starts as soon as the gradient arrives from the next stage. The base PR keeps
those blocks on GPU (offload_last_block=False), which costs one block of activations
per microbatch in flight on every stage. The schedule knows when each stage
is idle, so it can own the stage boundary the way it drives FSDP's
UNSHARD/RESHARD actions.

Example. One stage under 1F1B; the schedule calls the offloader around
its existing actions, naming the microbatch each action carries:

set_microbatch(0); F(mb0)
F(mb1) ...                 then wait_offload(0)      # mb0's last group freed
reload_backward(0)         # mb0's last group H2D, ahead of its backward
B(mb0)

What changed

  • ActivationOffloader.defer_to_schedule() hands the timing of each
    microbatch's last group to the schedule. State lives in
    _PipelineScheduleState, keyed by microbatch index; the non-PP path never
    touches it.
  • set_microbatch(i) tags the stage's next forward. A forward the schedule
    does not tag (e.g. a stage's metadata inference) behaves as without a
    schedule.
  • wait_offload(i) frees microbatch i's last group, called after an action
    following its forward so the copies had that action's compute to finish.
  • reload_backward(i, num_groups=1) queues the reload of microbatch i's
    last num_groups groups ahead of its backward. Inside the stage, gradient
    hooks still prefetch one block ahead, and the model part's output keeps its
    reload trigger as a fallback.
  • The microbatch index is the one PyTorch's schedule actions already carry
    (_Action.microbatch_index), so nothing assumes a particular schedule or
    backward order.
  • ACTIVATION_OFFLOAD.md: the PP section documents the calls.

Testing

tests/unit_tests/gpu/distributed/test_activation_offload.py, 4 new tests
that play a stage's actions with these calls: 1F1B order offloads every block
with no on-demand reloads and grads equal to no offload; backwards out of
forward order (F0 F1 F2 B2 B0 B1) still reload the right microbatch;
wait_offload(i) frees only microbatch i's last group;
reload_backward(i, num_groups=all) reloads the whole stage. PP2 1F1B /
Interleaved1F1B / ZBVZeroBubble end to end stay bitwise equal to no offload
(the schedule does not call the API yet, so this covers the unchanged default
path).

Known issues / follow-ups

  • Nothing in torchtitan calls these methods yet: the PyTorch pipeline
    schedule actions that would call them come separately.

Stacked on #6020.

Conflicts:

tests/unit_tests/gpu/distributed/test_activation_offload.py

Please enter the commit message for your changes. Lines starting

with '#' will be kept; you may remove them yourself if you want to.

An empty message aborts the commit.

interactive rebase in progress; onto 23f96aaa1

Last command done (1 command done):

pick 2006f2c # Schedule-driven activation offload for pipeline stages

No commands remaining.

You are currently rebasing branch 'activation-offload-pp' on '23f96aaa1'.

Changes to be committed:

modified: tests/unit_tests/gpu/distributed/test_activation_offload.py

modified: torchtitan/distributed/ACTIVATION_OFFLOAD.md

modified: torchtitan/distributed/activation_offload.py

Untracked files:

torchtitan_recipes/numa_recipes.py

torchtitan_recipes/offload_8b.py

torchtitan_recipes/offload_recipes.py

Conflicts:

tests/unit_tests/gpu/distributed/test_activation_offload.py

Please enter the commit message for your changes. Lines starting

with '#' will be kept; you may remove them yourself if you want to.

An empty message aborts the commit.

interactive rebase in progress; onto 2d1c51a8a

Last command done (1 command done):

pick 662a13c3b # Schedule-driven activation offload for pipeline stages

No commands remaining.

You are currently rebasing branch 'activation-offload-pp' on '2d1c51a8a'.

Changes to be committed:

modified: tests/unit_tests/gpu/distributed/test_activation_offload.py

modified: torchtitan/distributed/ACTIVATION_OFFLOAD.md

modified: torchtitan/distributed/activation_offload.py

Untracked files:

torchtitan_recipes/numa_recipes.py

torchtitan_recipes/offload_8b.py

torchtitan_recipes/offload_recipes.py

Conflicts:

torchtitan/distributed/activation_offload.py

Please enter the commit message for your changes. Lines starting

with '#' will be kept; you may remove them yourself if you want to.

An empty message aborts the commit.

interactive rebase in progress; onto b3551edb1

Last command done (1 command done):

pick 13b1ae8 # Schedule-driven activation offload for pipeline stages

No commands remaining.

You are currently rebasing branch 'activation-offload-pp' on 'b3551edb1'.

Changes to be committed:

modified: tests/unit_tests/gpu/distributed/test_activation_offload.py

modified: torchtitan/distributed/ACTIVATION_OFFLOAD.md

modified: torchtitan/distributed/activation_offload.py

Untracked files:

torchtitan_recipes/numa_recipes.py

torchtitan_recipes/offload_8b.py

torchtitan_recipes/offload_recipes.py

Conflicts:

torchtitan/distributed/activation_offload.py

Please enter the commit message for your changes. Lines starting

with '#' will be kept; you may remove them yourself if you want to.

An empty message aborts the commit.

interactive rebase in progress; onto c440a5c

Last command done (1 command done):

pick b9286a0 # Schedule-driven activation offload for pipeline stages

No commands remaining.

You are currently rebasing branch 'activation-offload-pp' on 'c440a5ceb'.

Changes to be committed:

modified: tests/unit_tests/gpu/distributed/test_activation_offload.py

modified: torchtitan/distributed/ACTIVATION_OFFLOAD.md

modified: torchtitan/distributed/activation_offload.py

Untracked files:

torchtitan_recipes/numa_recipes.py

torchtitan_recipes/offload_8b.py

torchtitan_recipes/offload_recipes.py

@anijain2305
anijain2305 added this pull request to stack #6023 November 11, 2026 00:33
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 11, 2026
@anijain2305
anijain2305 force-pushed the activation-offload-pp branch from 676cbc5 to aef65c3 Compare November 11, 2026 00:42
@anijain2305
anijain2305 force-pushed the activation-offload-pp branch 2 times, most recently from 7c44914 to ced03e5 Compare November 11, 2026 00:50
@anijain2305
anijain2305 force-pushed the activation-offload-pp branch 2 times, most recently from 54b086f to 2006f2c Compare November 11, 2026 02:30
@anijain2305
anijain2305 force-pushed the activation-offload-pp branch from 2006f2c to 13b1ae8 Compare November 11, 2026 20:24
@anijain2305
anijain2305 force-pushed the activation-offload-pp branch from 13b1ae8 to b9286a0 Compare November 15, 2026 21:08
@anijain2305
anijain2305 removed this pull request from stack #6023 November 15, 2026 21:11
@anijain2305
anijain2305 added this pull request to stack #6105 November 15, 2026 21:11
@anijain2305
anijain2305 force-pushed the activation-offload-pp branch from b9286a0 to 98c4f16 Compare November 15, 2026 22:17
@anijain2305
anijain2305 force-pushed the activation-offload-pp branch from 98c4f16 to d67acce Compare November 16, 2026 03:53
@anijain2305
anijain2305 force-pushed the activation-offload-pp branch from d67acce to 0138dd8 Compare November 16, 2026 03:59
@anijain2305
anijain2305 force-pushed the activation-offload-pp branch from 0138dd8 to c19b21b Compare November 16, 2026 06:17
@anijain2305
anijain2305 force-pushed the activation-offload-pp branch from c19b21b to 2d5194f Compare November 16, 2026 07:34
@anijain2305
anijain2305 force-pushed the activation-offload-pp branch from 2d5194f to f5d16a4 Compare November 16, 2026 07:56
@anijain2305
anijain2305 force-pushed the activation-offload-pp branch from f5d16a4 to 5cd5ba9 Compare November 16, 2026 20:23
@anijain2305
anijain2305 force-pushed the activation-offload-pp branch from 0a96b46 to 2283ad0 Compare November 18, 2026 21:38
@anijain2305
anijain2305 removed this pull request from stack #6105 November 18, 2026 21:38
anijain2305 added a commit 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
anijain2305 force-pushed the activation-offload-pp branch from 2283ad0 to 934e832 Compare November 19, 2026 00:12
anijain2305 added a commit 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
anijain2305 force-pushed the activation-offload-pp branch from 934e832 to 489ba67 Compare November 19, 2026 00:49
anijain2305 added a commit 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
anijain2305 force-pushed the activation-offload-pp branch from 489ba67 to 35d73f0 Compare November 19, 2026 01:17
## Summary (human-written)

This PR introduces activation offloading API. The design doc is in torchtitan/distributed/ACTIVATION_OFFLOAD.md.

tldr is
* activation offloadin works with and without remat. For both, we use the same pack/unpack hooks.
* users can choose among block inputs, tensors outputs in remat regions, and tensors saved for backward for offloading. This gives users many perf-memory tradeoff points.
* Both offload and reload have one layer full of compute to overlap with.
* For PP, there are natural actions that PP runtime IR can take to overlap the offload and reload with other microbatches on the same rank.

## Why

Remat is the only way to trade time for activation memory today. When a
model does not fit even with the remat policy you want (e.g. Muse Spark 816B
LoRA on 8 GB300: 253 GiB of 276 GiB), the only option is to recompute more.
Offloading what remat keeps to CPU DRAM is the other side of that trade.

**Example.** Offloading is part of the remat policy, which chooses, for each
region it retains, GPU or CPU:
```python
config.activation_remat = ActivationRematConfig(
    save_regions=["*"],               # retain every region: only cheap code is recomputed
    offload_block_input=True,         # each block's input goes to CPU
    offload_regions=["attention.*"],  # and what these regions retain
)
```

## What changed

- `ActivationRematConfig.offload_block_input` / `offload_regions` (default
  off): which retained tensors go to CPU. They are also `BlockRematOverride`
  fields (per-block policies, #6104), so offloading can differ per block; the
  fixed presets accept them, also in overrides that set nothing else.
  `offload_last_block` (default off) also offloads each model part's last
  block.
- `ActivationRematConfig.apply` checkpoints the blocks and, when the policy
  offloads anything, installs an `ActivationOffloader` on the model part and
  returns it (nothing in this PR uses it but tests; the PP schedule in #6022
  will).
  There is no module-level registry and no separate
  offload config. `apply` runs inside `parallelize`, before `fully_shard`;
  FSDP2's pre-forward is prepended, so it still runs before the offloader's.
- `apply`'s `saved_tensors_hooks` argument is removed: it existed for custom
  offloading, which this PR supersedes, and had no production caller.
- `torchtitan/distributed/activation_offload.py` (new): `ActivationOffloader`.
  Per transformer block it installs
  `torch_remat.saved_tensors_hooks`; `pack` copies selected storages D2H on a
  side stream, the GPU copies are freed at the end of the next block's
  forward, and a pre-hook on the autograd node of block i+1's output reloads
  block i on a reload stream (autograd runs it after FSDP2's pre-backward
  tensor hook, so the reload queues behind FSDP2's all-gather copy-out).
  Pinned host buffers come from a pool, so whole-step CUDA graphs work; it
  reuses buffers by power-of-two capacity, so saves whose size changes every
  step (tokens routed to an EP rank) do not grow pinned memory. Storages
  under 1 MiB, tensor subclasses, and parameter data stay on GPU, including
  the inner tensors of subclass parameters (the MXFP8 qdata and scales that
  MXFP8 Dist-MoE saves, which FSDP2 frees at reshard while a copy could
  still read them); a storage freed by something else before the free point
  raises. Autograd skips its in-place check for saves that
  hooks pack, so the offloader records each save's version and raises
  autograd's error at unpack if it changed. A tensor no reload trigger
  reloaded (its block's output got no gradient) raises at unpack.
  Under PP each stage has its own offloader; by default
  (`offload_last_block=False`) each stage's last block stays on GPU, which
  takes precedence over the base offload fields (an override offloading it
  raises, since under PP which block is last depends on the stage split).
  Offloading requires CUDA: `apply` raises on other accelerators.
  Encoder blocks cannot be offloaded: `apply` raises if the policy
  offloads one.
- GraphTrainer rejects a remat policy that offloads (its traced step does not
  run the eager hooks).
- Docs: `torchtitan/distributed/ACTIVATION_OFFLOAD.md`, timeline SVG, README links.

## Alternatives considered

- A hook inside FSDP2: offload must understand torch_remat (saved vs.
  recomputed, region names), which does not belong in pytorch/pytorch.
- Groups finer than a block: no backward savings under block remat, and the
  block input would be missed.
- Offload without remat: the closest setting is remat retaining every region
  and offloading some, which recomputes only the cheap code outside regions.
  Requiring remat makes the remat policy the one place that decides, per
  region, recompute, keep on GPU, or offload.

## Design notes

**Backward trigger: an autograd node pre-hook.** Group i is reloaded from a
pre-hook on the autograd node of block i+1's output, which fires before that
block's backward, one block ahead of the reload's consumer.
- Not a module backward pre-hook: it wraps the block's outputs in a custom
  autograd Function, so an in-place update of an output (`out += x`) raises,
  and it fires before FSDP2's pre-backward.
- Not a plain tensor hook: FSDP2's pre-backward is itself a tensor hook on
  the same output (`t.register_hook`), and tensor hooks fire in registration
  order, so the order would depend on whether offload was applied before or
  after `fully_shard`. Autograd runs every tensor hook of a node before any
  of its node pre-hooks, so the reload is always issued after FSDP2's
  pre-backward, whatever the registration order.
- Why the order matters: FSDP2's pre-backward runs the all-gather copy-out on
  the compute stream, and `split_with_sizes_copy` first copies a few KB of
  kernel metadata host-to-device. In #467 the reload was
  issued first and, on H100, that small copy queued behind the whole reload
  in the copy engine, stalling a block that does not read the reloaded
  activations (about -25% throughput). Issued after it, the reload waits on
  the compute stream (a GPU-side `wait_stream`), so it cannot start before
  that copy. GB300's copy engines do not serialize these copies (measured:
  0.07 ms with a 1 GiB copy in flight vs 0.04 ms idle), but the order holds
  on any hardware.

**FSDP2 CPU parameter offload.** It is the one FSDP2 traffic that shares the
CPU-GPU link with offloading (intra-node all-gather and reduce-scatter run
over NVLink; measured -1 to -2% with offload copies running). In block i's
backward, FSDP2 prefetches block i-1's parameter shards host-to-device while
the offloader reloads block i-1's activations, in the same direction, and
block i+1's gradient shards go device-to-host. The two host-to-device copies
are not ordered by default. When they do not fit in block i's backward,
parameters first would be better, since block i-1's parameters still need the
all-gather after their copy and its activations need nothing more. Under
`set_unshard_in_current_stream` or with a single rank, FSDP2 issues the
parameter copies on the compute stream, so reloads already follow them. A
follow-up makes the reload stream also wait on FSDP2's
`all_gather_copy_in_stream` (TODO in the code), which needs FSDP2 to expose
that stream.

**Pinned host memory.** Needed for the copies to be asynchronous at all, not
only for CUDA graphs. A `non_blocking` copy to or from pageable memory
returns only after the data has moved: on GB300, 1 GiB blocks the CPU for
5.3 ms pageable vs 0.16 ms pinned (bandwidth is the same, about 200 GB/s,
and the GPU still overlaps it with compute). At 15-23 GB offloaded per
forward that is 75-110 ms of blocked CPU per step, during which the CPU
cannot run ahead of the GPU, and CUDA graph capture rejects pageable copies.
The offloader's own buffer pool, rather than allocating per copy, is what
CUDA graphs need: the caching host allocator never reuses a block allocated
during capture.

**Two copy streams.** One per direction: the link is full duplex (one GPU:
about 143 GB/s each way concurrently vs 205 GB/s one way), so one
microbatch's offload and another's reload can run at once, and a reload
never queues behind a pending offload.

## Numerics

Offload moves tensors and copies them back unchanged. Loss and grad_norm are
bitwise equal with vs. without offload (seed 42, deterministic, flex attention,
10 steps, `scripts/loss_compare.py`):

| Model | Layouts |
| --- | --- |
| llama3 debugmodel | 1 GPU full / selective remat; PP2 1F1B, Interleaved1F1B, ZBV; CUDA graphs |
| DeepSeek-V3 debug + BF16 Dist-MoE | selective, full, EP 2, LoRA + EP 2, EP 4 |
| Muse Spark debug | TP/SP (dp2 x tp2 x ep2), LoRA selective / full, Dist-MoE, Dist-MoE + LoRA |

## Performance

llama3 8B, FSDP 4 x GB300, 8K tokens/rank, whole-step CUDA graph, NUMA-bound, 30 steps:

| Config | Peak mem | Offloaded / fwd | TPS (median) |
| --- | --- | --- | --- |
| selective remat | 60.82 GiB | - | 18,952 |
| + block input + attention.* | 52.43 GiB | 8.75 GiB | 18,977 |
| + block input + w13 | 45.62 GiB | 15.50 GiB | 17,265 |
| + all saved regions | 38.72 GiB | 22.3 GiB | 13,400 |

Muse Spark 816B SLAKE LoRA, 8 x GB300 (dp_shard 8 x EP 8, 4K), NUMA-bound:
no offload 252.84 GiB / 1,868 TPS; block input 245.44 GiB (-1.0%); block
input + attention.* 241.77 GiB (-1.8%); everything 238.57 GiB (-3.9%).
Dist-MoE's own activation buffers (28.95 GiB/rank) are not autograd saves and
are not reachable.

## Testing

`tests/unit_tests/gpu/distributed/test_activation_offload.py`: 23 tests, all
pass on GB300 (22 on 1 GPU, 1 FSDP CPU-offload test on 2 GPUs, with offload
installed before `fully_shard` as in `parallelize`). They check outputs and
grads equal to the same remat policy without offload; only the selected saves
move; per-block offload overrides; an override offloading the last block raises;
`offload_last_block`; one
transfer per storage across views; parameters never offloaded, nor the
FSDP2-managed operands of a tensor-subclass weight format (as MXFP8); tensor
subclass saves stay on GPU; a storage freed elsewhere before the free point
raises; forward frees
and backward releases the GPU copies; unpack without a reload raises; CUDA
graph replay equal to eager with shared host buffers; step-varying sizes
reuse host buffers; reloads queue after later-registered output hooks;
in-place updates of saves are detected; bitwise with FSDP2 CPU parameter
offload.
`test_activation_checkpoint.py`: offloading an encoder block, or on a
non-CUDA accelerator, raises.
The 2-GPU test is marked `multi_gpu` so the multi-GPU CI lane runs it.
Integration: the PP2 ZBV entry (`pp_zbv`) offloads block inputs
(`offload_last_block=True`, since each stage holds one or two blocks),
covering ZBV's split input/weight backward; loss and grad_norm match the
run without offload for 10 steps.

## Known issues / follow-ups

- Schedule-driven offload of each stage's last block under PP: the offloader
  API is a follow-up, #6022; the PyTorch schedule actions that call it
  come separately.
- Dist-MoE-side offload of its activation buffers.
- Loading FSDP2 CPU parameter offload's host-to-device shard copies before
  activation reloads in FSDP2's default mode (see Design notes): the reload
  stream also waits on FSDP2's `all_gather_copy_in_stream`, which needs FSDP2
  to expose it.
## 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

Under PP, every stage's last block is caught between its forward and its
backward: the forward leaves the stage right after it, and its backward
starts as soon as the gradient arrives from the next stage. The base PR keeps
those blocks on GPU (`offload_last_block=False`), which costs one block of activations
per microbatch in flight on every stage. The schedule knows when each stage
is idle, so it can own the stage boundary the way it drives FSDP's
UNSHARD/RESHARD actions.

**Example.** One stage under 1F1B; the schedule calls the offloader around
its existing actions, naming the microbatch each action carries:

```
set_microbatch(0); F(mb0)
F(mb1) ...                 then wait_offload(0)      # mb0's last group freed
reload_backward(0)         # mb0's last group H2D, ahead of its backward
B(mb0)
```

## What changed

- `ActivationOffloader.defer_to_schedule()` hands the timing of each
  microbatch's last group to the schedule. State lives in
  `_PipelineScheduleState`, keyed by microbatch index; the non-PP path never
  touches it.
- `set_microbatch(i)` tags the stage's next forward. A forward the schedule
  does not tag (e.g. a stage's metadata inference) behaves as without a
  schedule.
- `wait_offload(i)` frees microbatch `i`'s last group, called after an action
  following its forward so the copies had that action's compute to finish.
- `reload_backward(i, num_groups=1)` queues the reload of microbatch `i`'s
  last `num_groups` groups ahead of its backward. Inside the stage, gradient
  hooks still prefetch one block ahead, and the model part's output keeps its
  reload trigger as a fallback.
- The microbatch index is the one PyTorch's schedule actions already carry
  (`_Action.microbatch_index`), so nothing assumes a particular schedule or
  backward order.
- `ActivationRematConfig.pp_schedule_driven` (default off): `TrainingEngine`
  collects each stage's offloader (`get_activation_offloader`), calls
  `defer_to_schedule()` and registers it with the schedule's
  `register_activation_offloader`. It raises `ValueError` without PP or with a
  schedule runtime that lacks that method, and at config time when the policy
  offloads nothing.
- A group's D2H copies are joined to the compute stream even when its reload
  already ran: a last stage's backward follows its forward at once, so RELOAD
  can come before WAIT_OFFLOAD. `_free_gpu_copies` keys on `copy_done_event`,
  not on the group's remaining storages.
- `ACTIVATION_OFFLOAD.md`: the PP section documents the calls.

## Testing

`tests/unit_tests/gpu/distributed/test_activation_offload.py`, 5 new tests
that play a stage's actions with these calls: 1F1B order offloads every block
with grads equal to no offload; backwards out of
forward order (F0 F1 F2 B2 B0 B1) still reload the right microbatch;
`wait_offload(i)` frees only microbatch `i`'s last group;
`reload_backward(i, num_groups=all)` reloads the whole stage; RELOAD before
WAIT_OFFLOAD still joins the copies and captures in a CUDA graph. PP2 1F1B /
Interleaved1F1B / ZBVZeroBubble end to end stay bitwise equal to no offload
(the schedule does not call the API yet, so this covers the unchanged default
path).

## Known issues / follow-ups

- No PyTorch schedule runtime has `register_activation_offloader` yet: the
  schedule actions that call these methods come separately, so
  `pp_schedule_driven` raises today.

Depends on #6020.
@anijain2305
anijain2305 force-pushed the activation-offload-pp branch from 35d73f0 to 9aeb7aa Compare November 19, 2026 01:22
anijain2305 added a commit 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 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 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 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 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.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants