Skip to content

[Do not review] Activation offloading - #467

Closed
awgu wants to merge 3 commits into
gh/awgu/8/basefrom
gh/awgu/8/head
Closed

awgu wants to merge 3 commits into
gh/awgu/8/basefrom
gh/awgu/8/head

Conversation

@awgu

@awgu awgu commented Jul 18, 2024 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Current UX

  • We use a saved_tensors_hooks context manager, which should be wrapped around module.forward. The context lets us override pack and unpack hooks that are called when saving an activation for backward and using an activation in backward, respectively. See the tutorial for more info.
  • We expose two main methods for the user from the context: wait_for_d2h and copy_h2d_async.
    • By default, the D2H copies for offloading are async and use pinned memory. The user must call wait_for_d2h to wait on the D2H copies and free the device memory. This should be done after the compute to overlap with has been issued.
    • By default, the H2D copies are sync. The user must call copy_h2d_async to prefetch the H2D copies as async. This should be done before the compute to overlap with has been issued.
    • We show an example of this in apply_ac in parallelize_llama.py using module hooks.
  • Together, this means that by default, no GPU memory is saved and that H2D copies are sync. Only by calling the wait_for_d2h method can we save GPU memory, and only by calling copy_h2d_async methods can we overlap H2D in backward.

Known Problems

  • ! Conflict with split_with_sizes_copy's H2D copy (specific to FSDP2):
    • FSDP2's all-gather copy-out uses split_with_sizes_copy, which first issues a mini-H2D copy to send metadata needed for the main copy.
    • When the CPU issue order is copy_h2d_async for layer i-1 -> split_with_sizes_copy for layer i -> layer i backward compute, the mini-H2D copy for split_with_sizes_copy for layer i can get serialized to run after the copy_h2d_async for layer i-1 H2D copies even though they are running in different streams. This prevents the copy_h2d_async for layer i-1 to overlap with layer i backward compute.
    • For now, this can be worked around with reshard_after_forward=False.
    • Trick/hack from @yifuwang : sleep 1 ms in the offload_stream before un-offloading (https://fburl.com/perfdoctor/ms47gqvp) --> allows prioritizing the split_with_sizes_copy H2D copy
    • The CPU issue order of copy_h2d_async for layer i-1 -> split_with_sizes_copy for layer i -> layer i backward compute comes from running the copy_h2d_async for layer i-1 using a module full pre-backward hook.
  • ! If the user offloads too many activations, the program can become slow and/or freeze. Further, the first few iterations are slow due to cudaHostAlloc calls warming up the CPU caching allocator. This might be brittle if other parts of the program (e.g. checkpointing) also use pinned memory. If we do not gc.collect() every iteration, the pinned memory does not seem to be freed, so the allocator does not reuse it in subsequent iterations.
  • ! We do not have a good way to apply a predicate to decide which activation tensors to offload. With the pack hook API, we only see the tensor, not any other information like which op constructed the tensor.

Examples

awgu pushed a commit that referenced this pull request Jul 18, 2024
ghstack-source-id: 863f4bc
Pull Request resolved: #467
@facebook-github-bot facebook-github-bot added the CLA Signed This label is managed by the Meta Open Source bot. label Jul 18, 2024
awgu pushed a commit that referenced this pull request Jul 18, 2024
ghstack-source-id: f749e6f
Pull Request resolved: #467
**Current UX**
- We use a `saved_tensors_hooks` context manager, which should be wrapped around `module.forward`. The context lets us override pack and unpack hooks that are called when saving an activation for backward and using an activation in backward, respectively. See the [tutorial](https://pytorch.org/tutorials/intermediate/autograd_saved_tensors_hooks_tutorial.html) for more info.
- We expose two main methods for the user from the context: `wait_for_d2h` and `copy_h2d_async`.
    - By default, the D2H copies for offloading are async and use pinned memory. The user must call `wait_for_d2h` to wait on the D2H copies and free the device memory. This should be done after the compute to overlap with has been issued.
    - By default, the H2D copies are sync. The user must call `copy_h2d_async` to prefetch the H2D copies as async. This should be done before the compute to overlap with has been issued.
    - We show an example of this in `apply_ac` in `parallelize_llama.py` using module hooks.

**Known Problems**
- **!** Conflict with `split_with_sizes_copy`'s H2D copy (specific to FSDP2):
    - FSDP2's all-gather copy-out uses `split_with_sizes_copy`, which first issues a mini-H2D copy to send metadata needed for the main copy.
    - When the CPU issue order is `copy_h2d_async` for layer `i-1` -> `split_with_sizes_copy` for layer `i` -> layer `i` backward compute, the mini-H2D copy for `split_with_sizes_copy` for layer `i` can get serialized to run _after_ the `copy_h2d_async` for layer `i-1` H2D copies even though they are running in different streams. This prevents the `copy_h2d_async` for layer `i-1` to overlap with layer `i` backward compute.
    - For now, this can be worked around with `reshard_after_forward=False`.
    - Trick/hack from yifuwang : sleep 1 ms in the `offload_stream` before un-offloading (https://fburl.com/perfdoctor/ms47gqvp) --> allows prioritizing the `split_with_sizes_copy` H2D copy
    - The CPU issue order of `copy_h2d_async` for layer `i-1` -> `split_with_sizes_copy` for layer `i` -> layer `i` backward compute comes from running the `copy_h2d_async` for layer `i-1` using a module full pre-backward hook.
- **!** If the user offloads too many activations, the program can become slow and/or freeze. Further, the first few iterations are slow due to `cudaHostAlloc` calls warming up the CPU caching allocator. This might be brittle if other parts of the program (e.g. checkpointing) also use pinned memory. If we do not `gc.collect()` every iteration, the pinned memory does not seem to be freed, so the allocator does not reuse it in subsequent iterations.
- **!** We do not have a good way to apply a predicate to decide which activation tensors to offload. With the pack hook API, we only see the tensor, not any other information like which op constructed the tensor.

**Examples**
- Llama3-8B: DP=8, local batch size 1, sequence length 8192, no AC, `reshard_after_forward=False`:
    - Trace: https://fburl.com/perfdoctor/r1yf0lqf
    - Reserved memory: 65.67GiB(69.10%)
    - WPS: 5,294  MFU: 31.00%
- Llama3-8B: DP=8, local batch size 1, sequence length 8192, no AC, `reshard_after_forward=True`:
    - Trace: https://fburl.com/perfdoctor/qbhr98az
    - Reserved memory: 54.01GiB(56.83%)
    - WPS: 4,085  MFU: 23.92% (mainly because H2Ds in backward are not overlapped)
    - If we use yifuwang's trick, we can get WPS: 5,073, MFU: 29.70% without changing reserved memory
- Baseline Llama3-8B: DP=8, local batch size 1, sequence length 8192, no AC, `reshard_after_forward=True`:
    - Reserved memory: 78.38GiB(82.48%)
    - WPS: 6,341  MFU: 37.13%

[ghstack-poisoned]
awgu pushed a commit that referenced this pull request Jul 18, 2024
ghstack-source-id: 1f53901
Pull Request resolved: #467
Comment thread train.py
lr_schedulers.step()

if job_config.experimental.offload_activations:
# NOTE: We need `gc.collect` to ensure that CPU memory is freed

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

This needs some more investigation. Maybe there is some ref cycle that I am not aware of.

@awgu

awgu commented Jul 18, 2024 •

Copy link
Copy Markdown
Contributor Author

For fun:

Note how reshard_after_forward=False with this 2-FFN-activation offloading dominates reshard_after_forward=True without offloading/AC since it has higher WPS but lower memory.

@awgu

awgu commented Jul 19, 2024

Copy link
Copy Markdown
Contributor Author

@yifuwang made the good point there may be interference for inter-node collectives since they also use PCIe to send/recv data to/from the NIC, competing for the D2H/H2D activation copies. The testing so far was only intra-node due to lack of compute resources.

tianyu-l pushed a commit that referenced this pull request Aug 16, 2024
ghstack-source-id: 1f53901
Pull Request resolved: #467
@awgu awgu closed this Feb 7, 2025
anijain2305 added a commit that referenced this pull request Nov 16, 2026
## 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 always runs under remat; the remat policy 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
)
config.activation_offload = ActivationOffloadConfig()  # how: e.g. offload_last_block
```

## What changed

- `ActivationRematConfig.offload_block_input` / `offload_regions` (default
  off): which retained tensors go to CPU. They are also `BlockRematOverride`
  fields (per-block policies, the previous PR in this stack), so offloading
  can differ per block; the fixed presets accept them, also in overrides
  that set nothing else.
- `torchtitan/distributed/activation_offload.py` (new): `ActivationOffloadConfig`
  (runtime: `offload_last_block`)
  and `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 stay on GPU. 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.
  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 remat policy (an override offloading it logs a
  warning). Encoder blocks are not offloaded; a policy that would offload
  them logs a warning.
- `TrainingEngine.Config.activation_offload` (default `None`): applied to each
  model part after remat and parallelization. Required exactly when the remat
  policy offloads something, and requires `activation_remat` (`ValueError`
  otherwise).
- GraphTrainer rejects `activation_offload` (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: both load block i-1, which needs both before its backward,
so the order would not shorten the wait; what matters is whether the total
fits in one block's backward. Ordering them is a follow-up that needs FSDP2
to expose the stream it issues parameter copies on, since that is
`all_gather_copy_in_stream` by default but the compute stream under
`set_unshard_in_current_stream` or with a single rank.

**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`: 22 tests, all
pass on GB300 (21 on 1 GPU, 1 FSDP CPU-offload test on 2 GPUs). They check
outputs and grads equal to the same remat policy without offload; only the
selected saves move; per-block offload overrides, and the last block
winning over them; `offload_last_block`; a policy that offloads nothing is
rejected; one
transfer per storage across views; parameters never offloaded; forward frees
and backward releases the GPU copies; on-demand reload without triggers; 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.

## Known issues / follow-ups

- Schedule-driven offload of each stage's last block under PP: the offloader
  API is the next PR in this stack; the PyTorch schedule actions that call it
  come separately.
- Dist-MoE-side offload of its activation buffers.
- Ordering activation reloads with FSDP2 CPU parameter offload's
  host-to-device shard copies (see Design notes): needs FSDP2 to expose the
  stream it issues parameter copies on.
anijain2305 added a commit that referenced this pull request Nov 16, 2026
## 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 always runs under remat; the remat policy 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
)
config.activation_offload = ActivationOffloadConfig()  # how: e.g. offload_last_block
```

## What changed

- `ActivationRematConfig.offload_block_input` / `offload_regions` (default
  off): which retained tensors go to CPU. They are also `BlockRematOverride`
  fields (per-block policies, the previous PR in this stack), so offloading
  can differ per block; the fixed presets accept them, also in overrides
  that set nothing else.
- `torchtitan/distributed/activation_offload.py` (new): `ActivationOffloadConfig`
  (runtime: `offload_last_block`)
  and `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 stay on GPU. 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.
  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 remat policy (an override offloading it logs a
  warning). Encoder blocks are not offloaded; a policy that would offload
  them logs a warning.
- `TrainingEngine.Config.activation_offload` (default `None`): applied to each
  model part after remat and parallelization. Required exactly when the remat
  policy offloads something, and requires `activation_remat` (`ValueError`
  otherwise).
- GraphTrainer rejects `activation_offload` (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: both load block i-1, which needs both before its backward,
so the order would not shorten the wait; what matters is whether the total
fits in one block's backward. Ordering them is a follow-up that needs FSDP2
to expose the stream it issues parameter copies on, since that is
`all_gather_copy_in_stream` by default but the compute stream under
`set_unshard_in_current_stream` or with a single rank.

**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`: 22 tests, all
pass on GB300 (21 on 1 GPU, 1 FSDP CPU-offload test on 2 GPUs). They check
outputs and grads equal to the same remat policy without offload; only the
selected saves move; per-block offload overrides, and the last block
winning over them; `offload_last_block`; a policy that offloads nothing is
rejected; one
transfer per storage across views; parameters never offloaded; forward frees
and backward releases the GPU copies; on-demand reload without triggers; 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.

## Known issues / follow-ups

- Schedule-driven offload of each stage's last block under PP: the offloader
  API is the next PR in this stack; the PyTorch schedule actions that call it
  come separately.
- Dist-MoE-side offload of its activation buffers.
- Ordering activation reloads with FSDP2 CPU parameter offload's
  host-to-device shard copies (see Design notes): needs FSDP2 to expose the
  stream it issues parameter copies on.
anijain2305 added a commit that referenced this pull request Nov 16, 2026
## 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 always runs under remat; the remat policy 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
)
config.activation_offload = ActivationOffloadConfig()  # how: e.g. offload_last_block
```

## What changed

- `ActivationRematConfig.offload_block_input` / `offload_regions` (default
  off): which retained tensors go to CPU. They are also `BlockRematOverride`
  fields (per-block policies, the previous PR in this stack), so offloading
  can differ per block; the fixed presets accept them, also in overrides
  that set nothing else.
- `torchtitan/distributed/activation_offload.py` (new): `ActivationOffloadConfig`
  (runtime: `offload_last_block`)
  and `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 stay on GPU. 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.
  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 remat policy (an override offloading it logs a
  warning). Encoder blocks are not offloaded; a policy that would offload
  them logs a warning.
- `TrainingEngine.Config.activation_offload` (default `None`): applied to each
  model part after remat and parallelization. Required exactly when the remat
  policy offloads something, and requires `activation_remat` (`ValueError`
  otherwise).
- GraphTrainer rejects `activation_offload` (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: both load block i-1, which needs both before its backward,
so the order would not shorten the wait; what matters is whether the total
fits in one block's backward. Ordering them is a follow-up that needs FSDP2
to expose the stream it issues parameter copies on, since that is
`all_gather_copy_in_stream` by default but the compute stream under
`set_unshard_in_current_stream` or with a single rank.

**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`: 22 tests, all
pass on GB300 (21 on 1 GPU, 1 FSDP CPU-offload test on 2 GPUs). They check
outputs and grads equal to the same remat policy without offload; only the
selected saves move; per-block offload overrides, and the last block
winning over them; `offload_last_block`; a policy that offloads nothing is
rejected; one
transfer per storage across views; parameters never offloaded; forward frees
and backward releases the GPU copies; on-demand reload without triggers; 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.

## Known issues / follow-ups

- Schedule-driven offload of each stage's last block under PP: the offloader
  API is the next PR in this stack; the PyTorch schedule actions that call it
  come separately.
- Dist-MoE-side offload of its activation buffers.
- Ordering activation reloads with FSDP2 CPU parameter offload's
  host-to-device shard copies (see Design notes): needs FSDP2 to expose the
  stream it issues parameter copies on.
anijain2305 added a commit that referenced this pull request Nov 16, 2026
## 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 always runs under remat; the remat policy 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
)
config.activation_offload = ActivationOffloadConfig()  # how: e.g. offload_last_block
```

## What changed

- `ActivationRematConfig.offload_block_input` / `offload_regions` (default
  off): which retained tensors go to CPU. They are also `BlockRematOverride`
  fields (per-block policies, the previous PR in this stack), so offloading
  can differ per block; the fixed presets accept them, also in overrides
  that set nothing else.
- `torchtitan/distributed/activation_offload.py` (new): `ActivationOffloadConfig`
  (runtime: `offload_last_block`)
  and `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 stay on GPU. 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.
  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 remat policy (an override offloading it logs a
  warning). Encoder blocks are not offloaded; a policy that would offload
  them logs a warning.
- `TrainingEngine.Config.activation_offload` (default `None`): applied to each
  model part after remat and parallelization. Required exactly when the remat
  policy offloads something, and requires `activation_remat` (`ValueError`
  otherwise).
- GraphTrainer rejects `activation_offload` (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: both load block i-1, which needs both before its backward,
so the order would not shorten the wait; what matters is whether the total
fits in one block's backward. Ordering them is a follow-up that needs FSDP2
to expose the stream it issues parameter copies on, since that is
`all_gather_copy_in_stream` by default but the compute stream under
`set_unshard_in_current_stream` or with a single rank.

**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`: 22 tests, all
pass on GB300 (21 on 1 GPU, 1 FSDP CPU-offload test on 2 GPUs). They check
outputs and grads equal to the same remat policy without offload; only the
selected saves move; per-block offload overrides, and the last block
winning over them; `offload_last_block`; a policy that offloads nothing is
rejected; one
transfer per storage across views; parameters never offloaded; forward frees
and backward releases the GPU copies; on-demand reload without triggers; 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.

## Known issues / follow-ups

- Schedule-driven offload of each stage's last block under PP: the offloader
  API is the next PR in this stack; the PyTorch schedule actions that call it
  come separately.
- Dist-MoE-side offload of its activation buffers.
- Ordering activation reloads with FSDP2 CPU parameter offload's
  host-to-device shard copies (see Design notes): needs FSDP2 to expose the
  stream it issues parameter copies on.
anijain2305 added a commit that referenced this pull request Nov 16, 2026
## 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 always runs under remat; the remat policy 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
)
config.activation_offload = ActivationOffloadConfig()  # how: e.g. offload_last_block
```

## What changed

- `ActivationRematConfig.offload_block_input` / `offload_regions` (default
  off): which retained tensors go to CPU. They are also `BlockRematOverride`
  fields (per-block policies, the previous PR in this stack), so offloading
  can differ per block; the fixed presets accept them, also in overrides
  that set nothing else.
- `torchtitan/distributed/activation_offload.py` (new): `ActivationOffloadConfig`
  (runtime: `offload_last_block`)
  and `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 stay on GPU. 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.
  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 remat policy (an override offloading it logs a
  warning). Encoder blocks are not offloaded; a policy that would offload
  them logs a warning.
- `TrainingEngine.Config.activation_offload` (default `None`): applied to each
  model part after remat and parallelization. Required exactly when the remat
  policy offloads something, and requires `activation_remat` (`ValueError`
  otherwise).
- GraphTrainer rejects `activation_offload` (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: both load block i-1, which needs both before its backward,
so the order would not shorten the wait; what matters is whether the total
fits in one block's backward. Ordering them is a follow-up that needs FSDP2
to expose the stream it issues parameter copies on, since that is
`all_gather_copy_in_stream` by default but the compute stream under
`set_unshard_in_current_stream` or with a single rank.

**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`: 22 tests, all
pass on GB300 (21 on 1 GPU, 1 FSDP CPU-offload test on 2 GPUs). They check
outputs and grads equal to the same remat policy without offload; only the
selected saves move; per-block offload overrides, and the last block
winning over them; `offload_last_block`; a policy that offloads nothing is
rejected; one
transfer per storage across views; parameters never offloaded; forward frees
and backward releases the GPU copies; on-demand reload without triggers; 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.

## Known issues / follow-ups

- Schedule-driven offload of each stage's last block under PP: the offloader
  API is the next PR in this stack; the PyTorch schedule actions that call it
  come separately.
- Dist-MoE-side offload of its activation buffers.
- Ordering activation reloads with FSDP2 CPU parameter offload's
  host-to-device shard copies (see Design notes): needs FSDP2 to expose the
  stream it issues parameter copies on.
anijain2305 added a commit that referenced this pull request Nov 16, 2026
## 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 always runs under remat; the remat policy 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
)
config.activation_offload = ActivationOffloadConfig()  # how: e.g. offload_last_block
```

## What changed

- `ActivationRematConfig.offload_block_input` / `offload_regions` (default
  off): which retained tensors go to CPU. They are also `BlockRematOverride`
  fields (per-block policies, the previous PR in this stack), so offloading
  can differ per block; the fixed presets accept them, also in overrides
  that set nothing else.
- `torchtitan/distributed/activation_offload.py` (new): `ActivationOffloadConfig`
  (runtime: `offload_last_block`)
  and `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 stay on GPU. 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.
  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 remat policy (an override offloading it logs a
  warning). Encoder blocks are not offloaded; a policy that would offload
  them logs a warning.
- `TrainingEngine.Config.activation_offload` (default `None`): applied to each
  model part after remat and parallelization. Required exactly when the remat
  policy offloads something, and requires `activation_remat` (`ValueError`
  otherwise).
- GraphTrainer rejects `activation_offload` (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`: 22 tests, all
pass on GB300 (21 on 1 GPU, 1 FSDP CPU-offload test on 2 GPUs). They check
outputs and grads equal to the same remat policy without offload; only the
selected saves move; per-block offload overrides, and the last block
winning over them; `offload_last_block`; a policy that offloads nothing is
rejected; one
transfer per storage across views; parameters never offloaded; forward frees
and backward releases the GPU copies; on-demand reload without triggers; 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.

## Known issues / follow-ups

- Schedule-driven offload of each stage's last block under PP: the offloader
  API is the next PR in this stack; 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.
anijain2305 added a commit that referenced this pull request Nov 16, 2026
## 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 always runs under remat; the remat policy 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
)
config.activation_offload = ActivationOffloadConfig()  # how: e.g. offload_last_block
```

## What changed

- `ActivationRematConfig.offload_block_input` / `offload_regions` (default
  off): which retained tensors go to CPU. They are also `BlockRematOverride`
  fields (per-block policies, the previous PR in this stack), so offloading
  can differ per block; the fixed presets accept them, also in overrides
  that set nothing else.
- `torchtitan/distributed/activation_offload.py` (new): `ActivationOffloadConfig`
  (runtime: `offload_last_block`)
  and `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 stay on GPU. 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.
  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 remat policy (an override offloading it logs a
  warning). Encoder blocks are not offloaded; a policy that would offload
  them logs a warning.
- `TrainingEngine.Config.activation_offload` (default `None`): applied to each
  model part after remat and parallelization. Required exactly when the remat
  policy offloads something, and requires `activation_remat` (`ValueError`
  otherwise).
- GraphTrainer rejects `activation_offload` (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`: 22 tests, all
pass on GB300 (21 on 1 GPU, 1 FSDP CPU-offload test on 2 GPUs). They check
outputs and grads equal to the same remat policy without offload; only the
selected saves move; per-block offload overrides, and the last block
winning over them; `offload_last_block`; a policy that offloads nothing is
rejected; one
transfer per storage across views; parameters never offloaded; forward frees
and backward releases the GPU copies; on-demand reload without triggers; 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.

## Known issues / follow-ups

- Schedule-driven offload of each stage's last block under PP: the offloader
  API is the next PR in this stack; 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.
anijain2305 added a commit that referenced this pull request Nov 18, 2026
## 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
  (`get_activation_offloader(model_part)` returns it). There is 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 stay on GPU. 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 offload fields (an override offloading it logs a
  warning). 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`: 20 tests, all
pass on GB300 (19 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, and the last block winning over them;
`offload_last_block`; one
transfer per storage across views; parameters never offloaded; 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 raises.

## Known issues / follow-ups

- Schedule-driven offload of each stage's last block under PP: the offloader
  API is the next PR in this stack; 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.
anijain2305 added a commit that referenced this pull request Nov 19, 2026
## Summary (human-written)

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

tldr is
* activation offloadin works on top of remat. Offloading pack/unpack
hooks are entered before we run remat.checkpoint, so that offloader sees
what remat is stashing for backward.
* 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 always runs under remat; the remat policy
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
)
config.activation_offload = ActivationOffloadConfig()  # how: e.g. offload_last_block
```

## What changed

- `ActivationRematConfig.offload_block_input` / `offload_regions`
(default
off): which retained tensors go to CPU. They are also
`BlockRematOverride`
fields (per-block policies, the previous PR in this stack), so
offloading
  can differ per block; the fixed presets accept them, also in overrides
  that set nothing else.
- `torchtitan/distributed/activation_offload.py` (new):
`ActivationOffloadConfig`
  (runtime: `offload_last_block`)
  and `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 stay on GPU. 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.
  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 remat policy (an override offloading it logs a
warning). Encoder blocks are not offloaded; a policy that would offload
  them logs a warning.
- `TrainingEngine.Config.activation_offload` (default `None`): applied
to each
model part after remat and parallelization. Required exactly when the
remat
policy offloads something, and requires `activation_remat` (`ValueError`
  otherwise).
- GraphTrainer rejects `activation_offload` (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`: 22 tests,
all
pass on GB300 (21 on 1 GPU, 1 FSDP CPU-offload test on 2 GPUs). They
check
outputs and grads equal to the same remat policy without offload; only
the
selected saves move; per-block offload overrides, and the last block
winning over them; `offload_last_block`; a policy that offloads nothing
is
rejected; one
transfer per storage across views; parameters never offloaded; forward
frees
and backward releases the GPU copies; on-demand reload without triggers;
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.

## Known issues / follow-ups

- Schedule-driven offload of each stage's last block under PP: the
offloader
API is the next PR in this stack; 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.
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