GPU acceleration for Python: CuPy, Numba CUDA, PyTorch and JAX
Updated · Scientifically reviewed by Dinkar Mishra, PhD on
Short answer
The quickest route is CuPy: replace import numpy as np with import cupy as cp for array code, keep data on the GPU, and copy results back only at the end. For custom loops, write kernels with Numba CUDA or CuPy RawKernel. PyTorch and JAX also offer GPU arrays plus automatic differentiation. GPUs pay off for large, parallel array operations; small arrays and frequent CPU–GPU transfers can make code slower.
Who this is for
Researchers with NumPy-based analysis or simulation code who want to use a GPU without writing CUDA C++.
Software
CuPy ≥ 13 (cupy-cuda12x)Numba ≥ 0.57NVIDIA driver supporting CUDA 12.x
Prerequisites
- An NVIDIA GPU with a working driver (
nvidia-smi). If not, see NVIDIA driver installation on Ubuntu. - A Python environment. Install CuPy for your CUDA major version:
python -m pip install cupy-cuda12x.
Step 1: NumPy code on the GPU with CuPy
import cupy as cp
n = 4096
rng = cp.random.default_rng(0)
a = rng.random((n, n), dtype=cp.float32)
b = rng.random((n, n), dtype=cp.float32)
c = a @ b # runs on the GPU
s = float(c.sum()) # brings one number back to the CPU
print(f"checksum = {s:.4e}")
Most NumPy functions have CuPy equivalents (cp.fft, cp.linalg, and cupyx.scipy for parts of SciPy). Move data explicitly: cp.asarray(np_array) to the GPU, cp.asnumpy(gpu_array) back.
Step 2: time it correctly
GPU calls are asynchronous: they return before the work finishes. Synchronise before reading timers, and exclude the first (warm-up) call:
import time
import cupy as cp
x = cp.random.default_rng(1).random(50_000_000, dtype=cp.float64)
cp.sqrt(x) # warm-up: loads kernels
cp.cuda.Stream.null.synchronize()
t0 = time.perf_counter()
for _ in range(10):
y = cp.sqrt(x) * 2.0 + 1.0
cp.cuda.Stream.null.synchronize() # wait for the GPU to finish
print(f"{(time.perf_counter() - t0) / 10 * 1e3:.2f} ms per iteration")
Step 3: custom kernels with Numba CUDA
For loops that do not map onto array operations, write a kernel. Each GPU thread handles one element:
import numpy as np
from numba import cuda
@cuda.jit
def push(x, v, E, dt, qm):
i = cuda.grid(1)
if i < x.size:
v[i] += qm * E[i] * dt
x[i] += v[i] * dt
n = 10_000_000
x = cuda.to_device(np.random.default_rng(2).random(n))
v = cuda.to_device(np.zeros(n))
E = cuda.to_device(np.ones(n))
threads = 256
blocks = (n + threads - 1) // threads
push[blocks, threads](x, v, E, 1e-3, -1.0)
cuda.synchronize()
print(x.copy_to_host()[:3])
The cost of moving data
Host–GPU transfers go over PCIe or a similar link, which is much slower than the GPU’s own memory. A computation that copies an array to the GPU, does one small operation and copies it back is usually slower than NumPy. Load data once, do as much work as possible on the GPU, and transfer only final results or occasional diagnostics.
Step 4: when to use PyTorch or JAX
If your workflow includes optimisation, inverse problems or machine learning, frameworks with automatic differentiation are valuable: gradients of a simulation with respect to its parameters come almost for free. JAX’s jit and vmap are especially convenient for batched scientific computations.
Verify
- Correctness: compare GPU results with the NumPy version on a small input (
np.allclose), with tolerances appropriate to the precision used. - Speed: time both versions as in step 2, at the array sizes you actually use. Expect gains only above a certain size.
- Utilisation: while the code runs,
nvidia-smishould show high GPU utilisation. If it is low, the CPU or data transfers are the bottleneck.
Troubleshooting
ImportErroror CUDA library errors from CuPy: the CuPy build does not match your driver’s CUDA version. Reinstall the matchingcupy-cuda11xorcupy-cuda12x.- Out of memory: see CUDA out of memory.
- No speedup: the arrays are too small, transfers happen inside loops, or the work is in Python control flow. Restructure into larger batched operations first.
Assumptions and limitations
- Examples target NVIDIA GPUs and CUDA 12-era packages. Package names change with CUDA major versions.
- Speedups depend strongly on the GPU model, precision, array sizes and memory access patterns. No figures are given here; benchmark your workload.
- For large production simulation codes, a native GPU implementation (CUDA, HIP, Kokkos, or a GPU-ready code such as WarpX) usually outperforms Python-level acceleration.
Frequently asked questions
Why is my GPU code slower than NumPy?+
Usually because arrays are small (kernel-launch overhead dominates), data is copied between CPU and GPU inside the loop, or the timing includes one-off start-up and compilation. Keep data on the GPU, batch work into large arrays, and synchronise before stopping timers.
Do I need double precision?+
Many simulations do. Data-centre GPUs (for example NVIDIA A100/H100) have high FP64 throughput; most consumer and workstation GPUs have far lower FP64 than FP32 performance. Check your GPU's specification before porting double-precision codes.
Does this work on AMD GPUs?+
CuPy has ROCm support for AMD GPUs, and PyTorch and JAX have ROCm builds. Numba's CUDA target is NVIDIA-only. Check each project's documentation for the hardware and versions supported.
Which should I choose: CuPy, PyTorch or JAX?+
CuPy for porting existing NumPy/SciPy code with minimal changes; PyTorch if you also train neural networks; JAX for functional code that benefits from jit compilation, vectorisation (vmap) and automatic differentiation.
References
- CuPy user guide: basics · CuPy
- Numba for CUDA GPUs · Numba
- JAX documentation · JAX (Google)
- CUDA C++ Best Practices Guide · NVIDIA
Want this set up and verified for you?
We install, configure and validate scientific software on your workstation, cluster or cloud, and train your team to run it.
Services listed on this page are available today. Products marked “early access” or “in development” on our platform page are not yet generally available.
Spotted an error or an outdated command? Tell us. We correct verified issues promptly.