Repository navigation
Support multiple EMA copies - #5074
Conversation
57d8715 to
0a1128b
Compare
|
cc. @rakkit, ehh it seems I cannot request you for review, but feel free to leave comments.... |
|
@claude review this PR |
|
Claude finished @tianyu-l's task in 2m 35s —— View job Review: Support multiple EMA copies
Overall the design works: one 🔴 Bug: duplicate entries get applied twice per firing
for key, decay in zip(self.ema_keys, decays):
ema_params = [ema_opt.state[t][_EMA_STATE_KEY][key] for t in tensors]
...
torch._foreach_lerp_(ema_params, tensors, 1.0 - decay)With Suggested fix: reject duplicate entries in 🟠 Behavior change:
|
|
thanks a lot, will have a look. (had a look, most looks good for far, but i think claude's suggestion on add a two EMA copy configs into test kind make sense) a noob question. (i am good for it, and thanks a lot to bring it), is there any reason or refers we wanna multiple versions of EMA |
| # Track only the selected copy, so DCP is asked for just its keys. | ||
| ema = EMAContainer.Config( | ||
| buffer_patterns=[f"^{re.escape(fqn)}$" for fqn in sorted(buffer_fqns)] | ||
| decays=[decay_or_half_life_fraction] if is_decay else [], |
There was a problem hiding this comment.
this is_decay flag used for automatically rebuild EMAContainer? (because expected behaviors is convert one EMA copy at once per scripts call?)
There was a problem hiding this comment.
is_decay tells EMAContainer to build EMAContainer from decay mode checkpoint (is_decay=True) or half_life_fractions mode checkpoint (is_decay=False). Maybe I can make the variable name more verbose.
EMA is mostly used to simulate the models' performance after LR annealing. Having multiple EMA with different decay rates can help obtain model performance under different annealing strength. |
43acf27 to
9dc6b0b
Compare
|
@claude review again |
|
Claude finished @tianyu-l's task in 2m 17s —— View job Re-review: Support multiple EMA copies
The updated commit addresses nearly all of the first review. I found no new correctness bugs. Two things are still open: compatibility with old checkpoints, and converter tests for multiple copies. ✅ Fixed since the last review
🟠 Still open: old checkpoints and configsThis is unchanged from the last review, so I'll keep it short:
If #3985 hasn't shipped in a release (or no long runs depend on it), this is fine. Please say so in the PR description. If it has shipped, the cheapest mitigation is to detect bare 🟡 Still open: no converter test with multiple copies
Item 3 matters most, because it is the only test that would check the 🟡 Nits (optional)
✅ Other things I checked
I didn't run the tests or pre-commit here: Python execution isn't available in this job. |
This is fine, don't need to change For others, feel free to improve. |
9dc6b0b to
763c53d
Compare
added a test for "Still open: no converter test with multiple copies"; will merge after the CI passes |
## 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](https://github.com/pytorch/torchtitan/actions/runs/38204459291) 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](https://github.com/pytorch/torchtitan/actions/runs/38214567999) are still running. ```bash 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. <details> <summary>GPU-resident controls with offload_to_cpu=False</summary> 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% | </details> ### 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: ```bash 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. Signed-off-by: ZenAlexa <[email protected]>
This is a follow-up of #3985.
It allows EMA to keep track of multiple copies by having a mixture of
decaysandhalf_life_fractionsas the input list. As a results, we can now support both decay mode and half_life_fractions mode.It still maintains one
emacheckpoint key. Each tensor's state now holds one copy per entry, flattened by DCP toema.state.<fqn>.ema_params.<ema_key>. The decays and half-life fractions are flattened into one list of copies, and each copy is updated independently on the same firing. The CPU-offload path is unchanged; it runs once per copy on the same side stream.