Skip to content

fix EMA checkpoint saved with swapped weight state#590

Open
henriasv wants to merge 2 commits intomir-group:developfrom
henriasv:fix/ema-checkpoint-save-state
Open

fix EMA checkpoint saved with swapped weight state#590
henriasv wants to merge 2 commits intomir-group:developfrom
henriasv:fix/ema-checkpoint-save-state

Conversation

@henriasv
Copy link
Copy Markdown

@henriasv henriasv commented Mar 18, 2026

This error surfaced during development of a multi-head feature for nequip. Solved by Claude Code.

Summary

  • Lightning's ModelCheckpoint saves during on_validation_end, which runs before LightningModule.on_validation_end. This means checkpoints can be captured while EMA weights are swapped into the model (during validation), producing a checkpoint where the EMA module does not hold EMA weights.
  • Previously this caused an assertion failure on load.
  • Adds on_save_checkpoint to detect and correct the swapped state before saving.
  • Backward compatible: tolerates old checkpoints saved in swapped state via a corrective swap on load (with a warning).

Lightning's ModelCheckpoint saves during on_validation_end, which runs
before LightningModule.on_validation_end. This means checkpoints can be
captured while EMA weights are swapped into the model (during validation),
producing a checkpoint where the EMA module does not hold EMA weights.

Previously this caused an assertion failure on load. Now:
- on_save_checkpoint detects the swapped state and corrects it before save
- set_extra_state tolerates old checkpoints saved in swapped state
- evaluation_model performs a corrective swap when loading old checkpoints
@cw-tan
Copy link
Copy Markdown
Collaborator

cw-tan commented Mar 18, 2026

Hi @henriasv , thanks for the contribution. Let me fix the error related to a dependency's breaking change and let the tests run. The fix looks right to me so, happy to merge if all the tests pass (we do check state restoration c.f. EMA weights in the tests).

I am curious if there are specific conditions for this failure mode? e.g. was it an abrupt stop? or perhaps it's because you are using custom modules that might change the sequence of saving events somehow? Or could there be some upstream lightning logic that has changed?

@henriasv
Copy link
Copy Markdown
Author

Hi, it turned up when working on the compile pipeline for multi-head models. Seemed to be causing an error in loading models, but it might actually be that this thing never triggered a failure at all.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants