Skip to content

[optim] Keep Adam moments in pinned host memory (zero-copy) - #5881

Merged
fegin merged 1 commit into
mainfrom
fegin/stack/10
Nov 23, 2026
Merged

fegin merged 1 commit into
mainfrom
fegin/stack/10

Conversation

@fegin

@fegin fegin commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

Stacked PRs:


[optim] Keep Adam moments in pinned host memory (zero-copy)

Summary (human-written)

This PR implements CPU offloading for fused Adam/AdamW. We keep the moments in
pinned memory and never allocate GPU memory for them. Instead, we feed the pinned
memory data pointer to the CUDA tensor. So the fused op will directly
use the tensor assuming the tensor data is on GPU memory.

So the CPU <-> GPU reads and writes and the computation are all initiated through one
single kernel. And the overlapping comes from the kernel pipeline
itself.

Compared to PR #5749, this approach requires less GPU memory and the
performance is better. See the Alternatives below.

We now use preserve_state_dtype_on_load in TorchTitan. This preserves
the dtype, so we don't need to install a hook for bf16 moments. The hook
also made a temporary fp32 copy of every moment in GPU memory during load.

Why

Adam moments can be the last thing that does not fit on the GPU. Muse Spark 816B with DP8/CP8/EP64 and 32K sequence length runs out of memory in the first optimizer.step() with device moments. The check uses a fake process group (fake PG): one GB300 GPU runs rank 0 of a 64-GPU layout. Step 1 forward and backward finish, then Adam fails to allocate exp_avg (tried to allocate 512 MiB with 155 MiB free of 276.6 GiB). PR #5749 offloads the moments, but it streams them through two GPU slots with side-stream copies and needs a custom state_dict/load_state_dict.

This change keeps exp_avg and exp_avg_sq of a chosen share of the parameters in pinned CPU memory and exposes them to CUDA as tensors that alias that memory. The unchanged fused kernel reads and writes them in place over the host link.

Example.

# Before: moments live on the GPU. The 64-GPU Muse Spark run OOMs in optimizer.step().
# After:
optimizers = config.optim.optimizer.optimizers
optimizers[0] = replace(optimizers[0], moment_cpu_offload_fraction=1.0)
# Launch with: PYTORCH_ALLOC_CONF="expandable_segments:True,pinned_max_round_threshold_mb:1" ./run_train.sh ...
# Moments use no GPU memory. The step stays one fused kernel launch on fixed addresses.
# A fraction such as 0.5 offloads only part of the moments and costs less step time.

What changed

Config

  • Adam and AdamW get moment_cpu_offload_fraction: float (default 0.0). 0.0 keeps all moments on the device, 1.0 offloads all, and a value in between offloads that share of the local moment bytes.
  • The unit is a whole parameter. Parameters are taken in optimizer order until the offloaded moment bytes reach the fraction of all local moment bytes. FSDP shards evenly and experts have equal sizes, so ranks usually pick the same parameters.
  • Offloaded and device moments share one param group and one fused AdamW call.
  • Add pinned_max_round_threshold_mb:1 to PYTORCH_ALLOC_CONF when offloading moments (Moment allocation).
  • TrainingEngine applies NUMA binding before any pinned allocation, so no launcher flag is needed.

Moment allocation

  • The moments and step of offloaded parameters are created at optimizer construction. The moments are torch.zeros(..., pin_memory=True) CPU tensors; step stays a device tensor. The other parameters get device moments lazily, as before.
  • There are no chunks, slots, side streams, or events. The step stays one kernel launch on fixed addresses and is CUDA-graph capturable.
  • DTensor params get DTensor moments with the same mesh and placements, so DCP saves and reshards them like device moments.
  • Empty shards are never offloaded. They need no memory.
  • By default, PyTorch's caching host allocator rounds each allocation up to a power of two, using up to 2x host memory. pinned_max_round_threshold_mb (Add configurable threshold to avoid power-of-two rounding for large pinned memory allocations pytorch#171662) turns that off above the threshold. With pinned_max_round_threshold_mb:1, allocations above 1 MB are pinned at their exact size. After allocating, the optimizer compares the pinned bytes in torch.cuda.host_memory_stats() with the requested bytes. If rounding wasted more than 1 GiB, it raises ValueError that names the setting to add (pinned_max_round_threshold_mb:1 in PYTORCH_ALLOC_CONF).
  • The offloading code lives in a new torchtitan/components/optim/offloading.py. optimizer.py only validates the config and calls init_cpu_offloaded_moments.
  • New as_dtensor_like in torchtitan/distributed/utils.py wraps a local shard as a DTensor with a parameter's mesh, placements, and shape. The offloaded moments use it, and so does EMA._materialize_dtensor, which had the same code. EMA behavior is unchanged (mechanical). The CUDA view of pinned memory still uses __cuda_array_interface__, because PyTorch has no API for it.

State dict

  • optimizer.state_dict() returns each moment as the CPU tensor over its pinned memory (a DTensor with the parameter's mesh and placements, built without a copy). OptimizersContainer.state_dict() goes through it, so every checkpointer sees CPU tensors and copies the moments on the CPU. On one Grace socket, a CPU copy runs at 362 GB/s with 32 threads; a CUDA copy between two host buffers is synchronous and runs at 45-47 GB/s. With torch_checkpointing async saves on the 64-GPU fake-PG run, the CUDA copies made the step after each save 1.5 s slower.
  • A load pre-hook swaps the CPU tensors back to the CUDA moments, so Optimizer.load_state_dict keeps them and does not move them to the GPU. Loaded values that are other tensors are first copied into the CUDA moments on the stream, after any pending optimizer step. DCP and torch_checkpointing load in place into the CPU tensors, so no copy happens there.
  • Device moments keep the default state dict and load behavior.
  • Checkpointers copy CPU tensors on the host, outside stream order. So state_dict() first waits for the current stream, and the copy starts only after the queued optimizer step has written the moments. This covers every checkpointer (DCP sync, async, and async_with_pinned_mem, and torch_checkpointing) and costs one device sync per save.

Checkpoint load

  • DCP loads into the pinned buffers, so load makes no temporary device copy.
  • load_flat_optim_state_dict calls Optimizer.load_state_dict under torch.optim.preserve_state_dtype_on_load() (Add Optimizer.preserve_state_dtype_on_load context manager pytorch#201779). Without it, load_state_dict casts bf16 moments to new fp32 tensors in GPU memory.
  • Buffer addresses never change, so a captured optimizer graph stays valid.
  • Checkpoints are interchangeable between any two fractions.
  • The bf16 moment load post-hook (restore_moment_dtype) is removed. Under preserve_state_dtype_on_load(), DCP loads into the bf16 moments and they keep their dtype, so the hook did nothing; before, load cast each bf16 device moment to a new fp32 GPU tensor and the hook cast it back. BF16_OPTIMIZER_STATES.md describes the load without it.

Lifetime

  • When the last tensor that uses a pinned buffer is freed, a device synchronize runs first, so in-flight kernels finish before the caching host allocator can reuse the memory.
  • The synchronize is skipped at interpreter exit.

Rejected with ValueError

  • A fraction outside [0, 1] (config time).
  • A fraction above 0 with fused=False (config time).
  • A fraction above 0 on an accelerator other than CUDA, including ROCm (config time). A host without an accelerator can still build the config, so CPU recipe tests work.
  • Offloaded params not on CUDA, such as fsdp_enable_cpu_offloading and create_seed_checkpoint runs (construction).
  • Non-contiguous local shards of offloaded params (construction). The error names the parameter.
  • Pinned memory rounded up by more than 1 GiB (construction).
  • TorchFT with a fraction above 0 (config time, in torchtitan/experiments/torchft/optimizer.py). Replica recovery loads a peer's state by assignment, which would replace the pinned moments with device tensors.

Docs

  • torchtitan/components/optim/CPU_OFFLOADED_MOMENTS.md: usage, how to choose the fraction, the allocator setting and its check, cost formula, NUMA binding, and requirements. The benchmark tables stay in this description.

Alternatives considered

  • PR [optim] Streamed optimizer-state CPU offload #5749 streams the moments through two GPU slots with side-stream copies. This change keeps them in place, so it needs no slot memory, no stream or event bookkeeping, and no custom state_dict/load_state_dict. It also uses 2 GiB less peak memory and gets +2.5% tps (table below).
  • Managed (pageable) host memory instead of pinned. In a GB300 copy microbenchmark (not a training run) it matched pinned. Pinned memory needs no ATS or page-migration support, so it does not depend on the host's paging behavior.

Numerics / performance

Cost on a run that fits both ways (Muse Spark 816B, muse_spark_816b_a42b_dist_moe_bf16_spmd_256_fake, 256-GPU fake PG, DP16/TP4/CP4/EP64, 96K, one GB300 GPU runs rank 0, NUMA-bound, steps 4-10):

device all offloaded
peak reserved memory 253.06 GiB 228.84 GiB (-24.2 GiB)
tps 3,301 3,273 (-0.85%)
AdamW per step (mean of steps 4-9) 26.2 ms 166.5 ms (about 1.1% of a 15 s step)

Losses follow the same curve (2.644 vs 2.641 at step 10).

Vs PR #5749 on a run that only fits with offload (Muse Spark 816B, 64-GPU fake PG, DP8/CP8/EP64, 32K, one GB300 GPU runs rank 0, NUMA-bound):

no offload PR #5749 this change
peak memory OOM in optimizer.step() 257.12 GiB 255.12 GiB
tps (steps 4-10) - 2,906 2,979
optimizer span (trace) - 932 ms 656 ms

Host link traffic:

  • Each step moves about 16 bytes per local parameter over the host link for fp32 moments.
  • On the 64-GPU run on one GB300 GPU, AdamW moves 2 x 104 GB. AdamW alone takes 0.63 s (about 330 GB/s), 5.8% of the step (one synchronized measurement). This is close to the host link limit.
  • NUMA binding matters when copies run in both directions. On GB300 with four GPUs busy and no NUMA binding, copies in both directions at once dropped about 2-2.5x, from 86-111 GB/s to 44 GB/s. Host-to-device copies alone dropped 1.0-1.8x.
  • With both GPUs of a Grace socket running the step at the same time, AdamW takes about 2x longer, because they share the socket's host bandwidth. The training step was only about 6% slower in that run.

Numerics: pinned host moments match device moments bitwise, for full and partial offload (Testing).

Testing

  • GPU unit test tests/unit_tests/gpu/components/optim/test_adam_cpu_offloaded_moments.py (2 GPUs, FSDP2, fp32 and bf16 moments). It catches: loss of bitwise parity with device moments for fractions 0.25 and 1.0, moments that use device memory, a broken empty shard, and a fraction that pins the wrong parameters (0.25 must pin exactly the first weight). It catches pinned memory silently rounded up to a power of two. It also checks DCP async save of mixed pinned and device moments with the checkpointer's stager options, and load into all-pinned and all-device moments. state_dict() must return CPU tensors over the pinned memory for offloaded moments. Load must keep the same buffers, restore values exactly, allocate no temporary device copy, copy other loaded tensors into the same buffers, keep the moment dtype, and continue training bitwise identically.
  • CPU unit test test_moment_options_checked_at_config_time. It catches bf16 or pinned host moments silently using a non-fused kernel, a fraction outside [0, 1], and pinned host moments on ROCm or another non-CUDA accelerator.
  • bf16 device-moment resume on 2xH100 is bitwise equal to the uninterrupted run.
  • Integration test: pp_dp_tp (FSDP2+TP2+PP2, save then resume) saves device moments and resumes with fraction 0.5, so half the moments go to pinned host memory, and skips ROCm. No existing CUDA-only integration test does save and resume, so this drops ROCm coverage of this PP+DP+TP save/resume test. full_checkpoint and optional_checkpoint keep device moments and still run save/resume on ROCm. pp_dp_tp needs 8 GPUs and was not run here. The 4-GPU bitwise resume checks below (FSDP2+TP2, PP2+FSDP2) cover the same paths.
  • Resume check with the trainer, on a 4-GPU host: llama3 debug model with flex attention, 10 steps, async_with_pinned_mem checkpoint at step 5, seed 42, deterministic, NCCL_ALGO=Ring NCCL_NVLS_ENABLE=0. Resuming from step 5 gives bitwise identical loss and grad_norm (TensorBoard) to the uninterrupted run. Pinned host moments match device moments bitwise. Checked for FSDP2, FSDP2+TP2, PP2+FSDP2, FSDP2 with bf16 moments, and FSDP2 with the optimizer CUDA graph. These runs and the performance numbers above used full offload with cudaHostRegister allocation; partial offload and the pin_memory allocation were checked only by the unit tests.

Known issues / follow-ups

  • Varlen attention and NVLS were not run-to-run deterministic in our runs, even with device moments. The resume checks use flex attention and NVLS off for that reason.
  • Needs a PyTorch nightly from 2026-10-30 or later for torch.optim.preserve_state_dtype_on_load (Add Optimizer.preserve_state_dtype_on_load context manager pytorch#201779). Every optimizer checkpoint load calls it, also with moment_cpu_offload_fraction=0. Older PyTorch raises AttributeError on resume. The release-validation jobs pin torch 2.15.0, so a torchtitan release with this change must validate against a newer torch.
  • Two TODOs mark private or undocumented PyTorch behavior (the DTensor(local, spec) constructor and __cuda_array_interface__ over pinned host memory); their upstream issues are not filed yet.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 6, 2026
@fegin fegin changed the title [optim] Keep Adam moments in pinned host memory (zero-copy) [optim] Keep Adam moments in pinned host memory without using any device memory Nov 6, 2026
fegin added a commit that referenced this pull request Nov 8, 2026
Stacked PRs:
 * #5882
 * #5881
 * #5880
 * __->__#5879


--- --- ---

## Summary (human-written)

With fake_pg, the tflops becomes `tflops // dp_mesh_size`. The reason is
that `allreduce` is an no-op but `dp_mesh_size` is a constant value not
affected by whether it is fake pg or real pg. This PR submit another row
that contains all 1 so that when doing real or fake `allreduce`, the
`tflops` is always accurate (fake pg tflops is pure computation).

## Why
Since #4819, the trainer logs the DP average of FLOPs as
`dist_sum(flops) / dp_mesh.size()`. On a fake process group the
all-reduce is a no-op, so the "sum" is only the local value, but it is
still divided by the DP size. Logged TFLOPS and MFU come out 1/DP of the
right value. Real process groups are not affected.

**Example.** DP8, each rank does 100 TFLOPS:

| | all-reduce sum | divided by | logged |
|---|---|---|---|
| real PG | 800 | 8 (mesh size) | 100 |
| fake PG, main | 100 | 8 (mesh size) | 12.5 (8x too low) |
| fake PG, this PR | 100 | 1 (summed count) | 100 |

## What changed
- New `dist_utils.dist_mean(x, mesh)`: all-reduces `[x, 1]` and returns
`sum / count`. On a real process group this equals `dist_sum(x) /
mesh.size()`. On a fake process group it returns the local value.
- `Trainer.train_step` and the RL trainer use it for the DP average of
FLOPs.

## Alternatives considered
- Log local FLOPs only: drops the DP average that #4819 added for
batches whose FLOPs differ across ranks.
- Check for the fake backend in the trainer: extra code for a case the
count already handles.

## Numerics / performance
- Loss and grad norm are unchanged. Logged FLOPs are unchanged on real
process groups.
- llama3 debug model, fake PG, NGPU=8 (DP8): FLOPs per token is 8.946e6
on main and 7.158e7 with this PR, matching the value before #4819.

## Testing
-
`test_trainer_accumulates_reused_accelerator_graph_losses[fake_dp=True]`
runs `train_step` on an 8-way fake DP mesh. On main it logs 75.0 instead
of 600.0.
- CPU tests for the trainer, distributed utils, FLOPs estimators, and
observability pass.

## Known issues / follow-ups
- The TorchFT trainer divides its FLOPs and loss sums by the mesh size
in the same way. Not changed here.
@fegin
fegin changed the base branch from fegin/stack/9 to main November 8, 2026 17:52
@pytorch-bot pytorch-bot Bot added the ciflow/rl label Nov 8, 2026
@fegin fegin changed the title [optim] Keep Adam moments in pinned host memory without using any device memory [optim] Keep Adam moments in pinned host memory (zero-copy) Nov 8, 2026
@fegin
fegin changed the base branch from main to fegin/stack/9 November 8, 2026 17:53
fegin added a commit that referenced this pull request Nov 8, 2026
)

Stacked PRs:
 * #5882
 * #5881
 * __->__#5880


--- --- ---

## Summary (human-written)
When running on an unkown hardware, TorchTitan just uses the peak flops
of A100, which is very confusing. Instead of using A100 peak flops, we
should just warn and not report.

## Why
`get_peak_flops` falls back to the A100 peak (312 TFLOPS) for any device
it does not list, from any vendor: a new NVIDIA, AMD, or Intel GPU, or
an unknown TPU version. On an unlisted device, MFU is then computed
against the wrong peak. The value looks plausible but is wrong, and on a
fast device it can go above 100%.

**Example.**

```text
GPU with 4x the A100 peak, running at 40% real MFU
before: Peak FLOPS used for computing MFU: 3.120e+14   ...   mfu: 160.00%
after:  WARNING Peak FLOPS unknown for <device name>. MFU is not reported.   ...   mfu: N/A
```

## What changed
- `get_peak_flops` returns None for an unknown GPU and for an unknown
TPU version, and logs a warning that MFU is not reported. Known devices
keep their values. The lspci H100 detection stays.
- `compute_training_performance_metrics` skips `mfu_percent` when the
peak is None. The metrics log already prints `mfu: N/A` and leaves out
`mfu(%)` when MFU is missing, as it does for quantized runs. TFLOPS is
still reported.
- The Trainer, RL trainer, and TorchFT trainer log "Peak FLOPS used for
computing MFU" only when the peak is known. The RL trainer already
reports `trainer/mfu_percent` only when it is present.
- Unchanged: an unknown AWS Neuron device still falls back to the
trn2/trn3 peak. That is a same-family estimate, not a different vendor's
peak, and it is out of scope here.

## Alternatives considered
- Keep the A100 fallback and only warn. The wrong MFU still reaches
dashboards, where the warning is not seen.
- Raise for an unknown device. That blocks training on new hardware only
for a metric.

## Testing
- `test_get_peak_flops` (CPU): H100 and A100 keep their values. An
unknown GPU name and an unknown TPU version give None. The unknown cases
catch a silent A100 fallback. lspci is mocked so the device name
decides.
- `test_compute_training_performance_metrics_without_peak_flops` (CPU):
with no peak, the metrics keep tokens per second and TFLOPS and have no
`mfu_percent`.
- CPU tests: tools utils, observability, trainer, TorchFT, and RL CPU
tests. The RL failures and collection errors also happen on main
(missing vllm, and an old `renderers` package).
@fegin
fegin changed the base branch from fegin/stack/9 to main November 8, 2026 17:55
@fegin
fegin force-pushed the fegin/stack/10 branch 2 times, most recently from 49312f2 to ae3972a Compare November 9, 2026 20:41
@fegin
fegin marked this pull request as ready for review November 9, 2026 20:44
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 9, 2026
@github-actions
github-actions Bot requested a review from weifengpy November 9, 2026 20:44
@fegin
fegin marked this pull request as draft November 9, 2026 20:46
@pytorch-bot pytorch-bot Bot removed the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 9, 2026
@fegin

fegin commented Nov 16, 2026

Copy link
Copy Markdown
Contributor Author

@claude re-review this PR. Since last approval, we change the state_dict hook to work with torch_checkpointing's async_checkpointing.

@claude

claude Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @fegin's task in 4m 6s —— View job


Approve -- please address the items below before merging (link the two TODOs to upstream issues): 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. The new CPU-tensor state_dict hooks keep identity on every in-repo load path, and they order host-side copies after the queued step. I found no correctness problem. One item from the last review is still open: the TODOs need upstream issue links.

What changed since the last approval. A state_dict post-hook (use_cpu_moments, optimizer.py:213) now returns each pinned_host moment as the CPU tensor (or CPU-local DTensor) over its pinned memory, after torch.accelerator.current_stream().synchronize(). A load_state_dict pre-hook (load_into_pinned_memory) puts the CUDA moments back into the state. If the loaded value is a different tensor, it is first copied into them on the stream.

Example.

sd = optimizers.state_dict()          # syncs the stream; sd["state.w.exp_avg"].device == cpu,
                                      # data_ptr() == the pinned buffer the fused kernel uses
manager.save(ckpt_id, {"optimizer": sd, ...})   # torch_checkpointing stages with CPU memcpy
                                                # (362 GB/s), not a sync CUDA H2H copy (45 GB/s)
dcp.load(sd, ...)                     # loads in place into the CPU tensors
optimizers.load_state_dict(sd)        # `saved is cpu_moment` -> no copy; state keeps CUDA views
optimizers.load_state_dict(other_sd)  # other tensors -> moment.copy_(saved) on the stream

Earlier items

  1. Upstream TODO for the __cuda_array_interface__ aliasing: partly resolved. optimizer.py:96 now has the TODO, but it says "upstream issue not filed yet". The new DTensor(host, moment._spec) TODO at optimizer.py:192 says the same.

Must fix

  1. torchtitan/components/optim/optimizer.py:96 and :192 -- file the two upstream issues (a host-mapped CUDA tensor, and a no-copy DTensor.from_local for a local tensor on another device) and link them in the TODOs. Core principle 3 asks for the link, so it is clear when _PinnedHostBuffer and the private constructor can go.

Should consider

  • tests/unit_tests/gpu/components/optim/test_adam_pinned_host_moments.py:156 -- the wait_stream is now redundant, and it hides a regression of the hook's sync (inline).

Questions

  • The hook change targets torch_checkpointing async saves. But the resume checks under Testing all use DCP async_with_pinned_mem. Was a torch_checkpointing save -> resume with pinned_host run? Two things depend on it. Its DefaultResharder has to load in place into CPU-local DTensors whose mesh is CUDA. And _load_checkpoint passes state_dict[key] (not loaded[key]) to load_state_dict, so a value that is not loaded in place would be ignored silently.
Details
  • Identity on load: _unflatten_optim_state_dict (utils.py:189) passes the flat_sd values through unchanged, so saved[key] is cpu_moment holds after an in-place DCP or torch_checkpointing load. Under preserve_state_dtype_on_load(), Optimizer.load_state_dict's .to(device=param.device) on the CUDA moment returns the same tensor, which matches the unit test's data_ptr check.
  • In-place host-side loads cannot race with a pending step. Every loader builds its target with optimizers.state_dict(), which now synchronizes first.
  • The sync covers accelerator-graph mode. AcceleratorGraphWrapper replays on the current stream (accelerator_graph.py:570), and its eager warm-up joins back with current_stream.wait_stream(...) (:408).
  • Sync cost: state_dict() is called per save, once for prewarm (torch_checkpointing.py:427), and once per load. There are no per-step callers in core. graph_trainer's extract_train_state would call it per step with an optimizer, but no in-repo graph_trainer path passes one (spmd_graph_builder.py:104).
  • The next step cannot overwrite moments while they are being staged. TrainingEngine.optim_step calls maybe_wait_for_staging() (training_engine.py:926), and torch_checkpointing implements it with self._manager.lock().
  • The OPTIMIZER item uses requires_copy=True (torch_checkpointing.py:146), so staging should copy CPU tensors rather than keep references (unverified, backend source not available here).

Not verified: GPU tests and the torch_checkpointing resume were not run. I could not read the installed DefaultStager/_StateDictStager (DCP async mode) or torch_checkpointing stager source to confirm that they copy CPU-source tensors. A maintainer still needs to review, since this touches core optimizer and checkpoint code.

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

some nit comments

Comment on lines +96 to +97
# TODO: Use a supported host-mapped CUDA tensor once PyTorch has one (upstream
# issue not filed yet). This relies on two undocumented behaviors: PyTorch

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.

please file an issue and link here

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.

Also I imagine some part of this file could be upstreamed to torch...

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Yes, will do this later, if core team agrees.

fegin added a commit that referenced this pull request Nov 17, 2026
…r graph capture (#6131)

Stacked PRs:
 * #6136
 * #6135
 * #6134
 * #6133
 * #6132
 * #5882
 * #5881
 * __->__#6131


--- --- ---

### [cudagraph] Remove the unsynchronized empty_cache() before
accelerator graph capture


## Summary (human-written)
There is a race condition if users do not call a sync after step() and
call empty_cache() before the next step().

For the current TorchTitan main, we do call sync in the end of each
iteration to gather the log. However, if we change the logging to async,
this race condition will be exposed.

The race condition happens like this:
```text
step 2 (eager): FSDP2 allocates the sharded grads on its reduce-scatter stream
                AdamW reading those grads is queued on the default stream
step 3:         zero_grad(set_to_none=True) frees the grads on the host
                -> the blocks return to the reduce-scatter stream's free pool
                empty_cache() unmaps free blocks of expandable segments, after
                syncing only the reduce-scatter stream
                -> the queued AdamW reads unmapped memory: illegal memory access
```

This PR fixes the issue by removing the wrapper's empty_cache(). The
graph
capture context (torch.cuda.graph / torch.accelerator.Graph) already
calls
synchronize() and then empty_cache() when it starts, so the extra call
is
not needed and the race is gone.

## Why
`AcceleratorGraphWrapper` calls `torch.accelerator.empty_cache()` right
before it captures a graph, without a sync. If the host runs ahead of
the device, this can unmap memory that a queued kernel still reads:

```text
step 2 (eager): FSDP2 allocates the sharded grads on its reduce-scatter stream
                AdamW reading those grads is queued on the default stream
step 3:         zero_grad(set_to_none=True) frees the grads on the host
                -> the blocks return to the reduce-scatter stream's free pool
                empty_cache() unmaps free blocks of expandable segments, after
                syncing only the reduce-scatter stream
                -> the queued AdamW reads unmapped memory: illegal memory access
```

On main, a blocking host-to-device copy of the token counts in
`Trainer.train_step` waits for the previous optimizer step before
`zero_grad`, so the host never gets this far ahead. "[trainer] Log
training metrics without waiting for the device", later in this stack,
removes that copy and exposes the crash: llama3 debug model, FSDP2 on 2
GPUs, `expandable_segments:True` (set by `run_train.sh`), crashes in
step 2-3 with varlen, flex, and CP2.

The call is not needed. The capture context that runs right after it,
`torch.cuda.graph` or `torch.accelerator.Graph`, already calls
`synchronize()` and then `empty_cache()` in `__enter__`.

## What changed
- Remove the wrapper's `empty_cache()` and its `before_empty_cache` /
`after_empty_cache` memory logs. The capture context releases the same
cache, after a device sync.
- `ACCELERATOR_GRAPH.md` says the capture context empties the cache.
- `test_preparation_runs_only_before_first_capture` (renamed) expects no
`empty_cache()` call from the wrapper.

The underlying gap is in PyTorch. FSDP2 orders the reuse of gradient
blocks with stream events, which covers normal allocations but not
`empty_cache()`. The expandable-segment unmap waits only for the stream
that allocated the block, while a plain `cudaFree` syncs the device. A
single-GPU repro without torchtitan crashes with expandable segments,
and passes with a `record_stream` before the free or a sync before
`empty_cache()`. The optimizer's first-step `empty_cache()` already
syncs first (#5019). The other call runs at startup.

## Testing
- With the host running ahead ("[trainer] Log training metrics without
waiting for the device"), llama3 debug model on 2 GPUs, `log_freq=10`,
20 steps: with the wrapper's unsynchronized call, varlen, flex, and CP2
each crash 3 of 3 runs; with it removed all pass 3 of 3. A GPU coredump
puts the fault in the fused AdamW kernel, on gradients in segments owned
by FSDP2's reduce-scatter stream.
- On another 4-GPU host the debug model does not get far enough ahead to
crash. With an ~80 ms GPU sleep added before each AdamW step, the
wrapper's unsynchronized call crashes 8 of 9 runs (varlen, flex, CP2)
and this change passes 9 of 9.
- Losses and grad_norm match a `CUDA_LAUNCH_BLOCKING=1` run of the same
config (varlen with `debug.deterministic=True`).

This change was written with an AI assistant (Claude).
@fegin
fegin marked this pull request as draft November 18, 2026 08:46
@fegin
fegin changed the base branch from fegin/stack/38 to main November 18, 2026 08:46
@pytorch-bot pytorch-bot Bot removed the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 18, 2026
@fegin
fegin force-pushed the fegin/stack/10 branch 2 times, most recently from db0c072 to ae3047d Compare November 18, 2026 08:47
@fegin
fegin changed the base branch from main to fegin/stack/44 November 18, 2026 08:47
@fegin
fegin marked this pull request as ready for review November 18, 2026 08:47
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 18, 2026

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

nice work! please address comments

)


def _as_dtensor_like(param: Tensor, local: Tensor) -> Tensor:

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.

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.

Unified but I feel it should belong to distributed/utils.py

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.

seems about Adam / AdamW only, not Muon which is quite different

  • Muon has one optimizer state, instead of two -- optimizer offloading is less profitable already
  • Muon is compute heavy, compared with mostly pointwise ops in Adam -- needs to perform NS ops on GPU, which means we need to reload; but also it provides opportunity of overlapping reload by compute

could revisit later

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 agree, Muon is interesting and may be able to overlap the fetching and saving with the computation. Another more generic design is to overlap optimizer state prefetching with backward and overlap writing-back with next forward. But whether this can be fully overlapped need some investigation.

@fegin
fegin marked this pull request as draft November 19, 2026 21:12
@fegin
fegin changed the base branch from fegin/stack/44 to main November 19, 2026 21:12
@pytorch-bot pytorch-bot Bot removed the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 19, 2026
@fegin
fegin changed the base branch from main to fegin/stack/44 November 19, 2026 21:13
@fegin
fegin changed the base branch from fegin/stack/44 to main November 19, 2026 22:16
## Summary (human-written)
This PR implements CPU offloading for fused Adam/AdamW. We keep the moments in
pinned memory and never allocate GPU memory for them. Instead, we feed the pinned
memory data pointer to the CUDA tensor. So the fused op will directly
use the tensor assuming the tensor data is on GPU memory.

So the CPU <-> GPU reads and writes and the computation are all initiated through one
single kernel. And the overlapping comes from the kernel pipeline
itself.

Compared to PR #5749, this approach requires less GPU memory and the
performance is better. See the **Alternatives** below.

We now use `preserve_state_dtype_on_load` in TorchTitan. This preserves
the dtype, so we don't need to install a hook for bf16 moments. The hook
also made a temporary fp32 copy of every moment in GPU memory during load.

## Why
Adam moments can be the last thing that does not fit on the GPU. Muse Spark 816B with DP8/CP8/EP64 and 32K sequence length runs out of memory in the first `optimizer.step()` with device moments. The check uses a fake process group (fake PG): one GB300 GPU runs rank 0 of a 64-GPU layout. Step 1 forward and backward finish, then Adam fails to allocate `exp_avg` (tried to allocate 512 MiB with 155 MiB free of 276.6 GiB). PR #5749 offloads the moments, but it streams them through two GPU slots with side-stream copies and needs a custom state_dict/load_state_dict.

This change keeps `exp_avg` and `exp_avg_sq` of a chosen share of the parameters in pinned CPU memory and exposes them to CUDA as tensors that alias that memory. The unchanged fused kernel reads and writes them in place over the host link.

**Example.**

```python
# Before: moments live on the GPU. The 64-GPU Muse Spark run OOMs in optimizer.step().
# After:
optimizers = config.optim.optimizer.optimizers
optimizers[0] = replace(optimizers[0], moment_cpu_offload_fraction=1.0)
# Launch with: PYTORCH_ALLOC_CONF="expandable_segments:True,pinned_max_round_threshold_mb:1" ./run_train.sh ...
# Moments use no GPU memory. The step stays one fused kernel launch on fixed addresses.
# A fraction such as 0.5 offloads only part of the moments and costs less step time.
```

## What changed
**Config**
- Adam and AdamW get `moment_cpu_offload_fraction: float` (default `0.0`). 0.0 keeps all moments on the device, 1.0 offloads all, and a value in between offloads that share of the local moment bytes.
- The unit is a whole parameter. Parameters are taken in optimizer order until the offloaded moment bytes reach the fraction of all local moment bytes. FSDP shards evenly and experts have equal sizes, so ranks usually pick the same parameters.
- Offloaded and device moments share one param group and one fused AdamW call.
- Add `pinned_max_round_threshold_mb:1` to `PYTORCH_ALLOC_CONF` when offloading moments (Moment allocation).
- `TrainingEngine` applies NUMA binding before any pinned allocation, so no launcher flag is needed.

**Moment allocation**
- The moments and `step` of offloaded parameters are created at optimizer construction. The moments are `torch.zeros(..., pin_memory=True)` CPU tensors; `step` stays a device tensor. The other parameters get device moments lazily, as before.
- There are no chunks, slots, side streams, or events. The step stays one kernel launch on fixed addresses and is CUDA-graph capturable.
- DTensor params get DTensor moments with the same mesh and placements, so DCP saves and reshards them like device moments.
- Empty shards are never offloaded. They need no memory.
- By default, PyTorch's caching host allocator rounds each allocation up to a power of two, using up to 2x host memory. `pinned_max_round_threshold_mb` (pytorch/pytorch#171662) turns that off above the threshold. With `pinned_max_round_threshold_mb:1`, allocations above 1 MB are pinned at their exact size. After allocating, the optimizer compares the pinned bytes in `torch.cuda.host_memory_stats()` with the requested bytes. If rounding wasted more than 1 GiB, it raises `ValueError` that names the setting to add (`pinned_max_round_threshold_mb:1` in `PYTORCH_ALLOC_CONF`).
- The offloading code lives in a new `torchtitan/components/optim/offloading.py`. `optimizer.py` only validates the config and calls `init_cpu_offloaded_moments`.
- New `as_dtensor_like` in `torchtitan/distributed/utils.py` wraps a local shard as a DTensor with a parameter's mesh, placements, and shape. The offloaded moments use it, and so does `EMA._materialize_dtensor`, which had the same code. EMA behavior is unchanged (mechanical). The CUDA view of pinned memory still uses `__cuda_array_interface__`, because PyTorch has no API for it.

**State dict**
- `optimizer.state_dict()` returns each moment as the CPU tensor over its pinned memory (a DTensor with the parameter's mesh and placements, built without a copy). `OptimizersContainer.state_dict()` goes through it, so every checkpointer sees CPU tensors and copies the moments on the CPU. On one Grace socket, a CPU copy runs at 362 GB/s with 32 threads; a CUDA copy between two host buffers is synchronous and runs at 45-47 GB/s. With torch_checkpointing async saves on the 64-GPU fake-PG run, the CUDA copies made the step after each save 1.5 s slower.
- A load pre-hook swaps the CPU tensors back to the CUDA moments, so `Optimizer.load_state_dict` keeps them and does not move them to the GPU. Loaded values that are other tensors are first copied into the CUDA moments on the stream, after any pending optimizer step. DCP and torch_checkpointing load in place into the CPU tensors, so no copy happens there.
- Device moments keep the default state dict and load behavior.
- Checkpointers copy CPU tensors on the host, outside stream order. So `state_dict()` first waits for the current stream, and the copy starts only after the queued optimizer step has written the moments. This covers every checkpointer (DCP sync, async, and async_with_pinned_mem, and torch_checkpointing) and costs one device sync per save.

**Checkpoint load**
- DCP loads into the pinned buffers, so load makes no temporary device copy.
- `load_flat_optim_state_dict` calls `Optimizer.load_state_dict` under `torch.optim.preserve_state_dtype_on_load()` (pytorch/pytorch#201779). Without it, `load_state_dict` casts bf16 moments to new fp32 tensors in GPU memory.
- Buffer addresses never change, so a captured optimizer graph stays valid.
- Checkpoints are interchangeable between any two fractions.
- The bf16 moment load post-hook (`restore_moment_dtype`) is removed. Under `preserve_state_dtype_on_load()`, DCP loads into the bf16 moments and they keep their dtype, so the hook did nothing; before, load cast each bf16 device moment to a new fp32 GPU tensor and the hook cast it back. `BF16_OPTIMIZER_STATES.md` describes the load without it.

**Lifetime**
- When the last tensor that uses a pinned buffer is freed, a device synchronize runs first, so in-flight kernels finish before the caching host allocator can reuse the memory.
- The synchronize is skipped at interpreter exit.

**Rejected with ValueError**
- A fraction outside [0, 1] (config time).
- A fraction above 0 with `fused=False` (config time).
- A fraction above 0 on an accelerator other than CUDA, including ROCm (config time). A host without an accelerator can still build the config, so CPU recipe tests work.
- Offloaded params not on CUDA, such as `fsdp_enable_cpu_offloading` and `create_seed_checkpoint` runs (construction).
- Non-contiguous local shards of offloaded params (construction). The error names the parameter.
- Pinned memory rounded up by more than 1 GiB (construction).
- TorchFT with a fraction above 0 (config time, in `torchtitan/experiments/torchft/optimizer.py`). Replica recovery loads a peer's state by assignment, which would replace the pinned moments with device tensors.

**Docs**
- `torchtitan/components/optim/CPU_OFFLOADED_MOMENTS.md`: usage, how to choose the fraction, the allocator setting and its check, cost formula, NUMA binding, and requirements. The benchmark tables stay in this description.

## Alternatives considered
- PR #5749 streams the moments through two GPU slots with side-stream copies. This change keeps them in place, so it needs no slot memory, no stream or event bookkeeping, and no custom state_dict/load_state_dict. It also uses 2 GiB less peak memory and gets +2.5% tps (table below).
- Managed (pageable) host memory instead of pinned. In a GB300 copy microbenchmark (not a training run) it matched pinned. Pinned memory needs no ATS or page-migration support, so it does not depend on the host's paging behavior.

## Numerics / performance
Cost on a run that fits both ways (Muse Spark 816B, `muse_spark_816b_a42b_dist_moe_bf16_spmd_256_fake`, 256-GPU fake PG, DP16/TP4/CP4/EP64, 96K, one GB300 GPU runs rank 0, NUMA-bound, steps 4-10):

| | device | all offloaded |
|---|---|---|
| peak reserved memory | 253.06 GiB | 228.84 GiB (-24.2 GiB) |
| tps | 3,301 | 3,273 (-0.85%) |
| AdamW per step (mean of steps 4-9) | 26.2 ms | 166.5 ms (about 1.1% of a 15 s step) |

Losses follow the same curve (2.644 vs 2.641 at step 10).

Vs PR #5749 on a run that only fits with offload (Muse Spark 816B, 64-GPU fake PG, DP8/CP8/EP64, 32K, one GB300 GPU runs rank 0, NUMA-bound):

| | no offload | PR #5749 | this change |
|---|---|---|---|
| peak memory | OOM in optimizer.step() | 257.12 GiB | 255.12 GiB |
| tps (steps 4-10) | - | 2,906 | 2,979 |
| optimizer span (trace) | - | 932 ms | 656 ms |

Host link traffic:
- Each step moves about 16 bytes per local parameter over the host link for fp32 moments.
- On the 64-GPU run on one GB300 GPU, AdamW moves 2 x 104 GB. AdamW alone takes 0.63 s (about 330 GB/s), 5.8% of the step (one synchronized measurement). This is close to the host link limit.
- NUMA binding matters when copies run in both directions. On GB300 with four GPUs busy and no NUMA binding, copies in both directions at once dropped about 2-2.5x, from 86-111 GB/s to 44 GB/s. Host-to-device copies alone dropped 1.0-1.8x.
- With both GPUs of a Grace socket running the step at the same time, AdamW takes about 2x longer, because they share the socket's host bandwidth. The training step was only about 6% slower in that run.

Numerics: pinned host moments match device moments bitwise, for full and partial offload (Testing).

## Testing
- GPU unit test `tests/unit_tests/gpu/components/optim/test_adam_cpu_offloaded_moments.py` (2 GPUs, FSDP2, fp32 and bf16 moments). It catches: loss of bitwise parity with device moments for fractions 0.25 and 1.0, moments that use device memory, a broken empty shard, and a fraction that pins the wrong parameters (0.25 must pin exactly the first weight). It catches pinned memory silently rounded up to a power of two. It also checks DCP async save of mixed pinned and device moments with the checkpointer's stager options, and load into all-pinned and all-device moments. `state_dict()` must return CPU tensors over the pinned memory for offloaded moments. Load must keep the same buffers, restore values exactly, allocate no temporary device copy, copy other loaded tensors into the same buffers, keep the moment dtype, and continue training bitwise identically.
- CPU unit test `test_moment_options_checked_at_config_time`. It catches bf16 or pinned host moments silently using a non-fused kernel, a fraction outside [0, 1], and pinned host moments on ROCm or another non-CUDA accelerator.
- bf16 device-moment resume on 2xH100 is bitwise equal to the uninterrupted run.
- Integration test: `pp_dp_tp` (FSDP2+TP2+PP2, save then resume) saves device moments and resumes with fraction 0.5, so half the moments go to pinned host memory, and skips ROCm. No existing CUDA-only integration test does save and resume, so this drops ROCm coverage of this PP+DP+TP save/resume test. `full_checkpoint` and `optional_checkpoint` keep device moments and still run save/resume on ROCm. `pp_dp_tp` needs 8 GPUs and was not run here. The 4-GPU bitwise resume checks below (FSDP2+TP2, PP2+FSDP2) cover the same paths.
- Resume check with the trainer, on a 4-GPU host: llama3 debug model with flex attention, 10 steps, async_with_pinned_mem checkpoint at step 5, seed 42, deterministic, NCCL_ALGO=Ring NCCL_NVLS_ENABLE=0. Resuming from step 5 gives bitwise identical loss and grad_norm (TensorBoard) to the uninterrupted run. Pinned host moments match device moments bitwise. Checked for FSDP2, FSDP2+TP2, PP2+FSDP2, FSDP2 with bf16 moments, and FSDP2 with the optimizer CUDA graph. These runs and the performance numbers above used full offload with `cudaHostRegister` allocation; partial offload and the `pin_memory` allocation were checked only by the unit tests.

## Known issues / follow-ups
- Varlen attention and NVLS were not run-to-run deterministic in our runs, even with device moments. The resume checks use flex attention and NVLS off for that reason.
- Needs a PyTorch nightly from 2026-10-30 or later for `torch.optim.preserve_state_dtype_on_load` (pytorch/pytorch#201779). Every optimizer checkpoint load calls it, also with `moment_cpu_offload_fraction=0`. Older PyTorch raises `AttributeError` on resume. The release-validation jobs pin torch 2.15.0, so a torchtitan release with this change must validate against a newer torch.
- Two TODOs mark private or undocumented PyTorch behavior (the `DTensor(local, spec)` constructor and `__cuda_array_interface__` over pinned host memory); their upstream issues are not filed yet.

stack-info: PR: #5881, branch: fegin/stack/10
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.

2 participants