OpenCL host–device interaction and execution model
OpenCL host–device interaction and execution model: how the CPU (host) prepares, launches and coordinates kernels running on compute devices, and how work-items and work-groups map to NDRange execution.
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
GPUs and other accelerators run kernels that do heavy computation. The host (your CPU program) is responsible for preparing data, compiling kernels, launching work, and copying results back. Understanding the host–device interaction and OpenCL's execution model is essential for writing correct, efficient heterogeneous programs and for debugging performance or correctness problems.
Key ideas
Define terms before use: first time each term appears it is bold and defined.
- Host: the CPU program that controls OpenCL; it sets up the execution environment, moves data, and launches kernels.
- Device: a computing unit (GPU, CPU, FPGA) that executes OpenCL kernels.
- Context: an OpenCL object that represents an environment connecting one or more devices and the resources (memory objects, program objects) used by kernels on those devices.
- Command queue: a queue associated with a specific device; commands are enqueued by the host. By default it is in-order, but it can be created out-of-order with properties.
- Kernel: a function written in OpenCL C that runs on a device; a kernel executes across many parallel instances called work-items.
- Work-item: the OpenCL term for a single instance of a kernel execution; it has an identity (IDs) and executes the kernel code for a particular element of data.
- Work-group: a collection of work-items that execute on the same compute unit and can synchronize with each other using barriers and share fast local memory.
- NDRange: the N-dimensional index space of work-items launched for a kernel; e.g., a 2D NDRange with sizes (global_size_x, global_size_y). Optionally a global_work_offset per dimension shifts the starting indices; get_global_offset(d) is added to get_global_id(d).
- Global work size: the number of work-items in each NDRange dimension; also called global_size.
- Local work size: the number of work-items per work-group in each dimension; also called local_size or work-group size.
- Event: an OpenCL object used to track the completion of operations and to synchronize commands between host and device or between commands.
- Buffer (memory object): a block of memory allocated by the OpenCL implementation within a context that kernels use to read/write data; host access is via map/read/write APIs. Flags control allocation behavior and host-pointer usage (e.g., CL_MEM_USE_HOST_PTR, CL_MEM_COPY_HOST_PTR).
- Enqueue: the host operation of putting a command (buffer write/read, kernel launch) into a command queue.
- Blocking and non-blocking: whether an enqueue call waits (blocks) until the operation completes or returns immediately (non-blocking) while operation proceeds asynchronously.
- Barrier: in-kernel synchronization primitive used by work-items within the same work-group to wait until all reach the barrier and optionally ensure memory visibility.
Exact statements the exam expects (form-like definitions):
Definition (NDRange execution model): "A kernel is executed as an NDRange of work-items. Each work-item has a unique global id in each dimension given by get_global_id(dim). Work-items are partitioned into work-groups of size equal to the local work size; each work-group has a unique group id given by get_group_id(dim), and each work-item has a local id within its group given by get_local_id(dim)."
Relation between sizes (assumption: global size is an integer multiple of local size): "For each dimension d: global_size[d] = num_groups[d] * local_size[d], where num_groups[d] is the number of work-groups along dimension d. OpenCL requires that either local_size is NULL (implementation decides) or that global_size is divisible by local_size."
Host–device sequence (common exam answer): draw a vertical sequence diagram with two lifelines: Host and Device. Steps to label top-to-bottom: select Platform/Device, create Context, create Command Queue, create Buffers, write host data to Buffers (clEnqueueWriteBuffer or map), create Program from source and build, create Kernel and set arguments, enqueue NDRange kernel, optionally enqueue reads to retrieve data (clEnqueueReadBuffer), release objects. Mark that kernel launch and read can be synchronized with Events or clFinish.
Diagram to draw for a 2D NDRange (what to draw and label): draw a rectangle for the NDRange with width = global_size_x and height = global_size_y. Subdivide into tiles representing work-groups of size local_size_x × local_size_y. Inside one tile, draw small cells and label them with local ids (0..local_size_x-1 horizontally, 0..local_size_y-1 vertically). Label the global id of one cell and show the formula relating it to group id and local id.
Derivation universities ask for (index mapping): show that for dimension 0: get_global_id(0) = get_group_id(0) * local_size(0) + get_local_id(0). Extend to N dimensions similarly. For flattening 2D to 1D, show formula below in Formulas.
Assumptions to state in answers:
- Device may have limits: maximum work-group size, maximum work-item-dimensions and sizes; these are queried via device info (e.g., CL_DEVICE_MAX_WORK_GROUP_SIZE). Always check these before picking local_size.
- Some devices prefer local_size chosen to be a multiple of a hardware wavefront/warp size for better performance.
Formulas
global_size[d] = num_groups[d] * local_size[d] — global_size[d]: number of work-items in dimension d (unit: count), local_size[d]: work-items per work-group in d (count), num_groups[d]: count of work-groups in d (count). Applies when local_size is specified.
get_global_id(d) = get_global_offset(d) + get_group_id(d) * local_size[d] + get_local_id(d) — relationship between ids including optional global_work_offset (use 0 if NULL); all are dimensionless integer counts.
For 2D to 1D flattening (row-major, x fastest):
linear_idx = gidx + global_size_x * gidy. For 3D generalization: linear_idx = gidx + global_size_x * (gidy + global_size_y * gidz). Here gidx = get_global_id(0), gidy = get_global_id(1), gidz = get_global_id(2). Units: dimensionless index.
Key OpenCL host syntax to remember (common functions; prototype details skipped):
clGetPlatformIDs, clGetDeviceIDs, clCreateContext, clCreateCommandQueue (or clCreateCommandQueueWithProperties), clCreateProgramWithSource, clBuildProgram, clCreateKernel, clCreateBuffer, clEnqueueWriteBuffer, clEnqueueReadBuffer, clSetKernelArg, clEnqueueNDRangeKernel, clFinish, clRelease*.
Worked examples
Example 1 — Small complete OpenCL host program (vector add). Save as vector_add.c, compile with: gcc vector_add.c -o vector_add -lOpenCL.
#include <stdio.h>
#include <stdlib.h>
#include <CL/cl.h>
const char* kernel_src =
"__kernel void vadd(__global const int* A, __global const int* B, __global int* C, const int N) {\n"
" int i = get_global_id(0);\n"
" if (i < N) C[i] = A[i] + B[i];\n"
"}\n";
int main() {
const int N = 8;
int A[N], B[N], C[N];
for (int i = 0; i < N; ++i) { A[i] = i; B[i] = 10 + i; }
cl_int err;
cl_platform_id platform;
cl_device_id device;
clGetPlatformIDs(1, &platform, NULL);
clGetDeviceIDs(platform, CL_DEVICE_TYPE_DEFAULT, 1, &device, NULL);
cl_context context = clCreateContext(NULL, 1, &device, NULL, NULL, &err);
cl_command_queue queue = clCreateCommandQueue(context, device, 0, &err);
cl_program program = clCreateProgramWithSource(context, 1, &kernel_src, NULL, &err);
err = clBuildProgram(program, 1, &device, NULL, NULL, NULL);
cl_kernel kernel = clCreateKernel(program, "vadd", &err);
cl_mem bufA = clCreateBuffer(context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, sizeof(int)*N, A, &err);
cl_mem bufB = clCreateBuffer(context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, sizeof(int)*N, B, &err);
cl_mem bufC = clCreateBuffer(context, CL_MEM_WRITE_ONLY, sizeof(int)*N, NULL, &err);
err = clSetKernelArg(kernel, 0, sizeof(cl_mem), &bufA);
err |= clSetKernelArg(kernel, 1, sizeof(cl_mem), &bufB);
err |= clSetKernelArg(kernel, 2, sizeof(cl_mem), &bufC);
err |= clSetKernelArg(kernel, 3, sizeof(int), &N);
size_t global = N;
size_t local = 4; // must divide global or set NULL
err = clEnqueueNDRangeKernel(queue, kernel, 1, NULL, &global, &local, 0, NULL, NULL);
clFinish(queue);
clEnqueueReadBuffer(queue, bufC, CL_TRUE, 0, sizeof(int)*N, C, 0, NULL, NULL);
printf("Result:\n");
for (int i = 0; i < N; ++i) printf("C[%d] = %d\n", i, C[i]);
clReleaseMemObject(bufA); clReleaseMemObject(bufB); clReleaseMemObject(bufC);
clReleaseKernel(kernel); clReleaseProgram(program); clReleaseCommandQueue(queue); clReleaseContext(context);
return 0;
}
Sample input: none (program initializes arrays). Exact output when run:
Result: C[0] = 10 C[1] = 12 C[2] = 14 C[3] = 16 C[4] = 18 C[5] = 20 C[6] = 22 C[7] = 24
(Each line printed exactly as above.)
Example 2 — Calculation question (2D mapping).
Given: global_size = (16, 8), local_size = (4, 2). Compute num_groups and total groups, and show mapping of global id for group (g=2, h=1) local (l=3, m=0).
- num_groups_x = 16/4 = 4, num_groups_y = 8/2 = 4. Total groups = 4*4 = 16.
- For group with get_group_id(0)=2 and get_group_id(1)=1 and local id get_local_id(0)=3, get_local_id(1)=0: get_global_id(0) = 24 + 3 = 11 get_global_id(1) = 12 + 0 = 2 If flattening row-major with x fastest: linear_idx = 11 + 16*(2) = 11 + 32 = 43. Answer: total groups 16; global id = (11,2); linear index = 43.
Common mistakes
- Forgetting clFinish or using blocking reads when required: reading a buffer before kernel completes returns old data.
- Mismatch of host and kernel types/sizes (e.g., using float on host but int in kernel) or wrong buffer sizes (bytes) in clCreateBuffer/copy calls.
- Assuming all devices have the same preferred local sizes or memory sizes without querying device info.
- Using in-kernel barriers across entire NDRange (not allowed): barrier() synchronizes only within a work-group.
For your exam
Question types you will see: definitions (state what an NDRange or work-group is), short notes (describe host–device sequence), derivations (derive mapping formula from group and local ids), diagrams (draw NDRange with work-groups and ids), numerical problems (compute number of work-groups and linear indices), and short programming fragments (explain what a kernel with certain get_global_id calls computes). A full-marks answer includes:
- Clear definitions with bold names or labelled diagram.
- Sequence of host steps in correct order and mention of synchronization points (clFinish, events).
- Correct formulas and a numerical example showing each step.
- For code questions: correct calling sequence of major OpenCL functions and identification of potential errors (build logs, device limits).
Quick check
- What does get_local_id(0) return?
- If global_size_x = 1024 and local_size_x = 64, how many work-groups along x?
- Which OpenCL call compiles a kernel source into a program object on the device?
Answers: get_local_id(0) returns the work-item's local index within its work-group along dimension 0; 1024/64 = 16 work-groups along x; clBuildProgram compiles the program for the device (after clCreateProgramWithSource).
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?