Skip to content

[optim] Streamed optimizer-state CPU offload - #5749

Closed
felipemello1 wants to merge 8 commits into
mainfrom
felipemello1/opt-state-offload
Closed

felipemello1 wants to merge 8 commits into
mainfrom
felipemello1/opt-state-offload

Conversation

@felipemello1

@felipemello1 felipemello1 commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

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.

  • Qwen3-4B, FSDP=2, 2 GB300: peak GPU memory 30.7 -> 18.6 GiB per rank, for 22% fewer tokens/s.
  • If the freed memory lets a run drop full activation checkpointing, the run gets faster: Qwen3-8B SFT +10.5% tokens/s.
AdamW.Config(pattern=r".*", state_offload=OptimizerStateOffloader.Config())

Problem

  1. Moments. Adam keeps exp_avg and exp_avg_sq for every weight: 8 bytes per parameter in fp32, 4 with moment_dtype="bfloat16".
  2. Resident all step. They stay in GPU memory (HBM) through forward and backward. Only optimizer.step() reads them.
  3. Cost. Qwen3-4B at FSDP=2: 15.0 GiB of the 30.7 GiB peak per rank.
  4. When it matters. rl_grpo_muse_glimmer_30b_search_r1 turns 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

  1. Idea. Moments live in pinned CPU buffers between steps. step() streams them in chunks (whole parameter shards, ~256 MiB of moments) through two GPU slots into the unchanged fused Adam kernel.
  2. Overlap. While Adam updates one slot, the other slot stores its previous chunk and loads the next one, on two side streams.
  3. No host wait. step() ends with the compute stream waiting for the last store. state_dict() and load_state_dict() wait for it before the CPU touches the moments.
  4. Enable. state_offload on Adam.Config / AdamW.Config. Default None keeps today's path.
  5. Unchanged. Params, grads, clipping, checkpoint keys and values, DTensor sharding, LR metric names.
                warm-up | chunk 0       | chunk 1           | chunk 2
GPU compute:            | Adam 0 in A   | Adam 1 in B       | Adam 2 in A
slot A copies:  load 0  |               | store 0 -> load 2 |
slot B copies:          | load 1        |                   | store 1 -> load 3

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.

llama3 debugmodel, GB300, 10 steps, flex attention, debug.deterministic=True, 1 MiB chunks (15-20 per rank)

check                                          FSDP=2       TP=2         FSDP=2 x TP=2
                                               2 GPUs       2 GPUs       4 GPUs
resident vs offload: loss, grad_norm, 1-10     bitwise      bitwise      bitwise
offload resumed from its async step-5 save     bitwise      bitwise      bitwise
step-10 checkpoints of those 3 runs            156/156      156/156      156/156 tensors equal
torch_checkpointing backend, same two checks   bitwise      not run      not run
  • Flex attention: with the default varlen attention, two resident runs on main already differ from step 2.
  • bf16 moments: checked by the 2-GPU unit test (parity with resident).
Qwen3-4B, 2 GB300, FSDP=2, 32,768 tokens per rank per step, full AC, no compile, one run per cell
peak HBM = max of max_active over steps 4-8; speed = mean of steps 6-8

moments   peak HBM per rank     tokens/s/GPU                 step time
fp32      30.70 -> 18.62 GiB    36,182 -> 28,278  (-21.8%)   0.906 -> 1.159 s
bf16      23.21 -> 17.17 GiB    35,918 -> 31,858  (-11.3%)   0.913 -> 1.029 s
  • Memory. Saved = moments minus two slots: 14.98 - 2 x 1.45 = 12.08 GiB (fp32). The largest chunk is the tied-embedding shard.
  • Time. Copy-bound: 16 GB each way per rank per step (fp32). Step-7 profile: 158 ms from first load to last store, 10 ms of it Adam kernels.
  • Measured with an earlier 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).
  • Worst-case placement. Both ranks shared one CPU socket. One rank per socket ran the same offload cell 11% faster (31,386 tokens/s).
In the regime it targets: Qwen3-8B SFT, 2 GB300, FSDP=2, fp32 moments, 73,728 tokens per rank per step
272.9 GiB per GPU; peak = max over steps 1-15; one run per arm

arm                             peak reserved   allocator retries   tokens/s/GPU   step time
resident + full AC (today)       99.9 GiB        0                  23,242         3.17 s
resident + full AC, on main      99.9 GiB        0                  22,959         3.21 s
resident + default remat        271.2 GiB       70                   8,107         9.21 s
offload + default remat         259.4 GiB        0                  25,681         2.87 s
offload + full AC                69.4 GiB        0                  20,865         3.53 s
  • Setup. 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.
  • Resident + default remat sits at the limit (70 retries, 2.9x slower). With 77,824 tokens it runs out of memory at step 2.
  • Offload + default remat vs today: +10.5% tokens/s. Copies cost 0.36 s per step (3.53 vs 3.17 s, both with full AC). The recompute it removes costs 0.66 s.
  • Speed = mean of steps 7-15 without step 14. Steps 6 and 14 are ~4.5 s slower in every arm, main included (not bisected). With them: +9.1%.

You may ask:

  • Why a wrapper instead of chunking inside Adam/AdamW? Neither class changes. The wrapper narrows their param groups to one chunk per inner step().
  • Why two copy streams? One stream (load, update, store in order) was slower: offloaded step alone on one GB300, fp32 155 vs 176 ms, bf16 65 vs 97 ms.
  • Why not training.enable_cpu_offload? It also moves params and grads, and runs Adam on the CPU.
  • Why does lr_scheduler.py change? LR metric keys use the optimizer class name. Without it, lr/AdamW becomes lr/OptimizerStateOffloader.
  • Why reject 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.
  • Why does torchft reject state_offload? Its full saves read cache_state_dict, which skips OptimizerStateOffloader.state_dict() and its wait for the last stores.
  • Why torch.from_dlpack on the CPU state? DCP's DefaultStager fails on a DTensor whose local tensor starts at a storage offset > 0. The alias starts at 0. The TODO in _state_like holds the repro.

NOTE:

  • Launch with 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.
  • Host memory: one pinned copy of the moments per rank (Qwen3-4B fp32, FSDP=2: 16.1 GB per rank).
  • Fused Adam/AdamW only, params on CUDA. Raises for training.enable_cpu_offload and create_seed_checkpoint runs.
  • Not run: PP, EP, HSDP, MoE, H100, the search_r1 recipe (8 H100s and a retrieval server), the 4-GPU full_checkpoint integration 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).
  • File the DCP stager issue and link it from the TODO.
  • CUDA graph capture of step().

Test plan

pytest tests/unit_tests/cpu/components/optim tests/unit_tests/cpu/components/checkpointer    # 230 passed
pytest torchtitan/experiments/torchft/tests/                                                  # 30 passed
pytest tests/unit_tests/gpu/components/optim/test_optimizer_state_offload.py -m multi_gpu     # 3 passed, 2 GB300
#   parity with resident (fp32, bf16, a rank with an empty shard), slot memory bound, async DCP save -> load
# neighbor GPU tests (optim, qk_clip, dist_muon), split like CI, at 6863763de:
#   1 GPU 16 passed; 2 GPUs 9 passed, 5 skipped (need 4 GPUs)
# full_checkpoint integration entry on 2 GPUs: save at step 10, the load twin resumes to step 20

The full_checkpoint integration entry now sets state_offload, so CI saves and resumes an offloaded run (also the model_only_hf_checkpoint and last_save_model_only_bf16 entries built from it).

Felipe Mello added 3 commits November 2, 2026 13:12
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.
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 2, 2026
@felipemello1

Copy link
Copy Markdown
Contributor Author

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 full_checkpoint integration entry turns it on.

@claude please review

@claude

claude Bot commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @felipemello1's task in 6m 9s —— View job


Needs discussion: maintainers need to decide whether this offload engine belongs in core components/optim or upstream, and which recipe will use it. The review also flags 3 small must-fix items. Review

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Verdict: 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 back

Must fix

  1. PR description: the "Summary (human-written)" section is empty. The author needs to write it (agents leave it as the placeholder).
  2. torchtitan/components/optim/optim.py:88 -- the enable_accelerator_graph + state_offload guard is bypassed when either field is set after the config is constructed, which is how recipes and features.py set them. Move it into the enable_accelerator_graph branch of OptimizersContainer.__init__.
  3. torchtitan/components/optim/offload.py:351 -- the from_dlpack workaround for DCP's stager needs a TODO with 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(...)/DTensorSpec constructor, torch.cuda._pin_memory_utils, and a DCP stager workaround. Should it live in torchao (next to CPUOffloadOptimizer), or as an optimizer-state-only mode of FSDP2's OffloadPolicy, 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_free event, 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_state puts the original DTensor objects back after each chunk. Slab pointers stay stable through load_state_dict, and torchft's cache_state_dict references stay valid.
  • init_optim_state. State is allocated eagerly, so it is a no-op, and the isinstance(optim, (Adam, AdamW)) reset in utils.py:72 is never reached for the wrapper.
  • bf16 moments. The initialize_moments pre-hook on the inner optimizer runs once per chunk and is a no-op because state already exists. restore_moment_dtype is bypassed by the load_state_dict override, 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_inf returns False for the wrapper, so that path raises a clear ValueError. 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_checkpoint entry, rather than adding a new one, is the right shape. Resident optimizer resume is still covered by the fsdp2_tp2_pp2 save/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.

Comment thread torchtitan/components/optim/optim.py Resolved
Comment on lines +348 to +351
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)

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.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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.

Comment thread torchtitan/components/optim/offload.py Resolved
Comment thread torchtitan/components/optim/offload.py Resolved
Felipe Mello added 4 commits November 2, 2026 14:38
- 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.
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: Addressed the 22:31 review in f6ad176 (inline replies on each thread). The DCP stager TODO stays open until the upstream issue is filed. The consumer and layer questions are for the maintainers.

@claude please review

@claude

claude Bot commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

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 components/optim or upstream. Review

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Verdict: 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:88 guard is not bypassed. Optim.Config.build constructs with replace(self) (config/configurable.py:158,167), and that re-runs __post_init__. The engine always builds through config.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.py DCP-stager TODO needs the pytorch/pytorch issue link once the issue is filed.

Must fix

  1. Consumer. No in-repo recipe enables state_offload. The full_checkpoint integration 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(...)/DTensorSpec constructor, torch.cuda._pin_memory_utils, and a DCP stager workaround. Does it belong in core components/optim, or upstream (torchao next to CPUOffloadOptimizer, or an optimizer-state-only OffloadPolicy in 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, after compute.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_dict calls optim.state_dict() (utils.py:98), which is the wrapper's synced override. optim_step calls maybe_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 under enable_accelerator_graph, which offload bans.
  • torchft check. TorchFTOptimizersContainer.Config.__post_init__ doesn't shadow a parent check, because OptimizersContainer.Config defines 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.
@felipemello1

Copy link
Copy Markdown
Contributor Author

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: rl_grpo_muse_glimmer_30b_search_r1 (torchtitan_recipes/rl/search_r1.py).

Its docstring already names the problem. Full activation checkpointing is required only because Adam's moments appear at the first optimizer.step(). Memory jumps ~37 GB/GPU between step 1 and step 2, and the default remat policy OOMs at step 2 (measured on 8x H100 when the recipe was added).

Per trainer GPU (27.9B params, FSDP=3 x TP=2, fp32 master weights):

  • params 17.3 GiB + grads 17.3 GiB + Adam moments 34.6 GiB = 69.2 GiB of an 80 GB H100
  • with state_offload, the moments live in pinned host memory. step() holds two GPU slots of the largest shard (the embedding, 1.67 GiB each)
  • saving: 34.6 - 2 x 1.67 = 31.2 GiB per GPU. That is the step-2 jump minus the two slots, and the slots exist only inside step(), after activations are freed

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:

  1. AdamW.Config(pattern=r".*", lr=1e-6, state_offload=OptimizerStateOffloader.Config())
  2. remove activation_remat=FullActivationRematConfig() and update the docstring
  3. one 8-GPU run pair, ~20 steps: peak memory and trainer step time, today's config vs offload + default remat

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: rl_grpo_qwen3_6_27b_varlen_perf uses bf16 moments because fp32 Adam states OOM on 4x H100 (per the PR that added it). Offload cuts 23.1 GiB per GPU there, or brings back fp32 moments for 4.7 GiB of slots.

Layer

We think core components/optim is the right home for now, with the private-API gaps named in TODOs. The three homes compared:

on CPU where Adam runs FSDP2 / DTensor DCP
this PR Adam moments only GPU, the unchanged fused kernel, 2 streamed slots yes yes, same keys
torchao CPUOffloadOptimizer param copy, grads, state CPU no, "for single GPU training" (its README) own format
FSDP2 CPUOffloadPolicy params, grads, state CPU yes yes
  1. FSDP2: OffloadPolicy decides where sharded params live. torch.optim creates the optimizer state on the param's device, and FSDP2 never touches it. Its only optimizer hook is set_post_optim_event. A state-only policy would mean FSDP2 wrapping optimizer.step(), and it would miss params FSDP2 does not shard (this PR handles plain tensors too).
  2. torchao: a different algorithm (ZeRO-Offload for one GPU: the update runs on the CPU, no grad clipping). Core torchtitan also can't depend on torchao (principle 3).
  3. Other trainers keep this in their own optimizer layer: Megatron-LM HybridDeviceOptimizer, DeepSpeed ZeRO-Offload, prime-rl CPUOffloadOptimizer (on by default there). Megatron and DeepSpeed run Adam on the CPU. prime-rl moves the whole state to the GPU for each step. None streams moments through two slots into the fused GPU kernel, so there is nothing to reuse yet.
  4. Private APIs: PyTorch uses the same ones internally. FSDP2 builds DTensors with the constructor (_from_local_no_grad), and DCP's stager pins with _pin_memory_utils. Each use here has a TODO:
    • In-place pinning: the TODO links the open PyTorch issue.
    • The DTensor constructor: the TODO at that line names the gap, a public way to build a DTensor whose local tensor stays on the CPU.
    • The DCP stager bug: it has a repro ready and will be linked from the TODO once filed.

If you'd rather have it upstream later, the closest fit is torch.distributed.optim, next to ZeroRedundancyOptimizer. torchtitan would then keep only the state_offload field and its build branch. We'd like to prove it in a recipe here first.

@claude please review

@claude

claude Bot commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

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 search_r1 run that shows it pays off. The human-written summary and the DCP issue link are still open. Review

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Verdict: 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 OffloadPolicy places params, not optimizer state. torchao's CPUOffloadOptimizer runs 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:369 needs 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_r1 change 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=..., drop FullActivationRematConfig, 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=True in the recipe is separate from Optim.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.

@felipemello1

Copy link
Copy Markdown
Contributor Author

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 (sft_qwen3_8b_math, GSM8K), 2 GB300, FSDP=2, fp32 moments, 73,728 tokens per rank per step, 15 steps, one run per arm. Per GPU: params 15.3 + grads 15.3 + moments 30.5 GiB, and the default remat policy keeps ~3 GiB of activations per 1k tokens. Each GPU had 272.9 GiB for the run.

arm peak reserved allocator retries tokens/s/GPU step
resident moments + full AC (today) 99.9 GiB 0 23,242 3.17 s
same, on main 99.9 GiB 0 22,959 3.21 s
resident moments + default remat 271.2 GiB 70 8,107 9.21 s
offload + default remat 259.4 GiB 0 25,681 2.87 s
offload + full AC 69.4 GiB 0 20,865 3.53 s

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:

  1. The regime is real, and offload removes it. Without offload, default remat sits at the memory limit: 70 allocator retries here, and an OOM at step 2 with 5.6% more tokens (77,824). With offload it fits with 13.5 GiB to spare.
  2. On GB300, offload pays: +10.5% tokens/s over today's full AC. The copies cost 0.36 s per step (offload + full AC vs resident + full AC: 3.53 vs 3.17 s; 32.8 GB each way per rank, ~90 GB/s). Full AC's recompute costs 0.66 s.
  3. Today's path is unchanged: resident + full AC matches main (same memory, tokens/s within 1.2%).

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 search_r1 only the 8x H100 run pair can measure it.

On landing: this run shows the option pays in the regime it targets, on the hardware we have. The search_r1 change still waits on the H100 pair. Either order works for us: land the option now and turn it on in a follow-up, or stack the 3-line recipe change and merge both after the pair. That is the maintainers' call.

@claude please review

@claude

claude Bot commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

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 search_r1 H100 run pair. Review

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Verdict: 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

  1. PR description: the "Summary (human-written)" section is still empty. Only the author can write it.
  2. PR description, "In the regime it targets": the bullet says sft_qwen3_8b_math resident moments "need full AC". The recipe on main uses neither: torchtitan_recipes/tests/models/qwen3.py:673,697 sets num_tokens_per_microbatch_per_dp_rank=1 * max_context_length and DefaultActivationRematConfig(). 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.py still needs the pytorch/pytorch issue link once the issue is filed.

Questions

  • Land before or after the search_r1 pair? (maintainers) Using the author's own model, here is an estimate of where search_r1 falls (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_r1 at 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_r1 trains 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.

@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: Fixed the "In the regime it targets" bullet: it now says the run overrides sft_qwen3_8b_math's token count (one context per microbatch on main) and its remat (default on main), so it is not a second in-repo consumer. The landing order stays with maintainers.

fegin added a commit 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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant