从state_dict原理到断点续训、模型导出与版本管理,掌握模型全生命周期工程实践
训练一个模型可能需要数小时甚至数月,而一次程序崩溃就可能丢失所有进度。模型的保存与加载不仅是简单的序列化操作,更涉及断点续训、跨设备迁移、版本兼容、模型导出等工程问题。对于大模型训练,这些技能尤为关键。
本章将系统讲解PyTorch模型保存与加载的方方面面,从基础的state_dict到高级的TorchScript导出和ONNX部署。
state_dict是PyTorch模型保存与加载的核心数据结构,理解它是掌握模型持久化的前提。
state_dict是一个Python有序字典(OrderedDict),键是参数名(如"layer1.weight"),值是对应的Tensor。它包含模型的所有可学习参数(Parameter)和缓冲区(Buffer,如BatchNorm的running_mean)。
import torch
import torch.nn as nn
# 创建简单模型
model = nn.Sequential(
nn.Linear(10, 20),
nn.BatchNorm1d(20),
nn.ReLU(),
nn.Linear(20, 5),
)
# 查看state_dict
sd = model.state_dict()
print(f"类型: {type(sd)}")
for key, value in sd.items():
print(f" {key}: {value.shape}")
# 0.weight: torch.Size([20, 10]) ← 参数
# 0.bias: torch.Size([20]) ← 参数
# 1.weight: torch.Size([20]) ← 参数
# 1.bias: torch.Size([20]) ← 参数
# 1.running_mean: torch.Size([20]) ← 缓冲区
# 1.running_var: torch.Size([20]) ← 缓冲区
# 1.num_batches_tracked: torch.Size([]) ← 缓冲区
# 3.weight: torch.Size([5, 20]) ← 参数
# 3.bias: torch.Size([5]) ← 参数
参数(Parameter)是需要梯度优化的权重,如Linear的weight和bias。缓冲区(Buffer)是不需要梯度但需要保存的状态,如BatchNorm的running_mean和running_var。两者都会出现在state_dict中。
# 区分参数和缓冲区
print("可学习参数:")
for name, param in model.named_parameters():
print(f" {name}: {param.shape}, requires_grad={param.requires_grad}")
print("\n缓冲区:")
for name, buf in model.named_buffers():
print(f" {name}: {buf.shape}")
class CustomLayer(nn.Module):
def __init__(self, d_model):
super().__init__()
self.weight = nn.Parameter(torch.randn(d_model, d_model))
# 注册缓冲区:会被state_dict保存,但不参与梯度优化
self.register_buffer('position_encoding', torch.randn(100, d_model))
# 非缓冲区属性:不会被state_dict保存
self.scaling = 0.1
def forward(self, x):
return self.weight @ x * self.scaling
layer = CustomLayer(64)
print(f"state_dict键: {list(layer.state_dict().keys())}")
# ['weight', 'position_encoding'] — scaling不在其中
# 方式1:保存state_dict(推荐)
torch.save(model.state_dict(), 'model_weights.pth')
# 加载state_dict
model_new = nn.Sequential(/* 同样的结构 */)
model_new.load_state_dict(torch.load('model_weights.pth'))
model_new.eval() # 切换到推理模式
# 方式2:保存完整模型(不推荐)
torch.save(model, 'full_model.pth')
model_loaded = torch.load('full_model.pth')
PyTorch 2.6+默认使用weights_only=True加载,防止恶意pickle反序列化攻击。如果保存的文件包含非Tensor对象,需要显式设置weights_only=False。
# 安全加载(默认,推荐)
state_dict = torch.load('model_weights.pth', weights_only=True)
# 加载包含非Tensor对象的checkpoint
checkpoint = torch.load('checkpoint.pth', weights_only=False)
# PyTorch 2.6+ 可以通过add_safe_globals添加允许的全局对象
torch.serialization.add_safe_globals([nn.LayerNorm, nn.GELU])
safe_data = torch.load('data.pth', weights_only=True)
| 方式 | 保存内容 | 加载时需要模型定义 | 跨项目可移植 | 推荐 |
|---|---|---|---|---|
| state_dict | 仅参数张量 | 是 | 是 | ✅ 推荐 |
| 完整模型 | 模型对象+参数 | 否 | 否 | ❌ 不推荐 |
使用torch.save(model)保存完整模型时,pickle会序列化整个Python对象,包括类定义的路径。如果加载时模型类定义不在相同路径,会报错。此外,加载不受信任的模型文件可能导致任意代码执行。始终优先使用state_dict方式。
长时间训练中,断点续训是必须的。一个完整的checkpoint不仅包含模型参数,还需要保存优化器状态、当前epoch、学习率调度器状态等。
def save_checkpoint(epoch, model, optimizer, scheduler, best_loss, path):
"""保存完整训练状态"""
checkpoint = {
'epoch': epoch,
'model_state_dict': model.state_dict(),
'optimizer_state_dict': optimizer.state_dict(),
'scheduler_state_dict': scheduler.state_dict() if scheduler else None,
'best_loss': best_loss,
}
torch.save(checkpoint, path)
print(f"Checkpoint saved: {path} (epoch={epoch})")
def load_checkpoint(model, optimizer, scheduler, path, device='cpu'):
"""加载训练状态"""
checkpoint = torch.load(path, map_location=device, weights_only=False)
model.load_state_dict(checkpoint['model_state_dict'])
optimizer.load_state_dict(checkpoint['optimizer_state_dict'])
if scheduler and checkpoint['scheduler_state_dict']:
scheduler.load_state_dict(checkpoint['scheduler_state_dict'])
return checkpoint['epoch'], checkpoint['best_loss']
# 带断点续训的训练循环
start_epoch = 0
best_loss = float('inf')
# 尝试加载checkpoint
if os.path.exists('checkpoint.pth'):
start_epoch, best_loss = load_checkpoint(
model, optimizer, scheduler, 'checkpoint.pth', device)
print(f"Resumed from epoch {start_epoch}, best_loss={best_loss:.4f}")
for epoch in range(start_epoch, num_epochs):
model.train()
for batch in train_loader:
loss = train_step(model, batch, optimizer)
# 验证
val_loss = validate(model, val_loader)
# 保存最佳模型
if val_loss < best_loss:
best_loss = val_loss
torch.save(model.state_dict(), 'best_model.pth')
# 定期保存checkpoint
if epoch % 5 == 0:
save_checkpoint(epoch + 1, model, optimizer, scheduler,
best_loss, 'checkpoint.pth')
Adam等自适应优化器内部维护每个参数的动量和方差估计,这些状态对训练稳定性至关重要。如果不保存优化器状态,恢复训练时这些统计量会被重置,导致训练不稳定。
# 查看Adam优化器状态
optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)
# 训练几步后...
loss = model(input).sum()
loss.backward()
optimizer.step()
# 查看优化器状态
opt_state = optimizer.state_dict()
print(f"优化器状态键: {list(opt_state.keys())}")
for param_group in opt_state['param_groups']:
print(f" lr: {param_group['lr']}")
for key, val in opt_state['state'].items():
print(f" 参数{key}: step={val['step']}, exp_avg形状={val['exp_avg'].shape}")
TorchScript将PyTorch模型转换为可在C++中运行的静态计算图,无需Python环境。有两种方式:torch.jit.script(从代码分析)和torch.jit.trace(通过示例输入追踪)。
# 方式1: torch.jit.script(推荐,支持控制流)
scripted_model = torch.jit.script(model)
scripted_model.save('model_scripted.pt')
# 在C++中加载
# auto model = torch::jit::load("model_scripted.pt");
# 方式2: torch.jit.trace(通过示例输入追踪)
example_input = torch.randn(1, 3, 224, 224)
traced_model = torch.jit.trace(model, example_input)
traced_model.save('model_traced.pt')
# 加载TorchScript模型
loaded = torch.jit.load('model_scripted.pt')
output = loaded(example_input)
ONNX(Open Neural Network Exchange)是跨框架的模型格式,可以在不同深度学习框架间转换,也可用ONNX Runtime高效推理。
# 导出ONNX模型
dummy_input = torch.randn(1, 3, 224, 224)
model.eval()
torch.onnx.export(
model,
dummy_input,
'model.onnx',
export_params=True, # 导出模型参数
opset_version=17, # ONNX算子集版本
do_constant_folding=True, # 常量折叠优化
input_names=['input'], # 输入名
output_names=['output'], # 输出名
dynamic_axes={
'input': {0: 'batch_size'}, # 动态batch
'output': {0: 'batch_size'},
}
)
# 使用ONNX Runtime推理
import onnxruntime as ort
session = ort.InferenceSession('model.onnx')
results = session.run(None, {'input': dummy_input.numpy()})
| 导出方式 | 运行环境 | 支持动态形状 | 跨框架 | 推理速度 |
|---|---|---|---|---|
| state_dict | PyTorch | 是 | 否 | 基准 |
| TorchScript | libtorch(C++) | 是(script) | 否 | ~1-2x |
| ONNX | ONNX Runtime | 是 | 是 | ~2-5x |
| TorchExport | PyTorch 2.x | 是 | 否 | ~2-3x |
import torchvision.models as models
# 加载预训练ResNet50
model = models.resnet50(weights=models.ResNet50_Weights.IMAGENET1K_V2)
# 查看模型结构并修改分类头
num_features = model.fc.in_features
model.fc = nn.Linear(num_features, 100) # 100类分类
# 加载自己保存的权重
model.load_state_dict(torch.load('my_resnet50.pth', weights_only=True))
# 部分加载(迁移学习场景)
pretrained = torch.load('pretrained.pth', weights_only=True)
model_state = model.state_dict()
# 只加载匹配的键
matched = {k: v for k, v in pretrained.items()
if k in model_state and v.shape == model_state[k].shape}
model_state.update(matched)
model.load_state_dict(model_state)
print(f"加载了 {len(matched)}/{len(model_state)} 个参数")
# 使用transformers库加载预训练模型
from transformers import AutoModel, AutoTokenizer, AutoModelForCausalLM
# 加载BERT
tokenizer = AutoTokenizer.from_pretrained('bert-base-chinese')
model = AutoModel.from_pretrained('bert-base-chinese')
# 加载GPT风格模型
model = AutoModelForCausalLM.from_pretrained('gpt2')
# 加载量化模型(减少显存)
from transformers import BitsAndBytesConfig
quantization_config = BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_compute_dtype=torch.float16
)
model = AutoModelForCausalLM.from_pretrained(
'meta-llama/Llama-2-7b-hf',
quantization_config=quantization_config,
device_map='auto'
)
HuggingFace推荐使用safetensors格式,比pickle更快且更安全(不支持任意代码执行)。
# 使用safetensors保存
from safetensors.torch import save_file, load_file
# 保存(必须是state_dict且在CPU上)
state_dict = {k: v.cpu() for k, v in model.state_dict().items()}
save_file(state_dict, 'model.safetensors')
# 加载
loaded_state = load_file('model.safetensors')
model.load_state_dict(loaded_state)
模型可能在GPU上训练,但需要在CPU上推理。map_location参数控制加载时的设备映射。
# GPU训练的模型在CPU上加载
state_dict = torch.load('gpu_model.pth', map_location='cpu', weights_only=True)
model.load_state_dict(state_dict)
# CPU训练的模型加载到GPU
device = torch.device('cuda:0')
state_dict = torch.load('cpu_model.pth', map_location=device, weights_only=True)
model.load_state_dict(state_dict)
model = model.to(device)
# 多GPU到单GPU
state_dict = torch.load('multi_gpu_model.pth', map_location='cpu', weights_only=True)
# 去除DataParallel的"module."前缀
state_dict = {k.replace('module.', ''): v for k, v in state_dict.items()}
model.load_state_dict(state_dict)
# 保存版本信息
checkpoint = {
'model_state_dict': model.state_dict(),
'pytorch_version': torch.__version__,
'model_config': {'d_model': 512, 'num_layers': 12},
'epoch': 100,
}
torch.save(checkpoint, 'model_v1.pth')
# 加载时检查版本
loaded = torch.load('model_v1.pth', weights_only=False)
if loaded['pytorch_version'] != torch.__version__:
print(f"Warning: saved with {loaded['pytorch_version']}, "
f"current is {torch.__version__}")
# 模型结构变化后加载旧权重
new_state = model.state_dict()
old_state = torch.load('old_model.pth', weights_only=True)
# strict=False允许部分加载
missing, unexpected = model.load_state_dict(old_state, strict=False)
print(f"缺失的键: {missing}")
print(f"多余的键: {unexpected}")
| 应该保存 | 不需要保存 |
|---|---|
| model.state_dict() | 模型类定义(代码管理) |
| optimizer.state_dict() | 数据集(太大且可重建) |
| scheduler.state_dict() | 训练日志(单独保存) |
| 当前epoch/step | 随机种子状态(通常不需要) |
| 最佳指标值 | 梯度信息(除非做梯度分析) |
| 模型配置/超参数 | 临时中间变量 |
# 推荐的命名规范
# {项目名}_{模型名}_{数据集}_{epoch}_{指标}_{日期}.pth
from datetime import datetime
def generate_checkpoint_name(project, model_name, epoch, metric, metric_value):
date_str = datetime.now().strftime('%Y%m%d')
filename = f"{project}_{model_name}_e{epoch}_{metric}{metric_value:.4f}_{date_str}.pth"
return filename
# 示例: sentiment_bert_imdb_e10_acc0.9523_20261106.pth
name = generate_checkpoint_name('sentiment', 'bert', 10, 'acc', 0.9523)
print(name)
# 使用配置字典记录模型版本信息
model_config = {
'name': 'SimpleGPT-v1.2',
'version': '1.2.0',
'architecture': {
'd_model': 512,
'num_heads': 8,
'num_layers': 12,
'd_ff': 2048,
'vocab_size': 50000,
},
'training': {
'epochs': 100,
'lr': 3e-4,
'batch_size': 32,
'optimizer': 'AdamW',
},
'metrics': {
'train_loss': 1.234,
'val_loss': 1.456,
'val_accuracy': 0.892,
},
}
# 保存模型和配置
torch.save({
'config': model_config,
'state_dict': model.state_dict(),
}, 'simple_gpt_v1.2.0.pth')
import os
from collections import OrderedDict
class ModelCheckpoint:
def __init__(self, save_dir, max_keep=3):
self.save_dir = save_dir
self.max_keep = max_keep
self.best_loss = float('inf')
os.makedirs(save_dir, exist_ok=True)
def save(self, model, optimizer, epoch, val_loss):
if val_loss < self.best_loss:
self.best_loss = val_loss
path = os.path.join(self.save_dir, 'best.pth')
torch.save({'model': model.state_dict(),
'optimizer': optimizer.state_dict(),
'epoch': epoch, 'loss': val_loss}, path)
# 保留最近N个checkpoint
path = os.path.join(self.save_dir, f'ckpt_e{epoch}.pth')
torch.save({'model': model.state_dict(),
'optimizer': optimizer.state_dict(),
'epoch': epoch}, path)
self._cleanup()
def _cleanup(self):
ckpts = sorted([f for f in os.listdir(self.save_dir)
if f.startswith('ckpt_')])
while len(ckpts) > self.max_keep:
os.remove(os.path.join(self.save_dir, ckpts.pop(0)))
大模型(如7B+参数)的单个checkpoint文件可能超过30GB,加载时需要大量内存。分片保存将模型拆分为多个小文件,支持按需加载。
# 分片保存(类似HuggingFace的分片方式)
def save_sharded(model, save_dir, max_shard_size='5GB'):
os.makedirs(save_dir, exist_ok=True)
state_dict = model.state_dict()
shards = []
current_shard = {}
current_size = 0
max_bytes = 5 * 1024**3 # 5GB
for key, tensor in state_dict.items():
tensor_size = tensor.nelement() * tensor.element_size()
if current_size + tensor_size > max_bytes and current_shard:
shards.append(current_shard)
current_shard = {}
current_size = 0
current_shard[key] = tensor
current_size += tensor_size
if current_shard:
shards.append(current_shard)
for i, shard in enumerate(shards):
torch.save(shard, os.path.join(save_dir, f'model-{i:05d}.pth'))
# 保存索引
index = {'total_shards': len(shards)}
import json
with open(os.path.join(save_dir, 'index.json'), 'w') as f:
json.dump(index, f)
print(f"Saved {len(shards)} shards to {save_dir}")
# 以半精度保存模型(节省50%空间)
model_half = model.half()
torch.save(model_half.state_dict(), 'model_fp16.pth')
# 加载时恢复全精度
state_dict = torch.load('model_fp16.pth', weights_only=True)
model = model.float()
model.load_state_dict({k: v.float() for k, v in state_dict.items()})
大模型保存与加载中常见的问题:(1)显存不足——使用分片保存或量化加载解决;(2)加载速度慢——safetensors比pickle快2-5倍;(3)跨版本兼容——保存时记录PyTorch版本和模型配置;(4)分布式训练保存——每个rank都保存会导致重复,应只在rank=0上保存;(5)梯度检查点(gradient checkpointing)与模型保存无关,不要混淆——前者是训练时节省显存的技术,后者是持久化模型参数。
模型保存就像给一个正在工作的团队拍快照:state_dict是记录每个人的工作状态(参数),optimizer state是记录每个人的工作方法和进度(动量/方差),epoch是记录项目进行到第几周。恢复时,所有人回到快照时的状态继续工作,就像从未中断一样。
大模型生态中,HuggingFace Hub已成为模型分享的标准平台。使用model.push_to_hub()可以一键上传模型,from_pretrained可以一键下载。safetensors格式因其安全性和速度正在取代pickle成为默认格式。
至此,PyTorch从入门到熟悉系列的前10篇已完成。后续章节将深入分布式训练(DDP/FSDP/DeepSpeed)、自定义CUDA算子、性能优化(torch.compile/FlashAttention)、混合精度训练(AMP)、梯度累积与梯度检查点、以及完整的大模型训练框架搭建等高级主题。掌握模型保存与加载是迈向大模型工程化的第一步,它确保了训练成果的安全持久化和高效复用。