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

Đang mở
#9,134 2 bình luận 1 reaction 0 người được giao Xem trên GitHub

Maintainer thường phản hồi trong vòng 2 ngày

@varun-projects đang làm issue này rồi.

Từ ngày 21/11/2026.

  • #9139 của @varun-projects — đang mở
  • #9182 của @themanoj-025 — đang mở

Đánh giá

Độ khó
4/5
Thời gian dự kiến
3-5 ngày
Mức phù hợp với người mới
50/100
Loại issue
Lỗi
Độ rõ ràng
Đặc tả rõ ràng
Mức độ hoạt động
Sôi nổi
Công nghệ
python, pytorch

Hướng nghiên cứu

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.

Do mô hình lập chỉ mục viết ra từ nội dung của issue.

Mô tả

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).

Ngôn ngữ chính
Python
Star
43.3k
Fork
5.1k
Merge trung bình
5 ngày 10 giờ
Pull request đã merge (30 ngày)
85

Chuẩn bị môi trường

Bắt đầu từ đâu

  1. Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
  2. Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
  3. Fork repository và làm thay đổi trên một nhánh.
  4. Mở pull request có tham chiếu số hiệu của issue.

Issue khác của deepspeedai/DeepSpeed

Tất cả issue của deepspeedai/DeepSpeed

Issue tương tự

Thêm issue về Python

Nhận issue mới trong hộp thư của bạn

Bản tóm tắt ngắn những issue GitHub phù hợp với người mới.