CUDA Python

13.2.0 · active · verified Thu Apr 09

CUDA Python provides a high-performance Python interface to NVIDIA's CUDA Driver and Runtime APIs, allowing direct GPU programming from Python. It bridges Python applications with CUDA-enabled GPUs, enabling GPU acceleration for custom kernels and integration with other CUDA libraries. The current version is 13.2.0 and releases generally align with major CUDA Toolkit updates.

Warnings

Install

Imports

Quickstart

This quickstart initializes the CUDA Driver API and queries the number of available CUDA-enabled GPUs on the system, printing their names. It demonstrates basic interaction with the driver API and includes error handling for common CUDA-related issues.

import cuda.cuda_driver as drv

try:
    # Initialize the CUDA driver API
    # The '0' indicates the flags for initialization, 0 means default.
    drv.cuInit(0)

    # Get the number of available CUDA devices
    err, device_count = drv.cuDeviceGetCount()

    if err == drv.CUresult.CUDA_SUCCESS:
        print(f"Successfully initialized CUDA. Found {device_count} CUDA devices.")
        for i in range(device_count):
            err, device = drv.cuDeviceGet(i)
            if err == drv.CUresult.CUDA_SUCCESS:
                # Get device name (256 is max length)
                err, name_bytes = drv.cuDeviceGetName(256, device)
                if err == drv.CUresult.CUDA_SUCCESS:
                    # Decode the bytes to string and strip null terminators
                    device_name = name_bytes.decode('utf-8').strip('\x00')
                    print(f"  Device {i}: {device_name}")
    else:
        print(f"Failed to get CUDA device count. Error: {err.name}")
except drv.CUError as e:
    print(f"A CUDA driver error occurred: {e}. Ensure CUDA Toolkit and drivers are installed correctly and compatible.")
except Exception as e:
    print(f"An unexpected error occurred: {e}")

view raw JSON →