# 内部错误：CUDA_ERROR_INVALID_DEVICE：无效的设备序号

- **ID:** `tensorflow/gpu-visible-devices-invalid-id`
- **领域:** tensorflow
- **类别:** config_error
- **错误码:** `GID`
- **验证级别:** ai_generated
- **修复率:** 90%

## 根因

CUDA_VISIBLE_DEVICES 环境变量引用了系统中不存在的 GPU 索引。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| tensorflow 2.12 | active | — | — |
| tensorflow 2.13 | active | — | — |
| tensorflow 2.14 | active | — | — |
| cuda 11.8 | active | — | — |
| cuda 12.0 | active | — | — |

## 解决方案

1. ```
   List available GPUs with nvidia-smi, then set CUDA_VISIBLE_DEVICES to a valid index. For example: export CUDA_VISIBLE_DEVICES=0 (if only one GPU exists). In Python: import os; os.environ['CUDA_VISIBLE_DEVICES'] = '0'; import tensorflow as tf; print(tf.config.list_physical_devices('GPU'))
   ```
2. ```
   Remove CUDA_VISIBLE_DEVICES entirely to let TensorFlow auto-detect all GPUs: unset CUDA_VISIBLE_DEVICES
   ```

## 无效尝试

- **Reinstalling CUDA drivers** — The issue is not driver installation but environment variable misconfiguration; reinstalling drivers does not fix the ordinal mapping. (95% 失败率)
- **Setting CUDA_VISIBLE_DEVICES to all GPUs (e.g., '0,1,2,3') blindly** — If the system has fewer GPUs than specified, the error persists; the correct approach is to query available devices first. (70% 失败率)
