CUDA error: invalid device ordinal
时间: 2023-08-14 10:23:52 浏览: 60
该错误通常表示使用了无效的 GPU 设备索引。GPU 设备索引从 0 开始,如果使用了大于等于当前计算机 GPU 数量的索引,就会出现该错误。
以下是几种可能的解决方法:
1. 检查 GPU 设备数量:可以使用 `torch.cuda.device_count()` 函数检查当前计算机的 GPU 设备数量。
2. 检查 GPU 设备索引:如果使用了 GPU 设备索引,需要确保索引小于当前计算机的 GPU 设备数量。
3. 检查 PyTorch 版本:有些版本的 PyTorch 可能存在该错误。可以尝试升级或降级 PyTorch 版本。
以下是一个简单的示例代码,可以检查 GPU 设备数量和索引是否正确:
```python
import torch
if torch.cuda.is_available():
print(f"Number of GPUs: {torch.cuda.device_count()}")
for i in range(torch.cuda.device_count()):
print(f"GPU {i}: {torch.cuda.get_device_name(i)}")
else:
print("GPU is not available.")
# 假设当前计算机有两个 GPU 设备,使用第三个设备索引会出现 invalid device ordinal 错误
device = torch.device('cuda:2') # 错误的设备索引
```
如果输出结果中的 `Number of GPUs` 为 2,则可以使用 0 或 1 作为 GPU 设备索引。