Traceback (most recent call last): File "D:\yolov5\yolov5-6.0\detect.py", line 307, in <module> main(opt) File "D:\yolov5\yolov5-6.0\detect.py", line 302, in main run(**vars(opt)) File "C:\Users\故里\AppData\Roaming\Python\Python312\site-packages\torch\utils\_contextlib.py", line 116, in decorate_context return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "D:\yolov5\yolov5-6.0\detect.py", line 82, in run model = torch.jit.load(w) if 'torchscript' in w else attempt_load(weights, map_location=device) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\yolov5\yolov5-6.0\models\experimental.py", line 94, in attempt_load ckpt = torch.load(attempt_download(w), map_location=map_location) # load ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\故里\AppData\Roaming\Python\Python312\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 models.yolo.Model was not an allowed global by default. Please use `torch.serialization.add_safe_globals([Model])` or the `torch.serialization.safe_globals([Model])` context manager to allowlist this global if you trust this class/function. Check the documentation of torch.load to learn more about ty
时间: 2025-05-13 13:23:22 浏览: 26
### 解决 PyTorch 加载权重文件时出现的 UnpicklingError 错误
当遇到 `_unpicklingerror` 错误时,通常是因为尝试加载模型权重的过程中遇到了不受支持的全局类或函数。这种问题可能源于保存模型的方式或者环境中缺少必要的依赖项。
#### 1. 使用 `weights_only=True` 参数
PyTorch 的 `torch.load` 方法提供了一个参数 `weights_only`,可以用来仅加载张量数据而不加载其他 Python 对象。这有助于避免因序列化过程中涉及复杂对象而导致的错误[^1]。可以通过如下方式修改加载逻辑:
```python
import torch
model = torch.load('path_to_your_weights.pt', map_location=torch.device('cpu'), weights_only=True)
```
此方法适用于只需要加载权重而不需要恢复完整的训练状态的情况。
#### 2. 添加安全全局变量到允许列表
如果需要加载更复杂的模型结构,则应考虑将特定的全局类显式加入允许列表。通过调用 `torch.serialization.add_safe_globals()` 函数来实现这一点。例如,在加载 YOLOv5 模型时,可能会涉及到 `ultralytics.nn.tasks.DetectionModel` 类,因此需将其添加至允许列表中:
```python
from ultralytics.nn.tasks import DetectionModel
import torch
torch.serialization.add_safe_globals(DetectionModel=DetectionModel)
model = torch.load('path_to_your_weights.pt')
```
这样能够确保在反序列化期间不会因为未知全局变量引发异常。
#### 3. 调整批量大小和工作线程数
有时硬件资源不足也会导致类似的错误消息。降低 batch size 和 workers 数量可以帮助缓解内存压力并减少潜在冲突[^2]。例如调整命令行为以下形式运行脚本:
```bash
python -m torch.distributed.launch --nproc_per_node=2 train.py \
--weights weights/yolov5m6_coco.pt \
--img 640 \
--epochs 500 \
--data fire_smoke.yaml \
--batch-size 16 \
--workers 4 \
--save-period 20
```
这里我们将批处理尺寸从原来的 24 改为了 16,并减少了工作者数量以适应计算设备的能力。
#### 4. 更新环境配置
最后,请确认所使用的库版本是最新的,尤其是 PyTorch 及其相关扩展包(如 Ultralytics)。旧版可能存在兼容性问题从而引起此类错误。执行 pip 命令更新软件包:
```bash
pip install --upgrade torch torchvision torchaudio ultralytics
```
以上措施综合应用可有效应对大多数情况下发生的 _unpicklingerror 错误。
阅读全文
相关推荐


















