unigpu: GPU programming in Python, from CUDA to OpenCL
unigpu is made to teach GPU programming. Kernels are written in
Python, with exactly the API of numba-cuda.
The same code then runs on every detected platform:
| Backend | Hardware | How it works | Python package |
|---|---|---|---|
cuda |
NVIDIA GPUs | compiled by numba-cuda | numba-cuda |
hip |
AMD GPUs (ROCm) | compiled by numba-hip | numba-hip |
metal |
Apple GPUs (Mac, iPad) | translated to Metal Shading Language | pyobjc-framework-Metal (Mac), rubicon-objc or Pythonista (iPad) |
opencl |
any OpenCL device: GPU, CPU, FPGA | translated to OpenCL C 1.2 (2.0 or 3.0 for the warps) | pyopencl |
sim |
any computer | simulator in pure Python | none (NumPy only) |
The API covers the common core of these models: kernels and device functions, grid configuration, device memory, shared memory (static and dynamic), local and constant memory, synchronization of the threads of a block, atomics, streams and events. Hardware discovery follows OpenCL's model: platforms, and devices per platform.
import numpy as np
import unigpu as gpu # instead of: from numba import cuda
@gpu.jit
def addition(a, b, c):
i = gpu.grid(1) # blockIdx.x * blockDim.x + threadIdx.x
if i < c.size:
c[i] = a[i] + b[i]
a = np.random.rand(1_000_000).astype(np.float32)
d_a = gpu.to_device(a) # host → device
d_c = gpu.device_array_like(a) # allocation
addition[(a.size + 255) // 256, 256](d_a, d_a, d_c) # [blocks, threads per block]
c = d_c.copy_to_host() # device → host
Installation: three levels of equipment
unigpu is on PyPI: pip install unigpu, with the backend's option in
brackets (pip install "unigpu[cuda]"). The examples, the notebooks and the
tests are in the repository: clone it, then install that folder with
pip install -e ., with the same options (pip install -e ".[cuda]").
Step-by-step instructions for each kind of machine (Windows, macOS, Linux,
Chromebook, iPad, Google Colab): INSTALL.md.
Level 0: basic version, without a GPU. For the least equipped students, Python 3.9+ and NumPy are enough:
pip install unigpu
The simulator runs kernels on any computer (Windows, macOS, Linux,
Chromebook with Linux, iPad). The whole programming model is respected:
grid, blocks, barriers, shared memory, atomics. Kernels with barriers are
rewritten as generators: no system thread is needed, so it also runs in
Python environments based on WebAssembly (Pyodide, JupyterLite). The
simulator also detects out-of-bounds accesses and divergent barriers, and
print() and breakpoint() work inside kernels. It is slow: work on small
data.
Level 1: fast CPU through OpenCL. No GPU, but real parallelism:
pip install "unigpu[opencl-cpu]" # PyOpenCL + POCL (OpenCL on the CPU), Linux x86-64
pip distributes POCL for Linux on x86-64 only (also WSL 2). For the other systems, see INSTALL.md.
Kernels are then translated to OpenCL C, compiled and run on every core of the processor.
Level 2: GPU.
pip install "unigpu[cuda]" # NVIDIA: numba-cuda (CUDA 12)
pip install "unigpu[cuda13]" # NVIDIA, driver for CUDA 13 (Colab): numba-cuda (CUDA 13)
pip install "unigpu[hip]" # AMD, with ROCm installed: numba-hip
pip install "unigpu[opencl]" # AMD, Intel, NVIDIA: PyOpenCL + the GPU's OpenCL driver
pip install "unigpu[metal]" # Mac: PyObjC Metal
pip install "unigpu[metal-rubicon]" # iPad (or Mac): Metal through rubicon-objc, pure Python
On iPad, pip install works in the Python apps that have pip (Pyto,
a-Shell, Carnets, Code App; Pythonista through StaSh). Pythonista already
provides objc_util, which unigpu can use too: see docs/testing-ipad-colab.md.
The hip option installs numba-hip,
AMD's equivalent of numba-cuda, developed in
ROCm/hip-python. ROCm itself must
already be installed. pip takes the HIP Python bindings of the latest ROCm
release: with an older ROCm, see the installation guide of HIP Python.
numba-hip requires numba < 0.64. It does not provide atomics on arrays,
dynamic shared memory, print() in a kernel nor float16: unigpu says so
before compiling. The opencl backend, with ROCm's OpenCL runtime, supports
them on the same GPU.
Tip: Google Colab provides an NVIDIA GPU for free (Runtime → Change runtime type → GPU). Installing unigpu with the CUDA backend is then enough:
pip install "unigpu[cuda13]"(Colab already has CUDA 13).
Discover and choose the hardware
>>> import unigpu as gpu
>>> for p in gpu.get_platforms(): # like clGetPlatformIDs
... print(p.backend, p.name, [d.name for d in p.get_devices()])
opencl Portable Computing Language ['pthread-Intel(R) Xeon(R) ...']
sim unigpu simulator ['CPU simulator (Python)']
>>> gpu.list_devices(gpu.DeviceType.GPU) # like clGetDeviceIDs(..., GPU)
[]
>>> gpu.detect() # complete report (like cuda.detect())
Each device describes its characteristics in device.info: name, vendor,
type, compute units, threads per block, maximum block dimensions, shared
memory per block, global memory, float64 support.
By default, unigpu takes the best available device: a GPU, otherwise an accelerator, then a CPU, then the simulator. To choose one:
gpu.select_device("opencl") # first OpenCL device
gpu.select_device("opencl:0:1") # platform 0, device 1
gpu.select_device("cuda:1") # second CUDA GPU
gpu.select_device("sim") # simulator
gpu.select_device(gpu.DeviceType.GPU)
gpu.select_device(2) # rank in gpu.list_devices()
with gpu.gpus[1]: # temporarily (like "with cuda.gpus[1]:")
...
with gpu.device_scope(device): # the same, for a Device of gpu.list_devices()
...
The environment works too: UNIGPU_DEVICE=sim python lab1.py.
The programming model
Matching concepts
| unigpu = numba.cuda | CUDA C | OpenCL C | Metal |
|---|---|---|---|
@gpu.jit |
__global__ |
__kernel |
kernel |
@gpu.jit(device=True) |
__device__ |
function | function |
kernel[g, b, stream, nbytes](...) |
kernel<<<g, b, nbytes, stream>>> |
clEnqueueNDRangeKernel |
dispatchThreadgroups |
gpu.threadIdx.x |
threadIdx.x |
get_local_id(0) |
thread_position_in_threadgroup |
gpu.blockIdx.x |
blockIdx.x |
get_group_id(0) |
threadgroup_position_in_grid |
gpu.blockDim.x, gpu.gridDim.x |
blockDim.x, gridDim.x |
get_local_size(0), get_num_groups(0) |
threads_per_threadgroup, threadgroups_per_grid |
gpu.grid(1), gpu.gridsize(1) |
explicit computation | get_global_id(0), get_global_size(0) |
thread_position_in_grid |
gpu.shared.array(n, gpu.float32) |
__shared__ float t[n] |
__local float t[n] |
threadgroup float t[n] |
gpu.shared.array(0, gpu.float32) |
extern __shared__ |
__local argument |
[[threadgroup(0)]] |
gpu.local.array(n, gpu.int32) |
int t[n] |
int t[n] |
int t[n] |
gpu.const.array_like(TABLE) |
__constant__ |
__constant |
constant |
gpu.syncthreads() |
__syncthreads() |
barrier(...) |
threadgroup_barrier(...) |
gpu.syncwarp() |
__syncwarp() |
sub_group_barrier(...) |
simdgroup_barrier(...) |
gpu.warpsize |
warpSize |
get_max_sub_group_size() |
threads_per_simdgroup |
gpu.laneid |
index in the warp | get_sub_group_local_id() |
thread_index_in_simdgroup |
gpu.syncthreads_count(p) |
__syncthreads_count |
emulated (shared counter) | emulated (shared counter) |
gpu.atomic.add(t, i, v) |
atomicAdd(&t[i], v) |
atomic_add(&t[i], v) |
atomic_fetch_add_explicit |
stream: gpu.stream() |
cudaStream_t |
command queue | MTLCommandQueue |
gpu.event() |
cudaEvent_t |
cl_event marker |
timestamp |
| block / warp / thread | block / warp / thread | work-group / subgroup / work-item | threadgroup / SIMD-group / thread |
The primitives can also be imported on their own (from unigpu import threadIdx, shared). numba itself only accepts them as attributes of its
module (cuda.threadIdx): on CUDA and HIP, unigpu rewrites the kernel
accordingly.
Memory, launch, streams
d = gpu.to_device(a) # allocation + copy (stream=0: default stream)
d = gpu.device_array((n, m), np.float32) # allocation only; float64 by default, as in numba
d = gpu.device_array_like(a)
d.copy_to_device(a) ; h = d.copy_to_host()
d.reshape(m, n), d.ravel(), d.view(np.uint8) # views on the same memory
kernel[blocks, threads](args) # 1D; tuples for 2D and 3D
kernel[blocks, threads, stream](args) # on a stream
kernel[blocks, threads, 0, nbytes](args) # + dynamic shared memory
kernel.forall(n)(args) # grid computed for n tasks
stream = gpu.stream()
start, end = gpu.event(), gpu.event()
start.record(stream) ; kernel[g, b, stream](d) ; end.record(stream)
end.synchronize() ; print(start.elapsed_time(end), "ms")
with stream.auto_synchronize(): ...
gpu.synchronize() # launches are asynchronous
Passing a NumPy array directly to a kernel works too. It is then copied
both ways, with a UnigpuPerformanceWarning, like numba's
NumbaPerformanceWarning: an opportunity to talk about the cost of
transfers.
Signatures and options (as in numba)
@gpu.jit("void(float32[:], float32)") # declared types: scalars are converted
def scale(a, factor): ...
@gpu.jit(device=True)
def square(x): return x * x
@gpu.jit(fastmath=True) # -cl-fast-relaxed-math, fastMathEnabled...
def fast(a): ...
Atomics
gpu.atomic.add, sub, and_, or_, xor, exch, inc, dec, max,
min, nanmax, nanmin and cas work in global memory and in shared
memory. They return the old value. On OpenCL and Metal, they are available
for int32, uint32 and float32; the operations without a native
equivalent (floats, CUDA-style inc/dec) are emulated with
compare-and-swap.
Warps
A block is split into warps: groups of threads that the hardware runs
together. As in numba-cuda, gpu.warpsize and gpu.laneid (the index of the
thread in its warp) are integers, without parentheses, and gpu.syncwarp() is
a barrier for the threads of one warp. The other warps do not need to reach it:
if gpu.threadIdx.x < gpu.warpsize: # the first warp only
cache[gpu.laneid] = a[i]
gpu.syncwarp()
out[i] = cache[gpu.warpsize - 1 - gpu.laneid]
The size of a warp depends on the hardware: 32 threads on NVIDIA GPUs, 32
or 64 on AMD GPUs, other sizes elsewhere. Never write 32 in a kernel: read
gpu.warpsize. The example above also assumes that the first warp holds the
first threads of the block, which OpenCL and Metal do not guarantee.
| Backend | Warps |
|---|---|
cuda, hip, metal, sim |
available |
opencl |
only on the devices with subgroups: OpenCL 3.0 devices that announce them, OpenCL 2.x devices with cl_khr_subgroups, or devices with cl_intel_subgroups |
| numba's CUDA simulator | warpsize and laneid, but not syncwarp() |
Elsewhere, for instance with Apple's OpenCL 1.2 or POCL without subgroups, a
kernel that uses them raises a clear error before it runs. unigpu never
replaces syncwarp() by syncthreads(): if a single warp reached this barrier,
it would wait for the others forever. Use syncthreads() yourself only if every
thread of the block reaches it.
What can be written in a kernel
The accepted subset of Python is the same on every backend:
- scalar variables, typed by inference (
s = 0.0) or by annotation (acc: gpu.float32 = 0); if / elif / else,for i in range(...),while,break,continue,return,a if c else b,a, b = b, a;- arithmetic, comparison (chained too:
0 < x < n), logical and bitwise operators, with Python's semantics for//,%,/and**; - arrays:
a[i],a[i, j],a.shape,a.size,a.ndim,len(a), aliasesb = a; - the usual
mathandnumpyfunctions,min,max,abs, conversionsint(),float(),gpu.float32(),np.int32()...; - global constants of the module (
TPB = 16),print()(except on Metal and HIP).
Not accepted: lists, dictionaries, objects, exceptions, slices a[1:3],
recursion, calls of undecorated functions. The translator explains it,
giving the file and the line:
TranslationError: [lab1.py:12, in my_kernel()] slices (a[i:j]) are not supported in a kernel
Types. As in numba, a Python integer is an int64 and a Python float a
float64. The only exception is Metal, or an OpenCL device without double
precision, where a float is a float32. Thread indices and dimensions are
int32. Literals adapt: x * 2.0 stays float32 if x is. Use
np.float32 for good performance.
Debug and understand
gpu.select_device("sim") # simulator: print, pdb, IndexError
print(gpu.translate(kernel, a, b, target="metal")) # the Metal code, without a GPU
print(kernel.inspect_code(a, b)) # code for the current device (PTX on CUDA)
On the simulator, an out-of-bounds access raises an IndexError giving
threadIdx and blockIdx, where a real GPU silently corrupts memory. A
barrier placed in a branch that not every thread of the block takes raises a
DivergentBarrierError; on a real GPU, the kernel would hang or give a wrong
result. Device functions can also be called directly from Python, so they
can be unit-tested.
Examples
The examples/ folder offers a progression of lab sessions: download it
whole, examples.zip
(the scripts share common.py), or read each script from the table below.
Each one takes the device as an argument, for instance
python examples/03_matrix_multiplication.py sim:
| Script | Concepts |
|---|---|
00_discovery.py |
platforms, devices, characteristics, choice of the device |
01_vector_addition.py |
first kernel, 1D grid, transfers |
02_saxpy_grid_stride.py |
"grid-stride" loop, signature, forall, bandwidth |
03_matrix_multiplication.py |
2D grid, shared memory, tiling, timing with events |
04_reduction.py |
tree reduction, syncthreads |
05_histogram.py |
global atomics, privatization in shared memory |
06_heat_2d.py |
2D stencil, double buffering |
07_mandelbrot.py |
device function, divergence |
08_generated_code.py |
the same kernel in OpenCL C and in Metal |
09_streams_events.py |
streams, events, overlap |
10_dynamic_constant_memory.py |
dynamic shared memory, constant memory, block votes |
Examples notebook and performance measurements
notebooks/examples.ipynb goes through every
example. For each one, it shows the code, runs it, then measures it for
growing data sizes. The measurements are shown as a table, a summary and a
chart:
- duration of the kernel, measured with events;
- duration of the transfers;
- duration of the same computation with NumPy;
- speedup, with and without the transfers;
- throughput, in GB/s or in GFLOP/s.
It works on Colab (CUDA and OpenCL), on iPad (Metal, in Carnets or Juno), on a Mac or a PC, and even on the simulator, with small sizes.
The benchmarks are defined in examples/benchmarks.py,
one per example. They can also all run from the command line:
python examples/benchmarks.py [device] [--quick]. To measure your own
kernel, describe it with unigpu.benchmark.Case:
from unigpu import benchmark
case = benchmark.Case("Addition", arrays=lambda n: (a(n), b(n), np.zeros(n, np.float32)),
launch=lambda a, b, c: addition[(c.size + 255) // 256, 256](a, b, c),
reference=lambda a, b, c: a + b,
sizes=[2 ** k for k in range(10, 25, 2)], simulator_sizes=[256, 1024],
bytes_moved=lambda n: 12 * n)
results = benchmark.run(case) # or benchmark.compare(case): every device
print(benchmark.format_table(results))
benchmark.plot(results) # with matplotlib
Self-test
python -m unigpu.selftest all (or python autotest.py) checks the common
core on each detected device in a few seconds: indices, shared memory,
barriers, atomics, dynamic and constant memory, votes, streams, events and
math functions. It needs neither pytest nor any installation, which makes it
handy on iPad.
Documentation
docs/testing-ipad-colab.md: testing on iPad (Metal on the M4 GPU, simulator) and on Google Colab (NVIDIA GPU);docs/api.md: API reference, generated from the docstrings (python docs/generate_api.py);docs/architecture.md: organization of the code, SOLID/DRY principles, the rules every change follows (interfaces, unit tests, TDD), how to add a backend or a primitive.
Tests and quality
pip install -e ".[dev,opencl-cpu]"
pytest --cov=unigpu # unit + functional tests, on each detected device
ruff check .
mypy unigpu # not at zero errors yet
python tests/tools/check_clean_code.py # rules of clean code, not all followed yet
Every change follows the rules of
docs/architecture.md:
every class behind an interface, its collaborators injected, small classes
and functions (Clean Code), unit tests of each class with its
collaborators mocked, test-driven development. The same page says where
the code stands.
- The functional tests run each kernel on every detected device. The CUDA
backend is tested by default with numba's simulator
(
NUMBA_ENABLE_CUDASIM=1). On an NVIDIA machine, runUNIGPU_TEST_CUDA=real pytest. - Every kernel of the project (tests, self-test, examples, benchmarks) is
compiled to PTX by numba-cuda's real compiler, without a GPU, when
numba-cuda is installed (
tests/tools/check_cuda_ptx.py). Likewise, they are compiled to AMD GPU code objects by numba-hip and COMGR, without a GPU, where ROCm and numba-hip are installed (tests/tools/check_hip_codeobj.py, for gfx90a, gfx942, gfx1100 and gfx1201). The CI (.github/workflows/ci.yml) runs both checks, with--strict: a missing compiler is then a failure. - The generated OpenCL C code is compiled by
clang -cl-std=CL1.2 -target spir64 -Werror(CL3.0for the kernels that use the warps). The generated Metal code is compiled byclang++against a stand-in<metal_stdlib>header, which checks syntax and types without a Mac. - The Metal backend is tested with fake PyObjC and rubicon-objc/objc_util
modules, and the HIP backend with numba's simulator (
tests/fakes).
Status of the backends
| Backend | What has been checked |
|---|---|
sim |
Fully tested. |
opencl |
Fully tested on POCL (CPU). The functional tests of the kernels and of the memory, and the self-test, pass on an Apple GPU (M5 Max, OpenCL 1.2). Not tried on another GPU yet. The warps have not been tried on a device that has subgroups: there, only the code is checked, by clang. The known differences between drivers are handled (limits of a kernel read before its arguments are set, events without marker timestamps, largest buffer). |
cuda |
Tested with numba's simulator; every kernel of the project is compiled to PTX by the real numba-cuda compiler. Everything is delegated to numba-cuda, but it remains to be tried on a real NVIDIA GPU. |
hip |
Same code as cuda, with numba-hip, minus what numba-hip does not provide (atomics on arrays, dynamic shared memory, print(), float16). Every kernel of the project is compiled to AMD GPU code objects by numba-hip, without a GPU; not tried on an AMD GPU yet. |
metal |
Works on an iPad (M4) in Carnets and in Code App, through rubicon-objc. Driver logic tested with fake PyObjC and rubicon-objc/objc_util; PyObjC calls checked against its metadata; Metal code syntax checked by clang++. On a Mac (M5 Max), through PyObjC, the functional tests of the kernels (warps included) and of the memory, and the self-test, pass. |
Test reports on real hardware are welcome.
Note: according to its README, numba-cuda is now in "maintenance mode"; NVIDIA directs new developments to numba-cuda-mlir. The kernel API, which unigpu reproduces, stays the same.
License
unigpu is distributed under the MIT license: anyone may use, copy, modify and redistribute it, provided that the copyright notice and the license are kept.
Metadata
Release files for unigpu 0.4.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| unigpu-0.4.0.tar.gz | 148.3 kB | With provenance | Details for unigpu-0.4.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| unigpu-0.4.0-py3-none-any.whl | Python 3 | none | any | Details for unigpu-0.4.0-py3-none-any.whl |
Total release size: 336.0 kB
Release files / unigpu-0.4.0.tar.gz
| Download URL | unigpu-0.4.0.tar.gz |
|---|---|
| Size | 148.3 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
414f1d536c77e4de4b3ac3149338d01a798d7ec4a1f7bc514474fc749cad3150
|
|
BLAKE2b-256 checksum How to use checksums |
bdd0ccb365a26f4beed084d3c9fbc9053616a9d32931f9bb29f9063c232065f3
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 29, 2026.
Transparency logRelease files / unigpu-0.4.0-py3-none-any.whl
| Download URL | unigpu-0.4.0-py3-none-any.whl |
|---|---|
| Size | 187.7 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
e7aca091422dadd5c808282ffedcfcaf1f68e0c418f102918c7842c0a3fa9daa
|
|
BLAKE2b-256 checksum How to use checksums |
4dd2f353b850c5efa0e30c675d33330141a8e991e8c1d2a423a939e6da259323
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 29, 2026.
Transparency logSecurity for unigpu 0.4.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for unigpu-0.4.0.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 29, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.