在看小土堆的视频的时候,我尝试运行以下代码:

torch.save(vgg_16,"vgg16_method1.pth")
model=torch.load("vgg16_method1.pth")

报错如下:

Traceback (most recent call last):
  File "E:\PytorchProject\tensorboard\model_load.py", line 2, in <module>
    model=torch.load("vgg16_method1.pth")
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "E:\anaconda3\envs\pytorch\Lib\site-packages\torch\serialization.py", line 1578, in load
    raise pickle.UnpicklingError(_get_wo_message(str(e))) from None
_pickle.UnpicklingError: Weights only load failed. This file can still be loaded, to do so you have two options, do those steps only if you trust the source of the checkpoint. 
	(1) In PyTorch 2.6, we changed the default value of the `weights_only` argument in `torch.load` from `False` to `True`. Re-running `torch.load` with `weights_only` set to `False` will likely succeed, but it can result in arbitrary code execution. Do it only if you got the file from a trusted source.
	(2) Alternatively, to load with `weights_only=True` please check the recommended steps in the following error message.
	WeightsUnpickler error: Unsupported global: GLOBAL torchvision.models.vgg.VGG was not an allowed global by default. Please use `torch.serialization.add_safe_globals([torchvision.models.vgg.VGG])` or the `torch.serialization.safe_globals([torchvision.models.vgg.VGG])` context manager to allowlist this global if you trust this class/function.

Check the documentation of torch.load to learn more about types accepted by default with weights_only https://pytorch.org/docs/stable/generated/torch.load.html.

以上报错的大意:因为你使用的 PyTorch 2.6 出于安全考虑,把 torch.load() 里 weights_only 参数的默认值从 False 改为了 True

所以当你尝试去载入一个完整模型(包括模型架构+模型参数)时,你需要显式地指定weights_only的参数为False

model=torch.load("vgg16_method1.pth",weights_only=False)

Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐