YOLOv5 2025-6-5 torch 2.6.0+cu126 CUDA:0 (NVIDIA GeForce RTX 2060, 6144MiB) YOLOv5 2025-6-5 torch 2.6.0+cu126 CUDA:0 (NVIDIA GeForce RTX 2060, 6144MiB) Traceback (most recent call last): File "D:\custom\nongjiyuan\QtProject\src\process_image.py", line 155, in <module> main() File "D:\custom\nongjiyuan\QtProject\src\process_image.py", line 152, in main process.process_image(img, True, False, model_path_2, model2_data) File "D:\custom\nongjiyuan\QtProject\src\process_image.py", line 77, in process_image run( File "D:\software\anaconda3\envs\nongjiyuan\Lib\site-packages\torch\utils\_contextlib.py", line 116, in decorate_context return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "D:\custom\nongjiyuan\QtProject\damage_detect\detect.py", line 97, in run model = DetectMultiBackend(weights, device=device, dnn=dnn, data=data, fp16=half) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\custom\nongjiyuan\QtProject\damage_detect\models\common.py", line 589, in __init__ model = attempt_load(weights if isinstance(weights, list) else w, map_location=device) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\custom\nongjiyuan\QtProject\damage_detect\models\experimental.py", line 96, in attempt_load ckpt = torch.load(attempt_download(w), map_location=map_location) # load ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\software\anaconda3\envs\nongjiyuan\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.
时间: 2025-06-11 21:32:23 浏览: 28
### 解决YOLOv5在使用torch 2.6.0+cu126和CUDA环境下加载权重时的UnpicklingError问题
在使用PyTorch 2.6.0版本加载YOLOv5模型权重时,可能会遇到`pickle.UnpicklingError`错误。这是由于PyTorch 2.6引入了新的安全机制,默认情况下将`weights_only`参数设置为`True`,从而阻止加载包含未被允许全局对象(如`DetectionModel`)的模型文件[^3]。
#### 问题分析
当尝试加载YOLOv5模型权重时,如果模型文件中包含不受信任的全局对象(例如`ultralytics.nn.tasks.DetectionModel`),默认的安全机制会阻止其加载,并抛出`pickle.UnpicklingError`错误。为了解决这一问题,可以采取以下两种方法之一:
#### 方法一:修改`weights_only`参数
如果确定模型文件来源可靠,可以在加载模型时将`weights_only`参数设置为`False`。这可以通过修改`models/experimental.py`文件中的`attempt_load`函数实现。具体操作如下:
```python
# 在 models/experimental.py 文件中找到 attempt_load 函数
def attempt_load(weights, map_location=None):
# ... 其他代码 ...
ckpt = torch.load(w, map_location=map_location, weights_only=False) # 修改这一行,添加 weights_only=False
# ... 其他代码 ...
return model
```
通过将`weights_only`设置为`False`,可以绕过新的安全检查机制,成功加载模型权重[^3]。
#### 方法二:将`DetectionModel`添加到允许列表
另一种更安全的方法是将`DetectionModel`类添加到PyTorch的允许全局对象列表中。这可以通过`torch.serialization.add_safe_globals`或`torch.serialization.safe_globals`上下文管理器实现。以下是具体实现方式:
```python
from ultralytics.nn.tasks import DetectionModel
import torch
# 使用 add_safe_globals 方法
torch.serialization.add_safe_globals(DetectionModel)
# 或者使用 safe_globals 上下文管理器
with torch.serialization.safe_globals([DetectionModel]):
model = torch.hub.load('ultralytics/yolov5', 'custom', path='path/to/best.pt', force_reload=True)
```
这种方法不会完全禁用安全性检查,而是仅允许特定的全局对象加载,从而在保证安全性的前提下解决加载问题[^1]。
#### 环境依赖与配置
确保环境中的依赖库版本与YOLOv5兼容。例如,NumPy版本应为`1.20.3`,OpenCV版本应大于等于`4.1.1`,Pillow版本应大于等于`8.3.0`,PyTorch版本应为`2.6.0+cu126`以支持CUDA加速[^2]。
此外,确保CUDA驱动程序已正确安装并兼容NVIDIA GeForce RTX 2060显卡。可以通过以下命令验证CUDA是否正常工作:
```python
import torch
print(torch.cuda.is_available()) # 应返回 True
print(torch.cuda.get_device_name(0)) # 应返回 NVIDIA GeForce RTX 2060
```
#### 示例代码
以下是一个完整的代码示例,展示如何加载YOLOv5模型并处理`UnpicklingError`问题:
```python
from ultralytics.nn.tasks import DetectionModel
import torch
# 添加 DetectionModel 到允许列表
torch.serialization.add_safe_globals(DetectionModel)
# 加载自定义模型
model = torch.hub.load('ultralytics/yolov5', 'custom', path='path/to/best.pt', force_reload=True)
# 测试模型
results = model('path/to/image.jpg')
results.print()
```
通过上述方法,可以有效解决YOLOv5在使用PyTorch 2.6.0+cu126和CUDA环境下加载权重时的`UnpicklingError`问题。
阅读全文
相关推荐

















