Skip to content

Support multiple EMA copies - #5074

Merged
ruisizhang123 merged 1 commit into
mainfrom
multiple_ema
Oct 6, 2026
Merged

ruisizhang123 merged 1 commit into
mainfrom
multiple_ema

Conversation

@ruisizhang123

Copy link
Copy Markdown
Collaborator

This is a follow-up of #3985.

It allows EMA to keep track of multiple copies by having a mixture of decays and half_life_fractions as the input list. As a results, we can now support both decay mode and half_life_fractions mode.

It still maintains one ema checkpoint key. Each tensor's state now holds one copy per entry, flattened by DCP to ema.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.

@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Oct 6, 2026
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Oct 6, 2026
@ruisizhang123

Copy link
Copy Markdown
Collaborator Author

cc. @rakkit, ehh it seems I cannot request you for review, but feel free to leave comments....

@tianyu-l

tianyu-l commented Oct 6, 2026

Copy link
Copy Markdown
Contributor

@claude review this PR

@claude

claude Bot commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 2m 35s —— View job


Review: Support multiple EMA copies

  • Gather context
  • Review torchtitan/components/optim/ema.py
  • Review conversion script, docs, and tests
  • Post review

Overall the design works: one "ema" key, a nested ema_params.<ema_key> dict per tensor (which _flatten_state_nested/_unflatten_optim_state_dict already handle), and keys derived from the configured values so the converter can rebuild the container. I found one real bug and a couple of behavior changes that should at least be called out before landing.


🔴 Bug: duplicate entries get applied twice per firing

torchtitan/components/optim/ema.py:61 builds the per-tensor state as a dict keyed by ema_key, so duplicates collapse into one entry. self.ema_keys (line 169) is a list, though, and _update_group loops over it (line 344):

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 decays=[0.999, 0.999] (or half_life_fractions=[0.05, 5e-2], which map to the same float), there's one stored copy but it gets lerped twice per firing. The effective decay becomes 0.999**2 and nothing warns about it. The same happens if a fixed decay and a half-life somehow encode to the same key (they can't today because the prefixes differ, but the general point holds).

Suggested fix: reject duplicate entries in Config.__post_init__ with a ValueError (compare the encoded keys, so 0.05 and 5e-2 are caught too), and add a test for it.
Fix this →

🟠 Behavior change: decays=[x] now also tracks the default half-life copy

Before this PR, decay=0.999 replaced the half-life schedule. Now half_life_fractions defaults to [0.05], so EMA.Config(decays=[0.999]) silently tracks two copies (decay_0p999 and half_life_0p05). That doubles EMA memory (or offload traffic), and with more than one copy the converter will require --ema_key. test_valid_values_are_accepted uses exactly this config, and the docstring doesn't mention it. Only test_fixed_decay_ignores_firing_count knows to pass half_life_fractions=[].

Options:

  • default both lists to empty and have Optim or the recipe opt in to [0.05]; or
  • keep the default but log a warning when decays is non-empty and half_life_fractions is still the default, which is what the removed half_life_fraction-ignored warning used to cover; or
  • at minimum, document in the decays docstring that you need half_life_fractions=[] to get only fixed-decay copies.

🟠 Old checkpoints and configs stop loading (CLAUDE.md §5, "protect battle-tested code paths")

  • Checkpoint layout: existing checkpoints store ema.state.<fqn>.ema_params as a tensor. With the new layout, resuming one with the default config looks for ema.state.<fqn>.ema_params.half_life_0p05 and fails. The documented workaround (exclude_from_loading=["ema"]) throws away all EMA history for in-flight runs.
  • Converter: on an old checkpoint, _checkpoint_ema_copy (convert_ema_to_hf.py:122-137) finds no .ema_params. separator and raises "holds no EMA weights", which is misleading because the weights are there in the old layout.
  • Config: decay= and half_life_fraction= are removed, so any user recipe or CLI override that sets them breaks. I found no in-repo callsites besides tests, so the in-tree audit is clean.

If #3985 hasn't shipped in a release yet, this may be fine. Please say so explicitly in the PR description. Otherwise, consider a small legacy mapping that treats a bare ...ema_params key as the single copy when exactly one copy is configured, or at least a clear error message in both the loader and the converter.

🟡 Adding a copy discards history for the existing ones

The docs (docs/checkpoint.md:20-23) say that adding an entry to decays/half_life_fractions needs exclude_from_loading=["ema"], which cold-starts every copy. Now that copies are independent and individually keyed, restoring the copies that are present and cold-starting only the missing ones would be a natural follow-up. The offload load_state_dict path already skips missing keys per copy (line 560). The non-offload path and DCP's strict planner are what block this. A TODO is fine for now.

🟡 Smaller notes

  • Test coverage: every test still uses a single copy; the diff is mostly a mechanical rename to ["half_life_0p05"]. Please add at least:
    1. a mixed config (decays=[0.9], half_life_fractions=[0.05, 0.1]) checking each copy against its own closed form within one step();
    2. a DCP save→load round trip with more than one copy, including the CPU-offload state_dict and load_state_dict paths, since the owner id map (line 487) now holds K entries per tensor;
    3. converter tests for _select_ema_key: multiple copies with no --ema_key should error, an unknown key should error, and a valid selection should export that copy's values.
  • Offload efficiency (_update_group, lines 343-349): each copy calls _update_offloaded separately. That means K separate wait_stream/wait_event round trips, and the compute stream is held until the K-th copy's param reads finish. It's correct, but fusing copies per chunk (H2D all K copies → K lerps against one read of chunk_p → D2H) would keep the compute-stream stall at about one copy's worth. A TODO is fine.
  • Key encoding: ema_key is the only definition of the encoding, but the converter re-implements its inverse inline (convert_ema_to_hf.py:140-151). Consider putting a parse_ema_key(key) -> (is_decay, value) next to ema_key in ema.py so the two can't drift. Also, ema_key isn't in __all__, but the two prefixes are.
  • Docs: docs/checkpoint.md line 12 runs to about 170 characters, while the surrounding prose wraps near 80. It would also help to mention that non-offloaded memory scales with the number of copies (K× parameter memory).
  • Mutable alias: self.decays = config.decays shares the list with the config. It's harmless today because _decays_at builds a new list, but list(config.decays) would be safer.

✅ Things that look right

  • Nested state flattens and unflattens correctly through components/optim/utils.py, and init_optim_state stays a no-op because state is pre-populated.
  • The offload state_dict owner map and the in-place load_state_dict copy are correctly extended to per-copy tensors.
  • Key encoding round-trips: float(repr(x)) is exact, and inf/nan are rejected before encoding.
  • The cold-start path resets every copy and the warning lists them.

I didn't run the tests: the environment blocked running Python commands.

@rakkit

rakkit commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

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 [],

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.

this is_decay flag used for automatically rebuild EMAContainer? (because expected behaviors is convert one EMA copy at once per scripts call?)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.

@ruisizhang123

Copy link
Copy Markdown
Collaborator Author

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

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.

@ruisizhang123
ruisizhang123 force-pushed the multiple_ema branch 2 times, most recently from 43acf27 to 9dc6b0b Compare October 6, 2026 19:58
@tianyu-l

tianyu-l commented Oct 6, 2026

Copy link
Copy Markdown
Contributor

@claude review again

@claude

claude Bot commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 2m 17s —— View job


Re-review: Support multiple EMA copies

  • Gather context / diff
  • Re-check previous review findings
  • Review ema.py, converter, tests, docs
  • Post review

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

Previous finding Status
🔴 Duplicate entries lerped twice per firing Fixed. Config.__post_init__ (ema.py:189-197) rejects duplicates by comparing encoded keys, so 0.05 and 5e-2 collide. Covered by test_duplicate_entries_are_rejected.
🟠 decays=[x] silently also tracked half_life_0p05 Fixed. Both lists now default to [], and having both empty raises a clear ValueError (test_no_ema_copy_is_rejected).
Converter re-implemented the inverse of ema_key Fixed. parse_ema_key sits next to ema_key, both are in __all__, and TestEMAKey checks the round trip, including 1e-05 → half_life_1em05.
Tests for multiple copies Mostly fixed. TestEMAMultipleCopies checks a mixed config against each copy's closed form and does a DCP round trip with a distinct fill per key. The GPU test test_multi_copy_round_trip_through_offload_paths covers the offload state_dict/load_state_dict paths.
Offload K× round-trip cost A TODO is now in _update_group (ema.py:377-381).
@rakkit's is_decay naming question Renamed to is_decay_mode / decay_or_half_life_fraction, and documented in the _checkpoint_ema_copy docstring.

🟠 Still open: old checkpoints and configs

This is unchanged from the last review, so I'll keep it short:

  • Old checkpoints don't resume. A checkpoint saved before this PR stores ema.state.<fqn>.ema_params as a bare tensor, so a resume fails in DCP with a missing-key error for ...ema_params.half_life_0p05. The only workaround is exclude_from_loading=["ema"], which discards all EMA history.
  • The converter error is misleading for old checkpoints. On an old checkpoint, rpartition(".ema_params.") (convert_ema_to_hf.py:80) finds no separator, so the script says the checkpoint "holds no EMA weights", even though the weights are there in the old layout.
  • Old configs now fail. EMA.Config(), decay= and half_life_fraction= all raise now. They fail loudly, which is good, but it is still a breaking config change.

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 .ema_params keys and raise an error that names the old layout. Do this in the converter at least, and ideally on resume too.

🟡 Still open: no converter test with multiple copies

test_convert_ema_to_hf.py still writes a single half_life_0p05 copy, so _select_ema_key and --ema_key are never tested. Suggested cases:

  1. A checkpoint with two copies and ema_key=None should raise ValueError listing the available copies.
  2. An unknown ema_key should raise.
  3. Choosing ema_key="decay_0p9" should export that copy's values. Give each copy a different fill so that exporting the wrong one fails, as TestEMAMultipleCopies already does.

Item 3 matters most, because it is the only test that would check the decays=[...] if is_decay_mode else [] rebuild at convert_ema_to_hf.py:151-155.

Fix this →

🟡 Nits (optional)

  • docs/checkpoint.md:43-44: the new paragraph runs to about 150 characters per line, while the surrounding prose wraps near 80.
  • docs/checkpoint.md: it would help to mention that EMA memory without offload scales with the number of copies (K× parameter memory, or K× H2D/D2H traffic with offload_to_cpu).
  • ema.py:200: self.decays = config.decays still shares the list with the config. It's harmless because _decays_at builds a new list, but list(config.decays) costs nothing.
  • ema.py:41: in the ema_key docstring, the first line is long, and "half life" should be hyphenated as "half-life" to match the rest of the file.

✅ Other things I checked

  • Encoded keys contain no ., so DCP's nested flatten/unflatten (state.<fqn>.ema_params.<key>) can't be ambiguous. Since repr(float) is exact, decoding the key gives back the exact config value when the converter rebuilds the container.
  • The owner map in offload state_dict and the per-key load_state_dict copy cover all K copies. Cold start resets every copy, and the warning lists them.
  • In-repo callsites are updated: the torchft test, the converter, and the CPU/GPU EMA tests. No recipe or config_registry builds EMA.Config with the removed fields.
  • All lines are within flake8's 120-character limit.

I didn't run the tests or pre-commit here: Python execution isn't available in this job.

@tianyu-l

tianyu-l commented Oct 6, 2026

Copy link
Copy Markdown
Contributor

Still open: old checkpoints and configs

This is fine, don't need to change

For others, feel free to improve.

@ruisizhang123

Copy link
Copy Markdown
Collaborator Author

Still open: old checkpoints and configs

This is fine, don't need to change

For others, feel free to improve.

added a test for "Still open: no converter test with multiple copies"; will merge after the CI passes

tianyu-l pushed a commit that referenced this pull request Oct 12, 2026
## 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]>
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