diff --git a/CHANGELOG.md b/CHANGELOG.md index 91a5d08423..bd7698d890 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 * Added support for building `dpctl` with AdaptiveCpp as the SYCL implementation, selected with `--sycl-provider=AdaptiveCpp` in `scripts/build_locally.py` or `-DDPCTL_SYCL_PROVIDER=AdaptiveCpp` [gh-2384](https://github.com/IntelPython/dpctl/pull/2384) * Added `dpctl.backend_type.openmp` for the AdaptiveCpp OpenMP host device [gh-2384](https://github.com/IntelPython/dpctl/pull/2384) * Added `DPCTLService_GetSyclProvider` C-API function and `dpctl._diagnostics.sycl_provider`, which report the SYCL implementation `dpctl` was built with [gh-2384](https://github.com/IntelPython/dpctl/pull/2384) +* Added 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.SyclInputKernelBundle`, `SyclObjectKernelBundle`, `SyclKernelId` and `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 and the `SyclInputKernelBundle_*`, `SyclObjectKernelBundle_*` and `SyclKernelId_*` Cython C-API functions [gh-2440](https://github.com/IntelPython/dpctl/pull/2440) +* Added the `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 [gh-2440](https://github.com/IntelPython/dpctl/pull/2440) +* Added `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 [gh-2440](https://github.com/IntelPython/dpctl/pull/2440) +* Added `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` [gh-2440](https://github.com/IntelPython/dpctl/pull/2440) +* Added `dpctl.compiler.SyclKernel.get_work_group_size`, `get_preferred_work_group_size_multiple`, `get_private_mem_size`, `get_max_num_sub_groups`, `get_max_sub_group_size`, `get_compile_num_sub_groups` and `get_compile_sub_group_size`, which take an optional device of the kernel bundle and raise `ValueError` for another device, and the `DPCTLKernel_Get*ForDevice` and `DPCTLKernel_GetDevices` C-API functions [gh-2440](https://github.com/IntelPython/dpctl/pull/2440) +* Added the `DPCTLKernelBundle_CreateFromOCLSourceWithBuildLog` and `DPCTLKernelBundle_CreateFromSpirvWithBuildLog` C-API functions, which return the build log of a failed build [gh-2440](https://github.com/IntelPython/dpctl/pull/2440) ### 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) @@ -25,10 +31,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 * `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) * Pickled `dpctl.memory.MemoryUSMShared`, `MemoryUSMDevice`, and `MemoryUSMHost` objects keep their queue instead of being restored on the default device. Pickling memory whose queue can not be pickled raises `pickle.PicklingError` [gh-2406](https://github.com/IntelPython/dpctl/pull/2406) * NumPy is no longer a build dependency of `dpctl`, only a run-time dependency [gh-2436](https://github.com/IntelPython/dpctl/pull/2436) +* The `dpctl.compiler.SyclKernelBundleCompilationError` raised by `dpctl.compiler.create_kernel_bundle_from_source` and `create_kernel_bundle_from_spirv` contains the build log when the program could not be built [gh-2440](https://github.com/IntelPython/dpctl/pull/2440) ### 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) +* Deprecated 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` in favor of the `get_*` methods of the same name; they emit a `DeprecationWarning` [gh-2440](https://github.com/IntelPython/dpctl/pull/2440) ### Removed * Removed the deprecated `dpctl.program` submodule, use `dpctl.compiler` instead [gh-2407](https://github.com/IntelPython/dpctl/pull/2407) @@ -43,6 +51,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 * `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) * Building with the open source DPC++ toolchain no longer requires the toolchain to bundle the OpenCL ICD loader, which `dpctl` loads at run time [gh-2435](https://github.com/IntelPython/dpctl/pull/2435) +* `DPCTLKernel_Get*` device-specific queries return 0 instead of terminating the process when the SYCL runtime throws [gh-2440](https://github.com/IntelPython/dpctl/pull/2440) ### 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..3c45c749f1 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,30 @@ 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 + SyclInputKernelBundle + SyclObjectKernelBundle SyclKernel + SyclKernelId + SyclDeviceImage SpecializationConstant .. autosummary:: diff --git a/docs/doc_sources/api_reference/dpctl_capi.rst b/docs/doc_sources/api_reference/dpctl_capi.rst index 8458d0841b..535025b73f 100644 --- a/docs/doc_sources/api_reference/dpctl_capi.rst +++ b/docs/doc_sources/api_reference/dpctl_capi.rst @@ -37,6 +37,18 @@ Exported typedefs .. c:struct:: PySyclKernelBundleType +.. c:struct:: PySyclInputKernelBundleObject + +.. c:struct:: PySyclInputKernelBundleType + +.. c:struct:: PySyclObjectKernelBundleObject + +.. c:struct:: PySyclObjectKernelBundleType + +.. c:struct:: PySyclKernelIdObject + +.. c:struct:: PySyclKernelIdType + To check whether a particular Python object is an instance of :py:class:`dpctl.SyclQueue`: .. code-block:: C @@ -211,3 +223,57 @@ API for :c:struct:`PySyclKernelBundleObject` Note that function does not change the ownership of the ``KBRef`` instance and the caller remains responsible for freeing ``KBRef`` as appropriate. + + +API for :c:struct:`PySyclInputKernelBundleObject` +------------------------------------------------- + +.. c:function:: DPCTLSyclInputKernelBundleRef SyclInputKernelBundle_GetKernelBundleRef(struct PySyclInputKernelBundleObject *kb) + + :param kb: Input object + :returns: borrowed instance of :c:struct:`DPCTLSyclInputKernelBundleRef` corresponding + to ``sycl::kernel_bundle`` + +.. c:function:: struct PySyclInputKernelBundleObject * SyclInputKernelBundle_Make(DPCTLSyclInputKernelBundleRef KBRef) + + :param KBRef: instance of :c:struct:`DPCTLSyclInputKernelBundleRef` + :returns: new Python object of type :c:struct:`PySyclInputKernelBundleType` + + Note that function does not change the ownership of the ``KBRef`` instance and + the caller remains responsible for freeing ``KBRef`` as appropriate. + + +API for :c:struct:`PySyclObjectKernelBundleObject` +-------------------------------------------------- + +.. c:function:: DPCTLSyclObjectKernelBundleRef SyclObjectKernelBundle_GetKernelBundleRef(struct PySyclObjectKernelBundleObject *kb) + + :param kb: Input object + :returns: borrowed instance of :c:struct:`DPCTLSyclObjectKernelBundleRef` corresponding + to ``sycl::kernel_bundle`` + +.. c:function:: struct PySyclObjectKernelBundleObject * SyclObjectKernelBundle_Make(DPCTLSyclObjectKernelBundleRef KBRef) + + :param KBRef: instance of :c:struct:`DPCTLSyclObjectKernelBundleRef` + :returns: new Python object of type :c:struct:`PySyclObjectKernelBundleType` + + Note that function does not change the ownership of the ``KBRef`` instance and + the caller remains responsible for freeing ``KBRef`` as appropriate. + + +API for :c:struct:`PySyclKernelIdObject` +---------------------------------------- + +.. c:function:: DPCTLSyclKernelIdRef SyclKernelId_GetKernelIdRef(struct PySyclKernelIdObject *kid) + + :param kid: Input object + :returns: borrowed instance of :c:struct:`DPCTLSyclKernelIdRef` corresponding + to ``sycl::kernel_id`` + +.. c:function:: struct PySyclKernelIdObject * SyclKernelId_Make(DPCTLSyclKernelIdRef KIdRef) + + :param KIdRef: instance of :c:struct:`DPCTLSyclKernelIdRef` + :returns: new Python object of type :c:struct:`PySyclKernelIdType` + + Note that function does not change the ownership of the ``KIdRef`` instance and + the caller remains responsible for freeing ``KIdRef`` as appropriate. diff --git a/dpctl/_backend.pxd b/dpctl/_backend.pxd index ef80c03039..d0a99cb495 100644 --- a/dpctl/_backend.pxd +++ b/dpctl/_backend.pxd @@ -182,6 +182,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 @@ -192,6 +196,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 @@ -440,19 +448,39 @@ 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 DPCTLDeviceVectorRef DPCTLKernel_GetDevices( + const DPCTLSyclKernelRef KRef) cdef size_t DPCTLKernel_GetWorkGroupSize(const DPCTLSyclKernelRef KRef) + cdef size_t DPCTLKernel_GetWorkGroupSizeForDevice( + const DPCTLSyclKernelRef KRef, + const DPCTLSyclDeviceRef DRef) cdef size_t DPCTLKernel_GetPreferredWorkGroupSizeMultiple( - const DPCTLSyclKernelRef KRef - ) + const DPCTLSyclKernelRef KRef) + cdef size_t DPCTLKernel_GetPreferredWorkGroupSizeMultipleForDevice( + const DPCTLSyclKernelRef KRef, + const DPCTLSyclDeviceRef DRef) cdef size_t DPCTLKernel_GetPrivateMemSize(const DPCTLSyclKernelRef KRef) + cdef size_t DPCTLKernel_GetPrivateMemSizeForDevice( + const DPCTLSyclKernelRef KRef, + const DPCTLSyclDeviceRef DRef) cdef uint32_t DPCTLKernel_GetMaxNumSubGroups(const DPCTLSyclKernelRef KRef) + cdef uint32_t DPCTLKernel_GetMaxNumSubGroupsForDevice( + const DPCTLSyclKernelRef KRef, + const DPCTLSyclDeviceRef DRef) cdef uint32_t DPCTLKernel_GetMaxSubGroupSize(const DPCTLSyclKernelRef KRef) + cdef uint32_t DPCTLKernel_GetMaxSubGroupSizeForDevice( + const DPCTLSyclKernelRef KRef, + const DPCTLSyclDeviceRef DRef) cdef uint32_t DPCTLKernel_GetCompileNumSubGroups( - const DPCTLSyclKernelRef KRef - ) + const DPCTLSyclKernelRef KRef) + cdef uint32_t DPCTLKernel_GetCompileNumSubGroupsForDevice( + const DPCTLSyclKernelRef KRef, + const DPCTLSyclDeviceRef DRef) cdef uint32_t DPCTLKernel_GetCompileSubGroupSize( - const DPCTLSyclKernelRef KRef - ) + const DPCTLSyclKernelRef KRef) + cdef uint32_t DPCTLKernel_GetCompileSubGroupSizeForDevice( + const DPCTLSyclKernelRef KRef, + const DPCTLSyclDeviceRef DRef) cdef extern from "syclinterface/dpctl_sycl_platform_manager.h": @@ -559,6 +587,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 @@ -588,6 +795,24 @@ cdef extern from "syclinterface/dpctl_sycl_kernel_bundle_interface.h": cdef void DPCTLKernelBuildLog_Delete(DPCTLKernelBuildLogRef Ref) cdef const char *DPCTLKernelBuildLog_Get(DPCTLKernelBuildLogRef) + cdef DPCTLSyclKernelBundleRef \ + DPCTLKernelBundle_CreateFromSpirvWithBuildLog( + const DPCTLSyclContextRef Ctx, + const DPCTLSyclDeviceRef Dev, + const void *IL, + size_t Length, + const char *CompileOpts, + size_t NumSpecConsts, + const _spec_const *SpecConsts, + DPCTLKernelBuildLogRef BuildLog) + cdef DPCTLSyclKernelBundleRef \ + DPCTLKernelBundle_CreateFromOCLSourceWithBuildLog( + const DPCTLSyclContextRef Ctx, + const DPCTLSyclDeviceRef Dev, + const char *Source, + const char *CompileOpts, + DPCTLKernelBuildLogRef BuildLog) + cdef bool DPCTLKernelBundle_CreateFromSYCLSource_Available() cdef DPCTLSyclKernelBundleRef DPCTLKernelBundle_CreateFromSYCLSource( diff --git a/dpctl/apis/include/dpctl4pybind11.hpp b/dpctl/apis/include/dpctl4pybind11.hpp index 945ec6e929..b972096d3a 100644 --- a/dpctl/apis/include/dpctl4pybind11.hpp +++ b/dpctl/apis/include/dpctl4pybind11.hpp @@ -81,7 +81,10 @@ class dpctl_capi PyTypeObject *PyMemoryUSMSharedType_; PyTypeObject *PyMemoryUSMHostType_; PyTypeObject *PySyclKernelBundleType_; + PyTypeObject *PySyclInputKernelBundleType_; + PyTypeObject *PySyclObjectKernelBundleType_; PyTypeObject *PySyclKernelType_; + PyTypeObject *PySyclKernelIdType_; DPCTLSyclDeviceRef (*SyclDevice_GetDeviceRef_)(PySyclDeviceObject *); PySyclDeviceObject *(*SyclDevice_Make_)(DPCTLSyclDeviceRef); @@ -120,6 +123,19 @@ class dpctl_capi PySyclKernelBundleObject *); PySyclKernelBundleObject *(*SyclKernelBundle_Make_)( DPCTLSyclKernelBundleRef); + DPCTLSyclInputKernelBundleRef (*SyclInputKernelBundle_GetKernelBundleRef_)( + PySyclInputKernelBundleObject *); + PySyclInputKernelBundleObject *(*SyclInputKernelBundle_Make_)( + DPCTLSyclInputKernelBundleRef); + DPCTLSyclObjectKernelBundleRef ( + *SyclObjectKernelBundle_GetKernelBundleRef_)( + PySyclObjectKernelBundleObject *); + PySyclObjectKernelBundleObject *(*SyclObjectKernelBundle_Make_)( + DPCTLSyclObjectKernelBundleRef); + + DPCTLSyclKernelIdRef (*SyclKernelId_GetKernelIdRef_)( + PySyclKernelIdObject *); + PySyclKernelIdObject *(*SyclKernelId_Make_)(DPCTLSyclKernelIdRef); bool PySyclDevice_Check_(PyObject *obj) const { @@ -145,6 +161,18 @@ class dpctl_capi { return PyObject_TypeCheck(obj, PySyclKernelBundleType_) != 0; } + bool PySyclInputKernelBundle_Check_(PyObject *obj) const + { + return PyObject_TypeCheck(obj, PySyclInputKernelBundleType_) != 0; + } + bool PySyclObjectKernelBundle_Check_(PyObject *obj) const + { + return PyObject_TypeCheck(obj, PySyclObjectKernelBundleType_) != 0; + } + bool PySyclKernelId_Check_(PyObject *obj) const + { + return PyObject_TypeCheck(obj, PySyclKernelIdType_) != 0; + } ~dpctl_capi() { @@ -214,19 +242,26 @@ class dpctl_capi Py_SyclQueueType_(nullptr), PySyclQueueType_(nullptr), 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), + PySyclKernelBundleType_(nullptr), + PySyclInputKernelBundleType_(nullptr), + PySyclObjectKernelBundleType_(nullptr), PySyclKernelType_(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), + SyclInputKernelBundle_GetKernelBundleRef_(nullptr), + SyclInputKernelBundle_Make_(nullptr), + SyclObjectKernelBundle_GetKernelBundleRef_(nullptr), + SyclObjectKernelBundle_Make_(nullptr), + SyclKernelId_GetKernelIdRef_(nullptr), SyclKernelId_Make_(nullptr), + default_sycl_queue_{}, default_usm_memory_{}, as_usm_memory_{} { // Import Cython-generated C-API for dpctl @@ -252,7 +287,10 @@ class dpctl_capi this->PyMemoryUSMSharedType_ = &PyMemoryUSMSharedType; this->PyMemoryUSMHostType_ = &PyMemoryUSMHostType; this->PySyclKernelBundleType_ = &PySyclKernelBundleType; + this->PySyclInputKernelBundleType_ = &PySyclInputKernelBundleType; + this->PySyclObjectKernelBundleType_ = &PySyclObjectKernelBundleType; this->PySyclKernelType_ = &PySyclKernelType; + this->PySyclKernelIdType_ = &PySyclKernelIdType; // SyclDevice API this->SyclDevice_GetDeviceRef_ = SyclDevice_GetDeviceRef; @@ -285,6 +323,14 @@ class dpctl_capi this->SyclKernelBundle_GetKernelBundleRef_ = SyclKernelBundle_GetKernelBundleRef; this->SyclKernelBundle_Make_ = SyclKernelBundle_Make; + this->SyclInputKernelBundle_GetKernelBundleRef_ = + SyclInputKernelBundle_GetKernelBundleRef; + this->SyclInputKernelBundle_Make_ = SyclInputKernelBundle_Make; + this->SyclObjectKernelBundle_GetKernelBundleRef_ = + SyclObjectKernelBundle_GetKernelBundleRef; + this->SyclObjectKernelBundle_Make_ = SyclObjectKernelBundle_Make; + 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 @@ -556,6 +602,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 +633,125 @@ struct type_caster> DPCTL_TYPE_CASTER(sycl::kernel_bundle, _("dpctl.compiler.SyclKernelBundle")); }; + +/* This type caster associates + * ``sycl::kernel_bundle`` C++ class with + * :class:`dpctl.compiler.SyclInputKernelBundle` 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.PySyclInputKernelBundle_Check_(source)) { + DPCTLSyclInputKernelBundleRef KBRef = + api.SyclInputKernelBundle_GetKernelBundleRef_( + reinterpret_cast(source)); + 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.SyclInputKernelBundle"); + } + } + + static handle cast(sycl::kernel_bundle src, + return_value_policy, + handle) + { + auto const &api = ::dpctl::detail::dpctl_capi::get(); + auto tmp = api.SyclInputKernelBundle_Make_( + reinterpret_cast(&src)); + return handle(reinterpret_cast(tmp)); + } + + DPCTL_TYPE_CASTER(sycl::kernel_bundle, + _("dpctl.compiler.SyclInputKernelBundle")); +}; + +/* This type caster associates + * ``sycl::kernel_bundle`` C++ class with + * :class:`dpctl.compiler.SyclObjectKernelBundle` 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.PySyclObjectKernelBundle_Check_(source)) { + DPCTLSyclObjectKernelBundleRef KBRef = + api.SyclObjectKernelBundle_GetKernelBundleRef_( + reinterpret_cast(source)); + 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.SyclObjectKernelBundle"); + } + } + + static handle cast(sycl::kernel_bundle src, + return_value_policy, + handle) + { + auto const &api = ::dpctl::detail::dpctl_capi::get(); + auto tmp = api.SyclObjectKernelBundle_Make_( + reinterpret_cast(&src)); + return handle(reinterpret_cast(tmp)); + } + + DPCTL_TYPE_CASTER(sycl::kernel_bundle, + _("dpctl.compiler.SyclObjectKernelBundle")); +}; + +/* 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")); +}; #endif /* This type caster associates diff --git a/dpctl/compiler/__init__.py b/dpctl/compiler/__init__.py index e54e30f6a5..d884fd2853 100644 --- a/dpctl/compiler/__init__.py +++ b/dpctl/compiler/__init__.py @@ -17,31 +17,58 @@ """ **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, + SyclInputKernelBundle, SyclKernel, SyclKernelBundle, SyclKernelBundleCompilationError, + SyclKernelId, + SyclObjectKernelBundle, + 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", + "SyclInputKernelBundle", "SyclKernel", "SyclKernelBundle", "SyclKernelBundleCompilationError", + "SyclKernelId", + "SyclObjectKernelBundle", "SpecializationConstant", ] diff --git a/dpctl/compiler/_compiler.pxd b/dpctl/compiler/_compiler.pxd index 3958a2f83e..723289373a 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,7 +47,28 @@ cdef api class SyclKernel [object PySyclKernelObject, type PySyclKernelType]: cdef SyclKernel _create (DPCTLSyclKernelRef kref, str name) -cdef api class SyclKernelBundle [ +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 _SyclKernelBundleBase [ + object PySyclKernelBundleBaseObject, type PySyclKernelBundleBaseType +]: + """ Base class of the kernel bundle classes. Has no fields, so that + SyclKernelBundle keeps its layout. + """ + pass + + +cdef api class SyclKernelBundle(_SyclKernelBundleBase) [ object PySyclKernelBundleObject, type PySyclKernelBundleType ]: """ @@ -61,12 +89,45 @@ cdef api class SyclKernelBundle [ cpdef SyclKernel get_sycl_kernel(self, str kernel_name) +cdef api class SyclInputKernelBundle(_SyclKernelBundleBase) [ + object PySyclInputKernelBundleObject, type PySyclInputKernelBundleType +]: + """ Wraps a sycl::kernel_bundle object. + """ + cdef DPCTLSyclInputKernelBundleRef _kernel_bundle_ref + + @staticmethod + cdef SyclInputKernelBundle _create (DPCTLSyclInputKernelBundleRef kbref) + cdef DPCTLSyclInputKernelBundleRef get_kernel_bundle_ref (self) + + +cdef api class SyclObjectKernelBundle(_SyclKernelBundleBase) [ + object PySyclObjectKernelBundleObject, type PySyclObjectKernelBundleType +]: + """ Wraps a sycl::kernel_bundle object. + """ + cdef DPCTLSyclObjectKernelBundleRef _kernel_bundle_ref + + @staticmethod + cdef SyclObjectKernelBundle _create (DPCTLSyclObjectKernelBundleRef kbref) + cdef DPCTLSyclObjectKernelBundleRef get_kernel_bundle_ref (self) + + +cdef class SyclDeviceImage: + """ A device image of a :class:`SyclKernelBundle`. + """ + cdef _SyclKernelBundleBase _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 +138,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 e91662329c..1550e4160c 100644 --- a/dpctl/compiler/_compiler.pyx +++ b/dpctl/compiler/_compiler.pyx @@ -39,69 +39,172 @@ 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, + DPCTLDevice_AreEq, + DPCTLDevice_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, + DPCTLKernel_GetCompileNumSubGroupsForDevice, DPCTLKernel_GetCompileSubGroupSize, + DPCTLKernel_GetCompileSubGroupSizeForDevice, + DPCTLKernel_GetDevices, DPCTLKernel_GetMaxNumSubGroups, + DPCTLKernel_GetMaxNumSubGroupsForDevice, DPCTLKernel_GetMaxSubGroupSize, + DPCTLKernel_GetMaxSubGroupSizeForDevice, DPCTLKernel_GetNumArgs, DPCTLKernel_GetPreferredWorkGroupSizeMultiple, + DPCTLKernel_GetPreferredWorkGroupSizeMultipleForDevice, DPCTLKernel_GetPrivateMemSize, + DPCTLKernel_GetPrivateMemSizeForDevice, DPCTLKernel_GetWorkGroupSize, + DPCTLKernel_GetWorkGroupSizeForDevice, DPCTLKernelBuildLog_Create, DPCTLKernelBuildLog_Delete, DPCTLKernelBuildLog_Get, DPCTLKernelBuildLogRef, + DPCTLKernelBundle_CanCreateFromContext, + DPCTLKernelBundle_ContainsSpecializationConstants, DPCTLKernelBundle_Copy, - DPCTLKernelBundle_CreateFromOCLSource, - DPCTLKernelBundle_CreateFromSpirv, + DPCTLKernelBundle_CreateFromContext, + DPCTLKernelBundle_CreateFromContextWithSelector, + DPCTLKernelBundle_CreateFromOCLSourceWithBuildLog, + DPCTLKernelBundle_CreateFromSpirvWithBuildLog, 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 warnings 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", + "SyclInputKernelBundle", "SyclKernel", "SyclKernelBundle", "SyclKernelBundleCompilationError", + "SyclKernelId", + "SyclObjectKernelBundle", "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 +220,141 @@ 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() + try: + for i in range(len(kernel_ids)): + KIdRefs[i] = _kernel_id_ref(kernel_ids[i]) + except BaseException: + free(KIdRefs) + raise + KIdVRef = DPCTLKernelIdVector_CreateFromArray(len(kernel_ids), KIdRefs) + free(KIdRefs) + if KIdVRef is NULL: + raise MemoryError() + return KIdVRef + + +cdef DPCTLSyclKernelIdRef _kernel_id_ref(SyclKernelId kid) except NULL: + cdef DPCTLSyclKernelIdRef KIdRef = kid.get_kernel_id_ref() + if KIdRef is NULL: + raise ValueError("The SyclKernelId object wraps no kernel id") + return KIdRef + + +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: """ """ @@ -175,61 +413,312 @@ cdef class SyclKernel: """ return self.get_num_args() + def get_work_group_size(self, SyclDevice device=None): + """get_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. + + Raises: + ValueError: + If ``device`` is not a device of the kernel bundle. + """ + cdef size_t v + if device is None: + v = DPCTLKernel_GetWorkGroupSize(self._kernel_ref) + else: + _check_kernel_device(self, device) + v = DPCTLKernel_GetWorkGroupSizeForDevice( + self._kernel_ref, device.get_device_ref() + ) + return v + @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. + """ Property equivalent to method call + `SyclKernel.get_work_group_size()`. + + .. deprecated:: 0.24.0 + Use :meth:`.get_work_group_size` instead. + """ + warnings.warn( + "dpctl.compiler.SyclKernel.work_group_size is deprecated, " + "use get_work_group_size() instead", + DeprecationWarning, + ) + return self.get_work_group_size() + + def get_preferred_work_group_size_multiple(self, SyclDevice device=None): + """get_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. + + Raises: + ValueError: + If ``device`` is not a device of the kernel bundle. """ - cdef size_t v = DPCTLKernel_GetWorkGroupSize(self._kernel_ref) + cdef size_t v + if device is None: + v = DPCTLKernel_GetPreferredWorkGroupSizeMultiple(self._kernel_ref) + else: + _check_kernel_device(self, device) + v = DPCTLKernel_GetPreferredWorkGroupSizeMultipleForDevice( + self._kernel_ref, device.get_device_ref() + ) 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. + """ Property equivalent to method call + `SyclKernel.get_preferred_work_group_size_multiple()`. + + .. deprecated:: 0.24.0 + Use :meth:`.get_preferred_work_group_size_multiple` instead. """ - cdef size_t v = DPCTLKernel_GetPreferredWorkGroupSizeMultiple( - self._kernel_ref + warnings.warn( + "dpctl.compiler.SyclKernel.preferred_work_group_size_multiple " + "is deprecated, use get_preferred_work_group_size_multiple() " + "instead", + DeprecationWarning, ) + return self.get_preferred_work_group_size_multiple() + + def get_private_mem_size(self, SyclDevice device=None): + """get_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. + + Raises: + ValueError: + If ``device`` is not a device of the kernel bundle. + """ + cdef size_t v + if device is None: + v = DPCTLKernel_GetPrivateMemSize(self._kernel_ref) + else: + _check_kernel_device(self, device) + v = DPCTLKernel_GetPrivateMemSizeForDevice( + self._kernel_ref, device.get_device_ref() + ) 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. + """ Property equivalent to method call + `SyclKernel.get_private_mem_size()`. + + .. deprecated:: 0.24.0 + Use :meth:`.get_private_mem_size` instead. """ - cdef size_t v = DPCTLKernel_GetPrivateMemSize(self._kernel_ref) + warnings.warn( + "dpctl.compiler.SyclKernel.private_mem_size is deprecated, " + "use get_private_mem_size() instead", + DeprecationWarning, + ) + return self.get_private_mem_size() + + def get_max_num_sub_groups(self, SyclDevice device=None): + """get_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. + + Raises: + ValueError: + If ``device`` is not a device of the kernel bundle. + """ + cdef uint32_t v + if device is None: + v = DPCTLKernel_GetMaxNumSubGroups(self._kernel_ref) + else: + _check_kernel_device(self, device) + v = DPCTLKernel_GetMaxNumSubGroupsForDevice( + self._kernel_ref, device.get_device_ref() + ) return v @property def max_num_sub_groups(self): - """ Returns the maximum number of sub-groups for this kernel. + """ Property equivalent to method call + `SyclKernel.get_max_num_sub_groups()`. + + .. deprecated:: 0.24.0 + Use :meth:`.get_max_num_sub_groups` instead. """ - cdef uint32_t n = DPCTLKernel_GetMaxNumSubGroups(self._kernel_ref) - return n + warnings.warn( + "dpctl.compiler.SyclKernel.max_num_sub_groups is deprecated, " + "use get_max_num_sub_groups() instead", + DeprecationWarning, + ) + return self.get_max_num_sub_groups() + + def get_max_sub_group_size(self, SyclDevice device=None): + """get_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. + + Raises: + ValueError: + If ``device`` is not a device of the kernel bundle. + """ + cdef uint32_t v + if device is None: + v = DPCTLKernel_GetMaxSubGroupSize(self._kernel_ref) + else: + _check_kernel_device(self, device) + v = DPCTLKernel_GetMaxSubGroupSizeForDevice( + self._kernel_ref, device.get_device_ref() + ) + return v @property def max_sub_group_size(self): - """ Returns the maximum sub-groups size for this kernel. + """ Property equivalent to method call + `SyclKernel.get_max_sub_group_size()`. + + .. deprecated:: 0.24.0 + Use :meth:`.get_max_sub_group_size` instead. """ - cdef uint32_t sz = DPCTLKernel_GetMaxSubGroupSize(self._kernel_ref) - return sz + warnings.warn( + "dpctl.compiler.SyclKernel.max_sub_group_size is deprecated, " + "use get_max_sub_group_size() instead", + DeprecationWarning, + ) + return self.get_max_sub_group_size() + + def get_compile_num_sub_groups(self, SyclDevice device=None): + """get_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. + + Raises: + ValueError: + If ``device`` is not a device of the kernel bundle. + """ + cdef uint32_t v + if device is None: + v = DPCTLKernel_GetCompileNumSubGroups(self._kernel_ref) + else: + _check_kernel_device(self, device) + v = DPCTLKernel_GetCompileNumSubGroupsForDevice( + self._kernel_ref, device.get_device_ref() + ) + return v @property def compile_num_sub_groups(self): - """ Returns the number of sub-groups specified by this kernel, - or 0 (if not specified). + """ Property equivalent to method call + `SyclKernel.get_compile_num_sub_groups()`. + + .. deprecated:: 0.24.0 + Use :meth:`.get_compile_num_sub_groups` instead. """ - cdef size_t n = DPCTLKernel_GetCompileNumSubGroups(self._kernel_ref) - return n + warnings.warn( + "dpctl.compiler.SyclKernel.compile_num_sub_groups is deprecated, " + "use get_compile_num_sub_groups() instead", + DeprecationWarning, + ) + return self.get_compile_num_sub_groups() + + def get_compile_sub_group_size(self, SyclDevice device=None): + """get_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. + + Raises: + ValueError: + If ``device`` is not a device of the kernel bundle. + """ + cdef uint32_t v + if device is None: + v = DPCTLKernel_GetCompileSubGroupSize(self._kernel_ref) + else: + _check_kernel_device(self, device) + v = DPCTLKernel_GetCompileSubGroupSizeForDevice( + self._kernel_ref, device.get_device_ref() + ) + return v @property def compile_sub_group_size(self): - """ Returns the required sub-group size specified by this kernel, - or 0 (if not specified). + """ Property equivalent to method call + `SyclKernel.get_compile_sub_group_size()`. + + .. deprecated:: 0.24.0 + Use :meth:`.get_compile_sub_group_size` instead. """ - cdef size_t n = DPCTLKernel_GetCompileSubGroupSize(self._kernel_ref) - return n + warnings.warn( + "dpctl.compiler.SyclKernel.compile_sub_group_size is deprecated, " + "use get_compile_sub_group_size() instead", + DeprecationWarning, + ) + return self.get_compile_sub_group_size() + + +cdef _check_kernel_device(SyclKernel krn, SyclDevice device): + """ Raises ValueError if ``device`` is not a device of the kernel bundle + of ``krn``. + """ + cdef DPCTLDeviceVectorRef DVRef = DPCTLKernel_GetDevices( + krn.get_kernel_ref() + ) + cdef DPCTLSyclDeviceRef DRef = device.get_device_ref() + cdef DPCTLSyclDeviceRef KDRef = NULL + cdef size_t i + cdef bint found = False + if DVRef is NULL: + raise ValueError("Internal error: NULL device vector encountered") + for i in range(DPCTLDeviceVector_Size(DVRef)): + KDRef = DPCTLDeviceVector_GetAt(DVRef, i) + found = DPCTLDevice_AreEq(KDRef, DRef) + DPCTLDevice_Delete(KDRef) + if found: + break + DPCTLDeviceVector_Delete(DVRef) + if not found: + raise ValueError( + f"Device '{device.filter_string}' is not a device of the kernel " + "bundle of the kernel" + ) cdef api DPCTLSyclKernelRef SyclKernel_GetKernelRef(SyclKernel ker): @@ -251,17 +740,371 @@ cdef api SyclKernel SyclKernel_Make(DPCTLSyclKernelRef KRef, const char *name): return SyclKernel._create(copied_KRef, name.decode("utf-8")) -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. +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 _SyclKernelBundleBase: + """ Base class of :class:`.SyclInputKernelBundle`, + :class:`.SyclObjectKernelBundle` and :class:`.SyclKernelBundle`, with the + queries common to all kernel bundle states. + """ + + @property + def state(self): + """ Returns the state of the kernel bundle: ``"input"``, + ``"object"`` or ``"executable"``. + """ + return _state_to_str(_bundle_state(self)) + + @property + def backend(self): + """ Returns the ``backend_type`` enum value of the kernel bundle. + """ + cdef int st = _bundle_state(self) + cdef _backend_type BTy + if st == _KB_STATE_INPUT: + BTy = DPCTLInputKernelBundle_GetBackend(_input_ref(self)) + elif st == _KB_STATE_OBJECT: + BTy = DPCTLObjectKernelBundle_GetBackend(_object_ref(self)) + else: + BTy = DPCTLKernelBundle_GetBackend(_executable_ref(self)) + return _backend_type_to_enum(BTy) + + @property + def sycl_context(self): + """ Returns the :class:`dpctl.SyclContext` of the kernel bundle. + """ + cdef int st = _bundle_state(self) + cdef DPCTLSyclContextRef CRef + if st == _KB_STATE_INPUT: + CRef = DPCTLInputKernelBundle_GetContext(_input_ref(self)) + elif st == _KB_STATE_OBJECT: + CRef = DPCTLObjectKernelBundle_GetContext(_object_ref(self)) + else: + CRef = DPCTLKernelBundle_GetContext(_executable_ref(self)) + 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 int st = _bundle_state(self) + cdef DPCTLDeviceVectorRef DVRef + if st == _KB_STATE_INPUT: + DVRef = DPCTLInputKernelBundle_GetDevices(_input_ref(self)) + elif st == _KB_STATE_OBJECT: + DVRef = DPCTLObjectKernelBundle_GetDevices(_object_ref(self)) + else: + DVRef = DPCTLKernelBundle_GetDevices(_executable_ref(self)) + return _devices_from_vector(DVRef) + + @property + def is_empty(self): + """ Returns True if the kernel bundle contains no device images. + """ + cdef int st = _bundle_state(self) + if st == _KB_STATE_INPUT: + return DPCTLInputKernelBundle_IsEmpty(_input_ref(self)) + elif st == _KB_STATE_OBJECT: + return DPCTLObjectKernelBundle_IsEmpty(_object_ref(self)) + return DPCTLKernelBundle_IsEmpty(_executable_ref(self)) + + 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 int st = _bundle_state(self) + cdef DPCTLKernelIdVectorRef KIdVRef + if st == _KB_STATE_INPUT: + KIdVRef = DPCTLInputKernelBundle_GetKernelIds(_input_ref(self)) + elif st == _KB_STATE_OBJECT: + KIdVRef = DPCTLObjectKernelBundle_GetKernelIds(_object_ref(self)) + else: + KIdVRef = DPCTLKernelBundle_GetKernelIds(_executable_ref(self)) + 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 int st = _bundle_state(self) + cdef DPCTLSyclKernelIdRef KIdRef = _kernel_id_ref(kernel_id) + cdef DPCTLSyclDeviceRef DRef = NULL + if device is not None: + DRef = device.get_device_ref() + if st == _KB_STATE_INPUT: + return DPCTLInputKernelBundle_HasKernelId( + _input_ref(self), KIdRef, DRef + ) + elif st == _KB_STATE_OBJECT: + return DPCTLObjectKernelBundle_HasKernelId( + _object_ref(self), KIdRef, DRef + ) + return DPCTLKernelBundle_HasKernelId( + _executable_ref(self), KIdRef, DRef + ) + + @property + def contains_specialization_constants(self): + """ Returns True if any device image of the kernel bundle uses + SYCL specialization constants. + """ + cdef int st = _bundle_state(self) + if st == _KB_STATE_INPUT: + return DPCTLInputKernelBundle_ContainsSpecializationConstants( + _input_ref(self) + ) + elif st == _KB_STATE_OBJECT: + return DPCTLObjectKernelBundle_ContainsSpecializationConstants( + _object_ref(self) + ) + return DPCTLKernelBundle_ContainsSpecializationConstants( + _executable_ref(self) + ) + + @property + def native_specialization_constant(self): + """ Returns True if all SYCL specialization constants of the kernel + bundle are native to the backend. + """ + cdef int st = _bundle_state(self) + if st == _KB_STATE_INPUT: + return DPCTLInputKernelBundle_NativeSpecializationConstant( + _input_ref(self) + ) + elif st == _KB_STATE_OBJECT: + return DPCTLObjectKernelBundle_NativeSpecializationConstant( + _object_ref(self) + ) + return DPCTLKernelBundle_NativeSpecializationConstant( + _executable_ref(self) + ) + + def get_device_images(self): + """ Returns a tuple of the :class:`.SyclDeviceImage` objects of the + kernel bundle. + """ + cdef size_t n = _num_device_images(self) + cdef size_t i + cdef SyclDeviceImage img + images = [] + for i in range(n): + img = SyclDeviceImage.__new__(SyclDeviceImage) + img._kernel_bundle = self + img._index = i + images.append(img) + return tuple(images) + + +cdef int _bundle_state(_SyclKernelBundleBase kb) except -1: + if isinstance(kb, SyclInputKernelBundle): + return _KB_STATE_INPUT + elif isinstance(kb, SyclObjectKernelBundle): + return _KB_STATE_OBJECT + elif isinstance(kb, SyclKernelBundle): + return _KB_STATE_EXECUTABLE + raise TypeError(f"Unexpected kernel bundle type {type(kb)}") + + +cdef inline DPCTLSyclInputKernelBundleRef _input_ref(_SyclKernelBundleBase kb): + return (kb)._kernel_bundle_ref + + +cdef inline DPCTLSyclObjectKernelBundleRef _object_ref( + _SyclKernelBundleBase kb +): + return (kb)._kernel_bundle_ref + + +cdef inline DPCTLSyclKernelBundleRef _executable_ref(_SyclKernelBundleBase kb): + return (kb)._kernel_bundle_ref + + +cdef size_t _num_device_images(_SyclKernelBundleBase kb) except? 0: + cdef int st = _bundle_state(kb) + if st == _KB_STATE_INPUT: + return DPCTLInputKernelBundle_GetNumDeviceImages(_input_ref(kb)) + elif st == _KB_STATE_OBJECT: + return DPCTLObjectKernelBundle_GetNumDeviceImages(_object_ref(kb)) + return DPCTLKernelBundle_GetNumDeviceImages(_executable_ref(kb)) + + +cdef bint _device_image_has_kernel( + _SyclKernelBundleBase kb, + size_t index, + SyclKernelId kernel_id, + SyclDevice device, +) except -1: + cdef int st = _bundle_state(kb) + cdef DPCTLSyclKernelIdRef KIdRef = _kernel_id_ref(kernel_id) + cdef DPCTLSyclDeviceRef DRef = NULL + if device is not None: + DRef = device.get_device_ref() + if st == _KB_STATE_INPUT: + return DPCTLInputKernelBundle_DeviceImageHasKernel( + _input_ref(kb), index, KIdRef, DRef + ) + elif st == _KB_STATE_OBJECT: + return DPCTLObjectKernelBundle_DeviceImageHasKernel( + _object_ref(kb), index, KIdRef, DRef + ) + return DPCTLKernelBundle_DeviceImageHasKernel( + _executable_ref(kb), index, KIdRef, DRef + ) + + +cdef class SyclInputKernelBundle(_SyclKernelBundleBase): + """ Wraps a ``sycl::kernel_bundle`` object. + + Obtained from :func:`.get_kernel_bundle` with ``state="input"`` and + :func:`.join`, and converted with :func:`.compile` and :func:`.build`. + """ + + @staticmethod + cdef SyclInputKernelBundle _create(DPCTLSyclInputKernelBundleRef KBRef): + cdef SyclInputKernelBundle ret = SyclInputKernelBundle.__new__( + SyclInputKernelBundle + ) + ret._kernel_bundle_ref = KBRef + return ret + + def __dealloc__(self): + DPCTLInputKernelBundle_Delete(self._kernel_bundle_ref) + + cdef DPCTLSyclInputKernelBundleRef get_kernel_bundle_ref(self): + """ Returns the ``DPCTLSyclInputKernelBundleRef`` pointer for this + kernel bundle. + """ + return self._kernel_bundle_ref + + def addressof_ref(self): + """ Returns the address of the C API ``DPCTLSyclInputKernelBundleRef`` + pointer as a ``size_t``. + """ + return int(self._kernel_bundle_ref) + + +cdef class SyclObjectKernelBundle(_SyclKernelBundleBase): + """ Wraps a ``sycl::kernel_bundle`` object. + + Obtained from :func:`.get_kernel_bundle` with ``state="object"``, + :func:`.compile` and :func:`.join`, and converted with :func:`.link`. + """ + + @staticmethod + cdef SyclObjectKernelBundle _create(DPCTLSyclObjectKernelBundleRef KBRef): + cdef SyclObjectKernelBundle ret = SyclObjectKernelBundle.__new__( + SyclObjectKernelBundle + ) + ret._kernel_bundle_ref = KBRef + return ret + + def __dealloc__(self): + DPCTLObjectKernelBundle_Delete(self._kernel_bundle_ref) + + cdef DPCTLSyclObjectKernelBundleRef get_kernel_bundle_ref(self): + """ Returns the ``DPCTLSyclObjectKernelBundleRef`` pointer for this + kernel bundle. + """ + return self._kernel_bundle_ref + + def addressof_ref(self): + """ Returns the address of the C API ``DPCTLSyclObjectKernelBundleRef`` + pointer as a ``size_t``. + """ + return int(self._kernel_bundle_ref) + + +cdef class SyclKernelBundle(_SyclKernelBundleBase): + """ Wraps a ``sycl::kernel_bundle`` + object. SyclKernelBundle exposes the C API from ``dpctl_sycl_kernel_bundle_interface.h``. A SyclKernelBundle 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 can also be created from the kernels compiled into the + application with :func:`.get_kernel_bundle`, and obtained with + :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 @@ -281,8 +1124,38 @@ cdef class SyclKernelBundle: DPCTLKernelBundle_Delete(self._kernel_bundle_ref) cdef DPCTLSyclKernelBundleRef get_kernel_bundle_ref(self): + """ Returns the ``DPCTLSyclKernelBundleRef`` pointer for this + kernel bundle. + """ return self._kernel_bundle_ref + def get_kernel(self, SyclKernelId kernel_id not None): + """get_kernel(kernel_id) + + Returns the kernel with the given id. + + Args: + kernel_id (dpctl.compiler.SyclKernelId): + Id of the kernel. + + Returns: + dpctl.compiler.SyclKernel: + The kernel object. + + Raises: + ValueError: + If the kernel bundle does not contain the kernel. + """ + cdef DPCTLSyclKernelRef KRef = DPCTLKernelBundle_GetKernelById( + self._kernel_bundle_ref, _kernel_id_ref(kernel_id) + ) + 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) + cpdef SyclKernel get_sycl_kernel(self, str kernel_name): """get_sycl_kernel(kernel_name) @@ -344,6 +1217,61 @@ cdef class SyclKernelBundle: return int(self._kernel_bundle_ref) +cdef class SyclDeviceImage: + """ A device image of a kernel bundle, 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 _device_image_has_kernel( + self._kernel_bundle, 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_ref(kernel_id), DRef + ) + + cdef api DPCTLSyclKernelBundleRef SyclKernelBundle_GetKernelBundleRef( SyclKernelBundle kb ): @@ -363,6 +1291,66 @@ cdef api SyclKernelBundle SyclKernelBundle_Make(DPCTLSyclKernelBundleRef KBRef): return SyclKernelBundle._create(copied_KBRef, False) +cdef api DPCTLSyclInputKernelBundleRef SyclInputKernelBundle_GetKernelBundleRef( + SyclInputKernelBundle kb +): + """ C-API function to access opaque kernel bundle reference from + Python object of type :class:`dpctl.compiler.SyclInputKernelBundle`. + """ + return kb.get_kernel_bundle_ref() + + +cdef api SyclInputKernelBundle SyclInputKernelBundle_Make( + DPCTLSyclInputKernelBundleRef KBRef +): + """ + C-API function to create :class:`dpctl.compiler.SyclInputKernelBundle` + instance from opaque ``sycl::kernel_bundle`` + reference. + """ + cdef DPCTLSyclInputKernelBundleRef copied_KBRef = ( + DPCTLInputKernelBundle_Copy(KBRef) + ) + return SyclInputKernelBundle._create(copied_KBRef) + + +cdef api DPCTLSyclObjectKernelBundleRef \ + SyclObjectKernelBundle_GetKernelBundleRef(SyclObjectKernelBundle kb): + """ C-API function to access opaque kernel bundle reference from + Python object of type :class:`dpctl.compiler.SyclObjectKernelBundle`. + """ + return kb.get_kernel_bundle_ref() + + +cdef api SyclObjectKernelBundle SyclObjectKernelBundle_Make( + DPCTLSyclObjectKernelBundleRef KBRef +): + """ + C-API function to create :class:`dpctl.compiler.SyclObjectKernelBundle` + instance from opaque ``sycl::kernel_bundle`` + reference. + """ + cdef DPCTLSyclObjectKernelBundleRef copied_KBRef = ( + DPCTLObjectKernelBundle_Copy(KBRef) + ) + return SyclObjectKernelBundle._create(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) @@ -568,6 +1556,11 @@ cdef class SpecializationConstant: return self.addressof() +cdef str _build_log_message(DPCTLKernelBuildLogRef BuildLog): + cdef str log = str(DPCTLKernelBuildLog_Get(BuildLog), "utf-8") + return log if log else "Could not create the kernel bundle" + + cpdef create_kernel_bundle_from_source(SyclQueue q, str src, str copts=""): """ Creates a Sycl interoperability kernel bundle from an OpenCL source @@ -596,7 +1589,9 @@ cpdef create_kernel_bundle_from_source(SyclQueue q, str src, str copts=""): Raises: SyclKernelBundleCompilationError - If a SYCL kernel bundle could not be created. + If a SYCL kernel bundle could not be created. The exception + message contains the build log, if the source could not be + built. """ cdef DPCTLSyclKernelBundleRef KBref @@ -606,17 +1601,24 @@ cpdef create_kernel_bundle_from_source(SyclQueue q, str src, str copts=""): cdef const char *COpts = bCOpts cdef DPCTLSyclContextRef CRef = q.get_sycl_context().get_context_ref() cdef DPCTLSyclDeviceRef DRef = q.get_sycl_device().get_device_ref() - KBref = DPCTLKernelBundle_CreateFromOCLSource(CRef, DRef, Src, COpts) - - if KBref is NULL: - raise SyclKernelBundleCompilationError() + cdef DPCTLKernelBuildLogRef BuildLog = DPCTLKernelBuildLog_Create() + try: + KBref = DPCTLKernelBundle_CreateFromOCLSourceWithBuildLog( + CRef, DRef, Src, COpts, BuildLog + ) + if KBref is NULL: + raise SyclKernelBundleCompilationError( + _build_log_message(BuildLog) + ) + finally: + DPCTLKernelBuildLog_Delete(BuildLog) return SyclKernelBundle._create(KBref, False) cpdef create_kernel_bundle_from_spirv( SyclQueue q, - const unsigned char[:] IL, + const unsigned char[::1] IL, str copts="", list specializations=None, ): @@ -647,7 +1649,9 @@ cpdef create_kernel_bundle_from_spirv( Raises: SyclKernelBundleCompilationError - If a SYCL kernel bundle could not be created. + If a SYCL kernel bundle could not be created. The exception + message contains the build log, if the SPIR-V binary could + not be built. """ cdef DPCTLSyclKernelBundleRef KBref @@ -660,6 +1664,7 @@ cpdef create_kernel_bundle_from_spirv( cdef size_t num_spconsts cdef _spec_const *spconsts cdef SpecializationConstant spconst + cdef DPCTLKernelBuildLogRef BuildLog = NULL if specializations is not None and len(specializations) > 0: num_spconsts = len(specializations) @@ -683,17 +1688,22 @@ cpdef create_kernel_bundle_from_spirv( num_spconsts = 0 spconsts = NULL try: - KBref = DPCTLKernelBundle_CreateFromSpirv( + BuildLog = DPCTLKernelBuildLog_Create() + KBref = DPCTLKernelBundle_CreateFromSpirvWithBuildLog( CRef, DRef, dIL, length, COpts, num_spconsts, spconsts, + BuildLog, ) if KBref is NULL: - raise SyclKernelBundleCompilationError() + raise SyclKernelBundleCompilationError( + _build_log_message(BuildLog) + ) finally: + DPCTLKernelBuildLog_Delete(BuildLog) if spconsts != NULL: free(spconsts) @@ -834,3 +1844,541 @@ 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 ids are those of the kernels that appeared while the library was + loaded, so they include the kernels of SYCL libraries it loaded as + dependencies, e.g. oneMKL, which then return none when loaded + themselves, and a kernel bundle for these ids also builds those kernels. + 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 SyclInputKernelBundle._create(InRef) + elif ObjRef is not NULL: + return SyclObjectKernelBundle._create(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) + + +def compile(SyclInputKernelBundle 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.SyclInputKernelBundle): + 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.SyclObjectKernelBundle: + The kernel bundle in ``object`` state. + + Raises: + SyclKernelBundleCompilationError: + If the kernel bundle could not be compiled. + """ + cdef DPCTLDeviceVectorRef DVRef = _device_vector(devices) + cdef DPCTLSyclObjectKernelBundleRef ObjRef = NULL + try: + ObjRef = DPCTLInputKernelBundle_Compile( + kernel_bundle.get_kernel_bundle_ref(), DVRef + ) + finally: + DPCTLDeviceVector_Delete(DVRef) + if ObjRef is NULL: + raise SyclKernelBundleCompilationError( + "Could not compile the kernel bundle" + ) + return SyclObjectKernelBundle._create(ObjRef) + + +def build(SyclInputKernelBundle 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.SyclInputKernelBundle): + 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 = _device_vector(devices) + cdef DPCTLSyclKernelBundleRef ExeRef = NULL + try: + ExeRef = DPCTLInputKernelBundle_Build( + kernel_bundle.get_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.SyclObjectKernelBundle, 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, _SyclKernelBundleBase): + 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: + if not isinstance(kb, SyclObjectKernelBundle): + raise TypeError( + "link expects SyclObjectKernelBundle objects, got " + f"{type(kb)}" + ) + 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_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) + + +cdef bint _is_interop_bundle(SyclKernelBundle kb) except -1: + """ Returns True for a kernel bundle with device images but no kernel ids, + as created from OpenCL source or SPIR-V. + """ + cdef DPCTLSyclKernelBundleRef KBRef = kb.get_kernel_bundle_ref() + cdef DPCTLKernelIdVectorRef KIdVRef + cdef size_t n + if DPCTLKernelBundle_GetNumDeviceImages(KBRef) == 0: + return False + KIdVRef = DPCTLKernelBundle_GetKernelIds(KBRef) + if KIdVRef is NULL: + raise ValueError("Internal error: NULL kernel id vector encountered") + n = DPCTLKernelIdVector_Size(KIdVRef) + DPCTLKernelIdVector_Delete(KIdVRef) + return n == 0 + + +cdef _check_executable_join(tuple kernel_bundles, SyclKernelBundle joined): + """ Raises ValueError for joins of executable kernel bundles whose kernels + :meth:`.SyclKernelBundle.get_sycl_kernel` could not create. + """ + cdef SyclKernelBundle kb + cdef bint any_sycl_source = False + cdef bint all_sycl_source = True + cdef bint any_interop = False + for b in kernel_bundles: + kb = b + any_sycl_source = any_sycl_source or kb._is_sycl_source + all_sycl_source = all_sycl_source and kb._is_sycl_source + if any_sycl_source and not all_sycl_source: + raise ValueError( + "Kernel bundles created from SYCL source can not be joined with " + "other kernel bundles" + ) + # Level Zero creates an interoperability kernel only from a kernel bundle + # with a single device image + if any_sycl_source or ( + DPCTLKernelBundle_GetBackend(joined.get_kernel_bundle_ref()) + != _backend_type._LEVEL_ZERO + ): + return + if _num_device_images(joined) < 2: + return + for b in kernel_bundles: + any_interop = any_interop or _is_interop_bundle(b) + if any_interop: + raise ValueError( + "Kernel bundles created from SPIR-V or OpenCL source can not be " + "joined with other kernel bundles on Level Zero" + ) + + +def join(kernel_bundles): + """join(kernel_bundles) + + Joins the device images of kernel bundles in the same state. + + Kernel bundles created from SYCL source can only be joined with each + other, and kernel bundles created from SPIR-V can not be joined with + other kernel bundles on Level Zero, as + :meth:`.SyclKernelBundle.get_sycl_kernel` could not create their kernels + from the joined kernel bundle. + + Args: + kernel_bundles (Sequence): + A non-empty sequence of :class:`.SyclInputKernelBundle`, + :class:`.SyclObjectKernelBundle` or :class:`.SyclKernelBundle` + objects of the same type. + + Returns: + The kernel bundle with the device images of all given kernel bundles, + of the same type as the given kernel bundles. + + Raises: + TypeError: + If the kernel bundles are not of the same type. + ValueError: + If the kernel bundles can not be joined as described above. + 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 joined + cdef int st + 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], _SyclKernelBundleBase): + raise TypeError( + "join expects kernel bundle objects, got " + f"{type(kernel_bundles[0])}" + ) + kb_type = type(kernel_bundles[0]) + for b in kernel_bundles: + if type(b) is not kb_type: + raise TypeError( + f"join expects {kb_type.__name__} objects, got {type(b)}" + ) + st = _bundle_state(kernel_bundles[0]) + n = len(kernel_bundles) + Refs = malloc(n * sizeof(void *)) + if Refs is NULL: + raise MemoryError() + try: + for i in range(n): + if st == _KB_STATE_INPUT: + Refs[i] = _input_ref(kernel_bundles[i]) + elif st == _KB_STATE_OBJECT: + Refs[i] = _object_ref(kernel_bundles[i]) + else: + Refs[i] = _executable_ref(kernel_bundles[i]) + if st == _KB_STATE_INPUT: + InRef = DPCTLInputKernelBundle_Join( + n, Refs + ) + elif st == _KB_STATE_OBJECT: + ObjRef = DPCTLObjectKernelBundle_Join( + n, Refs + ) + else: + ExeRef = DPCTLKernelBundle_Join( + n, Refs + ) + finally: + free(Refs) + if InRef is not NULL: + return SyclInputKernelBundle._create(InRef) + elif ObjRef is not NULL: + return SyclObjectKernelBundle._create(ObjRef) + elif ExeRef is not NULL: + joined = SyclKernelBundle._create( + ExeRef, (kernel_bundles[0])._is_sycl_source + ) + _check_executable_join(kernel_bundles, joined) + return joined + 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 99d257104f..99f2acf79b 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.get_work_group_size() == k2.get_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.get_work_group_size() == k3.get_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.get_work_group_size() assert type(wgsz) is int - pwgszm = krn.preferred_work_group_size_multiple + pwgszm = krn.get_preferred_work_group_size_multiple() assert type(pwgszm) is int - pmsz = krn.private_mem_size + pmsz = krn.get_private_mem_size() assert type(pmsz) is int - vmnsg = krn.max_num_sub_groups + vmnsg = krn.get_max_num_sub_groups() assert type(vmnsg) is int - v = krn.max_sub_group_size + v = krn.get_max_sub_group_size() assert type(v) is int - cmnsg = krn.compile_num_sub_groups + cmnsg = krn.get_compile_num_sub_groups() assert type(cmnsg) is int - cmsgsz = krn.compile_sub_group_size + cmsgsz = krn.get_compile_sub_group_size() assert type(cmsgsz) is int _check_cpython_api_SyclKernelBundle_GetKernelBundleRef(kb) @@ -295,6 +295,28 @@ def test_create_kernel_bundle_from_invalid_src_ocl(): dpc.create_kernel_bundle_from_source(q, invalid_oclSrc) +@pytest.mark.unsupported_on_acpp +def test_invalid_src_ocl_reports_build_log(): + q = _get_opencl_queue_or_skip() + invalid_oclSrc = "kernel void add(global int* a) { a[0] = b; }" + with pytest.raises(dpc.SyclKernelBundleCompilationError) as e: + dpc.create_kernel_bundle_from_source(q, invalid_oclSrc) + assert "Build log:" in str(e.value) + + +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) + + @pytest.mark.unsupported_on_acpp def test_create_kernel_bundle_with_spec_const(): try: @@ -531,19 +553,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.get_work_group_size() assert type(wgsz) is int - pwgszm = krn.preferred_work_group_size_multiple + pwgszm = krn.get_preferred_work_group_size_multiple() assert type(pwgszm) is int - pmsz = krn.private_mem_size + pmsz = krn.get_private_mem_size() assert type(pmsz) is int - vmnsg = krn.max_num_sub_groups + vmnsg = krn.get_max_num_sub_groups() assert type(vmnsg) is int - v = krn.max_sub_group_size + v = krn.get_max_sub_group_size() assert type(v) is int - cmnsg = krn.compile_num_sub_groups + cmnsg = krn.get_compile_num_sub_groups() assert type(cmnsg) is int - cmsgsz = krn.compile_sub_group_size + cmsgsz = krn.get_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..96d6590010 --- /dev/null +++ b/dpctl/tests/test_sycl_kernel_bundle_states.py @@ -0,0 +1,470 @@ +# 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 ctypes +import os +import sys + +import pytest + +import dpctl +import dpctl.compiler as dpc + +pytestmark = pytest.mark.unsupported_on_acpp + +_STATES = ["input", "object", "executable"] + +_BUNDLE_TYPES = { + "input": dpc.SyclInputKernelBundle, + "object": dpc.SyclObjectKernelBundle, + "executable": dpc.SyclKernelBundle, +} + +_KERNEL_QUERIES = [ + "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", +] + +_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) { + auto it = sycl::ext::oneapi::this_work_item::get_nd_item<1>(); + a[it.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, fn="multi_kernel.spv"): + spirv_file = os.path.join( + os.path.dirname(os.path.abspath(__file__)), "input_files", fn + ) + 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_sycl_source_bundle_or_skip(q, name="bundle_state_test_kernel"): + if not dpc.is_sycl_source_compilation_available(): + pytest.skip("SYCL source compilation is not available") + if not q.sycl_device.can_compile("sycl"): + pytest.skip("The device can not compile SYCL source") + return dpc.create_kernel_bundle_from_sycl_source( + q, _SYCL_SOURCE.replace("bundle_state_test_kernel", name) + ) + + +def _get_capi_fn(name, sig, restype, argtype): + mod = sys.modules[dpc.SyclKernelBundle.__module__] + cap_ptr_fn = ctypes.pythonapi.PyCapsule_GetPointer + cap_ptr_fn.restype = ctypes.c_void_p + cap_ptr_fn.argtypes = [ctypes.py_object, ctypes.c_char_p] + fn_ptr = cap_ptr_fn(mod.__pyx_capi__[name], sig) + return ctypes.PYFUNCTYPE(restype, argtype)(fn_ptr) + + +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 type(kb) is _BUNDLE_TYPES[state] + 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 type(joined) is _BUNDLE_TYPES[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(TypeError): + dpc.compile(exe) + with pytest.raises(TypeError): + dpc.build(exe) + with pytest.raises(TypeError): + dpc.link(inp) + with pytest.raises(ValueError): + dpc.link([]) + with pytest.raises(ValueError): + dpc.join([]) + with pytest.raises(TypeError): + dpc.join([inp, exe]) + with pytest.raises(TypeError): + dpc.join([inp, q]) + with pytest.raises(TypeError): + dpc.join([q]) + assert not hasattr(inp, "get_sycl_kernel") + assert not hasattr(inp, "get_kernel") + + +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.get_work_group_size() > 0 + inp = dpc.get_kernel_bundle(q, kernel_ids=[kid], state="input") + 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 _KERNEL_QUERIES: + query = getattr(krn, "get_" + name) + assert type(query(d)) is int + assert query(d) == query() + assert query(device=d) == query() + assert krn.get_work_group_size(d) > 0 + + +def test_kernel_info_deprecated_properties(): + q = _get_queue_or_skip() + kb = _get_interop_bundle_or_skip(q) + krn = kb.get_sycl_kernel("add") + for name in _KERNEL_QUERIES: + with pytest.warns(DeprecationWarning, match=name): + v = getattr(krn, name) + assert v == getattr(krn, "get_" + name)() + + +def test_kernel_info_for_foreign_device(): + q = _get_queue_or_skip() + kb = _get_interop_bundle_or_skip(q) + krn = kb.get_sycl_kernel("add") + other = [d for d in dpctl.get_devices() if d != q.sycl_device] + if not other: + pytest.skip("Needs a second device") + for d in other: + for name in _KERNEL_QUERIES: + with pytest.raises(ValueError): + getattr(krn, "get_" + name)(d) + + +def test_join_different_interop_bundles(): + q = _get_queue_or_skip() + kb1 = _get_interop_bundle_or_skip(q) + kb2 = _get_interop_bundle_or_skip( + q, "local_accessor_kernel_inttys_fp32.spv" + ) + if q.sycl_device.backend == dpctl.backend_type.level_zero: + with pytest.raises(ValueError): + dpc.join([kb1, kb2]) + return + joined = dpc.join([kb1, kb2]) + assert isinstance(joined.get_sycl_kernel("add"), dpc.SyclKernel) + + +def test_join_sycl_source_with_interop_bundle(): + q = _get_queue_or_skip() + src = _get_sycl_source_bundle_or_skip(q) + with pytest.raises(ValueError): + dpc.join([src, _get_interop_bundle_or_skip(q)]) + other = _get_sycl_source_bundle_or_skip(q, "bundle_state_other_kernel") + joined = dpc.join([src, other]) + for name in ["bundle_state_test_kernel", "bundle_state_other_kernel"]: + assert isinstance(joined.get_sycl_kernel(name), dpc.SyclKernel) + + +def test_kernel_id_without_ref(): + q = _get_queue_or_skip() + kid = dpc.SyclKernelId.__new__(dpc.SyclKernelId) + with pytest.raises(ValueError): + dpc.is_compatible([kid], q.sycl_device) + with pytest.raises(ValueError): + dpc.get_kernel_bundle(q, kernel_ids=[kid]) + with pytest.raises(ValueError): + dpc.get_kernel_bundle(q).has_kernel(kid) + + +@pytest.mark.parametrize("state", ["input", "object"]) +def test_cpython_api_kernel_bundle(state): + q = _get_queue_or_skip() + kb = dpc.get_kernel_bundle(q, state=state) + cls = type(kb).__name__ + get_ref = _get_capi_fn( + f"{cls}_GetKernelBundleRef", + f"DPCTL{cls}Ref (struct Py{cls}Object *)".encode(), + ctypes.c_void_p, + ctypes.py_object, + ) + make = _get_capi_fn( + f"{cls}_Make", + f"struct Py{cls}Object *(DPCTL{cls}Ref)".encode(), + ctypes.py_object, + ctypes.c_void_p, + ) + assert get_ref(kb) == kb.addressof_ref() + kb2 = make(kb.addressof_ref()) + assert type(kb2) is type(kb) + assert kb2.addressof_ref() != kb.addressof_ref() + assert kb2.sycl_context == kb.sycl_context + + +def test_cpython_api_kernel_id(): + q = _get_queue_or_skip() + kid = _get_kernel_ids_or_skip(q)[0] + get_ref = _get_capi_fn( + "SyclKernelId_GetKernelIdRef", + b"DPCTLSyclKernelIdRef (struct PySyclKernelIdObject *)", + ctypes.c_void_p, + ctypes.py_object, + ) + make = _get_capi_fn( + "SyclKernelId_Make", + b"struct PySyclKernelIdObject *(DPCTLSyclKernelIdRef)", + ctypes.py_object, + ctypes.c_void_p, + ) + assert get_ref(kid) == kid.addressof_ref() + assert make(kid.addressof_ref()) == kid + + +def test_kernel_bundle_types(): + for cls in _BUNDLE_TYPES.values(): + assert issubclass(cls, dpc._compiler._SyclKernelBundleBase) + assert not issubclass(dpc.SyclInputKernelBundle, dpc.SyclKernelBundle) + assert not issubclass(dpc.SyclObjectKernelBundle, dpc.SyclKernelBundle) diff --git a/dpctl/tests/test_sycl_kernel_library.py b/dpctl/tests/test_sycl_kernel_library.py new file mode 100644 index 0000000000..89085447ea --- /dev/null +++ b/dpctl/tests/test_sycl_kernel_library.py @@ -0,0 +1,191 @@ +# 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 os +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 + +pytestmark = pytest.mark.unsupported_on_acpp + +_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; +} +""" + + +def _build_kernel_library(d, name, source, options=()): + """Builds a SYCL shared library ``name`` in directory ``d``, or skips.""" + src = d / "kernels.cpp" + src.write_text(source) + if sys.platform.startswith("linux"): + cxx = shutil.which("icpx") + lib = d / f"lib{name}.so" + cmd = [cxx, "-fsycl", "-fPIC", "-shared", str(src), *options] + cmd += ["-o", str(lib)] + elif sys.platform == "win32": + cxx = shutil.which("icx") + lib = d / f"{name}.dll" + cmd = [cxx, "-fsycl", "/LD", str(src), *options, f"/Fe{lib}"] + else: + pytest.skip("Building the test kernel library is not set up here") + if cxx is None: + pytest.skip("No compiler is available to build the test kernel library") + res = subprocess.run(cmd, capture_output=True, text=True, cwd=d) + if res.returncode != 0: + pytest.skip(f"Could not build the test kernel library: {res.stderr}") + return lib + + +@pytest.fixture(scope="module") +def kernel_library(tmp_path_factory): + # a non-ASCII directory name + d = tmp_path_factory.mktemp("kernel_library") / "\u044f\u0434\u0440\u0430" + d.mkdir() + return _build_kernel_library(d, "dpctl_test_kernels", _LIBRARY_SOURCE) + + +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_load_kernel_library_path_forms(kernel_library, monkeypatch): + kids = set(dpc.load_kernel_library(kernel_library)) + assert set(dpc.load_kernel_library(kernel_library.as_posix())) == kids + monkeypatch.chdir(kernel_library.parent.parent) + rel = os.path.join(kernel_library.parent.name, kernel_library.name) + assert set(dpc.load_kernel_library(rel)) == kids + + +def test_kernel_library_dependency_kernel_ids(tmp_path_factory): + if not sys.platform.startswith("linux"): + pytest.skip("Linking the test kernel libraries is only set up on Linux") + d = tmp_path_factory.mktemp("dependent_kernel_libraries") + dep_src = _LIBRARY_SOURCE.replace( + "dpctl_py_test_scale", "dpctl_py_test_dep" + ) + main_src = _LIBRARY_SOURCE.replace( + "dpctl_py_test_scale", "dpctl_py_test_main" + ) + (d / "dep").mkdir() + (d / "main").mkdir() + dep = _build_kernel_library(d / "dep", "dpctl_test_dep", dep_src) + main = _build_kernel_library( + d / "main", + "dpctl_test_main", + main_src, + [f"-L{dep.parent}", "-ldpctl_test_dep", f"-Wl,-rpath,{dep.parent}"], + ) + names = {k.name for k in dpc.load_kernel_library(main)} + assert names == { + "__sycl_kernel_dpctl_py_test_main", + "__sycl_kernel_dpctl_py_test_dep", + } + assert dpc.load_kernel_library(dep) == () + + +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): + return _build_kernel_library( + tmp_path_factory.mktemp("cpu_only_kernel_library"), + "dpctl_test_cpu_only_kernels", + _CPU_ONLY_SOURCE, + ["-fsycl-targets=spir64_x86_64"], + ) + + +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..97d57e2509 --- /dev/null +++ b/examples/pybind11/use_kernel_bundle/README.md @@ -0,0 +1,29 @@ +# Usage of dpctl Kernel Bundles in Pybind11 + +## Description + +This extension demonstrates how a Pybind11 extension can work with +``dpctl.compiler.SyclInputKernelBundle``, +``dpctl.compiler.SyclObjectKernelBundle`` and +``dpctl.compiler.SyclKernelBundle`` objects, 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..6cc8e74b8c --- /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.SyclObjectKernelBundle) + 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..f3e1ebaffa --- /dev/null +++ b/examples/pybind11/use_kernel_bundle/use_kernel_bundle/__init__.py @@ -0,0 +1,47 @@ +# 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.SyclInputKernelBundle`, `dpctl.compiler.SyclObjectKernelBundle` +and `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..5b48dc87cc 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 @@ -261,6 +264,61 @@ void DPCTLKernelBuildLog_Delete(__dpctl_take DPCTLKernelBuildLogRef Ref); DPCTL_API const char * DPCTLKernelBuildLog_Get(__dpctl_keep DPCTLKernelBuildLogRef); +/*! + * @brief Same as DPCTLKernelBundle_CreateFromSpirv, and stores the error and + * the build log in BuildLog if the SPIR-V binary could not be built. + * + * @param Ctx An opaque pointer to a sycl::context + * @param Dev An opaque pointer to a sycl::device + * @param IL SPIR-V binary + * @param Length The size of the IL binary in bytes. + * @param CompileOpts Optional compiler flags used when compiling the + * SPIR-V binary, or NULL for none. + * @param NumSpecConsts The number of specialization constants. + * @param SpecConsts An array of specialization constants, or NULL if + * NumSpecConsts is 0. + * @param BuildLog Opaque pointer to a kernel build log, or NULL. + * @return A new SyclKernelBundleRef pointer if the kernel_bundle creation + * succeeded, else returns NULL. + * + * @ingroup KernelBundleInterface + */ +DPCTL_API +__dpctl_give DPCTLSyclKernelBundleRef +DPCTLKernelBundle_CreateFromSpirvWithBuildLog( + __dpctl_keep const DPCTLSyclContextRef Ctx, + __dpctl_keep const DPCTLSyclDeviceRef Dev, + __dpctl_keep const void *IL, + size_t Length, + const char *CompileOpts, + size_t NumSpecConsts, + __dpctl_keep const DPCTLSpecConst *SpecConsts, + __dpctl_keep DPCTLKernelBuildLogRef BuildLog); + +/*! + * @brief Same as DPCTLKernelBundle_CreateFromOCLSource, and stores the error + * and the build log in BuildLog if the source could not be built. + * + * @param Ctx An opaque pointer to a sycl::context + * @param Dev An opaque pointer to a sycl::device + * @param Source OpenCL source string + * @param CompileOpts Extra compiler flags (refer Sycl spec.), or NULL + * for none + * @param BuildLog Opaque pointer to a kernel build log, or NULL. + * @return A new SyclKernelBundleRef pointer if the kernel bundle creation + * succeeded, else returns NULL. + * + * @ingroup KernelBundleInterface + */ +DPCTL_API +__dpctl_give DPCTLSyclKernelBundleRef +DPCTLKernelBundle_CreateFromOCLSourceWithBuildLog( + __dpctl_keep const DPCTLSyclContextRef Ctx, + __dpctl_keep const DPCTLSyclDeviceRef Dev, + __dpctl_keep const char *Source, + __dpctl_keep const char *CompileOpts, + __dpctl_keep DPCTLKernelBuildLogRef BuildLog); + /*! * @brief Return True if the DPCTLKernelBundle_CreateFromSYCLSource function is * available, else False. @@ -327,4 +385,874 @@ 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 ids are those of the kernels that appeared while the library was + * loaded, so they include the kernels of SYCL libraries it loaded as + * dependencies, which then return none when loaded themselves. 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, UTF-8 encoded on + * Windows + * @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 fd0ba14dfe..e371067500 100644 --- a/libsyclinterface/include/syclinterface/dpctl_sycl_kernel_interface.h +++ b/libsyclinterface/include/syclinterface/dpctl_sycl_kernel_interface.h @@ -30,6 +30,7 @@ #include "Support/ExternC.h" #include "Support/MemOwnershipAttrs.h" #include "dpctl_data_types.h" +#include "dpctl_sycl_device_manager.h" #include "dpctl_sycl_types.h" DPCTL_C_EXTERN_C_BEGIN @@ -171,4 +172,134 @@ DPCTL_API uint32_t DPCTLKernel_GetCompileSubGroupSize(__dpctl_keep const DPCTLSyclKernelRef KRef); +/*! + * @brief Returns the devices of the kernel bundle of the kernel. + * + * @param KRef DPCTLSyclKernelRef pointer to a SYCL kernel. + * @return A new DPCTLDeviceVectorRef, or NULL on failure. + * @ingroup KernelInterface + */ +DPCTL_API +__dpctl_give DPCTLDeviceVectorRef +DPCTLKernel_GetDevices(__dpctl_keep const DPCTLSyclKernelRef KRef); + +/*! + * !brief Wrapper around + * `kernel::get_info(device)`. + * + * @param KRef DPCTLSyclKernelRef pointer to a SYCL kernel. + * @param DRef DPCTLSyclDeviceRef pointer to a device of the + * kernel bundle of the kernel. + * @return Returns the maximum number of work-items in a work-group + * that can be used to execute the kernel on the device, or 0 if DRef + * is not a device of the kernel bundle or the query fails. + * @ingroup KernelInterface + */ +DPCTL_API +size_t DPCTLKernel_GetWorkGroupSizeForDevice( + __dpctl_keep const DPCTLSyclKernelRef KRef, + __dpctl_keep const DPCTLSyclDeviceRef DRef); + +/*! + * !brief Wrapper around + * `kernel::get_info(device)`. + * + * @param KRef DPCTLSyclKernelRef pointer to a SYCL kernel. + * @param DRef DPCTLSyclDeviceRef pointer to a device of the + * kernel bundle of the kernel. + * @return Returns a value, of which work-group size is preferred to + * be a multiple, for executing the kernel on the device, or 0 if DRef + * is not a device of the kernel bundle or the query fails. + * @ingroup KernelInterface + */ +DPCTL_API +size_t DPCTLKernel_GetPreferredWorkGroupSizeMultipleForDevice( + __dpctl_keep const DPCTLSyclKernelRef KRef, + __dpctl_keep const DPCTLSyclDeviceRef DRef); + +/*! + * !brief Wrapper around + * `kernel::get_info(device)`. + * + * @param KRef DPCTLSyclKernelRef pointer to a SYCL kernel. + * @param DRef DPCTLSyclDeviceRef pointer to a device of the + * kernel bundle of the kernel. + * @return Returns the minimum amount of private memory, in bytes, + * used by each work-item in the kernel on the device, or 0 if DRef is + * not a device of the kernel bundle or the query fails. + * @ingroup KernelInterface + */ +DPCTL_API +size_t DPCTLKernel_GetPrivateMemSizeForDevice( + __dpctl_keep const DPCTLSyclKernelRef KRef, + __dpctl_keep const DPCTLSyclDeviceRef DRef); + +/*! + * !brief Wrapper around + * `kernel::get_info(device)`. + * + * @param KRef DPCTLSyclKernelRef pointer to a SYCL kernel. + * @param DRef DPCTLSyclDeviceRef pointer to a device of the + * kernel bundle of the kernel. + * @return Returns the maximum number of sub-groups for the kernel on + * the device, or 0 if DRef is not a device of the kernel + * bundle or the query fails. + * @ingroup KernelInterface + */ +DPCTL_API +uint32_t DPCTLKernel_GetMaxNumSubGroupsForDevice( + __dpctl_keep const DPCTLSyclKernelRef KRef, + __dpctl_keep const DPCTLSyclDeviceRef DRef); + +/*! + * !brief Wrapper around + * `kernel::get_info(device)`. + * + * @param KRef DPCTLSyclKernelRef pointer to a SYCL kernel. + * @param DRef DPCTLSyclDeviceRef pointer to a device of the + * kernel bundle of the kernel. + * @return Returns the maximum sub-group size for the kernel on the + * device, or 0 if DRef is not a device of the kernel + * bundle or the query fails. + * @ingroup KernelInterface + */ +DPCTL_API +uint32_t DPCTLKernel_GetMaxSubGroupSizeForDevice( + __dpctl_keep const DPCTLSyclKernelRef KRef, + __dpctl_keep const DPCTLSyclDeviceRef DRef); + +/*! + * !brief Wrapper around + * `kernel::get_info(device)`. + * + * @param KRef DPCTLSyclKernelRef pointer to a SYCL kernel. + * @param DRef DPCTLSyclDeviceRef pointer to a device of the + * kernel bundle of the kernel. + * @return Returns the number of sub-groups specified by the kernel, + * or 0 (if not specified), or 0 if DRef is not a device of the kernel + * bundle or the query fails. + * @ingroup KernelInterface + */ +DPCTL_API +uint32_t DPCTLKernel_GetCompileNumSubGroupsForDevice( + __dpctl_keep const DPCTLSyclKernelRef KRef, + __dpctl_keep const DPCTLSyclDeviceRef DRef); + +/*! + * !brief Wrapper around + * `kernel::get_info(device)`. + * + * @param KRef DPCTLSyclKernelRef pointer to a SYCL kernel. + * @param DRef DPCTLSyclDeviceRef pointer to a device of the + * kernel bundle of the kernel. + * @return Returns the required sub-group size specified by the + * kernel, or 0 (if not specified), or 0 if DRef is not a device of the + * kernel bundle or the query fails. + * @ingroup KernelInterface + */ +DPCTL_API +uint32_t DPCTLKernel_GetCompileSubGroupSizeForDevice( + __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 ce8d8f12ed..26d0749ee7 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 @@ -69,6 +70,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) #endif #include "dpctl_sycl_device_manager.h" @@ -83,6 +91,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 8139cdeff7..46a14598e4 100644 --- a/libsyclinterface/source/dpctl_sycl_kernel_bundle_interface.cpp +++ b/libsyclinterface/source/dpctl_sycl_kernel_bundle_interface.cpp @@ -36,6 +36,7 @@ #include "dpctl_sycl_kernel_bundle_interface.h" #include "dpctl_sycl_type_casters.hpp" #include +#include #include #include #include /* Sycl headers */ @@ -205,50 +206,174 @@ 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 (*clReleaseDeviceFT)(cl_device_id); +const char *clReleaseDevice_Name = "clReleaseDevice"; +clReleaseDeviceFT get_clReleaseDevice() +{ + static auto st_clReleaseDeviceF = + cl_loader::get().getSymbol(clReleaseDevice_Name); + + return st_clReleaseDeviceF; +} + +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); + } +} + +void _Release_ocl_impl(cl_device_id clDevice) +{ + if (auto clReleaseDeviceF = get_clReleaseDevice()) { + clReleaseDeviceF(clDevice); + } +} + +/*! 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. On a build failure the error + * and build log are stored in Log, if not NULL. + */ DPCTLSyclKernelBundleRef _CreateKernelBundle_common_ocl_impl(cl_program clProgram, const context &ctx, const device &dev, - const char *CompileOpts) + const char *CompileOpts, + std::string *Log) { backend_traits::return_type clDevice; clDevice = get_native(dev); + cl_ref_guard clDeviceGuard(clDevice); // Last two pointers are notification function pointer and user-data pointer // 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; + } + if (Log) { + *Log = msg; } + 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 _CreateKernelBundleWithOCLSource_ocl_impl(const context &ctx, const device &dev, const char *oclSrc, - const char *CompileOpts) + const char *CompileOpts, + std::string *Log) { auto clCreateProgramWithSourceF = get_clCreateProgramWithSource(); if (clCreateProgramWithSourceF == nullptr) { @@ -257,6 +382,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( @@ -268,9 +394,10 @@ _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); + return _CreateKernelBundle_common_ocl_impl(clProgram, ctx, dev, CompileOpts, + Log); } DPCTLSyclKernelBundleRef @@ -280,22 +407,24 @@ _CreateKernelBundleWithIL_ocl_impl(const context &ctx, size_t il_length, const char *CompileOpts, size_t NumSpecConsts, - const DPCTLSpecConst *SpecConsts) + const DPCTLSpecConst *SpecConsts, + std::string *Log) { auto clCreateProgramWithILF = get_clCreateProgramWithIL(); if (clCreateProgramWithILF == nullptr) { 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); @@ -307,6 +436,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(); @@ -323,12 +453,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; } } @@ -337,18 +461,12 @@ _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; } } - return _CreateKernelBundle_common_ocl_impl(clProgram, ctx, dev, - CompileOpts); + return _CreateKernelBundle_common_ocl_impl(clProgram, ctx, dev, CompileOpts, + Log); } bool _HasKernel_ocl_impl(const kernel_bundle &kb, @@ -363,12 +481,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; @@ -385,36 +507,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 @@ -472,16 +591,6 @@ zeModuleCreateFT get_zeModuleCreate() return st_zeModuleCreateF; } -typedef ze_result_t (*zeModuleDestroyFT)(ze_module_handle_t); -const char *zeModuleDestroy_Name = "zeModuleDestroy"; -zeModuleDestroyFT get_zeModuleDestroy() -{ - static auto st_zeModuleDestroyF = - ze_loader::get().getSymbol(zeModuleDestroy_Name); - - return st_zeModuleDestroyF; -} - typedef ze_result_t (*zeKernelCreateFT)(ze_module_handle_t, const ze_kernel_desc_t *, ze_kernel_handle_t *); @@ -494,6 +603,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) { @@ -520,7 +701,8 @@ _CreateKernelBundleWithIL_ze_impl(const context &SyclCtx, size_t il_length, const char *CompileOpts, size_t NumSpecConsts, - const DPCTLSpecConst *SpecConsts) + const DPCTLSpecConst *SpecConsts, + std::string *Log) { auto zeModuleCreateFn = get_zeModuleCreate(); if (zeModuleCreateFn == nullptr) { @@ -567,29 +749,36 @@ _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; + } + if (Log) { + *Log = msg; + } + error_handler(msg, __FILE__, __func__, __LINE__, error_level::error); return nullptr; } + // With ownership::transfer the kernel bundle destroys ZeModule. If + // make_kernel_bundle throws, it may already own ZeModule, so ZeModule is + // leaked rather than destroyed. + 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(); - if (zeModuleDestroyFn) { - zeModuleDestroyFn(ZeModule); - } return nullptr; } } @@ -606,25 +795,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. If + // make_kernel throws, it may already own ZeKern, so ZeKern is + // leaked rather than destroyed. + 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__); + return nullptr; + } } else { if (ze_status != ZE_RESULT_ERROR_INVALID_KERNEL_NAME) { @@ -636,15 +829,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, @@ -664,12 +852,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 { @@ -699,8 +887,25 @@ DPCTLKernelBundle_CreateFromSpirv(__dpctl_keep const DPCTLSyclContextRef CtxRef, const char *CompileOpts, size_t NumSpecConsts, const DPCTLSpecConst *SpecConsts) +{ + return DPCTLKernelBundle_CreateFromSpirvWithBuildLog( + CtxRef, DevRef, IL, length, CompileOpts, NumSpecConsts, SpecConsts, + nullptr); +} + +__dpctl_give DPCTLSyclKernelBundleRef +DPCTLKernelBundle_CreateFromSpirvWithBuildLog( + __dpctl_keep const DPCTLSyclContextRef CtxRef, + __dpctl_keep const DPCTLSyclDeviceRef DevRef, + __dpctl_keep const void *IL, + size_t length, + const char *CompileOpts, + size_t NumSpecConsts, + const DPCTLSpecConst *SpecConsts, + __dpctl_keep DPCTLKernelBuildLogRef BuildLog) { #ifndef __ADAPTIVECPP__ + auto Log = reinterpret_cast(BuildLog); DPCTLSyclKernelBundleRef KBRef = nullptr; if (!CtxRef) { error_handler("Cannot create kernel bundle from SPIR-V as the supplied " @@ -729,13 +934,13 @@ DPCTLKernelBundle_CreateFromSpirv(__dpctl_keep const DPCTLSyclContextRef CtxRef, case backend::opencl: KBRef = _CreateKernelBundleWithIL_ocl_impl( *SyclCtx, *SyclDev, IL, length, CompileOpts, NumSpecConsts, - SpecConsts); + SpecConsts, Log); break; case backend::ext_oneapi_level_zero: #ifdef DPCTL_ENABLE_L0_KERNEL_BUNDLE_CREATION KBRef = _CreateKernelBundleWithIL_ze_impl( *SyclCtx, *SyclDev, IL, length, CompileOpts, NumSpecConsts, - SpecConsts); + SpecConsts, Log); break; #endif default: @@ -762,8 +967,21 @@ __dpctl_give DPCTLSyclKernelBundleRef DPCTLKernelBundle_CreateFromOCLSource( __dpctl_keep const DPCTLSyclDeviceRef Dev, __dpctl_keep const char *Source, __dpctl_keep const char *CompileOpts) +{ + return DPCTLKernelBundle_CreateFromOCLSourceWithBuildLog( + Ctx, Dev, Source, CompileOpts, nullptr); +} + +__dpctl_give DPCTLSyclKernelBundleRef +DPCTLKernelBundle_CreateFromOCLSourceWithBuildLog( + __dpctl_keep const DPCTLSyclContextRef Ctx, + __dpctl_keep const DPCTLSyclDeviceRef Dev, + __dpctl_keep const char *Source, + __dpctl_keep const char *CompileOpts, + __dpctl_keep DPCTLKernelBuildLogRef BuildLog) { #ifndef __ADAPTIVECPP__ + auto Log = reinterpret_cast(BuildLog); context *SyclCtx = nullptr; device *SyclDev = nullptr; @@ -783,26 +1001,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__); + *SyclCtx, *SyclDev, Source, CompileOpts, Log); + 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; } #else @@ -827,19 +1045,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; } #else @@ -863,19 +1086,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; } #else 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..bf4571c781 --- /dev/null +++ b/libsyclinterface/source/dpctl_sycl_kernel_bundle_state_interface.cpp @@ -0,0 +1,1560 @@ +//===- 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 + +#ifndef __ADAPTIVECPP__ + +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; +} + +#ifdef _WIN32 +std::wstring utf8_to_wide(const char *Str) +{ + int N = + MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, Str, -1, nullptr, 0); + if (N <= 0) + return std::wstring{}; + std::wstring W(static_cast(N), L'\0'); + if (MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, Str, -1, W.data(), + N) <= 0) + return std::wstring{}; + W.resize(static_cast(N) - 1); + return W; +} +#endif + +void *open_library(const char *Path, std::string &Error) +{ +#ifdef _WIN32 + std::wstring WPath = utf8_to_wide(Path); + if (WPath.empty()) { + Error = "the path is not valid UTF-8"; + return nullptr; + } + // the search flags require an absolute path with backslashes + DWORD N = GetFullPathNameW(WPath.c_str(), 0, nullptr, nullptr); + if (N == 0) { + Error = "GetFullPathNameW failed with error code " + + std::to_string(GetLastError()); + return nullptr; + } + std::wstring FullPath(N, L'\0'); + N = GetFullPathNameW(WPath.c_str(), N, FullPath.data(), nullptr); + if (N == 0 || N >= FullPath.size()) { + Error = "GetFullPathNameW failed with error code " + + std::to_string(GetLastError()); + return nullptr; + } + FullPath.resize(N); + void *Handle = LoadLibraryExW(FullPath.c_str(), nullptr, + LOAD_LIBRARY_SEARCH_DEFAULT_DIRS | + LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR); + if (!Handle) + Error = "LoadLibraryExW 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__); +} + +#else /* #ifndef __ADAPTIVECPP__ */ + +// AdaptiveCpp has no kernel_bundle or kernel_id + +namespace +{ +void report_unsupported(const char *Fn) +{ + error_handler("Kernel bundles are not supported in AdaptiveCpp", __FILE__, + Fn, __LINE__, error_level::error); +} +} // end of anonymous namespace + +__dpctl_give DPCTLKernelIdVectorRef DPCTLKernelIdVector_Create() +{ + report_unsupported(__func__); + return nullptr; +} + +__dpctl_give DPCTLKernelIdVectorRef +DPCTLKernelIdVector_CreateFromArray(size_t n, + __dpctl_keep DPCTLSyclKernelIdRef *elems) +{ + report_unsupported(__func__); + return nullptr; +} + +void DPCTLKernelIdVector_Delete(__dpctl_take DPCTLKernelIdVectorRef VRef) {} + +void DPCTLKernelIdVector_Clear(__dpctl_keep DPCTLKernelIdVectorRef VRef) {} + +size_t DPCTLKernelIdVector_Size(__dpctl_keep DPCTLKernelIdVectorRef VRef) +{ + report_unsupported(__func__); + return 0; +} + +__dpctl_give DPCTLSyclKernelIdRef +DPCTLKernelIdVector_GetAt(__dpctl_keep DPCTLKernelIdVectorRef VRef, + size_t index) +{ + report_unsupported(__func__); + return nullptr; +} + +__dpctl_give const char * +DPCTLKernelId_GetName(__dpctl_keep const DPCTLSyclKernelIdRef KIdRef) +{ + report_unsupported(__func__); + return nullptr; +} + +bool DPCTLKernelId_AreEq(__dpctl_keep const DPCTLSyclKernelIdRef KIdRef1, + __dpctl_keep const DPCTLSyclKernelIdRef KIdRef2) +{ + report_unsupported(__func__); + return false; +} + +size_t DPCTLKernelId_Hash(__dpctl_keep const DPCTLSyclKernelIdRef KIdRef) +{ + report_unsupported(__func__); + return 0; +} + +__dpctl_give DPCTLSyclKernelIdRef +DPCTLKernelId_Copy(__dpctl_keep const DPCTLSyclKernelIdRef KIdRef) +{ + report_unsupported(__func__); + return nullptr; +} + +void DPCTLKernelId_Delete(__dpctl_take DPCTLSyclKernelIdRef KIdRef) {} + +__dpctl_give DPCTLKernelIdVectorRef DPCTLKernelId_GetAll(void) +{ + report_unsupported(__func__); + return nullptr; +} + +__dpctl_give DPCTLKernelIdVectorRef +DPCTLKernelId_LoadLibrary(__dpctl_keep const char *Path) +{ + report_unsupported(__func__); + return nullptr; +} + +bool DPCTLKernelId_IsCompatible(__dpctl_keep const DPCTLKernelIdVectorRef + KIdVRef, + __dpctl_keep const DPCTLSyclDeviceRef DRef) +{ + report_unsupported(__func__); + return false; +} + +__dpctl_give DPCTLSyclKernelBundleRef DPCTLKernelBundle_CreateFromContext( + __dpctl_keep const DPCTLSyclContextRef CRef, + __dpctl_keep const DPCTLDeviceVectorRef DVRef, + __dpctl_keep const DPCTLKernelIdVectorRef KIdVRef) +{ + report_unsupported(__func__); + return nullptr; +} + +bool DPCTLKernelBundle_CanCreateFromContext( + __dpctl_keep const DPCTLSyclContextRef CRef, + __dpctl_keep const DPCTLDeviceVectorRef DVRef, + __dpctl_keep const DPCTLKernelIdVectorRef KIdVRef) +{ + report_unsupported(__func__); + return false; +} + +__dpctl_give DPCTLSyclContextRef +DPCTLKernelBundle_GetContext(__dpctl_keep const DPCTLSyclKernelBundleRef KBRef) +{ + report_unsupported(__func__); + return nullptr; +} + +__dpctl_give DPCTLDeviceVectorRef +DPCTLKernelBundle_GetDevices(__dpctl_keep const DPCTLSyclKernelBundleRef KBRef) +{ + report_unsupported(__func__); + return nullptr; +} + +DPCTLSyclBackendType +DPCTLKernelBundle_GetBackend(__dpctl_keep const DPCTLSyclKernelBundleRef KBRef) +{ + report_unsupported(__func__); + return DPCTL_UNKNOWN_BACKEND; +} + +bool DPCTLKernelBundle_IsEmpty( + __dpctl_keep const DPCTLSyclKernelBundleRef KBRef) +{ + report_unsupported(__func__); + return false; +} + +__dpctl_give DPCTLKernelIdVectorRef DPCTLKernelBundle_GetKernelIds( + __dpctl_keep const DPCTLSyclKernelBundleRef KBRef) +{ + report_unsupported(__func__); + return nullptr; +} + +bool DPCTLKernelBundle_HasKernelId( + __dpctl_keep const DPCTLSyclKernelBundleRef KBRef, + __dpctl_keep const DPCTLSyclKernelIdRef KIdRef, + __dpctl_keep const DPCTLSyclDeviceRef DRef) +{ + report_unsupported(__func__); + return false; +} + +bool DPCTLKernelBundle_ContainsSpecializationConstants( + __dpctl_keep const DPCTLSyclKernelBundleRef KBRef) +{ + report_unsupported(__func__); + return false; +} + +bool DPCTLKernelBundle_NativeSpecializationConstant( + __dpctl_keep const DPCTLSyclKernelBundleRef KBRef) +{ + report_unsupported(__func__); + return false; +} + +size_t DPCTLKernelBundle_GetNumDeviceImages( + __dpctl_keep const DPCTLSyclKernelBundleRef KBRef) +{ + report_unsupported(__func__); + return 0; +} + +bool DPCTLKernelBundle_DeviceImageHasKernel( + __dpctl_keep const DPCTLSyclKernelBundleRef KBRef, + size_t Index, + __dpctl_keep const DPCTLSyclKernelIdRef KIdRef, + __dpctl_keep const DPCTLSyclDeviceRef DRef) +{ + report_unsupported(__func__); + return false; +} + +__dpctl_give DPCTLSyclKernelBundleRef +DPCTLKernelBundle_Join(size_t NumKBRefs, + __dpctl_keep const DPCTLSyclKernelBundleRef *KBRefs) +{ + report_unsupported(__func__); + return nullptr; +} + +__dpctl_give DPCTLSyclKernelRef DPCTLKernelBundle_GetKernelById( + __dpctl_keep const DPCTLSyclKernelBundleRef KBRef, + __dpctl_keep const DPCTLSyclKernelIdRef KIdRef) +{ + report_unsupported(__func__); + return nullptr; +} + +__dpctl_give DPCTLSyclInputKernelBundleRef +DPCTLInputKernelBundle_CreateFromContext( + __dpctl_keep const DPCTLSyclContextRef CRef, + __dpctl_keep const DPCTLDeviceVectorRef DVRef, + __dpctl_keep const DPCTLKernelIdVectorRef KIdVRef) +{ + report_unsupported(__func__); + return nullptr; +} + +bool DPCTLInputKernelBundle_CanCreateFromContext( + __dpctl_keep const DPCTLSyclContextRef CRef, + __dpctl_keep const DPCTLDeviceVectorRef DVRef, + __dpctl_keep const DPCTLKernelIdVectorRef KIdVRef) +{ + report_unsupported(__func__); + return false; +} + +__dpctl_give DPCTLSyclInputKernelBundleRef DPCTLInputKernelBundle_Copy( + __dpctl_keep const DPCTLSyclInputKernelBundleRef KBRef) +{ + report_unsupported(__func__); + return nullptr; +} + +void DPCTLInputKernelBundle_Delete( + __dpctl_take DPCTLSyclInputKernelBundleRef KBRef) +{ +} + +__dpctl_give DPCTLSyclContextRef DPCTLInputKernelBundle_GetContext( + __dpctl_keep const DPCTLSyclInputKernelBundleRef KBRef) +{ + report_unsupported(__func__); + return nullptr; +} + +__dpctl_give DPCTLDeviceVectorRef DPCTLInputKernelBundle_GetDevices( + __dpctl_keep const DPCTLSyclInputKernelBundleRef KBRef) +{ + report_unsupported(__func__); + return nullptr; +} + +DPCTLSyclBackendType DPCTLInputKernelBundle_GetBackend( + __dpctl_keep const DPCTLSyclInputKernelBundleRef KBRef) +{ + report_unsupported(__func__); + return DPCTL_UNKNOWN_BACKEND; +} + +bool DPCTLInputKernelBundle_IsEmpty( + __dpctl_keep const DPCTLSyclInputKernelBundleRef KBRef) +{ + report_unsupported(__func__); + return false; +} + +__dpctl_give DPCTLKernelIdVectorRef DPCTLInputKernelBundle_GetKernelIds( + __dpctl_keep const DPCTLSyclInputKernelBundleRef KBRef) +{ + report_unsupported(__func__); + return nullptr; +} + +bool DPCTLInputKernelBundle_HasKernelId( + __dpctl_keep const DPCTLSyclInputKernelBundleRef KBRef, + __dpctl_keep const DPCTLSyclKernelIdRef KIdRef, + __dpctl_keep const DPCTLSyclDeviceRef DRef) +{ + report_unsupported(__func__); + return false; +} + +bool DPCTLInputKernelBundle_ContainsSpecializationConstants( + __dpctl_keep const DPCTLSyclInputKernelBundleRef KBRef) +{ + report_unsupported(__func__); + return false; +} + +bool DPCTLInputKernelBundle_NativeSpecializationConstant( + __dpctl_keep const DPCTLSyclInputKernelBundleRef KBRef) +{ + report_unsupported(__func__); + return false; +} + +size_t DPCTLInputKernelBundle_GetNumDeviceImages( + __dpctl_keep const DPCTLSyclInputKernelBundleRef KBRef) +{ + report_unsupported(__func__); + return 0; +} + +bool DPCTLInputKernelBundle_DeviceImageHasKernel( + __dpctl_keep const DPCTLSyclInputKernelBundleRef KBRef, + size_t Index, + __dpctl_keep const DPCTLSyclKernelIdRef KIdRef, + __dpctl_keep const DPCTLSyclDeviceRef DRef) +{ + report_unsupported(__func__); + return false; +} + +__dpctl_give DPCTLSyclInputKernelBundleRef DPCTLInputKernelBundle_Join( + size_t NumKBRefs, + __dpctl_keep const DPCTLSyclInputKernelBundleRef *KBRefs) +{ + report_unsupported(__func__); + return nullptr; +} + +__dpctl_give DPCTLSyclObjectKernelBundleRef DPCTLInputKernelBundle_Compile( + __dpctl_keep const DPCTLSyclInputKernelBundleRef KBRef, + __dpctl_keep const DPCTLDeviceVectorRef DVRef) +{ + report_unsupported(__func__); + return nullptr; +} + +__dpctl_give DPCTLSyclKernelBundleRef DPCTLInputKernelBundle_Build( + __dpctl_keep const DPCTLSyclInputKernelBundleRef KBRef, + __dpctl_keep const DPCTLDeviceVectorRef DVRef) +{ + report_unsupported(__func__); + return nullptr; +} + +__dpctl_give DPCTLSyclObjectKernelBundleRef +DPCTLObjectKernelBundle_CreateFromContext( + __dpctl_keep const DPCTLSyclContextRef CRef, + __dpctl_keep const DPCTLDeviceVectorRef DVRef, + __dpctl_keep const DPCTLKernelIdVectorRef KIdVRef) +{ + report_unsupported(__func__); + return nullptr; +} + +bool DPCTLObjectKernelBundle_CanCreateFromContext( + __dpctl_keep const DPCTLSyclContextRef CRef, + __dpctl_keep const DPCTLDeviceVectorRef DVRef, + __dpctl_keep const DPCTLKernelIdVectorRef KIdVRef) +{ + report_unsupported(__func__); + return false; +} + +__dpctl_give DPCTLSyclObjectKernelBundleRef DPCTLObjectKernelBundle_Copy( + __dpctl_keep const DPCTLSyclObjectKernelBundleRef KBRef) +{ + report_unsupported(__func__); + return nullptr; +} + +void DPCTLObjectKernelBundle_Delete( + __dpctl_take DPCTLSyclObjectKernelBundleRef KBRef) +{ +} + +__dpctl_give DPCTLSyclContextRef DPCTLObjectKernelBundle_GetContext( + __dpctl_keep const DPCTLSyclObjectKernelBundleRef KBRef) +{ + report_unsupported(__func__); + return nullptr; +} + +__dpctl_give DPCTLDeviceVectorRef DPCTLObjectKernelBundle_GetDevices( + __dpctl_keep const DPCTLSyclObjectKernelBundleRef KBRef) +{ + report_unsupported(__func__); + return nullptr; +} + +DPCTLSyclBackendType DPCTLObjectKernelBundle_GetBackend( + __dpctl_keep const DPCTLSyclObjectKernelBundleRef KBRef) +{ + report_unsupported(__func__); + return DPCTL_UNKNOWN_BACKEND; +} + +bool DPCTLObjectKernelBundle_IsEmpty( + __dpctl_keep const DPCTLSyclObjectKernelBundleRef KBRef) +{ + report_unsupported(__func__); + return false; +} + +__dpctl_give DPCTLKernelIdVectorRef DPCTLObjectKernelBundle_GetKernelIds( + __dpctl_keep const DPCTLSyclObjectKernelBundleRef KBRef) +{ + report_unsupported(__func__); + return nullptr; +} + +bool DPCTLObjectKernelBundle_HasKernelId( + __dpctl_keep const DPCTLSyclObjectKernelBundleRef KBRef, + __dpctl_keep const DPCTLSyclKernelIdRef KIdRef, + __dpctl_keep const DPCTLSyclDeviceRef DRef) +{ + report_unsupported(__func__); + return false; +} + +bool DPCTLObjectKernelBundle_ContainsSpecializationConstants( + __dpctl_keep const DPCTLSyclObjectKernelBundleRef KBRef) +{ + report_unsupported(__func__); + return false; +} + +bool DPCTLObjectKernelBundle_NativeSpecializationConstant( + __dpctl_keep const DPCTLSyclObjectKernelBundleRef KBRef) +{ + report_unsupported(__func__); + return false; +} + +size_t DPCTLObjectKernelBundle_GetNumDeviceImages( + __dpctl_keep const DPCTLSyclObjectKernelBundleRef KBRef) +{ + report_unsupported(__func__); + return 0; +} + +bool DPCTLObjectKernelBundle_DeviceImageHasKernel( + __dpctl_keep const DPCTLSyclObjectKernelBundleRef KBRef, + size_t Index, + __dpctl_keep const DPCTLSyclKernelIdRef KIdRef, + __dpctl_keep const DPCTLSyclDeviceRef DRef) +{ + report_unsupported(__func__); + return false; +} + +__dpctl_give DPCTLSyclObjectKernelBundleRef DPCTLObjectKernelBundle_Join( + size_t NumKBRefs, + __dpctl_keep const DPCTLSyclObjectKernelBundleRef *KBRefs) +{ + report_unsupported(__func__); + return nullptr; +} + +__dpctl_give DPCTLSyclKernelBundleRef DPCTLObjectKernelBundle_Link( + size_t NumKBRefs, + __dpctl_keep const DPCTLSyclObjectKernelBundleRef *KBRefs, + __dpctl_keep const DPCTLDeviceVectorRef DVRef) +{ + report_unsupported(__func__); + return nullptr; +} + +bool DPCTLDeviceImage_HasKernel(__dpctl_keep const DPCTLSyclDeviceImageRef + ImgRef, + __dpctl_keep const DPCTLSyclKernelIdRef KIdRef, + __dpctl_keep const DPCTLSyclDeviceRef DRef) +{ + report_unsupported(__func__); + return false; +} + +__dpctl_give DPCTLSyclKernelBundleRef +DPCTLKernelBundle_CreateFromContextWithSelector( + __dpctl_keep const DPCTLSyclContextRef CRef, + __dpctl_keep const DPCTLDeviceVectorRef DVRef, + DPCTLDeviceImageSelectorFn Selector, + void *UserData) +{ + report_unsupported(__func__); + return nullptr; +} + +__dpctl_give DPCTLSyclInputKernelBundleRef +DPCTLInputKernelBundle_CreateFromContextWithSelector( + __dpctl_keep const DPCTLSyclContextRef CRef, + __dpctl_keep const DPCTLDeviceVectorRef DVRef, + DPCTLDeviceImageSelectorFn Selector, + void *UserData) +{ + report_unsupported(__func__); + return nullptr; +} + +__dpctl_give DPCTLSyclObjectKernelBundleRef +DPCTLObjectKernelBundle_CreateFromContextWithSelector( + __dpctl_keep const DPCTLSyclContextRef CRef, + __dpctl_keep const DPCTLDeviceVectorRef DVRef, + DPCTLDeviceImageSelectorFn Selector, + void *UserData) +{ + report_unsupported(__func__); + return nullptr; +} + +#endif /* #ifndef __ADAPTIVECPP__ */ diff --git a/libsyclinterface/source/dpctl_sycl_kernel_interface.cpp b/libsyclinterface/source/dpctl_sycl_kernel_interface.cpp index c9a6175588..b1a2dbcdc3 100644 --- a/libsyclinterface/source/dpctl_sycl_kernel_interface.cpp +++ b/libsyclinterface/source/dpctl_sycl_kernel_interface.cpp @@ -29,9 +29,12 @@ #include "dpctl_error_handlers.h" #include "dpctl_string_utils.hpp" #include "dpctl_sycl_type_casters.hpp" +#include #include +#include #include #include /* Sycl headers */ +#include using namespace sycl; @@ -43,6 +46,57 @@ static_assert(__SYCL_COMPILER_VERSION >= __SYCL_COMPILER_VERSION_REQUIRED, #endif using namespace dpctl::syclinterface; + +std::vector kernel_devices(const kernel &Kernel) +{ +#ifndef __ADAPTIVECPP__ + return Kernel.get_kernel_bundle().get_devices(); +#else + return Kernel.get_context().get_devices(); +#endif +} + +template +RetT get_device_specific_info(DPCTLSyclKernelRef KRef, + DPCTLSyclDeviceRef DRef, + bool RequireDevice, + const char *Fn) +{ + if (!KRef) { + error_handler("Input DPCTKSyclKernelRef is nullptr.", __FILE__, Fn, + __LINE__); + return 0; + } + if (RequireDevice && !DRef) { + error_handler("Input DPCTLSyclDeviceRef is nullptr.", __FILE__, Fn, + __LINE__); + return 0; + } + auto sycl_kern = unwrap(KRef); + try { + auto devs = kernel_devices(*sycl_kern); + if (devs.empty()) { + error_handler("Input DPCTKSyclKernelRef has no associated device.", + __FILE__, Fn, __LINE__); + return 0; + } + if (!DRef) + return static_cast(sycl_kern->get_info(devs[0])); + const device &Dev = *unwrap(DRef); + // the SYCL runtime does not check the device, and a device of another + // backend can crash it + if (std::find(devs.begin(), devs.end(), Dev) == devs.end()) { + error_handler("The device is not a device of the kernel bundle of " + "the kernel.", + __FILE__, Fn, __LINE__); + return 0; + } + return static_cast(sycl_kern->get_info(Dev)); + } 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) @@ -87,183 +141,140 @@ DPCTLKernel_Copy(__dpctl_keep const DPCTLSyclKernelRef KRef) } } -size_t DPCTLKernel_GetWorkGroupSize(__dpctl_keep const DPCTLSyclKernelRef KRef) +__dpctl_give DPCTLDeviceVectorRef +DPCTLKernel_GetDevices(__dpctl_keep const DPCTLSyclKernelRef KRef) { if (!KRef) { error_handler("Input DPCTKSyclKernelRef is nullptr.", __FILE__, __func__, __LINE__); - return 0; + return nullptr; } - - auto sycl_kern = unwrap(KRef); -#ifndef __ADAPTIVECPP__ - auto devs = sycl_kern->get_kernel_bundle().get_devices(); -#else - auto devs = sycl_kern->get_context().get_devices(); -#endif - if (devs.empty()) { - error_handler("Input DPCTKSyclKernelRef has no associated device.", - __FILE__, __func__, __LINE__); - return 0; + try { + auto devs = kernel_devices(*unwrap(KRef)); + 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()); + } catch (std::exception const &e) { + error_handler(e, __FILE__, __func__, __LINE__); + return nullptr; } - auto v = sycl_kern->get_info( - devs[0]); - return static_cast(v); +} + +size_t DPCTLKernel_GetWorkGroupSize(__dpctl_keep const DPCTLSyclKernelRef KRef) +{ + return get_device_specific_info< + info::kernel_device_specific::work_group_size, size_t>(KRef, nullptr, + false, __func__); +} + +size_t DPCTLKernel_GetWorkGroupSizeForDevice( + __dpctl_keep const DPCTLSyclKernelRef KRef, + __dpctl_keep const DPCTLSyclDeviceRef DRef) +{ + return get_device_specific_info< + info::kernel_device_specific::work_group_size, size_t>(KRef, DRef, true, + __func__); } size_t DPCTLKernel_GetPreferredWorkGroupSizeMultiple( __dpctl_keep const DPCTLSyclKernelRef KRef) { - if (!KRef) { - error_handler("Input DPCTKSyclKernelRef is nullptr.", __FILE__, - __func__, __LINE__); - return 0; - } + return get_device_specific_info< + info::kernel_device_specific::preferred_work_group_size_multiple, + size_t>(KRef, nullptr, false, __func__); +} - auto sycl_kern = unwrap(KRef); -#ifndef __ADAPTIVECPP__ - auto devs = sycl_kern->get_kernel_bundle().get_devices(); -#else - auto devs = sycl_kern->get_context().get_devices(); -#endif - 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); +size_t DPCTLKernel_GetPreferredWorkGroupSizeMultipleForDevice( + __dpctl_keep const DPCTLSyclKernelRef KRef, + __dpctl_keep const DPCTLSyclDeviceRef DRef) +{ + return get_device_specific_info< + info::kernel_device_specific::preferred_work_group_size_multiple, + size_t>(KRef, DRef, true, __func__); } size_t DPCTLKernel_GetPrivateMemSize(__dpctl_keep const DPCTLSyclKernelRef KRef) { - if (!KRef) { - error_handler("Input DPCTKSyclKernelRef is nullptr.", __FILE__, - __func__, __LINE__); - return 0; - } + return get_device_specific_info< + info::kernel_device_specific::private_mem_size, size_t>( + KRef, nullptr, false, __func__); +} - auto sycl_kern = unwrap(KRef); -#ifndef __ADAPTIVECPP__ - auto devs = sycl_kern->get_kernel_bundle().get_devices(); -#else - auto devs = sycl_kern->get_context().get_devices(); -#endif - 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); +size_t DPCTLKernel_GetPrivateMemSizeForDevice( + __dpctl_keep const DPCTLSyclKernelRef KRef, + __dpctl_keep const DPCTLSyclDeviceRef DRef) +{ + return get_device_specific_info< + info::kernel_device_specific::private_mem_size, size_t>(KRef, DRef, + true, __func__); } uint32_t DPCTLKernel_GetMaxNumSubGroups(__dpctl_keep const DPCTLSyclKernelRef KRef) { - if (!KRef) { - error_handler("Input DPCTKSyclKernelRef is nullptr.", __FILE__, - __func__, __LINE__); - return 0; - } + return get_device_specific_info< + info::kernel_device_specific::max_num_sub_groups, uint32_t>( + KRef, nullptr, false, __func__); +} - auto sycl_kern = unwrap(KRef); -#ifndef __ADAPTIVECPP__ - auto devs = sycl_kern->get_kernel_bundle().get_devices(); -#else - auto devs = sycl_kern->get_context().get_devices(); -#endif - 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); +uint32_t DPCTLKernel_GetMaxNumSubGroupsForDevice( + __dpctl_keep const DPCTLSyclKernelRef KRef, + __dpctl_keep const DPCTLSyclDeviceRef DRef) +{ + return get_device_specific_info< + info::kernel_device_specific::max_num_sub_groups, uint32_t>( + KRef, DRef, true, __func__); } uint32_t DPCTLKernel_GetMaxSubGroupSize(__dpctl_keep const DPCTLSyclKernelRef KRef) { - if (!KRef) { - error_handler("Input DPCTKSyclKernelRef is nullptr.", __FILE__, - __func__, __LINE__); - return 0; - } + return get_device_specific_info< + info::kernel_device_specific::max_sub_group_size, uint32_t>( + KRef, nullptr, false, __func__); +} - auto sycl_kern = unwrap(KRef); -#ifndef __ADAPTIVECPP__ - auto devs = sycl_kern->get_kernel_bundle().get_devices(); -#else - auto devs = sycl_kern->get_context().get_devices(); -#endif - 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; +uint32_t DPCTLKernel_GetMaxSubGroupSizeForDevice( + __dpctl_keep const DPCTLSyclKernelRef KRef, + __dpctl_keep const DPCTLSyclDeviceRef DRef) +{ + return get_device_specific_info< + info::kernel_device_specific::max_sub_group_size, uint32_t>( + KRef, DRef, true, __func__); } uint32_t DPCTLKernel_GetCompileNumSubGroups(__dpctl_keep const DPCTLSyclKernelRef KRef) { - if (!KRef) { - error_handler("Input DPCTKSyclKernelRef is nullptr.", __FILE__, - __func__, __LINE__); - return 0; - } + return get_device_specific_info< + info::kernel_device_specific::compile_num_sub_groups, uint32_t>( + KRef, nullptr, false, __func__); +} - auto sycl_kern = unwrap(KRef); -#ifndef __ADAPTIVECPP__ - auto devs = sycl_kern->get_kernel_bundle().get_devices(); -#else - auto devs = sycl_kern->get_context().get_devices(); -#endif - 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); +uint32_t DPCTLKernel_GetCompileNumSubGroupsForDevice( + __dpctl_keep const DPCTLSyclKernelRef KRef, + __dpctl_keep const DPCTLSyclDeviceRef DRef) +{ + return get_device_specific_info< + info::kernel_device_specific::compile_num_sub_groups, uint32_t>( + KRef, DRef, true, __func__); } uint32_t DPCTLKernel_GetCompileSubGroupSize(__dpctl_keep const DPCTLSyclKernelRef KRef) { - if (!KRef) { - error_handler("Input DPCTKSyclKernelRef is nullptr.", __FILE__, - __func__, __LINE__); - return 0; - } + return get_device_specific_info< + info::kernel_device_specific::compile_sub_group_size, uint32_t>( + KRef, nullptr, false, __func__); +} - auto sycl_kern = unwrap(KRef); -#ifndef __ADAPTIVECPP__ - auto devs = sycl_kern->get_kernel_bundle().get_devices(); -#else - auto devs = sycl_kern->get_context().get_devices(); -#endif - 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); +uint32_t DPCTLKernel_GetCompileSubGroupSizeForDevice( + __dpctl_keep const DPCTLSyclKernelRef KRef, + __dpctl_keep const DPCTLSyclDeviceRef DRef) +{ + return get_device_specific_info< + info::kernel_device_specific::compile_sub_group_size, uint32_t>( + KRef, DRef, true, __func__); } diff --git a/libsyclinterface/tests/CMakeLists.txt b/libsyclinterface/tests/CMakeLists.txt index dac01ad743..f29d5ea3d5 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 @@ -80,6 +105,11 @@ target_link_libraries(dpctl_c_api_tests GTest::GTest DPCTLSyclInterface ) +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_interface.cpp b/libsyclinterface/tests/test_sycl_kernel_bundle_interface.cpp index 5d053bffa2..9cfca68dac 100644 --- a/libsyclinterface/tests/test_sycl_kernel_bundle_interface.cpp +++ b/libsyclinterface/tests/test_sycl_kernel_bundle_interface.cpp @@ -40,6 +40,7 @@ #include #include #include +#include #include using namespace sycl; @@ -181,6 +182,29 @@ TEST_P(TestDPCTLSyclKernelBundleInterface, ChkCreateFromSpirvWithCompileOpts) DPCTLKernelBundle_Delete(KB); } +TEST_P(TestDPCTLSyclKernelBundleInterface, ChkCreateFromSpirvWithBuildLog) +{ + auto Log = DPCTLKernelBuildLog_Create(); + auto KB = DPCTLKernelBundle_CreateFromSpirvWithBuildLog( + CRef, DRef, spirvBuffer.data(), spirvFileSize, nullptr, 0, nullptr, + Log); + ASSERT_TRUE(KB != nullptr); + EXPECT_TRUE(DPCTLKernelBundle_HasKernel(KB, "add")); + EXPECT_STREQ(DPCTLKernelBuildLog_Get(Log), ""); + DPCTLKernelBundle_Delete(KB); + + KB = DPCTLKernelBundle_CreateFromSpirvWithBuildLog( + CRef, DRef, spirvBuffer.data(), spirvFileSize, nullptr, 0, nullptr, + nullptr); + ASSERT_TRUE(KB != nullptr); + DPCTLKernelBundle_Delete(KB); + + EXPECT_TRUE(DPCTLKernelBundle_CreateFromSpirvWithBuildLog( + nullptr, DRef, spirvBuffer.data(), spirvFileSize, nullptr, + 0, nullptr, Log) == nullptr); + DPCTLKernelBuildLog_Delete(Log); +} + TEST_P(TestDPCTLSyclKernelBundleInterface, ChkHasKernelNullKernelBundle) { @@ -310,6 +334,33 @@ TEST_P(TestOCLKernelBundleFromSource, CheckCreateFromOCLSourceNullCompileOpts) DPCTLKernelBundle_Delete(KB); } +TEST_P(TestOCLKernelBundleFromSource, CheckCreateFromOCLSourceWithBuildLog) +{ + const char *InvalidCLProgramStr = R"CLC( + kernel void add(global int* a) { a[0] = b; } + )CLC"; + auto Log = DPCTLKernelBuildLog_Create(); + auto KB = DPCTLKernelBundle_CreateFromOCLSourceWithBuildLog( + CRef, DRef, InvalidCLProgramStr, CompileOpts, Log); + EXPECT_TRUE(KB == nullptr); + std::string LogStr = DPCTLKernelBuildLog_Get(Log); + EXPECT_NE(LogStr.find("Build log:"), std::string::npos); + DPCTLKernelBuildLog_Delete(Log); + + Log = DPCTLKernelBuildLog_Create(); + KB = DPCTLKernelBundle_CreateFromOCLSourceWithBuildLog( + CRef, DRef, CLProgramStr, CompileOpts, Log); + ASSERT_TRUE(KB != nullptr); + EXPECT_TRUE(DPCTLKernelBundle_HasKernel(KB, "add")); + EXPECT_STREQ(DPCTLKernelBuildLog_Get(Log), ""); + DPCTLKernelBundle_Delete(KB); + DPCTLKernelBuildLog_Delete(Log); + + KB = DPCTLKernelBundle_CreateFromOCLSourceWithBuildLog( + CRef, DRef, InvalidCLProgramStr, CompileOpts, nullptr); + EXPECT_TRUE(KB == nullptr); +} + TEST_P(TestOCLKernelBundleFromSource, CheckGetKernelOCLSource) { auto AddKernel = DPCTLKernelBundle_GetKernel(KBRef, "add"); 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..350d7c6a92 --- /dev/null +++ b/libsyclinterface/tests/test_sycl_kernel_bundle_state_interface.cpp @@ -0,0 +1,581 @@ +//===-- 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; +}; + +std::string kernel_id_name(DPCTLSyclKernelIdRef KIdRef) +{ + auto Name = DPCTLKernelId_GetName(KIdRef); + std::string Res(Name ? Name : ""); + DPCTLCString_Delete(Name); + return Res; +} + +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_NO_FATAL_FAILURE( + DPCTLKernelBundle_NativeSpecializationConstant(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), 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); + auto KDevs = DPCTLKernel_GetDevices(KRef); + ASSERT_TRUE(KDevs); + EXPECT_EQ(DPCTLDeviceVector_Size(KDevs), 1u); + DPCTLDeviceVector_Delete(KDevs); + EXPECT_EQ(DPCTLKernel_GetWorkGroupSizeForDevice(KRef, DRef), + DPCTLKernel_GetWorkGroupSize(KRef)); + EXPECT_EQ( + DPCTLKernel_GetPreferredWorkGroupSizeMultipleForDevice(KRef, DRef), + DPCTLKernel_GetPreferredWorkGroupSizeMultiple(KRef)); + EXPECT_EQ(DPCTLKernel_GetPrivateMemSizeForDevice(KRef, DRef), + DPCTLKernel_GetPrivateMemSize(KRef)); + EXPECT_EQ(DPCTLKernel_GetMaxNumSubGroupsForDevice(KRef, DRef), + DPCTLKernel_GetMaxNumSubGroups(KRef)); + EXPECT_EQ(DPCTLKernel_GetMaxSubGroupSizeForDevice(KRef, DRef), + DPCTLKernel_GetMaxSubGroupSize(KRef)); + EXPECT_EQ(DPCTLKernel_GetCompileNumSubGroupsForDevice(KRef, DRef), + DPCTLKernel_GetCompileNumSubGroups(KRef)); + EXPECT_EQ(DPCTLKernel_GetCompileSubGroupSizeForDevice(KRef, DRef), + DPCTLKernel_GetCompileSubGroupSize(KRef)); + EXPECT_GT(DPCTLKernel_GetWorkGroupSizeForDevice(KRef, DRef), 0u); + EXPECT_EQ(DPCTLKernel_GetMaxSubGroupSizeForDevice(nullptr, DRef), 0u); + DPCTLKernel_Delete(KRef); + DPCTLKernelBundle_Delete(KBRef); +} + +TEST_P(TestKernelBundleState, ChkInputQueries) +{ + ASSERT_TRUE(KIdA); + auto KIdVRef = DPCTLKernelIdVector_CreateFromArray(1, &KIdA); + auto InKB = DPCTLInputKernelBundle_CreateFromContext(CRef, DVRef, KIdVRef); + DPCTLKernelIdVector_Delete(KIdVRef); + ASSERT_TRUE(InKB); + EXPECT_EQ(DPCTLInputKernelBundle_GetBackend(InKB), + DPCTLDevice_GetBackend(DRef)); + EXPECT_FALSE(DPCTLInputKernelBundle_ContainsSpecializationConstants(InKB)); + EXPECT_NO_FATAL_FAILURE( + DPCTLInputKernelBundle_NativeSpecializationConstant(InKB)); + + auto Ctx = DPCTLInputKernelBundle_GetContext(InKB); + ASSERT_TRUE(Ctx); + EXPECT_TRUE(DPCTLContext_AreEq(Ctx, CRef)); + DPCTLContext_Delete(Ctx); + + auto Devs = DPCTLInputKernelBundle_GetDevices(InKB); + 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 = DPCTLInputKernelBundle_GetKernelIds(InKB); + ASSERT_TRUE(KIds); + auto Found = find_kernel_id(KIds, kernel_id_name(KIdA)); + EXPECT_TRUE(Found); + DPCTLKernelId_Delete(Found); + DPCTLKernelIdVector_Delete(KIds); + + size_t NumImages = DPCTLInputKernelBundle_GetNumDeviceImages(InKB); + ASSERT_GE(NumImages, 1u); + bool InSomeImage = false; + for (size_t i = 0; i < NumImages; ++i) + InSomeImage |= + DPCTLInputKernelBundle_DeviceImageHasKernel(InKB, i, KIdA, DRef); + EXPECT_TRUE(InSomeImage); + EXPECT_FALSE(DPCTLInputKernelBundle_DeviceImageHasKernel(InKB, NumImages, + KIdA, nullptr)); + + DPCTLInputKernelBundle_Delete(InKB); +} + +TEST_P(TestKernelBundleState, ChkObjectQueries) +{ + ASSERT_TRUE(KIdB); + auto KIdVRef = DPCTLKernelIdVector_CreateFromArray(1, &KIdB); + auto ObjKB = + DPCTLObjectKernelBundle_CreateFromContext(CRef, DVRef, KIdVRef); + DPCTLKernelIdVector_Delete(KIdVRef); + ASSERT_TRUE(ObjKB); + EXPECT_FALSE(DPCTLObjectKernelBundle_IsEmpty(ObjKB)); + EXPECT_FALSE( + DPCTLObjectKernelBundle_ContainsSpecializationConstants(ObjKB)); + EXPECT_NO_FATAL_FAILURE( + DPCTLObjectKernelBundle_NativeSpecializationConstant(ObjKB)); + + auto Devs = DPCTLObjectKernelBundle_GetDevices(ObjKB); + 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 = DPCTLObjectKernelBundle_GetKernelIds(ObjKB); + ASSERT_TRUE(KIds); + auto Found = find_kernel_id(KIds, kernel_id_name(KIdB)); + EXPECT_TRUE(Found); + DPCTLKernelId_Delete(Found); + DPCTLKernelIdVector_Delete(KIds); + + size_t NumImages = DPCTLObjectKernelBundle_GetNumDeviceImages(ObjKB); + ASSERT_GE(NumImages, 1u); + bool InSomeImage = false; + for (size_t i = 0; i < NumImages; ++i) + InSomeImage |= + DPCTLObjectKernelBundle_DeviceImageHasKernel(ObjKB, i, KIdB, DRef); + EXPECT_TRUE(InSomeImage); + EXPECT_FALSE(DPCTLObjectKernelBundle_DeviceImageHasKernel(ObjKB, NumImages, + KIdB, nullptr)); + + DPCTLObjectKernelBundle_Delete(ObjKB); +} + +TEST_P(TestKernelBundleState, ChkStateQueriesNullArgs) +{ + EXPECT_EQ(DPCTLInputKernelBundle_GetBackend(nullptr), + DPCTL_UNKNOWN_BACKEND); + EXPECT_EQ(DPCTLInputKernelBundle_GetContext(nullptr), nullptr); + EXPECT_EQ(DPCTLInputKernelBundle_GetDevices(nullptr), nullptr); + EXPECT_EQ(DPCTLInputKernelBundle_GetKernelIds(nullptr), nullptr); + EXPECT_FALSE( + DPCTLInputKernelBundle_ContainsSpecializationConstants(nullptr)); + EXPECT_FALSE(DPCTLInputKernelBundle_NativeSpecializationConstant(nullptr)); + EXPECT_FALSE( + DPCTLInputKernelBundle_DeviceImageHasKernel(nullptr, 0, KIdA, DRef)); + EXPECT_EQ(DPCTLObjectKernelBundle_GetDevices(nullptr), nullptr); + EXPECT_EQ(DPCTLObjectKernelBundle_GetKernelIds(nullptr), nullptr); + EXPECT_EQ(DPCTLObjectKernelBundle_GetNumDeviceImages(nullptr), 0u); + EXPECT_FALSE( + DPCTLObjectKernelBundle_ContainsSpecializationConstants(nullptr)); + EXPECT_FALSE(DPCTLObjectKernelBundle_NativeSpecializationConstant(nullptr)); + EXPECT_FALSE( + DPCTLObjectKernelBundle_DeviceImageHasKernel(nullptr, 0, KIdA, DRef)); + EXPECT_FALSE(DPCTLKernelBundle_NativeSpecializationConstant(nullptr)); +} + +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..ef34f77493 100644 --- a/libsyclinterface/tests/test_sycl_kernel_interface.cpp +++ b/libsyclinterface/tests/test_sycl_kernel_interface.cpp @@ -27,6 +27,7 @@ #include "Config/dpctl_config.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" @@ -201,6 +202,66 @@ TEST_P(TestDPCTLSyclKernelInterface, CheckGetCompileSubGroupSize) EXPECT_TRUE(axpy_csg_sz >= 0); } +TEST_P(TestDPCTLSyclKernelInterface, CheckGetDevices) +{ + auto DVRef = DPCTLKernel_GetDevices(AddKRef); + ASSERT_TRUE(DVRef); + ASSERT_EQ(DPCTLDeviceVector_Size(DVRef), 1ul); + auto D = DPCTLDeviceVector_GetAt(DVRef, 0); + EXPECT_TRUE(DPCTLDevice_AreEq(D, DRef)); + DPCTLDevice_Delete(D); + DPCTLDeviceVector_Delete(DVRef); +} + +TEST_P(TestDPCTLSyclKernelInterface, CheckQueriesForDevice) +{ + EXPECT_EQ(DPCTLKernel_GetWorkGroupSizeForDevice(AddKRef, DRef), + DPCTLKernel_GetWorkGroupSize(AddKRef)); + EXPECT_EQ( + DPCTLKernel_GetPreferredWorkGroupSizeMultipleForDevice(AddKRef, DRef), + DPCTLKernel_GetPreferredWorkGroupSizeMultiple(AddKRef)); + EXPECT_EQ(DPCTLKernel_GetPrivateMemSizeForDevice(AddKRef, DRef), + DPCTLKernel_GetPrivateMemSize(AddKRef)); + EXPECT_EQ(DPCTLKernel_GetMaxNumSubGroupsForDevice(AddKRef, DRef), + DPCTLKernel_GetMaxNumSubGroups(AddKRef)); + EXPECT_EQ(DPCTLKernel_GetMaxSubGroupSizeForDevice(AddKRef, DRef), + DPCTLKernel_GetMaxSubGroupSize(AddKRef)); + EXPECT_EQ(DPCTLKernel_GetCompileNumSubGroupsForDevice(AddKRef, DRef), + DPCTLKernel_GetCompileNumSubGroups(AddKRef)); + EXPECT_EQ(DPCTLKernel_GetCompileSubGroupSizeForDevice(AddKRef, DRef), + DPCTLKernel_GetCompileSubGroupSize(AddKRef)); + EXPECT_GT(DPCTLKernel_GetWorkGroupSizeForDevice(AddKRef, DRef), 0ul); + EXPECT_EQ(DPCTLKernel_GetWorkGroupSizeForDevice(AddKRef, nullptr), 0ul); +} + +TEST_P(TestDPCTLSyclKernelInterface, CheckQueriesForForeignDevice) +{ + auto Devs = DPCTLDeviceMgr_GetDevices(DPCTLSyclDeviceType::DPCTL_ALL); + size_t N = DPCTLDeviceVector_Size(Devs); + size_t NumForeign = 0; + for (size_t i = 0; i < N; ++i) { + auto D = DPCTLDeviceVector_GetAt(Devs, i); + if (!DPCTLDevice_AreEq(D, DRef)) { + ++NumForeign; + EXPECT_EQ(DPCTLKernel_GetWorkGroupSizeForDevice(AddKRef, D), 0ul); + EXPECT_EQ(DPCTLKernel_GetPreferredWorkGroupSizeMultipleForDevice( + AddKRef, D), + 0ul); + EXPECT_EQ(DPCTLKernel_GetPrivateMemSizeForDevice(AddKRef, D), 0ul); + EXPECT_EQ(DPCTLKernel_GetMaxNumSubGroupsForDevice(AddKRef, D), 0u); + EXPECT_EQ(DPCTLKernel_GetMaxSubGroupSizeForDevice(AddKRef, D), 0u); + EXPECT_EQ(DPCTLKernel_GetCompileNumSubGroupsForDevice(AddKRef, D), + 0u); + EXPECT_EQ(DPCTLKernel_GetCompileSubGroupSizeForDevice(AddKRef, D), + 0u); + } + DPCTLDevice_Delete(D); + } + DPCTLDeviceVector_Delete(Devs); + if (NumForeign == 0) + GTEST_SKIP_("Needs a second device"); +} + INSTANTIATE_TEST_SUITE_P(TestKernelInterfaceFunctions, TestDPCTLSyclKernelInterface, ::testing::Values("opencl:gpu:0", "opencl:cpu:0")); @@ -271,3 +332,25 @@ TEST_F(TestDPCTLSyclKernelNullArgs, CheckGetCompileSubGroupSizeNullKRef) ASSERT_EQ(DPCTLKernel_GetCompileSubGroupSize(NullKRef), 0); } + +TEST_F(TestDPCTLSyclKernelNullArgs, CheckGetDevicesNullKRef) +{ + ASSERT_TRUE(DPCTLKernel_GetDevices(Null_KRef) == nullptr); +} + +TEST_F(TestDPCTLSyclKernelNullArgs, CheckQueriesForDeviceNullArgs) +{ + auto DS = DPCTLDefaultSelector_Create(); + auto DRef = DPCTLDevice_CreateFromSelector(DS); + DPCTLDeviceSelector_Delete(DS); + EXPECT_EQ(DPCTLKernel_GetWorkGroupSizeForDevice(Null_KRef, DRef), 0ul); + EXPECT_EQ( + DPCTLKernel_GetPreferredWorkGroupSizeMultipleForDevice(Null_KRef, DRef), + 0ul); + EXPECT_EQ(DPCTLKernel_GetPrivateMemSizeForDevice(Null_KRef, DRef), 0ul); + EXPECT_EQ(DPCTLKernel_GetMaxNumSubGroupsForDevice(Null_KRef, DRef), 0u); + EXPECT_EQ(DPCTLKernel_GetMaxSubGroupSizeForDevice(Null_KRef, DRef), 0u); + EXPECT_EQ(DPCTLKernel_GetCompileNumSubGroupsForDevice(Null_KRef, DRef), 0u); + EXPECT_EQ(DPCTLKernel_GetCompileSubGroupSizeForDevice(Null_KRef, DRef), 0u); + DPCTLDevice_Delete(DRef); +} 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"));