[Bug] SwapAdamW (swap_optimizer=True) silently loses optimizer m/v across DCP checkpoint save and resume
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
- Ambito
- backend, distributed-systems
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=Truetrains 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):
-
Rebind on load (fixes defect 1). Override
SwapAdamW.load_state_dict: aftersuper().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 pointself.stateback at the same buffers, so the private map stays the single source of truth. -
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_dictafterget_optimizer_state_dict: wrap each pinned buffer as a DTensor over its parameter'sdevice_meshand placements, zero-copy — construct the DTensor so its_local_tensoris the pinned buffer, with aTensorMetaof the buffer's shape/stride/dtype (DTensor.from_localwould instead copy the buffer onto the device).dcp.savethen plans per-rank chunks in global coordinates anddcp.loadreshards in place into the buffers; a matchingunwrap_cpu_states_after_dcp_loadrestores plain values beforeset_optimizer_state_dicthands 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
- Include un Dockerfile o un file Docker Compose
- Nessun modello di pull request
- Leggi la guida per i contributori
Come iniziare
- Leggi tutta la issue e poi la guida ai contributi del progetto.
- Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
- Fai un fork del repository e lavora su un branch.
- Apri una pull request che faccia riferimento al numero della issue.
Altre issue di InternLM/xtuner
-
enhancement good first issue
Difficoltà 3/5 1-2 giorni Idoneità per principianti 62/100
InternLM/xtuner#2246 · 3 commenti ·
I maintainer di solito rispondono entro 4 giorni
-
Difficoltà 4/5 3-5 giorni Idoneità per principianti 52/100
InternLM/xtuner#2134 · 1 reazione ·
I maintainer di solito rispondono entro 4 giorni
-
[NPU] reduce_sum_across_dp_group builds the all_reduce tensor on CPU when CUDA is unavailableForse già presa @li-lizhe l’ha presa 69 giorni fa. Aperta
Difficoltà 2/5 1-3 ore Idoneità per principianti 30/100
I maintainer di solito rispondono entro 4 giorni
-
Difficoltà 5/5 Più di una settimana Idoneità per principianti 15/100
InternLM/xtuner#2118 · 6 commenti ·
I maintainer di solito rispondono entro 4 giorni
-
Difficoltà 4/5 3-5 giorni Idoneità per principianti 38/100
I maintainer di solito rispondono entro 4 giorni
Tutte le issue di InternLM/xtuner
Issue simili
-
accepted
Difficoltà 2/5 1-3 ore Idoneità per principianti 66/100
future-agi/future-agi#5908 ·
I maintainer di solito rispondono entro 1 giorno
-
Placeholder export disables HTML image input for picture descriptionForse già presa @cloudiful l’ha presa oggi. Aperta
Difficoltà 2/5 1-3 ore Idoneità per principianti 78/100
docling-project/docling-serve#817 ·
I maintainer di solito rispondono entro 1 giorno
-
Difficoltà 1/5 Meno di un'ora Idoneità per principianti 92/100
Techiebutler/freeframe#687 ·
I maintainer di solito rispondono entro 1 giorno
-
Parse truncated verbose GC logs up to the first XML errorForse già presa Una pull request collegata a questa issue è aperta o già unita. Apertabug verbose GC
Difficoltà 2/5 1-3 ore Idoneità per principianti 74/100
IBM/javacore-analyser#677 ·
I maintainer di solito rispondono entro 1 giorno
-
Difficoltà 2/5 1-3 ore Idoneità per principianti 79/100
I maintainer di solito rispondono entro 2 giorni