文章目录
- 6 PyTorch 官网教材之 保存和加载模型
- 0. 官网链接
- 1. What is a `state_dict`?
- 2. Saving & Loading Model for Inference
- 2.1. Save/Load state_dict (Recommended)
- 2.2. Save/Load Entire Model(官方不推荐)
- 2.3. 断点保存和加载;Saving & Loading a General Checkpoint for Inference and/or Resuming Training
- 2.4. 在一个文件中保存多个模型;Saving Multiple Models in One File
- 2.5. 使用另一个模型的参数进行训练; Warmstarting Model Using Parameters from a Different Model
- 2.6. Saving & Loading Model Across Devices
6 PyTorch 官网教材之 保存和加载模型
0. 官网链接
https://pytorch.org/tutorials/beginner/saving_loading_models.html
1. What is a state_dict
?
1.1. model.state_dict()
1.2. optimizer.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]}]
2. Saving & Loading Model for Inference
2.1. Save/Load state_dict (Recommended)
2.1.1. Save: torch.save(model.state_dict(), PATH)
torch.save(model.state_dict(), PATH)
# A common PyTorch convention is to save models using
# either a .pt or .pth file extension.
2.1.2. Load: model.load_state_dict(torch.load(PATH))
model = TheModelClass(*args, **kwargs)
model.load_state_dict(torch.load(PATH))
model.eval()
# you must call model.eval() to set dropout and batch normalization layers
# to evaluation mode before running inference
2.2. Save/Load Entire Model(官方不推荐)
- 官方不推荐使用,缺点是 your code can break in various ways when used in other projects or after refactors.
2.2.1. Save: torch.save(model, PATH)
torch.save(model, PATH)
# A common PyTorch convention is to save models using
# either a .pt or .pth file extension.
2.2.2. Load: model = torch.load(PATH)
# Model class must be defined somewhere
model = torch.load(PATH)
model.eval()
# you must call model.eval() to set dropout and batch normalization
# layers to evaluation mode before running inference
2.3. 断点保存和加载;Saving & Loading a General Checkpoint for Inference and/or Resuming Training
2.3.1. Save: 四项数据以字典保存
# 保存四项数据
torch.save({
'epoch': epoch,
'model_state_dict': model.state_dict(),
'optimizer_state_dict': optimizer.state_dict(),
'loss': loss,
...
}, PATH)
# A common PyTorch convention is to save these checkpoints using the .tar file extension.
2.3.2. Load: 四项数据以字典加载
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()
2.4. 在一个文件中保存多个模型;Saving Multiple Models in One File
2.4.1. 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)
# A common PyTorch convention is to save these checkpoints using the .tar file extension.
2.4.2. 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()
2.5. 使用另一个模型的参数进行训练; Warmstarting Model Using Parameters from a Different Model
2.5.1. Save:
torch.save(modelA.state_dict(), PATH)
2.5.2. Load:
modelB = TheModelBClass(*args, **kwargs)
modelB.load_state_dict(torch.load(PATH), strict=False)
# 参数和模型理论上来说应该是完全一一对应的,但有的时候另一个模型的参数会多余(新的模型没有与之对应的层) 或缺失(模型新增加的层,没有与之相对应的参数)。这个时候就需要将 strict 设置为FALSE,避免因参数和模型不匹配而报错(set the strict argument to False in the load_state_dict() function to ignore non-matching keys.)。
- If you want to load parameters from one layer to another, but some keys do not match, simply change the name of the parameter keys in the state_dict that you are loading to match the keys in the model that you are loading into.(还不会)
2.6. Saving & Loading Model Across Devices
2.6.1. Save on GPU, Load on CPU
2.6.1.1. Save:
torch.save(model.state_dict(), PATH)
2.6.1.2 .Load:
device = torch.device('cpu')
model = TheModelClass(*args, **kwargs)
model.load_state_dict(torch.load(PATH, map_location=device))
2.6.2. Save on GPU, Load on GPU
2.6.2.1. Save:
torch.save(model.state_dict(), PATH)
2.6.2.2. Load:
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
2.6.3. Save on CPU, Load on GPU
2.6.3.1. Save:
torch.save(model.state_dict(), PATH)
2.6.3.2. Load:
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
2.6.4. Saving torch.nn.DataParallel Models
2.6.4.1. Save:
torch.save(model.module.state_dict(), PATH)
2.6.4.2. Load:
# Load to whatever device you want
THE END