_pickle.UnpicklingError: Weights only load failed. 解决方法

_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 with weights_only=True, follow one of these approaches:

Option 1: Disable weights_only (Only if you trust the checkpoint source)

Set weights_only=False in torch.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 maintain weights_only=True safety:

  1. Import the _reconstruct function:

    from numpy.core.multiarray import _reconstruct
    import torch
    
  2. 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.

懒得翻译了,方案一是有效的,方案二没试

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值