_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 ultralytics.nn.tasks.SegmentationModel was not an allowed global by default. Please use `torch.serialization.add_safe_globals([SegmentationModel])` or the `torch.serialization.safe_globals([SegmentationModel])` 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.
询问deepseek后得到两种答案,对此进行记录:
To resolve the
pickle.UnpicklingError
when loading a PyTorch checkpoint withweights_only=True
, follow one of these approaches:Option 1: Disable
weights_only
(Only if you trust the checkpoint source)Set
weights_only=False
intorch.load
to allow arbitrary code execution (use with caution):model = torch.load('checkpoint.pth', weights_only=False)
Option 2: Allowlist the Required Global (Recommended for security)
Add
numpy.core.multiarray._reconstruct
to PyTorch’s safe globals to maintainweights_only=True
safety:
Import the
_reconstruct
function:from numpy.core.multiarray import _reconstruct import torch
Add to Safe Globals and Load:
- Method A: Permanently add to safe globals:
torch.serialization.add_safe_globals([_reconstruct]) model = torch.load('checkpoint.pth', weights_only=True)
- Method B: Use a context manager for temporary inclusion:
with torch.serialization.safe_globals([_reconstruct]): model = torch.load('checkpoint.pth', weights_only=True)
Key Considerations
- Security: Use
weights_only=False
only if the checkpoint is from a trusted source to avoid code execution risks.- Compatibility: Ensure PyTorch ≥2.6 for
add_safe_globals
or the context manager methods.Choose the method that best balances your security needs and workflow.
懒得翻译了,方案一是有效的,方案二没试
_pickle.UnpicklingError: Weights only load failed. 解决方法
最新推荐文章于 2025-04-22 16:21:40 发布