
Recall first from Choosing a library and benchmarking
- Operation coverage depends on the image format, parameters, and execution backend.
- A shared allocation can still require explicit synchronization, and an incompatible layout can require a copy.
- An asynchronous submission can return before the output is ready.
The objects behind a dispatch
3 min readYou have used NVIDIA-only libraries. Now you write portable compute, and this lesson answers what objects make up OpenCL and how its kernel language looks.
A Linux application can allocate sample data with malloc() or access data through an mmap() mapping. Both give the host application addresses it can use. When the application wants to process those samples with a buffer-based OpenCL kernel, it supplies OpenCL memory objects as the buffer arguments. That distinction matters when reading an example. The buffer handle in the host code and the pointer in the kernel declaration describe access to the same OpenCL buffer from different sides of the interface. See malloc(3) and mmap(2) for the host operations.
| OpenCL object | Host handle type | What it represents |
|---|---|---|
| Platform | cl_platform_id |
An OpenCL implementation that exposes devices to the host. |
| Device | cl_device_id |
A compute target exposed by the platform, such as a CPU, GPU or accelerator. |
| Context | cl_context |
A set of selected devices from one platform and the scope for sharing OpenCL resources among them. |
| Command queue | cl_command_queue |
The object through which the host submits commands for one device in the context. |
| Program | cl_program |
A container for kernel code and its build state for the associated devices. |
| Kernel | cl_kernel |
One named entry point from a program, together with the argument settings used for submission. |
| Memory object | cl_mem |
Data storage managed by OpenCL. A buffer provides a linear range of bytes. |
Suppose a host application selects one device for sample processing. It creates a context containing that device and a command queue for it. The context gives the program, queue and buffers a common scope. If the application later creates a context with two devices from the same platform, each queue still targets one device. To submit compute work to the second device, the host uses a queue for that device and needs an executable for it in the program.
A program can contain several __kernel functions. For example, sample addition and sample scaling could live in one source file and be built into one program. The host creates separate kernel objects by choosing their entry point names. It can also submit the same kernel object again with updated argument settings. For instance, it can keep the same addition entry point and give it a new pair of input buffers for the next batch.
For a single batch, imagine an in-order queue with commands to write two input buffers, execute the addition kernel, and read the output buffer. The dispatch uses the arguments and index range supplied at submission. Once the read has completed successfully, the host can inspect the result. The program object describes the available code, the kernel object identifies the operation and its argument settings, and each dispatch is a command submitted through the queue.
Writing an OpenCL C kernel
2 min readSave the following device source as add_samples.cl when you want to keep it in its own file. The code block contains OpenCL C device source. An OpenCL compiler builds it for the selected device. In this example, the host arranges three buffers with room for at least count elements each, initializes the input buffers and supplies the element count as a scalar argument.
__kernel void add_samples(__global const float *left,
__global const float *right,
__global float *out,
uint count)
{
const size_t index = get_global_id(0);
if (index >= count)
return;
out[index] = left[index] + right[index];
}
__kernel marks a function that the host can select as a kernel entry point. The function returns void. Each work-item that reaches the assignment writes its result to out. The three pointer parameters are qualified with __global, which identifies the OpenCL address space used for these buffers. The const qualifiers declare that this function reads through left and right. The scalar count gives each work-item the same logical length. OpenCL C uint is an unsigned 32-bit type, and get_global_id() returns size_t.
The arguments have an ordered meaning. In the host's zero-based argument list, arguments 0 and 1 are the input buffer handles, argument 2 is the output buffer handle, and argument 3 is the scalar length. A cl_uint on the host matches the kernel's uint. Swapping the length with a buffer argument breaks the interface. Swapping the two input buffers in this addition example preserves the result, though their order would matter if the operation were subtraction.
Use a one-dimensional dispatch with global offset zero for this function. If there are ten elements and the host requests sixteen work-items, IDs 0 through 9 each add one pair of values. IDs 10 through 15 return before accessing an array. Those numbers describe the dispatch requested in the example. The same function can handle a dispatch of exactly ten work-items when the chosen launch configuration permits it.
The guard checks the index against the logical element count. The host must still supply buffers large enough for that count and launch enough work-items to produce all the requested results. If the host supplies count = 10 but launches only eight work-items at offset zero, indices 8 and 9 have no work-item to write them. If it supplies a buffer holding eight floats and launches sixteen work-items with count = 10, IDs 8 and 9 pass the guard and would access beyond that buffer. The kernel's bounds check and the host's buffer sizes must agree.
Reading the dispatch coordinates
3 min readThe host submits an index space called an ND-range. Each point in that space corresponds to a work-item, which executes the kernel with its own coordinates. A work-group is a collection of work-items in a region of that space. The host specifies the number of dimensions and the global extent along each active axis. It can request a supported local size to specify the group shape, or let the implementation select a local size.
Three built-in functions let the kernel query the dispatch geometry:
| OpenCL C expression | What it returns |
|---|---|
get_work_dim() |
The number of dimensions specified for the dispatch, from 1 to 3. |
get_global_id(0) |
This work-item's coordinate on axis 0 across the dispatch. |
get_local_id(0) |
This work-item's zero-based coordinate on axis 0 within its own work-group. |
For example, request sixteen work-items at global offset zero, with a supported local size of four. The first group contains global IDs 0 through 3, the second 4 through 7, the third 8 through 11 and the fourth 12 through 15. Local IDs run from 0 through 3 in every group. The work-item with global ID 6 has local ID 2. The work-item with global ID 10 also has local ID 2. Both report get_work_dim() as 1.
If add_samples used get_local_id(0) as its buffer index with that launch, every group would target indices 0 through 3. Multiple work-items would write each of those positions, and indices 4 through 9 would have no writer. With get_global_id(0), each work-item in the example gets a distinct candidate index. The guard then selects the indices that belong to the data.
For a two-dimensional dispatch at zero offset, get_global_id(0) and get_global_id(1) can supply a column and a row. In a tightly packed row-major array with logical width width, the element index is row * width + column. When the dispatch extends beyond the logical rectangle, check the column against width and the row against height before indexing. A work-item at column 3 and row 2 in an array six elements wide would use index 15. get_work_dim() reports 2 for that dispatch even if its second axis has an extent of one. The returned value describes how the host declared the range.
Consider which coordinates would still identify the same input samples if the host changed the local size while keeping the same global range. The next lesson, Work-groups and the OpenCL memory model, uses group membership to explain where work-items can share data and coordinate memory accesses.
Key takeaways
- A platform exposes devices, a context groups selected devices, and each command queue targets one device in its context.
- A program supplies code for one or more entry points, and a kernel object selects one entry point and holds its argument settings.
- The host supplies buffer handles as arguments, and the kernel receives pointers it can use to access the buffer elements.
- A global ID identifies a coordinate across a dispatch, while a local ID identifies a coordinate within a work-group.
Reflect
- Explain to a colleague, in two sentences: identify the seven OpenCL objects used in a buffer-based dispatch.
- Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
- What surprised you when you ran the commands yourself?
On a real board
Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.
References and further reading
- Man pagemalloc(3): allocate and free dynamic memory
- Man pagemmap(2): map files or devices into memory
Official documentation first. Links checked when the lesson was published.