蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行 PyTorch 2.10 安全加载、断点续训、前缀清理与 strict=False 实验

PYTHONWindows CPU、CPython 3.12.14、PyTorch 2.10.0+cpu。explore-model-save-load.py
explore-model-save-load.py210 行
"""Independent PyTorch 2.10 CPU observations for model saving, loading, checkpoints and strictness."""
import json
import pickle
import platform
import tempfile
from pathlib import Path

import torch
import torch.nn as nn
import torch.optim as optim


class SimpleModel(nn.Module):
    def __init__(self, in_dim: int = 10, out_dim: int = 2):
        super().__init__()
        self.fc = nn.Linear(in_dim, out_dim)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        return self.fc(x)


class ExtendedModel(nn.Module):
    """Variant with one renamed/added layer to test strict=False IncompatibleKeys."""

    def __init__(self):
        super().__init__()
        self.fc = nn.Linear(10, 2)
        self.extra_head = nn.Linear(2, 2)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        return self.extra_head(self.fc(x))


def run_cases():
    torch.manual_seed(2026)
    cases = []

    with tempfile.TemporaryDirectory() as tmp:
        tmp_dir = Path(tmp)

        # 1. PyTorch 2.6+/2.10 default weights_only=True blocks whole-model pickle unless allowed
        m0 = SimpleModel().eval()
        whole_path = tmp_dir / "whole_model.pth"
        sd_path = tmp_dir / "model_weights.pth"
        torch.save(m0, whole_path)
        torch.save(m0.state_dict(), sd_path)
        default_blocked = False
        try:
            torch.load(whole_path)  # PyTorch 2.10 defaults to weights_only=True
        except (pickle.UnpicklingError, RuntimeError):
            default_blocked = True
        with torch.serialization.safe_globals([SimpleModel, nn.Linear]):
            reloaded_safe = torch.load(whole_path, weights_only=True)
        whole_size = whole_path.stat().st_size
        sd_size = sd_path.stat().st_size
        x_test = torch.randn(3, 10)
        with torch.inference_mode():
            whole_diff = float((m0(x_test) - reloaded_safe(x_test)).abs().max().item())
        c1_ok = default_blocked and whole_diff == 0.0 and sd_size < whole_size
        cases.append(dict(
            name="weights_only_default_and_whole_model",
            inputs=dict(whole_file="whole_model.pth", state_dict_file="model_weights.pth"),
            prerequisites="PyTorch 2.10 默认 torch.load(..., weights_only=True)",
            action="验证整模型 pickle 在默认安全模式下会被阻止,需配合 safe_globals 或改存更小更安全的 state_dict。",
            expected=dict(default_blocks_custom_class=True, safe_globals_matches=True, state_dict_smaller=True),
            actual=dict(default_blocks_custom_class=default_blocked, safe_globals_matches=whole_diff == 0.0, state_dict_smaller=sd_size < whole_size),
            measurements=dict(whole_bytes=whole_size, state_dict_bytes=sd_size),
            passed=c1_ok,
        ))

        # 2. Recommended state_dict save & load + eval mode verification
        m_loaded = SimpleModel()
        m_loaded.load_state_dict(torch.load(sd_path, weights_only=True))
        m_loaded.eval()
        with torch.inference_mode():
            sd_diff = float((m0(x_test) - m_loaded(x_test)).abs().max().item())
        c2_ok = sd_diff == 0.0 and not m_loaded.training
        cases.append(dict(
            name="state_dict_save_load_eval",
            inputs=dict(keys=list(m0.state_dict().keys())),
            prerequisites="先实例化同结构模型再加载 state_dict 并切换 eval()",
            action="验证 state_dict 以 weights_only=True 加载后前向输出与原模型逐位一致。",
            expected=dict(output_exact=True, eval_mode=True),
            actual=dict(output_exact=sd_diff == 0.0, eval_mode=not m_loaded.training),
            passed=c2_ok,
        ))

        # 3. Training checkpoint save/resume loop (saving loss.item() scalar)
        torch.manual_seed(7)
        m_tr = SimpleModel()
        opt_tr = optim.SGD(m_tr.parameters(), lr=0.05, momentum=0.9)
        crit = nn.CrossEntropyLoss()
        x_b = torch.randn(32, 10)
        y_b = torch.randint(0, 2, (32,))
        ckpt_files = []
        for epoch in range(5):
            opt_tr.zero_grad(set_to_none=True)
            loss = crit(m_tr(x_b), y_b)
            loss.backward()
            opt_tr.step()
            if epoch % 2 == 0:
                cp = tmp_dir / f"checkpoint_epoch{epoch}.pth"
                torch.save({
                    "epoch": epoch,
                    "model_state_dict": m_tr.state_dict(),
                    "optimizer_state_dict": opt_tr.state_dict(),
                    "loss": float(loss.item()),
                }, cp)
                ckpt_files.append(cp.name)
        # Resume from epoch 4 checkpoint and verify next step equivalence
        ckpt4 = torch.load(tmp_dir / "checkpoint_epoch4.pth", weights_only=True)
        m_res = SimpleModel()
        opt_res = optim.SGD(m_res.parameters(), lr=0.05, momentum=0.9)
        m_res.load_state_dict(ckpt4["model_state_dict"])
        opt_res.load_state_dict(ckpt4["optimizer_state_dict"])
        for mod, o in ((m_tr, opt_tr), (m_res, opt_res)):
            o.zero_grad(set_to_none=True)
            crit(mod(x_b), y_b).backward()
            o.step()
        resume_err = max(float((a - b).abs().max().item()) for a, b in zip(m_tr.parameters(), m_res.parameters()))
        c3_ok = ckpt_files == ["checkpoint_epoch0.pth", "checkpoint_epoch2.pth", "checkpoint_epoch4.pth"] and resume_err < 1e-6 and isinstance(ckpt4["loss"], float)
        cases.append(dict(
            name="checkpoint_resume_loop",
            inputs=dict(epochs=5, save_every=2),
            prerequisites="每 2 轮保存 epoch/model/optimizer/loss.item(),用 weights_only=True 恢复",
            action="验证断点续训后下一轮带 momentum 更新与连续训练完全一致。",
            expected=dict(checkpoints_count=3, resume_exact=True, loss_is_float=True),
            actual=dict(checkpoints_count=len(ckpt_files), resume_exact=resume_err < 1e-6, loss_is_float=isinstance(ckpt4["loss"], float)),
            measurements=dict(saved_files=ckpt_files, max_param_diff=round(resume_err, 9)),
            passed=c3_ok,
        ))

        # 4. map_location="cpu" + DataParallel/DDP "module." prefix stripping
        dp_state = {f"module.{k}": v.clone() for k, v in m0.state_dict().items()}
        dp_path = tmp_dir / "multigpu_wrapped.pth"
        torch.save(dp_state, dp_path)
        loaded_dp = torch.load(dp_path, map_location=torch.device("cpu"), weights_only=True)
        strict_fail_on_prefix = False
        try:
            SimpleModel().load_state_dict(loaded_dp, strict=True)
        except RuntimeError:
            strict_fail_on_prefix = True
        cleaned = {k.removeprefix("module."): v for k, v in loaded_dp.items()}
        m_clean = SimpleModel()
        m_clean.load_state_dict(cleaned, strict=True)
        clean_err = max(float((a - b).abs().max().item()) for a, b in zip(m0.parameters(), m_clean.parameters()))
        c4_ok = strict_fail_on_prefix and clean_err == 0.0
        cases.append(dict(
            name="map_location_and_module_prefix",
            inputs=dict(map_location="cpu", wrapped_prefix="module."),
            prerequisites="模拟 DataParallel/DDP 保存的 module. 键前缀",
            action="证明直接加载带 module. 前缀的权重会触发键不匹配,去除前缀并以 map_location='cpu' 可无损载入单设备模型。",
            expected=dict(prefixed_rejected=True, stripped_exact=True),
            actual=dict(prefixed_rejected=strict_fail_on_prefix, stripped_exact=clean_err == 0.0),
            passed=c4_ok,
        ))

        # 5. Zipfile serialization header + TorchScript script/save/load roundtrip
        zip_path = tmp_dir / "model_zip.pth"
        torch.save(m0.state_dict(), zip_path, _use_new_zipfile_serialization=True)
        is_zip_magic = zip_path.read_bytes()[:4] == b"PK\x03\x04"
        scripted = torch.jit.script(m0)
        ts_path = tmp_dir / "model_scripted.pt"
        torch.jit.save(scripted, str(ts_path))
        loaded_ts = torch.jit.load(str(ts_path), map_location="cpu")
        with torch.inference_mode():
            ts_err = float((m0(x_test) - loaded_ts(x_test)).abs().max().item())
        c5_ok = is_zip_magic and ts_err == 0.0
        cases.append(dict(
            name="zipfile_and_torchscript_roundtrip",
            inputs=dict(zip_serialization=True, torchscript="script"),
            prerequisites="_use_new_zipfile_serialization=True 与 torch.jit.script/save/load",
            action="核对新序列化格式以 ZIP 文件头封装,且 TorchScript 独立重载输出一致。",
            expected=dict(zip_magic_ok=True, torchscript_exact=True),
            actual=dict(zip_magic_ok=is_zip_magic, torchscript_exact=ts_err == 0.0),
            passed=c5_ok,
        ))

        # 6. strict=True error vs strict=False IncompatibleKeys report
        ext = ExtendedModel()
        strict_rejected = False
        try:
            ext.load_state_dict(torch.load(sd_path, weights_only=True), strict=True)
        except RuntimeError:
            strict_rejected = True
        incompat = ext.load_state_dict(torch.load(sd_path, weights_only=True), strict=False)
        missing_ok = sorted(incompat.missing_keys) == ["extra_head.bias", "extra_head.weight"]
        unexpected_ok = incompat.unexpected_keys == []
        c6_ok = strict_rejected and missing_ok and unexpected_ok
        cases.append(dict(
            name="strict_false_missing_unexpected_keys",
            inputs=dict(target_model="ExtendedModel", source_keys=["fc.weight", "fc.bias"]),
            prerequisites="目标模型新增 extra_head 层",
            action="验证 strict=True 抛出 Missing key RuntimeError,strict=False 加载匹配层并准确报告 missing_keys。",
            expected=dict(strict_rejected=True, missing_keys=["extra_head.bias", "extra_head.weight"], unexpected_empty=True),
            actual=dict(strict_rejected=strict_rejected, missing_keys=sorted(incompat.missing_keys), unexpected_empty=unexpected_ok),
            passed=c6_ok,
        ))

    print(json.dumps(dict(
        version=platform.python_version(),
        torch=torch.__version__,
        system=platform.system(),
        cases=cases,
    ), ensure_ascii=False))


if __name__ == "__main__":
    run_cases()
本例需在 Windows CPU、CPython 3.12.14、PyTorch 2.10.0+cpu。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows CPU、CPython 3.12.14、PyTorch 2.10.0+cpu。

入口文件:projects/pytorch-model-save-lab/explore-model-save-load.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-model-save-load.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows CPU、CPython 3.12.14、PyTorch 2.10.0+cpu。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:PyTorch

课程关联工程包(登记关联39章) · 含当前章节或实例 · mbskycom202612a409.zip

下载课程关联工程包:PyTorch

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a431.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习