pytorch
runtime_error
ai_generated
true
运行时错误:CUDA 错误:无效的设备序号
RuntimeError: CUDA error: invalid device ordinal
ID: pytorch/cuda-error-invalid-device-ordinal
85%修复率
88%置信度
1证据数
2024-03-15首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| pytorch>=2.0.0 | active | — | — | — |
| cuda>=11.7 | active | — | — | — |
根因分析
请求的 GPU 设备索引(如 cuda:0)在系统中不存在,或者 CUDA_VISIBLE_DEVICES 环境变量限制了可用设备。
English
The requested GPU device index (e.g., cuda:0) does not exist on the system, or the CUDA_VISIBLE_DEVICES environment variable restricts available devices.
官方文档
https://pytorch.org/docs/stable/notes/cuda.html#device-handling解决方案
-
使用 `torch.cuda.device_count()` 检查可用 GPU 设备,并通过 `nvidia-smi` 列出。然后设置有效的设备索引,例如 `torch.device('cuda:0')`。 -
检查 CUDA_VISIBLE_DEVICES 环境变量。在 bash 中运行 `echo $CUDA_VISIBLE_DEVICES`,如果已设置,确保包含有效索引,或取消设置:`unset CUDA_VISIBLE_DEVICES`。
无效尝试
常见但无效的做法:
-
70% 失败
The issue is configuration (device index), not installation. Reinstalling does not fix the index mismatch.
-
50% 失败
The environment variable is still incorrect after the change; users may set it to a non-existent device.
-
60% 失败
This still fails if no GPU is available; the root cause is the ordinal, not the device type.