PyOpenCL

2026.1.2 · active · verified Thu Apr 16

PyOpenCL is a Python wrapper for OpenCL, providing access to GPUs, CPUs, and other parallel compute devices for high-performance computing. It offers a Pythonic, object-oriented interface, integrates seamlessly with NumPy, and includes automatic error checking. The library is actively maintained with frequent releases, and its current version is 2026.1.2.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates a basic PyOpenCL workflow: creating an OpenCL context and command queue, preparing data on the host (NumPy array), transferring it to the device, compiling and executing a simple OpenCL kernel (doubling array elements), and transferring results back to the host.

import pyopencl as cl
import numpy as np

def run_opencl_kernel():
    # 1. Create a context
    try:
        ctx = cl.create_some_context()
    except cl.LogicError as e:
        print(f"Error creating OpenCL context: {e}")
        print("Please ensure you have OpenCL drivers/ICD installed.")
        return

    # 2. Create a command queue
    queue = cl.CommandQueue(ctx)

    # 3. Prepare host data
    a = np.random.rand(50000).astype(np.float32)

    # 4. Create device buffers and transfer data
    mf = cl.mem_flags
    a_buf = cl.Buffer(ctx, mf.READ_WRITE | mf.COPY_HOST_PTR, hostbuf=a)

    # 5. Define and build the OpenCL kernel program
    prg = cl.Program(ctx, """
    __kernel void twice(__global float *a) {
        int gid = get_global_id(0);
        a[gid] = 2*a[gid];
    }
    """).build()

    # 6. Execute the kernel
    # global_size is the total number of work-items
    # local_size (None) lets the OpenCL driver decide
    prg.twice(queue, a.shape, None, a_buf)

    # 7. Create output array and transfer data back to host
    result = np.empty_like(a)
    cl.enqueue_copy(queue, result, a_buf).wait()

    # 8. Verify the result
    print("Original first 5 elements:", a[:5])
    print("Resulting first 5 elements:", result[:5])
    assert np.allclose(result, 2*a)
    print("Kernel executed successfully and results verified!")

if __name__ == '__main__':
    run_opencl_kernel()

view raw JSON →