Skip to content

Initialize CPU-offloaded EMA directly in pinned host storage - #5282

Merged
tianyu-l merged 2 commits into
pytorch:mainfrom
ZenAlexa:contrib/new-ema-cpu-initialization
Oct 12, 2026
Merged

tianyu-l merged 2 commits into
pytorch:mainfrom
ZenAlexa:contrib/new-ema-cpu-initialization

Conversation

@ZenAlexa

@ZenAlexa ZenAlexa commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

Motivation

Initialize CPU-offloaded EMA copies directly in their final pinned host storage. offload_to_cpu=True currently constructs every parameter and selected-buffer shadow on the accelerator first, then converts the complete set to pinned CPU tensors. Multiple EMA decays amplify this initialization peak.

For K configured EMA copies and B bytes of tracked local parameters and buffers, the current path retains K*B bytes of accelerator shadows before offloading starts. The final EMA storage belongs on the CPU under the existing configuration. A model that fits with CPU-offloaded EMA can exhaust accelerator memory during EMA construction.

This follows the multi-copy interface added in #5074 and the direct pinned-storage approach used by #5107.

Changes

  • Pass the existing offload choice into the private _EMAParamOptimizer constructor for both parameters and selected buffers.
  • Detach each source and use the existing get_local_tensor helper for its local shard. Allocate a separate pinned CPU tensor for every EMA key and copy directly into it.
  • Keep the non-offloaded detach().clone() path unchanged.
  • Remove the post-construction migration loop and its unused helper. Preserve the offload stream, event, scratch-pool, update, save, and load behavior. Update the two existing GPU-test docstrings that referenced the removed helper.

The copy uses the default blocking behavior, so each host shadow is readable when construction returns. Every EMA key retains independent storage; changing a live weight or another EMA copy leaves that shadow unchanged. Checkpoint keys, configured decays, half-life schedules, tracked-buffer selection, and dtypes keep their existing owners.

Resource model

For dense local tensors, direct allocation removes the accumulated K*B accelerator clones. It also removes the pageable-CPU-to-pinned-CPU copy at initialization. Final pinned storage remains K*B, and initialization copies the source once per EMA key. No new configuration, dispatch threshold, or dependency is introduced.

Non-dense cross-device copies may use per-tensor contiguous staging inside PyTorch. The claim is removal of the accumulated EMA clones; the platform's copy temporaries retain their own layout-dependent cost. The update pipeline and checkpoint materialization keep their existing memory and transfer behavior.

Validation

current revision

merged main 65aaaa960698ab5d6e98c874177b41b9c30e9c58 at 92e824be6b71360e62759ae479cccb24b56588db. restored the dtensor pin-memory note and shortened the checkpoint docstring. the ema execution code is unchanged from 6c3ab4f7; the two test docstring edits now follow main's directory layout.

on python 3.12.14 and pytorch 2.14.1 cpu, the existing ema and reshard suites passed all 44 tests and 44 subtests. changed-file formatting, syntax, license, docstring and spelling checks passed. pyrefly 0.45.1 reported zero errors in the changed production file.

upstream gpu ci ran this head with pytorch 2.16.0.dev20261011+cu132. all 13 ema gpu cases passed. the full single-gpu group returned 181 passed, 46 skipped and 44 deselected. the multi-gpu group returned 34 passed, 11 skipped, 225 deselected and 1 xfailed. upstream lint also passed, including pyrefly and the link checker. integration tests are still running.

python -m pytest tests/unit_tests/cpu/components/optim/test_ema.py tests/unit_tests/cpu/components/optim/test_ema_resharding.py -q
python -m pytest tests/unit_tests/gpu/components/optim/test_ema.py --collect-only -q

historical h100 comparison

Compared main 432b95dcf55b3840d7f63ca24a0c585701e70c36 with 6c3ab4f7965733e312456e578843f6a37baf42ee on H100 80 GB HBM3, using Torch 2.16.0.dev20261010+cu132, Triton 3.9.0+gitfc8d31a5, Python 3.12 and driver 580.95.05. Both checkouts use the full project dependency manifest in the same offline environment; pip check and actual model imports pass.

Initialization memory and time

Four fresh processes run in main/candidate/candidate/main order. Each process performs the same ten cases in the same order after an 8 MiB warmup. Each case times one complete EMA.Config.build() plus CUDA completion; live parameter/buffer creation and output verification are outside timing. Allocator caches can carry across cases. The table reports the arithmetic mean of the two process observations per arm. Both observations agree on every memory peak.

B is the logical size of tracked local tensors; K is the number of EMA copies. Extra peak is max_memory_allocated - memory_allocated_before_build, with the peak reset after the live tensors exist. Final pinned storage is identical between arms at K×B.

B (MiB) K Layout Main extra GPU peak (MiB) Candidate extra GPU peak (MiB) Main build (ms) Candidate build (ms) Time change
64 1 contiguous 64 0 50.595 34.172 -32.46%
64 3 contiguous 192 0 137.377 80.124 -41.68%
256 1 contiguous 256 0 200.951 127.384 -36.61%
256 3 contiguous 768 0 502.480 260.863 -48.08%
64 3 transpose 192 0 75.224 28.840 -61.66%
64 3 holed 192 8 92.804 39.584 -57.35%

The holed input has 128 MiB of underlying live storage for 64 MiB of logical data. Its absolute GPU peak falls from 320 to 136 MiB; the remaining 8 MiB is a per-tensor copy temporary. For contiguous B256/K3, absolute peak falls from 1,024 to 256 MiB and final pinned storage remains 768 MiB. The two process build times are 520.445/484.515 ms on main and 258.904/262.822 ms in the candidate.

A separate fresh-process capacity scenario imposes a 2 GiB PyTorch allocator budget with 1 GiB of live tracked tensors and K=3. Main reaches OOM during EMA construction, after the complete source exists. The candidate completes with a 1 GiB GPU allocated peak and 3 GiB of independent pinned shadows. That budget excludes CUDA context and external allocations.

GPU-resident controls with offload_to_cpu=False

The clone path and measured memory peaks retain their existing behavior. The small control below records a 0.110 ms increase; construction speedups apply to CPU offload.

B (MiB) K Extra GPU peak in both arms (MiB) Main build (ms) Candidate build (ms) Time change
64 1 64 0.885 0.995 +12.42%
64 3 192 1.889 1.934 +2.35%
256 1 256 1.244 1.226 -1.47%
256 3 768 2.919 2.960 +1.41%

Values, ownership and training

  • Each arm passes 22 platform-allocation cases and 41 EMA lifecycle cases. The matrix covers CPU/CUDA sources, FP32/BF16/FP64/complex64, contiguous/transposed/holed/empty/scalar layouts, frozen parameters, selected buffers and multiple EMA keys. Checks cover complete initial values, independent pinned storage, live-input mutation, three CUDA-source updates, save/load, empty-state reseeding and one-rank FSDP2 with plain buffers. CPU-source cases cover construction.
  • Four fresh processes run ten actual debug-Llama training steps each in ABBA order, with seed=42, deterministic algorithms enabled and TF32 disabled. The six-layer, dim-256, vocab-2048 model has 6,163,712 parameters and uses the real Optim.step path, fused AdamW, clipping, LR scheduling, two fixed decays, one half-life EMA and a tracked buffer.
  • The three subsequent runs compare every step's complete model tensors, gradients, optimizer state, scheduler state, EMA state, loss and gradient norm against the first main run. All comparisons are bitwise equal. Each process checkpoints model/optimizer/scheduler/EMA after step 5, restores into fresh objects, and compares steps 6–10 against uninterrupted execution. The returned final snapshots also compare byte-for-byte: 316 tensors and 43,146,055 elements, all finite.

Distributed contract

Both arms pass nine scenarios on each of two H100 ranks using native NCCL:

  • Two named CUDA meshes, each with a DTensor parameter and a plain tracked buffer. Three EMA keys preserve initial values, independent pinned storage and local-shard metadata across three updates checked against separate pointwise CUDA lerp calculations. Placements cover uneven and even Shard(0), an empty local shard, Replicate, and transposed Shard(1).
  • Actual FSDP2 parameter sharding with uneven and empty local shards at construction.
  • A source tensor on one device with the caller's current device set to the other. Construction preserves the caller's device; this scenario covers initialization.
  • Balanced FSDP2 DCP save, zeroed-shadow load and one subsequent update, with exact values and pinned-storage identity preserved. Uneven checkpoint export and changes in world size retain their existing implementation and are outside this distributed scenario.

Existing regression coverage and static checks

Both arms pass the existing CPU EMA and reshard suites, 44 tests each, and the existing native GPU EMA suite, 13 tests each with no skips:

python -m pytest tests/unit_tests/cpu/test_ema.py tests/unit_tests/cpu/test_ema_resharding.py -q
python -m pytest tests/unit_tests/gpu/test_ema.py -q

Formatting, flake8, AST, license, docstring and spelling checks pass for both changed files, along with git diff --check. Full-tree pre-commit retains main's existing F401 at torchtitan/experiments/graph_trainer/tests/test_graph_pp_passes.py:84. A separate Linux pyrefly run reports the same six optional-model transformers import errors on both arms and zero EMA-file diagnostics. The link checker has no installed binary in the local hook environment.

The measurements cover EMA construction and the exercised training/checkpoint contracts. GH200 NVLink-C2C performance and full multi-node training throughput remain unmeasured.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Oct 11, 2026
@ZenAlexa
ZenAlexa marked this pull request as ready for review October 11, 2026 15:18
Copilot AI balanced review requested due to automatic review settings October 11, 2026 15:18
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Oct 11, 2026
@pytorch-bot

pytorch-bot Bot commented Oct 11, 2026 •

Copy link
Copy Markdown

Workflows were awaiting approval. CI has now been triggered for the ciflow labels on this PR.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@ZenAlexa

Copy link
Copy Markdown
Contributor Author

@tianyu-l Could you review the EMA storage placement in this change? It applies the pinned-allocation approach from #5107 to the multi-copy initialization from #5074, with update and checkpoint behavior preserved.

@tianyu-l

Copy link
Copy Markdown
Contributor

@claude review this PR

@claude

claude Bot commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 1m 28s —— View job


Review: Initialize CPU-offloaded EMA directly in pinned host storage

  • Gather diff and context
  • Review torchtitan/components/optim/ema.py
  • Review test changes
  • Post review

Verdict: I didn't find any correctness problems, and the change is a clear win. With offload_to_cpu=True, the old path built K full accelerator clones (t.detach().clone() per key) before _init_cpu_offload moved them to the host. Initialization peak was K×B on GPU, and that doesn't match what the feature promises. The new path removes that peak and the second pageable-to-pinned copy, and the diff is smaller.

What I checked

  • Placement and layout match the old behavior. Old: get_local_tensor(clone).cpu().pin_memory(). New: torch.empty_like(local, device="cpu", pin_memory=True).copy_(local). Both give a pinned local shard with preserve_format strides: a transposed source keeps its strides and a non-dense source becomes contiguous. Both use the same caching host allocator, so final pinned usage (including its power-of-two rounding) is the same. _scratch_chunks / _foreach_copy_ already handle stride mismatch between scratch and ema_param, so nothing changes downstream.
  • The host shadow is ready when construction returns. A blocking copy_ into pinned memory syncs the stream, so the first _update_offloaded H2D can't race initialization.
  • Each EMA key gets its own storage. One empty_like runs per key, so copies don't alias each other or the live param.
  • DTensor handling is unchanged. get_local_tensor(t.detach()) gives the same local shard as before. _materialize_dtensor, state_dict, load_state_dict and the cold-start reseed all still expect a plain pinned local tensor, and they get one.
  • The non-offload path is unchanged.
  • No callsites are left behind. _pin_local and _init_cpu_offload aren't referenced anywhere else, and _EMAParamOptimizer is private with only the two callers updated here. The keyword-only offload_to_cpu follows the repo's config rules.

Suggestions (non-blocking)

  1. Keep the DTensor pin_memory TODO. The deleted comment above _pin_local said why the shard is pinned on its own and rewrapped at save/load: aten._pin_memory is NYI for DTensor. It also noted the process-group/world-size caveat a native implementation would have to handle. That limitation still exists and is the reason _materialize_dtensor is needed, so please move the TODO next to the new allocation in _EMAParamOptimizer.__init__ (or into the _materialize_dtensor docstring) rather than drop it. Per CLAUDE.md, TODOs should record known limitations.
    Fix this →

  2. Add a regression test for the property this PR is about. The existing GPU tests already check is_pinned() and the values, so the behavior is covered. Nothing guards the memory claim, though: if someone brings back a clone() before offloading, every test still passes. A small case in tests/unit_tests/gpu/test_ema.py would catch that. It could build a plain CUDA module, call torch.cuda.reset_peak_memory_stats(), build EMA.Config(decays=[0.9, 0.99, 0.999], offload_to_cpu=True), and assert max_memory_allocated() - before is about 0 for contiguous params. The PR description has the measurement; checking in a cheap version keeps it true.

  3. Docstring nit. In _materialize_dtensor, the reflowed first sentence ("...matching p's own sharding for DCP at checkpoint save/load -- this is what DCP needs...") now reads a little awkwardly and leaves one long line. Consider: "Move the local shard onto the accelerator and rewrap it as a DTensor matching p's sharding, for the copy handed to DCP at checkpoint save/load."

  4. Optional optimization, not needed for this PR. With K>1, each tensor goes through K separate blocking D2H copies. Doing one D2H and then K-1 pinned-to-pinned host copies would leave the device alone after the first copy. Your timings already show a large speedup, so this isn't worth the extra code unless initialization time on large K becomes an issue.

Not verified here

I didn't run the GPU tests or pre-commit in this job because the runner has no GPU. The PR description reports both GPU suites passing on H100. The CI job for ciflow/fake-pg is still waiting for maintainer approval.

@tianyu-l

Copy link
Copy Markdown
Contributor

@ZenAlexa thanks, could you at least fix 1 and 3, after rebase

@ZenAlexa

Copy link
Copy Markdown
Contributor Author

fixed 1 and 3, and merged current main. the test edits now use the moved paths.

@tianyu-l
tianyu-l merged commit cf82228 into pytorch:main Oct 12, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/fake-pg Run 1-GPU Fake PG integration tests 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.

3 participants