Skip to content

Activation offloading on torch_remat saved-tensor hooks - #6020

Merged
anijain2305 merged 1 commit into
mainfrom
activation-offload
Nov 19, 2026
Merged

anijain2305 merged 1 commit into
mainfrom
activation-offload

Conversation

@anijain2305

@anijain2305 anijain2305 commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

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:

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 [Do not review] Activation offloading #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.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 10, 2026
@anijain2305 anijain2305 changed the title [WIP] Eager activation offloading on torch_remat saved-tensor hooks Activation offloading on torch_remat saved-tensor hooks Nov 10, 2026
@anijain2305
anijain2305 force-pushed the activation-offload branch 6 times, most recently from d1b82d3 to 3fc71cd Compare November 11, 2026 00:33
@anijain2305
anijain2305 added this pull request to stack #6023 November 11, 2026 00:33
anijain2305 added a commit that referenced this pull request Nov 11, 2026
## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why
     this approach, and what you checked yourself. -->

## Why

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

**Example.** One stage under 1F1B; the schedule calls the offloader around
its existing actions:

```
F(mb0)
<next action>              wait_offload()           # frees mb0's last group
...
reload_next_backward()     # queues mb0's last group H2D, one action early
B(mb0)
```

## What changed

- `ActivationOffloader.defer_to_schedule()` hands the timing of each
  microbatch's last group to the schedule. State lives in
  `_PipelineScheduleState` (pending microbatches' groups, the forward in
  progress, last groups awaiting `wait_offload`); the non-PP path never
  touches it.
- `wait_offload()` frees the last groups of finished forwards, one action
  after the forward, so their copies had that action's compute to finish.
- `reload_next_backward(num_groups=1)` queues the reload of the last
  `num_groups` groups of the oldest microbatch whose backward has not run;
  forwards whose backward already ran outside the schedule (e.g. a stage's
  metadata inference) are skipped. Inside the stage, gradient hooks still
  prefetch one block ahead, and the model part's output keeps its reload
  trigger as a fallback.
- `ACTIVATION_OFFLOAD.md`: the PP section documents the three calls.

## Testing

`tests/unit_tests/gpu/distributed/test_activation_offload.py`, 3 new tests,
with the calls made in 1F1B order: every block is offloaded with no
on-demand reloads and grads equal to no offload; `wait_offload` frees the last
group before its backward; `reload_next_backward(num_groups=all)` reloads the
whole stage. PP2 1F1B / Interleaved1F1B / ZBVZeroBubble end to end stay
bitwise equal to no offload (the schedule does not call the API yet, so this
covers the unchanged default path).

## Known issues / follow-ups

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

Stacked on #6020.
@anijain2305
anijain2305 marked this pull request as ready for review November 11, 2026 00:47
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 11, 2026
anijain2305 added a commit that referenced this pull request Nov 11, 2026
## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why
     this approach, and what you checked yourself. -->

## Why

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

**Example.** One stage under 1F1B; the schedule calls the offloader around
its existing actions:

```
F(mb0)
<next action>              wait_offload()           # frees mb0's last group
...
reload_next_backward()     # queues mb0's last group H2D, one action early
B(mb0)
```

## What changed

- `ActivationOffloader.defer_to_schedule()` hands the timing of each
  microbatch's last group to the schedule. State lives in
  `_PipelineScheduleState` (pending microbatches' groups, the forward in
  progress, last groups awaiting `wait_offload`); the non-PP path never
  touches it.
- `wait_offload()` frees the last groups of finished forwards, one action
  after the forward, so their copies had that action's compute to finish.
- `reload_next_backward(num_groups=1)` queues the reload of the last
  `num_groups` groups of the oldest microbatch whose backward has not run;
  forwards whose backward already ran outside the schedule (e.g. a stage's
  metadata inference) are skipped. Inside the stage, gradient hooks still
  prefetch one block ahead, and the model part's output keeps its reload
  trigger as a fallback.
- `ACTIVATION_OFFLOAD.md`: the PP section documents the three calls.

## Testing

`tests/unit_tests/gpu/distributed/test_activation_offload.py`, 3 new tests,
with the calls made in 1F1B order: every block is offloaded with no
on-demand reloads and grads equal to no offload; `wait_offload` frees the last
group before its backward; `reload_next_backward(num_groups=all)` reloads the
whole stage. PP2 1F1B / Interleaved1F1B / ZBVZeroBubble end to end stay
bitwise equal to no offload (the schedule does not call the API yet, so this
covers the unchanged default path).

## Known issues / follow-ups

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

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

## Why

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

**Example.** One stage under 1F1B; the schedule calls the offloader around
its existing actions:

```
F(mb0)
<next action>              wait_offload()           # frees mb0's last group
...
reload_next_backward()     # queues mb0's last group H2D, one action early
B(mb0)
```

## What changed

- `ActivationOffloader.defer_to_schedule()` hands the timing of each
  microbatch's last group to the schedule. State lives in
  `_PipelineScheduleState` (pending microbatches' groups, the forward in
  progress, last groups awaiting `wait_offload`); the non-PP path never
  touches it.
- `wait_offload()` frees the last groups of finished forwards, one action
  after the forward, so their copies had that action's compute to finish.
- `reload_next_backward(num_groups=1)` queues the reload of the last
  `num_groups` groups of the oldest microbatch whose backward has not run;
  forwards whose backward already ran outside the schedule (e.g. a stage's
  metadata inference) are skipped. Inside the stage, gradient hooks still
  prefetch one block ahead, and the model part's output keeps its reload
  trigger as a fallback.
- `ACTIVATION_OFFLOAD.md`: the PP section documents the three calls.

## Testing

`tests/unit_tests/gpu/distributed/test_activation_offload.py`, 3 new tests,
with the calls made in 1F1B order: every block is offloaded with no
on-demand reloads and grads equal to no offload; `wait_offload` frees the last
group before its backward; `reload_next_backward(num_groups=all)` reloads the
whole stage. PP2 1F1B / Interleaved1F1B / ZBVZeroBubble end to end stay
bitwise equal to no offload (the schedule does not call the API yet, so this
covers the unchanged default path).

## Known issues / follow-ups

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

Stacked on #6020.
@anijain2305

Copy link
Copy Markdown
Contributor Author

@tianyu-l This is the main followup from our discussion earlier, and Claude summary is concise, so just pasting it

image

@anijain2305

Copy link
Copy Markdown
Contributor Author

@claude review

@claude

claude Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Claude encountered an error after 0s —— View job


I'll analyze this and get back to you.

@anijain2305

Copy link
Copy Markdown
Contributor Author

@claude review

@claude

claude Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Claude encountered an error after 0s —— View job


I'll analyze this and get back to you.

Comment on lines +307 to +313
if offloading:
raise ValueError(
"Activation offload does not support encoder blocks, but the "
f"remat policy offloads {', '.join(offloading)}. Keep "
"offload_block_input and offload_regions off for them: off in "
"the base policy, set per decoder block with block_overrides."
)

This comment was marked as outdated.

This comment was marked as outdated.

This comment was marked as outdated.

Comment on lines +323 to +326
raise ValueError(
"Activation offload requires CUDA, but the accelerator is "
f"{accelerator}. Keep offload_block_input and offload_regions off."
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Comment on lines +331 to +333
if self.block_policy(last_fqn).offloads_activations and any(
last_fqn in override.blocks for override in self.block_overrides
):

This comment was marked as outdated.

Comment on lines +337 to +338
"offload_last_block=True. Set it, or drop the override's "
"offload fields for this block."

This comment was marked as outdated.

This comment was marked as outdated.

This comment was marked as outdated.

captures the whole training step, so this would multiply pinned memory
by the number of microbatches.

What the pool does instead: it takes over the allocator's job. It

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.

I also considered changing upstream caching host allocator to support this, but I realized that it will require some significant amount of rampup to land a good solution (allocator is one of the most fundamental pieces of PyTorch).

There was also an effort earlier solving same problem, but the PR was closed - pytorch/pytorch#161583

@tianyu-l tianyu-l left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

will follow up on the mem pool thing after I read the materials, which is not a blocker

one inline comment

also need to pass claude check

Comment on lines +307 to +313
if offloading:
raise ValueError(
"Activation offload does not support encoder blocks, but the "
f"remat policy offloads {', '.join(offloading)}. Keep "
"offload_block_input and offload_regions off for them: off in "
"the base policy, set per decoder block with block_overrides."
)

This comment was marked as outdated.

Comment on lines +273 to +274
offloader: ActivationOffloader | None = None,
) -> ActivationOffloader | None:

This comment was marked as outdated.

## 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.
  Every checkpointed block follows its policy, including the last one to
  run; a recipe keeps a block on GPU with an override (e.g. the last block,
  whose copies barely overlap compute).
- `ActivationRematConfig.apply` checkpoints the blocks and, when the policy
  offloads anything, installs an `ActivationOffloader` on the model part.
  Nothing holds a handle to it: its forward hooks keep it alive, and it logs
  its first forward's stats.
  There is no module-level registry and no separate
  offload config. `apply` runs inside `parallelize`, before `fully_shard`;
  FSDP2's pre-forward is prepended, so it still runs before the offloader's.
- `apply`'s `saved_tensors_hooks` argument is removed: it existed for custom
  offloading, which this PR supersedes, and had no production caller.
- `torchtitan/distributed/activation_offload.py` (new): `ActivationOffloader`.
  Per transformer block it installs
  `torch_remat.saved_tensors_hooks`; `pack` copies selected storages D2H on a
  side stream, the GPU copies are freed at the end of the next block's
  forward, and a pre-hook on the autograd node of block i+1's output reloads
  block i on a reload stream (autograd runs it after FSDP2's pre-backward
  tensor hook, so the reload queues behind FSDP2's all-gather copy-out).
  Pinned host buffers come from a pool, so whole-step CUDA graphs work; it
  reuses buffers by power-of-two capacity, so saves whose size changes every
  step (tokens routed to an EP rank) do not grow pinned memory. Storages
  under 1 MiB, tensor subclasses, and parameter data stay on GPU, including
  the inner tensors of subclass parameters (the MXFP8 qdata and scales that
  MXFP8 Dist-MoE saves, which FSDP2 frees at reshard while a copy could
  still read them); a storage freed by something else before the free point
  raises. Autograd skips its in-place check for saves that
  hooks pack, so the offloader records each save's version and raises
  autograd's error at unpack if it changed. A tensor no reload trigger
  reloaded (its block's output got no gradient) raises at unpack.
  Under PP each stage has its own offloader.
  Offloading requires CUDA: `apply` raises on other accelerators.
  `apply` records each block it checkpoints under its full FQN
  (`Module._remat_block_fqn`), and the offloader hooks every recorded block
  under its model part at the first forward. So encoder blocks of a
  multimodal model (`apply(encoder, module_fqn=...)`) join the model part's
  offloader whatever the call order, and groups chain in run order: an
  encoder's last block is freed and reloaded around decoder block 0. When
  the last block's output is also the model part's, its reload is queued
  before the previous block's, since its backward runs first.
- GraphTrainer rejects a remat policy that offloads (its traced step does not
  run the eager hooks).
- Recipe: `torchtitan_recipes.models.llama3.llama3_8b_activation_offload`,
  the measured configuration below (selective remat, offload block inputs and
  `attention.*`), with a block override keeping the last block on GPU, as a
  starting point for other recipes.
- Docs: `torchtitan/distributed/ACTIVATION_OFFLOAD.md` (including "Keeping a
  block on GPU"), 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 |
| Muse Spark multimodal debug (vision + audio encoders) | CP 2, all regions retained, block inputs and all regions offloaded in encoder and decoder blocks |

## Performance

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

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

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

## Testing

`tests/unit_tests/gpu/distributed/test_activation_offload.py`: 23 tests, all
pass on GB300 (22 on 1 GPU, 1 FSDP CPU-offload test on 2 GPUs, with offload
installed before `fully_shard` as in `parallelize`). They check outputs and
grads equal to the same remat policy without offload; only the selected saves
move; per-block offload overrides, including one keeping the last block on
GPU; one transfer per storage across views; parameters never offloaded, nor the
FSDP2-managed operands of a tensor-subclass weight format (as MXFP8); tensor
subclass saves stay on GPU; a storage freed elsewhere before the free point
raises; forward frees
and backward releases the GPU copies; unpack without a reload raises; CUDA
graph replay equal to eager with shared host buffers; step-varying sizes
reuse host buffers; reloads queue after later-registered output hooks;
in-place updates of saves are detected; bitwise with FSDP2 CPU parameter
offload.
Encoder blocks chain into the decoder (toy encoder + decoder: bitwise
grads, encoder's last block offloaded, freed in decoder block 0's forward).
`test_activation_checkpoint.py`: `apply` records the FQN of each block it
checkpoints, encoder blocks included; offloading on a non-CUDA accelerator
raises.
The 2-GPU test is marked `multi_gpu` so the multi-GPU CI lane runs it.
`tests/unit_tests/cpu/recipes/test_llama3.py`: the offload recipe offloads
every block but the last. Its policy on the 8B model with the debug data, on
2 x GB300 (FSDP, 8K tokens per rank, no CUDA graph): loss equal to no offload
at stdout precision over 10 steps, 8.5 GiB less peak memory.

## Known issues / follow-ups

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

Copy link
Copy Markdown
Contributor Author

@claude review

@claude

claude Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Claude encountered an error after 0s —— View job


I'll analyze this and get back to you.

@tianyu-l

Copy link
Copy Markdown
Contributor

@claude review again

@claude

claude Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Claude encountered an error after 0s —— View job


I'll analyze this and get back to you.

@anijain2305

Copy link
Copy Markdown
Contributor Author

@claude review

@claude

claude Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Claude encountered an error after 0s —— View job


I'll analyze this and get back to you.

@anijain2305

Copy link
Copy Markdown
Contributor Author

@claude review

@claude

claude Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @anijain2305's task in 3m 23s —— View job


Approve: the earlier must-fix items are resolved. Before merging, please update the stale PR description and delete the redundant recipe test. Review

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Verdict: Approve -- please address the items below before merging. Every must-fix item from the earlier reviews is resolved at HEAD, and I found no new correctness bug. What remains is a PR description that still describes an earlier design, and one redundant CPU test.

What this PR does.

  • The remat policy gains offload_block_input and offload_regions; both are also BlockRematOverride fields.
  • When any block offloads, ActivationRematConfig.apply installs one ActivationOffloader per model part. Each block call becomes an offload group under torch_remat saved-tensor hooks:
    • Selected storages are copied D2H into a pinned buffer pool.
    • The GPU copies are freed at the end of the next block's forward.
    • In backward, each group is reloaded one block ahead.
  • Encoder blocks chain into the decoder blocks.
  • GraphTrainer rejects offloading. Non-CUDA accelerators raise ValueError.

Example.

config.activation_remat = DefaultActivationRematConfig(
    offload_block_input=True, offload_regions=["attention.*"],
    block_overrides=[BlockRematOverride(blocks=["layers.31"],
                                        offload_block_input=False, offload_regions=[])],
)
# layers.0..30: the block input and attention.* saves go to CPU, and come back one block ahead.
# layers.31 stays on GPU. Loss and grad_norm are bitwise equal to running without offloading.

Must fix

  1. The PR description describes code that no longer exists. It says:

    • ActivationOffloadConfig and config.activation_offload are added, with offload_last_block.
    • TrainingEngine.Config.activation_offload is required when the policy offloads.
    • An override that offloads the last block logs a warning.
    • "Encoder blocks are not offloaded; a policy that would offload them logs a warning".
    • GraphTrainer rejects activation_offload.
    • Testing covers offload_last_block and "a policy that offloads nothing is rejected".

    At HEAD there is one config, and apply installs the offloader. The last block is kept on GPU only through an override (as in the new llama3_8b_activation_offload recipe). Encoder blocks are offloaded. apply no longer has a saved_tensors_hooks argument. Please update the Example, "What changed" and "Testing" sections. The human-written summary is present and still accurate.

  2. tests/unit_tests/cpu/recipes/test_llama3.py:10 -- this test re-reads the recipe's own override. Existing GPU tests already cover the behavior, so please delete it (inline comment).

Should consider

  • PP still has no CI coverage (still open). PP numerics were checked by hand only. Enabling offload_block_input=True on an existing PP entry, e.g. llama3_debugmodel_fsdp2_pp2_1f1b in tests/integration_tests/features.py:300, would guard the stage-input skip and the per-stage offloaders without adding a new job.

Questions

  • tianyu-l asked at activation_remat.py:300 whether ROCm needs a hardware skip. Today it does not:

    • The ROCm workflow runs only the features and models integration suites.
    • No integration test enables offloading.

    There are two catches:

    • ROCm reports its accelerator type as "cuda", so the new check lets ROCm through without any testing there.
    • If the PP suggestion above is adopted and ROCm can't run it, that test belongs under the ROCm key in tests/integration_tests/hardware_skips/skipped_tests.toml.
Details

Earlier items, verified at HEAD:

  • Separate offload config: merged into ActivationRematConfig, and apply installs the offloader. Resolved.
  • saved_tensors_hooks argument and its test: deleted. Resolved.
  • offload_last_block and its warning: removed. The recipe uses a BlockRematOverride instead. Resolved.
  • CUDA hardwiring: apply raises ValueError on other accelerators, with a TODO naming the missing graph-capture query. Resolved.
  • 2-GPU FSDP CPU-offload test: now has @pytest.mark.multi_gpu, so it runs in the multi-GPU job of unit_test_gpu.yaml. Resolved.
  • get_activation_offloader registry: removed; forward hooks keep the offloader alive. Resolved.
  • Stale "grad hook" text in the SVG: gone. Resolved.
  • tianyu-l's earlier questions: answered in threads. tianyu-l approved, conditional on this check.

Correctness notes:

  • Block hooks are registered at the first forward, after fully_shard, and the post-hook is prepended, so it runs before FSDP2 reshards.
  • During remat's replay and under no-grad, the pre-hook opens no group, so the replay and evaluation offload nothing.
  • The model part's inputs are skipped, which covers a PP stage's input.
  • Regional local_compile compiles regions inside the block, not around the checkpoint, so torch_remat's rejection of hooks under compile does not apply there.

A maintainer still needs to review the core torchtitan/distributed/ changes.

Not verified: GPU numerics and performance figures, MXFP8 Dist-MoE offloading (fegin's non-finite-loss report), behavior on ROCm.

Comment on lines +10 to +16
def test_activation_offload_recipe_keeps_the_last_block_on_gpu():
config = recipes.llama3_8b_activation_offload()
remat = config.activation_remat
num_layers = len(config.model.layers)
assert remat.block_policy("layers.0").offloads_activations
assert remat.block_policy(f"layers.{num_layers - 2}").offloads_activations
assert not remat.block_policy(f"layers.{num_layers - 1}").offloads_activations

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This test only reads back the BlockRematOverride that llama3_8b_activation_offload sets two lines earlier. Per .claude/rules/tests.md, tests that re-read a config they just set don't earn their cost.

The behavior it relies on, an override keeping the last block on GPU, is already covered at runtime by test_override_keeps_the_last_block_on_gpu and test_block_overrides_select_offloads_per_block in test_activation_offload.py. Please delete this file.

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

Labels

ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/rl CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Feature Request: Async activation offloading to CPU with prefetch

3 participants