Repository navigation
[optim] Streamed optimizer-state CPU offload - #5749
felipemello1 wants to merge 8 commits into
Conversation
Adam/AdamW moments live in pinned CPU slabs between steps. step() streams them through two GPU slots into the unchanged fused kernel, overlapping H2D, the update and D2H on separate streams. Opt-in through AdamW.Config(state_offload=OptimizerStateOffloader.Config(...)); off by default. Updates, checkpoint keys and values match the resident optimizer bitwise.
- Keep two copy streams: one stream is 13% slower (fp32) and 49% slower (bf16) per offloaded step on Qwen3-4B FSDP=2 shards on GB300; the docstring records both numbers. - Drop the NUMA binding call; launch with torchrun --numa-binding=node. - Replace chunk_size_mb with a module constant; Config has no fields. - Drop the try/finally restore; keep the side-stream synchronize. - Skip pinning an empty slab (a rank whose shards are all empty). - Shorter class docstring; call the GPU buffers slots everywhere. - Link the in-place pinning TODO to the PyTorch issue on in-place pinning. - Tests: drop the CPU rejection test; one parity test (fp32 and bf16 optimizers, plus one whose shard is empty on rank 1). - Enable state_offload in the full_checkpoint integration entry.
…chunk-size reason, unused test arg
|
Reply from claude: Upstream version of the fork prototype, rebased on main. Two fresh reviewers (bugs, simplicity) approved after 2 rounds. On GB300 (Qwen3-4B, FSDP 2): resident and offloaded moments train bitwise, checkpoint resume is bitwise, peak HBM 30.70 -> 18.62 GiB per rank for -21.8% tokens/s (fp32 moments). The @claude please review |
|
Claude finished @felipemello1's task in 6m 9s —— View job Needs discussion: maintainers need to decide whether this offload engine belongs in core |
There was a problem hiding this comment.
Verdict: Needs discussion -- the implementation is careful and the numerics claim is plausible, but maintainers need to decide whether a 359-line offload engine built on three private upstream APIs belongs in core components/optim, with no recipe that uses it yet. Two small code fixes are below.
What this PR does. OptimizerStateOffloader wraps a fused Adam/AdamW and shares its param_groups and state. It keeps exp_avg/exp_avg_sq in one pinned CPU slab per moment, as parameter-shaped DTensor views. In step() it packs params into ~256 MiB chunks. For each chunk it binds GPU slot views as the state, narrows the param groups to that chunk, and calls the unchanged inner step(), with loads and stores on two side streams. lr_scheduler.get_metrics unwraps it so the lr/AdamW/* keys stay the same.
Example.
AdamW.Config(pattern=r".*", state_offload=OptimizerStateOffloader.Config())
# Qwen3-4B, FSDP=2, fp32 moments (per the description):
# before: peak HBM 30.70 GiB/rank, 36182 tok/s/GPU
# after: peak HBM 18.62 GiB/rank, 28278 tok/s/GPU, plus 16.1 GB pinned host memory/rank
# checkpoint keys/values unchanged; an offloaded checkpoint loads into a resident run and backMust fix
- PR description: the "Summary (human-written)" section is empty. The author needs to write it (agents leave it as the placeholder).
torchtitan/components/optim/optim.py:88-- theenable_accelerator_graph+state_offloadguard is bypassed when either field is set after the config is constructed, which is how recipes andfeatures.pyset them. Move it into theenable_accelerator_graphbranch ofOptimizersContainer.__init__.torchtitan/components/optim/offload.py:351-- thefrom_dlpackworkaround for DCP's stager needs aTODOwith an upstream issue link.
Should consider
torchtitan/components/optim/offload.py:227-- a host sync on every step. Stream-order the slot frees and the next step's loads, and sync only where the slabs are read on the host (state_dict).torchtitan/components/optim/offload.py:52-- drop the benchmark numbers from the docstring.
Questions
- Consumer. The description says no recipe on main is memory-bound on optimizer state. Which workload will turn this on? Without a named recipe or user this is an option with no in-repo consumer. Please name one, or add it to the recipe that needs it.
- Layer. Principle 3 says moderate-to-large techniques belong upstream. This one depends on the private
DTensor(...)/DTensorSpecconstructor,torch.cuda._pin_memory_utils, and a DCP stager workaround. Should it live in torchao (next toCPUOffloadOptimizer), or as an optimizer-state-only mode of FSDP2'sOffloadPolicy, with torchtitan only adding the config field? That's a maintainer call.
Details
Checked and found no issue:
- Stream ordering. The first load waits on the compute stream, which covers slot memory the caching allocator hands back from pending compute work. A slot is reused only after its
slot_freeevent, recorded after the previous store. Each store waits on the compute stream after that chunk's Adam step. The slots are freed only after both side streams are synchronized. - State identity.
cpu_stateputs the original DTensor objects back after each chunk. Slab pointers stay stable throughload_state_dict, and torchft'scache_state_dictreferences stay valid. init_optim_state. State is allocated eagerly, so it is a no-op, and theisinstance(optim, (Adam, AdamW))reset inutils.py:72is never reached for the wrapper.- bf16 moments. The
initialize_momentspre-hook on the inner optimizer runs once per chunk and is a no-op because state already exists.restore_moment_dtypeis bypassed by theload_state_dictoverride, and the slab dtype is already right. - Hooks. Step hooks are registered on the container (MoE bias, aux loss, qk_clip), so they run once per step, not once per chunk.
- graph_trainer paged stash.
skips_step_on_found_infreturns False for the wrapper, so that path raises a clearValueError. Loud, and an experiment. - PP. Multiple model parts or optimizers each get their own offloader, streams and slabs. They step one after another, so peak HBM is set by the largest single pair of slots.
- Tests. Turning offload on in the existing
full_checkpointentry, rather than adding a new one, is the right shape. Resident optimizer resume is still covered by thefsdp2_tp2_pp2save/load entry, though with type checking off.
Not verified: the exact runtime failure when graph capture reaches step() (point 2), and the throughput effect of removing the per-step sync. Both need a GPU run. A maintainer still needs to review, since this touches core components/optim.
| if local.device.type == "cpu": | ||
| # A DTensor inherits its local's storage offset. DCP's async stager reads a non-zero | ||
| # data_ptr() as a dense tensor, so alias the slab view at offset 0. | ||
| local = torch.from_dlpack(local) |
There was a problem hiding this comment.
The from_dlpack alias works around DCP's async stager, which mishandles a CPU DTensor whose local tensor has a non-zero storage offset. That is an upstream DCP bug, and per the repo rules an upstream workaround needs a TODO with an issue link. Without one, nobody will know when this hack can go, and the next CPU-DTensor user in torchtitan will hit the same bug. Please file a pytorch/pytorch issue with a minimal repro (a slab view at offset > 0, wrapped as a DTensor, saved through DefaultStager(use_pinned_memory=True, use_shared_memory=True)) and reference it here, like the _pin_memory_utils TODO above does.
There was a problem hiding this comment.
Reply from claude: Added a TODO that names the stager bug: DCP's staging skips a tensor whose data_ptr() is 0 at _state_dict_stager.py:210,216, and a CPU DTensor view of a slab at a non-zero offset hits that check. It fails without async staging too. A minimal repro and an issue draft are ready for the author to file; the TODO gets the link once it exists.
- Test that build() rejects enable_accelerator_graph with state_offload set after the config is constructed: build() re-validates through replace(). - TODO at the from_dlpack alias naming the DCP DefaultStager bug and its repro. - Drop the benchmark numbers from the class docstring.
step() ended with a host synchronize on both copy streams. Now the compute stream waits for the D2H stream instead: later compute work that reuses the slots, and the next step's loads (which wait for the compute stream), run after every store. state_dict() and load_state_dict() wait for the pending stores before the host reads or writes the slabs. The graph-capture rejection stays, with the reason updated: step() picks its chunks on the host, and its first loads wait on events recorded outside the capture.
TorchFTOptimizersContainer.state_dict() returns cache_state_dict, and full saves read it. That skips OptimizerStateOffloader.state_dict(), which now waits for the last step's stores into the CPU moments, so a save could read them early. Reject the combination at config time; build() re-validates.
…e, smaller tests - Create the copy streams before the slabs, and have each slab's finalizer synchronize the D2H stream before unpinning, so dropping an offloader right after step() cannot free a slab under an in-flight store. - offloads_state(config): one predicate for "Adam/AdamW config with state_offload set", used by Optim.Config, OptimizersContainer and the torchft container config. - Guard test checks dataclasses.replace(config); the torchft test constructs the config inside assertRaisesRegex. - Docstring: read the CPU moments through state_dict() or after a device sync. - DCP TODO states the cause once, with keyword StagingOptions.
|
Claude finished @felipemello1's task in 3m 3s —— View job Needs discussion: the new commits fix or answer every code item from the last review and add no new problems. Two questions are still open for maintainers: which recipe will use this option, and whether the offload engine belongs in core |
There was a problem hiding this comment.
Verdict: Needs discussion -- the new commits fix or answer every code item from the last review and add no new defects, but the consumer and layer questions are still open, and only maintainers can settle them.
What changed since the last review (6863763, 151414a, 6322936, f6ad176). step() no longer waits on the host. It ends with compute_stream.wait_stream(d2h). state_dict() and load_state_dict() sync the D2H stream before the host touches the slabs, and the slab finalizer syncs it before unpinning. The torchft container now rejects state_offload at config time. One offloads_state() predicate backs all three checks. Mixed parameter dtypes under moment_dtype="parameter" now raise. The DCP-stager workaround has a TODO with a repro.
Example. For three offloaded AdamW groups in one container, before vs. after:
before: step() -> ... -> h2d.synchronize(); d2h.synchronize() # host blocks each step
after: step() -> ... -> compute.wait_stream(d2h) # host keeps going; next forward waits on GPU
checkpoint: get_flat_optim_state_dict -> offloader.state_dict() -> d2h.synchronize()
async staging: optim_step() calls checkpointer.maybe_wait_for_staging() first,
so the next step's stores can't race the stager's slab copy
Earlier items
- Resolved: the per-step host sync (should-consider), and the benchmark numbers in the docstring.
- Withdrawn: the
optim.py:88guard is not bypassed.Optim.Config.buildconstructs withreplace(self)(config/configurable.py:158,167), and that re-runs__post_init__. The engine always builds throughconfig.optim.build(...)(training_engine.py:463), so fields set after construction are still checked. My earlier finding was wrong. - Still open: the PR description's "Summary (human-written)" section is empty. Only the author can write it.
- Still open, small: the
offload.pyDCP-stager TODO needs the pytorch/pytorch issue link once the issue is filed.
Must fix
- Consumer. No in-repo recipe enables
state_offload. Thefull_checkpointintegration entry is test coverage, not a user. Name the workload that needs it, or turn it on in the recipe that does. Otherwise this is a new option with no consumer (CLAUDE.md principle 2).
Questions
- Layer (for maintainers). This is a ~380-line offload engine built on the private
DTensor(...)/DTensorSpecconstructor,torch.cuda._pin_memory_utils, and a DCP stager workaround. Does it belong in corecomponents/optim, or upstream (torchao next toCPUOffloadOptimizer, or an optimizer-state-onlyOffloadPolicyin FSDP2), with torchtitan adding only the config field?
Details
Checked in the new stream ordering, no issue found:
- Slot lifetime. Slots are allocated on the compute stream and dropped when
step()returns, aftercompute.wait_stream(d2h). The caching allocator reuses a block only for allocations on its own stream, and every later compute-stream use is ordered after the last store. Every H2D load was already waited on by the compute stream, so the H2D stream needs no join. - Next step's loads. At the top of
step(),h2d.wait_stream(compute)runs, and the compute stream already waited on the previous stores, so a load can't read a slab before the last store into it lands. - Host writes in
load_state_dict. Syncing D2H is enough. Each store waits on a compute stream that waited on every load, so no load from the last step is still running. - Async checkpoint.
get_flat_optim_state_dictcallsoptim.state_dict()(utils.py:98), which is the wrapper's synced override.optim_stepcallsmaybe_wait_for_staging()before the next update (training_engine.py:891), so background staging of the slabs finishes before new stores start. - Hook bypass. The wrapper's
state_dict()skips post-hooks registered on the inner optimizer. The only such hook,_save_host_lr, exists only underenable_accelerator_graph, which offload bans. - torchft check.
TorchFTOptimizersContainer.Config.__post_init__doesn't shadow a parent check, becauseOptimizersContainer.Configdefines none. - Several offloaders in one container. Each one's loads wait on the compute stream, which waits on the previous offloader's last store, so offloaders don't overlap each other. This affects throughput only.
Not verified: GPU runs of the new stream ordering (no GPU here). I checked it by reading the code against the caching-allocator and stream semantics. A maintainer still needs to review, since this touches core components/optim.
One sentence in the OptimizerStateOffloader docstring: use it when Adam's moments decide whether training fits, for example when a run needs full activation checkpointing only to make room for the moments that appear at the first step.
|
Reply from claude: Answers to the 23:09 review. Head is now 9f54966 (one docstring sentence on when to use offload); the description names the consumer and adds the TP results. Consumer Agreed, a CI entry is not a user. Proposed consumer: Its docstring already names the problem. Full activation checkpointing is required only because Adam's moments appear at the first Per trainer GPU (27.9B params, FSDP=3 x TP=2, fp32 master weights):
So the recipe can drop full recompute. That recipe uses TP, so we ran offload under TP on this head: llama3 debugmodel, 10 steps, TP=2 on 2 GPUs and FSDP=2 x TP=2 on 4 GPUs. In both, offload matches resident moments bitwise: loss and grad_norm on every step, a resume from the offloaded step-5 checkpoint, and all 156 tensors of the step-10 checkpoints. Plan:
Cost to weigh: the copies took ~0.47 s per step for 14.8 GB of moments per rank (Qwen3-14B, 8x H100, DP=4 TP=2, earlier version of this PR). Scaled to 37 GB, that is ~1.2 s per step. Full recompute costs about a quarter of the trainer's compute. The run decides. Second candidate: Layer We think core
If you'd rather have it upstream later, the closest fit is @claude please review |
|
Claude finished @felipemello1's task in 1m 55s —— View job Needs discussion: the consumer and layer answers check out, but maintainers should decide whether the option lands before the |
There was a problem hiding this comment.
Verdict: Needs discussion -- I checked the consumer and layer answers against the code and they hold. One decision is left for maintainers: should the option land before the recipe run that shows the named consumer actually benefits?
What changed since the last review (9f54966). One docstring paragraph in offload.py that says when to use the offloader. The description now names rl_grpo_muse_glimmer_30b_search_r1 as the consumer and adds TP / FSDP x TP bitwise results. No other code changed, so this review covers only the two open questions.
Example. Per trainer GPU for the named recipe, checked against torchtitan_recipes/rl/search_r1.py:354 and the 30B flavor (dim=6656, vocab_size=202048, FSDP=3 x TP=2):
moments: 27.9B x 8 B / 6 = 37.2 GB = 34.6 GiB (the recipe docstring says "~37 GB/GPU")
largest slot: 202048 x 6656 / 6 x 8 B = 1.67 GiB (embedding, and the untied SoftCapped head)
step 1 today: fwd/bwd without moments, then step() allocates 34.6 GiB -> fits
step 2 today: fwd/bwd with 34.6 GiB resident -> OOMs under default remat
step 2 with offload: fwd/bwd same as step 1; step() adds 2 x 1.67 GiB, after activations are freed
Step 1 already shows that step() has room for the full moments. So step 2 with offload should fit with default remat, apart from fragmentation (unverified).
Earlier items
- Consumer: answered. The workload is named, and its memory problem is documented in the recipe itself. The numbers above check out.
- Layer: answered. FSDP2's
OffloadPolicyplaces params, not optimizer state. torchao'sCPUOffloadOptimizerruns Adam on the CPU and is single-GPU. Neither one can take this design without a new API. Each private-API use has a TODO. - Still open: the "Summary (human-written)" section is empty. Only the author can write it.
- Still open: the TODO at
offload.py:369needs the pytorch/pytorch issue link once the issue is filed.
Questions
- Land the recipe change in this PR, or after it? (maintainers) The plan puts the
search_r1change in a follow-up because it needs an 8x H100 run pair. That run also tests whether offload is worth it there. By the author's estimate, offload costs ~1.2 s per trainer step (0.47 s for 14.8 GB on H100, scaled to 37 GB). Full recompute costs roughly a quarter of trainer compute. Offload only wins if the trainer step is longer than about 5 s. If it is shorter, the recipe keeps full AC, and this option has no consumer again. I recommend running the pair first and putting the recipe change (state_offload=..., dropFullActivationRematConfig, update the docstring) in this PR, or in a stacked PR merged with it. It's 3 lines, and it makes the option land together with its consumer.
Details
- The recipe builds its optimizer through
Optim.Config->OptimizersContainer.Config, the same path the PR's guards and build branch cover.TrainingConfig.disable_accelerator_graphs=Truein the recipe is separate fromOptim.enable_accelerator_graph, so the graph-capture ban isn't hit. - Host memory for the recipe: 6 trainer ranks x 37.2 GB = ~223 GB pinned, on the same host as vLLM and the retrieval server. That fits a typical 8x H100 node, but it's worth recording peak host RSS in the run pair.
- The second candidate (
moment_dtype="bfloat16"recipes) is plausible, but it is not needed to justify the option.
Not verified: the step-2 fit and the trainer step time for search_r1 (needs the 8x H100 run). A maintainer still needs to review, since this touches core components/optim.
|
Reply from claude: We can't run 8x H100 here, so we reproduced the regime on GB300: a run that needs full activation checkpointing only because Adam's moments don't fit. Setup: Qwen3-8B SFT (
Speed is the mean of steps 6-15 without steps 6 and 14, which are ~4 s slower in every arm, main included. With them, offload + default remat is +9.1% over today (22,482 vs 20,598). What this shows:
What it can't show: the H100 answer. Here the copies go over NVLink-C2C at ~90 GB/s per direction. Our earlier H100 run copied at ~32 GB/s over PCIe, 2.8x slower. H100 also has 2.5x less bf16 compute (989 vs 2,500 TFLOPS), so the recompute that offload saves is slower too. For the same tokens per step, copy time over recompute time is only ~12% worse on H100. That ratio falls as a step trains more tokens. Scaling this run's numbers, offload should win on H100 once a step trains more than ~50-90k tokens (the range covers 40-65% hardware utilization). That is an estimate. RL steps vary in length, so for On landing: this run shows the option pays in the regime it targets, on the hardware we have. The @claude please review |
|
Claude finished @felipemello1's task in 1m 29s —— View job Needs discussion: the GB300 run shows offload pays off in the regime it targets, but it used a modified config rather than an in-repo recipe, so maintainers still need to decide whether to land before the |
There was a problem hiding this comment.
Verdict: Needs discussion -- the GB300 run shows offload pays off in the regime it targets, but the run used a modified config, not an in-repo recipe. So landing the option before the search_r1 H100 pair is still a maintainer call.
What changed since the last review. No code changes: head is still 9f54966. The new evidence is a Qwen3-8B SFT run on 2 GB300 (FSDP=2, fp32 moments, 73,728 tokens per rank per step). I checked the arithmetic and it holds. Moments: 8.19B x 8 B / 2 = 32.8 GB = 30.5 GiB. Copies: 32.8 GB each way in 0.36 s, about 91 GB/s. Offload + full AC saves 30.5 GiB at peak (99.9 -> 69.4), which matches the moments minus the slots.
Example. The trade, as measured:
resident + full AC 99.9 GiB 23,242 tok/s/GPU 3.17 s <- "today" in the table
resident + default remat 271.2 GiB 8,107 tok/s/GPU 9.21 s 70 allocator retries
offload + default remat 259.4 GiB 25,681 tok/s/GPU 2.87 s copies +0.36 s, recompute -0.66 s
Must fix
- PR description: the "Summary (human-written)" section is still empty. Only the author can write it.
- PR description, "In the regime it targets": the bullet says
sft_qwen3_8b_mathresident moments "need full AC". The recipe on main uses neither:torchtitan_recipes/tests/models/qwen3.py:673,697setsnum_tokens_per_microbatch_per_dp_rank=1 * max_context_lengthandDefaultActivationRematConfig(). Say that the token count and the full-AC baseline were overridden for the run, so nobody reads it as a second in-repo consumer.
Still open from earlier reviews
- The DCP-stager TODO in
offload.pystill needs the pytorch/pytorch issue link once the issue is filed.
Questions
-
Land before or after the
search_r1pair? (maintainers) Using the author's own model, here is an estimate of wheresearch_r1falls (unverified, and it treats the moments-vs-recompute ratio as the only thing that changes):- Copy time scales with moment bytes per GPU, which is P x 8 / num_GPUs. Recompute time scales with P x tokens per DP rank / TP.
- So the break-even tokens per DP rank scale with TP / num_GPUs. Qwen3-8B at FSDP=2 gives 1/2.
search_r1at FSDP=3 x TP=2 gives 2/6. - The author's 50-90k tokens H100 break-even therefore becomes about 33-60k tokens per DP rank for
search_r1. search_r1trains at most 8 prompts x 8 samples x 4096 tokens / 3 DP ranks = ~87k tokens per DP rank per step (search_r1.py:398-399,421).- Offload wins there only if the mean rollout is longer than roughly 1.6-2.8k tokens. That's plausible for multi-turn search, but not certain, so the H100 pair is still the deciding run.
If maintainers want a consumer in the same PR, the stacked 3-line recipe change after the pair is still my recommendation.
Not verified: GPU numbers (no GPU here), and the search_r1 mean rollout length. A maintainer still needs to review, since this touches core components/optim.
|
Reply from claude: Fixed the "In the regime it targets" bullet: it now says the run overrides |
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.
Summary (human-written)
Agent details
Written with Claude Code: the analysis, measurements and test plan below.
Needs retesting on H100. All numbers are from GB300, where CPU-GPU copies ran at ~90 GB/s per direction. An earlier H100 run copied at ~32 GB/s (PCIe), so copies would take ~2.8x longer there.
TLDR: A new opt-in flag keeps Adam/AdamW's moments in pinned CPU memory between steps.
optimizer.step()streams them through the GPU in chunks. Updates are bitwise identical to today's.Problem
exp_avgandexp_avg_sqfor every weight: 8 bytes per parameter in fp32, 4 withmoment_dtype="bfloat16".optimizer.step()reads them.rl_grpo_muse_glimmer_30b_search_r1turns on full activation checkpointing (full AC) only to make room for the moments. Its docstring: they add ~37 GB per GPU at the first step, and default remat then runs out of memory at step 2.Estimated per trainer GPU (FSDP=3 x TP=2, fp32): params 17.3 + grads 17.3 + moments 34.6 = 69.2 GiB of an 80 GB H100. Offload frees 31.2 GiB of it.
Solution
step()streams them in chunks (whole parameter shards, ~256 MiB of moments) through two GPU slots into the unchanged fused Adam kernel.step()ends with the compute stream waiting for the last store.state_dict()andload_state_dict()wait for it before the CPU touches the moments.state_offloadonAdam.Config/AdamW.Config. DefaultNonekeeps today's path.Results
Numerics: bitwise identical to resident moments (loss, grad_norm, params, moments, checkpoints). Why: the same fused AdamW kernel runs on the same values; only where the moments wait between steps changes.
step()that ended with a host wait. The final one has none: same memory, +3.9% tokens/s with metrics every 4 steps (one run each).sft_qwen3_8b_math, overriding the tokens per microbatch (recipe: one context length) and the remat policy per arm (recipe: default). Random init, accelerator graphs off.You may ask:
Adam/AdamW? Neither class changes. The wrapper narrows their param groups to one chunk per innerstep().training.enable_cpu_offload? It also moves params and grads, and runs Adam on the CPU.lr_scheduler.pychange? LR metric keys use the optimizer class name. Without it,lr/AdamWbecomeslr/OptimizerStateOffloader.Optim.enable_accelerator_graph?step()picks chunks on the host, and its first loads wait on events recorded outside the capture. A capture probe on GB300 fails on such a wait.state_offload? Its full saves readcache_state_dict, which skipsOptimizerStateOffloader.state_dict()and its wait for the last stores.torch.from_dlpackon the CPU state? DCP'sDefaultStagerfails on a DTensor whose local tensor starts at a storage offset > 0. The alias starts at 0. The TODO in_state_likeholds the repro.NOTE:
torchrun --numa-binding=node, so the pinned buffers sit on the GPU's NUMA node. An H100 run of an earlier version lost 17% tokens/s without it.training.enable_cpu_offloadandcreate_seed_checkpointruns.search_r1recipe (8 H100s and a retrieval server), the 4-GPUfull_checkpointintegration test (run on 2 GPUs).Follow up
search_r1: turn it on and drop full AC, after one 8x H100 run pair (today vs offload + default remat).step().Test plan
The
full_checkpointintegration entry now setsstate_offload, so CI saves and resumes an offloaded run (also themodel_only_hf_checkpointandlast_save_model_only_bf16entries built from it).