Repository navigation
Add kernel bundle states, kernel ids and SYCL library loading - #2440
ndgrigorian wants to merge 11 commits into
Conversation
|
View rendered docs @ https://intelpython.github.io/dpctl/pulls/2440/index.html |
a3f6789 to
78a7927
Compare
| if (DRef) | ||
| return static_cast<RetT>( | ||
| sycl_kern->get_info<Param>(*unwrap<device>(DRef))); |
There was a problem hiding this comment.
Blocking: A device that is not one of the kernel bundle's devices goes straight to get_info, and DPC++ does not check it. A Level Zero kernel asked about the OpenCL CPU crashes the process; other foreign devices give that device's numbers or 0:
import dpctl, dpctl.compiler as dpc
q = dpctl.SyclQueue("level_zero:gpu")
kb = dpc.get_kernel_bundle(q)
krn = kb.get_kernel(kb.get_kernel_ids()[0])
print(krn.work_group_size(dpctl.SyclDevice("opencl:cpu"))) # SIGSEGV, 5/5 on Lunar LakeCould the device be checked against the bundle's devices, with a ValueError in Python for a foreign one?
| cdef DPCTLSyclInputKernelBundleRef _input_ref | ||
| cdef DPCTLSyclObjectKernelBundleRef _object_ref | ||
| cdef int _state |
There was a problem hiding this comment.
The new fields grow SyclKernelBundle from 40 to 64 bytes. Every Cython or pybind11 module built against an earlier dpctl checks that size on import, so dpnp built without this PR warns, and with -W error it does not import:
RuntimeWarning: dpctl.compiler._compiler.SyclKernelBundle size changed, may indicate binary incompatibility. Expected 40 from C header, got 64 from PyObject
Those modules also get NULL from SyclKernelBundle_GetKernelBundleRef for an input or object bundle, and do not check it. Could input and object bundles be separate classes, so SyclKernelBundle keeps its layout?
| def work_group_size(self): | ||
| """ Returns the maximum number of work-items in a work-group that can | ||
| be used to execute the kernel on device it was built for. | ||
| def work_group_size(self, SyclDevice device=None): |
There was a problem hiding this comment.
This turns the properties into methods with no deprecation, and old code breaks silently: krn.work_group_size is now a bound method, so min(krn.work_group_size, 256) raises TypeError, and if krn.compile_sub_group_size: is always true. The C functions keep their names but take one more argument, so a binary built against an earlier dpctl passes garbage as DRef. Could the properties stay, deprecated, with the device queries under new names?
| #ifdef _WIN32 | ||
| // the search flags require an absolute path, ERROR_INVALID_PARAMETER | ||
| // otherwise | ||
| void *Handle = LoadLibraryExA(Path, nullptr, | ||
| LOAD_LIBRARY_SEARCH_DEFAULT_DIRS | | ||
| LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR); | ||
| if (!Handle && GetLastError() == ERROR_INVALID_PARAMETER) | ||
| Handle = LoadLibraryExA(Path, nullptr, 0); |
There was a problem hiding this comment.
On Windows this fails for three valid paths (error 126): a non-ASCII path like ...\папка_ядер\x.dll, since os.fsencode gives UTF-8 and LoadLibraryExA reads it in the ANSI code page; an absolute path with /; and a relative path to a DLL whose dependencies sit next to it, since the retry with flags 0 skips the DLL's folder. UTF-8 to UTF-16, GetFullPathNameW, then LoadLibraryExW with the same flags fixed all of them locally. The tests skip on Windows, so CI misses this.
| return SyclKernelBundle._create( | ||
| ExeRef, | ||
| any((<SyclKernelBundle>b)._is_sycl_source for b in kernel_bundles), | ||
| ) |
There was a problem hiding this comment.
Two joined SPIR-V bundles on Level Zero report the kernel but cannot create it. A join of a SYCL-source and a SPIR-V bundle does not find the SPIR-V kernels on any device:
import os, dpctl, dpctl.compiler as dpc
q = dpctl.SyclQueue("level_zero:gpu")
spv = open(os.path.join(os.path.dirname(dpctl.__file__), "tests/input_files/multi_kernel.spv"), "rb").read()
j = dpc.join([dpc.create_kernel_bundle_from_spirv(q, spv), dpc.create_kernel_bundle_from_spirv(q, spv)])
print(j.has_sycl_kernel("add")) # True
j.get_sycl_kernel("add") # ValueError on Level Zero; works on OpenCL GPU and CPUThe test joins a bundle with itself, which keeps one image. Could join refuse what get_sycl_kernel cannot handle?
| std::string msg = | ||
| "clBuildProgram failed: " + _GetErrorCode_ocl_impl(build_status); | ||
| const std::string &log = _GetBuildLog_ocl_impl(clProgram, clDevice); | ||
| if (!log.empty()) { | ||
| msg += "\nBuild log:\n" + log; | ||
| } | ||
| error_handler(msg, __FILE__, __func__, __LINE__, error_level::error); |
There was a problem hiding this comment.
The build log goes only to error_handler, which prints nothing unless DPCTL_VERBOSITY is set, so by default the error still has no message:
import dpctl, dpctl.compiler as dpc
q = dpctl.SyclQueue("opencl")
try:
dpc.create_kernel_bundle_from_source(q, "kernel void add(global int* a) { a[0] = b; }")
except dpc.SyclKernelBundleCompilationError as e:
print(repr(str(e))) # ''Could the log go into the exception, as DPCTLKernelBuildLog does for SYCL source?
| auto Before = sycl::get_kernel_ids(); | ||
| std::string Error; | ||
| void *Handle = open_library(Path, Error); | ||
| if (!Handle) { | ||
| error_handler("Could not load " + std::string(Path) + ": " + Error, | ||
| __FILE__, __func__, __LINE__); | ||
| return nullptr; | ||
| } | ||
| auto It = Libs.KernelIds.find(Handle); | ||
| if (It == Libs.KernelIds.end()) { | ||
| std::unordered_set<kernel_id> Known(Before.begin(), Before.end()); | ||
| std::vector<kernel_id> New; | ||
| for (const auto &KId : sycl::get_kernel_ids()) { | ||
| if (Known.count(KId) == 0) | ||
| New.push_back(KId); | ||
| } |
There was a problem hiding this comment.
The ids are the difference of get_kernel_ids() before and after dlopen, so they include the kernels of every SYCL library loaded with this one, and that library then gets none:
import pathlib, subprocess, tempfile
import dpctl.compiler as dpc
src = """#include <sycl/sycl.hpp>
extern "C" SYCL_EXT_ONEAPI_FUNCTION_PROPERTY((sycl::ext::oneapi::experimental::nd_range_kernel<1>))
void NAME(int *a) { a[sycl::ext::oneapi::this_work_item::get_nd_item<1>().get_global_id(0)] = 1; }
"""
d = pathlib.Path(tempfile.mkdtemp())
for name, libs in [("kb", []), ("ka", [f"-L{d}", "-lkb", f"-Wl,-rpath,{d}"])]:
(d / f"{name}.cpp").write_text(src.replace("NAME", name))
subprocess.run(["icpx", "-fsycl", "-fPIC", "-shared", d / f"{name}.cpp", "-o", d / f"lib{name}.so", *libs], check=True)
print([k.name for k in dpc.load_kernel_library(d / "libka.so")]) # ['__sycl_kernel_ka', '__sycl_kernel_kb']
print([k.name for k in dpc.load_kernel_library(d / "libkb.so")]) # []For a library linked with oneMKL, get_kernel_bundle(q, kernel_ids=...) would then build oneMKL's kernels too. Could the docstring say this?
| @staticmethod | ||
| cdef SyclKernelBundle _create_input (DPCTLSyclInputKernelBundleRef kbref) | ||
|
|
||
| @staticmethod | ||
| cdef SyclKernelBundle _create_object (DPCTLSyclObjectKernelBundleRef kbref) | ||
|
|
||
| cdef DPCTLSyclKernelBundleRef get_kernel_bundle_ref (self) | ||
| cdef DPCTLSyclInputKernelBundleRef get_input_kernel_bundle_ref (self) | ||
| cdef DPCTLSyclObjectKernelBundleRef get_object_kernel_bundle_ref (self) | ||
| cdef _require_executable (self, str what) | ||
| cdef bint _device_image_has_kernel ( | ||
| self, size_t index, SyclKernelId kernel_id, SyclDevice device | ||
| ) | ||
| cpdef SyclKernel get_sycl_kernel(self, str kernel_name) |
There was a problem hiding this comment.
These methods are declared before get_kernel_bundle_ref and get_sycl_kernel, so their vtable slots move from 1 and 2 to 3 and 8. A Cython module built against an earlier dpctl that calls kb.get_sycl_kernel(name) would call _create_object instead. Could the new methods go after get_sycl_kernel?
| cdef api DPCTLSyclInputKernelBundleRef SyclKernelBundle_GetInputKernelBundleRef( | ||
| SyclKernelBundle kb | ||
| ): | ||
| """ C-API function to access the opaque reference of a | ||
| :class:`dpctl.compiler.SyclKernelBundle` in ``input`` state, NULL for | ||
| other states. | ||
| """ | ||
| return kb.get_input_kernel_bundle_ref() |
There was a problem hiding this comment.
The new C-API functions (SyclKernelBundle_GetInputKernelBundleRef, _GetObjectKernelBundleRef, _MakeInput, _MakeObject, SyclKernelId_GetKernelIdRef, SyclKernelId_Make) and PySyclKernelIdType are not in dpctl_capi.rst, which also still says SyclKernelBundle_GetKernelBundleRef always returns a bundle. 14 of the new libsyclinterface functions have no gtest, e.g. DPCTLInputKernelBundle_GetDevices and DPCTLObjectKernelBundle_GetKernelIds.
|
|
||
| #include "dpctl_sycl_kernel_bundle_interface.h" | ||
|
|
||
| #include "Config/dpctl_config.h" | ||
| #include "dpctl_error_handlers.h" | ||
| #include "dpctl_string_utils.hpp" | ||
| #include "dpctl_sycl_type_casters.hpp" | ||
| #include "dpctl_utils_helper.h" | ||
| #include <cstddef> | ||
| #include <functional> | ||
| #include <iterator> | ||
| #include <memory> | ||
| #include <mutex> | ||
| #include <stdexcept> | ||
| #include <string> | ||
| #include <sycl/sycl.hpp> | ||
| #include <unordered_map> |
There was a problem hiding this comment.
#2384 guards the kernel bundle code with __ADAPTIVECPP__ (11 places in dpctl_sycl_kernel_bundle_interface.cpp), but this new file has none, and it uses kernel_id, compile, link and device image selectors. Whichever of the two PRs is merged second will need stubs here for the AdaptiveCpp build. Which order do you plan?
| if KIdRefs is NULL: | ||
| raise MemoryError() | ||
| for i in range(<size_t>len(kernel_ids)): | ||
| KIdRefs[i] = (<SyclKernelId>kernel_ids[i]).get_kernel_id_ref() |
There was a problem hiding this comment.
Nit: SyclKernelId has no __cinit__, so SyclKernelId.__new__ gives an object with a NULL ref, and DPCTLKernelIdVector_CreateFromArray dereferences it:
import dpctl, dpctl.compiler as dpc
kid = dpc.SyclKernelId.__new__(dpc.SyclKernelId)
dpc.is_compatible([kid], dpctl.SyclDevice()) # SIGSEGVCould _kernel_id_vector reject a NULL ref?
| extern "C" SYCL_EXTERNAL | ||
| SYCL_EXT_ONEAPI_FUNCTION_PROPERTY((syclext::nd_range_kernel<1>)) | ||
| void bundle_state_test_kernel(int *a) { | ||
| a[syclext::this_work_item::get_nd_item<1>().get_global_id(0)] = 1; |
There was a problem hiding this comment.
Nit: This source does not compile with DPC++ 2026.2.1: get_nd_item is in sycl::ext::oneapi::this_work_item, not in experimental. It is not reached here because dpctl's own kernels give ids, so it would fail only where there are none. sycl::ext::oneapi::this_work_item::get_nd_item<1>(), as in test_sycl_compiler.py, would fix it.
| * sycl::get_native and sycl::make_* retain the OpenCL object, so references | ||
| * returned by get_native or clCreate* must be released by the caller. |
There was a problem hiding this comment.
Nit: get_native<cl_be>(dev) in _CreateKernelBundle_common_ocl_impl retains the cl_device_id too, and nothing releases it. For a root device that does nothing, but each bundle built for an OpenCL sub-device keeps one more reference. A cl_ref_guard<cl_device_id> with clReleaseDevice would close it.
| * Kernel bundles in `input`, `object` and `executable` states for the kernels compiled into the application: `dpctl.compiler.get_kernel_bundle`, `has_kernel_bundle`, `compile`, `link`, `build` and `join`, the `dpctl.compiler.SyclKernelId` and `dpctl.compiler.SyclDeviceImage` classes, `get_kernel_ids` and `is_compatible`, and new `dpctl.compiler.SyclKernelBundle` queries (`state`, `backend`, `sycl_context`, `get_devices`, `is_empty`, `get_kernel_ids`, `has_kernel`, `get_kernel`, `get_device_images`, `contains_specialization_constants`, `native_specialization_constant`), with the matching `DPCTLKernelBundle_*`, `DPCTLInputKernelBundle_*`, `DPCTLObjectKernelBundle_*` and `DPCTLKernelId_*` C-API functions | ||
| * `selector` argument of `dpctl.compiler.get_kernel_bundle`, a callable that chooses the device images to include, with the `DPCTLKernelBundle_CreateFromContextWithSelector`, `DPCTLInputKernelBundle_CreateFromContextWithSelector`, `DPCTLObjectKernelBundle_CreateFromContextWithSelector` and `DPCTLDeviceImage_HasKernel` C-API functions | ||
| * `dpctl4pybind11.hpp` type casters for `sycl::kernel_bundle<sycl::bundle_state::input>`, `sycl::kernel_bundle<sycl::bundle_state::object>` and `sycl::kernel_id`, and the `examples/pybind11/use_kernel_bundle` example that sets a SYCL specialization constant on a kernel bundle obtained in Python | ||
| * `dpctl.compiler.load_kernel_library` and the `DPCTLKernelId_LoadLibrary` C-API function, which load a shared library with SYCL device code, e.g. compiled for CUDA or HIP devices, and return the ids of its kernels for use with `dpctl.compiler.get_kernel_bundle` |
There was a problem hiding this comment.
Nit: The new entries (here, line 30 and line 46) have no [gh-2440](https://github.com/IntelPython/dpctl/pull/2440) link, and the blank lines 17 and 29 split the lists.
|
I tested this on Lunar Lake (Level Zero and OpenCL GPU, OpenCL CPU) with DPC++ 2026.2.1 and on Windows (Arc B390, a local build of this branch). Comments on lines outside the diff:
|
Wrap sycl::kernel_bundle in input, object and executable states, kernel_id and device images, with get_kernel_bundle, compile, link, build and join in the C API and dpctl.compiler. DPCTLKernel_GetNumArgs no longer terminates for kernels without a number of arguments.
SyclKernel device-specific queries become methods with an optional device, and DPCTLKernel_Get* take a nullable device (breaking). get_kernel_bundle accepts a device image selector, and dpctl4pybind11.hpp casts input and object bundles and kernel ids, used by the new use_kernel_bundle example.
Load a shared library with SYCL device code, e.g. built for CUDA or HIP, and return the ids of the kernels it registered, for get_kernel_bundle. Exposed as dpctl.compiler.load_kernel_library and DPCTLKernelId_LoadLibrary.
The IL memoryview was typed as strided but passed to the C API as a contiguous pointer and length. Declare it as const unsigned char[::1] so non-contiguous buffers are rejected.
The destructor called dlclose/FreeLibrary even when the library failed to open.
DPCTLKernelBundle_GetKernel, DPCTLKernelBundle_HasKernel and DPCTLKernelBundle_CreateFromOCLSource could let SYCL exceptions escape an extern "C" function, which terminates the process. Report them through error_handler and return the function's failure value.
get_native and make_kernel_bundle/make_kernel retain the OpenCL context, program and kernel, so the references obtained by dpctl were leaked. Release them with a scoped guard, and release the kernels created by _HasKernel_ocl_impl.
The module and kernels were created with ownership::keep and never destroyed. Use ownership::transfer, destroy them if interop fails, and destroy the kernel created by _HasKernel_ze_impl.
Append the clBuildProgram or zeModuleCreate build log to the error reported through error_handler.
A Debug build defines _DEBUG, which makes Windows pyconfig.h enable Py_DEBUG and reference symbols missing from the release python lib.
Split input and object bundles into SyclInputKernelBundle and SyclObjectKernelBundle so SyclKernelBundle keeps its layout, restore the SyclKernel properties (deprecated) and DPCTLKernel_Get* signatures with device queries under new names, put build logs into the exception, refuse joins get_sycl_kernel can not handle, and stub the new C API for AdaptiveCpp.
78a7927 to
90ec03e
Compare
This PR proposes expanding
dpctl.compilerto include kernel bundles in theinput,objectandexecutablestates,get_kernel_bundleandhas_kernel_bundle,compile,link,buildandjoin, theSyclKernelIdandSyclDeviceImageclasses,get_kernel_ids,is_compatible, and newSyclKernelBundlequeries (state,backend,sycl_context,get_devices,is_empty,get_kernel_ids,has_kernel,get_kernel,get_device_images, specialization constant queries)It also adds
dpctl.compiler.load_kernel_library, which loads a shared library with SYCL device code, e.g. compiled for CUDA or HIP devices, and returns the ids of its kernels for use withget_kernel_bundle, anddpctl4pybind11.hpptype casters forsycl::kernel_bundle<sycl::bundle_state::input>,sycl::kernel_bundle<sycl::bundle_state::object>andsycl::kernel_id, with a newexamples/pybind11/use_kernel_bundleexample that sets a SYCL specialization constant on a kernel bundle obtained in PythonThis includes a breaking change for
dpctl.compiler.SyclKernel: the device-specific queries become methods taking an optionaldevice, which defaults to the first device of the kernel bundle, and the matchingDPCTLKernel_Get*C-API functions take a nullableDPCTLSyclDeviceRef. These queries now return 0 instead of terminating the process when the SYCL runtime throwsThe PR also fixes a number of bugs in the existing kernel bundle C API:
DPCTLKernelBundle_GetKernel,DPCTLKernelBundle_HasKernelandDPCTLKernelBundle_CreateFromOCLSourcelet SYCL exceptions escape anextern "C"function, terminating the processget_nativeandmake_kernel_bundle/make_kernelwere leakedownership::keepand never destroyedDynamicLibHelperno longer closes a NULL handle when a library fails to opencreate_kernel_bundle_from_spirvrejects non-contiguous buffers which were passed to the C API as contiguous