Module 13 · Lesson 50 of 98

SYCL as single-source C++

Identify host and device code in a SYCL translation unit and explain how buffers, accessors, and USM affect data access, ordering, and lifetime.

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

Ubuntu 24.04 in WSL2 or a VM and familiarity with C++ lambdas and arrays. The exercises use source inspection and hand tracing. Running the snippets requires a SYCL implementation with a supported device.

Your place in the module
By the end you can 4 objectives
  • Identify the host submission code and device kernel in a SYCL source file.
  • Trace a write followed by a read through accessors on the same buffer.
  • Choose between malloc_device and malloc_shared based on where the allocation must be dereferenced.
  • Identify when the host may read results or release memory in each model.
Video coming soonSYCL as single-source C++
The video for this lesson is being recorded. Read the lesson below in the meantime.
Recall first from OpenCL on embedded targets and its caveats
  • An OpenCL work-item can compute the same element or pixel as its CUDA thread counterpart.
  • An OpenCL loader needs an implementation that exposes a usable device.
  • Explicit local sizes must satisfy per-dimension, device-wide and kernel-specific limits.
01

Host and device code in one C++ file

3 min read

You wrote portable kernels in OpenCL's C dialect. SYCL moves that into C++, and this lesson answers how host and device code live in one file and how buffers differ from USM.

Suppose a Linux program doubles every sample in an array, then checks the result on the CPU. The host can allocate an array with malloc() and read it through an ordinary pointer. A kernel submitted to a separate device needs a defined way to reach those elements, and the host needs a defined point at which it can read the results. Those two requirements explain most of the differences between the SYCL memory models. malloc(3)

A In SYCL, one translation unit can contain ordinary C++ host functions and the definitions of kernels those functions submit. The SYCL implementation builds code for host execution and for the supported device targets. In the snippets below, assume the source includes <sycl/sycl.hpp> and that q is a sycl::queue created by the host. Building device code requires a SYCL-capable toolchain.

A queue has an associated device and context. The host calls a queue submission function to request work for that device. The submission may return while work is still pending, so a host statement immediately after submission can execute before the kernel finishes. A dependency orders one command after another. A host wait lets the CPU know when specified work has finished.

The following function doubles values in an existing USM allocation. Its caller supplies a device-accessible pointer valid for the queue and a count n within the allocation. The function returns an event for the submitted kernel.

cpp
sycl::event double_samples(sycl::queue& q, int* values, std::size_t n)
{
    return q.parallel_for(sycl::range<1>{n}, [=](sycl::id<1> i) {
        values[i[0]] *= 2;
    });
}

The call to q.parallel_for runs on the host. The lambda body is the kernel. sycl::range<1>{n} requests a one-dimensional iteration space, and each kernel invocation receives its own index i. The capture [=] makes the pointer value available to the kernel. It copies the address into the kernel arguments, while the elements remain in the existing allocation. Each invocation updates one element. Assume the sample values are small enough that doubling fits in an int.

You can also express a kernel as a C++ functor. A functor is an object that you can call because its type defines operator(). The equivalent functor would store the pointer as a data member and provide operator()(sycl::id<1> i) const with the same update. Its data members supply the kernel state in the same way that the lambda's captures do. Both forms must use state and operations supported in device code. A lambda is convenient for a short calculation, while a named functor gives a reusable kernel a type you can instantiate in several host functions.

Host and device in one translation unitC++ translation unitHost functionSubmits through a queueDevice kernelLambda or functorC++ translation unitHost functionSubmits through a queueDevice kernelLambda or functor
One translation unit defines host submission and the kernel that the selected device executes.
02

Buffers declare how commands use data

3 min read

A sycl::buffer represents a sequence of elements managed by the SYCL runtime. An accessor provides a way to read or write those elements. For a device command, the accessor also tells the runtime which buffer the command uses and what kind of access it needs. The runtime uses this information to order conflicting accesses and make the relevant contents available where the command runs.

Here the queue submits two commands. The first writes a sample value at each index. The second doubles those values in place. The host then reads the result through a host accessor. Assume n is positive and the largest index doubled still fits in int.

cpp
sycl::buffer<int, 1> samples{sycl::range<1>{n}};

q.submit([&](sycl::handler& h) {
    sycl::accessor output{samples, h, sycl::write_only, sycl::no_init};
    h.parallel_for(sycl::range<1>{n}, [=](sycl::id<1> i) {
        output[i] = static_cast<int>(i[0]);
    });
});

q.submit([&](sycl::handler& h) {
    sycl::accessor values{samples, h, sycl::read_write};
    h.parallel_for(sycl::range<1>{n}, [=](sycl::id<1> i) {
        values[i] *= 2;
    });
});

{
    sycl::host_accessor result{samples, sycl::read_only};
    const int last_sample = result[n - 1];
    // Use last_sample on the host.
}

Each q.submit contains two lambdas. The outer [&] lambda runs on the host and receives the sycl::handler used to describe the command. The accessor created there registers the buffer requirement with that handler. The inner [=] lambda runs on the device and captures the accessor by value so that it can index the buffer.

The first accessor uses write_only because its kernel assigns every element without reading it. sycl::no_init says the previous contents need not be made available to this accessor. Use it here because every element that the second kernel will read gets a value in the first kernel. The second accessor needs read_write because *= uses the old value and stores a new one.

The second command requires the data written by the first. SYCL can infer that dependency from the two accessors on samples, even on a queue without the in_order property. The host accessor then waits as needed for the pending writes to finish before it grants host access. Keep it scoped to the host read. While the host accessor is alive, a device command that needs conflicting access must wait for its release.

This example constructs the buffer from a range and uses the host accessor to inspect it. If you construct a buffer from a writable host array, keep that array alive for the buffer's lifetime and use accessors to inspect the data while the buffer owns access to it. With default write-back behavior, destruction of the last buffer object referring to that storage waits as needed and copies modified data back to the supplied host array. That gives the surrounding host code a second way to retrieve results after the buffer scope ends.

Buffer access dependenciesInitializebufferWrite-onlydeviceaccessorDoublevaluesRead-writedeviceaccessorRead onhostRead-onlyhostaccessorInitializebufferWrite-onlydeviceaccessorDoublevaluesRead-writedeviceaccessorRead onhostRead-onlyhostaccessor
Accessor requirements order initialization, the in-place update, and the host read.
03

USM uses pointers and application-managed ordering

3 min read

The host can pass a USM pointer into a kernel capture, and the kernel indexes through it as it does in double_samples. The choice of allocation function determines which code may dereference the pointer. Passing the pointer as an argument and dereferencing it to read or write an element are distinct operations.

Allocation Host can dereference Allocating device can dereference How the host typically reads results
sycl::malloc_device<int>(n, q) No Yes Copy to host storage and wait for the copy to finish
sycl::malloc_shared<int>(n, q) Yes Yes Wait for the device write to finish, then read through the pointer

With malloc_device, the host can hold the pointer and pass it to the queue's memcpy function. For an input array, the host can queue a copy into the device allocation, run the kernel after that copy, and copy the modified values back to a host array after the kernel finishes. The host reads the destination array after the final copy completes. The allocation remains live through the final copy because that command still reads it.

With malloc_shared, the host can fill the allocation directly before submission. After the kernel completes, the host can read the results through the same pointer. On Linux, mmap() creates a mapping in a process's virtual address space. The ability to dereference a pointer in host code tells you about access, while the allocation and implementation determine the underlying storage. For SYCL shared USM, using one pointer on both sides provides no guarantee of a particular physical layout or transfer cost. mmap(2)

Before using either allocation kind, check the selected device with q.get_device().has(...). Use sycl::aspect::usm_device_allocations for device allocations and sycl::aspect::usm_shared_allocations for shared allocations. Check the allocation result for a null pointer before using it. Keep the allocation valid for the queue's context and for every command that uses it, then release it with sycl::free(ptr, q) after those commands finish.

With raw USM pointers, capturing the same pointer in two submissions supplies no accessor dependency. If one kernel fills a shared allocation and a second doubles its contents, the second needs to wait for the first. One simple approach is to wait on the first command's returned event before submitting the second. An in_order queue can also order commands submitted to that queue. Even with an in_order queue, a host read through a shared pointer still needs to wait for the relevant device write. The host dereference is an ordinary C++ operation outside the queue.

Buffer and USM accessBufferDevice USMShared USMKernel usesDeviceaccessorPointerPointerCommand orderingAccessorrequirementsApplicationorderscommandsApplicationorderscommandsHost resultaccessHost accessorCopy to hostPointer afterwait
The allocation choice determines how the host accesses results and how the program orders the work.

When you read a SYCL submission, locate the kernel and identify how it accesses each array. For a buffer, inspect the accessor modes and the point where the host acquires access. For USM, inspect the allocation kind, the ordering of commands that use the pointer, and the last use before release. The next lesson, nd_range and moving USM pointers, follows those same submissions with explicit work-group sizing and USM copy operations.

Key takeaways

  • A SYCL translation unit can contain host code and device kernels written as C++ lambdas or functors.
  • A queue submits work to its associated device, and buffer accessors describe dependencies between commands.
  • malloc_device provides memory for device access, while malloc_shared provides memory that both host and device can dereference.
  • USM pointers leave command ordering and allocation lifetime under application control.
Reflect
  1. Explain to a colleague, in two sentences: identify the host submission code and device kernel in a SYCL source file.
  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