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

オープン
#9,134 コメント 2 件 リアクション 1 件 担当者 0 名 GitHub で見る

メンテナーはふだん 2 日以内に返信

@varun-projects がすでに取り組んでいます。

2026年11月21日 から。

  • #9139 @varun-projects による — オープン
  • #9182 @themanoj-025 による — オープン

評価

難易度
4/5
見積もり時間
3〜5日
初心者へのやさしさ
50/100
issue の種類
バグ
明瞭さ
明確に書かれている
活発さ
活発
技術スタック
python, pytorch

調査の方向性

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.

索引モデルが issue の本文から書いたものです。

説明

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

主要言語
Python
スター
43.3k
フォーク
5.1k
平均マージ
5日 10時間
マージ済み PR(30日)
85

環境構築

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

deepspeedai/DeepSpeed のほかの issue

deepspeedai/DeepSpeed の issue をすべて見る

似ている issue

Python の issue をもっと見る

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。