to load with `weights_only=True` please check the recommended steps in the following error message.

错误详情

  File "C:\ProgramData\miniconda3\envs\py39\lib\site-packages\torch\serialization.py", line 1470, 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 ultralytics.nn.tasks.DetectionModel was not an allowed global by default. Please use `torch.serialization.add_safe_globals([DetectionModel])` or the `torch.serialization.safe_globals([DetectionModel])` 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()函数的安全性变更有关。在PyTorch 2.6中,weights_only参数的默认值已从False更改为True,这是为了增强安全性,防止加载不受信任的模型文件时可能出现的代码执行漏洞。

解决方案一:临时禁用安全保护(仅当您信任来源时)

# 在torch.load调用中添加weights_only=False
model = torch.load('your_model.pt', weights_only=False)

⚠️ 警告:如果您加载的文件来自不可信来源,此方法可能导致任意代码执行。仅当您自己创建了该文件或完全信任来源时才使用此方法。

解决方案二:安全方法(推荐)

要安全地加载模型同时保持安全保护:

from ultralytics.nn.tasks import DetectionModel
import torch.serialization

# 选项A:添加到安全全局列表
torch.serialization.add_safe_globals([DetectionModel])

# 然后正常加载
model = torch.load('your_model.pt')  # 默认weights_only=True

# 选项B:使用上下文管理器(更简洁)
with torch.serialization.safe_globals([DetectionModel]):
    model = torch.load('your_model.pt')

此方法仅允许您需要的特定类,同时保持对其他潜在威胁的安全保护。

最佳实践建议

如果您经常使用Ultralytics YOLO模型,建议使用第二种方法。您可以创建一个辅助函数:

def load_yolo_model(path):
    from ultralytics.nn.tasks import DetectionModel
    with torch.serialization.safe_globals([DetectionModel]):
        return torch.load(path)

重要提醒:永远不要为来自不可信来源的模型禁用安全功能(weights_only=False),因为这可能导致严重的安全漏洞。安全第一,特别是当处理来自外部的模型文件时。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AI浩

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值