Kernel Programming in Python with Numba HIP#
2026-08-31
30 min read
Advanced Micro Devices, Inc.
Numba is a just-in-time (JIT) compiler that turns a subset of Python and NumPy into fast machine code. Numba HIP is the ROCm™ HIP backend for Numba: it lets you write GPU kernels in Python and run them on AMD GPUs.
Numba HIP intentionally mirrors the numba.cuda API, so there are two
equivalent ways to use it.
Natively, through the numba.hip package (recommended for new code).
Every name lives under numba.hip instead of numba.cuda; the only
difference is the module prefix:
from numba import hip
@hip.jit
def f(a, b, c):
tid = hip.grid(1)
size = len(c)
if tid < size:
c[tid] = a[tid] + b[tid]
By posing as numba.cuda (mainly for porting). A single call re-binds
the numba.cuda module onto the HIP backend, so existing Numba CUDA kernels
run unchanged. This is intended primarily for porting existing Numba CUDA code:
from numba import hip
hip.pose_as_cuda()
from numba import cuda # now backed by HIP
Note
The examples in this chapter are the hipified versions of the upstream Numba
CUDA documentation examples. They are exercised as part of the Numba HIP test
suite under tests/numba-hip/doc_examples/ and run on AMD GPUs via the
hip.pose_as_cuda() shim shown above. Each example below begins with the
import + pose_as_cuda() preamble (omitted from the snippets for brevity).
All examples can equally be run natively through the numba.hip
package. Drop the pose_as_cuda() call, use from numba import hip,
and replace the cuda. prefix with hip. throughout (e.g. @hip.jit,
hip.grid(1), hip.to_device, hip.device_array_like,
hip.shared.array, hip.syncthreads(), hip.declare_device).
hip.pose_as_cuda() is mainly intended for porting existing Numba CUDA
code.
Installation#
Numba HIP ships as its own wheel, numba-hip, versioned independently of
the ROCm™-tracking binding wheels:
python3 -m pip install numba-hip
It declares numba, rocm-bindings-hip, rocm-bindings-compiler, and
hip-python-interop as dependencies, so pip pulls in the bindings it needs.
A ROCm™ installation must be present; see Installation.
Numba HIP compiles its kernels through the LLVM bindings in
rocm-bindings-compiler, which resolve a shared LLVM at the first call.
JIT Compilation and LLVM IR describes those bindings and how to
check that a library is there.
Note
On Windows, ROCm™ ships only static LLVM archives, so a shared
LLVM has to be linked from them at build time. Both the published
rocm-bindings-compiler wheel and a default source build carry one, so
Numba HIP works out of the box either way: its test suite passes. Only a
build that opts out with HIP_PYTHON_BUNDLE_LIBLLVM=OFF – which saves
about 75 MB in the wheel – leaves numba.hip unable to compile a kernel.
See Building from Source for that flag and for
HIP_PYTHON_BUILD_NUMBA_HIP, which builds the numba-hip wheel itself
from source.
Vector addition#
A minimal element-wise kernel. cuda.grid(1) returns the global thread index;
each thread adds one pair of elements:
@cuda.jit
def f(a, b, c):
# like threadIdx.x + (blockIdx.x * blockDim.x)
tid = cuda.grid(1)
size = len(c)
if tid < size:
c[tid] = a[tid] + b[tid]
Allocate device arrays with cuda.to_device / cuda.device_array_like:
N = 100000
a = cuda.to_device(np.random.random(N))
b = cuda.to_device(np.random.random(N))
c = cuda.device_array_like(a)
The simplest launch lets forall pick the grid configuration for you:
f.forall(len(a))(a, b, c)
print(c.copy_to_host())
Or specify the block/grid dimensions explicitly:
# Enough threads per block for several warps per block
nthreads = 256
# Enough blocks to cover the entire vector depending on its length
nblocks = (len(a) // nthreads) + 1
f[nblocks, nthreads](a, b, c)
print(c.copy_to_host())
Reduction#
A shared-memory tree reduction. cuda.shared.array allocates per-block shared
memory and cuda.syncthreads() synchronizes the threads in a block:
@cuda.jit
def array_sum(data):
tid = cuda.threadIdx.x
size = len(data)
if tid < size:
i = cuda.grid(1)
# Declare an array in shared memory
shr = cuda.shared.array(nelem, int32)
shr[tid] = data[i]
# Ensure writes to shared memory are visible
# to all threads before reducing
cuda.syncthreads()
s = 1
while s < cuda.blockDim.x:
if tid % (2 * s) == 0:
# Stride by `s` and add
shr[tid] += shr[tid + s]
s *= 2
cuda.syncthreads()
# After the loop, the zeroth element contains the sum
if tid == 0:
data[tid] = shr[tid]
Launch it over a single block covering the whole input array:
array_sum[1, nelem](a)
print(a[0]) # 523776
print(sum(np.arange(1024))) # 523776
Matrix multiplication#
A naive 2-D kernel where each thread computes one output element via
cuda.grid(2):
@cuda.jit
def matmul(A, B, C):
"""Perform square matrix multiplication of C = A * B."""
i, j = cuda.grid(2)
if i < C.shape[0] and j < C.shape[1]:
tmp = 0.0
for k in range(A.shape[1]):
tmp += A[i, k] * B[k, j]
C[i, j] = tmp
Run it with a 2-D block/grid:
x_h = np.arange(16).reshape([4, 4])
y_h = np.ones([4, 4])
z_h = np.zeros([4, 4])
x_d = cuda.to_device(x_h)
y_d = cuda.to_device(y_h)
z_d = cuda.to_device(z_h)
threadsperblock = (16, 16)
blockspergrid_x = math.ceil(z_h.shape[0] / threadsperblock[0])
blockspergrid_y = math.ceil(z_h.shape[1] / threadsperblock[1])
blockspergrid = (blockspergrid_x, blockspergrid_y)
matmul[blockspergrid, threadsperblock](x_d, y_d, z_d)
z_h = z_d.copy_to_host()
print(z_h)
print(x_h @ y_h)
A faster, shared-memory tiled variant blocks the dot product into
TPB-by-TPB tiles:
# Controls threads per block and shared memory usage.
# The computation will be done on blocks of TPBxTPB elements.
# TPB should not be larger than 32 in this example
TPB = 16
@cuda.jit
def fast_matmul(A, B, C):
"""
Perform matrix multiplication of C = A * B using CUDA shared memory.
Reference: https://stackoverflow.com/a/64198479/13697228 by @RobertCrovella
"""
# Define an array in the shared memory
# The size and type of the arrays must be known at compile time
sA = cuda.shared.array(shape=(TPB, TPB), dtype=float32)
sB = cuda.shared.array(shape=(TPB, TPB), dtype=float32)
x, y = cuda.grid(2)
tx = cuda.threadIdx.x
ty = cuda.threadIdx.y
bpg = cuda.gridDim.x # blocks per grid
# Each thread computes one element in the result matrix.
# The dot product is chunked into dot products of TPB-long vectors.
tmp = float32(0.0)
for i in range(bpg):
# Preload data into shared memory
sA[ty, tx] = 0
sB[ty, tx] = 0
if y < A.shape[0] and (tx + i * TPB) < A.shape[1]:
sA[ty, tx] = A[y, tx + i * TPB]
if x < B.shape[1] and (ty + i * TPB) < B.shape[0]:
sB[ty, tx] = B[ty + i * TPB, x]
# Wait until all threads finish preloading
cuda.syncthreads()
# Computes partial product on the shared memory
for j in range(TPB):
tmp += sA[ty, j] * sB[j, tx]
# Wait until all threads finish computing
cuda.syncthreads()
if y < C.shape[0] and x < C.shape[1]:
C[y, x] = tmp
Universal functions (ufuncs)#
NumPy ufuncs such as np.sin can be called directly inside a kernel:
import numpy as np
from numba import cuda
# A kernel calling a ufunc (sin, in this case)
@cuda.jit
def f(r, x):
# Compute sin(x) with result written to r
np.sin(x, r)
# Declare input and output arrays
x = (
np.arange(10, dtype=np.float64) - 5
) #: TODO(HIP): precision issue for np.float32
r = np.zeros_like(x)
# Launch kernel that calls the ufunc
f[1, 1](r, x)
# A quick sanity check demonstrating equality of the sine computed by
# the sin ufunc inside the kernel, and NumPy's sin ufunc
np.testing.assert_allclose(r, np.sin(x))
CPU/GPU compatibility#
A function decorated with @numba.jit can be reused unchanged inside a
@cuda.jit kernel, so the same business logic runs on both CPU and GPU.
Allocate the data on the device:
X = cuda.to_device([1, 10, 234])
Y = cuda.to_device([2, 2, 4014])
Z = cuda.to_device([3, 14, 2211])
results = cuda.to_device([0.0, 0.0, 0.0])
Define plain CPU logic with @numba.jit:
@numba.jit
def business_logic(x, y, z):
return 4 * z * (2 * x - (4 * y) / 2 * pi)
The same function can be called on the host:
print(business_logic(1, 2, 3)) # -126.79644737231007
…and reused verbatim from a device kernel:
@cuda.jit
def f(res, xarr, yarr, zarr):
tid = cuda.grid(1)
if tid < len(xarr):
# The function decorated with numba.jit may be directly reused
res[tid] = business_logic(xarr[tid], yarr[tid], zarr[tid])
f.forall(len(X))(results, X, Y, Z)
print(results)
# [-126.79644737231007, 416.28324559588634, -218912930.2987788]
Foreign Function Interface (FFI)#
Numba HIP can link external device functions written in HIP/CUDA C++ into a
kernel. Declare the foreign function with cuda.declare_device and link the
source file via the link=[...] argument of @cuda.jit.
The C++ device function (note the extern "C" linkage and the
caller-provided return slot):
// Foreign function example: multiplication of a pair of floats
extern "C" __device__ int
mul_f32_f32(
float* return_value,
float x,
float y)
{
// Compute result and store in caller-provided slot
*return_value = x * y;
// Signal that no Python exception occurred
return 0;
}
Declaring and linking it from Python:
import os
import numpy as np
from numba import cuda
# Declaration of the foreign function
mul = cuda.declare_device("mul_f32_f32", "float32(float32, float32)")
# Path to the source containing the foreign function
# (here assumed to be in a subdirectory called "ffi")
basedir = os.path.dirname(os.path.abspath(__file__))
functions_cu = os.path.join(basedir, "ffi", "functions.cu")
# Kernel that links in functions.cu and calls mul
@cuda.jit(link=[functions_cu])
def multiply_vectors(r, x, y):
i = cuda.grid(1)
if i < len(r):
r[i] = mul(x[i], y[i])
# Generate random data
N = 32
np.random.seed(1)
x = np.random.rand(N).astype(np.float32)
y = np.random.rand(N).astype(np.float32)
r = np.zeros_like(x)
# Run the kernel
multiply_vectors[1, 32](r, x, y)
# Sanity check - ensure the results match those expected
np.testing.assert_array_equal(r, x * y)
Arrays can be passed to a foreign function as raw pointers using
cffi’s ffi.from_buffer. The matching C++ prototype:
extern "C"
__device__ int
sum_reduce(
float* return_value,
float* array,
int n
);
Declare the device function with a CPointer signature:
signature = "float32(CPointer(float32), int32)"
sum_reduce = cuda.declare_device("sum_reduce", signature)
…and pass the array buffer pointer from the kernel:
import cffi
ffi = cffi.FFI()
@cuda.jit(link=[functions_cu])
# @cuda.jit(link=[(functions_cu, "hip")])
# @cuda.jit(link=[(functions_cu, "hip", "-ffast-math")])
# @cuda.jit(link=[(functions_cu, "hip", ["-ffast-math"])])
def reduction_caller(result, array):
array_ptr = ffi.from_buffer(array)
result[()] = sum_reduce(array_ptr, len(array))