基于Yolov8在训练集基础上训练时,报错UnpicklingError: Weights only load failed.

1.1报错详情

        在搭建好的虚拟环境中使用YOLOv8进行目标检测时,需要用数据集进行训练。在启动训练脚本时,遇到了报错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.

1.2报错图片

        报错图片如下:

        其中,训练使用的bvn_train.py文件如下(参考自B站/github——你可是处女座啊——手把手带你实战YOLOv8):

from ultralytics import YOLO
model=YOLO('yolov8n.pt')
model.train(data='bvn.yaml',workers=0,epochs=50,batch=16)

1.3解决方案

        在报错的文件后追加代码语句“, weights_only=False”,详情如下所示:

(1)根据报错代码,找到倒数第二个file,ctrl+单击进入第634行代码。

(2)在第634行代码torch.load()中添加“, weights_only=False”。

return torch.load(file, map_location="cpu"), file  # 原始代码
return torch.load(file, map_location="cpu", weights_only=False), file  # 修改后的代码

再次运行,发现原有报错消失,程序开始训练。

此处省略50条epoch的内容。

        50条epoch跑完,程序尝试traceback时,再次遇到相同报错。

2.1报错详情

        启动训练脚本后,完成50条epoch后,遇到了报错。

        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.

2.2报错图片

报错图片如下:

2.3解决方案

同上,在报错的文件后追加代码语句“, weights_only=False”,详情如下所示:

(1)根据报错代码,找到倒数第二个file,ctrl+单击进入第484行代码。

(2)在第484行代码torch.load()中添加“, weights_only=False”。

    x = torch.load(f, map_location=torch.device("cpu"))#原始代码
    x = torch.load(f, map_location=torch.device("cpu"), weights_only=False)#修改后的代码

        再次运行,发现原有报错消失,程序开始训练。训练完成后不再报错,成功将结果存回train7。完美!

### 解析 `_pickle.UnpicklingError` 错误 当遇到 `_pickle.UnpicklingError` 错误,通常意味着反序列化过程中出现问题。具体来说: - 对于 `STACK_GLOBAL requires str` 和 `invalid load key, '\x00'` 这类错误消息表明 Pickle 在尝试解析全局对象名称或遇到了无效的负载键[^1]。 - 当提示 `pickle data was truncated` ,则表示数据流在预期结束之前就已终止,这可能是由于文件损坏或者未完全写入造成的[^4]。 为了安全地加载来自不可信来源的 checkpoint 文件,建议采取以下措施来增强安全性并解决问题: #### 验证 Checkpoint 来源的安全性 确保所使用的 checkpoint 文件来源于可靠的渠道,并尽可能验证其完整性与合法性。如果无法确认源头可信度,应谨慎对待这些外部资源。 #### 使用受限环境执行加载操作 创建一个隔离的工作区,在其中测试未知的数据集或模型权重。这样即使发生异常情况也能将影响范围控制在一个较小区域内。 ```python import os os.environ['PYTHONPATH'] = '' # 清除 PYTHONPATH 环境变量以减少潜在风险 ``` #### 设置超机制防止无限等待 对于可能长间无响应的操作设定合理的超期限,避免因恶意构造的数据而导致程序挂起。 ```python from multiprocessing import Process, TimeoutError def load_checkpoint_with_timeout(timeout_seconds): p = Process(target=load_checkpoint_function) p.start() try: p.join(timeout_seconds) if p.is_alive(): raise TimeoutError("Loading process took too long.") finally: p.terminate() # 调用此函数代替直接调用原生加载方法 load_checkpoint_with_timeout(60) # 设定最大允许间为60秒 ``` #### 更新依赖库版本 有旧版 Python 或第三方模块可能存在 bug 导致此类问题频发;因此保持软件栈处于最新状态有助于规避一些已知漏洞。 ```bash pip install --upgrade python-xlwings pandas numpy scikit-learn tensorflow torch torchvision torchaudio dill cloudpickle msgpack-python ``` #### 处理特定场景下的工作参数调整 针对某些特殊应用场景(如多线程或多进程),适当修改配置项可缓解兼容性难题。例如设置 `num_workers=0` 可能会改善 Windows 平台下分布式计算任务中的不稳定现象[^5]。 ```yaml data_loader_config: batch_size: 8 shuffle: true num_workers: 0 # 关闭子进程预取功能适用于单机调试阶段 ``` 通过以上策略能够有效地降低加载非官方发布的 checkpoint 文件所带来的安全隐患,并提高系统的稳定性和可靠性。
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值