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

Abierto
#2,261 0 comentarios 0 reacciones 0 asignados Ver en GitHub

Los mantenedores suelen responder en 4 días

Nadie ha tomado este issue todavía.

Evaluación

Dificultad
4/5
Tiempo estimado
3-5 días
Aptitud para principiantes
42/100
Tipo de issue
Error
Claridad
Bien especificado
Estado de actividad
Activo
Stack tecnológico
python, pytorch

Línea de trabajo

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.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

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.

Lenguaje dominante
Python
Estrellas
5.2k
Forks
466
Merge medio
5 d 8 h
PR fusionados (30 d)
44

Preparar el entorno

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de InternLM/xtuner

Todos los issues de InternLM/xtuner

Issues similares

Más issues de Python

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.