保存、加载与预训练权重

Dive into Deep Learning · §5.6

文件读写、检查点与序列化
状态字典 · pickle 远程代码执行与 safetensors 对比 · 五部分原子检查点 · 预训练键审计

为何检查点与安全文件格式至关重要

容错与安全

  • 硬件故障是常态:在 16{,}384 块 GPU 上预训练 Llama 3 405B 的 54 天里,Meta 记录了 419 次意外中断(约每 3 小时崩溃 1 次)。
  • 恢复训练不止需要权重:仅凭保存的权重重启 Adam,第一步更新就会让损失暴涨 >100\times。
  • 加载时任意代码执行:下载第三方 pickle 检查点后,调用 load 的瞬间就可能执行恶意 shell 命令。

只序列化状态树,绝不序列化 Python 类代码

状态与架构

  • 状态字典仅存储 (path, shape, dtype, raw_bytes),不包含 MLP 类的任何痕迹:
class MLP(nn.Module):
    def __init__(self):
        super().__init__()
        self.hidden = nn.Linear(20, 256)
        self.output = nn.Linear(256, 10)

    def forward(self, x):
        return self.output(F.relu(self.hidden(x)))

net = MLP()
X = torch.randn(2, 20)
Y = net(X)
{name: tuple(t.shape) for name, t in net.state_dict().items()}
{'hidden.weight': (256, 20),
 'hidden.bias': (256,),
 'output.weight': (10, 256),
 'output.bias': (10,)}

安全隐患:Python Pickle 在加载时执行代码

为何 Pickle 不适合共享

  • Python 的 pickle 格式本质上是基于栈的虚拟机,会执行 __reduce__ 返回的任意可调用对象:
class Tripwire:
    def __reduce__(self):  # pickle calls print(...) to rebuild the object
        return (print, ('*** payload executed while loading ***',))
torch.save(Tripwire(), 'tripwire.pt')
_ = torch.load('tripwire.pt', weights_only=False)  # the payload runs here
*** payload executed while loading ***

加固加载器默认拒绝任意对象

白名单反序列化器

  • 加固加载器会拒绝任意 pickle 对象,而 safetensors 则彻底消除了操作码解析器的攻击面:
try:
    torch.load('tripwire.pt')  # weights_only=True, the default
except Exception as e:
    print(type(e).__name__, str(e).split('.')[0])
UnpicklingError Weights only load failed

safetensors 格式:零代码、零拷贝 mmap

安全权重交换

一个 safetensors 文件由三个扁平段构成,仅存放被动元数据与原始张量字节:

  1. 8 字节无符号小端整数(<Q):JSON 头部的精确字节长度 n。
  2. UTF-8 JSON 头部(n 字节):将每个张量的路径名映射到其 dtype、shape 以及相对于数据段的 [begin, end] 字节偏移量。
  3. 紧凑排列的原始张量字节:首尾相连的连续数组缓冲区,支持即时的零拷贝内存映射(mmap)和单张量随机访问,无需读取整个文件。

逐字节保存与审计 safetensors 文件

safetensors 存取往返与头部检查

  • 我们将 MLP 保存到 mlp.safetensors,验证逐位还原,并使用标准库 struct 和 json 解析其头部。

保存与还原 safetensors 文件

safetensors 存取往返与头部检查

save_file(net.state_dict(), 'mlp.safetensors')
clone = MLP()
clone.load_state_dict(load_file('mlp.safetensors'))
torch.equal(clone(X), Y)

手动解析 safetensors 头部

safetensors 存取往返与头部检查

with open('mlp.safetensors', 'rb') as f:
    n = struct.unpack('<Q', f.read(8))[0]  # header length, little-endian
    header = json.loads(f.read(n))
print('header length:', n, 'bytes')
for name, entry in sorted(header.items(), key=lambda e: e[1]['data_offsets']):
    print(f"{name:18s} {entry['dtype']} {str(entry['shape']):10s} "
          f"bytes {entry['data_offsets']}")
header length: 296 bytes
hidden.bias        F32 [256]      bytes [0, 1024]
hidden.weight      F32 [256, 20]  bytes [1024, 21504]
output.bias        F32 [10]       bytes [21504, 21544]
output.weight      F32 [10, 256]  bytes [21544, 31784]

为何恢复训练需要优化器状态

Adam 的有状态优化

\mathbf{w} \leftarrow \mathbf{w} - \eta \, \frac{\hat{\mathbf{m}}}{\sqrt{\hat{\mathbf{v}}} + \epsilon}

  • 全新 Adam 为何引发损失飙升:恢复训练时若丢弃 \mathbf{m} 和 \mathbf{v}(\mathbf{m}_0 = \mathbf{v}_0 = \mathbf{0}),第 1 步偏差校正会强制得出 \hat{\mathbf{m}}_1 = \mathbf{g} 和 \hat{\mathbf{v}}_1 = \mathbf{g} \odot \mathbf{g}。
  • 全步长冲击:每个参数都迈出 \Delta w_i = -\eta \, \frac{g_i}{|g_i| + \epsilon} \approx \pm \eta 的步长,直接跳出已收敛的极小值盆地。

可恢复训练检查点的五个组成部分

完整检查点剖析

  • 五项必需状态:模型状态(参数 + 缓冲区)、优化器状态(\mathbf{m}, \mathbf{v})、PRNG 状态(CPU、GPU、数据加载器)、步数计数器 t 以及架构配置。
  • 防崩溃原子写入:始终先写入临时文件(path + '.tmp'),再调用 os.replace(tmp, path),确保写入中途崩溃也不会损坏先前的检查点。

估算 8B 参数检查点大小:磁盘占用 96 GB

检查点存储计算

  • 推理文件(bf16 格式,16 GB):仅存储占 2\text{ B/param} 的模型权重 \mathbf{w}。
  • 可恢复训练检查点(fp32 格式,96 GB):存储权重 \mathbf{w}(32 GB)+ Adam \mathbf{m}(32 GB)+ Adam \mathbf{v}(32 GB)= 12\text{ B/param}(为推理文件的 6\times;梯度 \mathbf{g} 不保存到磁盘)。

实现原子保存与加载辅助函数

代码中的防崩溃检查点

  • 我们的 save_checkpoint 辅助函数将全部五个组成部分打包,并通过 os.replace 原子提交。

代码中的原子保存与加载辅助函数

代码中的防崩溃检查点

def save_checkpoint(path, model, optimizer, step, cfg=None, rng=None):
    """Atomically write a resumable training checkpoint."""
    ckpt = {'model': model.state_dict(),
            'optimizer': optimizer.state_dict(),
            'step': step,
            'cpu_rng': torch.get_rng_state()}
    if cfg is not None:
        ckpt['cfg'] = asdict(cfg)
    if rng is not None:                        # a torch.Generator
        ckpt['rng'] = rng.get_state()
    if torch.cuda.is_available():
        ckpt['cuda_rng'] = torch.cuda.get_rng_state_all()
    tmp = path + '.tmp'
    torch.save(ckpt, tmp)
    os.replace(tmp, path)

def load_checkpoint(path, model, optimizer=None, rng=None):
    """Restore the state written by save_checkpoint; return the raw dict."""
    ckpt = torch.load(path, weights_only=True)
    model.load_state_dict(ckpt['model'])
    if optimizer is not None:
        optimizer.load_state_dict(ckpt['optimizer'])
    if rng is not None:
        rng.set_state(ckpt['rng'])
    torch.set_rng_state(ckpt['cpu_rng'])
    if torch.cuda.is_available() and 'cuda_rng' in ckpt:
        torch.cuda.set_rng_state_all(ckpt['cuda_rng'])
    return ckpt

200 步后测试逐位一致恢复

实验验证

  • 恢复全部五个分区可逐位一致地复现第 201–205 步(差异为 0.0),而省略 RNG 状态会重放早期小批量:
for name, kwargs in (('full checkpoint', {}),
                     ('without the generator', {'restore_rng': False})):
    resumed, _ = resume(path, 205, **kwargs)
    print(f'{name:22s} max |difference| {max_diff(resumed, net):.3g}')
full checkpoint        max |difference| 0
without the generator  max |difference| 0.00397

丢弃优化器状态会摧毁近乎收敛的模型

全新 Adam 引发的损失尖峰

  • 从第 200 步恢复保存的权重和 RNG 状态——却使用全新初始化的 Adam 优化器——会在首次更新后立即使损失飙升约三个数量级:
_, full = resume(path, 205)
_, fresh = resume(path, 205, restore_optimizer=False)
print('saved optimizer:', [round(l, 4) for l in full])
print('fresh optimizer:', [round(l, 4) for l in fresh])
saved optimizer: [0.0009, 0.0017, 0.0022, 0.001, 0.0019]
fresh optimizer: [0.0009, 2.1294, 0.6979, 0.7146, 0.9511]

在新输出头下加载预训练骨干权重

迁移学习设置

将 ImageNet 预训练的 ResNet-50(\sim 25\text{M} 参数,1{,}000 类)适配到 10 分类数据集时,我们保留预训练骨干并替换最后的线性输出头(2048 -> 10):

net = resnet50(weights=ResNet50_Weights.DEFAULT)  # ~100 MB once
net.fc = nn.Linear(net.fc.in_features, 10)        # new 10-class head
net.fc
Linear(in_features=2048, out_features=10, bias=True)

部分加载时审计缺失键与多余键

捕获静默检查点不匹配

  • 以非严格模式将外部权重加载到修改后的架构时,务必检查缺失键与多余键。

解读部分加载的键审计报告

捕获静默检查点不匹配

damaged = {k: v for k, v in net.state_dict().items()
           if not k.startswith(('fc.', 'layer4.'))}
target = resnet50(weights=None)
target.fc = nn.Linear(target.fc.in_features, 10)
report = target.load_state_dict(damaged, strict=False)
print('missing by block:', dict(Counter(
    k.split('.')[0] for k in report.missing_keys)))
print('unexpected:', report.unexpected_keys)
missing by block: {'layer4': 50, 'fc': 2}
unexpected: []

概念自测:序列化与检查点恢复

概念自测

解答以下三道检查点问题:

  1. 假设保存为 mlp.safetensors 的 MLP(20 \to 256 \to 10,float32)包含 n = 296 字节的 JSON 头部(精确长度取决于框架写入的张量名)。文件总大小精确为多少字节?
  2. 我们的 20 \to 64 \to 1 回归器共有 20 \times 64 + 64 + 64 \times 1 + 1 = 1{,}409 个参数。若以 \eta = 0.05 配全新 Adam 优化器(\mathbf{m}=\mathbf{v}=\mathbf{0})恢复训练且每个梯度分量非零,第一步参数更新的欧氏范数 \|\Delta \mathbf{w}\|_2 为多少?
  3. 在 ResNet-50 中将 self.fc 重命名为 self.classifier,并用 strict=False 加载原始预训练检查点。missing_keys 和 unexpected_keys 中分别会出现什么?

答案:

  1. 8 + 296 + 4 \times 7{,}946 = 32{,}088 字节:8 字节长度前缀 + 296 字节 JSON 头部 + 7{,}946 个 float32 参数所占 31{,}784 字节。
  2. \|\Delta \mathbf{w}\|_2 \approx 0.05 \sqrt{1{,}409} \approx 1.88:无论 \|\mathbf{g}\|_2 多小,每个坐标都会移动 \pm \eta = \pm 0.05。
  3. missing_keys 列出 classifier.weight, classifier.bias(保持随机初始化);unexpected_keys 列出 fc.weight, fc.bias(从文件中忽略)。

小结:保存、加载与预训练权重

核心要点

  • 状态字典与 safetensors:按键路径保存张量数据;使用 safetensors(8 字节长度 + JSON + 原始字节)实现零 RCE、零拷贝 mmap 共享。
  • 五组件原子检查点:通过 .tmp + os.replace 保存模型状态、优化器 \mathbf{m}, \mathbf{v}、PRNG 状态、步数 t 和配置(8B 模型为 12\text{ B/param} = 96\text{ GB})。
  • 预训练键审计:断言 missing_keys 和 unexpected_keys 仅匹配有意替换的层。