在 Linux 上使用 PyTorch 报“内存错”(通常是 CUDA out of memory 或 RuntimeError: unable to allocate memory),原因一般可以归为以下几类。我按最常见 → 较少见给你梳理,并给出对应解决办法。
报错类似:
RuntimeError: CUDA out of memory. Tried to allocate ...
原因
解决办法
# 1. 减小 batch size
batch_size = 8 # 改成 4 / 2
# 2. 及时释放显存
del x, y
torch.cuda.empty_cache()
# 3. 使用混合精度
from torch.cuda.amp import autocast, GradScaler
scaler = GradScaler()
with autocast():
output = model(input)
报错类似:
RuntimeError: Expected all tensors to be on the same device
原因
.cuda() 和 .to(device) 混用正确写法
device = "cuda" if torch.cuda.is_available() else "cpu"
model = model.to(device)
x = x.to(device)
.cuda() 但机器没有 GPU报错:
AssertionError / CUDA error / no CUDA-capable device
检查
nvidia-smi
python -c "import torch; print(torch.cuda.is_available())"
报错:
MemoryError
Bus error
Killed
原因
解决
DataLoader(..., num_workers=4) # 减少
free -h
top
Linux 默认可能限制内存或线程数。
ulimit -a
可临时解除:
ulimit -s unlimited
nvcc --version
python -c "import torch; print(torch.version.cuda)"
不匹配会导致奇怪的内存/设备错误。
即使显存“看着够”,也可能分配失败。
解决
torch.cuda.memory_summary() 查看你可以照着一步步来:
nvidia-smi 看显存占用torch.cuda.is_available()你可以把完整报错信息贴出来(红字那段),我可以精准判断是显存 / 内存 / 设备 / 代码问题,甚至帮你改代码。