本系列记录了博主学习PyTorch过程中的笔记,官方tutorial。
本文介绍了模型的保存和加载,官方示例。更新于2019.03.21。
这个文档提供了关于保存和加载PyTorch模型的一系列使用案例。可以全看,也可以根据需要选择。
在保存和加载模块时,需要了解下面三个核心函数:
state_dict
加载模型的参数dictionary。关于state_dict
的更多内容,可以看What is a state_dict?
。在PyTorch中,一个torch.nn.Module
模型中的可学习参数(比如weights和biases)试吧Ocun在模型的参数中的(通过model.parameters()
获取)。而state_dict就是一个简单的Python dictionary,其功能是将每层与层的参数张量之间一一映射。注意,只有包含了可学习参数(卷积层、线性层等)的层和已注册的命令(registered buffers,比如batchnorm的running_mean)才有模型的state_dict入口。优化方法目标(torch.optim)也有state_dict,其中包含的是关于优化器状态的信息和使用到的超参数。
因为state_dict目标是Python dictionaries,所以它们可以很轻松地实现保存、更新、变化和再存储,从而给PyTorch模型和优化器增加了大量的模块化(modularity)。
示例:
下面看一下Training a classifier教程中用到的state_dict。
# 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()
# Initialize optimizer
optimizer = optim.SGD(model.parameters(), lr=0.001, momentum=0.9)
# Print model's state_dict
print("Model's state_dict:")
for param_tensor in model.state_dict():
print(param_tensor, "\t", model.state_dict()[param_tensor].size())
# Print optimizer's state_dict
print("Optimizer's state_dict:")
for var_name in optimizer.state_dict():
print(var_name, "\t", optimizer.state_dict()[var_name])
输出:
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])
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]}]
建议保存或加载state_dict.
保存:
torch.save(model.state_dict(), PATH)
加载:
model = TheModelClass(*args, **kwargs)
model.load_state_dict(torch.load(PATH))
model.eval()
保存模型作为参考时,只需要保存训练好的模型所习得的参数。因此,用torch.save
函数保存模型的state_dict能够提供最灵活的模型再存储方法,这也是为什么推荐使用这个方法保存模型。
一个PyTorch中常用的保存模型的规则是用.pt
或.pth
作为文件扩展名。
需要注意的是,在运行前,必须调用model.eval()
来设置dropout和batch normalization层到评估模式。如果没有这一步,就会导致不一致的推理结果(inference results)。
保存:
torch.save(model, PATH)
加载:
# Model class must be defined somewhere
model = torch.load(PATH)
model.eval()
保存:
torch.save({
'epoch': epoch,
'model_state_dict': model.state_dict(),
'optimizer_state_dict': optimizer.state_dict(),
'loss': loss,
...
}, PATH)
加载:
model = TheModelClass(*args, **kwargs)
optimizer = TheOptimizerClass(*args, **kwargs)
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()
保存:
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)
加载:
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()
保存:
torch.save(modelA.state_dict(), PATH)
加载:
modelB = TheModelBClass(*args, **kwargs)
modelB.load_state_dict(torch.load(PATH), strict=False)
保存:
torch.save(model.state_dict(), PATH)
加载:
device = torch.device('cpu')
model = TheModelClass(*args, **kwargs)
model.load_state_dict(torch.load(PATH, map_location=device))
保存:
torch.save(model.state_dict(), PATH)
加载:
device = torch.device("cuda")
model = TheModelClass(*args, **kwargs)
model.load_state_dict(torch.load(PATH))
model.to(device)
# Make sure to call input = input.to(device) on any input tensors that you feed to the model
保存:
torch.save(model.state_dict(), PATH)
加载:
device = torch.device("cuda")
model = TheModelClass(*args, **kwargs)
model.load_state_dict(torch.load(PATH, map_location="cuda:0")) # Choose whatever GPU device number you want
model.to(device)
# Make sure to call input = input.to(device) on any input tensors that you feed to the model
保存:
torch.save(model.module.state_dict(), PATH)
加载:
可以加载到任意想加载的设备
更多内容,欢迎加入星球讨论。