[Bug] SwapAdamW (swap_optimizer=True) silently loses optimizer m/v across DCP checkpoint save and resume

Aperta
#2,261 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub

I maintainer di solito rispondono entro 4 giorni

Nessuno ha ancora preso questa issue.

Valutazione

Difficoltà
4/5
Tempo stimato
3-5 giorni
Idoneità per principianti
42/100
Tipo di issue
Bug
Chiarezza
Specificata chiaramente
Stato di attività
Attiva
Stack tecnologico
python, pytorch

Direzione di ricerca

Start with xtuner/v1/optim/swap_adamw.py and trace SwapAdamW.step() and load_state_dict; then read the DCP flow through TrainEngine._get_dcp_state_dict and compare it with the Muon swap path in xtuner/v1/optim/muon.py. Reproduce save and resume with swap_optimizer=True, including multiple ranks. Done means momentum and variance survive resume and each rank's shard is represented and restored correctly.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

Summary

With swap_optimizer=True (SwapAdamW, xtuner/v1/optim/swap_adamw.py), the optimizer's exp_avg / exp_avg_sq live canonically in pinned CPU buffers. At construction, each pinned buffer is published twice as the same tensor object: into self.state[param][key] and into the private map self._param_to_cpu_states_map[param][key]. SwapAdamW.step() reads m/v from the private map (H2D -> torch_adam on device copies -> D2H write-back into the pinned buffers), so after construction the private map is the effective source of truth.

The DCP checkpoint flow breaks this aliasing in two places:

1. Resume silently restarts m/v from zeros.
On resume, TrainEngine.load_checkpoint -> dcp.load -> set_optimizer_state_dict -> Optimizer.load_state_dict (stock torch) replaces self.state[param] entries with fresh tensors. The pinned buffers in _param_to_cpu_states_map are never updated, and step() keeps reading them. Since step lives only in self.state (not in the pinned map), the step count loads correctly while m/v do not: every parameter resumes with zero momentum/variance against a loaded step count. The bias-correction mismatch (loaded step with zeroed m/v) makes the first optimizer steps take over-sized updates, which manifests as a loss spike immediately after resume.

2. Multi-rank checkpoints keep only one rank's m/v shard.
On save, TrainEngine._get_dcp_state_dict -> get_optimizer_state_dict passes the plain pinned CPU buffers through unchanged. To DCP they look like identical (offset-0, local-size) plain tensors on every rank, and the global dedup of dcp.save keeps a single writer. The checkpoint therefore stores only one rank's m/v chunk; the other ranks' momentum is silently dropped at save time, and on load every rank reads that single stored shard, so all ranks but the stored one get wrong m/v.

Reproduction conditions

  • Optimizer built with swap_optimizer=True (SwapAdamW).
  • Checkpoint saved through the standard DCP flow (save_optimizer=True).
  • Resume in a fresh process with load_optimizer=True.
  • Defect 1 reproduces at any world size; defect 2 additionally requires world_size > 1.

Observable signature right after resume:

# per DTensor parameter of the swap optimizer
opt._param_to_cpu_states_map[param]["exp_avg"].abs().sum()    # == 0
opt._param_to_cpu_states_map[param]["exp_avg_sq"].abs().sum() # == 0
opt.state[param]["step"]                                      # loaded correctly (nonzero)

while the checkpoint's stored shard contains nonzero values; training loss spikes within the first steps after resume relative to the pre-save trajectory. With world_size > 1, the saved DCP metadata contains m/v shards for exactly one rank.

Impact

  • Checkpoint resume with swap_optimizer=True trains from zero momentum/variance: the loss spikes right after resume and the trajectory deviates from the pre-save run, silently — no error is raised (values are present in the checkpoint; they just never reach the hot path).
  • With multiple ranks, the checkpoint itself is incomplete: ranks other than the one whose shard was kept cannot restore their own m/v at all, so resuming on a different rank count / re-sharding is also corrupted.

Suggested fix

Two orthogonal pieces; the second mirrors the residency design this repo already uses for the Muon swap path (_to_pinned_host preserves the DTensor wrapper, and Muon registers a load_state_dict post-hook in xtuner/v1/optim/muon.py):

  1. Rebind on load (fixes defect 1). Override SwapAdamW.load_state_dict: after super().load_state_dict(), copy the loaded values back into the construction-time pinned buffers (copy_ also handles dtype casts; zero the buffers for keys absent from the checkpoint to keep stock fresh-state semantics) and point self.state back at the same buffers, so the private map stays the single source of truth.

  2. Give DCP global coordinates for the CPU buffers (fixes defect 2). Let the optimizer expose a hook (e.g. wrap_cpu_states_for_dcp(optim_state_dict)) called from _get_dcp_state_dict after get_optimizer_state_dict: wrap each pinned buffer as a DTensor over its parameter's device_mesh and placements, zero-copy — construct the DTensor so its _local_tensor is the pinned buffer, with a TensorMeta of the buffer's shape/stride/dtype (DTensor.from_local would instead copy the buffer onto the device). dcp.save then plans per-rank chunks in global coordinates and dcp.load reshards in place into the buffers; a matching unwrap_cpu_states_after_dcp_load restores plain values before set_optimizer_state_dict hands the dict to the optimizer-level load (torch's optimizer load rejects mixed plain/DTensor values).

A larger but design-consistent alternative: keep SwapAdamW states as DTensors whose _local_tensor is pinned host memory from construction, and re-home loaded states to pinned host in a load_state_dict post-hook while preserving the DTensor wrapper — then get_optimizer_state_dict emits global coordinates natively and no wrap/unwrap hook is needed.

Lingua principale
Python
Stelle
5.2k
Fork
466
Merge medio
5g 8h
PR unite (30g)
44

Preparare l'ambiente

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di InternLM/xtuner

Tutte le issue di InternLM/xtuner

Issue simili

Altre issue su Python

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.