[BUG] Universal checkpoint load never restores frozen parameters or buffers

Abierto
#9,134 2 comentarios 1 reacción 0 asignados Ver en GitHub

Los mantenedores suelen responder en 2 días

@varun-projects ya está trabajando en esto.

Desde el 21/11/2026.

  • #9139 de @varun-projects — abierto
  • #9182 de @themanoj-025 — abierto

Evaluación

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

Línea de trabajo

Read DeepSpeedEngine._load_checkpoint around engine.py:4752 and trace how ds_to_universal handles *_model_states.pt and frozen parameter fragments. Start with the reproduction in the issue and the proposed test location, tests/unit/checkpoint/test_universal_checkpoint.py. Done means universal loads restore frozen parameters and buffers across ZeRO stages, with coverage for the reported cases.

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

Descripción

Describe the bug
Loading a universal checkpoint (checkpoint: {load_universal: true} after ds_to_universal) never restores frozen parameters or buffers. Every tensor the optimizer does not own (frozen weights, BatchNorm running_mean/running_var/num_batches_tracked, other registered buffers) keeps whatever the freshly built model had. Trainable parameters come back correctly, and there is no warning.

The universal branch of DeepSpeedEngine._load_checkpoint skips load_module_state_dict (if not self.load_universal_checkpoint(): around engine.py:4752) because weights are restored from zero/<param>/fp32.pt. But ds_to_universal only writes those files for optimizer-owned parameters, so nothing restores the rest. The source *_model_states.pt files, which ds_to_universal already copies into the universal folder, still hold them.

To Reproduce
Save at DP=2 (frozen Linear plus a BatchNorm1d), convert with ds_to_universal, load with load_universal into a model built with a different seed, and compare the state dicts. Run from a checkout with DS_ACCELERATOR=cpu PYTHONPATH=. python repro_uc_frozen.py:

# Repro: loading a universal checkpoint never restores frozen parameters or buffers.
# Run from the DeepSpeed checkout: DS_ACCELERATOR=cpu PYTHONPATH=. python repro_uc_frozen.py
import os, sys, shutil, subprocess, tempfile, torch, torch.multiprocessing as mp
os.environ.setdefault("DS_ACCELERATOR", "cpu")

def make_model(seed):
    torch.manual_seed(seed)
    m = torch.nn.Sequential(torch.nn.Linear(16, 32), torch.nn.BatchNorm1d(32), torch.nn.GELU(), torch.nn.Linear(32, 32), torch.nn.GELU(), torch.nn.Linear(32, 4))
    m[3].requires_grad_(False)
    return m

def cfg(stage, universal):
    c = {"train_micro_batch_size_per_gpu": 4, "zero_optimization": {"stage": stage},
         "optimizer": {"type": "AdamW", "params": {"lr": 1e-2, "torch_adam": True}}}
    if universal: c["checkpoint"] = {"load_universal": True}
    return c

def worker(rank, ws, stage, mode, port, d):
    os.environ.update(MASTER_ADDR="127.0.0.1", MASTER_PORT=str(port), RANK=str(rank), WORLD_SIZE=str(ws), LOCAL_RANK=str(rank))
    import deepspeed, logging
    deepspeed.utils.logger.setLevel(logging.ERROR)
    deepspeed.init_distributed(dist_backend="gloo")
    m = make_model(0 if mode == "save" else 123)
    e, *_ = deepspeed.initialize(model=m, config=cfg(stage, mode == "load"), model_parameters=[p for p in m.parameters() if p.requires_grad])
    if mode == "save":
        for s in range(2):
            x = torch.randn(4, 16, generator=torch.Generator().manual_seed(s * 10 + rank)) + 3
            e.backward(e(x).pow(2).mean()); e.step()
        e.save_checkpoint(d + "/ck", tag="t", client_state={"universal_checkpoint_info": {}})
    else:
        e.load_checkpoint(d + "/uc", tag="t")
    import deepspeed as ds
    with ds.zero.GatheredParameters(list(e.module.parameters()), enabled=stage == 3):
        sd = {k: v.detach().float().clone() for k, v in e.module.state_dict().items()}
    if rank == 0: torch.save(sd, d + f"/{mode}.pt")

if __name__ == "__main__":
    for i, stage in enumerate((1, 2, 3)):
        d = tempfile.mkdtemp()
        mp.spawn(worker, args=(2, stage, "save", 29790 + 3 * i, d), nprocs=2, join=True)
        r = subprocess.run([sys.executable, "-m", "deepspeed.checkpoint.ds_to_universal", "--input_folder", d + "/ck/t",
                            "--output_folder", d + "/uc/t", "--num_extract_workers", "1", "--num_merge_workers", "1"], capture_output=True, text=True)
        assert r.returncode == 0, r.stderr[-1500:]
        mp.spawn(worker, args=(2, stage, "load", 29791 + 3 * i, d), nprocs=2, join=True)
        a, b = torch.load(d + "/save.pt"), torch.load(d + "/load.pt")
        diffs = {k: round(float((a[k] - b[k]).abs().max()), 4) for k in a}
        print(f"stage {stage}: max|loaded - saved| per tensor: " + ", ".join(f"{k}={v}" for k, v in diffs.items() if v > 0) or "all match")
        shutil.rmtree(d, ignore_errors=True)

Output on master (adcabcf9), same for every stage:

stage 1: max|loaded - saved| per tensor: 1.running_mean=0.7603, 1.running_var=0.1719, 1.num_batches_tracked=2.0, 3.weight=0.3506, 3.bias=0.2357
stage 2: max|loaded - saved| per tensor: 1.running_mean=0.7603, 1.running_var=0.1719, 1.num_batches_tracked=2.0, 3.weight=0.3506, 3.bias=0.2357
stage 3: max|loaded - saved| per tensor: 1.running_mean=0.7603, 1.running_var=0.1719, 1.num_batches_tracked=2.0, 3.weight=0.3506, 3.bias=0.2357

Expected behavior
After a universal load, frozen parameters and buffers match the saved model, as they do with a regular (non-universal) load.

Runs whose frozen weights are reloaded from pretrained at construction are not affected. Runs with stateful buffers (BatchNorm stats, counters, trained routing biases) or frozen weights the checkpoint is expected to supply silently resume from the wrong values.

A possible fix, and I'd like your view before a PR: in the universal branch, load buffers and frozen parameters from checkpoint['module'] with a shape check (so TP-resharded tensors are skipped with a warning rather than loaded wrongly). For ZeRO-3, frozen parameters are only saved as per-rank frozen_param_fragments, so they would need either ds_to_universal to write them to zero/<name>/fp32.pt like trainable parameters, or a merge at load time. Which direction would you prefer? I can send the PR with a test in tests/unit/checkpoint/test_universal_checkpoint.py.

ds_report output
DeepSpeed master adcabcf9, torch 2.11.0, CPU accelerator (DS_ACCELERATOR=cpu), gloo backend.

System info

  • OS: macOS (CPU only)
  • GPU count and types: none, 2 CPU processes
  • Python 3.11.9

Launcher context
torch.multiprocessing.spawn with deepspeed.init_distributed(dist_backend="gloo") (see the script).

Lenguaje dominante
Python
Estrellas
43.3k
Forks
5.1k
Merge medio
5 d 10 h
PR fusionados (30 d)
85

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 deepspeedai/DeepSpeed

Todos los issues de deepspeedai/DeepSpeed

Issues similares

Más issues de Python

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.