报错:
RuntimeError: CUDA out of memory. Tried to allocate 1024.00 MiB (GPU 0; 7.78 GiB total capacity; 4.60 GiB already allocated; 372.94 MiB free; 5.65 GiB reserved in total by PyTorch) If reserved memory is >> allocated memory try setting max_split_size_mb to avoid fragmentation. See documentation for Memory Management and PYTORCH_CUDA_ALLOC_CONF
RuntimeError: CUDA error: out of memory CUDA kernel errors might be asynchronously reported at some other API call,so the stacktrace below might be incorrect. For debugging consider passing CUDA_LAUNCH_BLOCKING=1.
你遇到的错误是典型的 CUDA内存不足(CUDA Out of Memory)问题。你的GPU显存不足以处理当前任务,特别是在调用 image_encoder 时,出现了内存分配失败的情况。此类问题在处理大尺寸图像或深层神经网络时很常见。
解决方案1:减小批量大小(batch size)
通过减小批量大小来降低每次迭代中占用的显存
例如:batch_size=16#设置为较小的值
解决方案2:减小图像尺寸
缩小输入图像的分辨率以减小占用的内存
例如:resized_img = cv2.resize(img, (width // 2, height // 2))
解决方案3:清理缓存
你在多次运行过程中遇到该错误,可能是由于先前运行遗留的显存占用。
torch.cuda.empty_cache()
解决方案4:将模型移动到CPU上
model.to('cpu')
解决方案5:使用torch.cuda.set_per_process_memory_fraction调整显存使用
通过设置每个进程的显存分配比例来避免过度占用:
torch.cuda.set_per_process_memory_fraction(0.75)
解决方案6:尝试 torch.cuda.set_max_split_size_mb
这个选项可以减少显存碎片化,帮助模型更好地利用显存:
torch.cuda.set_max_split_size_mb(128)
解决方案7:切换到CPU/GPU混合模式
如果有些操作不需要在GPU上进行,你可以将部分操作切换到CPU,这样可以减轻GPU的压力。你可以在特定的操作上使用 .cpu() 方法。
其中,减少批量大小和输入图像尺寸,是最直接有效的方式。
解决方案8:重启CUDA进程
运行
nvidia-smi
查看哪些进程占用了显存,通过如下命令来结束进程。
kill -9 [PID]
1万+

被折叠的 条评论
为什么被折叠?



