YOLO(‘../yolo-weights/yolov8n.pt‘)跑ai模型:yolo模型报错:pythorn2.6版本问题
·
_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([ultralytics.nn.tasks.DetectionModel])`
or the `torch.serialization.safe_globals([ultralytics.nn.tasks.DetectionModel])` context manager to allowlist this global if you trust this class/function.
In PyTorch 2.6
主要错误就是在pyTorch的版本上:
根据您提供的错误信息和PyTorch官方文档,这个问题是由于PyTorch 2.6版本中安全策略变更导致的。以下是详细的解决方案:
问题原因分析
核心问题:PyTorch 2.6将 torch.load() 的 weights_only 参数默认值从 False 改为 True,这增强了安全性但导致旧代码无法加载包含自定义类的模型文件。
解决方案
方案一:安全白名单方法(推荐)
这是最安全的解决方案,仅允许特定的类被加载:
python
import ultralytics.nn.tasks
# 将DetectionModel添加到安全白名单
python
torch.serialization.add_safe_globals([ultralytics.nn.tasks.DetectionModel])
# 然后正常加载YOLO模型
```python
from ultralytics import YOLO
model = YOLO('../yolo-weights/yolov8n.pt')
或者使用上下文管理器:
python
python
import torch
import ultralytics.nn.tasks
from ultralytics import YOLO
python
with torch.serialization.safe_globals([ultralytics.nn.tasks.DetectionModel]):
model = YOLO('../yolo-weights/yolov8n.pt')
方案二:临时解决方案(仅限可信来源)
如果您完全信任模型文件的来源,可以强制设置 weights_only=False:
# 修改ultralytics库中的tasks.py文件
# 找到第332行左右的torch_safe_load函数
# 将原来的:
return torch.load(file, map_location='cpu') # load
# 改为:
return torch.load(file, map_location='cpu', weights_only=False)
方案三:降级PyTorch版本
https://pytorch.org/get-started/previous-versions/
如果上述方案都不适用,可以考虑暂时降级到PyTorch 2.5或更早版本:
pip install torch2.5.1 torchvision0.20.1 torchaudio==2.5.1
安全注意事项
根据PyTorch官方文档警告:除非将 weights_only 参数设置为 True,否则 torch.load() 会隐式使用pickle模块,这已知是不安全的。可能构造恶意的pickle数据,在反序列化期间执行任意代码。
我采用的方案三: wx : aijsq-com
pip install torch==2.5.1 torchvision==0.20.1 torchaudio==2.5.1 --index-url https://download.pytorch.org/whl/cu124
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐


所有评论(0)