保存和加载模型用到的核心函数:
在pytorch中,一个torch.nn.Model模型的可学习参数(比如权重或者偏置)保存在model.parameters()中。state_dict是一个Python字典,它将每一层映射到对应的参数张量。
例子:
# Define model
class TheModelClass(nn.Module):
def __init__(self):
super(TheModelClass, self).__init__()
self.conv1 = nn.Conv2d(3, 6, 5)
self.pool = nn.MaxPool2d(2, 2)
self.conv2 = nn.Conv2d(6, 16, 5)
self.fc1 = nn.Linear(16 * 5 * 5, 120)
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 10)
def forward(self, x):
x = self.pool(F.relu(self.conv1(x)))
x = self.pool(F.relu(self.conv2(x)))
x = x.view(-1, 16 * 5 * 5)
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x
# Initialize model
model = TheModelClass()
optimizer = optim.SGD(model.parameters(), lr=0.001, momentum=0.9)
print("Model's state_dict:")
for param_tensor in model.state_dict():
print(param_tensor, "\t", model.state_dict()[param_tensor].size())
结果:
Model's state_dict:
conv1.weight torch.Size([6, 3, 5, 5])
conv1.bias torch.Size([6])
conv2.weight torch.Size([16, 6, 5, 5])
conv2.bias torch.Size([16])
fc1.weight torch.Size([120, 400])
fc1.bias torch.Size([120])
fc2.weight torch.Size([84, 120])
fc2.bias torch.Size([84])
fc3.weight torch.Size([10, 84])
fc3.bias torch.Size([10])
print("Optimizer's state_dict:")
for var_name in optimizer.state_dict():
print(var_name, "\t", optimizer.state_dict()[var_name])
结果:
Optimizer's state_dict:
state {}
param_groups [{'lr': 0.001, 'momentum': 0.9, 'dampening': 0, 'weight_decay': 0, 'nesterov': False, 'params': [4675713712, 4675713784, 4675714000, 4675714072, 4675714216, 4675714288, 4675714432, 4675714504, 4675714648, 4675714720]}]
save:
torch.save(model.state_dict(), 'save/to/path/model.pth')
load:
model = MyModelDefinition(args)
model.load_state_dict(torch.load('load/from/path/model.pth'))
model.eval()
在pytorch里,保存模型使用的文件后缀要么是“.pt”要么是“.pth”
在运行评估(inference)之前要使用model.eval()将dropout和批处理规范化层设置为评估模式。如果不这样做,将产生不一致的推理结果
Attention:
1??load_state_dict函数接收的是字典,不能直接接收路径。
所以这样写就是错的:model.load_state_dict(PATH)?
应该是:model.load_state_dict(torch.load(PATH))??
2??如果想要保存best model,不能仅仅写成:best_model_state=model.state_dict(),因为这只是返回一个引用而不是复制下来了,需要写成:best_model_state=deepcopy(model.state_dict())。否则,最佳best_model_state将在随后的训练迭代中不断更新,进而导致最终的模型状态将是过拟合模型的状态。
save:
torch.save(model, PATH)
load:
# Model class must be defined somewhere
model = torch.load(PATH)
model.eval()
通常ML pipeline需要定期或在满足条件时保存模型检查点。保存检查点是为了防止训练的时候因为一些莫名其妙的原因中断,这样就可以从最后或最佳检查点恢复训练。
但是仅仅保存模型的state_dict是不够的,还需要保存优化器的state_dict(因为这包含随着模型训练而更新的缓冲区和参数)以及最后的epoch number,loss, external torch.nn.Embedding layers等等。基本上需要存储所有的大小来使用检查点恢复训练。这样的检查点通常比单独的模型大2~3倍。
save:
torch.save({
'epoch': epoch,
'model_state_dict': model.state_dict(),
'optimizer_state_dict': optimizer.state_dict(),
'loss': loss,
...
}, PATH)
load:
model = MyModelDefinition(args)
optimizer = optim.SGD(model.parameters(), lr=0.001, momentum=0.9)
checkpoint = torch.load(PATH)
model.load_state_dict(checkpoint['model_state_dict'])
optimizer.load_state_dict(checkpoint['optimizer_state_dict'])
epoch = checkpoint['epoch']
loss = checkpoint['loss']
model.eval()
# - or -
model.train()
当要保存多个复杂的模型时,和创建检查点相同,需要保存每个模型的state_dict和相对于的优化器在一个字典中。如前所述,您可以保存任何其他可能有助于您恢复训练的项目,只需将它们添加到字典中。
save:
torch.save({
'modelA_state_dict': modelA.state_dict(),
'modelB_state_dict': modelB.state_dict(),
'optimizerA_state_dict': optimizerA.state_dict(),
'optimizerB_state_dict': optimizerB.state_dict(),
...
}, PATH)
加载模型,首先初始化模型和优化器,然后使用torch.load()在本地加载字典。
load:
modelA = TheModelAClass(*args, **kwargs)
modelB = TheModelBClass(*args, **kwargs)
optimizerA = TheOptimizerAClass(*args, **kwargs)
optimizerB = TheOptimizerBClass(*args, **kwargs)
checkpoint = torch.load(PATH)
modelA.load_state_dict(checkpoint['modelA_state_dict'])
modelB.load_state_dict(checkpoint['modelB_state_dict'])
optimizerA.load_state_dict(checkpoint['optimizerA_state_dict'])
optimizerB.load_state_dict(checkpoint['optimizerB_state_dict'])
modelA.eval()
modelB.eval()
# - or -
modelA.train()
modelB.train()