如何仅用CPU训练YOLO v7?Mac训练CUDA报错解决问询
解决Mac上仅用CPU训练YOLOv7的CUDA设备错误
问题根源
错误出现在yolov7/utils/loss.py的build_targets方法中,代码硬编码指定了CUDA设备(device='cuda:0'),但你的环境只有CPU可用,导致初始化CUDA tensor失败。
具体修复步骤
- 打开
yolov7/utils/loss.py文件,找到对应报错的第786行代码:matching_bs[i] = torch.tensor([], device='cuda:0', dtype=torch.int64) - 将硬编码的
device='cuda:0'替换为动态获取当前训练设备,可选择以下两种方式之一:- 方式一:从预测张量中获取设备(推荐,适配性更强)
matching_bs[i] = torch.tensor([], device=p[0].device, dtype=torch.int64) - 方式二:从目标张量中获取设备
matching_bs[i] = torch.tensor([], device=targets.device, dtype=torch.int64)
- 方式一:从预测张量中获取设备(推荐,适配性更强)
- 全局检查
build_targets方法内其他硬编码CUDA的语句(比如device='cuda'),全部替换为动态设备参数。 - 重新执行原训练命令:
python train.py --workers 1 --device cpu --batch-size 1 --epochs 20 --img 640 640 --data data/custom_data.yaml --hyp data/hyp.scratch.custom.yaml --cfg cfg/training/yolov7-custom.yaml --name yolov7-custom --weights yolov7.pt
额外验证点
执行以下命令确认PyTorch环境为CPU版本:
python -c "import torch; print(torch.cuda.is_available())"
输出应为False,说明环境配置正确。
内容的提问来源于stack exchange,提问作者Glechik
相关产品推荐
相关产品推荐

