Skip to content

[checkpoint] Reseed EMA after a model-only or EMA-excluded load on any backend - #5141

Merged
tianyu-l merged 2 commits into
pytorch:mainfrom
David-Wu1119:fix/ema-reseed-any-backend
Oct 17, 2026
Merged

tianyu-l merged 2 commits into
pytorch:mainfrom
David-Wu1119:fix/ema-reseed-any-backend

Conversation

@David-Wu1119

@David-Wu1119 David-Wu1119 commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

CheckpointManager (DCP) reseeds the EMA from the just-loaded weights when the EMA itself was not restored: a model-only load (a seed step-0 checkpoint, or initial_load_path with the default initial_load_model_only=True) or exclude_from_loading=["ema"]. docs/checkpoint.md describes this, and test_model_only_load_reseeds_ema_from_loaded_weights / test_exclude_ema_honored_even_when_data_is_present pin it. The reseed lives in CheckpointManager._load_checkpoint, so TorchCheckpointingManager never does it: after those loads its EMA keeps tracking the random initialization the model just discarded, and the EMA's cold-start warning does not fire.

Loading a seed checkpoint, then resuming a step-5 checkpoint with exclude_from_loading=["ema"] (CPU, both backends on the same model):

CheckpointManager          after loading step-0: EMA==loaded weights True,  EMA==discarded random init False
TorchCheckpointingManager  after loading step-0: EMA==loaded weights False, EMA==discarded random init True
TorchCheckpointingManager  resume step-5 excluding ema: EMA==loaded weights False, EMA==discarded random init True

Change

Move the reseed from CheckpointManager._load_checkpoint into BaseCheckpointManager.load, right after _load_checkpoint, so every backend gets it. The old condition also required MODEL in states, to keep TorchFT's per-replica dataloader-only load from reseeding; that load calls _load_checkpoint directly rather than load(), and inside load() the states always include MODEL (model_only returns it and Config.__post_init__ rejects it in exclude_from_loading), so that check can no longer be false and was removed.

Test plan

  • New test_model_only_load_reseeds_ema_from_loaded_weights in tests/unit_tests/cpu/components/checkpointer/test_torch_checkpointing.py loads a step-0 checkpoint with an EMA attached and checks the EMA is reseeded. It fails on main.
  • New test_ema_excluded_from_resume_is_reseeded (step-5 resume with exclude_from_loading=["ema"]; fails on main) and test_full_resume_keeps_restored_ema (a full resume restores the EMA and does not reseed it).
  • TestBaseCheckpointManagerTracing._manager builds a Mock(spec=BaseCheckpointManager) and sets the instance attributes load() reads; it now also sets states = {}.
  • test_torch_checkpointing.py and test_checkpoint.py on the rebased branch: 115 passed (CPU, torch nightly, locally). The two test_hf_load_* tests fail locally with and without this change because macOS has no os.O_DIRECT.
  • The comparison above, run on the first commit: both backends report EMA==loaded weights True after both loads.
  • flake8 (with the hook's plugins) and ufmt (black 22.12.0, usort 1.0.5) pass on the changed files of the latest commit; the first commit also passed pydoclint and codespell.

🤖 Generated with Claude Code

Copilot AI balanced review requested due to automatic review settings October 8, 2026 04:21
@pytorch-bot pytorch-bot Bot added ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/rl labels Oct 8, 2026
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Oct 8, 2026

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.

@pytorch-bot

pytorch-bot Bot commented Oct 8, 2026 •

Copy link
Copy Markdown

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

@pytorch-bot

pytorch-bot Bot commented Oct 8, 2026

Copy link
Copy Markdown

The following ciflow label(s) have been added but CI has not been triggered yet because the workflows are awaiting approval:

  • ciflow/rl
  • ciflow/fake-pg

Once a maintainer approves the workflows (scroll to the bottom of the PR page), the corresponding CI jobs will be triggered automatically. Please ping one of the reviewers if you do not have access to approve and run workflows.

@tianyu-l

tianyu-l commented Oct 8, 2026

Copy link
Copy Markdown
Contributor

@claude review this PR

@claude

claude Bot commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

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


Review: reseed EMA in BaseCheckpointManager.load

  • Read the diff and the related code (base.py, dcp.py, torch_checkpointing.py, experiments/torchft/checkpoint.py, tests, docs)
  • Checked correctness across backends and callsites
  • Posted review

Verdict: LGTM. The fix is correct and it's in the right place. I found one cleanup nit and two small test gaps, and nothing that should block merging.

Why the change is correct

  • Root cause. The rule "reseed the EMA if it wasn't restored" doesn't depend on the storage format, but it was implemented in CheckpointManager._load_checkpoint (DCP only). Moving it into the shared load() path fixes the root cause rather than patching TorchCheckpointingManager separately.

  • Order is preserved. Both backends restore MODEL inside _load_checkpoint:

    • DCP: states[MODEL].load_state_dict(...)
    • torch_checkpointing: the target.load_state_dict(state_dict[key]) loop at torch_checkpointing.py:368-370

    So when EMA.load_state_dict({}) runs at base.py:328-329, the model already holds the loaded weights and the cold-start copies the right tensors.

  • TorchFT is unaffected. TorchFTCheckpointManager._load_checkpoint calls super()._load_checkpoint(...) and then _ft_load. The reseed now runs after _ft_load instead of between the two. _ft_load only touches DATALOADER, so the order doesn't matter. _ft_load calls super()._load_checkpoint directly, so it never reaches the reseed. Peer recovery through ft_manager.set_state_dict_fns doesn't go through load() either, and it carries EMA explicitly.

  • No other overrides. No subclass overrides load() (only CheckpointManager, TorchCheckpointingManager and TorchFTCheckpointManager exist), so all three get the behavior.

  • Mock fix makes sense. states = {} in TestBaseCheckpointManagerTracing._manager is needed because the new line reads self.states. Since EMA in self.states is checked first, the condition never touches the Mock returned by _states_to_load.

Nit: the MODEL in states check can no longer be false

torchtitan/components/checkpointer/base.py:328

The old comment explains the MODEL in states check: it stopped TorchFT's dataloader-only _load_checkpoint call from triggering a reseed. In load(), that case can't happen:

  • _states_to_load(model_only=True) returns {MODEL: ...}.
  • Otherwise it returns self.states minus exclude_from_loading, and MODEL is rejected from that list at base.py:603-604.
  • The only subclass override (TorchFT) only pops DATALOADER.

So the check is always true here. Per CLAUDE.md principle 7 (no speculative defensive checks), I'd simplify to:

# Reseed EMA from the just-loaded weights if it wasn't itself
# restored (excluded, or a model_only load).
if EMA in self.states and EMA not in states:
    self.states[EMA].load_state_dict({})

If you'd rather keep the guard, write it as assert MODEL in states so it reads as an invariant, not a branch. Either way, the PR description's sentence about TorchFT "(the old comment's reason for checking MODEL)" should be updated, since the check no longer protects anything.

Fix this →

Tests: two small gaps

tests/unit_tests/cpu/test_torch_checkpointing.py:904

The new test only covers the step-0 model-only path. Two cheap additions would make the torch_checkpointing backend match what test_checkpoint.py already checks for DCP:

  1. exclude_from_loading=["ema"] on a non-zero step (e.g. step-5 with metadata.pkl). This is the second scenario in your repro table. Assert that EMA isn't in load_calls[0][1] and that ema.load_state_dict.assert_called_once_with({}).
  2. A negative case: a full resume with EMA included. Assert that load_state_dict is called with the restored EMA state and not with {}. This catches a future regression that reseeds unconditionally and silently wipes EMA history on every resume.

Optional readability tweak: the test sets initial_load_model_only=False but still expects a model-only load, because step 0 forces model_only. A one-line comment saying so would help, since the setting looks contradictory at first.

Other notes

  • docs/checkpoint.md (around lines 51-61) already describes the backend-agnostic behavior, so no doc change is needed.
  • Comments are ASCII and placed sensibly.
  • I couldn't run the tests or pre-commit here: running commands needs approval that this job doesn't have. I relied on the CPU results in the PR description (108 passed).

@tianyu-l

tianyu-l commented Oct 8, 2026

Copy link
Copy Markdown
Contributor

@David-Wu1119 could you address

Nit: the MODEL in states check can no longer be false

…y backend

CheckpointManager (DCP) reseeds the EMA from the just-loaded weights when
the EMA itself was not restored (a model-only load such as a seed step-0 or
initial_load_path checkpoint, or exclude_from_loading=["ema"]), as
docs/checkpoint.md describes. TorchCheckpointingManager did not, so its EMA
kept tracking the discarded random initialization. Move the reseed from
CheckpointManager._load_checkpoint into BaseCheckpointManager.load so both
backends share it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@David-Wu1119
David-Wu1119 force-pushed the fix/ema-reseed-any-backend branch from c5f7d2a to 4ea0cb8 Compare October 16, 2026 16:26
@tianyu-l

Copy link
Copy Markdown
Contributor

@claude review again

@claude

claude Bot commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 46s —— View job


Re-review: reseed EMA in BaseCheckpointManager.load

  • Read the current diff
  • Check whether the earlier nit (MODEL in states) and the test gaps were addressed
  • Re-check correctness
  • Post review

Summary: the branch hasn't changed since my last review, so the nit you asked @David-Wu1119 to address is still open. The PR is still the single commit 4ea0cb8 (Oct 8). There's no follow-up commit, and base.py:338 still reads:

if EMA in self.states and MODEL in states and EMA not in states:

Everything else from the first review still holds. The fix is correct and in the right place, and it doesn't block merging apart from the nit below.

Still open: drop the MODEL in states check (requested by @tianyu-l)

torchtitan/components/checkpointer/base.py:336-339

I re-checked that this condition can't be false inside load():

  • When model_only is set, _states_to_load returns {MODEL: self.states[MODEL]} (base.py:409-410).
  • Otherwise it returns self.states minus exclude_from_loading (base.py:415-419), and Config.__post_init__ raises ValueError if MODEL is in that list (base.py:613-614).
  • No subclass overrides _states_to_load or load(). TorchFT only overrides _load_checkpoint (experiments/torchft/checkpoint.py:174), and its dataloader-only load at :247 calls super()._load_checkpoint directly, so it never reaches this code.

Suggested change:

# Reseed EMA from the just-loaded weights if it wasn't itself
# restored (excluded, or a model_only load).
if EMA in self.states and EMA not in states:
    self.states[EMA].load_state_dict({})

Please also update the PR description: the sentence ending "(the old comment's reason for checking MODEL)" should say the check was removed because it can no longer be false.

Fix this →

Still open (optional): test coverage in test_torch_checkpointing.py

The new test_model_only_load_reseeds_ema_from_loaded_weights only covers the step-0 model-only path. These two are still worth adding, but they don't block merging:

  1. exclude_from_loading=["ema"] on a step-5 checkpoint. Assert that EMA isn't in load_calls[0][1] and that ema.load_state_dict.assert_called_once_with({}).
  2. A full resume with EMA included. Assert that load_state_dict is never called with {}. This guards against a future change that reseeds unconditionally and wipes EMA history on every resume.

The test also sets initial_load_model_only=False but expects a model-only load, because step 0 forces model_only. A one-line comment saying so would make that clearer.

Re-confirmed

  • Order is still right. Both backends restore MODEL inside _load_checkpoint, before the reseed, so the EMA copies the loaded weights.
  • Mock fix still needed. manager.states = {} in TestBaseCheckpointManagerTracing._manager has to stay, because the new line reads self.states.
  • Warnings now work on both backends. EMA's cold-start and stale-exclude_from_loading warnings (components/optim/ema.py:550-574) now fire on the torch_checkpointing backend too.

I didn't run the tests or pre-commit in this job. Nothing has changed since the CPU results in the PR description (108 passed).

@tianyu-l

Copy link
Copy Markdown
Contributor

@David-Wu1119 could you fix?

_states_to_load always includes MODEL (model_only returns it, and
Config.__post_init__ rejects it in exclude_from_loading), so the reseed
condition only needs EMA in self.states and EMA not in states. Add tests
for a step-5 resume with exclude_from_loading=["ema"] (reseeded) and a
full resume (the restored EMA is not reseeded), and note why the step-0
test loads model-only.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@David-Wu1119

Copy link
Copy Markdown
Contributor Author

@tianyu-l sorry for missing this earlier. Fixed in 61fd246:

  • The reseed condition is now EMA in self.states and EMA not in states. Inside load() the states always include MODEL: model_only returns it, and Config.__post_init__ rejects it in exclude_from_loading.
  • New tests: test_ema_excluded_from_resume_is_reseeded (a step-5 resume with exclude_from_loading=["ema"], which fails against main's checkpointer) and test_full_resume_keeps_restored_ema (a full resume restores the EMA and doesn't reseed it). The step-0 test now has a comment explaining why it loads model-only.
  • Updated the PR description to match.

test_torch_checkpointing.py and test_checkpoint.py: 115 passed locally (CPU). The two test_hf_load_* tests fail on macOS with and without the change, because macOS has no os.O_DIRECT.

@tianyu-l
tianyu-l merged commit ba53205 into pytorch:main Oct 17, 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 ciflow/rl 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