Moving a NumPy computation to the GPU with CuPy

BeginnerGPU accelerationAccelerating computation

Goal: Running NumPy-style code on the GPU.

Python — example.py
import numpy as np, cupy as cp

a = cp.asarray(np.random.rand(4096, 4096).astype(np.float32))
b = a @ a.T
cp.cuda.Stream.null.synchronize()
print("Result on:", b.device, "| shape:", b.shape)
print("First value:", float(cp.asnumpy(b[0, 0])))

Code explanation

cupy.asarray moves the array to GPU memory, the functions work under the same names, and cupy.asnumpy brings it back. It needs an NVIDIA GPU (or AMD with ROCm) and the CuPy package matching the CUDA version, so it was not run in a test environment without a GPU.

Requirements

Shell
pip install cupy-cuda12x

How to run

Save the code in a file example.py then run it:

Shell
python example.py

This example was not run in the test environment: needs a GPU and CUDA. Check it against the library documentation before relying on it.

Libraries used

Related examples

ResearchTriton LanguageNot run in the test environment

A vector addition kernel in Triton

Writing a GPU kernel in Python instead of CUDA C++.

GPU acceleration · Custom GPU kernels