PyTorch 入门指南
学习 PyTorch
图像和视频
音频
后端
强化学习
在生产环境中部署 PyTorch 模型
Profiling PyTorch
代码变换与FX
前端API
扩展 PyTorch
模型优化
并行和分布式训练
边缘端的 ExecuTorch
推荐系统
多模态

基础知识 || 快速入门 || 张量 || 数据集和数据加载器 || 变换 || 构建模型 || 自动求导 || 优化 || 保存与加载模型

保存与加载模型

在本节中,我们将探讨如何通过保存、加载和运行模型预测来持久化模型状态。

importtorch
importtorchvision.modelsasmodels
Plain text

保存与加载模型权重

PyTorch 模型将学习到的参数存储在一个称为 state_dict 的内部状态字典中。这些参数可以通过 torch.save 方法持久化保存:

model = models.vgg16(weights='IMAGENET1K_V1')
torch.save(model.state_dict(), 'model_weights.pth')
Plain text
Downloading: "https://download.pytorch.org/models/vgg16-397923af.pth" to /var/lib/ci-user/.cache/torch/hub/checkpoints/vgg16-397923af.pth

  0%|          | 0.00/528M [00:00<?, ?B/s]
  3%|2         | 15.1M/528M [00:00<00:03, 158MB/s]
  6%|6         | 32.2M/528M [00:00<00:03, 170MB/s]
  9%|9         | 49.5M/528M [00:00<00:02, 175MB/s]
 13%|#2        | 67.0M/528M [00:00<00:02, 178MB/s]
 16%|#6        | 84.8M/528M [00:00<00:02, 181MB/s]
 19%|#9        | 102M/528M [00:00<00:02, 183MB/s]
 23%|##2       | 120M/528M [00:00<00:02, 184MB/s]
 26%|##6       | 138M/528M [00:00<00:02, 184MB/s]
 30%|##9       | 156M/528M [00:00<00:02, 185MB/s]
 33%|###2      | 174M/528M [00:01<00:02, 184MB/s]
 36%|###6      | 191M/528M [00:01<00:01, 181MB/s]
 40%|###9      | 209M/528M [00:01<00:01, 179MB/s]
 43%|####2     | 226M/528M [00:01<00:01, 178MB/s]
 46%|####5     | 243M/528M [00:01<00:01, 176MB/s]
 49%|####9     | 260M/528M [00:01<00:01, 175MB/s]
 52%|#####2    | 276M/528M [00:01<00:01, 174MB/s]
 56%|#####5    | 293M/528M [00:01<00:01, 174MB/s]
 59%|#####8    | 310M/528M [00:01<00:01, 174MB/s]
 62%|######1   | 326M/528M [00:01<00:01, 173MB/s]
 65%|######4   | 343M/528M [00:02<00:01, 173MB/s]
 68%|######8   | 359M/528M [00:02<00:01, 172MB/s]
 71%|#######1  | 376M/528M [00:02<00:00, 173MB/s]
 74%|#######4  | 392M/528M [00:02<00:00, 172MB/s]
 78%|#######7  | 409M/528M [00:02<00:00, 173MB/s]
 81%|########  | 426M/528M [00:02<00:00, 173MB/s]
 84%|########3 | 442M/528M [00:02<00:00, 173MB/s]
 87%|########6 | 459M/528M [00:02<00:00, 173MB/s]
 90%|######### | 476M/528M [00:02<00:00, 173MB/s]
 93%|#########3| 492M/528M [00:02<00:00, 173MB/s]
 96%|#########6| 509M/528M [00:03<00:00, 173MB/s]
100%|#########9| 525M/528M [00:03<00:00, 173MB/s]
100%|##########| 528M/528M [00:03<00:00, 176MB/s]
Plain text

要加载模型权重,首先需要创建相同模型的一个实例,然后使用 load_state_dict() 方法加载参数。

在下面的代码中,我们设置 weights_only=True,以限制在反序列化过程中仅执行加载权重所需的功能。在加载权重时,使用 weights_only=True 被视为最佳实践。

model = models.vgg16() # we do not specify ``weights``, i.e. create untrained model
model.load_state_dict(torch.load('model_weights.pth', weights_only=True))
model.eval()
Plain text
VGG(
  (features): Sequential(
    (0): Conv2d(3, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (1): ReLU(inplace=True)
    (2): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (3): ReLU(inplace=True)
    (4): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
    (5): Conv2d(64, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (6): ReLU(inplace=True)
    (7): Conv2d(128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (8): ReLU(inplace=True)
    (9): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
    (10): Conv2d(128, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (11): ReLU(inplace=True)
    (12): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (13): ReLU(inplace=True)
    (14): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (15): ReLU(inplace=True)
    (16): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
    (17): Conv2d(256, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (18): ReLU(inplace=True)
    (19): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (20): ReLU(inplace=True)
    (21): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (22): ReLU(inplace=True)
    (23): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
    (24): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (25): ReLU(inplace=True)
    (26): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (27): ReLU(inplace=True)
    (28): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (29): ReLU(inplace=True)
    (30): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
  )
  (avgpool): AdaptiveAvgPool2d(output_size=(7, 7))
  (classifier): Sequential(
    (0): Linear(in_features=25088, out_features=4096, bias=True)
    (1): ReLU(inplace=True)
    (2): Dropout(p=0.5, inplace=False)
    (3): Linear(in_features=4096, out_features=4096, bias=True)
    (4): ReLU(inplace=True)
    (5): Dropout(p=0.5, inplace=False)
    (6): Linear(in_features=4096, out_features=1000, bias=True)
  )
)
Plain text

在进行推理之前,请务必调用 model.eval() 方法,将 dropout 和 batch normalization 层设置为评估模式。如果不这样做,可能会导致不一致的推理结果。

保存和加载带有形状的模型

在加载模型权重时,我们需要先实例化模型类,因为该类定义了网络的结构。我们可能希望将该类的结构与模型一起保存,在这种情况下,我们可以将 model(而不是 model.state_dict())传递给保存函数:

torch.save(model, 'model.pth')
Plain text

我们可以按照如下所示加载模型。

Saving and loading torch.nn.Modules 中所述,保存 state_dict 被认为是最佳实践。然而,由于这里涉及到加载模型,这是一个 torch.save 的遗留用例,因此我们使用了 weights_only=False

model = torch.load('model.pth', weights_only=False),
Plain text

这种方法在序列化模型时使用了 Python 的 pickle 模块,因此在加载模型时需要确保实际的类定义可用。