Computer Engineering is coming soon

We're still writing and reviewing the notes for every subject, and we'll open it when every subject is ready. Meanwhile you can practise aptitude, ask Aria about any subject, or see the branches that are ready.

OpenCL for heterogeneous computing

OpenCL is a portable standard for writing kernels that run on heterogeneous devices (CPUs, GPUs, accelerators) using an explicit host–device model, command queues, and an NDRange execution model.

Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.

Why it matters

OpenCL is used by engineers to run heavy computations on the fastest device available (GPU, CPU, FPGA) while keeping one portable program. When you need to accelerate numerical code or run the same code on different hardware (GPU or CPU), OpenCL provides the API and kernel language to do that.

Key ideas

Start with plain definitions (I will bold each term when I define it).

  • Platform: the implementation of OpenCL by a vendor (for example, an NVIDIA or AMD runtime). A platform provides one or more devices.
  • Device: a physical compute device (for example, a GPU or CPU) capable of running OpenCL kernels.
  • Context: an object that groups one or more devices and manages memory objects and program objects shared among those devices.
  • Command queue: a queue on the host where commands (kernel execution, memory transfers) are submitted to a specific device in a context.
  • Kernel: a function written in OpenCL C that runs on a device. It executes in parallel across many work-items.
  • Work-item: the basic execution unit on a device. A work-item runs one instance of the kernel.
  • Work-group: a group of work-items that execute on the same compute unit and can share local memory and synchronize using barriers.
  • NDRange: the N-dimensional index space of work-items for a kernel launch; defined by global size and optional local (work-group) size; an optional global offset shifts the starting indices.
  • Memory object (buffer or image): data storage created in the context that can be read/written by kernels and host code. In kernel code, address spaces are annotated as __global, __local, __constant, or __private.
  • Program: a compiled set of kernels (created from source or binary) for devices in a context.

Execution model (step-by-step, what you draw and label):

  • Draw a box labelled "Host (CPU)" on the left and a box labelled "Device (GPU)" on the right. Inside Host, draw blocks: Platform -> Context -> Command Queue -> Program build calls. Draw an arrow from Host to Device labelled "Command queue: enqueue kernel, enqueue write/read buffer". Inside Device, draw many small boxes labelled "Compute Units"; inside them draw groups of boxes labelled "Work-groups"; inside those, tiny boxes labelled "Work-items". Label memory spaces: Host RAM outside device; Device memory (global), per-work-group local memory, per-work-item private memory, and constant memory.

Precise definitions universities expect (concise):

  • A kernel is defined as a function with qualifier __kernel and may use memory address qualifiers __global, __local, __constant, or __private. Example signature: __kernel void foo(__global float* A).
  • Global work size = total number of work-items launched. Local work size = number of work-items per work-group. If local is not provided, OpenCL runtime chooses a work-group size subject to device limits.
  • get_global_id(dim) returns the work-item index within the global NDRange for dimension dim; if global_work_offset is NULL or zero this is 0-based, otherwise it is offset by global_work_offset[dim].

Host-device interaction (typical sequence, step-by-step):

  1. Query available platforms with clGetPlatformIDs. Pick a platform.
  2. Query devices for that platform with clGetDeviceIDs. Pick a device (e.g., GPU or CPU).
  3. Create a cl_context for chosen device(s). (This groups memory and programs.)
  4. Create a cl_command_queue on the context for a chosen device. (Commands submitted here go to that device.)
  5. Create device memory with clCreateBuffer or images.
  6. Create a cl_program from source (or binary), then compile with clBuildProgram for the device(s).
  7. Create kernels from the program using clCreateKernel.
  8. Set kernel arguments with clSetKernelArg (pass buffers and scalars).
  9. Transfer data host->device with commands like clEnqueueWriteBuffer (or use mapping APIs).
  10. Launch kernels with clEnqueueNDRangeKernel providing global and local sizes.
  11. Read back results with clEnqueueReadBuffer (use blocking read with CL_TRUE, or use CL_FALSE and then clFinish/clWaitForEvents to ensure completion).
  12. Release OpenCL objects.

Memory model (definitions):

  • __global: device global memory accessible to all work-items; the host can access the contents only via OpenCL API commands (not by directly dereferencing device pointers).
  • __local: memory shared among work-items in the same work-group (fast, limited size).
  • __private: per-work-item registers or private variables.
  • __constant: read-only memory visible to all work-items, may be cached.

How OpenCL maps to familiar CUDA terms (short):

  • OpenCL work-item ≈ CUDA thread. OpenCL work-group ≈ CUDA block. OpenCL get_global_id(0) ≈ threadIdx.x + blockIdx.x * blockDim.x. OpenCL __local memory ≈ CUDA shared memory. Refer to CUDA threads, blocks, grids and warps topic for more details.

Portability and performance notes:

  • OpenCL gives portability across devices, but performance-tuning (local sizes, memory use, vector types) must be device-specific.
  • Synchronization is only possible within a work-group in kernel code using barrier() with appropriate memory fence flags (e.g., CLK_LOCAL_MEM_FENCE, CLK_GLOBAL_MEM_FENCE). There is no global barrier across all work-items in a single kernel invocation.

Formulas

For this programming topic, remember these API and kernel syntaxes (each on its own line): clGetPlatformIDs(cl_uint, cl_platform_id*, cl_uint*) — query platforms clGetDeviceIDs(cl_platform_id, cl_device_type, cl_uint, cl_device_id*, cl_uint*) — query devices clCreateContext(properties, cl_uint, cl_device_id*, pfn_notify, void*, cl_int*) — create context clCreateCommandQueue(context, device, cl_command_queue_properties, cl_int*) — create command queue (OpenCL 1.2) clCreateCommandQueueWithProperties(context, device, const cl_queue_properties*, cl_int*) — create command queue (OpenCL 2.0+, replaces clCreateCommandQueue) clCreateBuffer(context, flags, size_t size, void* host_ptr, cl_int*) — create buffer clCreateProgramWithSource(context, count, const char**, const size_t*, cl_int*) — create program clBuildProgram(cl_program, cl_uint, const cl_device_id*, const char*, void (*pfn_notify)(cl_program, void*), void*) — build program clGetProgramBuildInfo(cl_program, cl_device_id, cl_program_build_info, size_t, void*, size_t*) — query build status/log clCreateKernel(cl_program, const char* kernel_name, cl_int*) — create kernel clSetKernelArg(cl_kernel, cl_uint, size_t, const void*) — set kernel argument clEnqueueWriteBuffer(cl_command_queue, cl_mem, cl_bool, size_t, size_t, const void*, cl_uint, const cl_event*, cl_event*) — copy host->device clEnqueueNDRangeKernel(cl_command_queue, cl_kernel, cl_uint work_dim, const size_t* global_work_offset, const size_t* global_work_size, const size_t* local_work_size, cl_uint, const cl_event*, cl_event*) — launch kernel clEnqueueReadBuffer(cl_command_queue, cl_mem, cl_bool, size_t, size_t, void*, cl_uint, const cl_event*, cl_event*) — copy device->host Kernel signature example: __kernel void vecAdd(__global const float* A, __global const float* B, __global float* C, unsigned int n)

Worked examples

Example 1 — Vector addition (host C code + OpenCL kernel). This program adds two length-8 float vectors and prints the result.

Host code (C, minimal error checking removed for brevity; include <CL/cl.h>):

// vector_add.c
#include <stdio.h>
#include <stdlib.h>
#include <CL/cl.h>

const char* src = "__kernel void vecAdd(__global const float* A, __global const float* B, __global float* C, unsigned int n) {"
                  " size_t id = get_global_id(0);"
                  " if (id < n) C[id] = A[id] + B[id];"
                  " }";

int main() {
    const unsigned int n = 8;
    float A[8], B[8], C[8];
    for (unsigned int i = 0; i < n; ++i) { A[i] = (float)i; B[i] = (float)(2*i); }

    cl_platform_id plat; cl_device_id dev; clGetPlatformIDs(1, &plat, NULL); clGetDeviceIDs(plat, CL_DEVICE_TYPE_DEFAULT, 1, &dev, NULL);
    cl_context ctx = clCreateContext(NULL, 1, &dev, NULL, NULL, NULL);
    cl_command_queue q = clCreateCommandQueue(ctx, dev, 0, NULL);

    cl_mem bufA = clCreateBuffer(ctx, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, sizeof(A), A, NULL);
    cl_mem bufB = clCreateBuffer(ctx, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, sizeof(B), B, NULL);
    cl_mem bufC = clCreateBuffer(ctx, CL_MEM_WRITE_ONLY, sizeof(C), NULL, NULL);

    cl_program p = clCreateProgramWithSource(ctx, 1, &src, NULL, NULL);
    clBuildProgram(p, 1, &dev, NULL, NULL, NULL);
    cl_kernel k = clCreateKernel(p, "vecAdd", NULL);

    clSetKernelArg(k, 0, sizeof(cl_mem), &bufA);
    clSetKernelArg(k, 1, sizeof(cl_mem), &bufB);
    clSetKernelArg(k, 2, sizeof(cl_mem), &bufC);
    clSetKernelArg(k, 3, sizeof(unsigned int), &n);

    size_t global = n;
    clEnqueueNDRangeKernel(q, k, 1, NULL, &global, NULL, 0, NULL, NULL);
    clFinish(q);

    clEnqueueReadBuffer(q, bufC, CL_TRUE, 0, sizeof(C), C, 0, NULL, NULL);

    printf("Result:");
    for (unsigned int i = 0; i < n; ++i) printf(" %f", C[i]);
    printf("\n");

    clReleaseMemObject(bufA); clReleaseMemObject(bufB); clReleaseMemObject(bufC);
    clReleaseKernel(k); clReleaseProgram(p); clReleaseCommandQueue(q); clReleaseContext(ctx);
    return 0;
}

Compile (example): gcc vector_add.c -lOpenCL -o vector_add Run sample output (exact):

Result: 0.000000 3.000000 6.000000 9.000000 12.000000 15.000000 18.000000 21.000000

(Explanation: A[i] = i, B[i] = 2i, so C[i] = 3i.)

Example 2 — 2x2 matrix multiplication (naive kernel). This shows a 2D NDRange and index mapping.

Kernel source embedded in host:

// matmul.c (naive)
#include <stdio.h>
#include <CL/cl.h>

const char* src = "__kernel void matmul(__global const float* A, __global const float* B, __global float* C, unsigned int M, unsigned int N, unsigned int P) {"
                  " int row = get_global_id(0); int col = get_global_id(1);"
                  " if (row < M && col < P) { float sum = 0.0f; for (int k = 0; k < N; ++k) sum += A[row*N + k] * B[k*P + col]; C[row*P + col] = sum; }"
                  " }";

int main() {
    const unsigned int M = 2, N = 2, P = 2;
    float A[4] = {1,2,3,4}; // row-major: [ [1,2], [3,4] ]
    float B[4] = {5,6,7,8}; // [ [5,6], [7,8] ]
    float C[4] = {0};

    cl_platform_id plat; cl_device_id dev; clGetPlatformIDs(1, &plat, NULL); clGetDeviceIDs(plat, CL_DEVICE_TYPE_DEFAULT, 1, &dev, NULL);
    cl_context ctx = clCreateContext(NULL, 1, &dev, NULL, NULL, NULL);
    cl_command_queue q = clCreateCommandQueue(ctx, dev, 0, NULL);

    cl_mem bufA = clCreateBuffer(ctx, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, sizeof(A), A, NULL);
    cl_mem bufB = clCreateBuffer(ctx, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, sizeof(B), B, NULL);
    cl_mem bufC = clCreateBuffer(ctx, CL_MEM_WRITE_ONLY, sizeof(C), NULL, NULL);

    cl_program p = clCreateProgramWithSource(ctx, 1, &src, NULL, NULL);
    clBuildProgram(p, 1, &dev, NULL, NULL, NULL);
    cl_kernel k = clCreateKernel(p, "matmul", NULL);

    clSetKernelArg(k, 0, sizeof(cl_mem), &bufA);
    clSetKernelArg(k, 1, sizeof(cl_mem), &bufB);
    clSetKernelArg(k, 2, sizeof(cl_mem), &bufC);
    clSetKernelArg(k, 3, sizeof(unsigned int), &M);
    clSetKernelArg(k, 4, sizeof(unsigned int), &N);
    clSetKernelArg(k, 5, sizeof(unsigned int), &P);

    size_t global[2] = {M, P};
    clEnqueueNDRangeKernel(q, k, 2, NULL, global, NULL, 0, NULL, NULL);
    clFinish(q);

    clEnqueueReadBuffer(q, bufC, CL_TRUE, 0, sizeof(C), C, 0, NULL, NULL);

    printf("C = [ %f %f ; %f %f ]\n", C[0], C[1], C[2], C[3]);

    clReleaseMemObject(bufA); clReleaseMemObject(bufB); clReleaseMemObject(bufC);
    clReleaseKernel(k); clReleaseProgram(p); clReleaseCommandQueue(q); clReleaseContext(ctx);
    return 0;
}

Exact output when run:

C = [ 19.000000 22.000000 ; 43.000000 50.000000 ]

(Explanation: result computed by standard matrix multiplication.)

Common mistakes

  • Using clCreateCommandQueue vs clCreateCommandQueueWithProperties: their availability depends on OpenCL version. Know your target OpenCL version.
  • Assuming a global barrier is available inside kernel: only barrier() works inside the work-group, not across work-groups.
  • Passing host pointers directly to a kernel expecting device pointers: always pass cl_mem objects via clSetKernelArg.
  • Not releasing OpenCL resources (leaking cl_mem, kernels, programs, queues, contexts).

For your exam

Question types you will see:

  • Definitions and short-answer: define platform, device, context, kernel, work-item, work-group, NDRange.
  • Diagram question: draw the host–device interaction and label memory spaces and command queue flow.
  • Derivation/explanation: explain how get_global_id maps to 1D/2D indices; explain host sequence to run a kernel (list API calls/steps).
  • Programming task: write a simple OpenCL kernel and host calls (vector add, matrix multiply). Include correct kernel signature, memory qualifiers, and NDRange launch.
  • Debugging: Given a failing build, show how to retrieve and interpret the compiler build log.

What full-marks answers include:

  • Clear definitions with bold term names; correct API call order; correct mapping between NDRange, global and local sizes; for code questions, correct kernel signature and correct host calls in the sequence: create context → create queue → create buffers → build program → create kernel → set args → enqueue write → enqueue kernel → enqueue read → finish → release objects.

Quick check

  1. What OpenCL qualifier lets work-items in the same work-group share memory?
  2. Which host function launches an OpenCL kernel?
  3. How do you obtain a work-item's global index in dimension 0?

Answers: 1) __local. 2) clEnqueueNDRangeKernel. 3) get_global_id(0).

Finished this topic? Mark it so your progress, study plan and readiness keep up.

Stuck on something here?