diff --git a/CHANGELOG.md b/CHANGELOG.md index 36469b7c3f..4e0f75523d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,12 +14,19 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 * Added `dpctl.SyclQueue.get_last_event` and `dpctl.SyclQueue.is_get_last_event_available`, and the `DPCTLQueue_GetLastEvent` and `DPCTLQueue_GetLastEvent_Available` C-API functions, wrapping the DPC++ `sycl_ext_oneapi_in_order_queue_events` extension [gh-2299](https://github.com/IntelPython/dpctl/pull/2299) * Added `dpctl.SyclPlatform.has_aspect_*` properties and the `DPCTLPlatform_HasAspect` C-API function for querying aspects supported by all devices of a platform [gh-2412](https://github.com/IntelPython/dpctl/pull/2412) +* 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::kernel_bundle` 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` + ### Changed * Object lifetime during offload is now managed by a list of releases deferred until the events that gate them have completed, rather than by a `host_task`. `dpctl` keeps one thread for looking over the list and running the releases that have come due, started by the first release deferred and again in the child of a `fork`, which takes the GIL to do so and lets a release call into the interpreter and free USM allocations [gh-2359](https://github.com/IntelPython/dpctl/pull/2359) * `import_dpctl()` now returns 0 on success and -1 with a Python exception set on failure, and `dpctl4pybind11.hpp` raises that exception rather than failing on the first C-API call [gh-2359](https://github.com/IntelPython/dpctl/pull/2359) * The event returned by `dpctl.SyclQueue.keep_args_alive`, `dpctl::utils::keep_args_alive` and `dpctl.SyclQueue._submit_keep_args_alive` is now for an empty kernel that gates the deferred release rather than for a `host_task` that performs it, so its completion means that the objects are no longer in use rather than that they have been released [gh-2359](https://github.com/IntelPython/dpctl/pull/2359) * `dpctl.utils.SequentialOrderManager[q].submitted_events` includes the queue's last event for in-order queues when `sycl_ext_oneapi_in_order_queue_events` is available, and `wait()` waits for all work on an in-order queue [gh-2299](https://github.com/IntelPython/dpctl/pull/2299) +* **Breaking:** the `dpctl.compiler.SyclKernel` properties `work_group_size`, `preferred_work_group_size_multiple`, `private_mem_size`, `max_num_sub_groups`, `max_sub_group_size`, `compile_num_sub_groups` and `compile_sub_group_size` are now methods taking an optional `device`, which defaults to the first device of the kernel bundle; the matching `DPCTLKernel_Get*` C-API functions take a `DPCTLSyclDeviceRef` argument, which may be `NULL` + ### Deprecated * Deprecated `dpctl.SyclQueue._submit_keep_args_alive` in favor of `dpctl.SyclQueue.keep_args_alive`, which it now calls and which behaves identically [gh-2359](https://github.com/IntelPython/dpctl/pull/2359) * Deprecated the order manager's `add_event_pair`, `host_task_events` and `num_host_task_events`, as `host_task` is no longer used for managing object lifetimes, in favor of `add_event`, `add_cleanup_event`, `cleanup_events` and `num_cleanup_events`; they do not yet emit a `DeprecationWarning` [gh-2359](https://github.com/IntelPython/dpctl/pull/2359) @@ -32,6 +39,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 * A USM allocation that fails now drops the references held for offloaded tasks that have completed, and is attempted once more if that released anything, so that memory only waiting to be given up is not reported as unavailable [gh-2359](https://github.com/IntelPython/dpctl/pull/2359) * `dpctl.SyclPlatform.get_devices` no longer prints Unified Runtime warnings for `device_type="custom"` on non-OpenCL platforms, where custom devices are not supported [gh-2306](https://github.com/IntelPython/dpctl/pull/2306) * Fixed building with the open source DPC++ compiler and CMake 4.5 or newer, which identifies it as `DPClang` instead of `Clang` [gh-2433](https://github.com/IntelPython/dpctl/pull/2433) +* `DPCTLKernel_Get*` device-specific queries return 0 instead of terminating the process when the SYCL runtime throws ### Maintenance * Removed the `-fno-sycl-id-queries-fit-in-int` compile option, which none of the `dpctl` extensions need since `dpctl.tensor` moved to `dpnp` [gh-2413](https://github.com/IntelPython/dpctl/pull/2413) diff --git a/docs/doc_sources/api_reference/dpctl/compiler.rst b/docs/doc_sources/api_reference/dpctl/compiler.rst index 15a2231c85..3b9a084428 100644 --- a/docs/doc_sources/api_reference/dpctl/compiler.rst +++ b/docs/doc_sources/api_reference/dpctl/compiler.rst @@ -12,6 +12,10 @@ It implements creation of interoperability as well as creation of individual ``sycl::kernel``, suitable for submission for execution via :py:meth:`dpctl.SyclQueue.submit`. +It also exposes the kernel bundles of the kernels compiled into the +application, in ``input``, ``object`` and ``executable`` states, along with +the SYCL functions that compile, link, build and join them. + .. py:module:: dpctl.compiler .. currentmodule:: dpctl.compiler @@ -25,12 +29,28 @@ execution via :py:meth:`dpctl.SyclQueue.submit`. create_kernel_bundle_from_sycl_source is_sycl_source_compilation_available +.. autosummary:: + :toctree: generated + :nosignatures: + + get_kernel_bundle + has_kernel_bundle + get_kernel_ids + load_kernel_library + is_compatible + compile + link + build + join + .. autosummary:: :toctree: generated :nosignatures: SyclKernelBundle SyclKernel + SyclKernelId + SyclDeviceImage SpecializationConstant .. autosummary:: diff --git a/dpctl/_backend.pxd b/dpctl/_backend.pxd index efe5dbdec6..10194ed554 100644 --- a/dpctl/_backend.pxd +++ b/dpctl/_backend.pxd @@ -181,6 +181,10 @@ cdef extern from "syclinterface/dpctl_sycl_types.h": cdef struct DPCTLOpaqueSyclKernel cdef struct DPCTLOpaqueSyclPlatform cdef struct DPCTLOpaqueSyclKernelBundle + cdef struct DPCTLOpaqueSyclInputKernelBundle + cdef struct DPCTLOpaqueSyclObjectKernelBundle + cdef struct DPCTLOpaqueSyclKernelId + cdef struct DPCTLOpaqueSyclDeviceImage cdef struct DPCTLOpaqueSyclQueue cdef struct DPCTLOpaqueSyclUSM @@ -191,6 +195,10 @@ cdef extern from "syclinterface/dpctl_sycl_types.h": ctypedef DPCTLOpaqueSyclKernel *DPCTLSyclKernelRef ctypedef DPCTLOpaqueSyclPlatform *DPCTLSyclPlatformRef ctypedef DPCTLOpaqueSyclKernelBundle *DPCTLSyclKernelBundleRef + ctypedef DPCTLOpaqueSyclInputKernelBundle *DPCTLSyclInputKernelBundleRef + ctypedef DPCTLOpaqueSyclObjectKernelBundle *DPCTLSyclObjectKernelBundleRef + ctypedef DPCTLOpaqueSyclKernelId *DPCTLSyclKernelIdRef + ctypedef DPCTLOpaqueSyclDeviceImage *DPCTLSyclDeviceImageRef ctypedef DPCTLOpaqueSyclQueue *DPCTLSyclQueueRef ctypedef DPCTLOpaqueSyclUSM *DPCTLSyclUSMRef @@ -439,19 +447,27 @@ cdef extern from "syclinterface/dpctl_sycl_kernel_interface.h": cdef size_t DPCTLKernel_GetNumArgs(const DPCTLSyclKernelRef KRef) cdef void DPCTLKernel_Delete(DPCTLSyclKernelRef KRef) cdef DPCTLSyclKernelRef DPCTLKernel_Copy(const DPCTLSyclKernelRef KRef) - cdef size_t DPCTLKernel_GetWorkGroupSize(const DPCTLSyclKernelRef KRef) + cdef size_t DPCTLKernel_GetWorkGroupSize( + const DPCTLSyclKernelRef KRef, + const DPCTLSyclDeviceRef DRef) cdef size_t DPCTLKernel_GetPreferredWorkGroupSizeMultiple( - const DPCTLSyclKernelRef KRef - ) - cdef size_t DPCTLKernel_GetPrivateMemSize(const DPCTLSyclKernelRef KRef) - cdef uint32_t DPCTLKernel_GetMaxNumSubGroups(const DPCTLSyclKernelRef KRef) - cdef uint32_t DPCTLKernel_GetMaxSubGroupSize(const DPCTLSyclKernelRef KRef) + const DPCTLSyclKernelRef KRef, + const DPCTLSyclDeviceRef DRef) + cdef size_t DPCTLKernel_GetPrivateMemSize( + const DPCTLSyclKernelRef KRef, + const DPCTLSyclDeviceRef DRef) + cdef uint32_t DPCTLKernel_GetMaxNumSubGroups( + const DPCTLSyclKernelRef KRef, + const DPCTLSyclDeviceRef DRef) + cdef uint32_t DPCTLKernel_GetMaxSubGroupSize( + const DPCTLSyclKernelRef KRef, + const DPCTLSyclDeviceRef DRef) cdef uint32_t DPCTLKernel_GetCompileNumSubGroups( - const DPCTLSyclKernelRef KRef - ) + const DPCTLSyclKernelRef KRef, + const DPCTLSyclDeviceRef DRef) cdef uint32_t DPCTLKernel_GetCompileSubGroupSize( - const DPCTLSyclKernelRef KRef - ) + const DPCTLSyclKernelRef KRef, + const DPCTLSyclDeviceRef DRef) cdef extern from "syclinterface/dpctl_sycl_platform_manager.h": @@ -558,6 +574,185 @@ cdef extern from "syclinterface/dpctl_sycl_kernel_bundle_interface.h": cdef DPCTLSyclKernelBundleRef DPCTLKernelBundle_Copy( const DPCTLSyclKernelBundleRef KBRef) + cdef struct DPCTLKernelIdVector + ctypedef DPCTLKernelIdVector *DPCTLKernelIdVectorRef + cdef DPCTLKernelIdVectorRef DPCTLKernelIdVector_Create() + cdef DPCTLKernelIdVectorRef DPCTLKernelIdVector_CreateFromArray( + size_t nelems, + DPCTLSyclKernelIdRef *elems) + cdef void DPCTLKernelIdVector_Delete(DPCTLKernelIdVectorRef KIdVRef) + + ctypedef bool (*DPCTLDeviceImageSelectorFn)( + DPCTLSyclDeviceImageRef ImgRef, void *UserData) noexcept + cdef bool DPCTLDeviceImage_HasKernel( + const DPCTLSyclDeviceImageRef ImgRef, + const DPCTLSyclKernelIdRef KIdRef, + const DPCTLSyclDeviceRef DRef) + cdef DPCTLSyclKernelBundleRef \ + DPCTLKernelBundle_CreateFromContextWithSelector( + const DPCTLSyclContextRef CRef, + const DPCTLDeviceVectorRef DVRef, + DPCTLDeviceImageSelectorFn Selector, + void *UserData) + cdef DPCTLSyclInputKernelBundleRef \ + DPCTLInputKernelBundle_CreateFromContextWithSelector( + const DPCTLSyclContextRef CRef, + const DPCTLDeviceVectorRef DVRef, + DPCTLDeviceImageSelectorFn Selector, + void *UserData) + cdef DPCTLSyclObjectKernelBundleRef \ + DPCTLObjectKernelBundle_CreateFromContextWithSelector( + const DPCTLSyclContextRef CRef, + const DPCTLDeviceVectorRef DVRef, + DPCTLDeviceImageSelectorFn Selector, + void *UserData) + cdef size_t DPCTLKernelIdVector_Size(DPCTLKernelIdVectorRef KIdVRef) + cdef DPCTLSyclKernelIdRef DPCTLKernelIdVector_GetAt( + DPCTLKernelIdVectorRef KIdVRef, + size_t index) + + cdef const char *DPCTLKernelId_GetName(const DPCTLSyclKernelIdRef KIdRef) + cdef bool DPCTLKernelId_AreEq( + const DPCTLSyclKernelIdRef KIdRef1, + const DPCTLSyclKernelIdRef KIdRef2) + cdef size_t DPCTLKernelId_Hash(const DPCTLSyclKernelIdRef KIdRef) + cdef DPCTLSyclKernelIdRef DPCTLKernelId_Copy( + const DPCTLSyclKernelIdRef KIdRef) + cdef void DPCTLKernelId_Delete(DPCTLSyclKernelIdRef KIdRef) + cdef DPCTLKernelIdVectorRef DPCTLKernelId_GetAll() + cdef DPCTLKernelIdVectorRef DPCTLKernelId_LoadLibrary(const char *Path) + cdef bool DPCTLKernelId_IsCompatible( + const DPCTLKernelIdVectorRef KIdVRef, + const DPCTLSyclDeviceRef DRef) + + cdef DPCTLSyclContextRef DPCTLKernelBundle_GetContext( + const DPCTLSyclKernelBundleRef KBRef) + cdef DPCTLDeviceVectorRef DPCTLKernelBundle_GetDevices( + const DPCTLSyclKernelBundleRef KBRef) + cdef _backend_type DPCTLKernelBundle_GetBackend( + const DPCTLSyclKernelBundleRef KBRef) + cdef bool DPCTLKernelBundle_IsEmpty(const DPCTLSyclKernelBundleRef KBRef) + cdef DPCTLKernelIdVectorRef DPCTLKernelBundle_GetKernelIds( + const DPCTLSyclKernelBundleRef KBRef) + cdef bool DPCTLKernelBundle_HasKernelId( + const DPCTLSyclKernelBundleRef KBRef, + const DPCTLSyclKernelIdRef KIdRef, + const DPCTLSyclDeviceRef DRef) + cdef bool DPCTLKernelBundle_ContainsSpecializationConstants( + const DPCTLSyclKernelBundleRef KBRef) + cdef bool DPCTLKernelBundle_NativeSpecializationConstant( + const DPCTLSyclKernelBundleRef KBRef) + cdef size_t DPCTLKernelBundle_GetNumDeviceImages( + const DPCTLSyclKernelBundleRef KBRef) + cdef bool DPCTLKernelBundle_DeviceImageHasKernel( + const DPCTLSyclKernelBundleRef KBRef, + size_t Index, + const DPCTLSyclKernelIdRef KIdRef, + const DPCTLSyclDeviceRef DRef) + cdef DPCTLSyclKernelBundleRef DPCTLKernelBundle_Join( + size_t NumKBRefs, const DPCTLSyclKernelBundleRef *KBRefs) + cdef DPCTLSyclKernelBundleRef DPCTLKernelBundle_CreateFromContext( + const DPCTLSyclContextRef CRef, + const DPCTLDeviceVectorRef DVRef, + const DPCTLKernelIdVectorRef KIdVRef) + cdef bool DPCTLKernelBundle_CanCreateFromContext( + const DPCTLSyclContextRef CRef, + const DPCTLDeviceVectorRef DVRef, + const DPCTLKernelIdVectorRef KIdVRef) + cdef DPCTLSyclKernelRef DPCTLKernelBundle_GetKernelById( + const DPCTLSyclKernelBundleRef KBRef, + const DPCTLSyclKernelIdRef KIdRef) + + cdef DPCTLSyclContextRef DPCTLInputKernelBundle_GetContext( + const DPCTLSyclInputKernelBundleRef KBRef) + cdef DPCTLDeviceVectorRef DPCTLInputKernelBundle_GetDevices( + const DPCTLSyclInputKernelBundleRef KBRef) + cdef _backend_type DPCTLInputKernelBundle_GetBackend( + const DPCTLSyclInputKernelBundleRef KBRef) + cdef bool DPCTLInputKernelBundle_IsEmpty( + const DPCTLSyclInputKernelBundleRef KBRef) + cdef DPCTLKernelIdVectorRef DPCTLInputKernelBundle_GetKernelIds( + const DPCTLSyclInputKernelBundleRef KBRef) + cdef bool DPCTLInputKernelBundle_HasKernelId( + const DPCTLSyclInputKernelBundleRef KBRef, + const DPCTLSyclKernelIdRef KIdRef, + const DPCTLSyclDeviceRef DRef) + cdef bool DPCTLInputKernelBundle_ContainsSpecializationConstants( + const DPCTLSyclInputKernelBundleRef KBRef) + cdef bool DPCTLInputKernelBundle_NativeSpecializationConstant( + const DPCTLSyclInputKernelBundleRef KBRef) + cdef size_t DPCTLInputKernelBundle_GetNumDeviceImages( + const DPCTLSyclInputKernelBundleRef KBRef) + cdef bool DPCTLInputKernelBundle_DeviceImageHasKernel( + const DPCTLSyclInputKernelBundleRef KBRef, + size_t Index, + const DPCTLSyclKernelIdRef KIdRef, + const DPCTLSyclDeviceRef DRef) + cdef DPCTLSyclInputKernelBundleRef DPCTLInputKernelBundle_Join( + size_t NumKBRefs, const DPCTLSyclInputKernelBundleRef *KBRefs) + cdef DPCTLSyclInputKernelBundleRef DPCTLInputKernelBundle_CreateFromContext( + const DPCTLSyclContextRef CRef, + const DPCTLDeviceVectorRef DVRef, + const DPCTLKernelIdVectorRef KIdVRef) + cdef bool DPCTLInputKernelBundle_CanCreateFromContext( + const DPCTLSyclContextRef CRef, + const DPCTLDeviceVectorRef DVRef, + const DPCTLKernelIdVectorRef KIdVRef) + cdef DPCTLSyclInputKernelBundleRef DPCTLInputKernelBundle_Copy( + const DPCTLSyclInputKernelBundleRef KBRef) + cdef void DPCTLInputKernelBundle_Delete(DPCTLSyclInputKernelBundleRef KBRef) + cdef DPCTLSyclObjectKernelBundleRef DPCTLInputKernelBundle_Compile( + const DPCTLSyclInputKernelBundleRef KBRef, + const DPCTLDeviceVectorRef DVRef) + cdef DPCTLSyclKernelBundleRef DPCTLInputKernelBundle_Build( + const DPCTLSyclInputKernelBundleRef KBRef, + const DPCTLDeviceVectorRef DVRef) + + cdef DPCTLSyclContextRef DPCTLObjectKernelBundle_GetContext( + const DPCTLSyclObjectKernelBundleRef KBRef) + cdef DPCTLDeviceVectorRef DPCTLObjectKernelBundle_GetDevices( + const DPCTLSyclObjectKernelBundleRef KBRef) + cdef _backend_type DPCTLObjectKernelBundle_GetBackend( + const DPCTLSyclObjectKernelBundleRef KBRef) + cdef bool DPCTLObjectKernelBundle_IsEmpty( + const DPCTLSyclObjectKernelBundleRef KBRef) + cdef DPCTLKernelIdVectorRef DPCTLObjectKernelBundle_GetKernelIds( + const DPCTLSyclObjectKernelBundleRef KBRef) + cdef bool DPCTLObjectKernelBundle_HasKernelId( + const DPCTLSyclObjectKernelBundleRef KBRef, + const DPCTLSyclKernelIdRef KIdRef, + const DPCTLSyclDeviceRef DRef) + cdef bool DPCTLObjectKernelBundle_ContainsSpecializationConstants( + const DPCTLSyclObjectKernelBundleRef KBRef) + cdef bool DPCTLObjectKernelBundle_NativeSpecializationConstant( + const DPCTLSyclObjectKernelBundleRef KBRef) + cdef size_t DPCTLObjectKernelBundle_GetNumDeviceImages( + const DPCTLSyclObjectKernelBundleRef KBRef) + cdef bool DPCTLObjectKernelBundle_DeviceImageHasKernel( + const DPCTLSyclObjectKernelBundleRef KBRef, + size_t Index, + const DPCTLSyclKernelIdRef KIdRef, + const DPCTLSyclDeviceRef DRef) + cdef DPCTLSyclObjectKernelBundleRef DPCTLObjectKernelBundle_Join( + size_t NumKBRefs, const DPCTLSyclObjectKernelBundleRef *KBRefs) + cdef DPCTLSyclObjectKernelBundleRef \ + DPCTLObjectKernelBundle_CreateFromContext( + const DPCTLSyclContextRef CRef, + const DPCTLDeviceVectorRef DVRef, + const DPCTLKernelIdVectorRef KIdVRef) + cdef bool DPCTLObjectKernelBundle_CanCreateFromContext( + const DPCTLSyclContextRef CRef, + const DPCTLDeviceVectorRef DVRef, + const DPCTLKernelIdVectorRef KIdVRef) + cdef DPCTLSyclObjectKernelBundleRef DPCTLObjectKernelBundle_Copy( + const DPCTLSyclObjectKernelBundleRef KBRef) + cdef void DPCTLObjectKernelBundle_Delete( + DPCTLSyclObjectKernelBundleRef KBRef) + cdef DPCTLSyclKernelBundleRef DPCTLObjectKernelBundle_Link( + size_t NumKBRefs, + const DPCTLSyclObjectKernelBundleRef *KBRefs, + const DPCTLDeviceVectorRef DVRef) + cdef struct DPCTLBuildOptionList cdef struct DPCTLKernelNameList cdef struct DPCTLVirtualHeaderList diff --git a/dpctl/apis/include/dpctl4pybind11.hpp b/dpctl/apis/include/dpctl4pybind11.hpp index 8844ae3bdb..d78029a8d7 100644 --- a/dpctl/apis/include/dpctl4pybind11.hpp +++ b/dpctl/apis/include/dpctl4pybind11.hpp @@ -82,6 +82,7 @@ class dpctl_capi PyTypeObject *PyMemoryUSMHostType_; PyTypeObject *PySyclKernelBundleType_; PyTypeObject *PySyclKernelType_; + PyTypeObject *PySyclKernelIdType_; DPCTLSyclDeviceRef (*SyclDevice_GetDeviceRef_)(PySyclDeviceObject *); PySyclDeviceObject *(*SyclDevice_Make_)(DPCTLSyclDeviceRef); @@ -120,6 +121,19 @@ class dpctl_capi PySyclKernelBundleObject *); PySyclKernelBundleObject *(*SyclKernelBundle_Make_)( DPCTLSyclKernelBundleRef); + DPCTLSyclInputKernelBundleRef (*SyclKernelBundle_GetInputKernelBundleRef_)( + PySyclKernelBundleObject *); + PySyclKernelBundleObject *(*SyclKernelBundle_MakeInput_)( + DPCTLSyclInputKernelBundleRef); + DPCTLSyclObjectKernelBundleRef ( + *SyclKernelBundle_GetObjectKernelBundleRef_)( + PySyclKernelBundleObject *); + PySyclKernelBundleObject *(*SyclKernelBundle_MakeObject_)( + DPCTLSyclObjectKernelBundleRef); + + DPCTLSyclKernelIdRef (*SyclKernelId_GetKernelIdRef_)( + PySyclKernelIdObject *); + PySyclKernelIdObject *(*SyclKernelId_Make_)(DPCTLSyclKernelIdRef); bool PySyclDevice_Check_(PyObject *obj) const { @@ -145,6 +159,10 @@ class dpctl_capi { return PyObject_TypeCheck(obj, PySyclKernelBundleType_) != 0; } + bool PySyclKernelId_Check_(PyObject *obj) const + { + return PyObject_TypeCheck(obj, PySyclKernelIdType_) != 0; + } ~dpctl_capi() { @@ -215,18 +233,23 @@ class dpctl_capi Py_MemoryType_(nullptr), PyMemoryUSMDeviceType_(nullptr), PyMemoryUSMSharedType_(nullptr), PyMemoryUSMHostType_(nullptr), PySyclKernelBundleType_(nullptr), PySyclKernelType_(nullptr), - SyclDevice_GetDeviceRef_(nullptr), SyclDevice_Make_(nullptr), - SyclContext_GetContextRef_(nullptr), SyclContext_Make_(nullptr), - SyclEvent_GetEventRef_(nullptr), SyclEvent_Make_(nullptr), - SyclQueue_GetQueueRef_(nullptr), SyclQueue_Make_(nullptr), - SyclQueue_DeferRelease_(nullptr), Memory_GetUsmPointer_(nullptr), - Memory_GetOpaquePointer_(nullptr), Memory_GetContextRef_(nullptr), - Memory_GetQueueRef_(nullptr), Memory_GetNumBytes_(nullptr), - Memory_Make_(nullptr), SyclKernel_GetKernelRef_(nullptr), - SyclKernel_Make_(nullptr), + PySyclKernelIdType_(nullptr), SyclDevice_GetDeviceRef_(nullptr), + SyclDevice_Make_(nullptr), SyclContext_GetContextRef_(nullptr), + SyclContext_Make_(nullptr), SyclEvent_GetEventRef_(nullptr), + SyclEvent_Make_(nullptr), SyclQueue_GetQueueRef_(nullptr), + SyclQueue_Make_(nullptr), SyclQueue_DeferRelease_(nullptr), + Memory_GetUsmPointer_(nullptr), Memory_GetOpaquePointer_(nullptr), + Memory_GetContextRef_(nullptr), Memory_GetQueueRef_(nullptr), + Memory_GetNumBytes_(nullptr), Memory_Make_(nullptr), + SyclKernel_GetKernelRef_(nullptr), SyclKernel_Make_(nullptr), SyclKernelBundle_GetKernelBundleRef_(nullptr), - SyclKernelBundle_Make_(nullptr), default_sycl_queue_{}, - default_usm_memory_{}, as_usm_memory_{} + SyclKernelBundle_Make_(nullptr), + SyclKernelBundle_GetInputKernelBundleRef_(nullptr), + SyclKernelBundle_MakeInput_(nullptr), + SyclKernelBundle_GetObjectKernelBundleRef_(nullptr), + SyclKernelBundle_MakeObject_(nullptr), + SyclKernelId_GetKernelIdRef_(nullptr), SyclKernelId_Make_(nullptr), + default_sycl_queue_{}, default_usm_memory_{}, as_usm_memory_{} { // Import Cython-generated C-API for dpctl @@ -253,6 +276,7 @@ class dpctl_capi this->PyMemoryUSMHostType_ = &PyMemoryUSMHostType; this->PySyclKernelBundleType_ = &PySyclKernelBundleType; this->PySyclKernelType_ = &PySyclKernelType; + this->PySyclKernelIdType_ = &PySyclKernelIdType; // SyclDevice API this->SyclDevice_GetDeviceRef_ = SyclDevice_GetDeviceRef; @@ -285,6 +309,14 @@ class dpctl_capi this->SyclKernelBundle_GetKernelBundleRef_ = SyclKernelBundle_GetKernelBundleRef; this->SyclKernelBundle_Make_ = SyclKernelBundle_Make; + this->SyclKernelBundle_GetInputKernelBundleRef_ = + SyclKernelBundle_GetInputKernelBundleRef; + this->SyclKernelBundle_MakeInput_ = SyclKernelBundle_MakeInput; + this->SyclKernelBundle_GetObjectKernelBundleRef_ = + SyclKernelBundle_GetObjectKernelBundleRef; + this->SyclKernelBundle_MakeObject_ = SyclKernelBundle_MakeObject; + this->SyclKernelId_GetKernelIdRef_ = SyclKernelId_GetKernelIdRef; + this->SyclKernelId_Make_ = SyclKernelId_Make; // create shared pointers to python objects used in type-casters // for dpctl::memory::usm_memory @@ -555,6 +587,11 @@ struct type_caster> DPCTLSyclKernelBundleRef KBRef = api.SyclKernelBundle_GetKernelBundleRef_( reinterpret_cast(source)); + if (!KBRef) { + throw py::type_error("Input is not in 'executable' state, " + "expected dpctl.compiler.SyclKernelBundle " + "in 'executable' state"); + } value = std::make_unique< sycl::kernel_bundle>( *(reinterpret_cast< @@ -582,6 +619,135 @@ struct type_caster> _("dpctl.compiler.SyclKernelBundle")); }; +/* This type caster associates + * ``sycl::kernel_bundle`` C++ class with + * :class:`dpctl.compiler.SyclKernelBundle` in ``input`` state for the + * purposes of generation of Python bindings by pybind11. + */ +template <> struct type_caster> +{ +public: + bool load(handle src, bool) + { + PyObject *source = src.ptr(); + auto const &api = ::dpctl::detail::dpctl_capi::get(); + if (api.PySyclKernelBundle_Check_(source)) { + DPCTLSyclInputKernelBundleRef KBRef = + api.SyclKernelBundle_GetInputKernelBundleRef_( + reinterpret_cast(source)); + if (!KBRef) { + throw py::type_error("Input is not in 'input' state, " + "expected dpctl.compiler.SyclKernelBundle " + "in 'input' state"); + } + value = std::make_unique< + sycl::kernel_bundle>( + *(reinterpret_cast< + sycl::kernel_bundle *>(KBRef))); + return true; + } + else { + throw py::type_error("Input is of unexpected type, expected " + "dpctl.compiler.SyclKernelBundle"); + } + } + + static handle cast(sycl::kernel_bundle src, + return_value_policy, + handle) + { + auto const &api = ::dpctl::detail::dpctl_capi::get(); + auto tmp = api.SyclKernelBundle_MakeInput_( + reinterpret_cast(&src)); + return handle(reinterpret_cast(tmp)); + } + + DPCTL_TYPE_CASTER(sycl::kernel_bundle, + _("dpctl.compiler.SyclKernelBundle")); +}; + +/* This type caster associates + * ``sycl::kernel_bundle`` C++ class with + * :class:`dpctl.compiler.SyclKernelBundle` in ``object`` state for the + * purposes of generation of Python bindings by pybind11. + */ +template <> struct type_caster> +{ +public: + bool load(handle src, bool) + { + PyObject *source = src.ptr(); + auto const &api = ::dpctl::detail::dpctl_capi::get(); + if (api.PySyclKernelBundle_Check_(source)) { + DPCTLSyclObjectKernelBundleRef KBRef = + api.SyclKernelBundle_GetObjectKernelBundleRef_( + reinterpret_cast(source)); + if (!KBRef) { + throw py::type_error("Input is not in 'object' state, " + "expected dpctl.compiler.SyclKernelBundle " + "in 'object' state"); + } + value = std::make_unique< + sycl::kernel_bundle>( + *(reinterpret_cast< + sycl::kernel_bundle *>(KBRef))); + return true; + } + else { + throw py::type_error("Input is of unexpected type, expected " + "dpctl.compiler.SyclKernelBundle"); + } + } + + static handle cast(sycl::kernel_bundle src, + return_value_policy, + handle) + { + auto const &api = ::dpctl::detail::dpctl_capi::get(); + auto tmp = api.SyclKernelBundle_MakeObject_( + reinterpret_cast(&src)); + return handle(reinterpret_cast(tmp)); + } + + DPCTL_TYPE_CASTER(sycl::kernel_bundle, + _("dpctl.compiler.SyclKernelBundle")); +}; + +/* This type caster associates ``sycl::kernel_id`` C++ class with + * :class:`dpctl.compiler.SyclKernelId` for the purposes of generation of + * Python bindings by pybind11. + */ +template <> struct type_caster +{ +public: + bool load(handle src, bool) + { + PyObject *source = src.ptr(); + auto const &api = ::dpctl::detail::dpctl_capi::get(); + if (api.PySyclKernelId_Check_(source)) { + DPCTLSyclKernelIdRef KIdRef = api.SyclKernelId_GetKernelIdRef_( + reinterpret_cast(source)); + value = std::make_unique( + *(reinterpret_cast(KIdRef))); + return true; + } + else { + throw py::type_error("Input is of unexpected type, expected " + "dpctl.compiler.SyclKernelId"); + } + } + + static handle cast(sycl::kernel_id src, return_value_policy, handle) + { + auto const &api = ::dpctl::detail::dpctl_capi::get(); + auto tmp = api.SyclKernelId_Make_( + reinterpret_cast(&src)); + return handle(reinterpret_cast(tmp)); + } + + DPCTL_TYPE_CASTER(sycl::kernel_id, _("dpctl.compiler.SyclKernelId")); +}; + /* This type caster associates * ``sycl::half`` C++ class with Python :class:`float` for the purposes * of generation of Python bindings by pybind11. diff --git a/dpctl/compiler/__init__.py b/dpctl/compiler/__init__.py index e54e30f6a5..a4a36d904a 100644 --- a/dpctl/compiler/__init__.py +++ b/dpctl/compiler/__init__.py @@ -17,31 +17,54 @@ """ **Data Parallel Control Compiler** provides a way to create a SYCL kernel from either an OpenCL program represented as a string or a SPIR-V binary -file. +file, and to work with the kernel bundles of kernels compiled into the +application. """ from dpctl.compiler._compiler import ( SpecializationConstant, + SyclDeviceImage, SyclKernel, SyclKernelBundle, SyclKernelBundleCompilationError, + SyclKernelId, + build, + compile, create_kernel_bundle_from_source, create_kernel_bundle_from_spirv, create_kernel_bundle_from_sycl_source, + get_kernel_bundle, + get_kernel_ids, + has_kernel_bundle, + is_compatible, is_sycl_source_compilation_available, + join, + link, + load_kernel_library, ) from . import utils __all__ = [ + "build", + "compile", "create_kernel_bundle_from_source", "create_kernel_bundle_from_spirv", "create_kernel_bundle_from_sycl_source", + "get_kernel_bundle", + "get_kernel_ids", + "has_kernel_bundle", + "is_compatible", "is_sycl_source_compilation_available", + "join", + "link", + "load_kernel_library", + "SyclDeviceImage", "SyclKernel", "SyclKernelBundle", "SyclKernelBundleCompilationError", + "SyclKernelId", "SpecializationConstant", ] diff --git a/dpctl/compiler/_compiler.pxd b/dpctl/compiler/_compiler.pxd index 3958a2f83e..d6db3939b7 100644 --- a/dpctl/compiler/_compiler.pxd +++ b/dpctl/compiler/_compiler.pxd @@ -22,7 +22,14 @@ """ -from .._backend cimport DPCTLSyclKernelBundleRef, DPCTLSyclKernelRef +from .._backend cimport ( + DPCTLSyclDeviceImageRef, + DPCTLSyclInputKernelBundleRef, + DPCTLSyclKernelBundleRef, + DPCTLSyclKernelIdRef, + DPCTLSyclKernelRef, + DPCTLSyclObjectKernelBundleRef, +) from .._sycl_context cimport SyclContext from .._sycl_device cimport SyclDevice from .._sycl_queue cimport SyclQueue @@ -40,6 +47,18 @@ cdef api class SyclKernel [object PySyclKernelObject, type PySyclKernelType]: cdef SyclKernel _create (DPCTLSyclKernelRef kref, str name) +cdef api class SyclKernelId [ + object PySyclKernelIdObject, type PySyclKernelIdType +]: + """ Wraps a ``sycl::kernel_id`` object. + """ + cdef DPCTLSyclKernelIdRef _kernel_id_ref + cdef DPCTLSyclKernelIdRef get_kernel_id_ref(self) + + @staticmethod + cdef SyclKernelId _create(DPCTLSyclKernelIdRef kid_ref) + + cdef api class SyclKernelBundle [ object PySyclKernelBundleObject, type PySyclKernelBundleType ]: @@ -53,20 +72,45 @@ cdef api class SyclKernelBundle [ """ cdef DPCTLSyclKernelBundleRef _kernel_bundle_ref cdef bint _is_sycl_source + cdef DPCTLSyclInputKernelBundleRef _input_ref + cdef DPCTLSyclObjectKernelBundleRef _object_ref + cdef int _state @staticmethod cdef SyclKernelBundle _create (DPCTLSyclKernelBundleRef kbref, bint _is_sycl_source) + + @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) +cdef class SyclDeviceImage: + """ A device image of a :class:`SyclKernelBundle`. + """ + cdef SyclKernelBundle _kernel_bundle + cdef size_t _index + cdef DPCTLSyclDeviceImageRef _image_ref + cdef int _state + + cpdef create_kernel_bundle_from_source ( SyclQueue q, unicode source, unicode copts=* ) cpdef create_kernel_bundle_from_spirv ( SyclQueue q, - const unsigned char[:] IL, + const unsigned char[::1] IL, unicode copts=*, list specializations=*, ) @@ -77,3 +121,7 @@ cpdef create_kernel_bundle_from_sycl_source(SyclQueue q, unicode source, list copts=*) cpdef bint is_sycl_source_compilation_available() + +cpdef tuple get_kernel_ids() + +cpdef bint is_compatible(object kernel_ids, SyclDevice device) diff --git a/dpctl/compiler/_compiler.pyx b/dpctl/compiler/_compiler.pyx index 58d7a56310..2693eca770 100644 --- a/dpctl/compiler/_compiler.pyx +++ b/dpctl/compiler/_compiler.pyx @@ -39,12 +39,38 @@ from cpython.bytes cimport PyBytes_FromStringAndSize from libc.stdint cimport UINT32_MAX, uint32_t from libc.stdlib cimport free, malloc from libc.string cimport memcmp, memcpy +from libcpp cimport bool as cpp_bool from dpctl._backend cimport ( # noqa: E211, E402; DPCTLBuildOptionList_Append, DPCTLBuildOptionList_Create, DPCTLBuildOptionList_Delete, DPCTLBuildOptionListRef, + DPCTLCString_Delete, + DPCTLDeviceImage_HasKernel, + DPCTLDeviceVector_CreateFromArray, + DPCTLDeviceVector_Delete, + DPCTLDeviceVector_GetAt, + DPCTLDeviceVector_Size, + DPCTLDeviceVectorRef, + DPCTLInputKernelBundle_Build, + DPCTLInputKernelBundle_CanCreateFromContext, + DPCTLInputKernelBundle_Compile, + DPCTLInputKernelBundle_ContainsSpecializationConstants, + DPCTLInputKernelBundle_Copy, + DPCTLInputKernelBundle_CreateFromContext, + DPCTLInputKernelBundle_CreateFromContextWithSelector, + DPCTLInputKernelBundle_Delete, + DPCTLInputKernelBundle_DeviceImageHasKernel, + DPCTLInputKernelBundle_GetBackend, + DPCTLInputKernelBundle_GetContext, + DPCTLInputKernelBundle_GetDevices, + DPCTLInputKernelBundle_GetKernelIds, + DPCTLInputKernelBundle_GetNumDeviceImages, + DPCTLInputKernelBundle_HasKernelId, + DPCTLInputKernelBundle_IsEmpty, + DPCTLInputKernelBundle_Join, + DPCTLInputKernelBundle_NativeSpecializationConstant, DPCTLKernel_Copy, DPCTLKernel_Delete, DPCTLKernel_GetCompileNumSubGroups, @@ -59,49 +85,113 @@ from dpctl._backend cimport ( # noqa: E211, E402; DPCTLKernelBuildLog_Delete, DPCTLKernelBuildLog_Get, DPCTLKernelBuildLogRef, + DPCTLKernelBundle_CanCreateFromContext, + DPCTLKernelBundle_ContainsSpecializationConstants, DPCTLKernelBundle_Copy, + DPCTLKernelBundle_CreateFromContext, + DPCTLKernelBundle_CreateFromContextWithSelector, DPCTLKernelBundle_CreateFromOCLSource, DPCTLKernelBundle_CreateFromSpirv, DPCTLKernelBundle_CreateFromSYCLSource, DPCTLKernelBundle_CreateFromSYCLSource_Available, DPCTLKernelBundle_Delete, + DPCTLKernelBundle_DeviceImageHasKernel, + DPCTLKernelBundle_GetBackend, + DPCTLKernelBundle_GetContext, + DPCTLKernelBundle_GetDevices, DPCTLKernelBundle_GetKernel, + DPCTLKernelBundle_GetKernelById, + DPCTLKernelBundle_GetKernelIds, + DPCTLKernelBundle_GetNumDeviceImages, DPCTLKernelBundle_GetSyclKernel, DPCTLKernelBundle_HasKernel, + DPCTLKernelBundle_HasKernelId, DPCTLKernelBundle_HasSyclKernel, + DPCTLKernelBundle_IsEmpty, + DPCTLKernelBundle_Join, + DPCTLKernelBundle_NativeSpecializationConstant, + DPCTLKernelId_AreEq, + DPCTLKernelId_Copy, + DPCTLKernelId_Delete, + DPCTLKernelId_GetAll, + DPCTLKernelId_GetName, + DPCTLKernelId_Hash, + DPCTLKernelId_IsCompatible, + DPCTLKernelId_LoadLibrary, + DPCTLKernelIdVector_CreateFromArray, + DPCTLKernelIdVector_Delete, + DPCTLKernelIdVector_GetAt, + DPCTLKernelIdVector_Size, + DPCTLKernelIdVectorRef, DPCTLKernelNameList_Append, DPCTLKernelNameList_Create, DPCTLKernelNameList_Delete, DPCTLKernelNameListRef, + DPCTLObjectKernelBundle_CanCreateFromContext, + DPCTLObjectKernelBundle_ContainsSpecializationConstants, + DPCTLObjectKernelBundle_Copy, + DPCTLObjectKernelBundle_CreateFromContext, + DPCTLObjectKernelBundle_CreateFromContextWithSelector, + DPCTLObjectKernelBundle_Delete, + DPCTLObjectKernelBundle_DeviceImageHasKernel, + DPCTLObjectKernelBundle_GetBackend, + DPCTLObjectKernelBundle_GetContext, + DPCTLObjectKernelBundle_GetDevices, + DPCTLObjectKernelBundle_GetKernelIds, + DPCTLObjectKernelBundle_GetNumDeviceImages, + DPCTLObjectKernelBundle_HasKernelId, + DPCTLObjectKernelBundle_IsEmpty, + DPCTLObjectKernelBundle_Join, + DPCTLObjectKernelBundle_Link, + DPCTLObjectKernelBundle_NativeSpecializationConstant, DPCTLSyclContextRef, + DPCTLSyclDeviceImageRef, DPCTLSyclDeviceRef, + DPCTLSyclInputKernelBundleRef, DPCTLSyclKernelBundleRef, + DPCTLSyclKernelIdRef, DPCTLSyclKernelRef, + DPCTLSyclObjectKernelBundleRef, DPCTLVirtualHeaderList_Append, DPCTLVirtualHeaderList_Create, DPCTLVirtualHeaderList_Delete, DPCTLVirtualHeaderListRef, + _backend_type, _spec_const, ) import numbers +import os import numpy as np +from dpctl.enum_types import backend_type + __all__ = [ + "build", + "compile", "create_kernel_bundle_from_source", "create_kernel_bundle_from_spirv", "create_kernel_bundle_from_sycl_source", + "get_kernel_bundle", + "get_kernel_ids", + "has_kernel_bundle", + "is_compatible", "is_sycl_source_compilation_available", + "join", + "link", + "load_kernel_library", + "SyclDeviceImage", "SyclKernel", "SyclKernelBundle", "SyclKernelBundleCompilationError", + "SyclKernelId", "SpecializationConstant", ] cdef class SyclKernelBundleCompilationError(Exception): """This exception is raised when a ``sycl::kernel_bundle`` could not be - built from either a SPIR-V binary file or a string source. + created, compiled, linked, built or joined. """ pass @@ -117,6 +207,130 @@ cpdef bint is_sycl_source_compilation_available(): return DPCTLKernelBundle_CreateFromSYCLSource_Available() +cdef enum _kernel_bundle_state: + _KB_STATE_EXECUTABLE = 0 + _KB_STATE_INPUT = 1 + _KB_STATE_OBJECT = 2 + + +cdef object _backend_type_to_enum(_backend_type BTy): + if BTy == _backend_type._CUDA: + return backend_type.cuda + elif BTy == _backend_type._HIP: + return backend_type.hip + elif BTy == _backend_type._LEVEL_ZERO: + return backend_type.level_zero + elif BTy == _backend_type._OPENCL: + return backend_type.opencl + else: + raise ValueError("Unknown backend type.") + + +cdef str _state_to_str(int state): + if state == _KB_STATE_INPUT: + return "input" + elif state == _KB_STATE_OBJECT: + return "object" + return "executable" + + +cdef _kernel_bundle_state _state_from_str(str state) except *: + if state == "executable": + return _KB_STATE_EXECUTABLE + elif state == "input": + return _KB_STATE_INPUT + elif state == "object": + return _KB_STATE_OBJECT + raise ValueError( + "Kernel bundle state must be 'input', 'object' or 'executable', " + f"got '{state}'" + ) + + +cdef DPCTLDeviceVectorRef _device_vector(object devices) except *: + """ Returns a new device vector, or NULL if ``devices`` is None.""" + cdef DPCTLSyclDeviceRef *DRefs = NULL + cdef DPCTLDeviceVectorRef DVRef = NULL + cdef size_t i + if devices is None: + return NULL + if isinstance(devices, SyclDevice): + devices = (devices,) + devices = tuple(devices) + for d in devices: + if not isinstance(d, SyclDevice): + raise TypeError( + f"Expected a sequence of SyclDevice objects, got {type(d)}" + ) + DRefs = malloc( + max(len(devices), 1) * sizeof(DPCTLSyclDeviceRef) + ) + if DRefs is NULL: + raise MemoryError() + for i in range(len(devices)): + DRefs[i] = (devices[i]).get_device_ref() + DVRef = DPCTLDeviceVector_CreateFromArray(len(devices), DRefs) + free(DRefs) + if DVRef is NULL: + raise MemoryError() + return DVRef + + +cdef DPCTLKernelIdVectorRef _kernel_id_vector(object kernel_ids) except *: + """ Returns a new kernel id vector, or NULL if ``kernel_ids`` is None.""" + cdef DPCTLSyclKernelIdRef *KIdRefs = NULL + cdef DPCTLKernelIdVectorRef KIdVRef = NULL + cdef size_t i + if kernel_ids is None: + return NULL + if isinstance(kernel_ids, SyclKernelId): + kernel_ids = (kernel_ids,) + kernel_ids = tuple(kernel_ids) + for kid in kernel_ids: + if not isinstance(kid, SyclKernelId): + raise TypeError( + f"Expected a sequence of SyclKernelId objects, got {type(kid)}" + ) + KIdRefs = malloc( + max(len(kernel_ids), 1) * sizeof(DPCTLSyclKernelIdRef) + ) + if KIdRefs is NULL: + raise MemoryError() + for i in range(len(kernel_ids)): + KIdRefs[i] = (kernel_ids[i]).get_kernel_id_ref() + KIdVRef = DPCTLKernelIdVector_CreateFromArray(len(kernel_ids), KIdRefs) + free(KIdRefs) + if KIdVRef is NULL: + raise MemoryError() + return KIdVRef + + +cdef tuple _devices_from_vector(DPCTLDeviceVectorRef DVRef): + """ Returns a tuple of SyclDevice objects and deletes ``DVRef``.""" + cdef size_t i + if DVRef is NULL: + raise ValueError("Internal error: NULL device vector encountered") + devices = [] + for i in range(DPCTLDeviceVector_Size(DVRef)): + devices.append(SyclDevice._create(DPCTLDeviceVector_GetAt(DVRef, i))) + DPCTLDeviceVector_Delete(DVRef) + return tuple(devices) + + +cdef tuple _kernel_ids_from_vector(DPCTLKernelIdVectorRef KIdVRef): + """ Returns a tuple of SyclKernelId objects and deletes ``KIdVRef``.""" + cdef size_t i + if KIdVRef is NULL: + raise ValueError("Internal error: NULL kernel id vector encountered") + kernel_ids = [] + for i in range(DPCTLKernelIdVector_Size(KIdVRef)): + kernel_ids.append( + SyclKernelId._create(DPCTLKernelIdVector_GetAt(KIdVRef, i)) + ) + DPCTLKernelIdVector_Delete(KIdVRef) + return tuple(kernel_ids) + + cdef class SyclKernel: """ """ @@ -137,8 +351,22 @@ cdef class SyclKernel: def get_num_args(self): """ Returns the number of arguments for this kernel function. + + For a kernel compiled from SYCL source, this is the number of + arguments of the backend kernel, in which a ``sycl::local_accessor`` + parameter is four arguments. + + Raises: + RuntimeError: + If the number of arguments can not be queried. """ - return DPCTLKernel_GetNumArgs(self._kernel_ref) + cdef size_t n = DPCTLKernel_GetNumArgs(self._kernel_ref) + if n == -1: + raise RuntimeError( + "The number of arguments of kernel " + f"'{self._function_name}' can not be queried." + ) + return n cdef DPCTLSyclKernelRef get_kernel_ref(self): """ Returns the ``DPCTLSyclKernelRef`` pointer for this SyclKernel. @@ -161,61 +389,132 @@ cdef class SyclKernel: """ return self.get_num_args() - @property - 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): + """work_group_size(device=None) + + Returns the maximum number of work-items in a work-group that can + be used to execute the kernel on the device. + + Args: + device (dpctl.SyclDevice, optional): + A device of the kernel bundle of the kernel. Default: + ``None``, meaning the first device of the kernel bundle. """ - cdef size_t v = DPCTLKernel_GetWorkGroupSize(self._kernel_ref) + cdef DPCTLSyclDeviceRef DRef = NULL + cdef size_t v + if device is not None: + DRef = device.get_device_ref() + v = DPCTLKernel_GetWorkGroupSize(self._kernel_ref, DRef) return v - @property - def preferred_work_group_size_multiple(self): - """ Returns a value, of which work-group size is preferred to be - a multiple, for executing the kernel on the device it was built for. + def preferred_work_group_size_multiple(self, SyclDevice device=None): + """preferred_work_group_size_multiple(device=None) + + Returns a value, of which work-group size is preferred to be + a multiple, for executing the kernel on the device. + + Args: + device (dpctl.SyclDevice, optional): + A device of the kernel bundle of the kernel. Default: + ``None``, meaning the first device of the kernel bundle. """ - cdef size_t v = DPCTLKernel_GetPreferredWorkGroupSizeMultiple( - self._kernel_ref + cdef DPCTLSyclDeviceRef DRef = NULL + cdef size_t v + if device is not None: + DRef = device.get_device_ref() + v = DPCTLKernel_GetPreferredWorkGroupSizeMultiple( + self._kernel_ref, DRef ) return v - @property - def private_mem_size(self): - """ Returns the minimum amount of private memory, in bytes, used by each - work-item in the kernel. + def private_mem_size(self, SyclDevice device=None): + """private_mem_size(device=None) + + Returns the minimum amount of private memory, in bytes, used by each + work-item in the kernel on the device. + + Args: + device (dpctl.SyclDevice, optional): + A device of the kernel bundle of the kernel. Default: + ``None``, meaning the first device of the kernel bundle. """ - cdef size_t v = DPCTLKernel_GetPrivateMemSize(self._kernel_ref) + cdef DPCTLSyclDeviceRef DRef = NULL + cdef size_t v + if device is not None: + DRef = device.get_device_ref() + v = DPCTLKernel_GetPrivateMemSize(self._kernel_ref, DRef) return v - @property - def max_num_sub_groups(self): - """ Returns the maximum number of sub-groups for this kernel. + def max_num_sub_groups(self, SyclDevice device=None): + """max_num_sub_groups(device=None) + + Returns the maximum number of sub-groups for this kernel on the + device. + + Args: + device (dpctl.SyclDevice, optional): + A device of the kernel bundle of the kernel. Default: + ``None``, meaning the first device of the kernel bundle. """ - cdef uint32_t n = DPCTLKernel_GetMaxNumSubGroups(self._kernel_ref) - return n + cdef DPCTLSyclDeviceRef DRef = NULL + cdef uint32_t v + if device is not None: + DRef = device.get_device_ref() + v = DPCTLKernel_GetMaxNumSubGroups(self._kernel_ref, DRef) + return v - @property - def max_sub_group_size(self): - """ Returns the maximum sub-groups size for this kernel. + def max_sub_group_size(self, SyclDevice device=None): + """max_sub_group_size(device=None) + + Returns the maximum sub-group size for this kernel on the device. + + Args: + device (dpctl.SyclDevice, optional): + A device of the kernel bundle of the kernel. Default: + ``None``, meaning the first device of the kernel bundle. """ - cdef uint32_t sz = DPCTLKernel_GetMaxSubGroupSize(self._kernel_ref) - return sz + cdef DPCTLSyclDeviceRef DRef = NULL + cdef uint32_t v + if device is not None: + DRef = device.get_device_ref() + v = DPCTLKernel_GetMaxSubGroupSize(self._kernel_ref, DRef) + return v - @property - def compile_num_sub_groups(self): - """ Returns the number of sub-groups specified by this kernel, - or 0 (if not specified). + def compile_num_sub_groups(self, SyclDevice device=None): + """compile_num_sub_groups(device=None) + + Returns the number of sub-groups specified by this kernel, or 0 + (if not specified). + + Args: + device (dpctl.SyclDevice, optional): + A device of the kernel bundle of the kernel. Default: + ``None``, meaning the first device of the kernel bundle. """ - cdef size_t n = DPCTLKernel_GetCompileNumSubGroups(self._kernel_ref) - return n + cdef DPCTLSyclDeviceRef DRef = NULL + cdef uint32_t v + if device is not None: + DRef = device.get_device_ref() + v = DPCTLKernel_GetCompileNumSubGroups(self._kernel_ref, DRef) + return v - @property - def compile_sub_group_size(self): - """ Returns the required sub-group size specified by this kernel, - or 0 (if not specified). + def compile_sub_group_size(self, SyclDevice device=None): + """compile_sub_group_size(device=None) + + Returns the required sub-group size specified by this kernel, or 0 + (if not specified). + + Args: + device (dpctl.SyclDevice, optional): + A device of the kernel bundle of the kernel. Default: + ``None``, meaning the first device of the kernel bundle. """ - cdef size_t n = DPCTLKernel_GetCompileSubGroupSize(self._kernel_ref) - return n + cdef DPCTLSyclDeviceRef DRef = NULL + cdef uint32_t v + if device is not None: + DRef = device.get_device_ref() + v = DPCTLKernel_GetCompileSubGroupSize(self._kernel_ref, DRef) + return v cdef api DPCTLSyclKernelRef SyclKernel_GetKernelRef(SyclKernel ker): @@ -237,17 +536,81 @@ cdef api SyclKernel SyclKernel_Make(DPCTLSyclKernelRef KRef, const char *name): return SyclKernel._create(copied_KRef, name.decode("utf-8")) +cdef class SyclKernelId: + """ Wraps a ``sycl::kernel_id``, which identifies a kernel defined by the + application. + + Kernel ids are obtained from :func:`.get_kernel_ids` and + :meth:`.SyclKernelBundle.get_kernel_ids`. + """ + @staticmethod + cdef SyclKernelId _create(DPCTLSyclKernelIdRef kid_ref): + """ Takes ownership of ``kid_ref``.""" + cdef SyclKernelId ret = SyclKernelId.__new__(SyclKernelId) + ret._kernel_id_ref = kid_ref + return ret + + def __init__(self): + raise TypeError( + "SyclKernelId objects are obtained from get_kernel_ids() and " + "SyclKernelBundle.get_kernel_ids()" + ) + + def __dealloc__(self): + DPCTLKernelId_Delete(self._kernel_id_ref) + + cdef DPCTLSyclKernelIdRef get_kernel_id_ref(self): + """ Returns the ``DPCTLSyclKernelIdRef`` pointer for this SyclKernelId. + """ + return self._kernel_id_ref + + @property + def name(self): + """ Returns the name of the kernel as known to the SYCL runtime. + """ + cdef const char *cname = DPCTLKernelId_GetName(self._kernel_id_ref) + if cname is NULL: + raise ValueError("Internal error: NULL kernel name encountered") + try: + return cname.decode("utf-8") + finally: + DPCTLCString_Delete(cname) + + def addressof_ref(self): + """ Returns the address of the C API ``DPCTLSyclKernelIdRef`` pointer + as a ``size_t``. + """ + return int(self._kernel_id_ref) + + def __eq__(self, other): + if not isinstance(other, SyclKernelId): + return NotImplemented + return DPCTLKernelId_AreEq( + self._kernel_id_ref, (other)._kernel_id_ref + ) + + def __hash__(self): + return DPCTLKernelId_Hash(self._kernel_id_ref) + + def __repr__(self): + return f"" + + cdef class SyclKernelBundle: - """ Wraps a ``sycl::kernel_bundle`` object - created using SYCL interoperability layer with underlying backends. Only the - OpenCL and Level-Zero backends are currently supported. + """ Wraps a ``sycl::kernel_bundle`` object in ``input``, ``object`` or + ``executable`` state, see :attr:`state`. SyclKernelBundle exposes the C API from - ``dpctl_sycl_kernel_bundle_interface.h``. A SyclKernelBundle can be - created from an OpenCL C source string + ``dpctl_sycl_kernel_bundle_interface.h``. A SyclKernelBundle in + ``executable`` state can be created from an OpenCL C source string (:func:`.create_kernel_bundle_from_source`), a SPIR-V binary file (:func:`.create_kernel_bundle_from_spirv`), or a SYCL source string - (:func:`.create_kernel_bundle_from_sycl_source`). + (:func:`.create_kernel_bundle_from_sycl_source`), using the SYCL + interoperability layer of the OpenCL and Level-Zero backends. + + A SyclKernelBundle in any state can be created from the kernels compiled + into the application with :func:`.get_kernel_bundle`, and converted with + :func:`.compile`, :func:`.link`, :func:`.build` and :func:`.join`. Creation from SYCL source uses the DPC++ ``kernel_compiler`` extension, which requires both a compiler and a device that support it. Use @@ -261,14 +624,265 @@ cdef class SyclKernelBundle: cdef SyclKernelBundle ret = SyclKernelBundle.__new__(SyclKernelBundle) ret._kernel_bundle_ref = KBRef ret._is_sycl_source = is_sycl_source + ret._state = _KB_STATE_EXECUTABLE + return ret + + @staticmethod + cdef SyclKernelBundle _create_input(DPCTLSyclInputKernelBundleRef KBRef): + cdef SyclKernelBundle ret = SyclKernelBundle.__new__(SyclKernelBundle) + ret._input_ref = KBRef + ret._state = _KB_STATE_INPUT + return ret + + @staticmethod + cdef SyclKernelBundle _create_object(DPCTLSyclObjectKernelBundleRef KBRef): + cdef SyclKernelBundle ret = SyclKernelBundle.__new__(SyclKernelBundle) + ret._object_ref = KBRef + ret._state = _KB_STATE_OBJECT return ret def __dealloc__(self): DPCTLKernelBundle_Delete(self._kernel_bundle_ref) + DPCTLInputKernelBundle_Delete(self._input_ref) + DPCTLObjectKernelBundle_Delete(self._object_ref) cdef DPCTLSyclKernelBundleRef get_kernel_bundle_ref(self): + """ Returns the executable kernel bundle reference, or NULL if the + kernel bundle is not in ``executable`` state. + """ return self._kernel_bundle_ref + cdef DPCTLSyclInputKernelBundleRef get_input_kernel_bundle_ref(self): + """ Returns the input kernel bundle reference, or NULL if the kernel + bundle is not in ``input`` state. + """ + return self._input_ref + + cdef DPCTLSyclObjectKernelBundleRef get_object_kernel_bundle_ref(self): + """ Returns the object kernel bundle reference, or NULL if the kernel + bundle is not in ``object`` state. + """ + return self._object_ref + + cdef _require_executable(self, str what): + if self._state != _KB_STATE_EXECUTABLE: + raise ValueError( + f"{what} requires a kernel bundle in 'executable' state, " + f"this kernel bundle is in '{self.state}' state" + ) + + @property + def state(self): + """ Returns the state of the kernel bundle: ``"input"``, + ``"object"`` or ``"executable"``. + """ + return _state_to_str(self._state) + + @property + def backend(self): + """ Returns the ``backend_type`` enum value of the kernel bundle. + """ + cdef _backend_type BTy + if self._state == _KB_STATE_INPUT: + BTy = DPCTLInputKernelBundle_GetBackend(self._input_ref) + elif self._state == _KB_STATE_OBJECT: + BTy = DPCTLObjectKernelBundle_GetBackend(self._object_ref) + else: + BTy = DPCTLKernelBundle_GetBackend(self._kernel_bundle_ref) + return _backend_type_to_enum(BTy) + + @property + def sycl_context(self): + """ Returns the :class:`dpctl.SyclContext` of the kernel bundle. + """ + cdef DPCTLSyclContextRef CRef + if self._state == _KB_STATE_INPUT: + CRef = DPCTLInputKernelBundle_GetContext(self._input_ref) + elif self._state == _KB_STATE_OBJECT: + CRef = DPCTLObjectKernelBundle_GetContext(self._object_ref) + else: + CRef = DPCTLKernelBundle_GetContext(self._kernel_bundle_ref) + if CRef is NULL: + raise ValueError("Internal error: NULL context encountered") + return SyclContext._create(CRef) + + def get_devices(self): + """ Returns a tuple of the :class:`dpctl.SyclDevice` objects + associated with the kernel bundle. + """ + cdef DPCTLDeviceVectorRef DVRef + if self._state == _KB_STATE_INPUT: + DVRef = DPCTLInputKernelBundle_GetDevices(self._input_ref) + elif self._state == _KB_STATE_OBJECT: + DVRef = DPCTLObjectKernelBundle_GetDevices(self._object_ref) + else: + DVRef = DPCTLKernelBundle_GetDevices(self._kernel_bundle_ref) + return _devices_from_vector(DVRef) + + @property + def is_empty(self): + """ Returns True if the kernel bundle contains no device images. + """ + if self._state == _KB_STATE_INPUT: + return DPCTLInputKernelBundle_IsEmpty(self._input_ref) + elif self._state == _KB_STATE_OBJECT: + return DPCTLObjectKernelBundle_IsEmpty(self._object_ref) + return DPCTLKernelBundle_IsEmpty(self._kernel_bundle_ref) + + def get_kernel_ids(self): + """ Returns a tuple of :class:`.SyclKernelId` objects for the kernels + in the kernel bundle. + + Kernel bundles created with the backend interoperability layer, e.g. + from OpenCL source or SPIR-V, report no kernel ids. + """ + cdef DPCTLKernelIdVectorRef KIdVRef + if self._state == _KB_STATE_INPUT: + KIdVRef = DPCTLInputKernelBundle_GetKernelIds(self._input_ref) + elif self._state == _KB_STATE_OBJECT: + KIdVRef = DPCTLObjectKernelBundle_GetKernelIds(self._object_ref) + else: + KIdVRef = DPCTLKernelBundle_GetKernelIds(self._kernel_bundle_ref) + return _kernel_ids_from_vector(KIdVRef) + + def has_kernel(self, SyclKernelId kernel_id not None, + SyclDevice device=None): + """has_kernel(kernel_id, device=None) + + Returns True if the kernel bundle contains the kernel, compatible with + ``device`` if one is given. + + Args: + kernel_id (dpctl.compiler.SyclKernelId): + Id of the kernel. + device (dpctl.SyclDevice, optional): + Device the kernel must be compatible with. Default: ``None``. + + Returns: + bool: + Whether the kernel bundle contains the kernel. + """ + cdef DPCTLSyclKernelIdRef KIdRef = kernel_id.get_kernel_id_ref() + cdef DPCTLSyclDeviceRef DRef = NULL + if device is not None: + DRef = device.get_device_ref() + if self._state == _KB_STATE_INPUT: + return DPCTLInputKernelBundle_HasKernelId( + self._input_ref, KIdRef, DRef + ) + elif self._state == _KB_STATE_OBJECT: + return DPCTLObjectKernelBundle_HasKernelId( + self._object_ref, KIdRef, DRef + ) + return DPCTLKernelBundle_HasKernelId( + self._kernel_bundle_ref, KIdRef, DRef + ) + + def get_kernel(self, SyclKernelId kernel_id not None): + """get_kernel(kernel_id) + + Returns the kernel with the given id from a kernel bundle in + ``executable`` state. + + Args: + kernel_id (dpctl.compiler.SyclKernelId): + Id of the kernel. + + Returns: + dpctl.compiler.SyclKernel: + The kernel object. + + Raises: + ValueError: + If the kernel bundle is not in ``executable`` state, or does + not contain the kernel. + """ + cdef DPCTLSyclKernelRef KRef + self._require_executable("get_kernel") + KRef = DPCTLKernelBundle_GetKernelById( + self._kernel_bundle_ref, kernel_id.get_kernel_id_ref() + ) + if KRef is NULL: + raise ValueError( + f"Kernel '{kernel_id.name}' could not be obtained from the " + "kernel bundle." + ) + return SyclKernel._create(KRef, kernel_id.name) + + @property + def contains_specialization_constants(self): + """ Returns True if any device image of the kernel bundle uses + SYCL specialization constants. + """ + if self._state == _KB_STATE_INPUT: + return DPCTLInputKernelBundle_ContainsSpecializationConstants( + self._input_ref + ) + elif self._state == _KB_STATE_OBJECT: + return DPCTLObjectKernelBundle_ContainsSpecializationConstants( + self._object_ref + ) + return DPCTLKernelBundle_ContainsSpecializationConstants( + self._kernel_bundle_ref + ) + + @property + def native_specialization_constant(self): + """ Returns True if all SYCL specialization constants of the kernel + bundle are native to the backend. + """ + if self._state == _KB_STATE_INPUT: + return DPCTLInputKernelBundle_NativeSpecializationConstant( + self._input_ref + ) + elif self._state == _KB_STATE_OBJECT: + return DPCTLObjectKernelBundle_NativeSpecializationConstant( + self._object_ref + ) + return DPCTLKernelBundle_NativeSpecializationConstant( + self._kernel_bundle_ref + ) + + def get_device_images(self): + """ Returns a tuple of the :class:`.SyclDeviceImage` objects of the + kernel bundle. + """ + cdef size_t n + cdef size_t i + cdef SyclDeviceImage img + if self._state == _KB_STATE_INPUT: + n = DPCTLInputKernelBundle_GetNumDeviceImages(self._input_ref) + elif self._state == _KB_STATE_OBJECT: + n = DPCTLObjectKernelBundle_GetNumDeviceImages(self._object_ref) + else: + n = DPCTLKernelBundle_GetNumDeviceImages(self._kernel_bundle_ref) + images = [] + for i in range(n): + img = SyclDeviceImage.__new__(SyclDeviceImage) + img._kernel_bundle = self + img._index = i + images.append(img) + return tuple(images) + + cdef bint _device_image_has_kernel( + self, size_t index, SyclKernelId kernel_id, SyclDevice device + ): + cdef DPCTLSyclKernelIdRef KIdRef = kernel_id.get_kernel_id_ref() + cdef DPCTLSyclDeviceRef DRef = NULL + if device is not None: + DRef = device.get_device_ref() + if self._state == _KB_STATE_INPUT: + return DPCTLInputKernelBundle_DeviceImageHasKernel( + self._input_ref, index, KIdRef, DRef + ) + elif self._state == _KB_STATE_OBJECT: + return DPCTLObjectKernelBundle_DeviceImageHasKernel( + self._object_ref, index, KIdRef, DRef + ) + return DPCTLKernelBundle_DeviceImageHasKernel( + self._kernel_bundle_ref, index, KIdRef, DRef + ) + cpdef SyclKernel get_sycl_kernel(self, str kernel_name): """get_sycl_kernel(kernel_name) @@ -288,11 +902,13 @@ cdef class SyclKernelBundle: Raises: ValueError: - If the kernel could not be created for any reason. + If the kernel bundle is not in ``executable`` state, or the + kernel could not be created for any reason. """ cdef bytes name = kernel_name.encode("utf8") cdef DPCTLSyclKernelRef KRef = NULL + self._require_executable("get_sycl_kernel") if self._is_sycl_source: KRef = DPCTLKernelBundle_GetSyclKernel( self._kernel_bundle_ref, name @@ -312,6 +928,8 @@ cdef class SyclKernelBundle: def has_sycl_kernel(self, str kernel_name): name = kernel_name.encode("utf8") + if self._state != _KB_STATE_EXECUTABLE: + return False if self._is_sycl_source: return DPCTLKernelBundle_HasSyclKernel( self._kernel_bundle_ref, name @@ -330,6 +948,61 @@ cdef class SyclKernelBundle: return int(self._kernel_bundle_ref) +cdef class SyclDeviceImage: + """ A device image of a :class:`.SyclKernelBundle`, obtained from + :meth:`.SyclKernelBundle.get_device_images`, or passed to the ``selector`` + of :func:`.get_kernel_bundle`, in which case it is valid only during the + call of the selector. + """ + def __init__(self): + raise TypeError( + "SyclDeviceImage objects are obtained from " + "SyclKernelBundle.get_device_images()" + ) + + @property + def state(self): + """ Returns the state of the kernel bundle the device image belongs + to. + """ + if self._kernel_bundle is not None: + return self._kernel_bundle.state + return _state_to_str(self._state) + + def has_kernel(self, SyclKernelId kernel_id not None, + SyclDevice device=None): + """has_kernel(kernel_id, device=None) + + Returns True if the device image contains the kernel, compatible with + ``device`` if one is given. + + Args: + kernel_id (dpctl.compiler.SyclKernelId): + Id of the kernel. + device (dpctl.SyclDevice, optional): + Device the kernel must be compatible with. Default: ``None``. + + Returns: + bool: + Whether the device image contains the kernel. + """ + cdef DPCTLSyclDeviceRef DRef = NULL + if self._kernel_bundle is not None: + return self._kernel_bundle._device_image_has_kernel( + self._index, kernel_id, device + ) + if self._image_ref is NULL: + raise ValueError( + "A device image passed to a selector is valid only during " + "the call of the selector" + ) + if device is not None: + DRef = device.get_device_ref() + return DPCTLDeviceImage_HasKernel( + self._image_ref, kernel_id.get_kernel_id_ref(), DRef + ) + + cdef api DPCTLSyclKernelBundleRef SyclKernelBundle_GetKernelBundleRef( SyclKernelBundle kb ): @@ -349,6 +1022,68 @@ cdef api SyclKernelBundle SyclKernelBundle_Make(DPCTLSyclKernelBundleRef KBRef): return SyclKernelBundle._create(copied_KBRef, False) +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() + + +cdef api DPCTLSyclObjectKernelBundleRef \ + SyclKernelBundle_GetObjectKernelBundleRef(SyclKernelBundle kb): + """ C-API function to access the opaque reference of a + :class:`dpctl.compiler.SyclKernelBundle` in ``object`` state, NULL for + other states. + """ + return kb.get_object_kernel_bundle_ref() + + +cdef api SyclKernelBundle SyclKernelBundle_MakeInput( + DPCTLSyclInputKernelBundleRef KBRef +): + """ + C-API function to create :class:`dpctl.compiler.SyclKernelBundle` + instance from opaque ``sycl::kernel_bundle`` + reference. + """ + cdef DPCTLSyclInputKernelBundleRef copied_KBRef = ( + DPCTLInputKernelBundle_Copy(KBRef) + ) + return SyclKernelBundle._create_input(copied_KBRef) + + +cdef api SyclKernelBundle SyclKernelBundle_MakeObject( + DPCTLSyclObjectKernelBundleRef KBRef +): + """ + C-API function to create :class:`dpctl.compiler.SyclKernelBundle` + instance from opaque ``sycl::kernel_bundle`` + reference. + """ + cdef DPCTLSyclObjectKernelBundleRef copied_KBRef = ( + DPCTLObjectKernelBundle_Copy(KBRef) + ) + return SyclKernelBundle._create_object(copied_KBRef) + + +cdef api DPCTLSyclKernelIdRef SyclKernelId_GetKernelIdRef(SyclKernelId kid): + """ C-API function to access opaque kernel id reference from + Python object of type :class:`dpctl.compiler.SyclKernelId`. + """ + return kid.get_kernel_id_ref() + + +cdef api SyclKernelId SyclKernelId_Make(DPCTLSyclKernelIdRef KIdRef): + """ + C-API function to create :class:`dpctl.compiler.SyclKernelId` + instance from opaque ``sycl::kernel_id`` reference. + """ + return SyclKernelId._create(DPCTLKernelId_Copy(KIdRef)) + + cdef class SpecializationConstant: """ SpecializationConstant(spec_id, *args) @@ -602,7 +1337,7 @@ cpdef create_kernel_bundle_from_source(SyclQueue q, str src, str copts=""): cpdef create_kernel_bundle_from_spirv( SyclQueue q, - const unsigned char[:] IL, + const unsigned char[::1] IL, str copts="", list specializations=None, ): @@ -820,3 +1555,486 @@ cpdef create_kernel_bundle_from_sycl_source(SyclQueue q, DPCTLKernelBuildLog_Delete(BuildLog) return SyclKernelBundle._create(KBref, True) + + +cpdef tuple get_kernel_ids(): + """get_kernel_ids() + + Returns the ids of all kernels compiled into the application, including + kernels of SYCL libraries loaded into the process. + + Returns: + tuple: + A tuple of :class:`.SyclKernelId` objects. + """ + return _kernel_ids_from_vector(DPCTLKernelId_GetAll()) + + +cpdef tuple load_kernel_library(object path): + """load_kernel_library(path) + + Loads a shared library with SYCL device code and returns the ids of the + kernels it registered with the SYCL runtime, making them available to + :func:`.get_kernel_bundle`. This includes libraries compiled for CUDA or + HIP devices, e.g. with ``-fsycl-targets=nvptx64-nvidia-cuda``. + + The library is never unloaded. Loading a library again returns the same + kernel ids; a library that was loaded by other means before returns none. + + Args: + path (str, os.PathLike): + Path of the shared library. + + Returns: + tuple: + A tuple of :class:`.SyclKernelId` objects. + + Raises: + OSError: + If the library could not be loaded. + """ + cdef bytes bpath = os.fsencode(path) + cdef DPCTLKernelIdVectorRef KIdVRef = DPCTLKernelId_LoadLibrary( + bpath + ) + if KIdVRef is NULL: + raise OSError( + f"Could not load the kernel library '{os.fsdecode(bpath)}'" + ) + return _kernel_ids_from_vector(KIdVRef) + +cpdef bint is_compatible(object kernel_ids, SyclDevice device): + """is_compatible(kernel_ids, device) + + Returns True if all given kernels can be used on the device. + + Args: + kernel_ids (Sequence[dpctl.compiler.SyclKernelId]): + Ids of the kernels. + device (dpctl.SyclDevice): + The device. + + Returns: + bool: + Whether the kernels are compatible with the device. + """ + cdef DPCTLKernelIdVectorRef KIdVRef + if device is None: + raise TypeError("device must be a SyclDevice, got None") + if kernel_ids is None: + raise TypeError("kernel_ids must be a sequence of SyclKernelId objects") + KIdVRef = _kernel_id_vector(kernel_ids) + try: + return DPCTLKernelId_IsCompatible(KIdVRef, device.get_device_ref()) + finally: + DPCTLKernelIdVector_Delete(KIdVRef) + + +cdef cpp_bool _device_image_selector( + DPCTLSyclDeviceImageRef ImgRef, void *UserData +) noexcept with gil: + """ Calls the Python selector in ``UserData``, a list of the selector, + the bundle state and the first exception raised by the selector. + """ + cdef list data = UserData + cdef SyclDeviceImage img + if data[2] is not None: + return False + img = SyclDeviceImage.__new__(SyclDeviceImage) + img._image_ref = ImgRef + img._state = data[1] + try: + return bool(data[0](img)) + except BaseException as e: + data[2] = e + return False + finally: + img._image_ref = NULL + + +cdef SyclContext _context_and_devices(object ctx, list devices_out): + """ Returns the context for ``ctx`` and appends the default devices for + ``ctx`` to ``devices_out``. + """ + if isinstance(ctx, SyclQueue): + devices_out.append((ctx).get_sycl_device()) + return (ctx).get_sycl_context() + elif isinstance(ctx, SyclContext): + return ctx + raise TypeError( + f"Expected a SyclContext or a SyclQueue, got {type(ctx)}" + ) + + +def get_kernel_bundle(ctx, devices=None, kernel_ids=None, + str state="executable", selector=None): + """get_kernel_bundle(ctx, devices=None, kernel_ids=None, \ +state="executable", selector=None) + + Returns a kernel bundle with the kernels compiled into the application + that are compatible with the given context and devices. + + Args: + ctx (dpctl.SyclContext, dpctl.SyclQueue): + The context of the kernel bundle. For a queue, its context is used + and ``devices`` defaults to the device of the queue. + devices (Sequence[dpctl.SyclDevice], optional): + Devices of the kernel bundle. Default: ``None``, meaning the + devices of the context. + kernel_ids (Sequence[dpctl.compiler.SyclKernelId], optional): + Ids of the kernels to include. Default: ``None``, meaning all + kernels. + state (str, optional): + State of the kernel bundle: ``"input"``, ``"object"`` or + ``"executable"``. Default: ``"executable"``. + selector (Callable[[dpctl.compiler.SyclDeviceImage], bool], optional): + Called on each device image of the application, which is + included in the kernel bundle if the selector returns True. + Cannot be combined with ``kernel_ids``. Default: ``None``. + + Returns: + dpctl.compiler.SyclKernelBundle: + The kernel bundle. + + Raises: + SyclKernelBundleCompilationError: + If the kernel bundle could not be created. + """ + cdef _kernel_bundle_state st = _state_from_str(state) + cdef list default_devices = [] + cdef SyclContext sctx = _context_and_devices(ctx, default_devices) + cdef DPCTLSyclContextRef CRef = sctx.get_context_ref() + cdef DPCTLDeviceVectorRef DVRef = NULL + cdef DPCTLKernelIdVectorRef KIdVRef = NULL + cdef DPCTLSyclInputKernelBundleRef InRef = NULL + cdef DPCTLSyclObjectKernelBundleRef ObjRef = NULL + cdef DPCTLSyclKernelBundleRef ExeRef = NULL + cdef list sel_data = None + if selector is not None: + if kernel_ids is not None: + raise ValueError("kernel_ids and selector cannot be combined") + if not callable(selector): + raise TypeError(f"selector must be callable, got {type(selector)}") + sel_data = [selector, st, None] + if devices is None and default_devices: + devices = default_devices + try: + DVRef = _device_vector(devices) + KIdVRef = _kernel_id_vector(kernel_ids) + if st == _KB_STATE_INPUT: + if sel_data is None: + InRef = DPCTLInputKernelBundle_CreateFromContext( + CRef, DVRef, KIdVRef + ) + else: + InRef = DPCTLInputKernelBundle_CreateFromContextWithSelector( + CRef, DVRef, _device_image_selector, sel_data + ) + elif st == _KB_STATE_OBJECT: + if sel_data is None: + ObjRef = DPCTLObjectKernelBundle_CreateFromContext( + CRef, DVRef, KIdVRef + ) + else: + ObjRef = DPCTLObjectKernelBundle_CreateFromContextWithSelector( + CRef, DVRef, _device_image_selector, sel_data + ) + else: + if sel_data is None: + ExeRef = DPCTLKernelBundle_CreateFromContext( + CRef, DVRef, KIdVRef + ) + else: + ExeRef = DPCTLKernelBundle_CreateFromContextWithSelector( + CRef, DVRef, _device_image_selector, sel_data + ) + finally: + DPCTLDeviceVector_Delete(DVRef) + DPCTLKernelIdVector_Delete(KIdVRef) + if sel_data is not None and sel_data[2] is not None: + DPCTLInputKernelBundle_Delete(InRef) + DPCTLObjectKernelBundle_Delete(ObjRef) + DPCTLKernelBundle_Delete(ExeRef) + raise sel_data[2] + if InRef is not NULL: + return SyclKernelBundle._create_input(InRef) + elif ObjRef is not NULL: + return SyclKernelBundle._create_object(ObjRef) + elif ExeRef is not NULL: + return SyclKernelBundle._create(ExeRef, False) + raise SyclKernelBundleCompilationError( + f"Could not create a kernel bundle in '{state}' state" + ) + + +def has_kernel_bundle(ctx, devices=None, kernel_ids=None, + str state="executable"): + """has_kernel_bundle(ctx, devices=None, kernel_ids=None, state="executable") + + Returns True if :func:`.get_kernel_bundle` would succeed for the same + arguments. + + Args: + ctx (dpctl.SyclContext, dpctl.SyclQueue): + The context of the kernel bundle. For a queue, its context is used + and ``devices`` defaults to the device of the queue. + devices (Sequence[dpctl.SyclDevice], optional): + Devices of the kernel bundle. Default: ``None``, meaning the + devices of the context. + kernel_ids (Sequence[dpctl.compiler.SyclKernelId], optional): + Ids of the kernels to include. Default: ``None``, meaning all + kernels. + state (str, optional): + State of the kernel bundle: ``"input"``, ``"object"`` or + ``"executable"``. Default: ``"executable"``. + + Returns: + bool: + Whether a kernel bundle can be created. + """ + cdef _kernel_bundle_state st = _state_from_str(state) + cdef list default_devices = [] + cdef SyclContext sctx = _context_and_devices(ctx, default_devices) + cdef DPCTLSyclContextRef CRef = sctx.get_context_ref() + cdef DPCTLDeviceVectorRef DVRef = NULL + cdef DPCTLKernelIdVectorRef KIdVRef = NULL + if devices is None and default_devices: + devices = default_devices + try: + DVRef = _device_vector(devices) + KIdVRef = _kernel_id_vector(kernel_ids) + if st == _KB_STATE_INPUT: + return DPCTLInputKernelBundle_CanCreateFromContext( + CRef, DVRef, KIdVRef + ) + elif st == _KB_STATE_OBJECT: + return DPCTLObjectKernelBundle_CanCreateFromContext( + CRef, DVRef, KIdVRef + ) + return DPCTLKernelBundle_CanCreateFromContext(CRef, DVRef, KIdVRef) + finally: + DPCTLDeviceVector_Delete(DVRef) + DPCTLKernelIdVector_Delete(KIdVRef) + + +cdef SyclKernelBundle _check_state( + object kb, int st, str fn_name +): + if not isinstance(kb, SyclKernelBundle): + raise TypeError( + f"{fn_name} expects SyclKernelBundle objects, got {type(kb)}" + ) + if (kb)._state != st: + raise ValueError( + f"{fn_name} expects kernel bundles in '{_state_to_str(st)}' state, " + "got a " + f"kernel bundle in '{kb.state}' state" + ) + return kb + + +def compile(SyclKernelBundle kernel_bundle not None, devices=None): + """compile(kernel_bundle, devices=None) + + Compiles a kernel bundle in ``input`` state to ``object`` state. + + Args: + kernel_bundle (dpctl.compiler.SyclKernelBundle): + Kernel bundle in ``input`` state. + devices (Sequence[dpctl.SyclDevice], optional): + Devices to compile for. Default: ``None``, meaning the devices of + the kernel bundle. + + Returns: + dpctl.compiler.SyclKernelBundle: + The kernel bundle in ``object`` state. + + Raises: + SyclKernelBundleCompilationError: + If the kernel bundle could not be compiled. + """ + cdef DPCTLDeviceVectorRef DVRef = NULL + cdef DPCTLSyclObjectKernelBundleRef ObjRef = NULL + _check_state(kernel_bundle, _KB_STATE_INPUT, "compile") + DVRef = _device_vector(devices) + try: + ObjRef = DPCTLInputKernelBundle_Compile( + kernel_bundle.get_input_kernel_bundle_ref(), DVRef + ) + finally: + DPCTLDeviceVector_Delete(DVRef) + if ObjRef is NULL: + raise SyclKernelBundleCompilationError( + "Could not compile the kernel bundle" + ) + return SyclKernelBundle._create_object(ObjRef) + + +def build(SyclKernelBundle kernel_bundle not None, devices=None): + """build(kernel_bundle, devices=None) + + Builds a kernel bundle in ``input`` state to ``executable`` state. + + Args: + kernel_bundle (dpctl.compiler.SyclKernelBundle): + Kernel bundle in ``input`` state. + devices (Sequence[dpctl.SyclDevice], optional): + Devices to build for. Default: ``None``, meaning the devices of + the kernel bundle. + + Returns: + dpctl.compiler.SyclKernelBundle: + The kernel bundle in ``executable`` state. + + Raises: + SyclKernelBundleCompilationError: + If the kernel bundle could not be built. + """ + cdef DPCTLDeviceVectorRef DVRef = NULL + cdef DPCTLSyclKernelBundleRef ExeRef = NULL + _check_state(kernel_bundle, _KB_STATE_INPUT, "build") + DVRef = _device_vector(devices) + try: + ExeRef = DPCTLInputKernelBundle_Build( + kernel_bundle.get_input_kernel_bundle_ref(), DVRef + ) + finally: + DPCTLDeviceVector_Delete(DVRef) + if ExeRef is NULL: + raise SyclKernelBundleCompilationError( + "Could not build the kernel bundle" + ) + return SyclKernelBundle._create(ExeRef, False) + + +def link(kernel_bundles, devices=None): + """link(kernel_bundles, devices=None) + + Links kernel bundles in ``object`` state into a kernel bundle in + ``executable`` state. + + Args: + kernel_bundles (dpctl.compiler.SyclKernelBundle, Sequence): + A kernel bundle, or a non-empty sequence of kernel bundles, in + ``object`` state. + devices (Sequence[dpctl.SyclDevice], optional): + Devices to link for. Default: ``None``, meaning the devices of + the kernel bundles. + + Returns: + dpctl.compiler.SyclKernelBundle: + The kernel bundle in ``executable`` state. + + Raises: + SyclKernelBundleCompilationError: + If the kernel bundles could not be linked. + """ + cdef DPCTLSyclObjectKernelBundleRef *ObjRefs = NULL + cdef DPCTLDeviceVectorRef DVRef = NULL + cdef DPCTLSyclKernelBundleRef ExeRef = NULL + cdef size_t i + if isinstance(kernel_bundles, SyclKernelBundle): + kernel_bundles = (kernel_bundles,) + kernel_bundles = tuple(kernel_bundles) + if not kernel_bundles: + raise ValueError("link expects at least one kernel bundle") + for kb in kernel_bundles: + _check_state(kb, _KB_STATE_OBJECT, "link") + ObjRefs = malloc( + len(kernel_bundles) * sizeof(DPCTLSyclObjectKernelBundleRef) + ) + if ObjRefs is NULL: + raise MemoryError() + try: + for i in range(len(kernel_bundles)): + ObjRefs[i] = ( + kernel_bundles[i] + ).get_object_kernel_bundle_ref() + DVRef = _device_vector(devices) + ExeRef = DPCTLObjectKernelBundle_Link( + len(kernel_bundles), ObjRefs, DVRef + ) + finally: + free(ObjRefs) + DPCTLDeviceVector_Delete(DVRef) + if ExeRef is NULL: + raise SyclKernelBundleCompilationError( + "Could not link the kernel bundles" + ) + return SyclKernelBundle._create(ExeRef, False) + + +def join(kernel_bundles): + """join(kernel_bundles) + + Joins the device images of kernel bundles in the same state. + + Args: + kernel_bundles (Sequence[dpctl.compiler.SyclKernelBundle]): + A non-empty sequence of kernel bundles in the same state. + + Returns: + dpctl.compiler.SyclKernelBundle: + The kernel bundle with the device images of all given kernel + bundles. + + Raises: + SyclKernelBundleCompilationError: + If the kernel bundles could not be joined. + """ + cdef void **Refs = NULL + cdef DPCTLSyclInputKernelBundleRef InRef = NULL + cdef DPCTLSyclObjectKernelBundleRef ObjRef = NULL + cdef DPCTLSyclKernelBundleRef ExeRef = NULL + cdef SyclKernelBundle first + cdef SyclKernelBundle kb + cdef size_t i + cdef size_t n + kernel_bundles = tuple(kernel_bundles) + if not kernel_bundles: + raise ValueError("join expects at least one kernel bundle") + if not isinstance(kernel_bundles[0], SyclKernelBundle): + raise TypeError( + "join expects SyclKernelBundle objects, got " + f"{type(kernel_bundles[0])}" + ) + first = kernel_bundles[0] + for b in kernel_bundles: + _check_state(b, first._state, "join") + n = len(kernel_bundles) + Refs = malloc(n * sizeof(void *)) + if Refs is NULL: + raise MemoryError() + try: + for i in range(n): + kb = kernel_bundles[i] + if first._state == _KB_STATE_INPUT: + Refs[i] = kb._input_ref + elif first._state == _KB_STATE_OBJECT: + Refs[i] = kb._object_ref + else: + Refs[i] = kb._kernel_bundle_ref + if first._state == _KB_STATE_INPUT: + InRef = DPCTLInputKernelBundle_Join( + n, Refs + ) + elif first._state == _KB_STATE_OBJECT: + ObjRef = DPCTLObjectKernelBundle_Join( + n, Refs + ) + else: + ExeRef = DPCTLKernelBundle_Join( + n, Refs + ) + finally: + free(Refs) + if InRef is not NULL: + return SyclKernelBundle._create_input(InRef) + elif ObjRef is not NULL: + return SyclKernelBundle._create_object(ObjRef) + elif ExeRef is not NULL: + return SyclKernelBundle._create( + ExeRef, + any((b)._is_sycl_source for b in kernel_bundles), + ) + raise SyclKernelBundleCompilationError("Could not join the kernel bundles") diff --git a/dpctl/tests/test_sycl_compiler.py b/dpctl/tests/test_sycl_compiler.py index a2d4be191a..851a8086b6 100644 --- a/dpctl/tests/test_sycl_compiler.py +++ b/dpctl/tests/test_sycl_compiler.py @@ -164,12 +164,12 @@ def _check_cpython_api_SyclKernel_Make(krn): ) assert krn.get_function_name() == k2.get_function_name() assert krn.get_num_args() == k2.get_num_args() - assert krn.work_group_size == k2.work_group_size + assert krn.work_group_size() == k2.work_group_size() k3 = make_kernel_fn(krn.addressof_ref(), ctypes.c_void_p(None)) assert k3.get_function_name() == "default_name" assert krn.get_num_args() == k3.get_num_args() - assert krn.work_group_size == k3.work_group_size + assert krn.work_group_size() == k3.work_group_size() def _check_multi_kernel_bundle(kb): @@ -195,19 +195,19 @@ def _check_multi_kernel_bundle(kb): na = krn.num_args assert na == krn.get_num_args() - wgsz = krn.work_group_size + wgsz = krn.work_group_size() assert type(wgsz) is int - pwgszm = krn.preferred_work_group_size_multiple + pwgszm = krn.preferred_work_group_size_multiple() assert type(pwgszm) is int - pmsz = krn.private_mem_size + pmsz = krn.private_mem_size() assert type(pmsz) is int - vmnsg = krn.max_num_sub_groups + vmnsg = krn.max_num_sub_groups() assert type(vmnsg) is int - v = krn.max_sub_group_size + v = krn.max_sub_group_size() assert type(v) is int - cmnsg = krn.compile_num_sub_groups + cmnsg = krn.compile_num_sub_groups() assert type(cmnsg) is int - cmsgsz = krn.compile_sub_group_size + cmsgsz = krn.compile_sub_group_size() assert type(cmsgsz) is int _check_cpython_api_SyclKernelBundle_GetKernelBundleRef(kb) @@ -291,6 +291,30 @@ def test_create_kernel_bundle_from_invalid_src_ocl(): dpc.create_kernel_bundle_from_source(q, invalid_oclSrc) +def test_invalid_src_ocl_reports_build_log(monkeypatch, capfd): + q = _get_opencl_queue_or_skip() + invalid_oclSrc = "kernel void add( }" + monkeypatch.setenv("DPCTL_VERBOSITY", "error") + capfd.readouterr() + with pytest.raises(dpc.SyclKernelBundleCompilationError): + dpc.create_kernel_bundle_from_source(q, invalid_oclSrc) + _, err = capfd.readouterr() + assert "Build log:" in err + + +def test_create_kernel_bundle_from_non_contiguous_spirv(): + try: + q = dpctl.SyclQueue() + except dpctl.SyclQueueCreationError: + pytest.skip("Could not create default queue") + spirv_file = get_spirv_abspath("multi_kernel.spv") + with open(spirv_file, "rb") as fin: + spirv = fin.read() + strided = np.frombuffer(spirv * 2, dtype=np.uint8)[::2] + with pytest.raises(ValueError): + dpc.create_kernel_bundle_from_spirv(q, strided) + + def test_create_kernel_bundle_with_spec_const(): try: q = dpctl.SyclQueue() @@ -525,19 +549,19 @@ def test_create_kernel_bundle_from_sycl_source(queue_selector): assert 3 == krn.get_num_args() na = krn.num_args assert na == krn.get_num_args() - wgsz = krn.work_group_size + wgsz = krn.work_group_size() assert type(wgsz) is int - pwgszm = krn.preferred_work_group_size_multiple + pwgszm = krn.preferred_work_group_size_multiple() assert type(pwgszm) is int - pmsz = krn.private_mem_size + pmsz = krn.private_mem_size() assert type(pmsz) is int - vmnsg = krn.max_num_sub_groups + vmnsg = krn.max_num_sub_groups() assert type(vmnsg) is int - v = krn.max_sub_group_size + v = krn.max_sub_group_size() assert type(v) is int - cmnsg = krn.compile_num_sub_groups + cmnsg = krn.compile_num_sub_groups() assert type(cmnsg) is int - cmsgsz = krn.compile_sub_group_size + cmsgsz = krn.compile_sub_group_size() assert type(cmsgsz) is int _check_cpython_api_SyclKernelBundle_GetKernelBundleRef(prog) diff --git a/dpctl/tests/test_sycl_kernel_bundle_states.py b/dpctl/tests/test_sycl_kernel_bundle_states.py new file mode 100644 index 0000000000..8625eeb2aa --- /dev/null +++ b/dpctl/tests/test_sycl_kernel_bundle_states.py @@ -0,0 +1,332 @@ +# Data Parallel Control (dpctl) +# +# Copyright 2026 Intel Corporation +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Defines unit test cases for kernel bundle states, kernel ids and device +images in dpctl.compiler""" + +import os + +import pytest + +import dpctl +import dpctl.compiler as dpc + +_STATES = ["input", "object", "executable"] + +_SYCL_SOURCE = """ +#include + +namespace syclext = sycl::ext::oneapi::experimental; + +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; +} +""" + + +def _get_queue_or_skip(): + try: + return dpctl.SyclQueue() + except dpctl.SyclQueueCreationError: + pytest.skip("Could not create default queue") + + +def _get_interop_bundle_or_skip(q): + spirv_file = os.path.join( + os.path.dirname(os.path.abspath(__file__)), + "input_files", + "multi_kernel.spv", + ) + with open(spirv_file, "rb") as fin: + spirv = fin.read() + try: + return dpc.create_kernel_bundle_from_spirv(q, spirv) + except dpc.SyclKernelBundleCompilationError: + pytest.skip("Could not create kernel bundle from SPIR-V") + + +def _get_kernel_ids_or_skip(q): + kids = dpc.get_kernel_bundle(q).get_kernel_ids() + if not kids and dpc.is_sycl_source_compilation_available(): + if q.sycl_device.can_compile("sycl"): + # kernels built from SYCL source are registered with the runtime + dpc.create_kernel_bundle_from_sycl_source(q, _SYCL_SOURCE) + kids = dpc.get_kernel_bundle(q).get_kernel_ids() + if not kids: + pytest.skip("No kernel ids are available") + return kids + + +def test_get_kernel_ids(): + kids = dpc.get_kernel_ids() + assert isinstance(kids, tuple) + assert all(isinstance(kid, dpc.SyclKernelId) for kid in kids) + + +def test_kernel_id_and_device_image_not_constructible(): + with pytest.raises(TypeError): + dpc.SyclKernelId() + with pytest.raises(TypeError): + dpc.SyclDeviceImage() + + +def test_interop_bundle_queries(): + q = _get_queue_or_skip() + kb = _get_interop_bundle_or_skip(q) + assert kb.state == "executable" + assert kb.backend == q.sycl_device.backend + assert kb.sycl_context == q.sycl_context + assert kb.get_devices() == (q.sycl_device,) + assert kb.is_empty is False + assert isinstance(kb.get_kernel_ids(), tuple) + imgs = kb.get_device_images() + assert len(imgs) >= 1 + assert all(img.state == "executable" for img in imgs) + assert isinstance(kb.contains_specialization_constants, bool) + assert isinstance(kb.native_specialization_constant, bool) + + +def test_join_interop_bundles(): + q = _get_queue_or_skip() + kb = _get_interop_bundle_or_skip(q) + joined = dpc.join([kb, kb]) + assert joined.state == "executable" + assert joined.has_sycl_kernel("add") + assert isinstance(joined.get_sycl_kernel("add"), dpc.SyclKernel) + + +@pytest.mark.parametrize("state", _STATES) +def test_get_kernel_bundle(state): + q = _get_queue_or_skip() + kb = dpc.get_kernel_bundle(q, state=state) + assert isinstance(kb, dpc.SyclKernelBundle) + assert kb.state == state + assert kb.sycl_context == q.sycl_context + assert kb.get_devices() == (q.sycl_device,) + assert kb.backend == q.sycl_device.backend + assert isinstance(kb.is_empty, bool) + assert isinstance(kb.get_kernel_ids(), tuple) + assert len(kb.get_device_images()) >= 0 + assert isinstance(kb.contains_specialization_constants, bool) + + +@pytest.mark.parametrize("state", _STATES) +def test_get_kernel_bundle_from_context(state): + q = _get_queue_or_skip() + ctx = q.sycl_context + kb = dpc.get_kernel_bundle(ctx, devices=[q.sycl_device], state=state) + assert kb.state == state + assert kb.sycl_context == ctx + kb = dpc.get_kernel_bundle(ctx, state=state) + assert set(kb.get_devices()) == set(ctx.get_devices()) + + +@pytest.mark.parametrize("state", _STATES) +def test_has_kernel_bundle(state): + q = _get_queue_or_skip() + assert isinstance(dpc.has_kernel_bundle(q, state=state), bool) + assert dpc.has_kernel_bundle(q, kernel_ids=[], state=state) + + +def test_get_kernel_bundle_no_kernel_ids(): + q = _get_queue_or_skip() + kb = dpc.get_kernel_bundle(q, kernel_ids=[]) + assert kb.is_empty + assert kb.get_kernel_ids() == () + assert kb.get_device_images() == () + + +def test_get_kernel_bundle_invalid_args(): + q = _get_queue_or_skip() + with pytest.raises(ValueError): + dpc.get_kernel_bundle(q, state="source") + with pytest.raises(ValueError): + dpc.has_kernel_bundle(q, state="source") + with pytest.raises(TypeError): + dpc.get_kernel_bundle(q.sycl_device) + with pytest.raises(TypeError): + dpc.get_kernel_bundle(q, devices=[q]) + with pytest.raises(TypeError): + dpc.get_kernel_bundle(q, kernel_ids=["kernel"]) + + +def test_get_kernel_bundle_device_not_in_context(): + q = _get_queue_or_skip() + other = [d for d in dpctl.get_devices() if d != q.sycl_device] + if not other: + pytest.skip("Needs a second device") + with pytest.raises(dpc.SyclKernelBundleCompilationError): + dpc.get_kernel_bundle(q.sycl_context, devices=other[:1]) + assert not dpc.has_kernel_bundle(q.sycl_context, devices=other[:1]) + + +def test_compile_link_build(): + q = _get_queue_or_skip() + inp = dpc.get_kernel_bundle(q, state="input") + obj = dpc.compile(inp) + assert obj.state == "object" + assert obj.sycl_context == q.sycl_context + exe = dpc.link(obj) + assert exe.state == "executable" + exe = dpc.link([obj, obj], devices=[q.sycl_device]) + assert exe.state == "executable" + exe = dpc.build(inp, devices=[q.sycl_device]) + assert exe.state == "executable" + assert exe.get_devices() == (q.sycl_device,) + obj = dpc.compile(inp, devices=q.sycl_device) + assert obj.get_devices() == (q.sycl_device,) + + +@pytest.mark.parametrize("state", _STATES) +def test_join(state): + q = _get_queue_or_skip() + kb = dpc.get_kernel_bundle(q, state=state) + joined = dpc.join([kb, kb]) + assert joined.state == state + assert joined.sycl_context == q.sycl_context + + +def test_wrong_state_errors(): + q = _get_queue_or_skip() + inp = dpc.get_kernel_bundle(q, state="input") + exe = dpc.get_kernel_bundle(q) + with pytest.raises(ValueError): + dpc.compile(exe) + with pytest.raises(ValueError): + dpc.build(exe) + with pytest.raises(ValueError): + dpc.link(inp) + with pytest.raises(ValueError): + dpc.link([]) + with pytest.raises(ValueError): + dpc.join([]) + with pytest.raises(ValueError): + dpc.join([inp, exe]) + with pytest.raises(TypeError): + dpc.join([inp, q]) + with pytest.raises(ValueError): + inp.get_sycl_kernel("add") + assert inp.has_sycl_kernel("add") is False + + +def test_kernel_ids_queries(): + q = _get_queue_or_skip() + kids = _get_kernel_ids_or_skip(q) + kid = kids[0] + assert isinstance(kid.name, str) and kid.name + assert repr(kid) == f"" + same = dpc.get_kernel_bundle(q).get_kernel_ids()[0] + assert kid == same + assert hash(kid) == hash(same) + assert kid != "not a kernel id" + assert dpc.is_compatible(kids, q.sycl_device) + assert dpc.is_compatible([], q.sycl_device) + + +@pytest.mark.parametrize("state", _STATES) +def test_has_kernel(state): + q = _get_queue_or_skip() + kid = _get_kernel_ids_or_skip(q)[0] + kb = dpc.get_kernel_bundle(q, kernel_ids=[kid], state=state) + assert kb.has_kernel(kid) + assert kb.has_kernel(kid, q.sycl_device) + assert any(img.has_kernel(kid) for img in kb.get_device_images()) + assert any( + img.has_kernel(kid, q.sycl_device) for img in kb.get_device_images() + ) + assert dpc.has_kernel_bundle(q, kernel_ids=[kid], state=state) + + +def test_get_kernel_by_id(): + q = _get_queue_or_skip() + kid = _get_kernel_ids_or_skip(q)[0] + kb = dpc.get_kernel_bundle(q, kernel_ids=kid) + krn = kb.get_kernel(kid) + assert isinstance(krn, dpc.SyclKernel) + assert krn.get_function_name() == kid.name + assert krn.work_group_size() > 0 + inp = dpc.get_kernel_bundle(q, kernel_ids=[kid], state="input") + with pytest.raises(ValueError): + inp.get_kernel(kid) + assert isinstance(dpc.build(inp).get_kernel(kid), dpc.SyclKernel) + with pytest.raises(RuntimeError): + krn.get_num_args() + + +@pytest.mark.parametrize("state", _STATES) +def test_get_kernel_bundle_with_selector(state): + q = _get_queue_or_skip() + kid = _get_kernel_ids_or_skip(q)[0] + seen = [] + + def _select(img): + seen.append(img) + assert img.state == state + return img.has_kernel(kid, q.sycl_device) + + kb = dpc.get_kernel_bundle(q, state=state, selector=_select) + assert seen + assert kb.state == state + assert kb.has_kernel(kid) + with pytest.raises(ValueError): + seen[0].has_kernel(kid) + kb = dpc.get_kernel_bundle(q, state=state, selector=lambda img: False) + assert kb.is_empty + + +def test_get_kernel_bundle_selector_raises(): + q = _get_queue_or_skip() + _get_kernel_ids_or_skip(q) + + class _SelectorError(Exception): + pass + + def _select(img): + raise _SelectorError() + + with pytest.raises(_SelectorError): + dpc.get_kernel_bundle(q, selector=_select) + + +def test_get_kernel_bundle_selector_invalid_args(): + q = _get_queue_or_skip() + with pytest.raises(ValueError): + dpc.get_kernel_bundle(q, kernel_ids=[], selector=lambda img: True) + with pytest.raises(TypeError): + dpc.get_kernel_bundle(q, selector=1) + + +def test_kernel_info_for_device(): + q = _get_queue_or_skip() + kb = _get_interop_bundle_or_skip(q) + krn = kb.get_sycl_kernel("add") + d = q.sycl_device + for name in [ + "work_group_size", + "preferred_work_group_size_multiple", + "private_mem_size", + "max_num_sub_groups", + "max_sub_group_size", + "compile_num_sub_groups", + "compile_sub_group_size", + ]: + query = getattr(krn, name) + assert type(query(d)) is int + assert query(d) == query() + assert query(device=d) == query() + assert krn.work_group_size(d) > 0 diff --git a/dpctl/tests/test_sycl_kernel_library.py b/dpctl/tests/test_sycl_kernel_library.py new file mode 100644 index 0000000000..ce29493ff6 --- /dev/null +++ b/dpctl/tests/test_sycl_kernel_library.py @@ -0,0 +1,163 @@ +# Data Parallel Control (dpctl) +# +# Copyright 2026 Intel Corporation +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Defines unit test cases for dpctl.compiler.load_kernel_library""" + +import ctypes +import pathlib +import shutil +import subprocess +import sys + +import numpy as np +import pytest + +import dpctl +import dpctl.compiler as dpc +import dpctl.memory as dpm + +_SCALE_KERNEL_NAME = "__sycl_kernel_dpctl_py_test_scale" + +_LIBRARY_SOURCE = """ +#include + +namespace syclexp = sycl::ext::oneapi::experimental; + +extern "C" SYCL_EXT_ONEAPI_FUNCTION_PROPERTY((syclexp::nd_range_kernel<1>)) +void dpctl_py_test_scale(int *a, int factor) +{ + auto i = sycl::ext::oneapi::this_work_item::get_nd_item<1>() + .get_global_id(0); + a[i] *= factor; +} +""" + + +@pytest.fixture(scope="module") +def kernel_library(tmp_path_factory): + if not sys.platform.startswith("linux"): + pytest.skip("Building the test kernel library is only set up on Linux") + cxx = shutil.which("icpx") + if cxx is None: + pytest.skip("icpx is not available to build the test kernel library") + d = tmp_path_factory.mktemp("kernel_library") + src = d / "kernels.cpp" + src.write_text(_LIBRARY_SOURCE) + lib = d / "libdpctl_test_kernels.so" + res = subprocess.run( + [cxx, "-fsycl", "-fPIC", "-shared", str(src), "-o", str(lib)], + capture_output=True, + text=True, + ) + if res.returncode != 0: + pytest.skip(f"Could not build the test kernel library: {res.stderr}") + return lib + + +def _get_queue_or_skip(): + try: + return dpctl.SyclQueue() + except dpctl.SyclQueueCreationError: + pytest.skip("Could not create default queue") + + +def test_load_kernel_library(kernel_library): + kids = dpc.load_kernel_library(kernel_library) + assert isinstance(kids, tuple) + assert all(isinstance(kid, dpc.SyclKernelId) for kid in kids) + assert _SCALE_KERNEL_NAME in [kid.name for kid in kids] + assert set(kids) <= set(dpc.get_kernel_ids()) + assert set(dpc.load_kernel_library(str(kernel_library))) == set(kids) + + +def test_submit_kernel_from_library(kernel_library): + q = _get_queue_or_skip() + kids = dpc.load_kernel_library(kernel_library) + kid = next(kid for kid in kids if kid.name == _SCALE_KERNEL_NAME) + assert dpc.is_compatible([kid], q.sycl_device) + kb = dpc.get_kernel_bundle(q, kernel_ids=kids) + assert kb.has_kernel(kid, q.sycl_device) + krn = kb.get_kernel(kid) + x = np.arange(16, dtype="i4") + mem = dpm.MemoryUSMDevice(x.nbytes, queue=q) + mem.copy_from_host(x.view("u1")) + q.submit(krn, [mem, ctypes.c_int(3)], [x.size], [4]).wait() + res = np.empty_like(x) + mem.copy_to_host(res.view("u1")) + assert np.array_equal(res, 3 * x) + + +def test_load_kernel_library_invalid(tmp_path): + with pytest.raises(OSError): + dpc.load_kernel_library(tmp_path / "libdpctl_nothing.so") + with pytest.raises(OSError): + dpc.load_kernel_library(pathlib.Path("/nonexistent/libdpctl.so")) + with pytest.raises(TypeError): + dpc.load_kernel_library(None) + + +_CPU_ONLY_SOURCE = _LIBRARY_SOURCE.replace( + "dpctl_py_test_scale", "dpctl_py_test_cpu_only_scale" +) + + +@pytest.fixture(scope="module") +def cpu_only_kernel_library(tmp_path_factory): + if not sys.platform.startswith("linux"): + pytest.skip("Building the test kernel library is only set up on Linux") + cxx = shutil.which("icpx") + if cxx is None: + pytest.skip("icpx is not available to build the test kernel library") + d = tmp_path_factory.mktemp("cpu_only_kernel_library") + src = d / "kernels.cpp" + src.write_text(_CPU_ONLY_SOURCE) + lib = d / "libdpctl_test_cpu_only_kernels.so" + res = subprocess.run( + [ + cxx, + "-fsycl", + "-fsycl-targets=spir64_x86_64", + "-fPIC", + "-shared", + str(src), + "-o", + str(lib), + ], + capture_output=True, + text=True, + ) + if res.returncode != 0: + pytest.skip(f"Could not build the test kernel library: {res.stderr}") + return lib + + +def test_kernel_library_for_one_target(cpu_only_kernel_library): + cpus = dpctl.get_devices(device_type="cpu") + others = [d for d in dpctl.get_devices() if not d.is_cpu] + if not cpus or not others: + pytest.skip("Needs a CPU device and a non-CPU device") + kids = dpc.load_kernel_library(cpu_only_kernel_library) + assert "__sycl_kernel_dpctl_py_test_cpu_only_scale" in [ + k.name for k in kids + ] + q_cpu = dpctl.SyclQueue(cpus[0]) + assert dpc.is_compatible(kids, cpus[0]) + assert not dpc.get_kernel_bundle(q_cpu, kernel_ids=kids).is_empty + q_other = dpctl.SyclQueue(others[0]) + assert not dpc.is_compatible(kids, others[0]) + assert not dpc.has_kernel_bundle(q_other, kernel_ids=kids) + with pytest.raises(dpc.SyclKernelBundleCompilationError): + dpc.get_kernel_bundle(q_other, kernel_ids=kids) diff --git a/examples/pybind11/use_kernel_bundle/CMakeLists.txt b/examples/pybind11/use_kernel_bundle/CMakeLists.txt new file mode 100644 index 0000000000..fff55155ea --- /dev/null +++ b/examples/pybind11/use_kernel_bundle/CMakeLists.txt @@ -0,0 +1,38 @@ +cmake_minimum_required(VERSION 3.21...3.27 FATAL_ERROR) + +project(use_kernel_bundle VERSION 0.1 LANGUAGES CXX + DESCRIPTION "Example of using dpctl.compiler.SyclKernelBundle <-> sycl::kernel_bundle type casting") + +set(DPCTL_CMAKE_MODULES_PATH "${CMAKE_SOURCE_DIR}/../../../cmake") +set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${DPCTL_CMAKE_MODULES_PATH}) +find_package(IntelSYCL REQUIRED PATHS ${DPCTL_CMAKE_MODULES_PATH} NO_DEFAULT_PATH) + +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED True) + +# Fetch pybind11 +include(FetchContent) +FetchContent_Declare( + pybind11 + URL https://github.com/pybind/pybind11/archive/refs/tags/v3.1.0.tar.gz + URL_HASH SHA256=ef712655692a2e9bf7bb7874c022564a45f91d847ddee987e720cd9e28849665 + FIND_PACKAGE_ARGS NAMES pybind11 +) +FetchContent_MakeAvailable(pybind11) + +find_package(Python REQUIRED COMPONENTS Development.Module NumPy) +find_package(Dpctl REQUIRED) + +set(py_module_name _use_kernel_bundle) +set(_sources use_kernel_bundle/_example.cpp) +pybind11_add_module(${py_module_name} + MODULE + ${_sources} +) +add_sycl_to_target(TARGET ${py_module_name} SOURCES ${_sources}) +target_include_directories(${py_module_name} PUBLIC ${Dpctl_INCLUDE_DIRS}) +install(TARGETS ${py_module_name} + DESTINATION use_kernel_bundle +) + +set(ignoreMe "${SKBUILD}") diff --git a/examples/pybind11/use_kernel_bundle/README.md b/examples/pybind11/use_kernel_bundle/README.md new file mode 100644 index 0000000000..1fa458ffa9 --- /dev/null +++ b/examples/pybind11/use_kernel_bundle/README.md @@ -0,0 +1,27 @@ +# Usage of dpctl Kernel Bundles in Pybind11 + +## Description + +This extension demonstrates how a Pybind11 extension can work with +``dpctl.compiler.SyclKernelBundle`` objects in ``input``, ``object`` and +``executable`` state, and with ``dpctl.compiler.SyclKernelId`` objects, to +set a SYCL specialization constant defined in C++ on a kernel bundle that is +obtained and built in Python. + + +## Building + +To build the extension, run: +``` +source /opt/intel/oneapi/compiler/latest/env/vars.sh +CXX=icpx python setup.py build_ext --inplace +python -m pytest tests +python example.py +``` + +# Sample output + +``` +$ python example.py +[ 0 3 6 9 12 15 18 21 24 27] +``` diff --git a/examples/pybind11/use_kernel_bundle/example.py b/examples/pybind11/use_kernel_bundle/example.py new file mode 100644 index 0000000000..4f6677bf7e --- /dev/null +++ b/examples/pybind11/use_kernel_bundle/example.py @@ -0,0 +1,38 @@ +# Data Parallel Control (dpctl) +# +# Copyright 2026 Intel Corporation +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# coding: utf-8 + +import numpy as np +import use_kernel_bundle as ukb + +import dpctl +import dpctl.compiler as dpc +import dpctl.memory as dpm + +q = dpctl.SyclQueue() +kid = ukb.scale_kernel_id() + +kb = dpc.get_kernel_bundle(q, kernel_ids=[kid], state="input") +kb = ukb.set_scale_factor(kb, 3) +exe = dpc.build(kb) + +x = np.arange(10, dtype="i4") +mem = dpm.MemoryUSMDevice(x.nbytes, queue=q) +mem.copy_from_host(x.view("u1")) +ukb.scale(q, exe, mem).wait() +mem.copy_to_host(x.view("u1")) +print(x) diff --git a/examples/pybind11/use_kernel_bundle/setup.py b/examples/pybind11/use_kernel_bundle/setup.py new file mode 100644 index 0000000000..d455417ec5 --- /dev/null +++ b/examples/pybind11/use_kernel_bundle/setup.py @@ -0,0 +1,26 @@ +# Data Parallel Control (dpctl) +# +# Copyright 2026 Intel Corporation +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from skbuild import setup + +setup( + name="use_kernel_bundle", + version="0.0.1", + description="an example of SYCL-powered Python package (with pybind11)", + author="Intel Scripting", + license="Apache 2.0", + packages=["use_kernel_bundle"], +) diff --git a/examples/pybind11/use_kernel_bundle/tests/test_use_kernel_bundle.py b/examples/pybind11/use_kernel_bundle/tests/test_use_kernel_bundle.py new file mode 100644 index 0000000000..1431925604 --- /dev/null +++ b/examples/pybind11/use_kernel_bundle/tests/test_use_kernel_bundle.py @@ -0,0 +1,108 @@ +# Data Parallel Control (dpctl) +# +# Copyright 2026 Intel Corporation +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# coding: utf-8 + +import numpy as np +import pytest +import use_kernel_bundle as ukb + +import dpctl +import dpctl.compiler as dpc +import dpctl.memory as dpm + + +def _get_queue_or_skip(): + try: + return dpctl.SyclQueue() + except dpctl.SyclQueueCreationError: + pytest.skip("Could not create default queue") + + +def _input_bundle(q): + return dpc.get_kernel_bundle( + q, kernel_ids=[ukb.scale_kernel_id()], state="input" + ) + + +def _run_scale(q, exe): + x = np.arange(16, dtype="i4") + mem = dpm.MemoryUSMDevice(x.nbytes, queue=q) + mem.copy_from_host(x.view("u1")) + ukb.scale(q, exe, mem).wait() + res = np.empty_like(x) + mem.copy_to_host(res.view("u1")) + return x, res + + +def test_kernel_id(): + kid = ukb.scale_kernel_id() + assert isinstance(kid, dpc.SyclKernelId) + assert kid in dpc.get_kernel_ids() + assert kid == ukb.scale_kernel_id() + + +def test_default_scale_factor(): + q = _get_queue_or_skip() + kb = _input_bundle(q) + assert kb.contains_specialization_constants + assert ukb.get_scale_factor(kb) == 1 + x, res = _run_scale(q, dpc.build(kb)) + assert np.array_equal(res, x) + + +def test_set_scale_factor_and_build(): + q = _get_queue_or_skip() + kb = ukb.set_scale_factor(_input_bundle(q), 3) + assert kb.state == "input" + assert ukb.get_scale_factor(kb) == 3 + x, res = _run_scale(q, dpc.build(kb)) + assert np.array_equal(res, 3 * x) + + +def test_compile_in_extension_and_link(): + q = _get_queue_or_skip() + kid = ukb.scale_kernel_id() + kb = ukb.set_scale_factor(_input_bundle(q), 5) + obj = ukb.compile_bundle(kb) + assert isinstance(obj, dpc.SyclKernelBundle) + assert obj.state == "object" + assert ukb.object_bundle_has_kernel(obj, kid) + assert ukb.object_bundle_has_kernel(dpc.compile(kb), kid) + x, res = _run_scale(q, dpc.link(obj)) + assert np.array_equal(res, 5 * x) + + +def test_bundle_without_constant(): + q = _get_queue_or_skip() + kb = dpc.get_kernel_bundle(q, kernel_ids=[], state="input") + with pytest.raises(ValueError): + ukb.set_scale_factor(kb, 2) + + +def test_wrong_state_raises(): + q = _get_queue_or_skip() + kb = _input_bundle(q) + exe = dpc.build(kb) + mem = dpm.MemoryUSMDevice(64, queue=q) + with pytest.raises(TypeError): + ukb.set_scale_factor(exe, 2) + with pytest.raises(TypeError): + ukb.scale(q, kb, mem) + with pytest.raises(TypeError): + ukb.object_bundle_has_kernel(kb, ukb.scale_kernel_id()) + with pytest.raises(TypeError): + ukb.object_bundle_has_kernel(dpc.compile(kb), "kernel") diff --git a/examples/pybind11/use_kernel_bundle/use_kernel_bundle/__init__.py b/examples/pybind11/use_kernel_bundle/use_kernel_bundle/__init__.py new file mode 100644 index 0000000000..968cc8a8c6 --- /dev/null +++ b/examples/pybind11/use_kernel_bundle/use_kernel_bundle/__init__.py @@ -0,0 +1,46 @@ +# Data Parallel Control (dpctl) +# +# Copyright 2026 Intel Corporation +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# coding: utf-8 + +from ._use_kernel_bundle import ( + compile_bundle, + get_scale_factor, + object_bundle_has_kernel, + scale, + scale_kernel_id, + set_scale_factor, +) + +__all__ = [ + "compile_bundle", + "get_scale_factor", + "object_bundle_has_kernel", + "scale", + "scale_kernel_id", + "set_scale_factor", +] + +__doc__ = """ +Example pybind11 extension demonstrating binding of +`dpctl.compiler.SyclKernelBundle` to ``sycl::kernel_bundle`` in each bundle +state, and of `dpctl.compiler.SyclKernelId` to ``sycl::kernel_id``. + +The extension sets a SYCL specialization constant, which requires the +``sycl::specialization_id`` object defined in C++, on a kernel bundle that +Python obtains with `dpctl.compiler.get_kernel_bundle` and builds with +`dpctl.compiler.build`. +""" diff --git a/examples/pybind11/use_kernel_bundle/use_kernel_bundle/_example.cpp b/examples/pybind11/use_kernel_bundle/use_kernel_bundle/_example.cpp new file mode 100644 index 0000000000..9b256b5f68 --- /dev/null +++ b/examples/pybind11/use_kernel_bundle/use_kernel_bundle/_example.cpp @@ -0,0 +1,123 @@ +//==- _example.cpp - Example of Pybind11 extension working with =---------===// +// dpctl.compiler.SyclKernelBundle objects. +// +// Data Parallel Control (dpctl) +// +// Copyright 2026 Intel Corporation +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//===----------------------------------------------------------------------===// +/// +/// \file +/// This file implements Pybind11-generated extension that sets a SYCL +/// specialization constant on a kernel bundle obtained in Python, and submits +/// its kernel using the kernel bundle built in Python. +/// +//===----------------------------------------------------------------------===// + +#include "dpctl4pybind11.hpp" +#include +#include +#include +#include +#include + +namespace py = pybind11; + +class ScaleKernel; + +constexpr sycl::specialization_id scale_factor(1); + +using input_bundle_t = sycl::kernel_bundle; +using object_bundle_t = sycl::kernel_bundle; +using exe_bundle_t = sycl::kernel_bundle; + +sycl::kernel_id scale_kernel_id() { return sycl::get_kernel_id(); } + +input_bundle_t set_scale_factor(input_bundle_t kb, std::int32_t factor) +{ + if (!kb.has_specialization_constant()) { + throw py::value_error( + "Kernel bundle does not contain the scale_factor constant"); + } + kb.set_specialization_constant(factor); + return kb; +} + +std::int32_t get_scale_factor(const input_bundle_t &kb) +{ + return kb.get_specialization_constant(); +} + +object_bundle_t compile_bundle(const input_bundle_t &kb) +{ + return sycl::compile(kb); +} + +bool object_bundle_has_kernel(const object_bundle_t &kb, + const sycl::kernel_id &kid) +{ + return kb.has_kernel(kid); +} + +sycl::event scale(sycl::queue &q, + const exe_bundle_t &kb, + dpctl::memory::usm_memory x, + const std::vector &depends = {}) +{ + const std::size_t nbytes = x.get_nbytes(); + if (nbytes % sizeof(std::int32_t) != 0) { + throw py::value_error("Memory must be interpretable as int32 " + "(nbytes must be a multiple of 4)."); + } + if (!dpctl::utils::queues_are_compatible(q, {x.get_queue()})) { + throw std::runtime_error( + "Execution queue is not compatible with allocation queue"); + } + + auto *data = reinterpret_cast(x.get_pointer()); + const std::size_t n = nbytes / sizeof(std::int32_t); + + return q.submit([&](sycl::handler &cgh) { + cgh.depends_on(depends); + cgh.use_kernel_bundle(kb); + cgh.parallel_for( + sycl::range<1>(n), [=](sycl::item<1> it, sycl::kernel_handler kh) { + data[it] *= kh.get_specialization_constant(); + }); + }); +} + +PYBIND11_MODULE(_use_kernel_bundle, m, py::mod_gil_not_used()) +{ + m.def("scale_kernel_id", &scale_kernel_id, + "Returns the kernel id of the scaling kernel"); + m.def("set_scale_factor", &set_scale_factor, + "Sets the scale factor of a kernel bundle in input state", + py::arg("kernel_bundle"), py::arg("factor")); + m.def("get_scale_factor", &get_scale_factor, + "Returns the scale factor of a kernel bundle in input state", + py::arg("kernel_bundle")); + m.def("compile_bundle", &compile_bundle, + "Compiles a kernel bundle in input state to object state", + py::arg("kernel_bundle")); + m.def("object_bundle_has_kernel", &object_bundle_has_kernel, + "Checks a kernel bundle in object state for a kernel", + py::arg("kernel_bundle"), py::arg("kernel_id")); + m.def("scale", &scale, + "Multiplies int32 elements of USM memory in place by the scale " + "factor of the kernel bundle in executable state", + py::arg("queue"), py::arg("kernel_bundle"), py::arg("memory"), + py::arg("depends") = py::list()); +} diff --git a/libsyclinterface/helper/include/dpctl_dynamic_lib_helper.h b/libsyclinterface/helper/include/dpctl_dynamic_lib_helper.h index 363897ef65..a591ef3217 100644 --- a/libsyclinterface/helper/include/dpctl_dynamic_lib_helper.h +++ b/libsyclinterface/helper/include/dpctl_dynamic_lib_helper.h @@ -63,6 +63,8 @@ class DynamicLibHelper final ~DynamicLibHelper() { + if (!_handle) + return; #ifdef __linux__ dlclose(_handle); #elif defined(_WIN32) || defined(_WIN64) diff --git a/libsyclinterface/include/syclinterface/dpctl_sycl_kernel_bundle_interface.h b/libsyclinterface/include/syclinterface/dpctl_sycl_kernel_bundle_interface.h index b65303d094..4de238d9ca 100644 --- a/libsyclinterface/include/syclinterface/dpctl_sycl_kernel_bundle_interface.h +++ b/libsyclinterface/include/syclinterface/dpctl_sycl_kernel_bundle_interface.h @@ -1,5 +1,5 @@ //===- dpctl_sycl_kernel_bundle_interface.h - C API for -// sycl::kernel_bundle -*-C++-*- ===// +// sycl::kernel_bundle and sycl::kernel_id -*-C++-*- ===// // // Data Parallel Control (dpctl) // @@ -20,8 +20,8 @@ //===----------------------------------------------------------------------===// /// /// \file -/// This header declares a C API to create Sycl kernel bundles for OpenCL and -/// Level Zero backends. +/// This header declares a C API for SYCL kernel bundles in all bundle states +/// and for kernel ids. /// //===----------------------------------------------------------------------===// @@ -31,7 +31,10 @@ #include "Support/ExternC.h" #include "Support/MemOwnershipAttrs.h" #include "dpctl_data_types.h" +#include "dpctl_sycl_device_manager.h" +#include "dpctl_sycl_enum_types.h" #include "dpctl_sycl_types.h" +#include "dpctl_vector.h" DPCTL_C_EXTERN_C_BEGIN @@ -327,4 +330,870 @@ bool DPCTLKernelBundle_HasSyclKernel(__dpctl_keep DPCTLSyclKernelBundleRef KBRef, __dpctl_keep const char *KernelName); +/** + * @defgroup KernelIdInterface Kernel_id class C wrapper + */ + +DPCTL_DECLARE_VECTOR(KernelId) + +/*! + * @brief Returns the name of the kernel. + * + * @param KIdRef Opaque pointer to a ``sycl::kernel_id`` + * @return A new C string with the kernel name, or NULL on failure. + * @ingroup KernelIdInterface + */ +DPCTL_API +__dpctl_give const char * +DPCTLKernelId_GetName(__dpctl_keep const DPCTLSyclKernelIdRef KIdRef); + +/*! + * @brief Checks if two kernel ids refer to the same kernel. + * + * @param KIdRef1 First opaque pointer to a ``sycl::kernel_id`` + * @param KIdRef2 Second opaque pointer to a ``sycl::kernel_id`` + * @return True if the kernel ids are equal, else False. + * @ingroup KernelIdInterface + */ +DPCTL_API +bool DPCTLKernelId_AreEq(__dpctl_keep const DPCTLSyclKernelIdRef KIdRef1, + __dpctl_keep const DPCTLSyclKernelIdRef KIdRef2); + +/*! + * @brief Returns the hash of the ``sycl::kernel_id``. + * + * @param KIdRef Opaque pointer to a ``sycl::kernel_id`` + * @return Hash value of the kernel id, 0 on failure. + * @ingroup KernelIdInterface + */ +DPCTL_API +size_t DPCTLKernelId_Hash(__dpctl_keep const DPCTLSyclKernelIdRef KIdRef); + +/*! + * @brief Returns a copy of the DPCTLSyclKernelIdRef. + * + * @param KIdRef Opaque pointer to a ``sycl::kernel_id`` + * @return A new DPCTLSyclKernelIdRef, or NULL on failure. + * @ingroup KernelIdInterface + */ +DPCTL_API +__dpctl_give DPCTLSyclKernelIdRef +DPCTLKernelId_Copy(__dpctl_keep const DPCTLSyclKernelIdRef KIdRef); + +/*! + * @brief Frees the DPCTLSyclKernelIdRef pointer. + * + * @param KIdRef Opaque pointer to a ``sycl::kernel_id`` + * @ingroup KernelIdInterface + */ +DPCTL_API +void DPCTLKernelId_Delete(__dpctl_take DPCTLSyclKernelIdRef KIdRef); + +/*! + * @brief Returns the ids of all kernels defined by the application. + * + * @return A new DPCTLKernelIdVectorRef, or NULL on failure. + * @ingroup KernelIdInterface + */ +DPCTL_API +__dpctl_give DPCTLKernelIdVectorRef DPCTLKernelId_GetAll(void); + +/*! + * @brief Loads a shared library with SYCL device code and returns the ids of + * the kernels it registered with the SYCL runtime. + * + * The library is never unloaded. Loading a library again returns the same + * kernel ids; a library that was loaded by other means before returns none. + * + * @param Path Path of the shared library + * @return A new DPCTLKernelIdVectorRef, or NULL if the library could not be + * loaded. + * @ingroup KernelIdInterface + */ +DPCTL_API +__dpctl_give DPCTLKernelIdVectorRef +DPCTLKernelId_LoadLibrary(__dpctl_keep const char *Path); + +/*! + * @brief Returns True if all given kernels are compatible with the device. + * + * @param KIdVRef Ids of the kernels + * @param DRef Opaque pointer to a ``sycl::device`` + * @return True if the kernels are compatible with the device, else False. + * @ingroup KernelIdInterface + */ +DPCTL_API +bool DPCTLKernelId_IsCompatible(__dpctl_keep const DPCTLKernelIdVectorRef + KIdVRef, + __dpctl_keep const DPCTLSyclDeviceRef DRef); + +/*! + * @brief Returns a kernel bundle in ``executable`` state with the kernels of + * the application compatible with the given context and devices. + * + * @param CRef Opaque pointer to a ``sycl::context`` + * @param DVRef Devices to include, or NULL for the devices of the + * context + * @param KIdVRef Ids of the kernels to include, or NULL for all + * kernels + * @return A new DPCTLSyclKernelBundleRef, or NULL on failure. + * @ingroup KernelBundleInterface + */ +DPCTL_API +__dpctl_give DPCTLSyclKernelBundleRef DPCTLKernelBundle_CreateFromContext( + __dpctl_keep const DPCTLSyclContextRef CRef, + __dpctl_keep const DPCTLDeviceVectorRef DVRef, + __dpctl_keep const DPCTLKernelIdVectorRef KIdVRef); + +/*! + * @brief Returns True if DPCTLKernelBundle_CreateFromContext would succeed for + * the same arguments. + * + * @param CRef Opaque pointer to a ``sycl::context`` + * @param DVRef Devices to include, or NULL for the devices of the + * context + * @param KIdVRef Ids of the kernels to include, or NULL for all + * kernels + * @return True if a kernel bundle can be created, else False. + * @ingroup KernelBundleInterface + */ +DPCTL_API +bool DPCTLKernelBundle_CanCreateFromContext( + __dpctl_keep const DPCTLSyclContextRef CRef, + __dpctl_keep const DPCTLDeviceVectorRef DVRef, + __dpctl_keep const DPCTLKernelIdVectorRef KIdVRef); + +/*! + * @brief Returns the context associated with the kernel bundle. + * + * @param KBRef Opaque pointer to a + * ``sycl::kernel_bundle`` + * @return A new DPCTLSyclContextRef, or NULL on failure. + * @ingroup KernelBundleInterface + */ +DPCTL_API +__dpctl_give DPCTLSyclContextRef +DPCTLKernelBundle_GetContext(__dpctl_keep const DPCTLSyclKernelBundleRef KBRef); + +/*! + * @brief Returns the devices associated with the kernel bundle. + * + * @param KBRef Opaque pointer to a + * ``sycl::kernel_bundle`` + * @return A new DPCTLDeviceVectorRef, or NULL on failure. + * @ingroup KernelBundleInterface + */ +DPCTL_API +__dpctl_give DPCTLDeviceVectorRef +DPCTLKernelBundle_GetDevices(__dpctl_keep const DPCTLSyclKernelBundleRef KBRef); + +/*! + * @brief Returns the backend of the kernel bundle. + * + * @param KBRef Opaque pointer to a + * ``sycl::kernel_bundle`` + * @return A DPCTLSyclBackendType enum value, DPCTL_UNKNOWN_BACKEND on + * failure. + * @ingroup KernelBundleInterface + */ +DPCTL_API +DPCTLSyclBackendType +DPCTLKernelBundle_GetBackend(__dpctl_keep const DPCTLSyclKernelBundleRef KBRef); + +/*! + * @brief Returns True if the kernel bundle contains no device images. + * + * @param KBRef Opaque pointer to a + * ``sycl::kernel_bundle`` + * @return True if the kernel bundle is empty, else False. + * @ingroup KernelBundleInterface + */ +DPCTL_API +bool DPCTLKernelBundle_IsEmpty( + __dpctl_keep const DPCTLSyclKernelBundleRef KBRef); + +/*! + * @brief Returns the ids of all kernels in the kernel bundle. + * + * @param KBRef Opaque pointer to a + * ``sycl::kernel_bundle`` + * @return A new DPCTLKernelIdVectorRef, or NULL on failure. + * @ingroup KernelBundleInterface + */ +DPCTL_API +__dpctl_give DPCTLKernelIdVectorRef DPCTLKernelBundle_GetKernelIds( + __dpctl_keep const DPCTLSyclKernelBundleRef KBRef); + +/*! + * @brief Returns True if the kernel bundle contains the kernel with the given + * id, compatible with the given device if one is passed. + * + * @param KBRef Opaque pointer to a + * ``sycl::kernel_bundle`` + * @param KIdRef Opaque pointer to a ``sycl::kernel_id`` + * @param DRef Opaque pointer to a ``sycl::device``, or NULL + * @return True if the kernel is in the kernel bundle, else False. + * @ingroup KernelBundleInterface + */ +DPCTL_API +bool DPCTLKernelBundle_HasKernelId( + __dpctl_keep const DPCTLSyclKernelBundleRef KBRef, + __dpctl_keep const DPCTLSyclKernelIdRef KIdRef, + __dpctl_keep const DPCTLSyclDeviceRef DRef); + +/*! + * @brief Returns True if any device image in the kernel bundle uses + * specialization constants. + * + * @param KBRef Opaque pointer to a + * ``sycl::kernel_bundle`` + * @return True if the kernel bundle uses specialization constants, else + * False. + * @ingroup KernelBundleInterface + */ +DPCTL_API +bool DPCTLKernelBundle_ContainsSpecializationConstants( + __dpctl_keep const DPCTLSyclKernelBundleRef KBRef); + +/*! + * @brief Returns True if all specialization constants in the kernel bundle + * are native to the backend. + * + * @param KBRef Opaque pointer to a + * ``sycl::kernel_bundle`` + * @return True if all specialization constants are native, else False. + * @ingroup KernelBundleInterface + */ +DPCTL_API +bool DPCTLKernelBundle_NativeSpecializationConstant( + __dpctl_keep const DPCTLSyclKernelBundleRef KBRef); + +/*! + * @brief Returns the number of device images in the kernel bundle. + * + * @param KBRef Opaque pointer to a + * ``sycl::kernel_bundle`` + * @return The number of device images, 0 on failure. + * @ingroup KernelBundleInterface + */ +DPCTL_API +size_t DPCTLKernelBundle_GetNumDeviceImages( + __dpctl_keep const DPCTLSyclKernelBundleRef KBRef); + +/*! + * @brief Returns True if the device image at the given position in the kernel + * bundle contains the kernel with the given id, compatible with the given + * device if one is passed. + * + * @param KBRef Opaque pointer to a + * ``sycl::kernel_bundle`` + * @param Index Position of the device image in the kernel bundle + * @param KIdRef Opaque pointer to a ``sycl::kernel_id`` + * @param DRef Opaque pointer to a ``sycl::device``, or NULL + * @return True if the device image contains the kernel, else False. + * @ingroup KernelBundleInterface + */ +DPCTL_API +bool DPCTLKernelBundle_DeviceImageHasKernel( + __dpctl_keep const DPCTLSyclKernelBundleRef KBRef, + size_t Index, + __dpctl_keep const DPCTLSyclKernelIdRef KIdRef, + __dpctl_keep const DPCTLSyclDeviceRef DRef); + +/*! + * @brief Returns a kernel bundle joining the device images of the given + * kernel bundles. + * + * @param NumKBRefs Number of kernel bundles, must be positive + * @param KBRefs Array of opaque pointers to + * ``sycl::kernel_bundle`` + * @return A new DPCTLSyclKernelBundleRef, or NULL on failure. + * @ingroup KernelBundleInterface + */ +DPCTL_API +__dpctl_give DPCTLSyclKernelBundleRef +DPCTLKernelBundle_Join(size_t NumKBRefs, + __dpctl_keep const DPCTLSyclKernelBundleRef *KBRefs); + +/*! + * @brief Returns the kernel with the given id from the kernel bundle. + * + * @param KBRef Opaque pointer to a + * ``sycl::kernel_bundle`` + * @param KIdRef Opaque pointer to a ``sycl::kernel_id`` + * @return A new DPCTLSyclKernelRef, or NULL on failure. + * @ingroup KernelBundleInterface + */ +DPCTL_API +__dpctl_give DPCTLSyclKernelRef DPCTLKernelBundle_GetKernelById( + __dpctl_keep const DPCTLSyclKernelBundleRef KBRef, + __dpctl_keep const DPCTLSyclKernelIdRef KIdRef); + +/*! + * @brief Returns a kernel bundle in ``input`` state with the kernels of the + * application compatible with the given context and devices. + * + * @param CRef Opaque pointer to a ``sycl::context`` + * @param DVRef Devices to include, or NULL for the devices of the + * context + * @param KIdVRef Ids of the kernels to include, or NULL for all + * kernels + * @return A new DPCTLSyclInputKernelBundleRef, or NULL on failure. + * @ingroup KernelBundleInterface + */ +DPCTL_API +__dpctl_give DPCTLSyclInputKernelBundleRef +DPCTLInputKernelBundle_CreateFromContext( + __dpctl_keep const DPCTLSyclContextRef CRef, + __dpctl_keep const DPCTLDeviceVectorRef DVRef, + __dpctl_keep const DPCTLKernelIdVectorRef KIdVRef); + +/*! + * @brief Returns True if DPCTLInputKernelBundle_CreateFromContext would succeed + * for the same arguments. + * + * @param CRef Opaque pointer to a ``sycl::context`` + * @param DVRef Devices to include, or NULL for the devices of the + * context + * @param KIdVRef Ids of the kernels to include, or NULL for all + * kernels + * @return True if a kernel bundle can be created, else False. + * @ingroup KernelBundleInterface + */ +DPCTL_API +bool DPCTLInputKernelBundle_CanCreateFromContext( + __dpctl_keep const DPCTLSyclContextRef CRef, + __dpctl_keep const DPCTLDeviceVectorRef DVRef, + __dpctl_keep const DPCTLKernelIdVectorRef KIdVRef); + +/*! + * @brief Returns a copy of the DPCTLSyclInputKernelBundleRef. + * + * @param KBRef Opaque pointer to a + * ``sycl::kernel_bundle`` + * @return A new DPCTLSyclInputKernelBundleRef, or NULL on failure. + * @ingroup KernelBundleInterface + */ +DPCTL_API +__dpctl_give DPCTLSyclInputKernelBundleRef DPCTLInputKernelBundle_Copy( + __dpctl_keep const DPCTLSyclInputKernelBundleRef KBRef); + +/*! + * @brief Frees the DPCTLSyclInputKernelBundleRef pointer. + * + * @param KBRef Opaque pointer to a + * ``sycl::kernel_bundle`` + * @ingroup KernelBundleInterface + */ +DPCTL_API +void DPCTLInputKernelBundle_Delete( + __dpctl_take DPCTLSyclInputKernelBundleRef KBRef); + +/*! + * @brief Returns the context associated with the kernel bundle. + * + * @param KBRef Opaque pointer to a + * ``sycl::kernel_bundle`` + * @return A new DPCTLSyclContextRef, or NULL on failure. + * @ingroup KernelBundleInterface + */ +DPCTL_API +__dpctl_give DPCTLSyclContextRef DPCTLInputKernelBundle_GetContext( + __dpctl_keep const DPCTLSyclInputKernelBundleRef KBRef); + +/*! + * @brief Returns the devices associated with the kernel bundle. + * + * @param KBRef Opaque pointer to a + * ``sycl::kernel_bundle`` + * @return A new DPCTLDeviceVectorRef, or NULL on failure. + * @ingroup KernelBundleInterface + */ +DPCTL_API +__dpctl_give DPCTLDeviceVectorRef DPCTLInputKernelBundle_GetDevices( + __dpctl_keep const DPCTLSyclInputKernelBundleRef KBRef); + +/*! + * @brief Returns the backend of the kernel bundle. + * + * @param KBRef Opaque pointer to a + * ``sycl::kernel_bundle`` + * @return A DPCTLSyclBackendType enum value, DPCTL_UNKNOWN_BACKEND on + * failure. + * @ingroup KernelBundleInterface + */ +DPCTL_API +DPCTLSyclBackendType DPCTLInputKernelBundle_GetBackend( + __dpctl_keep const DPCTLSyclInputKernelBundleRef KBRef); + +/*! + * @brief Returns True if the kernel bundle contains no device images. + * + * @param KBRef Opaque pointer to a + * ``sycl::kernel_bundle`` + * @return True if the kernel bundle is empty, else False. + * @ingroup KernelBundleInterface + */ +DPCTL_API +bool DPCTLInputKernelBundle_IsEmpty( + __dpctl_keep const DPCTLSyclInputKernelBundleRef KBRef); + +/*! + * @brief Returns the ids of all kernels in the kernel bundle. + * + * @param KBRef Opaque pointer to a + * ``sycl::kernel_bundle`` + * @return A new DPCTLKernelIdVectorRef, or NULL on failure. + * @ingroup KernelBundleInterface + */ +DPCTL_API +__dpctl_give DPCTLKernelIdVectorRef DPCTLInputKernelBundle_GetKernelIds( + __dpctl_keep const DPCTLSyclInputKernelBundleRef KBRef); + +/*! + * @brief Returns True if the kernel bundle contains the kernel with the given + * id, compatible with the given device if one is passed. + * + * @param KBRef Opaque pointer to a + * ``sycl::kernel_bundle`` + * @param KIdRef Opaque pointer to a ``sycl::kernel_id`` + * @param DRef Opaque pointer to a ``sycl::device``, or NULL + * @return True if the kernel is in the kernel bundle, else False. + * @ingroup KernelBundleInterface + */ +DPCTL_API +bool DPCTLInputKernelBundle_HasKernelId( + __dpctl_keep const DPCTLSyclInputKernelBundleRef KBRef, + __dpctl_keep const DPCTLSyclKernelIdRef KIdRef, + __dpctl_keep const DPCTLSyclDeviceRef DRef); + +/*! + * @brief Returns True if any device image in the kernel bundle uses + * specialization constants. + * + * @param KBRef Opaque pointer to a + * ``sycl::kernel_bundle`` + * @return True if the kernel bundle uses specialization constants, else + * False. + * @ingroup KernelBundleInterface + */ +DPCTL_API +bool DPCTLInputKernelBundle_ContainsSpecializationConstants( + __dpctl_keep const DPCTLSyclInputKernelBundleRef KBRef); + +/*! + * @brief Returns True if all specialization constants in the kernel bundle + * are native to the backend. + * + * @param KBRef Opaque pointer to a + * ``sycl::kernel_bundle`` + * @return True if all specialization constants are native, else False. + * @ingroup KernelBundleInterface + */ +DPCTL_API +bool DPCTLInputKernelBundle_NativeSpecializationConstant( + __dpctl_keep const DPCTLSyclInputKernelBundleRef KBRef); + +/*! + * @brief Returns the number of device images in the kernel bundle. + * + * @param KBRef Opaque pointer to a + * ``sycl::kernel_bundle`` + * @return The number of device images, 0 on failure. + * @ingroup KernelBundleInterface + */ +DPCTL_API +size_t DPCTLInputKernelBundle_GetNumDeviceImages( + __dpctl_keep const DPCTLSyclInputKernelBundleRef KBRef); + +/*! + * @brief Returns True if the device image at the given position in the kernel + * bundle contains the kernel with the given id, compatible with the given + * device if one is passed. + * + * @param KBRef Opaque pointer to a + * ``sycl::kernel_bundle`` + * @param Index Position of the device image in the kernel bundle + * @param KIdRef Opaque pointer to a ``sycl::kernel_id`` + * @param DRef Opaque pointer to a ``sycl::device``, or NULL + * @return True if the device image contains the kernel, else False. + * @ingroup KernelBundleInterface + */ +DPCTL_API +bool DPCTLInputKernelBundle_DeviceImageHasKernel( + __dpctl_keep const DPCTLSyclInputKernelBundleRef KBRef, + size_t Index, + __dpctl_keep const DPCTLSyclKernelIdRef KIdRef, + __dpctl_keep const DPCTLSyclDeviceRef DRef); + +/*! + * @brief Returns a kernel bundle joining the device images of the given + * kernel bundles. + * + * @param NumKBRefs Number of kernel bundles, must be positive + * @param KBRefs Array of opaque pointers to + * ``sycl::kernel_bundle`` + * @return A new DPCTLSyclInputKernelBundleRef, or NULL on failure. + * @ingroup KernelBundleInterface + */ +DPCTL_API +__dpctl_give DPCTLSyclInputKernelBundleRef DPCTLInputKernelBundle_Join( + size_t NumKBRefs, + __dpctl_keep const DPCTLSyclInputKernelBundleRef *KBRefs); + +/*! + * @brief Compiles a kernel bundle in ``input`` state to ``object`` state. + * + * @param KBRef Opaque pointer to a + * ``sycl::kernel_bundle`` + * @param DVRef Devices to compile for, or NULL for the devices of + * the kernel bundle + * @return A new DPCTLSyclObjectKernelBundleRef, or NULL on failure. + * @ingroup KernelBundleInterface + */ +DPCTL_API +__dpctl_give DPCTLSyclObjectKernelBundleRef DPCTLInputKernelBundle_Compile( + __dpctl_keep const DPCTLSyclInputKernelBundleRef KBRef, + __dpctl_keep const DPCTLDeviceVectorRef DVRef); + +/*! + * @brief Builds a kernel bundle in ``input`` state to ``executable`` state. + * + * @param KBRef Opaque pointer to a + * ``sycl::kernel_bundle`` + * @param DVRef Devices to build for, or NULL for the devices of + * the kernel bundle + * @return A new DPCTLSyclKernelBundleRef, or NULL on failure. + * @ingroup KernelBundleInterface + */ +DPCTL_API +__dpctl_give DPCTLSyclKernelBundleRef DPCTLInputKernelBundle_Build( + __dpctl_keep const DPCTLSyclInputKernelBundleRef KBRef, + __dpctl_keep const DPCTLDeviceVectorRef DVRef); + +/*! + * @brief Returns a kernel bundle in ``object`` state with the kernels of the + * application compatible with the given context and devices. + * + * @param CRef Opaque pointer to a ``sycl::context`` + * @param DVRef Devices to include, or NULL for the devices of the + * context + * @param KIdVRef Ids of the kernels to include, or NULL for all + * kernels + * @return A new DPCTLSyclObjectKernelBundleRef, or NULL on failure. + * @ingroup KernelBundleInterface + */ +DPCTL_API +__dpctl_give DPCTLSyclObjectKernelBundleRef +DPCTLObjectKernelBundle_CreateFromContext( + __dpctl_keep const DPCTLSyclContextRef CRef, + __dpctl_keep const DPCTLDeviceVectorRef DVRef, + __dpctl_keep const DPCTLKernelIdVectorRef KIdVRef); + +/*! + * @brief Returns True if DPCTLObjectKernelBundle_CreateFromContext would + * succeed for the same arguments. + * + * @param CRef Opaque pointer to a ``sycl::context`` + * @param DVRef Devices to include, or NULL for the devices of the + * context + * @param KIdVRef Ids of the kernels to include, or NULL for all + * kernels + * @return True if a kernel bundle can be created, else False. + * @ingroup KernelBundleInterface + */ +DPCTL_API +bool DPCTLObjectKernelBundle_CanCreateFromContext( + __dpctl_keep const DPCTLSyclContextRef CRef, + __dpctl_keep const DPCTLDeviceVectorRef DVRef, + __dpctl_keep const DPCTLKernelIdVectorRef KIdVRef); + +/*! + * @brief Returns a copy of the DPCTLSyclObjectKernelBundleRef. + * + * @param KBRef Opaque pointer to a + * ``sycl::kernel_bundle`` + * @return A new DPCTLSyclObjectKernelBundleRef, or NULL on failure. + * @ingroup KernelBundleInterface + */ +DPCTL_API +__dpctl_give DPCTLSyclObjectKernelBundleRef DPCTLObjectKernelBundle_Copy( + __dpctl_keep const DPCTLSyclObjectKernelBundleRef KBRef); + +/*! + * @brief Frees the DPCTLSyclObjectKernelBundleRef pointer. + * + * @param KBRef Opaque pointer to a + * ``sycl::kernel_bundle`` + * @ingroup KernelBundleInterface + */ +DPCTL_API +void DPCTLObjectKernelBundle_Delete( + __dpctl_take DPCTLSyclObjectKernelBundleRef KBRef); + +/*! + * @brief Returns the context associated with the kernel bundle. + * + * @param KBRef Opaque pointer to a + * ``sycl::kernel_bundle`` + * @return A new DPCTLSyclContextRef, or NULL on failure. + * @ingroup KernelBundleInterface + */ +DPCTL_API +__dpctl_give DPCTLSyclContextRef DPCTLObjectKernelBundle_GetContext( + __dpctl_keep const DPCTLSyclObjectKernelBundleRef KBRef); + +/*! + * @brief Returns the devices associated with the kernel bundle. + * + * @param KBRef Opaque pointer to a + * ``sycl::kernel_bundle`` + * @return A new DPCTLDeviceVectorRef, or NULL on failure. + * @ingroup KernelBundleInterface + */ +DPCTL_API +__dpctl_give DPCTLDeviceVectorRef DPCTLObjectKernelBundle_GetDevices( + __dpctl_keep const DPCTLSyclObjectKernelBundleRef KBRef); + +/*! + * @brief Returns the backend of the kernel bundle. + * + * @param KBRef Opaque pointer to a + * ``sycl::kernel_bundle`` + * @return A DPCTLSyclBackendType enum value, DPCTL_UNKNOWN_BACKEND on + * failure. + * @ingroup KernelBundleInterface + */ +DPCTL_API +DPCTLSyclBackendType DPCTLObjectKernelBundle_GetBackend( + __dpctl_keep const DPCTLSyclObjectKernelBundleRef KBRef); + +/*! + * @brief Returns True if the kernel bundle contains no device images. + * + * @param KBRef Opaque pointer to a + * ``sycl::kernel_bundle`` + * @return True if the kernel bundle is empty, else False. + * @ingroup KernelBundleInterface + */ +DPCTL_API +bool DPCTLObjectKernelBundle_IsEmpty( + __dpctl_keep const DPCTLSyclObjectKernelBundleRef KBRef); + +/*! + * @brief Returns the ids of all kernels in the kernel bundle. + * + * @param KBRef Opaque pointer to a + * ``sycl::kernel_bundle`` + * @return A new DPCTLKernelIdVectorRef, or NULL on failure. + * @ingroup KernelBundleInterface + */ +DPCTL_API +__dpctl_give DPCTLKernelIdVectorRef DPCTLObjectKernelBundle_GetKernelIds( + __dpctl_keep const DPCTLSyclObjectKernelBundleRef KBRef); + +/*! + * @brief Returns True if the kernel bundle contains the kernel with the given + * id, compatible with the given device if one is passed. + * + * @param KBRef Opaque pointer to a + * ``sycl::kernel_bundle`` + * @param KIdRef Opaque pointer to a ``sycl::kernel_id`` + * @param DRef Opaque pointer to a ``sycl::device``, or NULL + * @return True if the kernel is in the kernel bundle, else False. + * @ingroup KernelBundleInterface + */ +DPCTL_API +bool DPCTLObjectKernelBundle_HasKernelId( + __dpctl_keep const DPCTLSyclObjectKernelBundleRef KBRef, + __dpctl_keep const DPCTLSyclKernelIdRef KIdRef, + __dpctl_keep const DPCTLSyclDeviceRef DRef); + +/*! + * @brief Returns True if any device image in the kernel bundle uses + * specialization constants. + * + * @param KBRef Opaque pointer to a + * ``sycl::kernel_bundle`` + * @return True if the kernel bundle uses specialization constants, else + * False. + * @ingroup KernelBundleInterface + */ +DPCTL_API +bool DPCTLObjectKernelBundle_ContainsSpecializationConstants( + __dpctl_keep const DPCTLSyclObjectKernelBundleRef KBRef); + +/*! + * @brief Returns True if all specialization constants in the kernel bundle + * are native to the backend. + * + * @param KBRef Opaque pointer to a + * ``sycl::kernel_bundle`` + * @return True if all specialization constants are native, else False. + * @ingroup KernelBundleInterface + */ +DPCTL_API +bool DPCTLObjectKernelBundle_NativeSpecializationConstant( + __dpctl_keep const DPCTLSyclObjectKernelBundleRef KBRef); + +/*! + * @brief Returns the number of device images in the kernel bundle. + * + * @param KBRef Opaque pointer to a + * ``sycl::kernel_bundle`` + * @return The number of device images, 0 on failure. + * @ingroup KernelBundleInterface + */ +DPCTL_API +size_t DPCTLObjectKernelBundle_GetNumDeviceImages( + __dpctl_keep const DPCTLSyclObjectKernelBundleRef KBRef); + +/*! + * @brief Returns True if the device image at the given position in the kernel + * bundle contains the kernel with the given id, compatible with the given + * device if one is passed. + * + * @param KBRef Opaque pointer to a + * ``sycl::kernel_bundle`` + * @param Index Position of the device image in the kernel bundle + * @param KIdRef Opaque pointer to a ``sycl::kernel_id`` + * @param DRef Opaque pointer to a ``sycl::device``, or NULL + * @return True if the device image contains the kernel, else False. + * @ingroup KernelBundleInterface + */ +DPCTL_API +bool DPCTLObjectKernelBundle_DeviceImageHasKernel( + __dpctl_keep const DPCTLSyclObjectKernelBundleRef KBRef, + size_t Index, + __dpctl_keep const DPCTLSyclKernelIdRef KIdRef, + __dpctl_keep const DPCTLSyclDeviceRef DRef); + +/*! + * @brief Returns a kernel bundle joining the device images of the given + * kernel bundles. + * + * @param NumKBRefs Number of kernel bundles, must be positive + * @param KBRefs Array of opaque pointers to + * ``sycl::kernel_bundle`` + * @return A new DPCTLSyclObjectKernelBundleRef, or NULL on failure. + * @ingroup KernelBundleInterface + */ +DPCTL_API +__dpctl_give DPCTLSyclObjectKernelBundleRef DPCTLObjectKernelBundle_Join( + size_t NumKBRefs, + __dpctl_keep const DPCTLSyclObjectKernelBundleRef *KBRefs); + +/*! + * @brief Links kernel bundles in ``object`` state into a kernel bundle in + * ``executable`` state. + * + * @param NumKBRefs Number of kernel bundles, must be positive + * @param KBRefs Array of opaque pointers to + * ``sycl::kernel_bundle`` + * @param DVRef Devices to link for, or NULL for the devices of + * the kernel bundles + * @return A new DPCTLSyclKernelBundleRef, or NULL on failure. + * @ingroup KernelBundleInterface + */ +DPCTL_API +__dpctl_give DPCTLSyclKernelBundleRef DPCTLObjectKernelBundle_Link( + size_t NumKBRefs, + __dpctl_keep const DPCTLSyclObjectKernelBundleRef *KBRefs, + __dpctl_keep const DPCTLDeviceVectorRef DVRef); + +/*! + * @brief Selector of device images for the ``CreateFromContextWithSelector`` + * functions. + * + * @param ImgRef Opaque pointer to the device image, valid only + * during the call + * @param UserData The user data passed to the creation function + * @return True to include the device image in the kernel bundle. + * @ingroup KernelBundleInterface + */ +typedef bool (*DPCTLDeviceImageSelectorFn)(DPCTLSyclDeviceImageRef ImgRef, + void *UserData); + +/*! + * @brief Returns True if the device image contains the kernel with the given + * id, compatible with the given device if one is passed. + * + * @param ImgRef Opaque pointer to a ``sycl::device_image`` + * @param KIdRef Opaque pointer to a ``sycl::kernel_id`` + * @param DRef Opaque pointer to a ``sycl::device``, or NULL + * @return True if the device image contains the kernel, else False. + * @ingroup KernelBundleInterface + */ +DPCTL_API +bool DPCTLDeviceImage_HasKernel(__dpctl_keep const DPCTLSyclDeviceImageRef + ImgRef, + __dpctl_keep const DPCTLSyclKernelIdRef KIdRef, + __dpctl_keep const DPCTLSyclDeviceRef DRef); + +/*! + * @brief Returns a kernel bundle in ``executable`` state with the device images + * of the application, compatible with the given context and devices, that the + * selector accepts. + * + * @param CRef Opaque pointer to a ``sycl::context`` + * @param DVRef Devices to include, or NULL for the devices of the + * context + * @param Selector Device image selector, called on the calling + * thread + * @param UserData Passed to the selector + * @return A new DPCTLSyclKernelBundleRef, or NULL on failure. + * @ingroup KernelBundleInterface + */ +DPCTL_API +__dpctl_give DPCTLSyclKernelBundleRef +DPCTLKernelBundle_CreateFromContextWithSelector( + __dpctl_keep const DPCTLSyclContextRef CRef, + __dpctl_keep const DPCTLDeviceVectorRef DVRef, + DPCTLDeviceImageSelectorFn Selector, + void *UserData); + +/*! + * @brief Returns a kernel bundle in ``input`` state with the device images + * of the application, compatible with the given context and devices, that the + * selector accepts. + * + * @param CRef Opaque pointer to a ``sycl::context`` + * @param DVRef Devices to include, or NULL for the devices of the + * context + * @param Selector Device image selector, called on the calling + * thread + * @param UserData Passed to the selector + * @return A new DPCTLSyclInputKernelBundleRef, or NULL on failure. + * @ingroup KernelBundleInterface + */ +DPCTL_API +__dpctl_give DPCTLSyclInputKernelBundleRef +DPCTLInputKernelBundle_CreateFromContextWithSelector( + __dpctl_keep const DPCTLSyclContextRef CRef, + __dpctl_keep const DPCTLDeviceVectorRef DVRef, + DPCTLDeviceImageSelectorFn Selector, + void *UserData); + +/*! + * @brief Returns a kernel bundle in ``object`` state with the device images + * of the application, compatible with the given context and devices, that the + * selector accepts. + * + * @param CRef Opaque pointer to a ``sycl::context`` + * @param DVRef Devices to include, or NULL for the devices of the + * context + * @param Selector Device image selector, called on the calling + * thread + * @param UserData Passed to the selector + * @return A new DPCTLSyclObjectKernelBundleRef, or NULL on failure. + * @ingroup KernelBundleInterface + */ +DPCTL_API +__dpctl_give DPCTLSyclObjectKernelBundleRef +DPCTLObjectKernelBundle_CreateFromContextWithSelector( + __dpctl_keep const DPCTLSyclContextRef CRef, + __dpctl_keep const DPCTLDeviceVectorRef DVRef, + DPCTLDeviceImageSelectorFn Selector, + void *UserData); + DPCTL_C_EXTERN_C_END diff --git a/libsyclinterface/include/syclinterface/dpctl_sycl_kernel_interface.h b/libsyclinterface/include/syclinterface/dpctl_sycl_kernel_interface.h index d8a69afb1d..2511c955a0 100644 --- a/libsyclinterface/include/syclinterface/dpctl_sycl_kernel_interface.h +++ b/libsyclinterface/include/syclinterface/dpctl_sycl_kernel_interface.h @@ -45,7 +45,7 @@ DPCTL_C_EXTERN_C_BEGIN * @param KRef DPCTLSyclKernelRef pointer to a SYCL * interoperability kernel. * @return Returns the number of arguments for the interoperability - * kernel. + * kernel, or -1 if the number of arguments is not available. * @ingroup KernelInterface */ DPCTL_API @@ -80,13 +80,17 @@ DPCTLKernel_Copy(__dpctl_keep const DPCTLSyclKernelRef KRef); * * @param KRef DPCTLSyclKernelRef pointer to a SYCL * interoperability kernel. + * @param DRef DPCTLSyclDeviceRef pointer to a device of the + * kernel bundle of the kernel, or NULL for the + * first device of the kernel bundle. * @return Returns the maximum number of work-items in a work-group * that can be used to execute a kernel on the device it was * built for. * @ingroup KernelInterface */ DPCTL_API -size_t DPCTLKernel_GetWorkGroupSize(__dpctl_keep const DPCTLSyclKernelRef KRef); +size_t DPCTLKernel_GetWorkGroupSize(__dpctl_keep const DPCTLSyclKernelRef KRef, + __dpctl_keep const DPCTLSyclDeviceRef DRef); /*! * !brief Wrapper around @@ -94,13 +98,17 @@ size_t DPCTLKernel_GetWorkGroupSize(__dpctl_keep const DPCTLSyclKernelRef KRef); * * @param KRef DPCTLSyclKernelRef pointer to a SYCL * interoperability kernel. + * @param DRef DPCTLSyclDeviceRef pointer to a device of the + * kernel bundle of the kernel, or NULL for the + * first device of the kernel bundle. * @return Returns a value, of which work-group size is preferred to be a * multiple, for executing a kernel on the device it was built for. * @ingroup KernelInterface */ DPCTL_API size_t DPCTLKernel_GetPreferredWorkGroupSizeMultiple( - __dpctl_keep const DPCTLSyclKernelRef KRef); + __dpctl_keep const DPCTLSyclKernelRef KRef, + __dpctl_keep const DPCTLSyclDeviceRef DRef); /*! * !brief Wrapper around @@ -108,13 +116,17 @@ size_t DPCTLKernel_GetPreferredWorkGroupSizeMultiple( * * @param KRef DPCTLSyclKernelRef pointer to a SYCL * interoperability kernel. + * @param DRef DPCTLSyclDeviceRef pointer to a device of the + * kernel bundle of the kernel, or NULL for the + * first device of the kernel bundle. * @return Returns the minimum amount of private memory, in bytes, * used by each work-item in the kernel. * @ingroup KernelInterface */ DPCTL_API size_t -DPCTLKernel_GetPrivateMemSize(__dpctl_keep const DPCTLSyclKernelRef KRef); +DPCTLKernel_GetPrivateMemSize(__dpctl_keep const DPCTLSyclKernelRef KRef, + __dpctl_keep const DPCTLSyclDeviceRef DRef); /*! * !brief Wrapper around @@ -122,12 +134,16 @@ DPCTLKernel_GetPrivateMemSize(__dpctl_keep const DPCTLSyclKernelRef KRef); * * @param KRef DPCTLSyclKernelRef pointer to an SYCL * interoperability kernel. + * @param DRef DPCTLSyclDeviceRef pointer to a device of the + * kernel bundle of the kernel, or NULL for the + * first device of the kernel bundle. * @return Returns the maximum number of sub-groups for this kernel. * @ingroup KernelInterface */ DPCTL_API uint32_t -DPCTLKernel_GetMaxNumSubGroups(__dpctl_keep const DPCTLSyclKernelRef KRef); +DPCTLKernel_GetMaxNumSubGroups(__dpctl_keep const DPCTLSyclKernelRef KRef, + __dpctl_keep const DPCTLSyclDeviceRef DRef); /*! * !brief Wrapper around @@ -135,12 +151,16 @@ DPCTLKernel_GetMaxNumSubGroups(__dpctl_keep const DPCTLSyclKernelRef KRef); * * @param KRef DPCTLSyclKernelRef pointer to an SYCL * interoperability kernel. + * @param DRef DPCTLSyclDeviceRef pointer to a device of the + * kernel bundle of the kernel, or NULL for the + * first device of the kernel bundle. * @return Returns the maximum sub-group size for this kernel. * @ingroup KernelInterface */ DPCTL_API uint32_t -DPCTLKernel_GetMaxSubGroupSize(__dpctl_keep const DPCTLSyclKernelRef KRef); +DPCTLKernel_GetMaxSubGroupSize(__dpctl_keep const DPCTLSyclKernelRef KRef, + __dpctl_keep const DPCTLSyclDeviceRef DRef); /*! * !brief Wrapper around @@ -148,13 +168,17 @@ DPCTLKernel_GetMaxSubGroupSize(__dpctl_keep const DPCTLSyclKernelRef KRef); * * @param KRef DPCTLSyclKernelRef pointer to an SYCL * interoperability kernel. + * @param DRef DPCTLSyclDeviceRef pointer to a device of the + * kernel bundle of the kernel, or NULL for the + * first device of the kernel bundle. * @return Returns the number of sub-groups specified by the kernel, * or 0 (if not specified). * @ingroup KernelInterface */ DPCTL_API uint32_t -DPCTLKernel_GetCompileNumSubGroups(__dpctl_keep const DPCTLSyclKernelRef KRef); +DPCTLKernel_GetCompileNumSubGroups(__dpctl_keep const DPCTLSyclKernelRef KRef, + __dpctl_keep const DPCTLSyclDeviceRef DRef); /*! * !brief Wrapper around @@ -162,12 +186,16 @@ DPCTLKernel_GetCompileNumSubGroups(__dpctl_keep const DPCTLSyclKernelRef KRef); * * @param KRef DPCTLSyclKernelRef pointer to an SYCL * interoperability kernel. + * @param DRef DPCTLSyclDeviceRef pointer to a device of the + * kernel bundle of the kernel, or NULL for the + * first device of the kernel bundle. * @return Returns the required sub-group size specified by this kernel, * or 0 (if not specified). * @ingroup KernelInterface */ DPCTL_API uint32_t -DPCTLKernel_GetCompileSubGroupSize(__dpctl_keep const DPCTLSyclKernelRef KRef); +DPCTLKernel_GetCompileSubGroupSize(__dpctl_keep const DPCTLSyclKernelRef KRef, + __dpctl_keep const DPCTLSyclDeviceRef DRef); DPCTL_C_EXTERN_C_END diff --git a/libsyclinterface/include/syclinterface/dpctl_sycl_type_casters.hpp b/libsyclinterface/include/syclinterface/dpctl_sycl_type_casters.hpp index 4d4156d92a..1eb7560f5b 100644 --- a/libsyclinterface/include/syclinterface/dpctl_sycl_type_casters.hpp +++ b/libsyclinterface/include/syclinterface/dpctl_sycl_type_casters.hpp @@ -29,6 +29,7 @@ #ifdef __cplusplus #include "dpctl_device_selection.hpp" +#include "dpctl_sycl_kernel_bundle_interface.h" #include "dpctl_sycl_types.h" #include #include @@ -67,6 +68,13 @@ DEFINE_SIMPLE_CONVERSION_FUNCTIONS(sycl::kernel, DPCTLSyclKernelRef) DEFINE_SIMPLE_CONVERSION_FUNCTIONS( sycl::kernel_bundle, DPCTLSyclKernelBundleRef) +DEFINE_SIMPLE_CONVERSION_FUNCTIONS( + sycl::kernel_bundle, + DPCTLSyclInputKernelBundleRef) +DEFINE_SIMPLE_CONVERSION_FUNCTIONS( + sycl::kernel_bundle, + DPCTLSyclObjectKernelBundleRef) +DEFINE_SIMPLE_CONVERSION_FUNCTIONS(sycl::kernel_id, DPCTLSyclKernelIdRef) #include "dpctl_sycl_device_manager.h" DEFINE_SIMPLE_CONVERSION_FUNCTIONS(std::vector, @@ -80,6 +88,9 @@ DEFINE_SIMPLE_CONVERSION_FUNCTIONS(std::vector, DEFINE_SIMPLE_CONVERSION_FUNCTIONS(std::vector, DPCTLEventVectorRef) +DEFINE_SIMPLE_CONVERSION_FUNCTIONS(std::vector, + DPCTLKernelIdVectorRef) + #include "dpctl_sycl_extension_interface.h" DEFINE_SIMPLE_CONVERSION_FUNCTIONS(RawWorkGroupMemory, DPCTLSyclWorkGroupMemoryRef) diff --git a/libsyclinterface/include/syclinterface/dpctl_sycl_types.h b/libsyclinterface/include/syclinterface/dpctl_sycl_types.h index f8dbb0afd1..bfca92991b 100644 --- a/libsyclinterface/include/syclinterface/dpctl_sycl_types.h +++ b/libsyclinterface/include/syclinterface/dpctl_sycl_types.h @@ -66,6 +66,34 @@ typedef struct DPCTLOpaqueSyclKernel *DPCTLSyclKernelRef; */ typedef struct DPCTLOpaqueSyclKernelBundle *DPCTLSyclKernelBundleRef; +/*! + * @brief Opaque pointer to a + * ``sycl::kernel_bundle`` + * + */ +typedef struct DPCTLOpaqueSyclInputKernelBundle *DPCTLSyclInputKernelBundleRef; + +/*! + * @brief Opaque pointer to a + * ``sycl::kernel_bundle`` + * + */ +typedef struct DPCTLOpaqueSyclObjectKernelBundle + *DPCTLSyclObjectKernelBundleRef; + +/*! + * @brief Opaque pointer to a ``sycl::kernel_id`` + * + */ +typedef struct DPCTLOpaqueSyclKernelId *DPCTLSyclKernelIdRef; + +/*! + * @brief Opaque pointer to a ``sycl::device_image`` in any bundle state, + * passed to a device image selector. + * + */ +typedef struct DPCTLOpaqueSyclDeviceImage *DPCTLSyclDeviceImageRef; + /*! * @brief Opaque pointer to a ``sycl::platform`` * diff --git a/libsyclinterface/source/dpctl_sycl_kernel_bundle_interface.cpp b/libsyclinterface/source/dpctl_sycl_kernel_bundle_interface.cpp index 163f9efd8c..4300d565d4 100644 --- a/libsyclinterface/source/dpctl_sycl_kernel_bundle_interface.cpp +++ b/libsyclinterface/source/dpctl_sycl_kernel_bundle_interface.cpp @@ -32,6 +32,7 @@ #include "dpctl_sycl_type_casters.hpp" #include /* OpenCL headers */ #include +#include #include #include #include @@ -196,6 +197,111 @@ clReleaseProgramFT get_clReleaseProgram() return st_clReleaseProgramF; } +typedef cl_int (*clReleaseKernelFT)(cl_kernel); +const char *clReleaseKernel_Name = "clReleaseKernel"; +clReleaseKernelFT get_clReleaseKernel() +{ + static auto st_clReleaseKernelF = + cl_loader::get().getSymbol(clReleaseKernel_Name); + + return st_clReleaseKernelF; +} + +typedef cl_int (*clReleaseContextFT)(cl_context); +const char *clReleaseContext_Name = "clReleaseContext"; +clReleaseContextFT get_clReleaseContext() +{ + static auto st_clReleaseContextF = + cl_loader::get().getSymbol(clReleaseContext_Name); + + return st_clReleaseContextF; +} + +typedef cl_int (*clGetProgramBuildInfoFT)(cl_program, + cl_device_id, + cl_program_build_info, + size_t, + void *, + size_t *); +const char *clGetProgramBuildInfo_Name = "clGetProgramBuildInfo"; +clGetProgramBuildInfoFT get_clGetProgramBuildInfo() +{ + static auto st_clGetProgramBuildInfoF = + cl_loader::get().getSymbol( + clGetProgramBuildInfo_Name); + + return st_clGetProgramBuildInfoF; +} + +void _Release_ocl_impl(cl_program clProgram) +{ + if (auto clReleaseProgramF = get_clReleaseProgram()) { + clReleaseProgramF(clProgram); + } +} + +void _Release_ocl_impl(cl_kernel clKernel) +{ + if (auto clReleaseKernelF = get_clReleaseKernel()) { + clReleaseKernelF(clKernel); + } +} + +void _Release_ocl_impl(cl_context clContext) +{ + if (auto clReleaseContextF = get_clReleaseContext()) { + clReleaseContextF(clContext); + } +} + +/*! Releases one reference to an OpenCL object on scope exit. + * sycl::get_native and sycl::make_* retain the OpenCL object, so references + * returned by get_native or clCreate* must be released by the caller. + */ +template class cl_ref_guard +{ +public: + explicit cl_ref_guard(T obj) : obj_(obj) {} + ~cl_ref_guard() + { + if (obj_) { + _Release_ocl_impl(obj_); + } + } + cl_ref_guard(const cl_ref_guard &) = delete; + cl_ref_guard &operator=(const cl_ref_guard &) = delete; + +private: + T obj_; +}; + +std::string _GetBuildLog_ocl_impl(cl_program clProgram, cl_device_id clDevice) +{ + auto clGetProgramBuildInfoF = get_clGetProgramBuildInfo(); + if (clGetProgramBuildInfoF == nullptr) { + return std::string{}; + } + size_t log_size = 0; + if (clGetProgramBuildInfoF(clProgram, clDevice, CL_PROGRAM_BUILD_LOG, 0, + nullptr, &log_size) != CL_SUCCESS || + log_size == 0) + { + return std::string{}; + } + std::string log(log_size, '\0'); + if (clGetProgramBuildInfoF(clProgram, clDevice, CL_PROGRAM_BUILD_LOG, + log_size, log.data(), nullptr) != CL_SUCCESS) + { + return std::string{}; + } + // drop the terminating null character(s) + log.resize(std::strlen(log.c_str())); + return log; +} + +/*! Builds clProgram and wraps it in a kernel bundle. The caller keeps its + * reference to clProgram and must release it. + */ DPCTLSyclKernelBundleRef _CreateKernelBundle_common_ocl_impl(cl_program clProgram, const context &ctx, @@ -209,30 +315,25 @@ _CreateKernelBundle_common_ocl_impl(cl_program clProgram, // that can be passed to the notification function. auto clBuildProgramF = get_clBuildProgram(); if (clBuildProgramF == nullptr) { - auto clReleaseProgramF = get_clReleaseProgram(); - if (clReleaseProgramF) { - clReleaseProgramF(clProgram); - } return nullptr; } cl_int build_status = clBuildProgramF(clProgram, 1, &clDevice, CompileOpts, nullptr, nullptr); if (build_status != CL_SUCCESS) { - error_handler("clBuildProgram failed: " + - _GetErrorCode_ocl_impl(build_status), - __FILE__, __func__, __LINE__); - auto clReleaseProgramF = get_clReleaseProgram(); - if (clReleaseProgramF) { - clReleaseProgramF(clProgram); + 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); return nullptr; } using ekbTy = kernel_bundle; - const ekbTy &kb = - make_kernel_bundle(clProgram, ctx); - return wrap(new ekbTy(kb)); + return wrap(new ekbTy( + make_kernel_bundle(clProgram, ctx))); } DPCTLSyclKernelBundleRef @@ -248,6 +349,7 @@ _CreateKernelBundleWithOCLSource_ocl_impl(const context &ctx, backend_traits::return_type clContext; clContext = get_native(ctx); + cl_ref_guard clContextGuard(clContext); cl_int build_with_source_err_code = CL_SUCCESS; cl_program clProgram = clCreateProgramWithSourceF( @@ -259,6 +361,7 @@ _CreateKernelBundleWithOCLSource_ocl_impl(const context &ctx, __FILE__, __func__, __LINE__); return nullptr; } + cl_ref_guard clProgramGuard(clProgram); return _CreateKernelBundle_common_ocl_impl(clProgram, ctx, dev, CompileOpts); @@ -278,15 +381,16 @@ _CreateKernelBundleWithIL_ocl_impl(const context &ctx, return nullptr; } - backend_traits::return_type clContext; - clContext = get_native(ctx); - if (NumSpecConsts > 0 && SpecConsts == nullptr) { error_handler("NumSpecConsts > 0 but SpecConsts is NULL.", __FILE__, __func__, __LINE__); return nullptr; } + backend_traits::return_type clContext; + clContext = get_native(ctx); + cl_ref_guard clContextGuard(clContext); + cl_int create_err_code = CL_SUCCESS; cl_program clProgram = clCreateProgramWithILF(clContext, IL, il_length, &create_err_code); @@ -298,6 +402,7 @@ _CreateKernelBundleWithIL_ocl_impl(const context &ctx, __FILE__, __func__, __LINE__); return nullptr; } + cl_ref_guard clProgramGuard(clProgram); if (SpecConsts != nullptr && NumSpecConsts > 0) { auto clSetProgramSpecConstF = get_clSetProgramSpecializationConstant(); @@ -314,12 +419,6 @@ _CreateKernelBundleWithIL_ocl_impl(const context &ctx, ". OpenCL Error " + _GetErrorCode_ocl_impl(spec_err), __FILE__, __func__, __LINE__); - - auto clReleaseProgramF = get_clReleaseProgram(); - if (clReleaseProgramF) { - clReleaseProgramF(clProgram); - } - return nullptr; } } @@ -328,12 +427,6 @@ _CreateKernelBundleWithIL_ocl_impl(const context &ctx, error_handler("clSetProgramSpecializationConstant is not available " "in the OpenCL implementation.", __FILE__, __func__, __LINE__); - - auto clReleaseProgramF = get_clReleaseProgram(); - if (clReleaseProgramF) { - clReleaseProgramF(clProgram); - } - return nullptr; } } @@ -354,12 +447,16 @@ bool _HasKernel_ocl_impl(const kernel_bundle &kb, bool found = false; for (auto &cl_pr : oclKB) { + cl_ref_guard clProgramGuard(cl_pr); + if (found) { + continue; + } cl_int create_kernel_err_code = CL_SUCCESS; - [[maybe_unused]] cl_kernel try_kern = + cl_kernel try_kern = clCreateKernelF(cl_pr, kernel_name, &create_kernel_err_code); if (create_kernel_err_code == CL_SUCCESS) { found = true; - break; + _Release_ocl_impl(try_kern); } } return found; @@ -376,36 +473,33 @@ _GetKernel_ocl_impl(const kernel_bundle &kb, std::vector oclKB = get_native(kb); - bool found = false; - cl_kernel ocl_kernel_from_kb; + cl_kernel ocl_kernel_from_kb = nullptr; for (auto &cl_pr : oclKB) { + cl_ref_guard clProgramGuard(cl_pr); + if (ocl_kernel_from_kb) { + continue; + } cl_int create_kernel_err_code = CL_SUCCESS; cl_kernel try_kern = clCreateKernelF(cl_pr, kernel_name, &create_kernel_err_code); if (create_kernel_err_code == CL_SUCCESS) { - found = true; ocl_kernel_from_kb = try_kern; - break; - } - } - if (found) { - try { - context ctx = kb.get_context(); - - const kernel &interop_kernel = - make_kernel(ocl_kernel_from_kb, ctx); - - return wrap(new kernel(interop_kernel)); - } catch (std::exception const &e) { - error_handler(e, __FILE__, __func__, __LINE__); - return nullptr; } } - else { + if (!ocl_kernel_from_kb) { error_handler("Kernel " + std::string(kernel_name) + " not found.", __FILE__, __func__, __LINE__); return nullptr; } + cl_ref_guard clKernelGuard(ocl_kernel_from_kb); + try { + context ctx = kb.get_context(); + return wrap( + new kernel(make_kernel(ocl_kernel_from_kb, ctx))); + } catch (std::exception const &e) { + error_handler(e, __FILE__, __func__, __LINE__); + return nullptr; + } } #ifdef DPCTL_ENABLE_L0_KERNEL_BUNDLE_CREATION @@ -485,6 +579,78 @@ zeKernelCreateFT get_zeKernelCreate() return st_zeKernelCreateF; } +typedef ze_result_t (*zeKernelDestroyFT)(ze_kernel_handle_t); +const char *zeKernelDestroy_Name = "zeKernelDestroy"; +zeKernelDestroyFT get_zeKernelDestroy() +{ + static auto st_zeKernelDestroyF = + ze_loader::get().getSymbol(zeKernelDestroy_Name); + + return st_zeKernelDestroyF; +} + +typedef ze_result_t (*zeModuleBuildLogGetStringFT)(ze_module_build_log_handle_t, + size_t *, + char *); +const char *zeModuleBuildLogGetString_Name = "zeModuleBuildLogGetString"; +zeModuleBuildLogGetStringFT get_zeModuleBuildLogGetString() +{ + static auto st_zeModuleBuildLogGetStringF = + ze_loader::get().getSymbol( + zeModuleBuildLogGetString_Name); + + return st_zeModuleBuildLogGetStringF; +} + +typedef ze_result_t (*zeModuleBuildLogDestroyFT)(ze_module_build_log_handle_t); +const char *zeModuleBuildLogDestroy_Name = "zeModuleBuildLogDestroy"; +zeModuleBuildLogDestroyFT get_zeModuleBuildLogDestroy() +{ + static auto st_zeModuleBuildLogDestroyF = + ze_loader::get().getSymbol( + zeModuleBuildLogDestroy_Name); + + return st_zeModuleBuildLogDestroyF; +} + +void _DestroyKernel_ze_impl(ze_kernel_handle_t ZeKernel) +{ + if (auto zeKernelDestroyFn = get_zeKernelDestroy()) { + zeKernelDestroyFn(ZeKernel); + } +} + +/*! Returns the contents of the build log and destroys it. */ +std::string _ConsumeBuildLog_ze_impl(ze_module_build_log_handle_t ZeBuildLog) +{ + std::string log{}; + if (ZeBuildLog == nullptr) { + return log; + } + auto zeModuleBuildLogGetStringFn = get_zeModuleBuildLogGetString(); + size_t log_size = 0; + if (zeModuleBuildLogGetStringFn && + zeModuleBuildLogGetStringFn(ZeBuildLog, &log_size, nullptr) == + ZE_RESULT_SUCCESS && + log_size > 0) + { + log.resize(log_size); + if (zeModuleBuildLogGetStringFn(ZeBuildLog, &log_size, log.data()) == + ZE_RESULT_SUCCESS) + { + // drop the terminating null character(s) + log.resize(std::strlen(log.c_str())); + } + else { + log.clear(); + } + } + if (auto zeModuleBuildLogDestroyFn = get_zeModuleBuildLogDestroy()) { + zeModuleBuildLogDestroyFn(ZeBuildLog); + } + return log; +} + std::string _GetErrorCode_ze_impl(ze_result_t code) { switch (code) { @@ -558,23 +724,30 @@ _CreateKernelBundleWithIL_ze_impl(const context &SyclCtx, ZeModuleDesc.pBuildFlags = CompileOpts; ZeModuleDesc.pConstants = &ZeSpecConstants; - ze_module_handle_t ZeModule; + ze_module_handle_t ZeModule = nullptr; + ze_module_build_log_handle_t ZeBuildLog = nullptr; auto ret_code = zeModuleCreateFn(ZeContext, ZeDevice, &ZeModuleDesc, - &ZeModule, nullptr); + &ZeModule, &ZeBuildLog); + const std::string &log = _ConsumeBuildLog_ze_impl(ZeBuildLog); if (ret_code != ZE_RESULT_SUCCESS) { - error_handler("Module creation failed " + - _GetErrorCode_ze_impl(ret_code), - __FILE__, __func__, __LINE__); + std::string msg = + "Module creation failed " + _GetErrorCode_ze_impl(ret_code); + if (!log.empty()) { + msg += "\nBuild log:\n" + log; + } + error_handler(msg, __FILE__, __func__, __LINE__, error_level::error); return nullptr; } + // With ownership::transfer the kernel bundle destroys ZeModule. Assumes + // ownership is not taken if make_kernel_bundle throws. + using ekbTy = kernel_bundle; try { - const auto &kb = make_kernel_bundle( - {ZeModule, ext::oneapi::level_zero::ownership::keep}, SyclCtx); - - return wrap>( - new kernel_bundle(kb)); + return wrap( + new ekbTy(make_kernel_bundle( + {ZeModule, ext::oneapi::level_zero::ownership::transfer}, + SyclCtx))); } catch (std::exception const &e) { error_handler(e, __FILE__, __func__, __LINE__); auto zeModuleDestroyFn = get_zeModuleDestroy(); @@ -597,25 +770,29 @@ _GetKernel_ze_impl(const kernel_bundle &kb, } auto ZeKernelBundle = sycl::get_native(kb); - bool found = false; // Populate the Level Zero kernel descriptions ze_kernel_desc_t ZeKernelDescr = {ZE_STRUCTURE_TYPE_KERNEL_DESC, nullptr, 0, // flags kernel_name}; - std::unique_ptr syclInteropKern_ptr; - ze_kernel_handle_t ZeKern; for (auto &ZeM : ZeKernelBundle) { + ze_kernel_handle_t ZeKern = nullptr; ze_result_t ze_status = zeKernelCreateFn(ZeM, &ZeKernelDescr, &ZeKern); if (ze_status == ZE_RESULT_SUCCESS) { - found = true; - const auto &ctx = kb.get_context(); - const auto &k = make_kernel( - {kb, ZeKern, ext::oneapi::level_zero::ownership::keep}, ctx); - syclInteropKern_ptr = std::unique_ptr(new kernel(k)); - break; + // With ownership::transfer the kernel destroys ZeKern. Assumes + // ownership is not taken if make_kernel throws. + try { + const auto &ctx = kb.get_context(); + return wrap(new kernel(make_kernel( + {kb, ZeKern, ext::oneapi::level_zero::ownership::transfer}, + ctx))); + } catch (std::exception const &e) { + error_handler(e, __FILE__, __func__, __LINE__); + _DestroyKernel_ze_impl(ZeKern); + return nullptr; + } } else { if (ze_status != ZE_RESULT_ERROR_INVALID_KERNEL_NAME) { @@ -627,15 +804,10 @@ _GetKernel_ze_impl(const kernel_bundle &kb, } } - if (found) { - return wrap(new kernel(*syclInteropKern_ptr)); - } - else { - error_handler("Kernel named " + std::string(kernel_name) + - " could not be found.", - __FILE__, __func__, __LINE__, error_level::error); - return nullptr; - } + error_handler("Kernel named " + std::string(kernel_name) + + " could not be found.", + __FILE__, __func__, __LINE__, error_level::error); + return nullptr; } bool _HasKernel_ze_impl(const kernel_bundle &kb, @@ -655,12 +827,12 @@ bool _HasKernel_ze_impl(const kernel_bundle &kb, 0, // flags kernel_name}; - std::unique_ptr syclInteropKern_ptr; - ze_kernel_handle_t ZeKern; for (auto &ZeM : ZeKernelBundle) { + ze_kernel_handle_t ZeKern = nullptr; ze_result_t ze_status = zeKernelCreateFn(ZeM, &ZeKernelDescr, &ZeKern); if (ze_status == ZE_RESULT_SUCCESS) { + _DestroyKernel_ze_impl(ZeKern); return true; } else { @@ -764,26 +936,26 @@ __dpctl_give DPCTLSyclKernelBundleRef DPCTLKernelBundle_CreateFromOCLSource( SyclCtx = unwrap(Ctx); SyclDev = unwrap(Dev); - // get the backend type - auto BE = SyclCtx->get_platform().get_backend(); - switch (BE) { - case backend::opencl: - try { + try { + // get the backend type + auto BE = SyclCtx->get_platform().get_backend(); + switch (BE) { + case backend::opencl: return _CreateKernelBundleWithOCLSource_ocl_impl( *SyclCtx, *SyclDev, Source, CompileOpts); - } catch (std::exception const &e) { - error_handler(e, __FILE__, __func__, __LINE__); + case backend::ext_oneapi_level_zero: + error_handler( + "CreateFromSource is not supported for Level Zero backend.", + __FILE__, __func__, __LINE__); + return nullptr; + default: + error_handler( + "CreateFromSource is not supported in unknown backend.", + __FILE__, __func__, __LINE__); return nullptr; } - break; - case backend::ext_oneapi_level_zero: - error_handler( - "CreateFromSource is not supported for Level Zero backend.", - __FILE__, __func__, __LINE__); - return nullptr; - default: - error_handler("CreateFromSource is not supported in unknown backend.", - __FILE__, __func__, __LINE__); + } catch (std::exception const &e) { + error_handler(e, __FILE__, __func__, __LINE__); return nullptr; } } @@ -801,19 +973,24 @@ DPCTLKernelBundle_GetKernel(__dpctl_keep DPCTLSyclKernelBundleRef KBRef, __LINE__); return nullptr; } - auto SyclKB = unwrap>(KBRef); - sycl::backend be = SyclKB->get_backend(); - switch (be) { - case sycl::backend::opencl: - return _GetKernel_ocl_impl(*SyclKB, KernelName); - case sycl::backend::ext_oneapi_level_zero: + try { + auto SyclKB = unwrap>(KBRef); + sycl::backend be = SyclKB->get_backend(); + switch (be) { + case sycl::backend::opencl: + return _GetKernel_ocl_impl(*SyclKB, KernelName); + case sycl::backend::ext_oneapi_level_zero: #ifdef DPCTL_ENABLE_L0_KERNEL_BUNDLE_CREATION - return _GetKernel_ze_impl(*SyclKB, KernelName); + return _GetKernel_ze_impl(*SyclKB, KernelName); #endif - default: - std::ostringstream os; - os << "Backend " << be << " is not supported"; - error_handler(os.str(), __FILE__, __func__, __LINE__); + default: + std::ostringstream os; + os << "Backend " << be << " is not supported"; + error_handler(os.str(), __FILE__, __func__, __LINE__); + return nullptr; + } + } catch (std::exception const &e) { + error_handler(e, __FILE__, __func__, __LINE__); return nullptr; } } @@ -831,19 +1008,24 @@ bool DPCTLKernelBundle_HasKernel(__dpctl_keep DPCTLSyclKernelBundleRef KBRef, return false; } - auto SyclKB = unwrap>(KBRef); - sycl::backend be = SyclKB->get_backend(); - switch (be) { - case sycl::backend::opencl: - return _HasKernel_ocl_impl(*SyclKB, KernelName); - case sycl::backend::ext_oneapi_level_zero: + try { + auto SyclKB = unwrap>(KBRef); + sycl::backend be = SyclKB->get_backend(); + switch (be) { + case sycl::backend::opencl: + return _HasKernel_ocl_impl(*SyclKB, KernelName); + case sycl::backend::ext_oneapi_level_zero: #ifdef DPCTL_ENABLE_L0_KERNEL_BUNDLE_CREATION - return _HasKernel_ze_impl(*SyclKB, KernelName); + return _HasKernel_ze_impl(*SyclKB, KernelName); #endif - default: - std::ostringstream os; - os << "Backend " << be << " is not supported"; - error_handler(os.str(), __FILE__, __func__, __LINE__); + default: + std::ostringstream os; + os << "Backend " << be << " is not supported"; + error_handler(os.str(), __FILE__, __func__, __LINE__); + return false; + } + } catch (std::exception const &e) { + error_handler(e, __FILE__, __func__, __LINE__); return false; } } diff --git a/libsyclinterface/source/dpctl_sycl_kernel_bundle_state_interface.cpp b/libsyclinterface/source/dpctl_sycl_kernel_bundle_state_interface.cpp new file mode 100644 index 0000000000..22215cddaf --- /dev/null +++ b/libsyclinterface/source/dpctl_sycl_kernel_bundle_state_interface.cpp @@ -0,0 +1,1025 @@ +//===- dpctl_sycl_kernel_bundle_state_interface.cpp - Implements C API for +// sycl::kernel_bundle states and sycl::kernel_id -*-C++-*- ===// +// +// Data Parallel Control (dpctl) +// +// Copyright 2026 Intel Corporation +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//===----------------------------------------------------------------------===// +/// +/// \file +/// This file implements the kernel_id functions and the kernel_bundle +/// functions for the input, object and executable bundle states declared in +/// dpctl_sycl_kernel_bundle_interface.h. +/// +//===----------------------------------------------------------------------===// + +#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 +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef _WIN32 +#define NOMINMAX +#include +#else +#include +#endif + +using namespace sycl; + +namespace +{ +static_assert(__SYCL_COMPILER_VERSION >= __SYCL_COMPILER_VERSION_REQUIRED, + "The compiler does not meet minimum version requirement"); + +using namespace dpctl::syclinterface; + +template struct bundle_ref; +template <> struct bundle_ref +{ + using type = DPCTLSyclInputKernelBundleRef; +}; +template <> struct bundle_ref +{ + using type = DPCTLSyclObjectKernelBundleRef; +}; +template <> struct bundle_ref +{ + using type = DPCTLSyclKernelBundleRef; +}; +template using bundle_ref_t = typename bundle_ref::type; + +std::vector unwrap_devices(DPCTLDeviceVectorRef DVRef) +{ + auto DV = unwrap>(DVRef); + std::vector Devs; + Devs.reserve(DV->size()); + for (auto DRef : *DV) { + auto D = unwrap(DRef); + if (!D) + throw std::invalid_argument("Device vector has a nullptr element"); + Devs.push_back(*D); + } + return Devs; +} + +std::vector unwrap_kernel_ids(DPCTLKernelIdVectorRef KIdVRef) +{ + auto KIdV = unwrap>(KIdVRef); + std::vector KIds; + KIds.reserve(KIdV->size()); + for (auto KIdRef : *KIdV) { + auto KId = unwrap(KIdRef); + if (!KId) + throw std::invalid_argument( + "Kernel id vector has a nullptr element"); + KIds.push_back(*KId); + } + return KIds; +} + +__dpctl_give DPCTLDeviceVectorRef wrap_devices(const std::vector &Devs) +{ + auto DV = std::make_unique>(); + DV->reserve(Devs.size()); + for (const auto &D : Devs) + DV->push_back(wrap(new device(D))); + return wrap>(DV.release()); +} + +__dpctl_give DPCTLKernelIdVectorRef +wrap_kernel_ids(const std::vector &KIds) +{ + auto KIdV = std::make_unique>(); + KIdV->reserve(KIds.size()); + for (const auto &KId : KIds) + KIdV->push_back(wrap(new kernel_id(KId))); + return wrap>(KIdV.release()); +} + +template +__dpctl_give bundle_ref_t wrap_bundle(kernel_bundle &&KB) +{ + return wrap>(new kernel_bundle(std::move(KB))); +} + +template +__dpctl_give bundle_ref_t +create_from_context_impl(DPCTLSyclContextRef CRef, + DPCTLDeviceVectorRef DVRef, + DPCTLKernelIdVectorRef KIdVRef, + const char *Fn) +{ + auto Ctx = unwrap(CRef); + if (!Ctx) { + error_handler("Input CRef is nullptr", __FILE__, Fn, __LINE__); + return nullptr; + } + try { + auto Devs = DVRef ? unwrap_devices(DVRef) : Ctx->get_devices(); + if (KIdVRef) + return wrap_bundle(sycl::get_kernel_bundle( + *Ctx, Devs, unwrap_kernel_ids(KIdVRef))); + return wrap_bundle(sycl::get_kernel_bundle(*Ctx, Devs)); + } catch (std::exception const &e) { + error_handler(e, __FILE__, Fn, __LINE__); + return nullptr; + } +} + +template +bool can_create_from_context_impl(DPCTLSyclContextRef CRef, + DPCTLDeviceVectorRef DVRef, + DPCTLKernelIdVectorRef KIdVRef, + const char *Fn) +{ + auto Ctx = unwrap(CRef); + if (!Ctx) { + error_handler("Input CRef is nullptr", __FILE__, Fn, __LINE__); + return false; + } + try { + auto Devs = DVRef ? unwrap_devices(DVRef) : Ctx->get_devices(); + if (KIdVRef) + return sycl::has_kernel_bundle(*Ctx, Devs, + unwrap_kernel_ids(KIdVRef)); + return sycl::has_kernel_bundle(*Ctx, Devs); + } catch (std::exception const &e) { + error_handler(e, __FILE__, Fn, __LINE__); + return false; + } +} + +template +const kernel_bundle *get_bundle_impl(bundle_ref_t KBRef, const char *Fn) +{ + auto KB = unwrap>(KBRef); + if (!KB) + error_handler("Input KBRef is nullptr", __FILE__, Fn, __LINE__); + return KB; +} + +template +__dpctl_give bundle_ref_t copy_bundle_impl(bundle_ref_t KBRef, + const char *Fn) +{ + auto KB = get_bundle_impl(KBRef, Fn); + if (!KB) + return nullptr; + try { + return wrap>(new kernel_bundle(*KB)); + } catch (std::exception const &e) { + error_handler(e, __FILE__, Fn, __LINE__); + return nullptr; + } +} + +template +__dpctl_give DPCTLSyclContextRef get_context_impl(bundle_ref_t KBRef, + const char *Fn) +{ + auto KB = get_bundle_impl(KBRef, Fn); + if (!KB) + return nullptr; + try { + return wrap(new context(KB->get_context())); + } catch (std::exception const &e) { + error_handler(e, __FILE__, Fn, __LINE__); + return nullptr; + } +} + +template +__dpctl_give DPCTLDeviceVectorRef get_devices_impl(bundle_ref_t KBRef, + const char *Fn) +{ + auto KB = get_bundle_impl(KBRef, Fn); + if (!KB) + return nullptr; + try { + return wrap_devices(KB->get_devices()); + } catch (std::exception const &e) { + error_handler(e, __FILE__, Fn, __LINE__); + return nullptr; + } +} + +template +DPCTLSyclBackendType get_backend_impl(bundle_ref_t KBRef, const char *Fn) +{ + auto KB = get_bundle_impl(KBRef, Fn); + if (!KB) + return DPCTL_UNKNOWN_BACKEND; + try { + return DPCTL_SyclBackendToDPCTLBackendType(KB->get_backend()); + } catch (std::exception const &e) { + error_handler(e, __FILE__, Fn, __LINE__); + return DPCTL_UNKNOWN_BACKEND; + } +} + +template +bool is_empty_impl(bundle_ref_t KBRef, const char *Fn) +{ + auto KB = get_bundle_impl(KBRef, Fn); + return KB ? KB->empty() : false; +} + +template +__dpctl_give DPCTLKernelIdVectorRef get_kernel_ids_impl(bundle_ref_t KBRef, + const char *Fn) +{ + auto KB = get_bundle_impl(KBRef, Fn); + if (!KB) + return nullptr; + try { + return wrap_kernel_ids(KB->get_kernel_ids()); + } catch (std::exception const &e) { + error_handler(e, __FILE__, Fn, __LINE__); + return nullptr; + } +} + +template +bool has_kernel_id_impl(bundle_ref_t KBRef, + DPCTLSyclKernelIdRef KIdRef, + DPCTLSyclDeviceRef DRef, + const char *Fn) +{ + auto KB = get_bundle_impl(KBRef, Fn); + if (!KB) + return false; + auto KId = unwrap(KIdRef); + if (!KId) { + error_handler("Input KIdRef is nullptr", __FILE__, Fn, __LINE__); + return false; + } + try { + if (auto D = unwrap(DRef)) + return KB->has_kernel(*KId, *D); + return KB->has_kernel(*KId); + } catch (std::exception const &e) { + error_handler(e, __FILE__, Fn, __LINE__); + return false; + } +} + +template +bool contains_specialization_constants_impl(bundle_ref_t KBRef, + const char *Fn) +{ + auto KB = get_bundle_impl(KBRef, Fn); + return KB ? KB->contains_specialization_constants() : false; +} + +template +bool native_specialization_constant_impl(bundle_ref_t KBRef, const char *Fn) +{ + auto KB = get_bundle_impl(KBRef, Fn); + return KB ? KB->native_specialization_constant() : false; +} + +template +size_t get_num_device_images_impl(bundle_ref_t KBRef, const char *Fn) +{ + auto KB = get_bundle_impl(KBRef, Fn); + if (!KB) + return 0; + return static_cast(std::distance(KB->begin(), KB->end())); +} + +template +bool device_image_has_kernel_impl(bundle_ref_t KBRef, + size_t Index, + DPCTLSyclKernelIdRef KIdRef, + DPCTLSyclDeviceRef DRef, + const char *Fn) +{ + auto KB = get_bundle_impl(KBRef, Fn); + if (!KB) + return false; + auto KId = unwrap(KIdRef); + if (!KId) { + error_handler("Input KIdRef is nullptr", __FILE__, Fn, __LINE__); + return false; + } + auto NumImages = static_cast(std::distance(KB->begin(), KB->end())); + if (Index >= NumImages) { + error_handler("Device image index " + std::to_string(Index) + + " is out of range for a kernel bundle with " + + std::to_string(NumImages) + " device images", + __FILE__, Fn, __LINE__); + return false; + } + try { + auto It = KB->begin(); + std::advance(It, Index); + if (auto D = unwrap(DRef)) + return It->has_kernel(*KId, *D); + return It->has_kernel(*KId); + } catch (std::exception const &e) { + error_handler(e, __FILE__, Fn, __LINE__); + return false; + } +} + +template +std::vector> unwrap_bundles(size_t NumKBRefs, + const bundle_ref_t *KBRefs) +{ + if (NumKBRefs == 0 || !KBRefs) + throw std::invalid_argument("No kernel bundles were given"); + std::vector> Bundles; + Bundles.reserve(NumKBRefs); + for (size_t i = 0; i < NumKBRefs; ++i) { + auto KB = unwrap>(KBRefs[i]); + if (!KB) + throw std::invalid_argument( + "Kernel bundle array has a nullptr element"); + Bundles.push_back(*KB); + } + return Bundles; +} + +template +__dpctl_give bundle_ref_t join_bundles_impl(size_t NumKBRefs, + const bundle_ref_t *KBRefs, + const char *Fn) +{ + try { + return wrap_bundle(sycl::join(unwrap_bundles(NumKBRefs, KBRefs))); + } catch (std::exception const &e) { + error_handler(e, __FILE__, Fn, __LINE__); + return nullptr; + } +} + +struct device_image_view +{ + std::function has_kernel; +}; + +template +__dpctl_give bundle_ref_t +create_with_selector_impl(DPCTLSyclContextRef CRef, + DPCTLDeviceVectorRef DVRef, + DPCTLDeviceImageSelectorFn Selector, + void *UserData, + const char *Fn) +{ + auto Ctx = unwrap(CRef); + if (!Ctx) { + error_handler("Input CRef is nullptr", __FILE__, Fn, __LINE__); + return nullptr; + } + if (!Selector) { + error_handler("Input Selector is nullptr", __FILE__, Fn, __LINE__); + return nullptr; + } + try { + auto Devs = DVRef ? unwrap_devices(DVRef) : Ctx->get_devices(); + auto Sel = [Selector, UserData](const device_image &Img) { + device_image_view View{ + [&Img](const kernel_id &KId, const device *D) { + return D ? Img.has_kernel(KId, *D) : Img.has_kernel(KId); + }}; + return Selector(reinterpret_cast(&View), + UserData); + }; + return wrap_bundle(sycl::get_kernel_bundle(*Ctx, Devs, Sel)); + } catch (std::exception const &e) { + error_handler(e, __FILE__, Fn, __LINE__); + return nullptr; + } +} + +// Kernel ids registered by each library loaded with DPCTLKernelId_LoadLibrary +struct loaded_kernel_libraries +{ + std::mutex Mutex; + std::unordered_map> KernelIds; +}; + +loaded_kernel_libraries &get_loaded_kernel_libraries() +{ + // never destroyed, as the libraries are never unloaded + static auto *Libs = new loaded_kernel_libraries; + return *Libs; +} + +void *open_library(const char *Path, std::string &Error) +{ +#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); + if (!Handle) + Error = "LoadLibraryEx failed with error code " + + std::to_string(GetLastError()); +#else + void *Handle = dlopen(Path, RTLD_NOW | RTLD_LOCAL); + if (!Handle) { + const char *Msg = dlerror(); + Error = Msg ? Msg : "dlopen failed"; + } +#endif + return Handle; +} + +} // end of anonymous namespace + +#undef EL +#undef EL_SYCL_TYPE +#define EL KernelId +#define EL_SYCL_TYPE sycl::kernel_id +#include "dpctl_vector_templ.cpp" +#undef EL +#undef EL_SYCL_TYPE + +__dpctl_give const char * +DPCTLKernelId_GetName(__dpctl_keep const DPCTLSyclKernelIdRef KIdRef) +{ + auto KId = unwrap(KIdRef); + if (!KId) { + error_handler("Input KIdRef is nullptr", __FILE__, __func__, __LINE__); + return nullptr; + } + return dpctl::helper::cstring_from_string(KId->get_name()); +} + +bool DPCTLKernelId_AreEq(__dpctl_keep const DPCTLSyclKernelIdRef KIdRef1, + __dpctl_keep const DPCTLSyclKernelIdRef KIdRef2) +{ + auto KId1 = unwrap(KIdRef1); + auto KId2 = unwrap(KIdRef2); + if (!(KId1 && KId2)) { + error_handler("At least one of the inputs is nullptr", __FILE__, + __func__, __LINE__); + return false; + } + return *KId1 == *KId2; +} + +size_t DPCTLKernelId_Hash(__dpctl_keep const DPCTLSyclKernelIdRef KIdRef) +{ + auto KId = unwrap(KIdRef); + if (!KId) { + error_handler("Input KIdRef is nullptr", __FILE__, __func__, __LINE__); + return 0; + } + std::hash hash_fn; + return hash_fn(*KId); +} + +__dpctl_give DPCTLSyclKernelIdRef +DPCTLKernelId_Copy(__dpctl_keep const DPCTLSyclKernelIdRef KIdRef) +{ + auto KId = unwrap(KIdRef); + if (!KId) { + error_handler("Cannot copy DPCTLSyclKernelIdRef as input is a nullptr", + __FILE__, __func__, __LINE__); + return nullptr; + } + try { + return wrap(new kernel_id(*KId)); + } catch (std::exception const &e) { + error_handler(e, __FILE__, __func__, __LINE__); + return nullptr; + } +} + +void DPCTLKernelId_Delete(__dpctl_take DPCTLSyclKernelIdRef KIdRef) +{ + delete unwrap(KIdRef); +} + +__dpctl_give DPCTLKernelIdVectorRef DPCTLKernelId_GetAll(void) +{ + try { + return wrap_kernel_ids(sycl::get_kernel_ids()); + } catch (std::exception const &e) { + error_handler(e, __FILE__, __func__, __LINE__); + return nullptr; + } +} + +__dpctl_give DPCTLKernelIdVectorRef +DPCTLKernelId_LoadLibrary(__dpctl_keep const char *Path) +{ + if (!Path) { + error_handler("Input Path is nullptr", __FILE__, __func__, __LINE__); + return nullptr; + } + auto &Libs = get_loaded_kernel_libraries(); + try { + std::lock_guard Lock(Libs.Mutex); + 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 Known(Before.begin(), Before.end()); + std::vector New; + for (const auto &KId : sycl::get_kernel_ids()) { + if (Known.count(KId) == 0) + New.push_back(KId); + } + It = Libs.KernelIds.emplace(Handle, std::move(New)).first; + } + return wrap_kernel_ids(It->second); + } catch (std::exception const &e) { + error_handler(e, __FILE__, __func__, __LINE__); + return nullptr; + } +} + +bool DPCTLKernelId_IsCompatible(__dpctl_keep const DPCTLKernelIdVectorRef + KIdVRef, + __dpctl_keep const DPCTLSyclDeviceRef DRef) +{ + auto D = unwrap(DRef); + if (!(KIdVRef && D)) { + error_handler("At least one of the inputs is nullptr", __FILE__, + __func__, __LINE__); + return false; + } + try { + return sycl::is_compatible(unwrap_kernel_ids(KIdVRef), *D); + } catch (std::exception const &e) { + error_handler(e, __FILE__, __func__, __LINE__); + return false; + } +} + +__dpctl_give DPCTLSyclKernelBundleRef DPCTLKernelBundle_CreateFromContext( + __dpctl_keep const DPCTLSyclContextRef CRef, + __dpctl_keep const DPCTLDeviceVectorRef DVRef, + __dpctl_keep const DPCTLKernelIdVectorRef KIdVRef) +{ + return create_from_context_impl( + CRef, DVRef, KIdVRef, __func__); +} + +bool DPCTLKernelBundle_CanCreateFromContext( + __dpctl_keep const DPCTLSyclContextRef CRef, + __dpctl_keep const DPCTLDeviceVectorRef DVRef, + __dpctl_keep const DPCTLKernelIdVectorRef KIdVRef) +{ + return can_create_from_context_impl( + CRef, DVRef, KIdVRef, __func__); +} + +__dpctl_give DPCTLSyclContextRef +DPCTLKernelBundle_GetContext(__dpctl_keep const DPCTLSyclKernelBundleRef KBRef) +{ + return get_context_impl(KBRef, __func__); +} + +__dpctl_give DPCTLDeviceVectorRef +DPCTLKernelBundle_GetDevices(__dpctl_keep const DPCTLSyclKernelBundleRef KBRef) +{ + return get_devices_impl(KBRef, __func__); +} + +DPCTLSyclBackendType +DPCTLKernelBundle_GetBackend(__dpctl_keep const DPCTLSyclKernelBundleRef KBRef) +{ + return get_backend_impl(KBRef, __func__); +} + +bool DPCTLKernelBundle_IsEmpty( + __dpctl_keep const DPCTLSyclKernelBundleRef KBRef) +{ + return is_empty_impl(KBRef, __func__); +} + +__dpctl_give DPCTLKernelIdVectorRef DPCTLKernelBundle_GetKernelIds( + __dpctl_keep const DPCTLSyclKernelBundleRef KBRef) +{ + return get_kernel_ids_impl(KBRef, __func__); +} + +bool DPCTLKernelBundle_HasKernelId( + __dpctl_keep const DPCTLSyclKernelBundleRef KBRef, + __dpctl_keep const DPCTLSyclKernelIdRef KIdRef, + __dpctl_keep const DPCTLSyclDeviceRef DRef) +{ + return has_kernel_id_impl(KBRef, KIdRef, DRef, + __func__); +} + +bool DPCTLKernelBundle_ContainsSpecializationConstants( + __dpctl_keep const DPCTLSyclKernelBundleRef KBRef) +{ + return contains_specialization_constants_impl( + KBRef, __func__); +} + +bool DPCTLKernelBundle_NativeSpecializationConstant( + __dpctl_keep const DPCTLSyclKernelBundleRef KBRef) +{ + return native_specialization_constant_impl( + KBRef, __func__); +} + +size_t DPCTLKernelBundle_GetNumDeviceImages( + __dpctl_keep const DPCTLSyclKernelBundleRef KBRef) +{ + return get_num_device_images_impl(KBRef, + __func__); +} + +bool DPCTLKernelBundle_DeviceImageHasKernel( + __dpctl_keep const DPCTLSyclKernelBundleRef KBRef, + size_t Index, + __dpctl_keep const DPCTLSyclKernelIdRef KIdRef, + __dpctl_keep const DPCTLSyclDeviceRef DRef) +{ + return device_image_has_kernel_impl( + KBRef, Index, KIdRef, DRef, __func__); +} + +__dpctl_give DPCTLSyclKernelBundleRef +DPCTLKernelBundle_Join(size_t NumKBRefs, + __dpctl_keep const DPCTLSyclKernelBundleRef *KBRefs) +{ + return join_bundles_impl(NumKBRefs, KBRefs, + __func__); +} + +__dpctl_give DPCTLSyclKernelRef DPCTLKernelBundle_GetKernelById( + __dpctl_keep const DPCTLSyclKernelBundleRef KBRef, + __dpctl_keep const DPCTLSyclKernelIdRef KIdRef) +{ + auto KB = get_bundle_impl(KBRef, __func__); + if (!KB) + return nullptr; + auto KId = unwrap(KIdRef); + if (!KId) { + error_handler("Input KIdRef is nullptr", __FILE__, __func__, __LINE__); + return nullptr; + } + try { + return wrap(new kernel(KB->get_kernel(*KId))); + } catch (std::exception const &e) { + error_handler(e, __FILE__, __func__, __LINE__); + return nullptr; + } +} + +__dpctl_give DPCTLSyclInputKernelBundleRef +DPCTLInputKernelBundle_CreateFromContext( + __dpctl_keep const DPCTLSyclContextRef CRef, + __dpctl_keep const DPCTLDeviceVectorRef DVRef, + __dpctl_keep const DPCTLKernelIdVectorRef KIdVRef) +{ + return create_from_context_impl(CRef, DVRef, KIdVRef, + __func__); +} + +bool DPCTLInputKernelBundle_CanCreateFromContext( + __dpctl_keep const DPCTLSyclContextRef CRef, + __dpctl_keep const DPCTLDeviceVectorRef DVRef, + __dpctl_keep const DPCTLKernelIdVectorRef KIdVRef) +{ + return can_create_from_context_impl(CRef, DVRef, + KIdVRef, __func__); +} + +__dpctl_give DPCTLSyclInputKernelBundleRef DPCTLInputKernelBundle_Copy( + __dpctl_keep const DPCTLSyclInputKernelBundleRef KBRef) +{ + return copy_bundle_impl(KBRef, __func__); +} + +void DPCTLInputKernelBundle_Delete( + __dpctl_take DPCTLSyclInputKernelBundleRef KBRef) +{ + delete unwrap>(KBRef); +} + +__dpctl_give DPCTLSyclContextRef DPCTLInputKernelBundle_GetContext( + __dpctl_keep const DPCTLSyclInputKernelBundleRef KBRef) +{ + return get_context_impl(KBRef, __func__); +} + +__dpctl_give DPCTLDeviceVectorRef DPCTLInputKernelBundle_GetDevices( + __dpctl_keep const DPCTLSyclInputKernelBundleRef KBRef) +{ + return get_devices_impl(KBRef, __func__); +} + +DPCTLSyclBackendType DPCTLInputKernelBundle_GetBackend( + __dpctl_keep const DPCTLSyclInputKernelBundleRef KBRef) +{ + return get_backend_impl(KBRef, __func__); +} + +bool DPCTLInputKernelBundle_IsEmpty( + __dpctl_keep const DPCTLSyclInputKernelBundleRef KBRef) +{ + return is_empty_impl(KBRef, __func__); +} + +__dpctl_give DPCTLKernelIdVectorRef DPCTLInputKernelBundle_GetKernelIds( + __dpctl_keep const DPCTLSyclInputKernelBundleRef KBRef) +{ + return get_kernel_ids_impl(KBRef, __func__); +} + +bool DPCTLInputKernelBundle_HasKernelId( + __dpctl_keep const DPCTLSyclInputKernelBundleRef KBRef, + __dpctl_keep const DPCTLSyclKernelIdRef KIdRef, + __dpctl_keep const DPCTLSyclDeviceRef DRef) +{ + return has_kernel_id_impl(KBRef, KIdRef, DRef, + __func__); +} + +bool DPCTLInputKernelBundle_ContainsSpecializationConstants( + __dpctl_keep const DPCTLSyclInputKernelBundleRef KBRef) +{ + return contains_specialization_constants_impl( + KBRef, __func__); +} + +bool DPCTLInputKernelBundle_NativeSpecializationConstant( + __dpctl_keep const DPCTLSyclInputKernelBundleRef KBRef) +{ + return native_specialization_constant_impl(KBRef, + __func__); +} + +size_t DPCTLInputKernelBundle_GetNumDeviceImages( + __dpctl_keep const DPCTLSyclInputKernelBundleRef KBRef) +{ + return get_num_device_images_impl(KBRef, __func__); +} + +bool DPCTLInputKernelBundle_DeviceImageHasKernel( + __dpctl_keep const DPCTLSyclInputKernelBundleRef KBRef, + size_t Index, + __dpctl_keep const DPCTLSyclKernelIdRef KIdRef, + __dpctl_keep const DPCTLSyclDeviceRef DRef) +{ + return device_image_has_kernel_impl( + KBRef, Index, KIdRef, DRef, __func__); +} + +__dpctl_give DPCTLSyclInputKernelBundleRef DPCTLInputKernelBundle_Join( + size_t NumKBRefs, + __dpctl_keep const DPCTLSyclInputKernelBundleRef *KBRefs) +{ + return join_bundles_impl(NumKBRefs, KBRefs, __func__); +} + +__dpctl_give DPCTLSyclObjectKernelBundleRef DPCTLInputKernelBundle_Compile( + __dpctl_keep const DPCTLSyclInputKernelBundleRef KBRef, + __dpctl_keep const DPCTLDeviceVectorRef DVRef) +{ + auto KB = get_bundle_impl(KBRef, __func__); + if (!KB) + return nullptr; + try { + if (DVRef) + return wrap_bundle( + sycl::compile(*KB, unwrap_devices(DVRef))); + return wrap_bundle(sycl::compile(*KB)); + } catch (std::exception const &e) { + error_handler(e, __FILE__, __func__, __LINE__); + return nullptr; + } +} + +__dpctl_give DPCTLSyclKernelBundleRef DPCTLInputKernelBundle_Build( + __dpctl_keep const DPCTLSyclInputKernelBundleRef KBRef, + __dpctl_keep const DPCTLDeviceVectorRef DVRef) +{ + auto KB = get_bundle_impl(KBRef, __func__); + if (!KB) + return nullptr; + try { + if (DVRef) + return wrap_bundle( + sycl::build(*KB, unwrap_devices(DVRef))); + return wrap_bundle(sycl::build(*KB)); + } catch (std::exception const &e) { + error_handler(e, __FILE__, __func__, __LINE__); + return nullptr; + } +} + +__dpctl_give DPCTLSyclObjectKernelBundleRef +DPCTLObjectKernelBundle_CreateFromContext( + __dpctl_keep const DPCTLSyclContextRef CRef, + __dpctl_keep const DPCTLDeviceVectorRef DVRef, + __dpctl_keep const DPCTLKernelIdVectorRef KIdVRef) +{ + return create_from_context_impl(CRef, DVRef, KIdVRef, + __func__); +} + +bool DPCTLObjectKernelBundle_CanCreateFromContext( + __dpctl_keep const DPCTLSyclContextRef CRef, + __dpctl_keep const DPCTLDeviceVectorRef DVRef, + __dpctl_keep const DPCTLKernelIdVectorRef KIdVRef) +{ + return can_create_from_context_impl( + CRef, DVRef, KIdVRef, __func__); +} + +__dpctl_give DPCTLSyclObjectKernelBundleRef DPCTLObjectKernelBundle_Copy( + __dpctl_keep const DPCTLSyclObjectKernelBundleRef KBRef) +{ + return copy_bundle_impl(KBRef, __func__); +} + +void DPCTLObjectKernelBundle_Delete( + __dpctl_take DPCTLSyclObjectKernelBundleRef KBRef) +{ + delete unwrap>(KBRef); +} + +__dpctl_give DPCTLSyclContextRef DPCTLObjectKernelBundle_GetContext( + __dpctl_keep const DPCTLSyclObjectKernelBundleRef KBRef) +{ + return get_context_impl(KBRef, __func__); +} + +__dpctl_give DPCTLDeviceVectorRef DPCTLObjectKernelBundle_GetDevices( + __dpctl_keep const DPCTLSyclObjectKernelBundleRef KBRef) +{ + return get_devices_impl(KBRef, __func__); +} + +DPCTLSyclBackendType DPCTLObjectKernelBundle_GetBackend( + __dpctl_keep const DPCTLSyclObjectKernelBundleRef KBRef) +{ + return get_backend_impl(KBRef, __func__); +} + +bool DPCTLObjectKernelBundle_IsEmpty( + __dpctl_keep const DPCTLSyclObjectKernelBundleRef KBRef) +{ + return is_empty_impl(KBRef, __func__); +} + +__dpctl_give DPCTLKernelIdVectorRef DPCTLObjectKernelBundle_GetKernelIds( + __dpctl_keep const DPCTLSyclObjectKernelBundleRef KBRef) +{ + return get_kernel_ids_impl(KBRef, __func__); +} + +bool DPCTLObjectKernelBundle_HasKernelId( + __dpctl_keep const DPCTLSyclObjectKernelBundleRef KBRef, + __dpctl_keep const DPCTLSyclKernelIdRef KIdRef, + __dpctl_keep const DPCTLSyclDeviceRef DRef) +{ + return has_kernel_id_impl(KBRef, KIdRef, DRef, + __func__); +} + +bool DPCTLObjectKernelBundle_ContainsSpecializationConstants( + __dpctl_keep const DPCTLSyclObjectKernelBundleRef KBRef) +{ + return contains_specialization_constants_impl( + KBRef, __func__); +} + +bool DPCTLObjectKernelBundle_NativeSpecializationConstant( + __dpctl_keep const DPCTLSyclObjectKernelBundleRef KBRef) +{ + return native_specialization_constant_impl(KBRef, + __func__); +} + +size_t DPCTLObjectKernelBundle_GetNumDeviceImages( + __dpctl_keep const DPCTLSyclObjectKernelBundleRef KBRef) +{ + return get_num_device_images_impl(KBRef, __func__); +} + +bool DPCTLObjectKernelBundle_DeviceImageHasKernel( + __dpctl_keep const DPCTLSyclObjectKernelBundleRef KBRef, + size_t Index, + __dpctl_keep const DPCTLSyclKernelIdRef KIdRef, + __dpctl_keep const DPCTLSyclDeviceRef DRef) +{ + return device_image_has_kernel_impl( + KBRef, Index, KIdRef, DRef, __func__); +} + +__dpctl_give DPCTLSyclObjectKernelBundleRef DPCTLObjectKernelBundle_Join( + size_t NumKBRefs, + __dpctl_keep const DPCTLSyclObjectKernelBundleRef *KBRefs) +{ + return join_bundles_impl(NumKBRefs, KBRefs, __func__); +} + +__dpctl_give DPCTLSyclKernelBundleRef DPCTLObjectKernelBundle_Link( + size_t NumKBRefs, + __dpctl_keep const DPCTLSyclObjectKernelBundleRef *KBRefs, + __dpctl_keep const DPCTLDeviceVectorRef DVRef) +{ + try { + auto Bundles = unwrap_bundles(NumKBRefs, KBRefs); + if (DVRef) + return wrap_bundle( + sycl::link(Bundles, unwrap_devices(DVRef))); + return wrap_bundle(sycl::link(Bundles)); + } catch (std::exception const &e) { + error_handler(e, __FILE__, __func__, __LINE__); + return nullptr; + } +} + +bool DPCTLDeviceImage_HasKernel(__dpctl_keep const DPCTLSyclDeviceImageRef + ImgRef, + __dpctl_keep const DPCTLSyclKernelIdRef KIdRef, + __dpctl_keep const DPCTLSyclDeviceRef DRef) +{ + auto View = reinterpret_cast(ImgRef); + auto KId = unwrap(KIdRef); + if (!(View && KId)) { + error_handler("At least one of the inputs is nullptr", __FILE__, + __func__, __LINE__); + return false; + } + try { + return View->has_kernel(*KId, unwrap(DRef)); + } catch (std::exception const &e) { + error_handler(e, __FILE__, __func__, __LINE__); + return false; + } +} + +__dpctl_give DPCTLSyclKernelBundleRef +DPCTLKernelBundle_CreateFromContextWithSelector( + __dpctl_keep const DPCTLSyclContextRef CRef, + __dpctl_keep const DPCTLDeviceVectorRef DVRef, + DPCTLDeviceImageSelectorFn Selector, + void *UserData) +{ + return create_with_selector_impl( + CRef, DVRef, Selector, UserData, __func__); +} + +__dpctl_give DPCTLSyclInputKernelBundleRef +DPCTLInputKernelBundle_CreateFromContextWithSelector( + __dpctl_keep const DPCTLSyclContextRef CRef, + __dpctl_keep const DPCTLDeviceVectorRef DVRef, + DPCTLDeviceImageSelectorFn Selector, + void *UserData) +{ + return create_with_selector_impl(CRef, DVRef, Selector, + UserData, __func__); +} + +__dpctl_give DPCTLSyclObjectKernelBundleRef +DPCTLObjectKernelBundle_CreateFromContextWithSelector( + __dpctl_keep const DPCTLSyclContextRef CRef, + __dpctl_keep const DPCTLDeviceVectorRef DVRef, + DPCTLDeviceImageSelectorFn Selector, + void *UserData) +{ + return create_with_selector_impl( + CRef, DVRef, Selector, UserData, __func__); +} diff --git a/libsyclinterface/source/dpctl_sycl_kernel_interface.cpp b/libsyclinterface/source/dpctl_sycl_kernel_interface.cpp index e035ea7000..a83018a682 100644 --- a/libsyclinterface/source/dpctl_sycl_kernel_interface.cpp +++ b/libsyclinterface/source/dpctl_sycl_kernel_interface.cpp @@ -41,6 +41,34 @@ static_assert(__SYCL_COMPILER_VERSION >= __SYCL_COMPILER_VERSION_REQUIRED, "The compiler does not meet minimum version requirement"); using namespace dpctl::syclinterface; + +template +RetT get_device_specific_info(DPCTLSyclKernelRef KRef, + DPCTLSyclDeviceRef DRef, + const char *Fn) +{ + if (!KRef) { + error_handler("Input DPCTKSyclKernelRef is nullptr.", __FILE__, Fn, + __LINE__); + return 0; + } + auto sycl_kern = unwrap(KRef); + try { + if (DRef) + return static_cast( + sycl_kern->get_info(*unwrap(DRef))); + auto devs = sycl_kern->get_kernel_bundle().get_devices(); + if (devs.empty()) { + error_handler("Input DPCTKSyclKernelRef has no associated device.", + __FILE__, Fn, __LINE__); + return 0; + } + return static_cast(sycl_kern->get_info(devs[0])); + } catch (std::exception const &e) { + error_handler(e, __FILE__, Fn, __LINE__); + return 0; + } +} } // end of anonymous namespace size_t DPCTLKernel_GetNumArgs(__dpctl_keep const DPCTLSyclKernelRef KRef) @@ -53,8 +81,13 @@ size_t DPCTLKernel_GetNumArgs(__dpctl_keep const DPCTLSyclKernelRef KRef) } auto sycl_kernel = unwrap(KRef); - auto num_args = sycl_kernel->get_info(); - return static_cast(num_args); + try { + auto num_args = sycl_kernel->get_info(); + return static_cast(num_args); + } catch (std::exception const &e) { + error_handler(e, __FILE__, __func__, __LINE__); + return -1; + } } void DPCTLKernel_Delete(__dpctl_take DPCTLSyclKernelRef KRef) @@ -80,155 +113,63 @@ DPCTLKernel_Copy(__dpctl_keep const DPCTLSyclKernelRef KRef) } } -size_t DPCTLKernel_GetWorkGroupSize(__dpctl_keep const DPCTLSyclKernelRef KRef) +size_t DPCTLKernel_GetWorkGroupSize(__dpctl_keep const DPCTLSyclKernelRef KRef, + __dpctl_keep const DPCTLSyclDeviceRef DRef) { - if (!KRef) { - error_handler("Input DPCTKSyclKernelRef is nullptr.", __FILE__, - __func__, __LINE__); - return 0; - } - - auto sycl_kern = unwrap(KRef); - auto devs = sycl_kern->get_kernel_bundle().get_devices(); - if (devs.empty()) { - error_handler("Input DPCTKSyclKernelRef has no associated device.", - __FILE__, __func__, __LINE__); - return 0; - } - auto v = sycl_kern->get_info( - devs[0]); - return static_cast(v); + return get_device_specific_info< + info::kernel_device_specific::work_group_size, size_t>(KRef, DRef, + __func__); } size_t DPCTLKernel_GetPreferredWorkGroupSizeMultiple( - __dpctl_keep const DPCTLSyclKernelRef KRef) + __dpctl_keep const DPCTLSyclKernelRef KRef, + __dpctl_keep const DPCTLSyclDeviceRef DRef) { - if (!KRef) { - error_handler("Input DPCTKSyclKernelRef is nullptr.", __FILE__, - __func__, __LINE__); - return 0; - } - - auto sycl_kern = unwrap(KRef); - auto devs = sycl_kern->get_kernel_bundle().get_devices(); - if (devs.empty()) { - error_handler("Input DPCTKSyclKernelRef has no associated device.", - __FILE__, __func__, __LINE__); - return 0; - } - auto v = sycl_kern->get_info< - info::kernel_device_specific::preferred_work_group_size_multiple>( - devs[0]); - return static_cast(v); + return get_device_specific_info< + info::kernel_device_specific::preferred_work_group_size_multiple, + size_t>(KRef, DRef, __func__); } -size_t DPCTLKernel_GetPrivateMemSize(__dpctl_keep const DPCTLSyclKernelRef KRef) +size_t DPCTLKernel_GetPrivateMemSize(__dpctl_keep const DPCTLSyclKernelRef KRef, + __dpctl_keep const DPCTLSyclDeviceRef DRef) { - if (!KRef) { - error_handler("Input DPCTKSyclKernelRef is nullptr.", __FILE__, - __func__, __LINE__); - return 0; - } - - auto sycl_kern = unwrap(KRef); - auto devs = sycl_kern->get_kernel_bundle().get_devices(); - if (devs.empty()) { - error_handler("Input DPCTKSyclKernelRef has no associated device.", - __FILE__, __func__, __LINE__); - return 0; - } - auto v = - sycl_kern->get_info( - devs[0]); - return static_cast(v); + return get_device_specific_info< + info::kernel_device_specific::private_mem_size, size_t>(KRef, DRef, + __func__); } uint32_t -DPCTLKernel_GetMaxNumSubGroups(__dpctl_keep const DPCTLSyclKernelRef KRef) +DPCTLKernel_GetMaxNumSubGroups(__dpctl_keep const DPCTLSyclKernelRef KRef, + __dpctl_keep const DPCTLSyclDeviceRef DRef) { - if (!KRef) { - error_handler("Input DPCTKSyclKernelRef is nullptr.", __FILE__, - __func__, __LINE__); - return 0; - } - - auto sycl_kern = unwrap(KRef); - auto devs = sycl_kern->get_kernel_bundle().get_devices(); - if (devs.empty()) { - error_handler("Input DPCTKSyclKernelRef has no associated device.", - __FILE__, __func__, __LINE__); - return 0; - } - auto v = - sycl_kern->get_info( - devs[0]); - return static_cast(v); + return get_device_specific_info< + info::kernel_device_specific::max_num_sub_groups, uint32_t>(KRef, DRef, + __func__); } uint32_t -DPCTLKernel_GetMaxSubGroupSize(__dpctl_keep const DPCTLSyclKernelRef KRef) +DPCTLKernel_GetMaxSubGroupSize(__dpctl_keep const DPCTLSyclKernelRef KRef, + __dpctl_keep const DPCTLSyclDeviceRef DRef) { - if (!KRef) { - error_handler("Input DPCTKSyclKernelRef is nullptr.", __FILE__, - __func__, __LINE__); - return 0; - } - - auto sycl_kern = unwrap(KRef); - auto devs = sycl_kern->get_kernel_bundle().get_devices(); - if (devs.empty()) { - error_handler("Input DPCTKSyclKernelRef has no associated device.", - __FILE__, __func__, __LINE__); - return 0; - } - auto v = - sycl_kern->get_info( - devs[0]); - return v; + return get_device_specific_info< + info::kernel_device_specific::max_sub_group_size, uint32_t>(KRef, DRef, + __func__); } uint32_t -DPCTLKernel_GetCompileNumSubGroups(__dpctl_keep const DPCTLSyclKernelRef KRef) +DPCTLKernel_GetCompileNumSubGroups(__dpctl_keep const DPCTLSyclKernelRef KRef, + __dpctl_keep const DPCTLSyclDeviceRef DRef) { - if (!KRef) { - error_handler("Input DPCTKSyclKernelRef is nullptr.", __FILE__, - __func__, __LINE__); - return 0; - } - - auto sycl_kern = unwrap(KRef); - auto devs = sycl_kern->get_kernel_bundle().get_devices(); - if (devs.empty()) { - error_handler("Input DPCTKSyclKernelRef has no associated device.", - __FILE__, __func__, __LINE__); - return 0; - } - auto v = - sycl_kern - ->get_info( - devs[0]); - return static_cast(v); + return get_device_specific_info< + info::kernel_device_specific::compile_num_sub_groups, uint32_t>( + KRef, DRef, __func__); } uint32_t -DPCTLKernel_GetCompileSubGroupSize(__dpctl_keep const DPCTLSyclKernelRef KRef) +DPCTLKernel_GetCompileSubGroupSize(__dpctl_keep const DPCTLSyclKernelRef KRef, + __dpctl_keep const DPCTLSyclDeviceRef DRef) { - if (!KRef) { - error_handler("Input DPCTKSyclKernelRef is nullptr.", __FILE__, - __func__, __LINE__); - return 0; - } - - auto sycl_kern = unwrap(KRef); - auto devs = sycl_kern->get_kernel_bundle().get_devices(); - if (devs.empty()) { - error_handler("Input DPCTKSyclKernelRef has no associated device.", - __FILE__, __func__, __LINE__); - return 0; - } - auto v = - sycl_kern - ->get_info( - devs[0]); - return static_cast(v); + return get_device_specific_info< + info::kernel_device_specific::compile_sub_group_size, uint32_t>( + KRef, DRef, __func__); } diff --git a/libsyclinterface/tests/CMakeLists.txt b/libsyclinterface/tests/CMakeLists.txt index 9ef7717bc2..804edb49ba 100644 --- a/libsyclinterface/tests/CMakeLists.txt +++ b/libsyclinterface/tests/CMakeLists.txt @@ -29,6 +29,29 @@ file(GLOB_RECURSE sources ${CMAKE_CURRENT_SOURCE_DIR}/*.cpp ) +# Shared library with SYCL kernels loaded by the DPCTLKernelId_LoadLibrary tests +set(_kernel_library_source ${CMAKE_CURRENT_SOURCE_DIR}/test_kernel_library.cpp) +list(REMOVE_ITEM sources ${_kernel_library_source}) +add_library(dpctl_test_kernel_library SHARED EXCLUDE_FROM_ALL + ${_kernel_library_source} +) +add_sycl_to_target( + TARGET dpctl_test_kernel_library + SOURCES ${_kernel_library_source} +) +if(_dpctl_sycl_targets) + target_compile_options( + dpctl_test_kernel_library + PRIVATE + ${_dpctl_sycl_target_compile_options} + ) + target_link_options( + dpctl_test_kernel_library + PRIVATE + ${_dpctl_sycl_target_link_options} + ) +endif() + # Add all dpctl sources into a single executable so that we can run coverage # analysis and generate a report. add_executable(dpctl_c_api_tests @@ -51,6 +74,8 @@ add_sycl_to_target( ${CMAKE_CURRENT_SOURCE_DIR}/test_sycl_platform_interface.cpp ${CMAKE_CURRENT_SOURCE_DIR}/test_sycl_kernel_interface.cpp ${CMAKE_CURRENT_SOURCE_DIR}/test_sycl_kernel_bundle_interface.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/test_sycl_kernel_bundle_state_interface.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/test_sycl_kernel_library_interface.cpp ${CMAKE_CURRENT_SOURCE_DIR}/test_sycl_platform_invalid_filters.cpp ${CMAKE_CURRENT_SOURCE_DIR}/test_sycl_queue_manager.cpp ${CMAKE_CURRENT_SOURCE_DIR}/test_sycl_queue_submit.cpp @@ -83,6 +108,11 @@ target_link_libraries(dpctl_c_api_tests # Seems to work without it... ${CMAKE_DL_LIBS} ) +add_dependencies(dpctl_c_api_tests dpctl_test_kernel_library) +target_compile_definitions(dpctl_c_api_tests + PRIVATE + DPCTL_TEST_KERNEL_LIBRARY="$" +) target_include_directories(dpctl_c_api_tests PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/../helper/include" diff --git a/libsyclinterface/tests/test_kernel_library.cpp b/libsyclinterface/tests/test_kernel_library.cpp new file mode 100644 index 0000000000..f33d079e36 --- /dev/null +++ b/libsyclinterface/tests/test_kernel_library.cpp @@ -0,0 +1,39 @@ +//===-- test_kernel_library.cpp - Shared library with SYCL kernels for +// DPCTLKernelId_LoadLibrary tests -*-C++-*- ===// +// +// Data Parallel Control (dpctl) +// +// Copyright 2026 Intel Corporation +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//===----------------------------------------------------------------------===// +/// +/// \file +/// This file defines the kernels of the shared library loaded by the tests in +/// test_sycl_kernel_library_interface.cpp. +/// +//===----------------------------------------------------------------------===// + +#include + +namespace syclexp = sycl::ext::oneapi::experimental; + +extern "C" SYCL_EXT_ONEAPI_FUNCTION_PROPERTY( + (syclexp::nd_range_kernel<1>)) void dpctl_test_library_scale(int *a, + int factor) +{ + auto i = + sycl::ext::oneapi::this_work_item::get_nd_item<1>().get_global_id(0); + a[i] *= factor; +} diff --git a/libsyclinterface/tests/test_sycl_kernel_bundle_state_interface.cpp b/libsyclinterface/tests/test_sycl_kernel_bundle_state_interface.cpp new file mode 100644 index 0000000000..6e928ad837 --- /dev/null +++ b/libsyclinterface/tests/test_sycl_kernel_bundle_state_interface.cpp @@ -0,0 +1,455 @@ +//===-- test_sycl_kernel_bundle_state_interface.cpp - Test cases for kernel +// bundle states and kernel ids -*-C++-*- ===// +// +// Data Parallel Control (dpctl) +// +// Copyright 2026 Intel Corporation +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//===----------------------------------------------------------------------===// +/// +/// \file +/// This file has unit test cases for the kernel_id functions and the +/// kernel_bundle functions for the input, object and executable states in +/// dpctl_sycl_kernel_bundle_interface.h. +/// +//===----------------------------------------------------------------------===// + +#include "dpctl_service.h" +#include "dpctl_sycl_context_interface.h" +#include "dpctl_sycl_device_interface.h" +#include "dpctl_sycl_device_manager.h" +#include "dpctl_sycl_device_selector_interface.h" +#include "dpctl_sycl_kernel_bundle_interface.h" +#include "dpctl_sycl_kernel_interface.h" +#include "dpctl_utils.h" + +#include +#include +#include +#include + +class BundleStateTestKernelA; +class BundleStateTestKernelB; + +// Instantiates the kernels so that the test binary carries their device code. +void dpctl_test_bundle_state_kernels(sycl::queue &q, int *p) +{ + q.parallel_for( + sycl::range<1>(4), [=](sycl::id<1> i) { p[i] = static_cast(i); }); + q.single_task([=]() { p[0] += 1; }); +} + +namespace +{ + +DPCTLSyclKernelIdRef find_kernel_id(DPCTLKernelIdVectorRef KIdVRef, + const std::string &Name) +{ + size_t N = DPCTLKernelIdVector_Size(KIdVRef); + for (size_t i = 0; i < N; ++i) { + auto KIdRef = DPCTLKernelIdVector_GetAt(KIdVRef, i); + auto KIdName = DPCTLKernelId_GetName(KIdRef); + bool Found = (Name == KIdName); + DPCTLCString_Delete(KIdName); + if (Found) + return KIdRef; + DPCTLKernelId_Delete(KIdRef); + } + return nullptr; +} + +struct SelectorData +{ + DPCTLSyclKernelIdRef KId = nullptr; + bool Accept = true; + size_t Calls = 0; +}; + +bool select_images(DPCTLSyclDeviceImageRef ImgRef, void *UserData) +{ + auto Data = static_cast(UserData); + ++Data->Calls; + return Data->Accept && + DPCTLDeviceImage_HasKernel(ImgRef, Data->KId, nullptr); +} + +} // namespace + +struct TestKernelBundleState : public ::testing::TestWithParam +{ + DPCTLSyclDeviceRef DRef = nullptr; + DPCTLSyclContextRef CRef = nullptr; + DPCTLDeviceVectorRef DVRef = nullptr; + DPCTLKernelIdVectorRef AllKIds = nullptr; + DPCTLSyclKernelIdRef KIdA = nullptr; + DPCTLSyclKernelIdRef KIdB = nullptr; + + TestKernelBundleState() + { + auto DS = DPCTLFilterSelector_Create(GetParam()); + DRef = DPCTLDevice_CreateFromSelector(DS); + DPCTLDeviceSelector_Delete(DS); + if (!DRef) + return; + CRef = DPCTLContext_Create(DRef, nullptr, 0); + DVRef = DPCTLDeviceVector_CreateFromArray(1, &DRef); + AllKIds = DPCTLKernelId_GetAll(); + KIdA = find_kernel_id( + AllKIds, sycl::get_kernel_id().get_name()); + KIdB = find_kernel_id( + AllKIds, sycl::get_kernel_id().get_name()); + } + + void SetUp() + { + if (!DRef) { + auto message = "Skipping as no device of type " + + std::string(GetParam()) + "."; + GTEST_SKIP_(message.c_str()); + } + } + + ~TestKernelBundleState() + { + DPCTLKernelId_Delete(KIdA); + DPCTLKernelId_Delete(KIdB); + DPCTLKernelIdVector_Delete(AllKIds); + DPCTLDeviceVector_Delete(DVRef); + DPCTLContext_Delete(CRef); + DPCTLDevice_Delete(DRef); + } +}; + +TEST_P(TestKernelBundleState, ChkKernelIds) +{ + ASSERT_TRUE(AllKIds); + ASSERT_TRUE(KIdA); + ASSERT_TRUE(KIdB); + EXPECT_FALSE(DPCTLKernelId_AreEq(KIdA, KIdB)); + + auto KIdACopy = DPCTLKernelId_Copy(KIdA); + ASSERT_TRUE(KIdACopy); + EXPECT_TRUE(DPCTLKernelId_AreEq(KIdA, KIdACopy)); + EXPECT_EQ(DPCTLKernelId_Hash(KIdA), DPCTLKernelId_Hash(KIdACopy)); + DPCTLKernelId_Delete(KIdACopy); + + EXPECT_TRUE(DPCTLKernelId_IsCompatible(AllKIds, DRef)); +} + +TEST_P(TestKernelBundleState, ChkKernelIdNullArgs) +{ + EXPECT_EQ(DPCTLKernelId_GetName(nullptr), nullptr); + EXPECT_FALSE(DPCTLKernelId_AreEq(KIdA, nullptr)); + EXPECT_EQ(DPCTLKernelId_Hash(nullptr), 0u); + EXPECT_EQ(DPCTLKernelId_Copy(nullptr), nullptr); + EXPECT_FALSE(DPCTLKernelId_IsCompatible(nullptr, DRef)); + EXPECT_FALSE(DPCTLKernelId_IsCompatible(AllKIds, nullptr)); + EXPECT_NO_FATAL_FAILURE(DPCTLKernelId_Delete(nullptr)); +} + +TEST_P(TestKernelBundleState, ChkExecutableFromContext) +{ + ASSERT_TRUE(KIdA); + EXPECT_TRUE(DPCTLKernelBundle_CanCreateFromContext(CRef, DVRef, nullptr)); + auto KBRef = DPCTLKernelBundle_CreateFromContext(CRef, DVRef, nullptr); + ASSERT_TRUE(KBRef); + EXPECT_FALSE(DPCTLKernelBundle_IsEmpty(KBRef)); + EXPECT_TRUE(DPCTLKernelBundle_HasKernelId(KBRef, KIdA, nullptr)); + EXPECT_TRUE(DPCTLKernelBundle_HasKernelId(KBRef, KIdA, DRef)); + EXPECT_FALSE(DPCTLKernelBundle_ContainsSpecializationConstants(KBRef)); + EXPECT_EQ(DPCTLKernelBundle_GetBackend(KBRef), + DPCTLDevice_GetBackend(DRef)); + + auto Ctx = DPCTLKernelBundle_GetContext(KBRef); + ASSERT_TRUE(Ctx); + EXPECT_TRUE(DPCTLContext_AreEq(Ctx, CRef)); + DPCTLContext_Delete(Ctx); + + auto Devs = DPCTLKernelBundle_GetDevices(KBRef); + ASSERT_TRUE(Devs); + ASSERT_EQ(DPCTLDeviceVector_Size(Devs), 1u); + auto D = DPCTLDeviceVector_GetAt(Devs, 0); + EXPECT_TRUE(DPCTLDevice_AreEq(D, DRef)); + DPCTLDevice_Delete(D); + DPCTLDeviceVector_Delete(Devs); + + auto KIds = DPCTLKernelBundle_GetKernelIds(KBRef); + ASSERT_TRUE(KIds); + EXPECT_GE(DPCTLKernelIdVector_Size(KIds), 2u); + DPCTLKernelIdVector_Delete(KIds); + + size_t NumImages = DPCTLKernelBundle_GetNumDeviceImages(KBRef); + ASSERT_GE(NumImages, 1u); + bool InSomeImage = false; + for (size_t i = 0; i < NumImages; ++i) + InSomeImage |= + DPCTLKernelBundle_DeviceImageHasKernel(KBRef, i, KIdA, nullptr); + EXPECT_TRUE(InSomeImage); + EXPECT_FALSE( + DPCTLKernelBundle_DeviceImageHasKernel(KBRef, NumImages, KIdA, DRef)); + + auto KRef = DPCTLKernelBundle_GetKernelById(KBRef, KIdA); + ASSERT_TRUE(KRef); + EXPECT_GT(DPCTLKernel_GetWorkGroupSize(KRef, nullptr), 0u); + // num_args is only defined for interoperability and built-in kernels + EXPECT_EQ(DPCTLKernel_GetNumArgs(KRef), static_cast(-1)); + DPCTLKernel_Delete(KRef); + + DPCTLKernelBundle_Delete(KBRef); +} + +TEST_P(TestKernelBundleState, ChkFromContextWithKernelIds) +{ + ASSERT_TRUE(KIdA); + auto KIdVRef = DPCTLKernelIdVector_CreateFromArray(1, &KIdA); + auto KBRef = DPCTLKernelBundle_CreateFromContext(CRef, nullptr, KIdVRef); + ASSERT_TRUE(KBRef); + EXPECT_TRUE(DPCTLKernelBundle_HasKernelId(KBRef, KIdA, DRef)); + DPCTLKernelBundle_Delete(KBRef); + DPCTLKernelIdVector_Delete(KIdVRef); + + auto NoKIds = DPCTLKernelIdVector_Create(); + auto EmptyKB = DPCTLKernelBundle_CreateFromContext(CRef, DVRef, NoKIds); + ASSERT_TRUE(EmptyKB); + EXPECT_TRUE(DPCTLKernelBundle_IsEmpty(EmptyKB)); + EXPECT_EQ(DPCTLKernelBundle_GetNumDeviceImages(EmptyKB), 0u); + DPCTLKernelBundle_Delete(EmptyKB); + DPCTLKernelIdVector_Delete(NoKIds); +} + +TEST_P(TestKernelBundleState, ChkCompileLinkBuild) +{ + ASSERT_TRUE(KIdA); + EXPECT_TRUE( + DPCTLInputKernelBundle_CanCreateFromContext(CRef, DVRef, nullptr)); + auto InKB = DPCTLInputKernelBundle_CreateFromContext(CRef, DVRef, nullptr); + ASSERT_TRUE(InKB); + EXPECT_FALSE(DPCTLInputKernelBundle_IsEmpty(InKB)); + EXPECT_TRUE(DPCTLInputKernelBundle_HasKernelId(InKB, KIdA, DRef)); + EXPECT_GE(DPCTLInputKernelBundle_GetNumDeviceImages(InKB), 1u); + + auto ObjKB = DPCTLInputKernelBundle_Compile(InKB, nullptr); + ASSERT_TRUE(ObjKB); + EXPECT_TRUE(DPCTLObjectKernelBundle_HasKernelId(ObjKB, KIdA, nullptr)); + auto ObjCtx = DPCTLObjectKernelBundle_GetContext(ObjKB); + EXPECT_TRUE(DPCTLContext_AreEq(ObjCtx, CRef)); + DPCTLContext_Delete(ObjCtx); + + auto LinkedKB = DPCTLObjectKernelBundle_Link(1, &ObjKB, DVRef); + ASSERT_TRUE(LinkedKB); + auto KRef = DPCTLKernelBundle_GetKernelById(LinkedKB, KIdA); + EXPECT_TRUE(KRef); + DPCTLKernel_Delete(KRef); + + auto BuiltKB = DPCTLInputKernelBundle_Build(InKB, DVRef); + ASSERT_TRUE(BuiltKB); + EXPECT_TRUE(DPCTLKernelBundle_HasKernelId(BuiltKB, KIdB, DRef)); + + DPCTLKernelBundle_Delete(BuiltKB); + DPCTLKernelBundle_Delete(LinkedKB); + DPCTLObjectKernelBundle_Delete(ObjKB); + DPCTLInputKernelBundle_Delete(InKB); +} + +TEST_P(TestKernelBundleState, ChkObjectFromContext) +{ + ASSERT_TRUE(KIdB); + auto KIdVRef = DPCTLKernelIdVector_CreateFromArray(1, &KIdB); + EXPECT_TRUE( + DPCTLObjectKernelBundle_CanCreateFromContext(CRef, DVRef, KIdVRef)); + auto ObjKB = + DPCTLObjectKernelBundle_CreateFromContext(CRef, DVRef, KIdVRef); + ASSERT_TRUE(ObjKB); + EXPECT_TRUE(DPCTLObjectKernelBundle_HasKernelId(ObjKB, KIdB, DRef)); + EXPECT_EQ(DPCTLObjectKernelBundle_GetBackend(ObjKB), + DPCTLDevice_GetBackend(DRef)); + auto ExeKB = DPCTLObjectKernelBundle_Link(1, &ObjKB, nullptr); + ASSERT_TRUE(ExeKB); + EXPECT_TRUE(DPCTLKernelBundle_HasKernelId(ExeKB, KIdB, DRef)); + DPCTLKernelBundle_Delete(ExeKB); + DPCTLObjectKernelBundle_Delete(ObjKB); + DPCTLKernelIdVector_Delete(KIdVRef); +} + +TEST_P(TestKernelBundleState, ChkCopyAndJoin) +{ + auto InKB = DPCTLInputKernelBundle_CreateFromContext(CRef, DVRef, nullptr); + ASSERT_TRUE(InKB); + auto InCopy = DPCTLInputKernelBundle_Copy(InKB); + ASSERT_TRUE(InCopy); + DPCTLSyclInputKernelBundleRef InKBs[] = {InKB, InCopy}; + auto InJoined = DPCTLInputKernelBundle_Join(2, InKBs); + ASSERT_TRUE(InJoined); + EXPECT_FALSE(DPCTLInputKernelBundle_IsEmpty(InJoined)); + + auto ObjKB = DPCTLInputKernelBundle_Compile(InKB, DVRef); + ASSERT_TRUE(ObjKB); + auto ObjCopy = DPCTLObjectKernelBundle_Copy(ObjKB); + ASSERT_TRUE(ObjCopy); + DPCTLSyclObjectKernelBundleRef ObjKBs[] = {ObjKB, ObjCopy}; + auto ObjJoined = DPCTLObjectKernelBundle_Join(2, ObjKBs); + ASSERT_TRUE(ObjJoined); + EXPECT_FALSE(DPCTLObjectKernelBundle_IsEmpty(ObjJoined)); + + auto ExeA = DPCTLKernelBundle_CreateFromContext(CRef, DVRef, nullptr); + ASSERT_TRUE(ExeA); + auto ExeB = DPCTLKernelBundle_Copy(ExeA); + ASSERT_TRUE(ExeB); + DPCTLSyclKernelBundleRef ExeKBs[] = {ExeA, ExeB}; + auto ExeJoined = DPCTLKernelBundle_Join(2, ExeKBs); + ASSERT_TRUE(ExeJoined); + EXPECT_TRUE(DPCTLKernelBundle_HasKernelId(ExeJoined, KIdA, DRef)); + + DPCTLKernelBundle_Delete(ExeJoined); + DPCTLKernelBundle_Delete(ExeB); + DPCTLKernelBundle_Delete(ExeA); + DPCTLObjectKernelBundle_Delete(ObjJoined); + DPCTLObjectKernelBundle_Delete(ObjCopy); + DPCTLObjectKernelBundle_Delete(ObjKB); + DPCTLInputKernelBundle_Delete(InJoined); + DPCTLInputKernelBundle_Delete(InCopy); + DPCTLInputKernelBundle_Delete(InKB); +} + +TEST_P(TestKernelBundleState, ChkNullArgs) +{ + EXPECT_EQ(DPCTLKernelBundle_CreateFromContext(nullptr, DVRef, nullptr), + nullptr); + EXPECT_FALSE( + DPCTLInputKernelBundle_CanCreateFromContext(nullptr, nullptr, nullptr)); + EXPECT_EQ(DPCTLKernelBundle_Join(0, nullptr), nullptr); + EXPECT_EQ(DPCTLObjectKernelBundle_Link(0, nullptr, nullptr), nullptr); + DPCTLSyclObjectKernelBundleRef NullObj = nullptr; + EXPECT_EQ(DPCTLObjectKernelBundle_Link(1, &NullObj, nullptr), nullptr); + EXPECT_EQ(DPCTLInputKernelBundle_Compile(nullptr, DVRef), nullptr); + EXPECT_EQ(DPCTLInputKernelBundle_Build(nullptr, nullptr), nullptr); + EXPECT_EQ(DPCTLInputKernelBundle_Copy(nullptr), nullptr); + EXPECT_EQ(DPCTLObjectKernelBundle_GetContext(nullptr), nullptr); + EXPECT_EQ(DPCTLKernelBundle_GetDevices(nullptr), nullptr); + EXPECT_EQ(DPCTLKernelBundle_GetKernelIds(nullptr), nullptr); + EXPECT_EQ(DPCTLKernelBundle_GetBackend(nullptr), DPCTL_UNKNOWN_BACKEND); + EXPECT_FALSE(DPCTLKernelBundle_IsEmpty(nullptr)); + EXPECT_EQ(DPCTLKernelBundle_GetNumDeviceImages(nullptr), 0u); + EXPECT_EQ(DPCTLKernelBundle_GetKernelById(nullptr, KIdA), nullptr); + + auto KBRef = DPCTLKernelBundle_CreateFromContext(CRef, DVRef, nullptr); + ASSERT_TRUE(KBRef); + EXPECT_FALSE(DPCTLKernelBundle_HasKernelId(KBRef, nullptr, nullptr)); + EXPECT_FALSE( + DPCTLKernelBundle_DeviceImageHasKernel(KBRef, 0, nullptr, nullptr)); + EXPECT_EQ(DPCTLKernelBundle_GetKernelById(KBRef, nullptr), nullptr); + DPCTLKernelBundle_Delete(KBRef); + + EXPECT_NO_FATAL_FAILURE(DPCTLInputKernelBundle_Delete(nullptr)); + EXPECT_NO_FATAL_FAILURE(DPCTLObjectKernelBundle_Delete(nullptr)); +} + +TEST_P(TestKernelBundleState, ChkDeviceNotInContext) +{ + auto Devs = DPCTLDeviceMgr_GetDevices(DPCTLSyclDeviceType::DPCTL_ALL); + size_t N = DPCTLDeviceVector_Size(Devs); + DPCTLSyclDeviceRef Other = nullptr; + for (size_t i = 0; i < N && !Other; ++i) { + auto D = DPCTLDeviceVector_GetAt(Devs, i); + if (!DPCTLDevice_AreEq(D, DRef)) + Other = D; + else + DPCTLDevice_Delete(D); + } + DPCTLDeviceVector_Delete(Devs); + if (!Other) + GTEST_SKIP_("Needs a second device"); + auto OtherV = DPCTLDeviceVector_CreateFromArray(1, &Other); + EXPECT_EQ(DPCTLKernelBundle_CreateFromContext(CRef, OtherV, nullptr), + nullptr); + EXPECT_FALSE(DPCTLKernelBundle_CanCreateFromContext(CRef, OtherV, nullptr)); + DPCTLDeviceVector_Delete(OtherV); + DPCTLDevice_Delete(Other); +} + +TEST_P(TestKernelBundleState, ChkCreateWithSelector) +{ + ASSERT_TRUE(KIdA); + SelectorData Data; + Data.KId = KIdA; + + auto ExeKB = DPCTLKernelBundle_CreateFromContextWithSelector( + CRef, DVRef, select_images, &Data); + ASSERT_TRUE(ExeKB); + EXPECT_GE(Data.Calls, 1u); + EXPECT_TRUE(DPCTLKernelBundle_HasKernelId(ExeKB, KIdA, DRef)); + DPCTLKernelBundle_Delete(ExeKB); + + Data.Calls = 0; + auto InKB = DPCTLInputKernelBundle_CreateFromContextWithSelector( + CRef, nullptr, select_images, &Data); + ASSERT_TRUE(InKB); + EXPECT_GE(Data.Calls, 1u); + EXPECT_TRUE(DPCTLInputKernelBundle_HasKernelId(InKB, KIdA, DRef)); + DPCTLInputKernelBundle_Delete(InKB); + + Data.Accept = false; + auto ObjKB = DPCTLObjectKernelBundle_CreateFromContextWithSelector( + CRef, DVRef, select_images, &Data); + ASSERT_TRUE(ObjKB); + EXPECT_TRUE(DPCTLObjectKernelBundle_IsEmpty(ObjKB)); + DPCTLObjectKernelBundle_Delete(ObjKB); +} + +TEST_P(TestKernelBundleState, ChkCreateWithSelectorNullArgs) +{ + SelectorData Data; + EXPECT_EQ(DPCTLKernelBundle_CreateFromContextWithSelector(CRef, DVRef, + nullptr, &Data), + nullptr); + EXPECT_EQ(DPCTLInputKernelBundle_CreateFromContextWithSelector( + nullptr, DVRef, select_images, &Data), + nullptr); + EXPECT_EQ(Data.Calls, 0u); + EXPECT_FALSE(DPCTLDeviceImage_HasKernel(nullptr, KIdA, nullptr)); +} + +TEST_P(TestKernelBundleState, ChkKernelInfoWithDevice) +{ + ASSERT_TRUE(KIdA); + auto KBRef = DPCTLKernelBundle_CreateFromContext(CRef, DVRef, nullptr); + ASSERT_TRUE(KBRef); + auto KRef = DPCTLKernelBundle_GetKernelById(KBRef, KIdA); + ASSERT_TRUE(KRef); + EXPECT_EQ(DPCTLKernel_GetWorkGroupSize(KRef, DRef), + DPCTLKernel_GetWorkGroupSize(KRef, nullptr)); + EXPECT_EQ(DPCTLKernel_GetPreferredWorkGroupSizeMultiple(KRef, DRef), + DPCTLKernel_GetPreferredWorkGroupSizeMultiple(KRef, nullptr)); + EXPECT_EQ(DPCTLKernel_GetPrivateMemSize(KRef, DRef), + DPCTLKernel_GetPrivateMemSize(KRef, nullptr)); + EXPECT_EQ(DPCTLKernel_GetMaxNumSubGroups(KRef, DRef), + DPCTLKernel_GetMaxNumSubGroups(KRef, nullptr)); + EXPECT_EQ(DPCTLKernel_GetMaxSubGroupSize(KRef, DRef), + DPCTLKernel_GetMaxSubGroupSize(KRef, nullptr)); + EXPECT_EQ(DPCTLKernel_GetCompileNumSubGroups(KRef, DRef), + DPCTLKernel_GetCompileNumSubGroups(KRef, nullptr)); + EXPECT_EQ(DPCTLKernel_GetCompileSubGroupSize(KRef, DRef), + DPCTLKernel_GetCompileSubGroupSize(KRef, nullptr)); + EXPECT_GT(DPCTLKernel_GetWorkGroupSize(KRef, DRef), 0u); + EXPECT_EQ(DPCTLKernel_GetMaxSubGroupSize(nullptr, DRef), 0u); + DPCTLKernel_Delete(KRef); + DPCTLKernelBundle_Delete(KBRef); +} + +INSTANTIATE_TEST_SUITE_P(KernelBundleStates, + TestKernelBundleState, + ::testing::Values("opencl:gpu", + "opencl:cpu", + "level_zero:gpu")); diff --git a/libsyclinterface/tests/test_sycl_kernel_interface.cpp b/libsyclinterface/tests/test_sycl_kernel_interface.cpp index fba5e7a4d3..e1c755f84a 100644 --- a/libsyclinterface/tests/test_sycl_kernel_interface.cpp +++ b/libsyclinterface/tests/test_sycl_kernel_interface.cpp @@ -118,8 +118,10 @@ TEST_P(TestDPCTLSyclKernelInterface, CheckGetWorkGroupSize) { size_t add_wgsz = 0, axpy_wgsz = 0; - EXPECT_NO_FATAL_FAILURE(add_wgsz = DPCTLKernel_GetWorkGroupSize(AddKRef)); - EXPECT_NO_FATAL_FAILURE(axpy_wgsz = DPCTLKernel_GetWorkGroupSize(AxpyKRef)); + EXPECT_NO_FATAL_FAILURE(add_wgsz = + DPCTLKernel_GetWorkGroupSize(AddKRef, nullptr)); + EXPECT_NO_FATAL_FAILURE( + axpy_wgsz = DPCTLKernel_GetWorkGroupSize(AxpyKRef, nullptr)); ASSERT_TRUE(add_wgsz != 0); ASSERT_TRUE(axpy_wgsz != 0); @@ -130,9 +132,11 @@ TEST_P(TestDPCTLSyclKernelInterface, CheckGetPreferredWorkGroupSizeMultiple) size_t add_wgsz_m = 0, axpy_wgsz_m = 0; EXPECT_NO_FATAL_FAILURE( - add_wgsz_m = DPCTLKernel_GetPreferredWorkGroupSizeMultiple(AddKRef)); + add_wgsz_m = + DPCTLKernel_GetPreferredWorkGroupSizeMultiple(AddKRef, nullptr)); EXPECT_NO_FATAL_FAILURE( - axpy_wgsz_m = DPCTLKernel_GetPreferredWorkGroupSizeMultiple(AxpyKRef)); + axpy_wgsz_m = + DPCTLKernel_GetPreferredWorkGroupSizeMultiple(AxpyKRef, nullptr)); ASSERT_TRUE(add_wgsz_m != 0); ASSERT_TRUE(axpy_wgsz_m != 0); @@ -142,10 +146,10 @@ TEST_P(TestDPCTLSyclKernelInterface, CheckGetPrivateMemSize) { size_t add_private_mem_sz = 0, axpy_private_mem_sz = 0; - EXPECT_NO_FATAL_FAILURE(add_private_mem_sz = - DPCTLKernel_GetPrivateMemSize(AddKRef)); - EXPECT_NO_FATAL_FAILURE(axpy_private_mem_sz = - DPCTLKernel_GetPrivateMemSize(AxpyKRef)); + EXPECT_NO_FATAL_FAILURE( + add_private_mem_sz = DPCTLKernel_GetPrivateMemSize(AddKRef, nullptr)); + EXPECT_NO_FATAL_FAILURE( + axpy_private_mem_sz = DPCTLKernel_GetPrivateMemSize(AxpyKRef, nullptr)); ASSERT_TRUE(add_private_mem_sz >= 0); ASSERT_TRUE(axpy_private_mem_sz >= 0); @@ -155,9 +159,10 @@ TEST_P(TestDPCTLSyclKernelInterface, CheckGetMaxNumSubGroups) { uint32_t add_mnsg = 0, axpy_mnsg = 0; - EXPECT_NO_FATAL_FAILURE(add_mnsg = DPCTLKernel_GetMaxNumSubGroups(AddKRef)); - EXPECT_NO_FATAL_FAILURE(axpy_mnsg = - DPCTLKernel_GetMaxNumSubGroups(AxpyKRef)); + EXPECT_NO_FATAL_FAILURE( + add_mnsg = DPCTLKernel_GetMaxNumSubGroups(AddKRef, nullptr)); + EXPECT_NO_FATAL_FAILURE( + axpy_mnsg = DPCTLKernel_GetMaxNumSubGroups(AxpyKRef, nullptr)); ASSERT_TRUE(add_mnsg != 0); ASSERT_TRUE(axpy_mnsg != 0); @@ -167,10 +172,10 @@ TEST_P(TestDPCTLSyclKernelInterface, CheckGetMaxSubGroupSize) { uint32_t add_msg_sz = 0, axpy_msg_sz = 0; - EXPECT_NO_FATAL_FAILURE(add_msg_sz = - DPCTLKernel_GetMaxSubGroupSize(AddKRef)); - EXPECT_NO_FATAL_FAILURE(axpy_msg_sz = - DPCTLKernel_GetMaxSubGroupSize(AxpyKRef)); + EXPECT_NO_FATAL_FAILURE( + add_msg_sz = DPCTLKernel_GetMaxSubGroupSize(AddKRef, nullptr)); + EXPECT_NO_FATAL_FAILURE( + axpy_msg_sz = DPCTLKernel_GetMaxSubGroupSize(AxpyKRef, nullptr)); ASSERT_TRUE(add_msg_sz != 0); ASSERT_TRUE(axpy_msg_sz != 0); @@ -180,10 +185,10 @@ TEST_P(TestDPCTLSyclKernelInterface, CheckGetCompileNumSubGroups) { uint32_t add_cnsg = 0, axpy_cnsg = 0; - EXPECT_NO_FATAL_FAILURE(add_cnsg = - DPCTLKernel_GetCompileNumSubGroups(AddKRef)); - EXPECT_NO_FATAL_FAILURE(axpy_cnsg = - DPCTLKernel_GetCompileNumSubGroups(AxpyKRef)); + EXPECT_NO_FATAL_FAILURE( + add_cnsg = DPCTLKernel_GetCompileNumSubGroups(AddKRef, nullptr)); + EXPECT_NO_FATAL_FAILURE( + axpy_cnsg = DPCTLKernel_GetCompileNumSubGroups(AxpyKRef, nullptr)); EXPECT_TRUE(add_cnsg >= 0); EXPECT_TRUE(axpy_cnsg >= 0); @@ -193,10 +198,10 @@ TEST_P(TestDPCTLSyclKernelInterface, CheckGetCompileSubGroupSize) { uint32_t add_csg_sz = 0, axpy_csg_sz = 0; - EXPECT_NO_FATAL_FAILURE(add_csg_sz = - DPCTLKernel_GetCompileSubGroupSize(AddKRef)); - EXPECT_NO_FATAL_FAILURE(axpy_csg_sz = - DPCTLKernel_GetCompileSubGroupSize(AxpyKRef)); + EXPECT_NO_FATAL_FAILURE( + add_csg_sz = DPCTLKernel_GetCompileSubGroupSize(AddKRef, nullptr)); + EXPECT_NO_FATAL_FAILURE( + axpy_csg_sz = DPCTLKernel_GetCompileSubGroupSize(AxpyKRef, nullptr)); EXPECT_TRUE(add_csg_sz >= 0); EXPECT_TRUE(axpy_csg_sz >= 0); } @@ -226,7 +231,7 @@ TEST_F(TestDPCTLSyclKernelNullArgs, CheckGetWorkGroupsSizeNullKRef) { DPCTLSyclKernelRef NullKRef = nullptr; - ASSERT_EQ(DPCTLKernel_GetWorkGroupSize(NullKRef), 0); + ASSERT_EQ(DPCTLKernel_GetWorkGroupSize(NullKRef, nullptr), 0); } TEST_F(TestDPCTLSyclKernelNullArgs, @@ -234,40 +239,41 @@ TEST_F(TestDPCTLSyclKernelNullArgs, { DPCTLSyclKernelRef NullKRef = nullptr; - ASSERT_EQ(DPCTLKernel_GetPreferredWorkGroupSizeMultiple(NullKRef), 0); + ASSERT_EQ(DPCTLKernel_GetPreferredWorkGroupSizeMultiple(NullKRef, nullptr), + 0); } TEST_F(TestDPCTLSyclKernelNullArgs, CheckGetPrivateMemSizeNullKRef) { DPCTLSyclKernelRef NullKRef = nullptr; - ASSERT_EQ(DPCTLKernel_GetPrivateMemSize(NullKRef), 0); + ASSERT_EQ(DPCTLKernel_GetPrivateMemSize(NullKRef, nullptr), 0); } TEST_F(TestDPCTLSyclKernelNullArgs, CheckGetMaxNumSubGroupsNullKRef) { DPCTLSyclKernelRef NullKRef = nullptr; - ASSERT_EQ(DPCTLKernel_GetMaxNumSubGroups(NullKRef), 0); + ASSERT_EQ(DPCTLKernel_GetMaxNumSubGroups(NullKRef, nullptr), 0); } TEST_F(TestDPCTLSyclKernelNullArgs, CheckGetMaxSubGroupSizeNullKRef) { DPCTLSyclKernelRef NullKRef = nullptr; - ASSERT_EQ(DPCTLKernel_GetMaxSubGroupSize(NullKRef), 0); + ASSERT_EQ(DPCTLKernel_GetMaxSubGroupSize(NullKRef, nullptr), 0); } TEST_F(TestDPCTLSyclKernelNullArgs, CheckGetCompileNumSubGroupsNullKRef) { DPCTLSyclKernelRef NullKRef = nullptr; - ASSERT_EQ(DPCTLKernel_GetCompileNumSubGroups(NullKRef), 0); + ASSERT_EQ(DPCTLKernel_GetCompileNumSubGroups(NullKRef, nullptr), 0); } TEST_F(TestDPCTLSyclKernelNullArgs, CheckGetCompileSubGroupSizeNullKRef) { DPCTLSyclKernelRef NullKRef = nullptr; - ASSERT_EQ(DPCTLKernel_GetCompileSubGroupSize(NullKRef), 0); + ASSERT_EQ(DPCTLKernel_GetCompileSubGroupSize(NullKRef, nullptr), 0); } diff --git a/libsyclinterface/tests/test_sycl_kernel_library_interface.cpp b/libsyclinterface/tests/test_sycl_kernel_library_interface.cpp new file mode 100644 index 0000000000..b7e5203de2 --- /dev/null +++ b/libsyclinterface/tests/test_sycl_kernel_library_interface.cpp @@ -0,0 +1,162 @@ +//===-- test_sycl_kernel_library_interface.cpp - Test cases for +// DPCTLKernelId_LoadLibrary -*-C++-*- ===// +// +// Data Parallel Control (dpctl) +// +// Copyright 2026 Intel Corporation +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//===----------------------------------------------------------------------===// +/// +/// \file +/// This file has unit test cases for DPCTLKernelId_LoadLibrary, using the +/// shared library built from test_kernel_library.cpp. +/// +//===----------------------------------------------------------------------===// + +#include "dpctl_sycl_context_interface.h" +#include "dpctl_sycl_device_interface.h" +#include "dpctl_sycl_device_manager.h" +#include "dpctl_sycl_device_selector_interface.h" +#include "dpctl_sycl_event_interface.h" +#include "dpctl_sycl_kernel_bundle_interface.h" +#include "dpctl_sycl_kernel_interface.h" +#include "dpctl_sycl_queue_interface.h" +#include "dpctl_sycl_usm_interface.h" +#include "dpctl_utils.h" + +#include +#include +#include + +namespace +{ +const std::string ScaleKernelName = "__sycl_kernel_dpctl_test_library_scale"; + +DPCTLSyclKernelIdRef find_kernel_id(DPCTLKernelIdVectorRef KIdVRef, + const std::string &Name) +{ + size_t N = DPCTLKernelIdVector_Size(KIdVRef); + for (size_t i = 0; i < N; ++i) { + auto KIdRef = DPCTLKernelIdVector_GetAt(KIdVRef, i); + auto KIdName = DPCTLKernelId_GetName(KIdRef); + bool Found = (Name == KIdName); + DPCTLCString_Delete(KIdName); + if (Found) + return KIdRef; + DPCTLKernelId_Delete(KIdRef); + } + return nullptr; +} +} // namespace + +struct TestKernelLibrary : public ::testing::TestWithParam +{ + DPCTLSyclDeviceRef DRef = nullptr; + DPCTLSyclQueueRef QRef = nullptr; + + TestKernelLibrary() + { + auto DS = DPCTLFilterSelector_Create(GetParam()); + DRef = DPCTLDevice_CreateFromSelector(DS); + DPCTLDeviceSelector_Delete(DS); + if (DRef) + QRef = DPCTLQueue_CreateForDevice(DRef, nullptr, 0); + } + + void SetUp() + { + if (!QRef) { + auto message = "Skipping as no device of type " + + std::string(GetParam()) + "."; + GTEST_SKIP_(message.c_str()); + } + } + + ~TestKernelLibrary() + { + DPCTLQueue_Delete(QRef); + DPCTLDevice_Delete(DRef); + } +}; + +TEST_P(TestKernelLibrary, ChkLoadAndSubmit) +{ + auto KIds = DPCTLKernelId_LoadLibrary(DPCTL_TEST_KERNEL_LIBRARY); + ASSERT_TRUE(KIds); + auto KId = find_kernel_id(KIds, ScaleKernelName); + ASSERT_TRUE(KId); + + auto KIdsAgain = DPCTLKernelId_LoadLibrary(DPCTL_TEST_KERNEL_LIBRARY); + ASSERT_TRUE(KIdsAgain); + EXPECT_EQ(DPCTLKernelIdVector_Size(KIdsAgain), + DPCTLKernelIdVector_Size(KIds)); + DPCTLKernelIdVector_Delete(KIdsAgain); + + auto CRef = DPCTLQueue_GetContext(QRef); + auto DVRef = DPCTLDeviceVector_CreateFromArray(1, &DRef); + auto KBRef = DPCTLKernelBundle_CreateFromContext(CRef, DVRef, KIds); + ASSERT_TRUE(KBRef); + auto KRef = DPCTLKernelBundle_GetKernelById(KBRef, KId); + ASSERT_TRUE(KRef); + + constexpr size_t N = 16; + std::array Host; + for (size_t i = 0; i < N; ++i) + Host[i] = static_cast(i); + auto Data = DPCTLmalloc_device(N * sizeof(int), QRef); + ASSERT_TRUE(Data); + DPCTLEvent_Delete( + DPCTLQueue_Memcpy(QRef, Data, Host.data(), N * sizeof(int))); + DPCTLQueue_Wait(QRef); + + int Factor = 3; + void *Args[] = {Data, &Factor}; + DPCTLKernelArgType ArgTypes[] = {DPCTL_VOID_PTR, DPCTL_INT32_T}; + size_t GRange[] = {N, 1, 1}; + size_t LRange[] = {4, 1, 1}; + auto ERef = DPCTLQueue_SubmitNDRange(KRef, QRef, Args, ArgTypes, 2, GRange, + LRange, 1, nullptr, 0); + ASSERT_TRUE(ERef); + DPCTLEvent_Wait(ERef); + DPCTLEvent_Delete(ERef); + + std::array Result; + DPCTLEvent_Delete( + DPCTLQueue_Memcpy(QRef, Result.data(), Data, N * sizeof(int))); + DPCTLQueue_Wait(QRef); + for (size_t i = 0; i < N; ++i) + EXPECT_EQ(Result[i], 3 * static_cast(i)); + + DPCTLfree_with_queue(Data, QRef); + DPCTLKernel_Delete(KRef); + DPCTLKernelBundle_Delete(KBRef); + DPCTLDeviceVector_Delete(DVRef); + DPCTLContext_Delete(CRef); + DPCTLKernelId_Delete(KId); + DPCTLKernelIdVector_Delete(KIds); +} + +TEST_P(TestKernelLibrary, ChkLoadInvalid) +{ + EXPECT_EQ(DPCTLKernelId_LoadLibrary(nullptr), nullptr); + EXPECT_EQ(DPCTLKernelId_LoadLibrary("/nonexistent/libdpctl_nothing.so"), + nullptr); +} + +INSTANTIATE_TEST_SUITE_P(KernelLibrary, + TestKernelLibrary, + ::testing::Values("opencl:gpu", + "opencl:cpu", + "level_zero:gpu"));