# 运行时错误：CUDA 错误：无效的设备序号

- **ID:** `pytorch/cuda-error-invalid-device-ordinal`
- **领域:** pytorch
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 85%

## 根因

请求的 GPU 设备索引（如 cuda:0）在系统中不存在，或者 CUDA_VISIBLE_DEVICES 环境变量限制了可用设备。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| pytorch>=2.0.0 | active | — | — |
| cuda>=11.7 | active | — | — |

## 解决方案

1. ```
   使用 `torch.cuda.device_count()` 检查可用 GPU 设备，并通过 `nvidia-smi` 列出。然后设置有效的设备索引，例如 `torch.device('cuda:0')`。
   ```
2. ```
   检查 CUDA_VISIBLE_DEVICES 环境变量。在 bash 中运行 `echo $CUDA_VISIBLE_DEVICES`，如果已设置，确保包含有效索引，或取消设置：`unset CUDA_VISIBLE_DEVICES`。
   ```

## 无效尝试

- **** — The issue is configuration (device index), not installation. Reinstalling does not fix the index mismatch. (70% 失败率)
- **** — The environment variable is still incorrect after the change; users may set it to a non-existent device. (50% 失败率)
- **** — This still fails if no GPU is available; the root cause is the ordinal, not the device type. (60% 失败率)
