CUDA error: invalid device ordinal

cudaErrorInvalidDeviceerror 101

In PyTorch the same failure appears as RuntimeError: CUDA error: invalid device ordinal.

Common causes

Code written for a multi-GPU machine

A hard-coded cuda:1, cudaSetDevice(1) or a --gpu 1 default works on the machine it was written on and fails on a laptop, Colab or a single-GPU cloud instance.

CUDA_VISIBLE_DEVICES renumbers the GPUs

With CUDA_VISIBLE_DEVICES=2, physical GPU 2 becomes device 0 inside the process and there is no device 1 or 2. Schedulers such as Slurm and Kubernetes set this variable for you.

More workers than GPUs

torchrun --nproc_per_node=4 on a 2-GPU machine gives ranks 2 and 3 a local_rank with no matching GPU.

Reproduce it

Press Run to execute this on a real NVIDIA GPU in the playground.

Repro: select GPU 1 on a one-GPU machine
main.cu
123456789101112
#include <cstdio>
#include <cuda_runtime.h>

int main() {
    int count = 0;
    cudaGetDeviceCount(&count);
    printf("visible GPUs: %d\n", count);

    cudaError_t err = cudaSetDevice(1);
    printf("cudaSetDevice(1): %s (%s)\n", cudaGetErrorString(err), cudaGetErrorName(err));
    return 0;
}
Output on an NVIDIA T4
visible GPUs: 1
cudaSetDevice(1): invalid device ordinal (cudaErrorInvalidDevice)

Fix

Fixed: pick a device that exists
main.cu
12345678910111213141516171819202122232425262728
#include <cstdio>
#include <cstdlib>
#include <cuda_runtime.h>

#define CUDA_CHECK(call)                                                  \
    do {                                                                  \
        cudaError_t err_ = (call);                                        \
        if (err_ != cudaSuccess) {                                        \
            fprintf(stderr, "%s:%d: %s (%s)\n", __FILE__, __LINE__,       \
                    cudaGetErrorString(err_), cudaGetErrorName(err_));    \
            exit(1);                                                      \
        }                                                                 \
    } while (0)

int main() {
    int count = 0;
    CUDA_CHECK(cudaGetDeviceCount(&count));

    int wanted = 1;                                  // e.g. from a command-line flag
    int device = wanted < count ? wanted : 0;
    if (device != wanted) printf("GPU %d not found, using GPU %d\n", wanted, device);
    CUDA_CHECK(cudaSetDevice(device));

    cudaDeviceProp prop;
    CUDA_CHECK(cudaGetDeviceProperties(&prop, device));
    printf("running on device %d: %s\n", device, prop.name);
    return 0;
}
Output on an NVIDIA T4
GPU 1 not found, using GPU 0
running on device 0: Tesla T4

In PyTorch

Loading a checkpoint saved on another GPU fails with a different message ("Attempting to deserialize object on CUDA device 1"). Pass map_location="cuda:0" or map_location="cpu" to torch.load to fix that one.

PyTorch repro and fix
main.py
123456789101112
import torch

print("device_count:", torch.cuda.device_count())
try:
    x = torch.zeros(3, device="cuda:1")
except RuntimeError as e:
    print("RuntimeError:", str(e).splitlines()[0])

# Fix: derive the device from what exists.
index = 1 if torch.cuda.device_count() > 1 else 0
x = torch.zeros(3, device=f"cuda:{index}")
print("tensor on", x.device)
Output on an NVIDIA T4
device_count: 1
RuntimeError: CUDA error: invalid device ordinal
tensor on cuda:0

Debugging checklist

  1. Print the device count inside the failing process: cudaGetDeviceCount or torch.cuda.device_count().
  2. Print CUDA_VISIBLE_DEVICES. If it is set, the device numbers you can use are 0 to (number of listed GPUs - 1).
  3. Search the code and its config files for hard-coded device numbers such as cuda:1, device_ids=[0, 1] or --gpu.

FAQ

Why does nvidia-smi show GPU 1 but my program cannot use it?

nvidia-smi lists physical GPUs and ignores CUDA_VISIBLE_DEVICES. Inside your process, CUDA only numbers the visible GPUs, starting from 0.

Is this error sticky?

No. The failed cudaSetDevice leaves the current device unchanged, and you can select a valid device and continue.