Module 13 · Lesson 46 of 98

The OpenCL object model and kernel language

Trace an OpenCL dispatch through its objects and write an OpenCL C kernel that uses work-item coordinates to access buffers safely.

  • Beginner to advanced
  • 7 min read
  • 20 min lab
What you will need

Ubuntu 24.04 in WSL2 or a VM and a text editor for the source and dispatch exercises.

Your place in the module
By the end you can 4 objectives
  • Identify the seven OpenCL objects used in a buffer-based dispatch.
  • Explain how a context relates to its devices, queues, programs and buffers.
  • Write an OpenCL C kernel with buffer arguments, a scalar length and a bounds check.
  • Derive global IDs, local IDs and work dimension for a specified dispatch.
Video coming soonThe OpenCL object model and kernel language
The video for this lesson is being recorded. Read the lesson below in the meantime.
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.
01

The objects behind a dispatch

3 min read

You 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.
OpenCL object relationshipsOpenCL objectRelationshipPlatformImplementationExposesdevicesDeviceComputetargetExposed byplatformContextResourcescopeGroupsselecteddevicesCommand queueSubmissionobjectTargets onecontextdeviceProgramCodecontainerBelongs tocontextKernelEntry pointComes fromprogramMemory objectManagedstorageBelongs tocontext
The queue selects the execution device. The kernel comes from a program, and its buffer arguments refer to memory objects.

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.

02

Writing an OpenCL C kernel

2 min read

Save 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.

c
__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.

One addition work-itemRead globalIDCheck indexRead bothinputsAdd valuesExit from step 2: Index at least countReturnStoreoutputRead globalIDCheck indexExit from step 2: Index atleast countReturnRead bothinputsAdd valuesStoreoutput
A work-item checks its global index before using that index for all three buffer accesses.

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.

03

Reading the dispatch coordinates

3 min read

The 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.

Global and local IDsLocal ID0123Group 0global IDs0123Group 1global IDs4567Group 2global IDs891011Group 3global IDs12131415Axis 0, global offset zero.
For a one-dimensional dispatch of sixteen work-items in groups of four, the same local IDs occur in every group.

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
  1. Explain to a colleague, in two sentences: identify the seven OpenCL objects used in a buffer-based dispatch.
  2. Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
  3. 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

Official documentation first. Links checked when the lesson was published.

Find your next step

↑ ↓ to move · Enter to open · Esc to close