如何测试模型保存/加载一致性?
解读
面试官问的不是“怎么保存/加载”,而是“怎么证明保存前后、加载前后,模型行为完全一致”。
在国内工业场景里,这条验证链直接决定模型能否上线:
- 训练→验证→测试三台机器,权重文件传来传去,必须 bit-wise 一致;
- 线上推理服务用 C++ LibTorch,线下用 Python,结果必须对齐;
- 量化/剪枝后再加载,仍要保证误差在 1e-6 以内。
因此,候选人需要给出“可脚本化、可集成 CI、可量化误差”的完整方案,而不是口头说“我 print 了一下”。
知识点
- 状态字典(state_dict)与完整检查点(checkpoint)区别:
- state_dict 只含参数,不保存结构;
- checkpoint 可含结构、优化器、epoch、args。
- 随机源隔离:PyTorch 的 CPU/CUDA 随机性、Python hash、NumPy 随机、第三方算子(如 DCNv2)都要固定。
- 确定性算法:torch.use_deterministic_algorithms(True) 与 CUDA 10.2+ 的 CUBLAS_WORKSPACE_CONFIG=:4096:8。
- 浮点误差累积:GPU 上 reduce 操作默认使用 tensor core,TF32 打开后误差可达 1e-5;需要 torch.backends.cuda.matmul.allow_tf32 = False。
- 生产环境一致性:TorchScript、ONNX、TensorRT 与 PyTorch 数值对齐的验证方法。
- 自动化测试:pytest + allclose + CI 卡点,误差阈值按业务指标(ACC、F1、MAE)反推,而非简单 1e-6。
答案
我给出一个可直接写进 GitLab CI 的 Python 脚本模板,覆盖“参数一致性”与“推理一致性”双验证。
# test_save_load.py
import os, random, torch, numpy as np
from pathlib import Path
def set_seed(seed=42):
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
torch.backends.cuda.matmul.allow_tf32 = False
torch.backends.cudnn.allow_tf32 = False
os.environ["CUBLAS_WORKSPACE_CONFIG"] = ":4096:8"
torch.use_deterministic_algorithms(True)
class DummyNet(torch.nn.Module):
def __init__(self):
super().__init__()
self.conv = torch.nn.Conv2d(3, 8, 3, padding=1)
self.gelu = torch.nn.GELU()
self.pool = torch.nn.AdaptiveAvgPool2d(1)
self.fc = torch.nn.Linear(8, 10)
def forward(self, x):
x = self.pool(self.gelu(self.conv(x))).flatten(1)
return self.fc(x)
def test_state_dict_bitwise():
set_seed()
model = DummyNet().cuda().eval()
sd = model.state_dict()
torch.save(sd, "/tmp/model.pt")
sd2 = torch.load("/tmp/model.pt", map_location="cuda:0")
for k in sd:
assert torch.equal(sd[k], sd2[k]), f"Key {k} not equal"
print("✅ state_dict bitwise check passed")
def test_inference_numerical():
set_seed()
model = DummyNet().cuda().eval()
x = torch.randn(8, 3, 32, 32, device="cuda")
with torch.no_grad():
y1 = model(x).cpu()
# 保存并加载
ckpt = {"model": model.state_dict(),
"args": {"classes": 10}}
torch.save(ckpt, "/tmp/ckpt.pt")
del model
torch.cuda.empty_cache()
# 重建
set_seed() # 必须重新固定,保证输入一致
model2 = DummyNet().cuda().eval()
ckpt = torch.load("/tmp/ckpt.pt", map_location="cuda:0")
model2.load_state_dict(ckpt["model"])
with torch.no_grad():
y2 = model2(x).cpu()
# 误差阈值按业务反推:分类任务 top-1 不变即可
torch.testing.assert_close(y1, y2, rtol=0, atol=0)
assert (y1.argmax(1) == y2.argmax(1)).all()
print("✅ inference numerical check passed")
if __name__ == "__main__":
test_state_dict_bitwise()
test_inference_numerical()
运行 python test_save_load.py 无报错即通过。
CI 里再加一行 pytest test_save_load.py -v --tb=short,失败即阻断 MR。
拓展思考
- 多卡 DP/DDP 场景:保存的是
module.layer.weight还是layer.weight?需要在model.module.state_dict()与model.state_dict()之间做统一封装,避免 key mismatch。 - 半精度/混合精度:保存前
model.half(),加载后再float(),需验证 AMP 缩放系数(scaler)是否也序列化。 - 量化模型:PTQ/QAT 后权重变成
uint8+scale/zero_point,需用torch.quantization._save_observer_state_dict与load_observer_state_dict,并对比 INT8 推理与 FP32 误差在 1% 以内。 - TorchScript 一致性:
需再跑一遍traced = torch.jit.trace(model, x) torch.jit.save(traced, "model.pt") loaded = torch.jit.load("model.pt")torch.testing.assert_close(traced(x), loaded(x)),防止序列化图优化导致算子融合偏差。 - 黑盒验收:把验证脚本输出 MD5(y1) 与 MD5(y2) 写进模型交付清单,甲方直接
md5sum -c delivery.md5,杜绝“口头一致”。