This repository has been archived on 2026-11-24. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
radiance-sycl/core/device/sycl.cpp
T
claudeandClaude Opus 5.5 8addda231b device: the SYCL backend -- Intel GPUs through oneAPI over Level Zero
A fourth DeviceBackend, in librad_sycl.so: in-order sycl::queues on one context, events as
barriers, copies and fills on the queue, gates as a spin kernel on a pinned flag, and the core's
advance and weight-table kernels as SYCL twins of their .hip files. RadStreams are RadSyclStreams
(abi/rad_sycl.h). Pinned host memory is page-aligned memory registered for device copies, since
O_DIRECT cannot read into SYCL's malloc_host pages; event timing is opt-in (RADIANCE_SYCL_TIMING=1)
because profiling queues cost ~20 us of host time a submission.

The SYCL code is its own CMake project, sycl/, configured with icpx through ExternalProject, so the
engine and every host plugin stay on the main compiler: a SYCL build's host code is the default
build's. RAD_SYCL (default OFF), build.sh --sycl, the sycl presets; HIP and SYCL in one build are
refused at configure.

On the SYCL backend --tp > 1 and ops resolved only to host kernels stop the start, since the Intel
backend runs on one card and never puts an op on the CPU. A SYCL build that sees no GPU warns that
it runs on the CPU and names the missing oneAPI environment.

device_test runs on the Arc Pro B65 as device_test_sycl (label sycl): 36 cases pass, 12 skip
(elastic memory, not provided; host-backend-only cases). Host tests hide Level Zero GPUs with
ONEAPI_DEVICE_SELECTOR. The host tier is the baseline's in both the default and the SYCL build.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018EpFgqQidSnH8zo7boVZC1
2026-10-23 15:38:42 +02:00

852 lines
34 KiB
C++

/* sycl.cpp -- the SYCL device backend: Intel GPUs through oneAPI's SYCL runtime over Level Zero.
*
* Every stream is an in-order sycl::queue on one context holding every device, and a RadStream is
* a RadSyclStream (abi/rad_sycl.h), so a SYCL kernel library submits to the engine's queue itself.
* Events are barriers on those queues: a record is a barrier whose event completes once everything
* before it has, and a wait is a barrier on the waiting queue that depends on that event, so no
* host thread blocks for either.
*
* Thin by design, like hip.cpp: each entry point is one runtime call plus error capture, and the
* contract is the host backend's (docs/IMPLEMENTATION.md). Where the runtime is more permissive
* than a card's contract (rad_memset_async on pageable memory, device.h note 1) the refusal is
* made here, so code developed on the host backend sees the same answer on this one.
*
* What this backend leaves out, each a supported configuration (device.h): recorded passes, elastic
* memory, the DMA lane and link holds, the expert prefetch, gates, chained launches. Peer access is
* refused, since the Intel backend serves one card (docs/SYCL_PORTING.md §4.7).
*
* Timing is opt-in. A queue made with enable_profiling costs ~20 us of host time per submission
* against ~4.5 us without (measured on the Arc Pro B65, docs/SYCL_PROGRESS.md D9), which at ~550
* launches a decode step is most of a step. So queues carry it only under RADIANCE_SYCL_TIMING=1,
* and otherwise rad_event_elapsed_ms refuses, naming the variable (--profile-ops, rad-kbench).
*
* Built by icpx into librad_sycl.so (sycl/CMakeLists.txt); the engine reaches it through
* rad_sycl_backend() and hands it its logger (sycl_host.h). core/CMakeLists.txt globs this
* directory into the engine, built without SYCL, where the file compiles to nothing.
*/
#if defined(SYCL_LANGUAGE_VERSION)
#include "device.h"
#include "sycl_host.h"
#include "../rad_internal.h"
#include "rad_sycl.h"
#include <sycl/sycl.hpp>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <atomic>
#include <cstring>
#include <map>
#include <mutex>
#include <new>
#include <string>
#include <vector>
namespace rad {
namespace {
namespace syclex = sycl::ext::oneapi::experimental;
/* ------------------------------------------------------------------ the runtime's state
*
* Built once, on first use: the Level Zero GPUs in the platform's order and one context over all
* of them (USM pointers are valid only within their context). */
struct Runtime {
std::vector<sycl::device> devs;
sycl::context* ctx = nullptr;
};
Runtime& rt() {
static Runtime* r = [] {
auto* x = new Runtime();
try {
for (const sycl::device& d : sycl::device::get_devices(sycl::info::device_type::gpu))
if (d.get_backend() == sycl::backend::ext_oneapi_level_zero) x->devs.push_back(d);
if (!x->devs.empty()) x->ctx = new sycl::context(x->devs);
} catch (const sycl::exception& e) {
RAD_DEBUG("device: SYCL device enumeration failed: %s", e.what());
x->devs.clear();
}
return x;
}();
return *r;
}
/* RADIANCE_SYCL_TIMING=1: queues are made with enable_profiling (see the file header). */
bool timing_on() {
static const bool on = [] {
const char* e = std::getenv("RADIANCE_SYCL_TIMING");
return e && e[0] == '1';
}();
return on;
}
/* Per thread, matching hipSetDevice: one thread per rank, one device per rank (spec §1). */
thread_local int t_device = 0;
int sycl_fail(const sycl::exception& e, const char* who) {
device_set_error("%s: %s", who, e.what());
const std::error_code c = e.code();
if (c == sycl::errc::memory_allocation) return RAD_E_NOMEM;
if (c == sycl::errc::invalid || c == sycl::errc::nd_range) return RAD_E_INVAL;
if (c == sycl::errc::feature_not_supported) return RAD_E_UNSUPPORTED;
return RAD_E_DEVICE;
}
#define SYCL_TRY(who, ...) \
do { try { __VA_ARGS__; } \
catch (const sycl::exception& _e) { return sycl_fail(_e, who); } } while (0)
bool valid_device(int device) { return device >= 0 && device < (int)rt().devs.size(); }
/* Asynchronous errors (a kernel fault) arrive here from wait_and_throw. A device fault is not
* recoverable in-process (rad_device.h), so the error is recorded for the thread that waited and
* every later wait reports it too. */
std::mutex g_async_m;
std::string g_async_error;
void async_handler(sycl::exception_list errs) {
for (const std::exception_ptr& p : errs) {
try {
std::rethrow_exception(p);
} catch (const sycl::exception& e) {
std::lock_guard<std::mutex> lk(g_async_m);
if (g_async_error.empty()) g_async_error = e.what();
RAD_WARN("device: asynchronous SYCL error: %s", e.what());
}
}
}
int async_status(const char* who) {
std::lock_guard<std::mutex> lk(g_async_m);
if (g_async_error.empty()) return RAD_OK;
device_set_error("%s: the device reported an error earlier: %s", who, g_async_error.c_str());
return RAD_E_DEVICE;
}
/* ------------------------------------------------------------------ devices */
int d_count(void) { return (int)rt().devs.size(); }
int d_set(int device) {
if (!valid_device(device)) {
device_set_error("rad_dev_set(%d): %d SYCL device(s)", device, d_count());
return RAD_E_INVAL;
}
t_device = device;
return RAD_OK;
}
/* RadDeviceProps::arch, the name a kernel library's build_target names: the oneAPI architecture
* enum's own spelling. A device this table does not know is "intel_gpu" plus its IP version, so
* a library built for a named architecture never claims it. */
std::string arch_name(const sycl::device& d) {
try {
switch (d.get_info<syclex::info::device::architecture>()) {
case syclex::architecture::intel_gpu_bmg_g21: return "intel_gpu_bmg_g21";
case syclex::architecture::intel_gpu_bmg_g31: return "intel_gpu_bmg_g31";
case syclex::architecture::intel_gpu_lnl_m: return "intel_gpu_lnl_m";
case syclex::architecture::intel_gpu_ptl_h: return "intel_gpu_ptl_h";
case syclex::architecture::intel_gpu_ptl_u: return "intel_gpu_ptl_u";
case syclex::architecture::intel_gpu_acm_g10: return "intel_gpu_acm_g10";
case syclex::architecture::intel_gpu_acm_g11: return "intel_gpu_acm_g11";
case syclex::architecture::intel_gpu_acm_g12: return "intel_gpu_acm_g12";
case syclex::architecture::intel_gpu_pvc: return "intel_gpu_pvc";
default: break;
}
char b[32];
std::snprintf(b, sizeof b, "intel_gpu_%llx",
(unsigned long long)d.get_info<syclex::info::device::architecture>());
return b;
} catch (const sycl::exception&) {
return "intel_gpu";
}
}
int64_t free_bytes(const sycl::device& d) {
if (!d.has(sycl::aspect::ext_intel_free_memory)) return -1;
try {
return (int64_t)d.get_info<sycl::ext::intel::info::device::free_memory>();
} catch (const sycl::exception&) {
return -1;
}
}
int d_integrated(int device) {
if (!valid_device(device)) return 0;
/* Unified host memory is how SYCL tells an integrated GPU, whose "device memory" is host
* memory shared with every process. */
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
try {
return rt().devs[device].get_info<sycl::info::device::host_unified_memory>() ? 1 : 0;
} catch (const sycl::exception&) {
return 0;
}
#pragma clang diagnostic pop
}
int d_props(int device, RadDeviceProps* out) {
if (!out) return RAD_E_INVAL;
if (!valid_device(device)) {
device_set_error("rad_dev_props(%d): %d SYCL device(s)", device, d_count());
return RAD_E_INVAL;
}
const sycl::device& d = rt().devs[device];
std::memset(out, 0, sizeof *out);
SYCL_TRY("rad_dev_props", {
const std::string name = d.get_info<sycl::info::device::name>();
std::snprintf(out->name, sizeof out->name, "%.*s", (int)(sizeof out->name) - 1, name.c_str());
const std::string arch = arch_name(d);
std::snprintf(out->arch, sizeof out->arch, "%.*s", (int)(sizeof out->arch) - 1, arch.c_str());
out->device_id = device;
out->n_cu = (int)d.get_info<sycl::info::device::max_compute_units>();
/* The sub-group the kernel libraries use: 16 where offered (Xe2's native width). */
const std::vector<size_t> sg = d.get_info<sycl::info::device::sub_group_sizes>();
out->warp_size = sg.empty() ? 1 : (int)sg.front();
for (size_t s : sg)
if (s == 16) out->warp_size = 16;
out->vram_bytes = (int64_t)d.get_info<sycl::info::device::global_mem_size>();
const int64_t fr = free_bytes(d);
out->vram_free = fr >= 0 ? fr : out->vram_bytes;
out->lds_bytes = (int64_t)d.get_info<sycl::info::device::local_mem_size>();
});
out->supports_p2p = 0;
out->is_host_backend = 0;
return RAD_OK;
}
/* One card only (docs/SYCL_PORTING.md §4.7): no peer is reachable. */
int d_peer_access(int self, int peer) { return self == peer ? 1 : 0; }
int d_enable_peer(int self, int peer) {
if (self == peer) return RAD_OK;
device_set_error("rad_dev_enable_peer(%d, %d): the SYCL backend serves one card; tensor "
"parallelism is not supported on it", self, peer);
return RAD_E_UNSUPPORTED;
}
int d_pci_address(int device, char* out, int cap) {
if (!out || cap <= 0) return RAD_E_INVAL;
if (!valid_device(device)) return RAD_E_INVAL;
const sycl::device& d = rt().devs[device];
if (!d.has(sycl::aspect::ext_intel_pci_address)) return RAD_E_UNSUPPORTED;
std::string a;
SYCL_TRY("rad_dev_pci_address", a = d.get_info<sycl::ext::intel::info::device::pci_address>());
unsigned dom = 0, b = 0, dv = 0, f = 0;
if (std::sscanf(a.c_str(), "%x:%x:%x.%x", &dom, &b, &dv, &f) != 4) {
device_set_error("ext_intel_pci_address(%d): '%s' is not a PCI address", device, a.c_str());
return RAD_E_IO;
}
std::snprintf(out, (size_t)cap, "%04x:%02x:%02x.%x", dom, b, dv, f);
return RAD_OK;
}
int d_runtime_version(char* out, int cap) {
if (!out || cap <= 0) return RAD_E_INVAL;
if (rt().devs.empty()) return RAD_E_UNSUPPORTED;
SYCL_TRY("rad_dev_runtime_version", {
const sycl::device& d = rt().devs[0];
std::snprintf(out, (size_t)cap, "SYCL %s, Level Zero driver %s",
d.get_platform().get_info<sycl::info::platform::version>().c_str(),
d.get_info<sycl::info::device::driver_version>().c_str());
});
return RAD_OK;
}
/* VRAM in use by all processes, from the driver's free count. Answered once props() has read the
* device, as the contract asks; the query does not enter a queue. */
int d_vram_used(int device, int64_t* out) {
if (!out || !valid_device(device)) return RAD_E_INVAL;
const sycl::device& d = rt().devs[device];
const int64_t fr = free_bytes(d);
if (fr < 0) return RAD_E_UNSUPPORTED;
int64_t total = 0;
SYCL_TRY("rad_dev_vram_used", total = (int64_t)d.get_info<sycl::info::device::global_mem_size>());
*out = total - fr;
return RAD_OK;
}
/* ------------------------------------------------------------------ memory
*
* Pinned host memory (RAD_MEM_HOST_PINNED and _MAPPED) is ordinary page-aligned memory registered
* with the driver (prepare_for_device_copy), not SYCL's malloc_host. The driver maps malloc_host
* pages itself, and O_DIRECT cannot read into them (EFAULT), while the mover reads the file tier
* straight into pinned buffers (directio.h). Registered memory copies at the same rate (28.4 GB/s
* either way on the Arc Pro B65) and kernels reach it through system USM, which the Intel driver
* provides (aspect usm_system_allocations). The runtime does not know such a pointer, so the
* ranges are kept here for host_ptr, device_ptr and the memset check. */
std::mutex g_pinned_m;
std::map<uintptr_t, size_t> g_pinned; /* base -> bytes */
bool in_pinned(const void* p) {
const uintptr_t a = (uintptr_t)p;
std::lock_guard<std::mutex> lk(g_pinned_m);
auto it = g_pinned.upper_bound(a);
if (it == g_pinned.begin()) return false;
--it;
return a < it->first + it->second;
}
/* Device bytes this process holds through rad_dev_alloc, for the room check's message. */
std::atomic<int64_t> g_device_bytes{0};
std::mutex g_dev_sizes_m;
std::map<uintptr_t, int64_t> g_dev_sizes;
std::string human(int64_t b) {
char buf[32];
if (b >= ((int64_t)1 << 30)) std::snprintf(buf, sizeof buf, "%.2f GiB", (double)b / (1 << 30));
else if (b >= ((int64_t)1 << 20)) std::snprintf(buf, sizeof buf, "%.1f MiB", (double)b / (1 << 20));
else std::snprintf(buf, sizeof buf, "%lld B", (long long)b);
return buf;
}
/* True when the card can take `bytes` more. Level Zero may accept an allocation past the free
* figure and fault later, so the backend refuses it itself, as the AQL backend does. If the driver
* gives no figure the allocation is allowed. */
bool card_has_room(int device, int64_t bytes, const char* what) {
const int64_t avail = free_bytes(rt().devs[device]);
if (avail < 0 || bytes <= avail) return true;
device_set_error("%s(%s) on card %d: the driver has %s left to give on it. Of the memory in "
"use on it, this process holds %s through rad_dev_alloc. Memory another "
"process took after the VRAM budget was measured is the usual cause",
what, human(bytes).c_str(), device, human(avail).c_str(),
human(g_device_bytes.load()).c_str());
return false;
}
void* d_alloc(int64_t bytes, int kind) {
if (bytes <= 0) {
device_set_error("rad_dev_alloc(%lld): size must be positive", (long long)bytes);
return nullptr;
}
if (!valid_device(t_device)) {
device_set_error("rad_dev_alloc: no SYCL device %d", t_device);
return nullptr;
}
void* p = nullptr;
try {
switch (kind) {
case RAD_MEM_DEVICE:
if (!card_has_room(t_device, bytes, "rad_dev_alloc")) return nullptr;
p = sycl::malloc_device((size_t)bytes, rt().devs[t_device], *rt().ctx);
if (p) {
g_device_bytes += bytes;
std::lock_guard<std::mutex> lk(g_dev_sizes_m);
g_dev_sizes[(uintptr_t)p] = bytes;
}
break;
case RAD_MEM_HOST_PINNED:
case RAD_MEM_HOST_MAPPED: {
/* Registered page-aligned memory (see above): one address on both sides, so
* host_ptr and device_ptr are the pointer itself. */
const size_t n = (size_t)((bytes + 4095) / 4096 * 4096);
if (posix_memalign(&p, 4096, n) != 0) p = nullptr;
if (!p) break;
try {
syclex::prepare_for_device_copy(p, n, *rt().ctx);
} catch (...) {
std::free(p);
throw;
}
std::lock_guard<std::mutex> lk(g_pinned_m);
g_pinned[(uintptr_t)p] = n;
break;
}
case RAD_MEM_HOST:
/* Pageable, page-aligned so it can be an O_DIRECT target. */
if (posix_memalign(&p, 4096, (size_t)((bytes + 4095) / 4096 * 4096)) != 0) p = nullptr;
break;
default:
device_set_error("rad_dev_alloc: unknown memory kind %d", kind);
return nullptr;
}
} catch (const sycl::exception& e) {
sycl_fail(e, "rad_dev_alloc");
return nullptr;
}
if (!p) device_set_error("rad_dev_alloc(%lld, kind %d): out of memory", (long long)bytes, kind);
return p;
}
void d_free(void* p, int kind) {
if (!p) return;
switch (kind) {
case RAD_MEM_DEVICE:
try {
sycl::free(p, *rt().ctx);
} catch (const sycl::exception& e) {
RAD_WARN("device: rad_dev_free(%p): %s", p, e.what());
}
{
std::lock_guard<std::mutex> lk(g_dev_sizes_m);
auto it = g_dev_sizes.find((uintptr_t)p);
if (it != g_dev_sizes.end()) {
g_device_bytes -= it->second;
g_dev_sizes.erase(it);
}
}
break;
case RAD_MEM_HOST_PINNED:
case RAD_MEM_HOST_MAPPED: {
{
std::lock_guard<std::mutex> lk(g_pinned_m);
if (!g_pinned.erase((uintptr_t)p)) {
RAD_WARN("rad_dev_free(%p): not pinned memory this backend gave out; leaked "
"rather than freed with the wrong allocator", p);
break;
}
}
try {
syclex::release_from_device_copy(p, *rt().ctx);
} catch (const sycl::exception& e) {
RAD_WARN("device: rad_dev_free(%p): %s", p, e.what());
}
std::free(p);
break;
}
case RAD_MEM_HOST:
std::free(p);
break;
default:
RAD_WARN("rad_dev_free(%p): unknown memory kind %d; leaked rather than freed with the "
"wrong allocator", p, kind);
break;
}
}
/* What `p` is to the device: USM device memory, host memory it reaches (SYCL's or this backend's
* registered pinned ranges), or unknown (pageable). */
sycl::usm::alloc ptr_kind(const void* p) {
if (in_pinned(p)) return sycl::usm::alloc::host;
try {
return sycl::get_pointer_type(p, *rt().ctx);
} catch (const sycl::exception&) {
return sycl::usm::alloc::unknown;
}
}
void* d_host_ptr(void* p) {
if (!p) return nullptr;
const sycl::usm::alloc k = ptr_kind(p);
return k == sycl::usm::alloc::host || k == sycl::usm::alloc::shared ? p : nullptr;
}
void* d_device_ptr(void* p) {
if (!p) return nullptr;
return ptr_kind(p) != sycl::usm::alloc::unknown ? p : nullptr;
}
/* ------------------------------------------------------------------ streams */
/* `pub` first, so the RadStream handed out is the RadSyclStream a plugin reads. */
struct SyclStream {
RadSyclStream pub;
sycl::queue q;
std::atomic<int> gates{0}; /* closed gates on this stream (rad_stream_gate) */
SyclStream(const sycl::context& c, const sycl::device& d, const sycl::property_list& pl)
: pub{}, q(c, d, async_handler, pl) {}
};
SyclStream* as_stream(RadStream s) { return (SyclStream*)s; }
/* A null stream is refused, as on every backend (device.h note 2). */
int check_stream(RadStream s, const char* who) {
if (s) return RAD_OK;
device_set_error("%s: null stream -- radiance does not use the default stream, "
"create one with rad_stream_create", who);
return RAD_E_INVAL;
}
int d_stream_create(RadStream* out, int high_priority) {
if (!out) return RAD_E_INVAL;
if (!valid_device(t_device)) {
device_set_error("rad_stream_create: no SYCL device %d", t_device);
return RAD_E_INVAL;
}
SyclStream* s = nullptr;
SYCL_TRY("rad_stream_create", {
using sycl::property::queue::enable_profiling;
using sycl::property::queue::in_order;
using sycl::ext::oneapi::property::queue::priority_high;
sycl::property_list pl;
if (high_priority && timing_on())
pl = sycl::property_list{in_order{}, enable_profiling{}, priority_high{}};
else if (high_priority)
pl = sycl::property_list{in_order{}, priority_high{}};
else if (timing_on())
pl = sycl::property_list{in_order{}, enable_profiling{}};
else
pl = sycl::property_list{in_order{}};
s = new (std::nothrow) SyclStream(*rt().ctx, rt().devs[t_device], pl);
});
if (!s) {
device_set_error("rad_stream_create: out of memory");
return RAD_E_NOMEM;
}
s->pub.magic = RAD_SYCL_STREAM_MAGIC;
s->pub.version = RAD_SYCL_STREAM_VERSION;
s->pub.queue = &s->q;
s->pub.device = t_device;
*out = (RadStream)s;
return RAD_OK;
}
/* Drains rather than discards, as the host backend's destroy does. */
void d_stream_destroy(RadStream st) {
if (!st) return;
SyclStream* s = as_stream(st);
try {
s->q.wait_and_throw();
} catch (const sycl::exception& e) {
RAD_WARN("device: rad_stream_destroy: %s", e.what());
}
s->pub.magic = 0;
delete s;
}
int d_stream_sync(RadStream st) {
if (!st) {
device_set_error("rad_stream_sync: null stream");
return RAD_E_INVAL;
}
if (as_stream(st)->gates.load() > 0) {
device_set_error("rad_stream_sync: the stream waits at a closed gate, which only "
"rad_gate_open releases");
return RAD_E_STATE;
}
SYCL_TRY("rad_stream_sync", as_stream(st)->q.wait_and_throw());
return async_status("rad_stream_sync");
}
/* ------------------------------------------------------------------ events
*
* An event holds its latest record. `recorded` counts records, so a never-recorded event is
* complete and waiting on it is a no-op (the mover relies on that, host.cpp). */
struct SyclEvent {
std::mutex m;
sycl::event ev;
uint64_t recorded = 0;
bool host = false; /* RAD_EVENT_HOST_WAIT: rad_event_sync may block on it */
};
int d_event_create(RadEvent* out, unsigned flags) {
if (!out) return RAD_E_INVAL;
auto* e = new (std::nothrow) SyclEvent();
if (!e) {
device_set_error("rad_event_create: out of memory");
return RAD_E_NOMEM;
}
/* RAD_EVENT_LOCAL has no scope to choose here: a barrier's completion is visible to the host
* and to every queue of the context alike. */
e->host = (flags & RAD_EVENT_HOST_WAIT) != 0;
*out = (RadEvent)e;
return RAD_OK;
}
/* A queued barrier that waits on the event holds its own reference, so dropping ours is safe. */
void d_event_destroy(RadEvent ev) { delete (SyclEvent*)ev; }
int d_event_record(RadEvent ev, RadStream st) {
if (!ev || !st) {
device_set_error("rad_event_record: null %s", ev ? "stream" : "event");
return RAD_E_INVAL;
}
auto* e = (SyclEvent*)ev;
sycl::event b;
SYCL_TRY("rad_event_record", b = as_stream(st)->q.ext_oneapi_submit_barrier());
std::lock_guard<std::mutex> lk(e->m);
e->ev = b;
++e->recorded;
return RAD_OK;
}
int d_event_wait(RadStream st, RadEvent ev) {
if (!ev || !st) {
device_set_error("rad_event_wait: null %s", ev ? "stream" : "event");
return RAD_E_INVAL;
}
auto* e = (SyclEvent*)ev;
sycl::event dep;
{
std::lock_guard<std::mutex> lk(e->m);
if (e->recorded == 0) return RAD_OK;
dep = e->ev;
}
SYCL_TRY("rad_event_wait", as_stream(st)->q.ext_oneapi_submit_barrier({dep}));
return RAD_OK;
}
bool event_done(const sycl::event& ev) {
return ev.get_info<sycl::info::event::command_execution_status>() ==
sycl::info::event_command_status::complete;
}
int d_event_query(RadEvent ev) {
if (!ev) return RAD_E_INVAL;
auto* e = (SyclEvent*)ev;
std::lock_guard<std::mutex> lk(e->m);
if (e->recorded == 0) return 1;
try {
return event_done(e->ev) ? 1 : 0;
} catch (const sycl::exception& x) {
return sycl_fail(x, "rad_event_query");
}
}
int d_event_sync(RadEvent ev) {
if (!ev) return RAD_E_INVAL;
auto* e = (SyclEvent*)ev;
if (!e->host) {
device_set_error("rad_event_sync: the event was made without RAD_EVENT_HOST_WAIT");
return RAD_E_INVAL;
}
sycl::event w;
{
std::lock_guard<std::mutex> lk(e->m);
if (e->recorded == 0) return RAD_OK;
w = e->ev;
}
SYCL_TRY("rad_event_sync", w.wait_and_throw());
return async_status("rad_event_sync");
}
int d_event_elapsed_ms(RadEvent a, RadEvent b, float* out) {
if (!a || !b || !out) return RAD_E_INVAL;
if (!timing_on()) {
device_set_error("rad_event_elapsed_ms: the SYCL backend times events only under "
"RADIANCE_SYCL_TIMING=1 (profiling queues cost ~20 us a submission)");
return RAD_E_UNSUPPORTED;
}
auto stamp = [](RadEvent ev, uint64_t* t) -> int {
auto* e = (SyclEvent*)ev;
std::lock_guard<std::mutex> lk(e->m);
if (e->recorded == 0) return RAD_E_STATE;
SYCL_TRY("rad_event_elapsed_ms", {
if (!event_done(e->ev)) return RAD_E_STATE;
*t = e->ev.get_profiling_info<sycl::info::event_profiling::command_end>();
});
return RAD_OK;
};
uint64_t ta = 0, tb = 0;
RAD_TRY(stamp(a, &ta));
RAD_TRY(stamp(b, &tb));
*out = (float)(((double)tb - (double)ta) / 1e6);
return RAD_OK;
}
/* USM host memory is coherent for the device at submission: nothing to make visible. */
void d_host_wrote(void) {}
/* ------------------------------------------------------------------ copies and fills */
int d_memcpy_async(void* dst, const void* src, int64_t bytes, RadStream st) {
RAD_TRY(check_stream(st, "rad_memcpy_async"));
if (bytes == 0) return RAD_OK;
if (!dst || !src || bytes < 0) {
device_set_error("rad_memcpy_async(%p <- %p, %lld): invalid argument", dst, src,
(long long)bytes);
return RAD_E_INVAL;
}
SYCL_TRY("rad_memcpy_async", as_stream(st)->q.memcpy(dst, src, (size_t)bytes));
return RAD_OK;
}
int d_memcpy_2d_async(void* dst, int64_t dpitch, const void* src, int64_t spitch, int64_t width,
int64_t height, RadStream st) {
RAD_TRY(check_stream(st, "rad_memcpy_2d_async"));
if (width == 0 || height == 0) return RAD_OK;
if (!dst || !src || width < 0 || height < 0 || dpitch < width || spitch < width) {
device_set_error("rad_memcpy_2d_async(%p/%lld <- %p/%lld, %lld x %lld): invalid argument",
dst, (long long)dpitch, src, (long long)spitch, (long long)width,
(long long)height);
return RAD_E_INVAL;
}
SYCL_TRY("rad_memcpy_2d_async",
as_stream(st)->q.ext_oneapi_memcpy2d(dst, (size_t)dpitch, src, (size_t)spitch,
(size_t)width, (size_t)height));
return RAD_OK;
}
int d_memset_async(void* dst, int value, int64_t bytes, RadStream st) {
RAD_TRY(check_stream(st, "rad_memset_async"));
if (bytes == 0) return RAD_OK;
if (!dst || bytes < 0) {
device_set_error("rad_memset_async(%p, %lld): invalid argument", dst, (long long)bytes);
return RAD_E_INVAL;
}
/* The runtime fills pageable memory too; a card's contract does not (device.h note 1). */
if (ptr_kind(dst) == sycl::usm::alloc::unknown) {
device_set_error("rad_memset_async(%p): the destination is not device-accessible "
"(pageable host memory)", dst);
return RAD_E_UNSUPPORTED;
}
SYCL_TRY("rad_memset_async", as_stream(st)->q.memset(dst, value & 0xff, (size_t)bytes));
return RAD_OK;
}
/* The list is read here, at the call. The contract (device.h) requires it unchanged until the
* stream passes the copy, so reading it early copies the same bytes. */
int d_memcpy_ranges_async(void* dst, const void* src, int64_t prefix, const RadCopyRange* ranges,
int n, RadStream st) {
RAD_TRY(check_stream(st, "rad_memcpy_ranges_async"));
/* The card's copy kernel moves 16-byte pieces (aql.cpp), and the host backend refuses what it
* cannot copy; the same calls are refused here, so the three backends agree. */
if (!dst || !src || prefix < 0 || (prefix & 15) || n < 0 || (n > 0 && !ranges)) {
device_set_error("rad_memcpy_ranges_async(%p <- %p, prefix %lld (a multiple of 16), %d "
"ranges): invalid argument", dst, src, (long long)prefix, n);
return RAD_E_INVAL;
}
if (prefix == 0 && n == 0) return RAD_OK;
if (((uintptr_t)dst | (uintptr_t)src) & 15) {
device_set_error("rad_memcpy_ranges_async(%p <- %p): both bases must be 16-byte aligned",
dst, src);
return RAD_E_UNSUPPORTED;
}
sycl::queue& q = as_stream(st)->q;
char* d = (char*)dst;
const char* s = (const char*)src;
SYCL_TRY("rad_memcpy_ranges_async", {
if (prefix > 0) q.memcpy(d, s, (size_t)prefix);
for (int i = 0; i < n; ++i)
if (ranges[i].bytes > 0)
q.memcpy(d + ranges[i].dst, s + ranges[i].src, (size_t)ranges[i].bytes);
});
return RAD_OK;
}
/* ------------------------------------------------------------------ gates
*
* A gate is a one-work-item kernel that spins until a flag in pinned host memory turns 1; the
* in-order queue holds everything behind it. rad_gate_open sets the flag. The flag's memory is
* freed only once the kernel has finished (reaped on later gate calls), since the kernel may still
* be reading it when the host opens. A gate held for seconds can trip the driver's job timeout;
* rad-kbench holds one for a batch. */
struct SyclGate {
uint32_t* flag = nullptr;
SyclStream* s = nullptr;
sycl::event spin;
};
std::mutex g_gate_m;
std::vector<std::pair<sycl::event, uint32_t*>> g_gate_graveyard;
void gate_reap() {
std::lock_guard<std::mutex> lk(g_gate_m);
for (size_t i = 0; i < g_gate_graveyard.size();) {
bool done = true;
try {
done = event_done(g_gate_graveyard[i].first);
} catch (const sycl::exception&) {
}
if (!done) { ++i; continue; }
d_free(g_gate_graveyard[i].second, RAD_MEM_HOST_PINNED);
g_gate_graveyard[i] = g_gate_graveyard.back();
g_gate_graveyard.pop_back();
}
}
int d_stream_gate(RadStream st, void** out) {
RAD_TRY(check_stream(st, "rad_stream_gate"));
if (!out) return RAD_E_INVAL;
gate_reap();
SyclStream* s = as_stream(st);
auto* g = new (std::nothrow) SyclGate();
uint32_t* flag = (uint32_t*)d_alloc(64, RAD_MEM_HOST_PINNED);
if (!g || !flag) {
delete g;
if (flag) d_free(flag, RAD_MEM_HOST_PINNED);
device_set_error("rad_stream_gate: out of memory");
return RAD_E_NOMEM;
}
*flag = 0;
try {
g->spin = s->q.single_task([=] {
sycl::atomic_ref<uint32_t, sycl::memory_order::relaxed, sycl::memory_scope::system,
sycl::access::address_space::global_space> f(*flag);
while (f.load() == 0) {
}
sycl::atomic_fence(sycl::memory_order::acquire, sycl::memory_scope::system);
});
} catch (const sycl::exception& e) {
delete g;
d_free(flag, RAD_MEM_HOST_PINNED);
return sycl_fail(e, "rad_stream_gate");
}
g->flag = flag;
g->s = s;
++s->gates;
*out = g;
return RAD_OK;
}
int d_gate_open(void* p) {
auto* g = (SyclGate*)p;
if (!g || !g->flag) return RAD_E_INVAL;
std::atomic_ref<uint32_t>(*g->flag).store(1, std::memory_order_release);
--g->s->gates;
{
std::lock_guard<std::mutex> lk(g_gate_m);
g_gate_graveyard.emplace_back(g->spin, g->flag);
}
delete g;
return RAD_OK;
}
/* A Level Zero queue has no fixed depth, so nothing behind a gate waits for room; the figure only
* bounds how far a caller runs ahead. */
int64_t d_gate_room(RadStream st) { return st ? 4096 : 0; }
const DeviceBackend g_sycl = {
.name = "sycl",
.count = d_count, .set = d_set, .props = d_props, .enable_peer = d_enable_peer,
.alloc = d_alloc, .free = d_free, .host_ptr = d_host_ptr, .device_ptr = d_device_ptr,
.stream_create = d_stream_create, .stream_destroy = d_stream_destroy,
.stream_sync = d_stream_sync,
.event_create = d_event_create, .event_destroy = d_event_destroy,
.event_record = d_event_record, .event_wait = d_event_wait, .event_query = d_event_query,
.event_sync = d_event_sync, .event_elapsed_ms = d_event_elapsed_ms,
.host_wrote = d_host_wrote,
.memcpy_async = d_memcpy_async, .memcpy_2d_async = d_memcpy_2d_async,
.memset_async = d_memset_async, .memcpy_ranges_async = d_memcpy_ranges_async,
/* memcpy_list_async, link_hold, link_gate: null (dispatch.cpp copies segment by segment and
* holds nothing). Recorded passes, elastic memory: null. */
.vram_used = d_vram_used,
/* code_mark / code_runs: null for now, so every plugin runs; a build with libr4d beside the
* SYCL backend is refused at configure (docs/SYCL_PORTING.md §4.5). */
.integrated = d_integrated,
.peer_access = d_peer_access,
.pci_address = d_pci_address,
.runtime_version = d_runtime_version,
/* Expert prefetch: null. */
.stream_gate = d_stream_gate, .gate_open = d_gate_open, .gate_room = d_gate_room,
};
} /* namespace */
extern const SyclHost* g_sycl_host; /* sycl_host.cpp */
} /* namespace rad */
extern "C" __attribute__((visibility("default")))
const rad::DeviceBackend* rad_sycl_backend(const rad::SyclHost* host) {
if (!host || host->version != rad::kSyclHostVersion) {
std::fprintf(stderr, "librad_sycl: the engine's host table is version %u, this library "
"reads %u; rebuild them together\n",
host ? host->version : 0u, rad::kSyclHostVersion);
return nullptr;
}
rad::g_sycl_host = host;
if (rad::rt().devs.empty()) {
/* Supported configuration (host backend); dispatch.cpp logs it at Info. */
RAD_DEBUG("device: no Level Zero GPU visible to SYCL");
return nullptr;
}
return &rad::g_sycl;
}
#endif /* SYCL_LANGUAGE_VERSION */