Skip to content

Add Optimizer.preserve_state_dtype_on_load context manager - #201779

Closed
janeyx99 wants to merge 7 commits into
gh/janeyx99/421/basefrom
gh/janeyx99/421/head
Closed

janeyx99 wants to merge 7 commits into
gh/janeyx99/421/basefrom
gh/janeyx99/421/head

Conversation

@janeyx99

@janeyx99 janeyx99 commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #201669

The previous approach jumped straight to BC breakage, which is very risky given that there are likely people who rely on the existing behavior for their training. For example, if you load bf16 optimizer state for a fp32 model or the other way around.

So! The new approach moves this into a deprecation, and adds a new context manager that would allow people to silence the deprecation warning + opt into the behavior that preserves the state dtype of the checkpoint, as desired in #201669.

With ZeRO, we maintain existing behavior and silence warnings.

Stack from ghstack (oldest at bottom):

Details

OLLDLDDDDD:
saved for future PR that will BC break:

BC-breaking note

Optimizer.load_state_dict() now preserves the saved dtype of non-step state tensors and only moves them to the parameter’s device. Previously, loading would also cast these tensors to the parameter dtype.

When resuming with a different parameter dtype, users must be careful to explicitly convert any optimizer state that requires matching with parameter dtype. Otherwise, the next optimizer step may silently run with unintended type promotion or raise dtype mismatch errors, e.g.:

RuntimeError: expected dtype float for `end` but got dtype c10::BFloat16

The existing special handling of step tensors is unchanged. On load, step keeps its saved dtype and device unless the parameter group is fused or capturable, in which case it becomes FP32 on the parameter’s device.

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Oct 22, 2026 •

Copy link
Copy Markdown

PR Status: Approved 🚀

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

✅ AUTOMATED REVIEW - Ready for human review:

The PR adds a public
`torch.optim.preserve_state_dtype_on_load(preserve_dtype=True)` context manager,
backed by a ContextVar, that keeps checkpoint dtypes for non-step state in
`Optimizer.load_state_dict`; when the default load cast changes a dtype it now
emits a FutureWarning. The review found no code issues. Recommendation: Approve.

Findings (1):

[minor] torch/optim/optimizer.py:1078
Housekeeping item outside the diff (the earlier automated review also raised it,
and it is still open): the PR description still has a `### BC-breaking note`
inside the "saved for future PR" `<details>` block. That note describes
behaviour this PR does not ship. ghstack turns the description into the commit
message, so trim the block before landing.

Reviewed commit: 33ba737

Review run

🔗 Helpful Links

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

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

❗ 1 Active SEVs

There are 1 currently active SEVs. If your PR is affected, please view them below:

✅ No Failures

As of commit 33ba737 with merge base 25298e6 (image):
💚 Looks good so far! There are no failures yet. 💚

🟡 GREEN LIGHT - OUTDATED (earlier commit) - PR requires human review:

  • Never trivial: deprecation and dtype numerics
    • Optimizer.load_state_dict in torch/optim/optimizer.py now emits a FutureWarning announcing that the default state-dtype cast will change
    • _process_value_according_to_param_policy skips the dtype cast when the new ContextVar is set, so loaded optimizer state precision changes
  • New public API
    • Adds torch.optim.preserve_state_dtype_on_load to torch/optim/__init__.py __all__ and to docs/source/optim.md, so a human should review the design
  • Cross-subsystem behavior
    • ZeroRedundancyOptimizer.load_state_dict wraps super().load_state_dict in the new context to suppress the warning
    • The automated review raised concerns about ZeRO policy semantics, and the author declined them in the PR comments; a human should settle that

reason: not_trivial
Reviewed commit: 2e92a6e (NOT the current head 33ba737)

Inference job

🐛 Report a wrong verdict

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

@janeyx99
janeyx99 marked this pull request as draft October 22, 2026 22:34
[ghstack-poisoned]
janeyx99 added a commit that referenced this pull request Oct 22, 2026
@janeyx99 janeyx99 changed the title fix 201669, do not cast state to param dtype in load_state_dict Optimizer.load_state_dict now respects user state dtype (vs always casting to param dtype) Oct 22, 2026
@janeyx99 janeyx99 changed the title Optimizer.load_state_dict now respects user state dtype (vs always casting to param dtype) Optimizer.load_state_dict now respects saved state dtype (vs casting to param dtype) Oct 22, 2026
@janeyx99
janeyx99 marked this pull request as ready for review October 22, 2026 23:27
@janeyx99 janeyx99 added the topic: bc breaking topic category label Oct 22, 2026
@pytorchbot pytorchbot added the in progress PR is being worked on by the author, until the automated review accepts it label Oct 22, 2026
github-actions[bot]

This comment was marked as outdated.

@janeyx99 janeyx99 changed the title Optimizer.load_state_dict now respects saved state dtype (vs casting to param dtype) Add Optimizer.preserve_state_dtype_on_load context manager Oct 24, 2026
[ghstack-poisoned]
janeyx99 added a commit that referenced this pull request Oct 24, 2026
@janeyx99 janeyx99 added topic: deprecation topic category and removed topic: bc breaking topic category labels Oct 24, 2026
github-actions[bot]

This comment was marked as outdated.

[ghstack-poisoned]
janeyx99 added a commit that referenced this pull request Oct 26, 2026
github-actions[bot]

This comment was marked as outdated.

[ghstack-poisoned]
@janeyx99
janeyx99 requested a review from weifengpy as a code owner October 26, 2026 19:55
janeyx99 added a commit that referenced this pull request Oct 26, 2026
@pytorch-bot pytorch-bot Bot added the ciflow/torchtitan Run TorchTitan integration tests label Oct 26, 2026
github-actions[bot]

This comment was marked as outdated.

@github-actions
github-actions Bot dismissed stale reviews from themself October 26, 2026 20:01

Withdrawn: the automated review of 4a0c60d found nothing blocking.

@pytorchgreenlight pytorchgreenlight Bot added the GL/human GreenLight marked as needing human review label Oct 27, 2026
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

The merge job was canceled or timed out. This most often happen if two merge requests were issued for the same PR, or if merge job was waiting for more than 6 hours for tests to finish. In later case, please do not hesitate to reissue the merge command
For more information see pytorch-bot wiki.

@janeyx99

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

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

Learn more about merging in the wiki.

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

Advanced Debugging
Check the merge workflow status
here

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge failed

Reason: 1 jobs have failed, first few of them are: trunk / macos-py3-arm64 / test (mps, 1, 1, macos-m2-15)

Details for Dev Infra team

Raised by workflow job

janeyx99 added a commit that referenced this pull request Oct 28, 2026
@pytorchgreenlight pytorchgreenlight Bot added GL/superseded GreenLight review is superseded by changes and removed GL/human GreenLight marked as needing human review labels Oct 28, 2026

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Automated review of 33ba737: nothing blocking; ready for human review.

The PR adds a public torch.optim.preserve_state_dtype_on_load(preserve_dtype=True) context manager, backed by a ContextVar, that keeps checkpoint dtypes for non-step state in Optimizer.load_state_dict; when the default load cast changes a dtype it now emits a FutureWarning. The review found no code issues. Recommendation: Approve.

⚪ 1 non-blocking finding

"Optimizer.load_state_dict currently casts non-step state tensors to "

Housekeeping item outside the diff (the earlier automated review also raised it, and it is still open): the PR description still has a ### BC-breaking note inside the "saved for future PR" &lt;details&gt; block. That note describes behaviour this PR does not ship. ghstack turns the description into the commit message, so trim the block before landing.

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

@pytorch-bot pytorch-bot Bot added ready for review Automated review passed, ready for a final review by a maintainer. and removed in progress PR is being worked on by the author, until the automated review accepts it labels Oct 29, 2026
@janeyx99

Copy link
Copy Markdown
Contributor Author

mergedog handoff

Note

This PR is being shepherded by mergedog, an automation tool run by a maintainer. It watches CI and may push fixes; the PR author does not need to act unless a maintainer asks.

All CI is green (or skipped). Ready for human review and @pytorchbot merge.

Current PR head: 2e92a6e213d9269ae80fb257c9e9068f1a88d94e.

Autonomous changes pushed

  • None.

During shepherding, the configured LLM was invoked 1 time. If any CI shows red, it judged that failure unrelated to this PR's changes — please verify below before merging.

Session 1 — fix-CI (2026-10-28T20:19:47+00:00)

  • Before: b10c6c94f471
  • Verdict: exited with a contract violation
LLM transcript

@janeyx99

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

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

Learn more about merging in the wiki.

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

Advanced Debugging
Check the merge workflow status
here

dominikjastrzebskix pushed a commit to dominikjastrzebskix/pytorch that referenced this pull request Nov 5, 2026
…01779)

Fixes pytorch#201669

The previous approach jumped straight to BC breakage, which is very risky given that there are likely people who rely on the existing behavior for their training. For example, if you load bf16 optimizer state for a fp32 model or the other way around.

So! The new approach moves this into a deprecation, and adds a new context manager that would allow people to silence the deprecation warning + opt into the behavior that preserves the state dtype of the checkpoint, as desired in pytorch#201669.

With ZeRO, we maintain existing behavior and silence warnings.

<details>

OLLDLDDDDD:
saved for future PR that will BC break:

### BC-breaking note

`Optimizer.load_state_dict()` now preserves the saved dtype of non-step state tensors and only moves them to the parameter’s device. Previously, loading would also cast these tensors to the parameter dtype.

When resuming with a different parameter dtype, users must be careful to explicitly convert any optimizer state that requires matching with parameter dtype. Otherwise, the next optimizer step may silently run with unintended type promotion or raise dtype mismatch errors, e.g.:
```
RuntimeError: expected dtype float for `end` but got dtype c10::BFloat16
```

The existing special handling of step tensors is unchanged. On load, step keeps its saved dtype and device unless the parameter group is `fused` or `capturable`, in which case it becomes FP32 on the parameter’s device.

</details>

Pull Request resolved: pytorch#201779
Approved by: https://github.com/albanD, https://github.com/weifengpy
dominikjastrzebskix pushed a commit to dominikjastrzebskix/pytorch that referenced this pull request Nov 9, 2026
…01779)

Fixes pytorch#201669

The previous approach jumped straight to BC breakage, which is very risky given that there are likely people who rely on the existing behavior for their training. For example, if you load bf16 optimizer state for a fp32 model or the other way around.

So! The new approach moves this into a deprecation, and adds a new context manager that would allow people to silence the deprecation warning + opt into the behavior that preserves the state dtype of the checkpoint, as desired in pytorch#201669.

With ZeRO, we maintain existing behavior and silence warnings.

<details>

OLLDLDDDDD:
saved for future PR that will BC break:

### BC-breaking note

`Optimizer.load_state_dict()` now preserves the saved dtype of non-step state tensors and only moves them to the parameter’s device. Previously, loading would also cast these tensors to the parameter dtype.

When resuming with a different parameter dtype, users must be careful to explicitly convert any optimizer state that requires matching with parameter dtype. Otherwise, the next optimizer step may silently run with unintended type promotion or raise dtype mismatch errors, e.g.:
```
RuntimeError: expected dtype float for `end` but got dtype c10::BFloat16
```

The existing special handling of step tensors is unchanged. On load, step keeps its saved dtype and device unless the parameter group is `fused` or `capturable`, in which case it becomes FP32 on the parameter’s device.

</details>

Pull Request resolved: pytorch#201779
Approved by: https://github.com/albanD, https://github.com/weifengpy
fegin added a commit to pytorch/torchtitan that referenced this pull request Nov 23, 2026
Stacked PRs:
 * #6252
 * #5746
 * #6135
 * #6134
 * #6133
 * #6132
 * #5882
 * __->__#5881


--- --- ---

### [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.**

```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.
submartingales pushed a commit to botcanlearn/torchtitan-upstream that referenced this pull request Nov 23, 2026
## 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: pytorch/torchtitan#5881, branch: fegin/stack/10
submartingales pushed a commit to botcanlearn/torchtitan-upstream that referenced this pull request Nov 23, 2026
## 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`. 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: pytorch/torchtitan#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/torchtitan Run TorchTitan integration tests ciflow/trunk Trigger trunk jobs on your pull request GL/superseded GreenLight review is superseded by changes Merged ready for review Automated review passed, ready for a final review by a maintainer. release notes: optim topic: deprecation topic category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants