/* 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 #include #include #include #include #include #include #include #include #include #include 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 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 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 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()) { 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()); 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(); } 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() ? 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(); 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(); /* The sub-group the kernel libraries use: 16 where offered (Xe2's native width). */ const std::vector sg = d.get_info(); 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(); const int64_t fr = free_bytes(d); out->vram_free = fr >= 0 ? fr : out->vram_bytes; out->lds_bytes = (int64_t)d.get_info(); }); 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()); 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().c_str(), d.get_info().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()); *out = total - fr; return RAD_OK; } /* ------------------------------------------------------------------ memory * * Pinned host memory (RAD_MEM_HOST_PINNED and _MAPPED) is SYCL's malloc_host: USM host memory * the runtime knows, which kernels and the copy engines reach through the driver's own mapping. * Nothing the device touches is plain system memory. Ordinary pages registered with * prepare_for_device_copy were used before, so that O_DIRECT could read into them; the device then * reaches them through the xe driver's shared virtual memory, which may migrate the pages into * VRAM, and on kernel 7.0 the CPU fault that moves such a page back can oops the kernel * (drm_pagemap_zdd_destroy from __drm_pagemap_migrate_to_ram). O_DIRECT cannot read into * malloc_host pages (EFAULT, the driver maps them itself), so DirectFile bounces those transfers * (directio.cpp). */ /* Device bytes this process holds through rad_dev_alloc, for the room check's message. */ std::atomic g_device_bytes{0}; std::mutex g_dev_sizes_m; std::map 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 lk(g_dev_sizes_m); g_dev_sizes[(uintptr_t)p] = bytes; } break; case RAD_MEM_HOST_PINNED: case RAD_MEM_HOST_MAPPED: { /* USM host memory (see above): one address on both sides, so host_ptr and * device_ptr are the pointer itself. Page-aligned and whole pages, as the * RAD_ALIGN_UNIT pools and the file tier's extents expect. */ const size_t n = (size_t)((bytes + 4095) / 4096 * 4096); p = sycl::aligned_alloc_host(4096, n, *rt().ctx); 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 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: { sycl::usm::alloc k = sycl::usm::alloc::unknown; try { k = sycl::get_pointer_type(p, *rt().ctx); } catch (const sycl::exception&) { } if (k != sycl::usm::alloc::host) { RAD_WARN("rad_dev_free(%p): not pinned memory this backend gave out; leaked " "rather than freed with the wrong allocator", p); break; } try { sycl::free(p, *rt().ctx); } catch (const sycl::exception& e) { RAD_WARN("device: rad_dev_free(%p): %s", p, e.what()); } 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, host or shared memory, or unknown (pageable). */ sycl::usm::alloc ptr_kind(const void* p) { 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; char* stage = nullptr; /* rad_memcpy_ranges_async's device copy of host sources */ size_t stage_n = 0; 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()); } if (s->stage) sycl::free(s->stage, s->q); 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; } 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 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 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_status::complete; } int d_event_query(RadEvent ev) { if (!ev) return RAD_E_INVAL; auto* e = (SyclEvent*)ev; std::lock_guard 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 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 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(); }); 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 */ /* A copy with a side in pageable host memory (a std::vector, the stack) goes through a bounce of * USM host memory, and synchronously: handed such a pointer, the runtime may reach it through the * driver's shared virtual memory, which the backend keeps out of (see memory, above). Rare -- the * engine copies through pinned buffers -- so the wait costs nothing on the step path. `span` is * the bytes from each base the copy can touch; `run` makes the copy with the bounce standing in * for the pageable side(s). */ bool is_pageable(const void* p) { return ptr_kind(p) == sycl::usm::alloc::unknown; } template void bounced(sycl::queue& q, void* dst, const void* src, size_t span, Run run) { const bool pd = is_pageable(dst), ps = is_pageable(src); char* bd = pd ? (char*)sycl::malloc_host(span, q) : nullptr; char* bs = ps ? (char*)sycl::malloc_host(span, q) : nullptr; if ((pd && !bd) || (ps && !bs)) { if (bd) sycl::free(bd, q); if (bs) sycl::free(bs, q); throw sycl::exception(sycl::make_error_code(sycl::errc::memory_allocation), "bounce for pageable host memory"); } if (bs) std::memcpy(bs, src, span); if (bd) std::memcpy(bd, dst, span); /* bytes between rows of a 2-D copy stay as they were */ try { run(bd ? (void*)bd : dst, bs ? (const void*)bs : src); q.wait_and_throw(); } catch (...) { if (bd) sycl::free(bd, q); if (bs) sycl::free(bs, q); throw; } if (bd) std::memcpy(dst, bd, span); if (bd) sycl::free(bd, q); if (bs) sycl::free(bs, q); } 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::queue& q = as_stream(st)->q; if (is_pageable(dst) || is_pageable(src)) { SYCL_TRY("rad_memcpy_async", bounced(q, dst, src, (size_t)bytes, [&](void* d, const void* s) { q.memcpy(d, s, (size_t)bytes); })); return async_status("rad_memcpy_async"); } SYCL_TRY("rad_memcpy_async", 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::queue& q = as_stream(st)->q; if (is_pageable(dst) || is_pageable(src)) { /* One span for both sides, the larger pitch's. */ const size_t span = (size_t)(std::max(dpitch, spitch) * (height - 1) + width); SYCL_TRY("rad_memcpy_2d_async", bounced(q, dst, src, span, [&](void* d, const void* s) { q.ext_oneapi_memcpy2d(d, (size_t)dpitch, s, (size_t)spitch, (size_t)width, (size_t)height); })); return async_status("rad_memcpy_2d_async"); } SYCL_TRY("rad_memcpy_2d_async", 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 prefix as one copy, then one kernel in which work-group i copies range i in 4-byte words * (ranges are only 4-byte aligned), as the HIP card's aql_copy_ranges does. The list is read by the * kernel when it runs: it may live in device memory, or be written by earlier work on the stream * (rad-kbench's timer keeps it on the card). The in-order queue puts the ranges after the prefix, * so a range over the prefix wins, which a single kernel copying both at once would leave to * scheduling. */ constexpr size_t kRangeWg = 256; constexpr int kRangeWords = 16; 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; } if (n > 0 && is_pageable(dst)) { /* The ranges are written by a kernel, which pageable memory is not open to (as for * rad_memset_async, device.h note 1). */ device_set_error("rad_memcpy_ranges_async(%p): the destination is not device-accessible " "(pageable host memory)", dst); return RAD_E_UNSUPPORTED; } SyclStream* ss = as_stream(st); sycl::queue& q = ss->q; char* d = (char*)dst; const char* s = (const char*)src; SYCL_TRY("rad_memcpy_ranges_async", { if (prefix > 0) { if (is_pageable(d) || is_pageable(s)) bounced(q, d, s, (size_t)prefix, [&](void* dd, const void* ff) { q.memcpy(dd, ff, (size_t)prefix); }); else q.memcpy(d, s, (size_t)prefix); } /* Sources and ranges in host memory (the step upload's pinned staging): read by the copy * kernel they cost a link round trip a load -- 650 us a call over a PCIe x1 link -- so * their span and the range list cross first in one transfer each, into a device buffer * of the stream's (in order, so the next call's copy waits for this kernel). */ /* Either in host memory: the source span, the range list or both cross into the stage. * A pageable one goes through the bounce (see bounced), so the kernel only ever reads * device memory. */ const bool host_src = n > 0 && ptr_kind(src) != sycl::usm::alloc::device; const bool host_rng = n > 0 && ptr_kind(ranges) != sycl::usm::alloc::device; if (host_src || host_rng) { int64_t lo = INT64_MAX, hi = 0; for (int i = 0; i < n; ++i) { lo = std::min(lo, ranges[i].src); hi = std::max(hi, ranges[i].src + ranges[i].bytes); } lo &= ~(int64_t)15; const size_t span = host_src ? (size_t)(hi - lo + 15) / 16 * 16 : 0; const size_t rb = host_rng ? (size_t)n * sizeof(RadCopyRange) : 0; if (ss->stage_n < span + rb) { q.wait(); if (ss->stage) sycl::free(ss->stage, q); ss->stage_n = (span + rb) * 2; ss->stage = (char*)sycl::malloc_device(ss->stage_n, q); if (!ss->stage) { ss->stage_n = 0; throw sycl::exception(sycl::make_error_code(sycl::errc::memory_allocation), "range staging"); } } auto up = [&](void* d, const void* from, size_t bytes) { if (is_pageable(from)) bounced(q, d, from, bytes, [&](void* dd, const void* ff) { q.memcpy(dd, ff, bytes); }); else q.memcpy(d, from, bytes); }; if (host_src) { up(ss->stage, s + lo, (size_t)(hi - lo)); s = ss->stage - lo; } if (host_rng) { up(ss->stage + span, ranges, rb); ranges = (const RadCopyRange*)(ss->stage + span); } } if (n > 0) { q.parallel_for(sycl::nd_range<1>{(size_t)n * kRangeWg, kRangeWg}, [=](sycl::nd_item<1> it) { const size_t t = it.get_local_id(0); const RadCopyRange r = ranges[it.get_group(0)]; const uint32_t* s4 = (const uint32_t*)(s + r.src); uint32_t* d4 = (uint32_t*)(d + r.dst); const int64_t nw = r.bytes / 4; for (int64_t base = 0; base < nw; base += (int64_t)kRangeWg * kRangeWords) { uint32_t v[kRangeWords]; for (int k = 0; k < kRangeWords; ++k) { const int64_t w = base + (int64_t)k * kRangeWg + (int64_t)t; v[k] = s4[w < nw ? w : nw - 1]; } for (int k = 0; k < kRangeWords; ++k) { const int64_t w = base + (int64_t)k * kRangeWg + (int64_t)t; if (w < nw) d4[w] = v[k]; } } }); } }); return RAD_OK; } /* ------------------------------------------------------------------ gates * * None (rad_stream_gate reports the backend has none; rad-kbench then times ungated). A gate's * spinning kernel needs a flag the host can flip while it runs: on the Arc Pro B65 it never sees a * store to host USM, and plain system memory, which it does see, goes through the driver's shared * virtual memory (see memory, above). A device flag written by a copy from another queue deadlocks * as soon as a copy is queued behind the gate (both share the copy engine), and a kernel on another * queue does not run beside the spinning one. */ 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. */ }; } /* 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 */