diff --git a/CMakeLists.txt b/CMakeLists.txt index da4380b9..1c99ee37 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -84,6 +84,38 @@ elseif(NOT RAD_HIPCC) "/opt/rocm/llvm/bin and $ROCM_PATH.") endif() +# ---------------------------------------------------------------- SYCL detection +# The Intel GPU backend (docs/SYCL_PORTING.md). Off by default. SYCL code is compiled and linked by +# icpx in a sub-build of its own (sycl/CMakeLists.txt, added below), so everything else stays on +# this project's compiler: a SYCL build's host code is the default build's. +# +# RAD_SYCL_TARGETS names the AOT targets (icpx -fsycl-targets spelling); the default is the Arc Pro +# B65's Battlemage G31. +set(RAD_SYCL "OFF" CACHE STRING "ON | OFF | AUTO -- build the SYCL (Intel GPU) backend with icpx") +set_property(CACHE RAD_SYCL PROPERTY STRINGS ON OFF AUTO) +set(RAD_SYCL_TARGETS "intel_gpu_bmg_g31" CACHE STRING "AOT targets for SYCL device code") +set(RAD_SYCL_FOUND OFF) +if(NOT RAD_SYCL STREQUAL "OFF") + find_program(RAD_ICPX icpx HINTS ENV CMPLR_ROOT PATH_SUFFIXES bin + PATHS /opt/intel/oneapi/compiler/latest/bin) + if(RAD_ICPX) + set(RAD_SYCL_FOUND ON) + elseif(RAD_SYCL STREQUAL "ON") + message(FATAL_ERROR "RAD_SYCL=ON but icpx was not found. Install the oneAPI DPC++ compiler, or " + "source /opt/intel/oneapi/setvars.sh first.") + endif() +endif() +if(RAD_SYCL_FOUND AND RAD_HIP_FOUND) + # Both could be compiled side by side in principle; nothing has tested one engine holding both, + # so a build picks one (docs/SYCL_PORTING.md §4.5). + message(FATAL_ERROR + "radiance: RAD_SYCL and the HIP backend are both on. One build holds one device backend: " + "configure the SYCL build with -DRAD_WITH_HIP=OFF (build.sh --sycl does).") +endif() +if(RAD_SYCL_FOUND) + message(STATUS "radiance: SYCL backend ON, ${RAD_ICPX}, targets ${RAD_SYCL_TARGETS}") +endif() + # ASan + UBSan for host code only. AMD's amdgcn ASan needs xnack+ for its page-fault-based shadow, # and RDNA has no xnack, so the generator expressions keep the flags off HIP. Device kernels rely on # rad-kbench's red zones instead: a poisoned margin around every operand and scratch allocation, @@ -286,6 +318,31 @@ if(NOT RAD_WITH_FFMPEG STREQUAL "OFF") endif() endif() +# ---------------------------------------------------------------- the icpx sub-build +# sycl/ is its own CMake project, configured with icpx, so -fsycl code never meets this project's +# compiler. rad_core links librad_sycl.so (the device backend) as an imported library. +if(RAD_SYCL_FOUND) + include(ExternalProject) + set(RAD_SYCL_BINARY_DIR ${CMAKE_BINARY_DIR}/sycl) + ExternalProject_Add(rad_sycl_build + SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/sycl + BINARY_DIR ${RAD_SYCL_BINARY_DIR} + CMAKE_ARGS -DCMAKE_CXX_COMPILER=${RAD_ICPX} + -DCMAKE_BUILD_TYPE=${CMAKE_BUILD_TYPE} + -DRAD_SOURCE_DIR=${CMAKE_CURRENT_SOURCE_DIR} + -DRAD_SYCL_TARGETS=${RAD_SYCL_TARGETS} + -DCMAKE_EXPORT_COMPILE_COMMANDS=ON + BUILD_ALWAYS ON + INSTALL_COMMAND "" + BUILD_BYPRODUCTS ${RAD_SYCL_BINARY_DIR}/librad_sycl.so + USES_TERMINAL_BUILD ON) + add_library(rad_sycl_rt SHARED IMPORTED GLOBAL) + set_target_properties(rad_sycl_rt PROPERTIES + IMPORTED_LOCATION ${RAD_SYCL_BINARY_DIR}/librad_sycl.so + IMPORTED_NO_SONAME ON) + add_dependencies(rad_sycl_rt rad_sycl_build) +endif() + add_subdirectory(vendor) add_subdirectory(core) # Kernel plugins, one root directory each. Each holds its kernels, row table and layouts and links diff --git a/CMakePresets.json b/CMakePresets.json index ee5eb945..4222aa6a 100644 --- a/CMakePresets.json +++ b/CMakePresets.json @@ -21,12 +21,20 @@ "inherits": "default", "binaryDir": "${sourceDir}/build-tsan", "cacheVariables": { "RAD_TSAN": "ON", "RAD_ASAN": "OFF", "RAD_WITH_HIP": "OFF" } + }, + { + "name": "sycl", + "displayName": "The Intel GPU (SYCL) backend, its code built by icpx, in build-sycl/", + "inherits": "default", + "binaryDir": "${sourceDir}/build-sycl", + "cacheVariables": { "RAD_SYCL": "ON", "RAD_WITH_HIP": "OFF" } } ], "buildPresets": [ { "name": "default", "configurePreset": "default" }, { "name": "asan", "configurePreset": "asan" }, - { "name": "tsan", "configurePreset": "tsan" } + { "name": "tsan", "configurePreset": "tsan" }, + { "name": "sycl", "configurePreset": "sycl" } ], "testPresets": [ { @@ -59,6 +67,14 @@ "inherits": "base", "filter": { "include": { "label": "^gpu$" } } }, + { + "name": "sycl", + "displayName": "The tests that need an Intel GPU, one at a time (load the oneAPI environment first)", + "inherits": "base", + "configurePreset": "sycl", + "filter": { "include": { "label": "^sycl$" } }, + "execution": { "jobs": 1, "noTestsAction": "error" } + }, { "name": "perf", "displayName": "The wall-clock checks, one at a time", diff --git a/build.sh b/build.sh index f2abd0ba..ec5f64cd 100755 --- a/build.sh +++ b/build.sh @@ -15,6 +15,8 @@ # ./build.sh --no-hip force the host backend even where hipcc exists # ./build.sh --asan AddressSanitizer + UBSan, host backend, in build-asan/ # ./build.sh --tsan ThreadSanitizer, host backend, in build-tsan/ +# ./build.sh --sycl the Intel GPU (SYCL) backend, in build-sycl/: the engine as usual, its +# SYCL code built by icpx (oneAPI); docs/SYCL_PORTING.md # ./build.sh --debug CMAKE_BUILD_TYPE=Debug # ./build.sh -b DIR build in DIR instead of build/ (or build-asan/, build-tsan/) # @@ -33,6 +35,7 @@ while [ $# -gt 0 ]; do --no-hip) CMAKE_ARGS="$CMAKE_ARGS -DRAD_WITH_HIP=OFF" ;; --asan) SAN=asan ;; --tsan) SAN=tsan ;; + --sycl) SAN=sycl ;; --debug) CMAKE_ARGS="$CMAKE_ARGS -DCMAKE_BUILD_TYPE=Debug" ;; -b) shift; BUILD="$1" ;; *) echo "build.sh: unknown option $1" >&2; exit 2 ;; @@ -47,6 +50,9 @@ case "$SAN" in BUILD=${BUILD:-build-asan} ;; tsan) CMAKE_ARGS="$CMAKE_ARGS -DRAD_TSAN=ON -DRAD_ASAN=OFF -DRAD_WITH_HIP=OFF" BUILD=${BUILD:-build-tsan} ;; + # Not a sanitiser, but likewise a configuration with a directory of its own. + sycl) CMAKE_ARGS="$CMAKE_ARGS -DRAD_SYCL=ON -DRAD_WITH_HIP=OFF" + BUILD=${BUILD:-build-sycl} ;; *) BUILD=${BUILD:-build} ;; esac [ "$CLEAN" = 1 ] && rm -rf "$BUILD" diff --git a/core/CMakeLists.txt b/core/CMakeLists.txt index ddac9118..b3e137a0 100644 --- a/core/CMakeLists.txt +++ b/core/CMakeLists.txt @@ -37,6 +37,14 @@ if(RAD_FFMPEG_FOUND) target_link_libraries(rad_core PUBLIC PkgConfig::RAD_FFMPEG) endif() +if(RAD_SYCL_FOUND) + # The SYCL device backend lives in librad_sycl.so, built by icpx (sycl/CMakeLists.txt); + # device/sycl.cpp compiles to nothing here. The rpath finds it in the build tree. + target_compile_definitions(rad_core PUBLIC RAD_HAVE_SYCL=1) + target_link_libraries(rad_core PUBLIC rad_sycl_rt) + target_link_options(rad_core INTERFACE "LINKER:-rpath,${RAD_SYCL_BINARY_DIR}") +endif() + if(RAD_HIP_FOUND) target_compile_definitions(rad_core PUBLIC RAD_HAVE_HIP=1) target_link_libraries(rad_core PUBLIC ${RAD_HIP_RUNTIME} ${RAD_HSA_RUNTIME}) diff --git a/core/device/device.h b/core/device/device.h index 0d9655ce..fdb9e2b3 100644 --- a/core/device/device.h +++ b/core/device/device.h @@ -156,7 +156,7 @@ typedef void* RadTape; * no VRAM tier), the selector (only RAD_DOMAIN_HOST can run) and tests that skip device-only * assertions. */ bool device_is_host(); -const char* device_backend_name(); /* "host" or "aql" */ +const char* device_backend_name(); /* "host", "aql" or "sycl" */ /* ------------------------------------------------------------------ two contract notes * diff --git a/core/device/dispatch.cpp b/core/device/dispatch.cpp index cf075dd6..6a366351 100644 --- a/core/device/dispatch.cpp +++ b/core/device/dispatch.cpp @@ -8,6 +8,9 @@ */ #include "device.h" #include "../rad_internal.h" +#if defined(RAD_HAVE_SYCL) && RAD_HAVE_SYCL +#include "sycl_host.h" +#endif #include #include @@ -84,7 +87,33 @@ static void warn_cwsr_off() { static DeviceBackend g_host_beside_hip; #endif +#if defined(RAD_HAVE_SYCL) && RAD_HAVE_SYCL +/* What librad_sycl.so reaches of the engine (sycl_host.h). */ +static const SyclHost g_sycl_host = { + kSyclHostVersion, + [] { return (int)log_level(); }, + [](int level, const char* file, int line, const char* msg) { + log_emit((Log)level, file, line, "%s", msg); + }, + [](const char* msg) { device_set_error("%s", msg); }, +}; +#endif + static const DeviceBackend* select_backend() { +#if defined(RAD_HAVE_SYCL) && RAD_HAVE_SYCL + /* A SYCL build has no HIP (configure refuses both, docs/SYCL_PORTING.md §4.5). */ + if (const DeviceBackend* b = rad_sycl_backend(&g_sycl_host)) { + RAD_INFO("device: SYCL backend, %d device(s) [%s]", b->count(), + device_inventory(b).c_str()); + return b; + } + /* A warning, not Info: on a machine whose card is there, this is the GPU being skipped. The + * usual cause is a missing oneAPI environment, since the runtime loads its Level Zero adapter + * and that adapter's libraries (libumf) from the oneAPI tree at run time. */ + RAD_WARN("device: built with SYCL but no Level Zero GPU is visible -- using the host backend " + "(CPU). If this machine has an Intel GPU, load the oneAPI environment first " + "(. /opt/intel/oneapi/setvars.sh); ONEAPI_DEVICE_SELECTOR may also be hiding it"); +#endif #if defined(RAD_HAVE_HIP) && RAD_HAVE_HIP if (const DeviceBackend* b = aql_backend_if_present()) { RAD_INFO("device: AQL backend, %d device(s) [%s]", b->count(), diff --git a/core/device/sycl.cpp b/core/device/sycl.cpp new file mode 100644 index 00000000..55ddf7b6 --- /dev/null +++ b/core/device/sycl.cpp @@ -0,0 +1,851 @@ +/* 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 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 g_pinned; /* base -> bytes */ + +bool in_pinned(const void* p) { + const uintptr_t a = (uintptr_t)p; + std::lock_guard 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 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: { + /* 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 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 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 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 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 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 */ + +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> g_gate_graveyard; + +void gate_reap() { + std::lock_guard 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 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(*g->flag).store(1, std::memory_order_release); + --g->s->gates; + { + std::lock_guard 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 */ diff --git a/core/device/sycl_host.cpp b/core/device/sycl_host.cpp new file mode 100644 index 00000000..b1b060e2 --- /dev/null +++ b/core/device/sycl_host.cpp @@ -0,0 +1,41 @@ +/* sycl_host.cpp -- inside librad_sycl.so: the engine's logger and error slot, over the table the + * engine hands rad_sycl_backend() (sycl_host.h). Built by the icpx sub-build; in the engine's own + * build (core/CMakeLists.txt globs this directory) it compiles to nothing. */ +#if defined(SYCL_LANGUAGE_VERSION) + +#include "sycl_host.h" +#include "../rad_internal.h" + +#include +#include + +namespace rad { + +const SyclHost* g_sycl_host = nullptr; + +Log log_level() { + return g_sycl_host ? (Log)g_sycl_host->log_level() : Log::Warn; +} + +void log_emit(Log l, const char* file, int line, const char* fmt, ...) { + char buf[2048]; + va_list ap; + va_start(ap, fmt); + vsnprintf(buf, sizeof buf, fmt, ap); + va_end(ap); + if (g_sycl_host) g_sycl_host->log((int)l, file, line, buf); + else std::fprintf(stderr, "%s\n", buf); +} + +void device_set_error(const char* fmt, ...) { + char buf[1024]; + va_list ap; + va_start(ap, fmt); + vsnprintf(buf, sizeof buf, fmt, ap); + va_end(ap); + if (g_sycl_host) g_sycl_host->set_error(buf); +} + +} /* namespace rad */ + +#endif /* SYCL_LANGUAGE_VERSION */ diff --git a/core/device/sycl_host.h b/core/device/sycl_host.h new file mode 100644 index 00000000..4c20f0bd --- /dev/null +++ b/core/device/sycl_host.h @@ -0,0 +1,32 @@ +/* sycl_host.h -- the seam between the engine and librad_sycl.so, the SYCL device backend. + * + * The SYCL backend is compiled and linked by icpx into a shared library of its own, while the + * engine stays a GCC build (docs/SYCL_PORTING.md §4.5, docs/SYCL_PROGRESS.md D6). The library + * reaches the engine's logger and error slot through this table, so it links nothing of the + * engine's, and the engine reaches the library through one C entry point. + * + * Inside the library, sycl_host.cpp defines rad::log_level, rad::log_emit and + * rad::device_set_error over the table, so the backend's source uses rad_internal.h's macros as + * hip.cpp does. Bump kSyclHostVersion on any change to the table. + */ +#pragma once +#include + +namespace rad { + +struct DeviceBackend; + +constexpr uint32_t kSyclHostVersion = 1; + +struct SyclHost { + uint32_t version; /* kSyclHostVersion */ + int (*log_level)(void); /* rad::log_level() as an int */ + void (*log)(int level, const char* file, int line, const char* msg); + void (*set_error)(const char* msg); /* rad::device_set_error("%s", msg) */ +}; + +} /* namespace rad */ + +/* The backend, or null when no Level Zero GPU is visible or `host` is of another version. The + * table must outlive the backend. */ +extern "C" const rad::DeviceBackend* rad_sycl_backend(const rad::SyclHost* host); diff --git a/core/engine_bringup.cpp b/core/engine_bringup.cpp index 59689caa..0cf31b7e 100644 --- a/core/engine_bringup.cpp +++ b/core/engine_bringup.cpp @@ -1225,6 +1225,7 @@ int Engine::declare() { { std::vector rep; for (auto& r : ranks_) rep.push_back(miss_report(r->program, device_is_host())); + const bool sycl = std::strcmp(device_backend_name(), "sycl") == 0; bool same = true; for (size_t i = 1; i < rep.size(); ++i) if (!(rep[i] == rep[0])) same = false; @@ -1237,9 +1238,23 @@ int Engine::declare() { "one of them cannot run:", who.c_str(), rep[i].device.size()); for (const std::string& l : rep[i].device) RAD_ERR(" %s", l.c_str()); } - if (!rep[i].host_only.empty()) RAD_INFO("%s", rep[i].host_only.c_str()); + if (!rep[i].host_only.empty()) { + if (sycl) RAD_ERR("%s", rep[i].host_only.c_str()); + else RAD_INFO("%s", rep[i].host_only.c_str()); + } if (!rep[i].host.empty()) RAD_INFO("%s", rep[i].host.c_str()); } + /* On the SYCL backend a host-only op is a hole, not a placement: the Intel backend runs + * its ops on the card or not at all, so a kernel it lacks stops the start by name rather + * than running that op on the CPU (docs/SYCL_PORTING.md §4.4). --debug-graph serves + * nothing and prints the graph regardless. */ + if (sycl && !cfg_.debug_graph) + for (const MissReport& m : rep) + if (!m.host_only.empty()) { + RAD_ERR("not starting: on the SYCL backend every op runs on the card, and the " + "op(s) above have no device kernel in the loaded libraries"); + return RAD_E_UNSUPPORTED; + } /* A hole refuses startup: the bands come from this run's limits, so a request can land in * one, and that step would fail at issue and stop the engine. --debug-graph serves nothing, * so it continues to print the graph and reports the holes in its exit status @@ -3306,6 +3321,14 @@ int Engine::start() { devnote_ = devnote; if (s < 0) { RAD_ERR("no usable device"); return s; } + /* One card on the SYCL backend (docs/SYCL_PORTING.md §4.7): it has no all-reduce kernels, and a + * second rank would wait on one. */ + if (cfg_.tp > 1 && std::strcmp(device_backend_name(), "sycl") == 0) { + RAD_ERR("--tp %d: the SYCL (Intel GPU) backend serves one card; tensor parallelism needs " + "all-reduce kernels it does not have. Use --tp 1", cfg_.tp); + return RAD_E_UNSUPPORTED; + } + if ((int)devs.size() < cfg_.tp) { RAD_ERR("--tp %d needs %d devices of one architecture; %zu are usable [%s]", cfg_.tp, cfg_.tp, devs.size(), inventory.c_str()); diff --git a/core/runtime/wtab.cpp b/core/runtime/wtab.cpp index 360c88ef..8123ef27 100644 --- a/core/runtime/wtab.cpp +++ b/core/runtime/wtab.cpp @@ -15,7 +15,9 @@ int wtab_patch(const WtabPatch& p, RadStream s) { for (uint32_t i = 0; i < p.n; ++i) *p.dst[i] = p.val[i]; return RAD_OK; } -#if defined(RAD_HAVE_HIP) && RAD_HAVE_HIP +#if (defined(RAD_HAVE_HIP) && RAD_HAVE_HIP) || (defined(RAD_HAVE_SYCL) && RAD_HAVE_SYCL) + /* The launcher: wtab.hip on the AQL backend, wtab_sycl.cpp (in librad_sycl.so) on the SYCL + * one. A build holds one of the two. */ return rad_wtab_patch_launch(&p, (void*)s) == 0 ? RAD_OK : RAD_E_DEVICE; #else (void)s; diff --git a/core/runtime/wtab_sycl.cpp b/core/runtime/wtab_sycl.cpp new file mode 100644 index 00000000..d177b44f --- /dev/null +++ b/core/runtime/wtab_sycl.cpp @@ -0,0 +1,28 @@ +/* wtab_sycl.cpp -- the weight-table patch kernel under the SYCL backend: one work-item a write. See + * wtab.h; wtab.hip is the AMD twin. Built by icpx into librad_sycl.so; in the engine's own build + * (core/CMakeLists.txt globs this directory) it compiles to nothing. */ +#if defined(SYCL_LANGUAGE_VERSION) + +#include + +#include "rad_sycl.h" +#include "wtab.h" + +extern "C" __attribute__((visibility("default"))) +int rad_wtab_patch_launch(const rad::WtabPatch* p, void* stream) { + if (!p || p->n == 0) return 0; + sycl::queue* q = rad_sycl_queue((RadStream)stream); + if (!q) return -1; + const rad::WtabPatch w = *p; + try { + q->parallel_for(sycl::nd_range<1>{64, 64}, [=](sycl::nd_item<1> it) { + const uint32_t i = (uint32_t)it.get_local_id(0); + if (i < w.n) *w.dst[i] = w.val[i]; + }); + } catch (const sycl::exception&) { + return -1; + } + return 0; +} + +#endif /* SYCL_LANGUAGE_VERSION */ diff --git a/core/sched/advance.cpp b/core/sched/advance.cpp index ad87fa33..80ffe8af 100644 --- a/core/sched/advance.cpp +++ b/core/sched/advance.cpp @@ -15,7 +15,9 @@ int step_advance(const AdvanceArgs& a, RadStream s) { for (int i = 0; i < a.n_seq; ++i) adv_row(a, i); return RAD_OK; } -#if defined(RAD_HAVE_HIP) && RAD_HAVE_HIP +#if (defined(RAD_HAVE_HIP) && RAD_HAVE_HIP) || (defined(RAD_HAVE_SYCL) && RAD_HAVE_SYCL) + /* The launcher: advance.hip on the AQL backend, advance_sycl.cpp (in librad_sycl.so) on the + * SYCL one. A build holds one of the two. */ return rad_step_advance_launch(&a, (void*)s) == 0 ? RAD_OK : RAD_E_DEVICE; #else (void)s; diff --git a/core/sched/advance_sycl.cpp b/core/sched/advance_sycl.cpp new file mode 100644 index 00000000..50c0dfa6 --- /dev/null +++ b/core/sched/advance_sycl.cpp @@ -0,0 +1,39 @@ +/* advance_sycl.cpp -- the advance kernel under the SYCL backend: one work-item per row of the batch + * it patches, in stream order on the rank's queue. See advance.h; advance.hip is the AMD twin. + * + * Built by icpx into librad_sycl.so (sycl/CMakeLists.txt); core/CMakeLists.txt globs this directory + * into the engine, built without SYCL, where the file compiles to nothing. There is no chained form: + * chained launches are the AQL backend's (rad_dev_chain_enabled is 0 here). + */ +#if defined(SYCL_LANGUAGE_VERSION) + +#include + +#include "advance_impl.h" +#include "rad_sycl.h" + +namespace { + +constexpr int kThreads = 64; + +} // namespace + +extern "C" __attribute__((visibility("default"))) +int rad_step_advance_launch(const rad::AdvanceArgs* args, void* stream) { + if (!args || args->n_seq <= 0) return 0; + sycl::queue* q = rad_sycl_queue((RadStream)stream); + if (!q) return -1; + const rad::AdvanceArgs a = *args; + const size_t blocks = (size_t)((a.n_seq + kThreads - 1) / kThreads); + try { + q->parallel_for(sycl::nd_range<1>{blocks * kThreads, kThreads}, [=](sycl::nd_item<1> it) { + const int i = (int)it.get_global_id(0); + if (i < a.n_seq) rad::adv_row(a, i); + }); + } catch (const sycl::exception&) { + return -1; + } + return 0; +} + +#endif /* SYCL_LANGUAGE_VERSION */ diff --git a/docs/SYCL_PORTING.md b/docs/SYCL_PORTING.md index 9ca9e451..a169a03d 100644 --- a/docs/SYCL_PORTING.md +++ b/docs/SYCL_PORTING.md @@ -194,16 +194,17 @@ implementations are already behind it. So no wrapper is introduced and the HIP p | vtable entry | SYCL / Level Zero | |---|---| | `count`, `set`, `props` | GPU devices of the Level Zero platform; `props.arch` from `ext::oneapi::experimental::info::device::architecture` (`"intel_gpu_bmg_g31"`); `n_cu` = `max_compute_units` (160), `warp_size` = 16 (the sub-group the kernels use), `lds_bytes` = `local_mem_size`, `vram_free` from `ext::intel::info::device::free_memory` | -| `alloc` | `RAD_MEM_DEVICE` -> `malloc_device`; `HOST_PINNED` and `HOST_MAPPED` -> `malloc_host` (device-reachable, same address both sides, so `host_ptr`/`device_ptr` are identity); `HOST` -> plain `malloc` | -| streams | one in-order `sycl::queue` per stream on one shared `sycl::context`; `high_priority` -> `ext::oneapi::property::queue::priority_high` | -| events | `queue::ext_oneapi_submit_barrier()` returns the record; `event_wait` = `ext_oneapi_submit_barrier({e})` on the waiting queue (no host sync); `query` / `sync` on the event; `elapsed_ms` from profiling info (queues created with `enable_profiling`; its cost to be measured, and dropped if it shows) | +| `alloc` | `RAD_MEM_DEVICE` -> `malloc_device` behind a room check; `HOST_PINNED` and `HOST_MAPPED` -> page-aligned memory registered with `prepare_for_device_copy` (not `malloc_host`, which O_DIRECT cannot target; D10), same address both sides; `HOST` -> plain `malloc` | +| streams | one in-order `sycl::queue` per stream on one shared `sycl::context`; `high_priority` -> `ext::oneapi::property::queue::priority_high`; no `enable_profiling` unless `RADIANCE_SYCL_TIMING=1` (it costs ~20 us of host time a submission, D9) | +| events | `queue::ext_oneapi_submit_barrier()` returns the record; `event_wait` = `ext_oneapi_submit_barrier({e})` on the waiting queue (no host sync); `query` / `sync` on the event; `elapsed_ms` from profiling info, under `RADIANCE_SYCL_TIMING=1` only | | copies, fills | `queue::memcpy`, `memset`; 2-D copy as `ext_oneapi_copy2d` or a row loop; ranges and lists as one small kernel / a loop of copies | | `host_wrote` | nothing: USM host allocations are coherent for the device at submission | | `vram_used` | `ext::intel::info::device::free_memory` | | `pci_address` | `ext::intel::info::device::pci_address` | | `runtime_version` | the SYCL platform version string | | tapes | null at first; later `sycl_ext_oneapi_graph` (Phase 4, if submission overhead dominates decode) | -| vmem, DMA lane, link holds, rides, prefetch, gates | null (each a supported configuration) | +| gates | a one-work-item kernel spinning on a flag in pinned host memory | +| vmem, DMA lane, link holds, rides, prefetch | null (each a supported configuration) | `select_backend()` tries, in order: AQL (if built with HIP and an AMD card is visible), SYCL (if built with SYCL and a Level Zero GPU is visible), host. `RADIANCE_DEVICE_BACKEND=sycl|aql|host` (new) @@ -261,16 +262,17 @@ without weights already fail as holes. `--debug-graph` shows the resolution eith - `RAD_SYCL` (`OFF | ON | AUTO`, default **OFF**), `build.sh --sycl`, a `sycl` preset, a `sycl` ctest label (card tests, `SKIP_RETURN_CODE 77` without a Level Zero GPU, like `gpu`). -- **Compiler.** CMake has no SYCL language, and `-fsycl` sources need `icpx`. With `RAD_SYCL=ON` the - whole build uses `icpx` as `CMAKE_CXX_COMPILER` and only SYCL sources get `-fsycl` (with - `-fsycl` on the link of targets holding them). Configure refuses `RAD_SYCL=ON` with another C++ - compiler, naming the fix (`-DCMAKE_CXX_COMPILER=icpx`, which `build.sh --sycl` passes). - **`icpx` defaults to `-fp-model=fast`**; the SYCL build passes `-ffp-model=precise` to host code so - libref and libavx compute what they compute under GCC, and the host tier is run in the SYCL build - too to show it. The default build (GCC, `RAD_SYCL=OFF`) is unchanged. - *Fallback* if host code under `icpx` does not reproduce the GCC results: build the SYCL pieces - (`core/device/sycl.cpp` as a small C-ABI shared library, `libxe2`) as a separate CMake project - with `icpx` through `ExternalProject`, leaving the main build on GCC. +- **Compiler.** CMake has no SYCL language, and `-fsycl` sources need `icpx`. The first plan, the + whole build on `icpx`, failed: libavx calls `_pdep_u64` without `-mbmi2`, which GCC accepts and + clang refuses (`SYCL_PROGRESS.md` D6). So **the main build stays on its own compiler in every + configuration**, and the SYCL code is a separate CMake project, `sycl/`, configured with `icpx` + through `ExternalProject`: `librad_sycl.so` (the device backend with the core's SYCL kernels; + one C entry point, `rad_sycl_backend`, and a callback table for the engine's logger and error + slot, `core/device/sycl_host.h`) and later `libxe2.so`. Host code in a SYCL build is therefore the + default build's. `icpx` defaults to `-fp-model=fast`; the sub-build passes `-ffp-model=precise`. +- **Run time.** The SYCL runtime `dlopen`s its Level Zero adapter, which needs oneAPI's `umf/` + libraries, so the engine runs under the oneAPI environment (`. /opt/intel/oneapi/setvars.sh`). + Without it no GPU is visible and the engine warns that it is running on the CPU. - **HIP and SYCL in one build**: allowed in principle (HIP is its own CMake language), but untestable here (no ROCm). The first version refuses `RAD_SYCL=ON` together with a found HIP at configure time with a clear message; lifting that is a later change made on a machine with both. diff --git a/docs/SYCL_PROGRESS.md b/docs/SYCL_PROGRESS.md index 1c47ea12..ba6350e7 100644 --- a/docs/SYCL_PROGRESS.md +++ b/docs/SYCL_PROGRESS.md @@ -10,7 +10,7 @@ from it alone. |---|---| | 0 environment check | done | | 1 codebase study, `SYCL_PORTING.md` | done (`docs/SYCL_PORTING.md` §1-§3, Appendix A) | -| 2 design | written (`docs/SYCL_PORTING.md` §4); implementation next | +| 2 design | written (`docs/SYCL_PORTING.md` §4); device backend, build integration and core kernels done and passing `device_test` on the B65; `libxe2` skeleton next | | 3 correctness-first kernels | not started | | 4 performance | not started | | 5 broaden and finish | not started | @@ -136,10 +136,14 @@ present in `betterbench run --help`. --note backend=sycl --note gpu=arc-pro-b65 --note commit= ``` -Discord posting: **`~/.config/radiance-bench.env` does not exist, so `DISCORD_WEBHOOK_URL` is unset** -(checked 2026-10-23). Runs are recorded here without posting until the user creates that file. -`scripts/bench_report.sh` (quick run, parse `results.json` with `jq`, post, check the HTTP status) is -to be written at the first benchmarkable milestone, against a real `results.json`. +Discord posting: the user added `~/.config/radiance-bench.env` (mode 0600) on 2026-10-23; +`DISCORD_WEBHOOK_URL` loads from it (never printed or logged). The user also asked for +**screenshots of BetterBench's HTML report** to be sent to the webhook with each result. No headless +browser is installed (no chromium/firefox/wkhtmltoimage, no playwright); at the first benchmark, +install one outside the repo (e.g. playwright + chromium in `~/tools/betterbench-venv`) and have +`scripts/bench_report.sh` render the report to PNG and post it as a multipart attachment beside the +summary. `scripts/bench_report.sh` (quick run, parse `results.json` with `jq`, post, check the HTTP +status) is to be written at the first benchmarkable milestone, against a real `results.json`. Runs: none yet. Nothing is benchmarked before Milestone A passes its correctness checks. All runs are `--quick` (1 warmup, 5 passes): progress tracking, not publishable numbers. @@ -191,18 +195,53 @@ Planned use: Milestone A = `minicpm5-2b-bf16.rad` (blocked, item 1); Milestone B default build's, byte for byte. HIP + SYCL refused together at configure until a ROCm machine can test it. (§4.5) - D7: `advance` and `wtab` get SYCL launchers; `xprefetch` stays off. (§4.6) -- D8: `--tp > 1` refused at startup on the SYCL backend. (§4.7) +- D8: `--tp > 1` refused at startup on the SYCL backend, before the device-count check. (§4.7) +- D9 (2026-10-23): queues are made **without** `enable_profiling` unless `RADIANCE_SYCL_TIMING=1`. + Measured on the idle B65 (`scratchpad` probe `subcost.cpp`, 4000 trivial kernels): in-order + + profiling 24.4 us host time per `single_task`, 22.8 us per `parallel_for`; in-order without + profiling 4.5 / 4.4 us; `ext::oneapi::experimental::nd_launch` 4.0 us either way. At ~550 launches + per MiniCPM5 decode step that is 13 ms vs 2.5 ms. Without timing, `rad_event_elapsed_ms` refuses + and names the variable (`--profile-ops` and `rad-kbench` need it set). libxe2 launches with + `nd_launch`. (An earlier 50 us figure was measured while a -j8 build loaded the host.) +- D10 (2026-10-23): `RAD_MEM_HOST_PINNED` / `_MAPPED` are `posix_memalign` + `prepare_for_device_copy`, + not SYCL `malloc_host`: O_DIRECT into `malloc_host` fails with EFAULT (driver-mapped pages), and + the mover reads the file tier straight into pinned buffers. Measured, 256 MiB: `malloc_host` 28.4 / + 28.5 GB/s H2D / D2H, O_DIRECT fails; registered `posix_memalign` 28.4 / 28.4 GB/s, O_DIRECT ok, + kernel read/write ok (system USM); unregistered 21.0 / 18.2 GB/s. The backend keeps a registry + of those ranges, since the runtime does not know them. +- D11: the SYCL engine needs the oneAPI environment at run time: the runtime `dlopen`s its Level + Zero adapter, which needs `libumf.so.1` from oneAPI's `umf/` tree (no RUNPATH can reach it). A SYCL + build that sees no GPU now warns (not Info) that it is running on the CPU and names the fix. -## Next steps (Phase 2 implementation, in commit order) +## Done in Phase 2 (2026-10-23) -1. CMake: `RAD_SYCL`, the `icpx` check, `-ffp-model=precise`, `build.sh --sycl`, preset, `sycl` - label. Verify: default GCC build unchanged; SYCL build's host tier matches the baseline. -2. `abi/rad_sycl.h`; `__host__ __device__` macros' SYCL case. -3. `core/device/sycl.cpp` backend + selection + `RADIANCE_DEVICE_BACKEND`; a `sycl`-labelled - device test (the contract tests of `tests/device_test.cpp` run against it). -4. `advance` / `wtab` SYCL launchers; `--tp` refusal; fatal host-only placement. -5. `libxe2/` skeleton with one op (`add`) and its libref-checked test; `oot` rebuild. -6. Phase 3: the 13 + 13 ops of `SYCL_PORTING.md` §3.1, each with a libref test, then the tiny +- `abi/rad_sycl.h` (commit `f00e9b7`). The `__host__ __device__` macros needed no SYCL case: their + `#else` (empty) is what SYCL device code wants. +- Build: `RAD_SYCL=OFF|ON|AUTO` (default OFF), `RAD_SYCL_TARGETS` (default `intel_gpu_bmg_g31`), + `build.sh --sycl` (in `build-sycl/`), presets `sycl` (configure, build, test). The icpx sub-build is + `sycl/CMakeLists.txt`, run through ExternalProject; `rad_core` links `librad_sycl.so` with + `RAD_HAVE_SYCL=1`. HIP + SYCL refused at configure. The default build's generated test + definitions are byte-identical apart from CMake's backtrace line numbers. +- `core/device/sycl.cpp` (+ `sycl_host.h/.cpp`: the logger/error-slot callback table), selection in + `dispatch.cpp` ahead of the host fallback; `core/sched/advance_sycl.cpp`, + `core/runtime/wtab_sycl.cpp`; startup refusals for `--tp > 1` and host-only ops on SYCL. +- Tests: host-tier tests hide Level Zero GPUs with `ONEAPI_DEVICE_SELECTOR=!level_zero:*` + (`RAD_TEST_HIDE_ENV`). `device_test_sycl` (label `sycl`, `RAD_TEST_BACKEND=sycl` so a fallback to + the host backend fails, `RADIANCE_SYCL_TIMING=1`): **36 cases pass on the B65, 16579 checks**, + 12 skipped (8 elastic memory, not provided; 4 host-backend-only, skipped on AMD cards too). It + runs the SYCL `advance` kernel (`an_advance_reads_the_token_a_copy_issued_before_it_delivers`). + Fixed on the way: memset of pageable memory returns `RAD_E_UNSUPPORTED`; ranged copies refuse + what the other backends refuse; a room check refuses an allocation past the driver's free count; + gates (a spin kernel on a pinned flag). +- SYCL build, `ctest -LE 'gpu|oot'` with the oneAPI environment loaded (card present, hidden): + 83/88, the baseline's failures (FFmpeg, CPU budgets); `trigger_test`'s load flake did not occur. + +## Next steps + +1. `libxe2/` skeleton built by the icpx sub-build, installed under `radiance_home/kernels`, with one + op (`add`) and a libref-checked test on the card (`sycl` label); its `oot` rebuild. +2. `code_runs` under SYCL from `build_target` (D4), so a host-only build target never claims the card. +3. Phase 3: the 13 + 13 ops of `SYCL_PORTING.md` §3.1, each with a libref test, then the tiny llama end to end against the host backend. ## HIP-side edits awaiting a ROCm compile check @@ -213,6 +252,9 @@ None yet. ```sh . /opt/intel/oneapi/setvars.sh +./build.sh --sycl # build-sycl/: configure, build, fast tests +ctest --test-dir build-sycl -L '^sycl$' --output-on-failure # the card tests (B65) +ctest --test-dir build-sycl -LE 'gpu|oot' -j8 # host tier in the SYCL build scripts/sycl/probe.sh # Phase 0 device tables scripts/sycl/op_inventory.sh # SYCL_PORTING.md Appendix A # the tiny llama containers and their graphs (Phase 1, SYCL_PORTING.md §3.1): diff --git a/sycl/CMakeLists.txt b/sycl/CMakeLists.txt new file mode 100644 index 00000000..3ac5e9df --- /dev/null +++ b/sycl/CMakeLists.txt @@ -0,0 +1,50 @@ +# The parts of radiance compiled by icpx: the SYCL device backend (librad_sycl.so) and, later, the +# Intel kernel library. The main project builds this directory through ExternalProject with icpx +# as the C++ compiler (top-level CMakeLists.txt, RAD_SYCL), so the engine and every host plugin +# stay on the main project's compiler (docs/SYCL_PORTING.md §4.5, docs/SYCL_PROGRESS.md D6). +cmake_minimum_required(VERSION 3.21) +project(radiance_sycl LANGUAGES CXX) + +if(NOT CMAKE_CXX_COMPILER_ID STREQUAL "IntelLLVM") + message(FATAL_ERROR "sycl/ is built by icpx (IntelLLVM); this configure has " + "${CMAKE_CXX_COMPILER_ID} at ${CMAKE_CXX_COMPILER}.") +endif() +set(CMAKE_CXX_STANDARD 20) +set(CMAKE_CXX_STANDARD_REQUIRED ON) +set(CMAKE_POSITION_INDEPENDENT_CODE ON) +if(NOT CMAKE_BUILD_TYPE) + set(CMAKE_BUILD_TYPE RelWithDebInfo) +endif() + +set(RAD_SOURCE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/.." CACHE PATH "the radiance checkout") +set(RAD_SYCL_TARGETS "intel_gpu_bmg_g31" CACHE STRING "AOT targets for SYCL device code") + +# The same warnings as the main build. icpx defaults to -fp-model=fast; host code here is precise +# as the main build's is, and device code keeps the main build's -ffp-contract=off discipline in +# the kernels themselves. +add_compile_options(-Wall -Wextra -Wno-unused-parameter -Wno-missing-field-initializers + -ffp-model=precise) +set(RAD_SYCL_FLAGS -fsycl "-fsycl-targets=${RAD_SYCL_TARGETS}") + +# The oneAPI runtime libraries sit beside the compiler; record their directory so the engine runs +# without setvars.sh in its environment. +get_filename_component(_icpx_bin "${CMAKE_CXX_COMPILER}" DIRECTORY) +get_filename_component(RAD_ONEAPI_LIBDIR "${_icpx_bin}/../lib" ABSOLUTE) + +# ---------------------------------------------------------------- the device backend +# The backend, and the core's own kernels under it (the step's advance, the weight-table patches), +# each the SYCL twin of a .hip the AMD build compiles. The engine calls the kernels' launchers by +# the same names on either backend. +add_library(rad_sycl SHARED + ${RAD_SOURCE_DIR}/core/device/sycl.cpp + ${RAD_SOURCE_DIR}/core/device/sycl_host.cpp + ${RAD_SOURCE_DIR}/core/sched/advance_sycl.cpp + ${RAD_SOURCE_DIR}/core/runtime/wtab_sycl.cpp) +target_include_directories(rad_sycl PRIVATE + ${RAD_SOURCE_DIR}/core/device ${RAD_SOURCE_DIR}/core ${RAD_SOURCE_DIR}/abi + ${RAD_SOURCE_DIR}/vendor) +target_compile_definitions(rad_sycl PRIVATE RAD_HAVE_SYCL=1) +target_compile_options(rad_sycl PRIVATE ${RAD_SYCL_FLAGS} -fvisibility=hidden) +target_link_options(rad_sycl PRIVATE ${RAD_SYCL_FLAGS} "LINKER:-rpath,${RAD_ONEAPI_LIBDIR}" + "LINKER:--no-undefined") +set_target_properties(rad_sycl PROPERTIES OUTPUT_NAME rad_sycl) diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index db9b788d..b9d0aaa8 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -80,7 +80,8 @@ set(RAD_TEST_SHARDS_gbnf_test 4) # # ROCR_VISIBLE_DEVICES=99 hides every card, so a unit test runs on the host backend on every # machine: the same code everywhere, and nothing touches a card a server is using. The _card -# entries below run the device tests on a card. +# entries below run the device tests on a card. A SYCL build hides its cards the same way with +# ONEAPI_DEVICE_SELECTOR (the backend uses Level Zero devices only). # # RAD_TEST_STRICT=1: a plugin or fixture this build makes is never legitimately absent, so a test # that cannot find one fails rather than skips. RAD_TEST_TMPDIR puts radtest::tmpdir() in the build @@ -109,7 +110,11 @@ set(RAD_TEST_OMP_ENV "OMP_WAIT_POLICY=passive" "OMP_NUM_THREADS=${RAD_TEST_OMP_T set(RAD_TEST_CARD_ENV "RADIANCE_HOME=${CMAKE_BINARY_DIR}/radiance_home" ${RAD_TEST_OMP_ENV} "RAD_TEST_STRICT=1" "RAD_TEST_TMPDIR=${CMAKE_BINARY_DIR}/tmp" ${RAD_TEST_SAN_ENV}) -set(RAD_TEST_ENV ${RAD_TEST_CARD_ENV} "ROCR_VISIBLE_DEVICES=99") +set(RAD_TEST_HIDE_ENV "ROCR_VISIBLE_DEVICES=99") +if(RAD_SYCL_FOUND) + list(APPEND RAD_TEST_HIDE_ENV "ONEAPI_DEVICE_SELECTOR=!level_zero:*") +endif() +set(RAD_TEST_ENV ${RAD_TEST_CARD_ENV} ${RAD_TEST_HIDE_ENV}) # Binaries that need more CPU than the default budget, and what costs it. Lower an entry when its # cost comes down, so the tripwire stays tight. @@ -244,6 +249,21 @@ if(RAD_HIP_FOUND) endforeach() endif() +# The same on an Intel GPU through the SYCL backend, labelled sycl. The oneAPI environment must be +# loaded (the runtime finds its Level Zero adapter through it), and RAD_TEST_BACKEND=sycl makes a +# run that fell back to the host backend fail instead of passing on the CPU. RADIANCE_SYCL_TIMING=1 +# turns event timing on, which the backend leaves off by default (core/device/sycl.cpp), so the +# whole device contract is under test. +if(RAD_SYCL_FOUND) + foreach(n device_test) + add_test(NAME ${n}_sycl COMMAND ${n} -perf_) + set_tests_properties(${n}_sycl PROPERTIES + LABELS sycl + TIMEOUT ${RAD_TEST_TIMEOUT} + ENVIRONMENT "${RAD_TEST_CARD_ENV};RAD_TEST_BACKEND=sycl;RADIANCE_SYCL_TIMING=1") + endforeach() +endif() + # ================================================================== whole models on the CPU # # engine_e2e_test runs the radiance binary on tiny synthetic checkpoints (tests/tiny_model.h) on @@ -362,7 +382,7 @@ if(TARGET libavx AND TARGET rad-avx-check) add_test(NAME avx_check COMMAND rad-avx-check --ref ${RAD_PLUGIN_OUT}/kernels/libref.so --avx ${RAD_PLUGIN_OUT}/kernels/libavx.so) - set(env ${RAD_TEST_OMP_ENV} "ROCR_VISIBLE_DEVICES=99" ${RAD_TEST_SAN_ENV}) + set(env ${RAD_TEST_OMP_ENV} ${RAD_TEST_HIDE_ENV} ${RAD_TEST_SAN_ENV}) set_tests_properties(avx_check PROPERTIES TIMEOUT ${RAD_TEST_TIMEOUT} ENVIRONMENT "${env}") endif() @@ -376,7 +396,7 @@ if(TARGET rad-avx-check AND TARGET libref) COMMAND sh ${CMAKE_CURRENT_SOURCE_DIR}/avx_check_general.sh $ ${RAD_PLUGIN_OUT}/kernels/libref.so $) - set(env ${RAD_TEST_OMP_ENV} "ROCR_VISIBLE_DEVICES=99" ${RAD_TEST_SAN_ENV}) + set(env ${RAD_TEST_OMP_ENV} ${RAD_TEST_HIDE_ENV} ${RAD_TEST_SAN_ENV}) set_tests_properties(avx_check_general PROPERTIES TIMEOUT ${RAD_TEST_TIMEOUT} ENVIRONMENT "${env}") endif() @@ -530,7 +550,7 @@ add_test(NAME ops_doc set_tests_properties(ops_doc PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT ${RAD_TEST_TIMEOUT} - ENVIRONMENT "ROCR_VISIBLE_DEVICES=99") + ENVIRONMENT "${RAD_TEST_HIDE_ENV}") # tools/rad-export. Its standard-library checks always run; the merge arithmetic runs where torch # and safetensors import, and the PEFT comparison where peft and transformers do too. diff --git a/tests/device_test.cpp b/tests/device_test.cpp index c4b2df5a..968fb8a8 100644 --- a/tests/device_test.cpp +++ b/tests/device_test.cpp @@ -93,6 +93,21 @@ std::string temp_path(const char* tag) { /* ------------------------------------------------------------------ identity */ +/* RAD_TEST_BACKEND names the backend a run is registered for (the sycl-labelled entries set it). + * A run that fell back to another backend, typically the host one for want of a driver + * environment, fails here instead of passing every case on the CPU. */ +TEST(the_backend_is_the_one_the_run_names) { + const char* want = std::getenv("RAD_TEST_BACKEND"); + if (!want || !*want) return; + if (std::strcmp(rad::device_backend_name(), want) != 0) + fprintf(stderr, " RAD_TEST_BACKEND=%s but the %s backend is running: %s\n", want, + rad::device_backend_name(), + std::strcmp(want, "sycl") == 0 + ? "load the oneAPI environment (. /opt/intel/oneapi/setvars.sh)" + : "is the device visible?"); + CHECK_EQ(std::string(rad::device_backend_name()), std::string(want)); +} + TEST(backend_reports_itself) { const char* name = rad::device_backend_name(); CHECK(name && *name);