From 350943a5b44f12751b567cd4778cfb144fa2e3c9 Mon Sep 17 00:00:00 2001 From: Nikita Grigorian Date: Wed, 2 Dec 2026 23:31:00 -0800 Subject: [PATCH 1/2] do not abort when the number of kernel arguments can not be queried DPCTLKernel_GetNumArgs returns -1 when the query throws, and SyclKernel.get_num_args raises RuntimeError --- CHANGELOG.md | 1 + dpctl/compiler/_compiler.pyx | 16 +++++++++++++++- .../syclinterface/dpctl_sycl_kernel_interface.h | 3 ++- .../source/dpctl_sycl_kernel_interface.cpp | 9 +++++++-- 4 files changed, 25 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6c7c188b78..058228b141 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -27,6 +27,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 * Removed the deprecated `dpctl.program` submodule, use `dpctl.compiler` instead [gh-2407](https://github.com/IntelPython/dpctl/pull/2407) ### Fixed +* `DPCTLKernel_GetNumArgs` returns -1 instead of aborting the process when the number of arguments can not be queried, and `dpctl.compiler.SyclKernel.get_num_args` raises `RuntimeError` [gh-2425](https://github.com/IntelPython/dpctl/pull/2425) * Removed stale `select_host_device` and `has_host_device` names from `dpctl.__all__`, which made `from dpctl import *` fail with `AttributeError` [gh-2410](https://github.com/IntelPython/dpctl/pull/2410) * A USM allocation that fails now drops the references held for offloaded tasks that have completed, and is attempted once more if that released anything, so that memory only waiting to be given up is not reported as unavailable [gh-2359](https://github.com/IntelPython/dpctl/pull/2359) * `dpctl.SyclPlatform.get_devices` no longer prints Unified Runtime warnings for `device_type="custom"` on non-OpenCL platforms, where custom devices are not supported [gh-2306](https://github.com/IntelPython/dpctl/pull/2306) diff --git a/dpctl/compiler/_compiler.pyx b/dpctl/compiler/_compiler.pyx index 58d7a56310..e91662329c 100644 --- a/dpctl/compiler/_compiler.pyx +++ b/dpctl/compiler/_compiler.pyx @@ -137,8 +137,22 @@ cdef class SyclKernel: def get_num_args(self): """ Returns the number of arguments for this kernel function. + + For a kernel compiled from SYCL source, this is the number of + arguments of the backend kernel, in which a ``sycl::local_accessor`` + parameter is four arguments. + + Raises: + RuntimeError: + If the number of arguments can not be queried. """ - return DPCTLKernel_GetNumArgs(self._kernel_ref) + cdef size_t n = DPCTLKernel_GetNumArgs(self._kernel_ref) + if n == -1: + raise RuntimeError( + "The number of arguments of kernel " + f"'{self._function_name}' can not be queried." + ) + return n cdef DPCTLSyclKernelRef get_kernel_ref(self): """ Returns the ``DPCTLSyclKernelRef`` pointer for this SyclKernel. diff --git a/libsyclinterface/include/syclinterface/dpctl_sycl_kernel_interface.h b/libsyclinterface/include/syclinterface/dpctl_sycl_kernel_interface.h index d8a69afb1d..fd0ba14dfe 100644 --- a/libsyclinterface/include/syclinterface/dpctl_sycl_kernel_interface.h +++ b/libsyclinterface/include/syclinterface/dpctl_sycl_kernel_interface.h @@ -45,7 +45,8 @@ DPCTL_C_EXTERN_C_BEGIN * @param KRef DPCTLSyclKernelRef pointer to a SYCL * interoperability kernel. * @return Returns the number of arguments for the interoperability - * kernel. + * kernel, or -1 if KRef is NULL or the number of arguments can + * not be queried. * @ingroup KernelInterface */ DPCTL_API diff --git a/libsyclinterface/source/dpctl_sycl_kernel_interface.cpp b/libsyclinterface/source/dpctl_sycl_kernel_interface.cpp index e035ea7000..f5bcfae8c5 100644 --- a/libsyclinterface/source/dpctl_sycl_kernel_interface.cpp +++ b/libsyclinterface/source/dpctl_sycl_kernel_interface.cpp @@ -53,8 +53,13 @@ size_t DPCTLKernel_GetNumArgs(__dpctl_keep const DPCTLSyclKernelRef KRef) } auto sycl_kernel = unwrap(KRef); - auto num_args = sycl_kernel->get_info(); - return static_cast(num_args); + try { + auto num_args = sycl_kernel->get_info(); + return static_cast(num_args); + } catch (std::exception const &e) { + error_handler(e, __FILE__, __func__, __LINE__); + return -1; + } } void DPCTLKernel_Delete(__dpctl_take DPCTLSyclKernelRef KRef) From 83c01c8a177b96d867fcfc063f5d9775f596cc62 Mon Sep 17 00:00:00 2001 From: Nikita Grigorian Date: Wed, 2 Dec 2026 23:31:02 -0800 Subject: [PATCH 2/2] count a LocalAccessor as up to 4 kernel arguments a sycl::local_accessor is 4 arguments in a kernel compiled from SYCL source, so the argument count check rejected such kernels; the LocalAccessor docstring now describes passing a split local accessor to SPIR-V from SYCL --- CHANGELOG.md | 1 + dpctl/_sycl_queue.pyx | 63 ++++-- .../local-accessor-free-function-kernel.spv | Bin 0 -> 2060 bytes dpctl/tests/test_sycl_kernel_submit.py | 181 ++++++++++++++++++ 4 files changed, 233 insertions(+), 12 deletions(-) create mode 100644 dpctl/tests/input_files/local-accessor-free-function-kernel.spv diff --git a/CHANGELOG.md b/CHANGELOG.md index 058228b141..87314af851 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -27,6 +27,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 * Removed the deprecated `dpctl.program` submodule, use `dpctl.compiler` instead [gh-2407](https://github.com/IntelPython/dpctl/pull/2407) ### Fixed +* `dpctl.SyclQueue.submit_async` and `dpctl.SyclQueue.submit` no longer reject kernels compiled from SYCL source that take a `sycl::local_accessor`: a `dpctl.LocalAccessor` is counted as up to 4 kernel arguments, and the arguments of kernels whose number of arguments can not be queried are not checked [gh-2425](https://github.com/IntelPython/dpctl/pull/2425) * `DPCTLKernel_GetNumArgs` returns -1 instead of aborting the process when the number of arguments can not be queried, and `dpctl.compiler.SyclKernel.get_num_args` raises `RuntimeError` [gh-2425](https://github.com/IntelPython/dpctl/pull/2425) * Removed stale `select_host_device` and `has_host_device` names from `dpctl.__all__`, which made `from dpctl import *` fail with `AttributeError` [gh-2410](https://github.com/IntelPython/dpctl/pull/2410) * A USM allocation that fails now drops the references held for offloaded tasks that have completed, and is attempted once more if that released anything, so that memory only waiting to be given up is not reported as unavailable [gh-2359](https://github.com/IntelPython/dpctl/pull/2359) diff --git a/dpctl/_sycl_queue.pyx b/dpctl/_sycl_queue.pyx index 07fcd0cf20..84de3e52b7 100644 --- a/dpctl/_sycl_queue.pyx +++ b/dpctl/_sycl_queue.pyx @@ -34,6 +34,7 @@ from ._backend cimport ( # noqa: E211 DPCTLEvent_Delete, DPCTLEvent_Wait, DPCTLFilterSelector_Create, + DPCTLKernel_GetNumArgs, DPCTLQueue_AreEq, DPCTLQueue_Copy, DPCTLQueue_CopyData, @@ -174,6 +175,19 @@ cdef class LocalAccessor: Python class for specifying the dimensionality and type of a ``sycl::local_accessor``, to be used as a kernel argument type. + A ``LocalAccessor`` is a ``sycl::local_accessor`` parameter of a kernel + compiled from SYCL source, or a ``local`` pointer parameter of an OpenCL C + kernel. In a kernel compiled from SYCL to SPIR-V, a + ``sycl::local_accessor`` parameter is four arguments: the pointer to the + local memory, the access range, the memory range and the offset. Each + range and the offset is one argument of ``N`` ``size_t`` for an + ``N``-dimensional accessor. Pass the ``LocalAccessor`` as the pointer and + the others explicitly, e.g. for an accessor of shape ``(n, m)``:: + + rng = dpctl.RawKernelArg(np.array([n, m], dtype=np.uintp)) + off = dpctl.RawKernelArg(np.array([0, 0], dtype=np.uintp)) + [dpctl.LocalAccessor("i4", (n, m)), rng, rng, off, ...] + Args: dtype (str): the data type of the local memory. @@ -1540,8 +1554,11 @@ cdef class SyclQueue(_SyclQueue): Raises: ValueError: - If the number of arguments in ``args`` differs from the number - of arguments the kernel takes. + If the number of arguments in ``args`` does not match the + number of arguments the kernel takes. A + :class:`dpctl.LocalAccessor` may stand for up to 4 arguments, + and the number of arguments of a kernel that can not be + queried is not checked. SyclKernelSubmitError: If ``kernel`` does not reference a ``sycl::kernel``, or if submission to the queue fails. @@ -1556,21 +1573,16 @@ cdef class SyclQueue(_SyclQueue): cdef size_t nGS = len(gS) cdef size_t nLS = len(lS) if lS is not None else 0 cdef size_t nDE = len(dEvents) if dEvents is not None else 0 + cdef size_t nArgs = len(args) cdef size_t nKA = 0 + cdef size_t nLA = 0 + cdef size_t i if kernel.get_kernel_ref() is NULL: raise SyclKernelSubmitError( "The kernel can not be submitted, as it does not reference a " "``sycl::kernel``." ) - # the backend can not detect that the correct number of arguments were - # provided, so check it here - nKA = kernel.num_args - if len(args) != nKA: - raise ValueError( - f"Kernel '{kernel.get_function_name()}' takes {nKA} " - f"argument(s), got {len(args)}." - ) # Allocate the arrays to be sent to DPCTLQueue_Submit kargs = malloc(len(args) * sizeof(void*)) @@ -1611,6 +1623,30 @@ cdef class SyclQueue(_SyclQueue): free(depEvents) raise TypeError("Unsupported type for a kernel argument") + # the backend may not detect missing arguments, so check the number + # of arguments here. In a kernel compiled from SYCL source, a + # LocalAccessor is 4 arguments, while it is 1 in other kernels. + nKA = DPCTLKernel_GetNumArgs(kernel.get_kernel_ref()) + if nKA != -1: + for i in range(nArgs): + if kargty[i] == _arg_data_type._LOCAL_ACCESSOR: + nLA += 1 + if nArgs > nKA or nArgs + 3 * nLA < nKA: + free(kargs) + free(kargty) + free(depEvents) + msg = ( + f"Kernel '{kernel.get_function_name()}' takes {nKA} " + f"argument(s), got {nArgs}." + ) + if nLA > 0: + msg += ( + f" {nLA} of them are dpctl.LocalAccessor, which is 4 " + "arguments in a kernel compiled from SYCL source and " + "1 in other kernels." + ) + raise ValueError(msg) + if lS is None: ret = self._populate_range(gRange, gS, nGS) if ret == -1: @@ -1718,8 +1754,11 @@ cdef class SyclQueue(_SyclQueue): Raises: ValueError: - If the number of arguments in ``args`` differs from the number - of arguments the kernel takes. + If the number of arguments in ``args`` does not match the + number of arguments the kernel takes. A + :class:`dpctl.LocalAccessor` may stand for up to 4 arguments, + and the number of arguments of a kernel that can not be + queried is not checked. SyclKernelSubmitError: If ``kernel`` does not reference a ``sycl::kernel``, or if submission to the queue fails. diff --git a/dpctl/tests/input_files/local-accessor-free-function-kernel.spv b/dpctl/tests/input_files/local-accessor-free-function-kernel.spv new file mode 100644 index 0000000000000000000000000000000000000000..20bc522169e4c8774f25c37df1c65b926f02c80f GIT binary patch literal 2060 zcmZ{l+fEZv6oz*x=Q9H00dWvT5k>I;rbc5Vp%O_@N$_$~%Rm~&wwV?pUKuaE_7S}G z&ZqD>d<<_;|8FxZ)>1cFS?7PR!=93Do9S{c;|5))d*F`Gh--8065$;w?@W1L%8$mK z>vdgj^Tk&9{MoB8dRL8#^{`N@?Z1r_)2Gag_(nAf26tWQFKF4Y^_6=-j9% z3~PtQINXbpaukPgrC5l=La`XtYLz6l`Z|bLv94Q`)gLu}`IM25+dNLSlpKUl_e*ho zt-KDOZ#N*!BT7pJLsV42J0ol0Rqv;@p+~J3SN1k;})!1L^F6yU|DG=}GPE5FhnUN*WTk zTBj7vH-iniUmP90VR7CQHuMp3W&_T&wsuOKJHRK_h`2G`z*~N(Jnkls+DvB$jXL)< z>bwc`In@Nt1<{gFxR2jE4)-t1&;7hbWNP4@namq8nSCQuAG`gj8hP7~^z|~cb0X?w zHi77+G-SSUe4MX}#dc9dP59XFH^oxtvb;G|T8+|w9&&Y<4WB8XPgO3k< z!?+@uSv6zK%7%|)7*{2Ofe(z2X+PH_gOA_p<~IU+Afj&cRmC%_>mufbpE}t8ya+pW zuwP=?1K$g~U>*0=Me1V7_ v(7&fW-;+#Dd_yZ~t@kBUD>-Icl8l{r>vdT&cI$z@=pDP+j$B6n`!ntj?ZnQ~ literal 0 HcmV?d00001 diff --git a/dpctl/tests/test_sycl_kernel_submit.py b/dpctl/tests/test_sycl_kernel_submit.py index 9c57186d81..048031a8e0 100644 --- a/dpctl/tests/test_sycl_kernel_submit.py +++ b/dpctl/tests/test_sycl_kernel_submit.py @@ -343,6 +343,116 @@ def test_submit_local_accessor_arg(): expected = np.arange(1, x.size + 1, dtype=x.dtype) * (2 * lws) assert np.all(res == expected) + assert krn.num_args == 2 + la = dpctl.LocalAccessor("i8", (lws,)) + with pytest.raises(ValueError): + q.submit_async(krn, [x_usm], [gws], [lws]) + with pytest.raises(ValueError, match="LocalAccessor"): + q.submit_async(krn, [x_usm, la, x_usm], [gws], [lws]) + + +_local_accessor_sycl_source = """ +#include + +namespace syclext = sycl::ext::oneapi; +namespace syclexp = sycl::ext::oneapi::experimental; + +extern "C" SYCL_EXTERNAL +SYCL_EXT_ONEAPI_FUNCTION_PROPERTY((syclexp::nd_range_kernel<1>)) +void reverse_in_group(sycl::local_accessor lmem, int *x, int scale) { + auto item = syclext::this_work_item::get_nd_item<1>(); + size_t lid = item.get_local_linear_id(); + size_t lws = item.get_local_range(0); + lmem[lid] = x[item.get_global_linear_id()]; + sycl::group_barrier(item.get_group()); + x[item.get_global_linear_id()] = scale * lmem[lws - 1 - lid]; +} +""" + + +@pytest.mark.parametrize("backend", ["opencl", "level_zero"]) +def test_submit_local_accessor_arg_sycl_source(backend): + try: + q = dpctl.SyclQueue(backend) + except dpctl.SyclQueueCreationError: + pytest.skip(f"No {backend} queue is available") + if not dpc.is_sycl_source_compilation_available(): + pytest.skip("SYCL source compilation extension not available") + if not q.get_sycl_device().can_compile("sycl"): + pytest.skip("SYCL source compilation not supported") + kb = dpc.create_kernel_bundle_from_sycl_source( + q, _local_accessor_sycl_source + ) + krn = kb.get_sycl_kernel("reverse_in_group") + + lws = 16 + gws = lws * 4 + x = np.arange(gws, dtype="i4") + x_usm = dpm.MemoryUSMDevice(x.nbytes, queue=q) + la = dpctl.LocalAccessor("i4", (lws,)) + q.memcpy(dest=x_usm, src=x, count=x.nbytes) + q.submit(krn, [la, x_usm, ctypes.c_int(3)], [gws], [lws]).wait() + res = np.empty_like(x) + q.memcpy(dest=res, src=x_usm, count=x.nbytes) + expected = 3 * x.reshape(-1, lws)[:, ::-1].ravel() + assert np.array_equal(res, expected) + + # the local accessor is 4 of the 6 arguments + assert krn.num_args == 6 + with pytest.raises(ValueError, match="LocalAccessor"): + q.submit_async(krn, [la, x_usm], [gws], [lws]) + # within what a LocalAccessor may stand for, so not checked by dpctl; the + # backend rejects the extra argument + with pytest.raises(dpctl.SyclKernelSubmitError): + q.submit_async( + krn, + [la, x_usm, ctypes.c_int(3), ctypes.c_int(3)], + [gws], + [lws], + ) + + +_fill_sycl_source = """ +#include + +namespace syclexp = sycl::ext::oneapi::experimental; + +extern "C" SYCL_EXTERNAL +SYCL_EXT_ONEAPI_FUNCTION_PROPERTY((syclexp::nd_range_kernel<1>)) +void fill(int *x, int v) { + auto it = sycl::ext::oneapi::this_work_item::get_nd_item<1>(); + x[it.get_global_linear_id()] = v; +} +""" + + +@pytest.mark.parametrize("backend", ["opencl", "level_zero"]) +def test_submit_wrong_number_of_args_sycl_source(backend): + try: + q = dpctl.SyclQueue(backend) + except dpctl.SyclQueueCreationError: + pytest.skip(f"No {backend} queue is available") + if not dpc.is_sycl_source_compilation_available(): + pytest.skip("SYCL source compilation extension not available") + if not q.get_sycl_device().can_compile("sycl"): + pytest.skip("SYCL source compilation not supported") + krn = dpc.create_kernel_bundle_from_sycl_source( + q, _fill_sycl_source + ).get_sycl_kernel("fill") + assert krn.num_args == 2 + + x_usm = dpm.MemoryUSMDevice(64 * 4, queue=q) + with pytest.raises(ValueError): + q.submit_async(krn, [x_usm], [64], [16]) + with pytest.raises(ValueError): + q.submit_async( + krn, [x_usm, ctypes.c_int(1), ctypes.c_int(2)], [64], [16] + ) + q.submit(krn, [x_usm, ctypes.c_int(7)], [64], [16]).wait() + res = np.empty(64, dtype="i4") + q.memcpy(dest=res, src=x_usm, count=res.nbytes) + assert np.all(res == 7) + def test_submit_wrong_number_of_args(): try: @@ -367,3 +477,74 @@ def test_submit_wrong_number_of_args(): [x_usm, x_usm, x_usm, ctypes.c_int(2), ctypes.c_int(3)], [n], ) + + +# The kernel in local-accessor-free-function-kernel.spv was generated with +# `icpx -fsycl -save-offload-code=` (DPC++ 2026.2) from: +# +# #include +# +# namespace syclexp = sycl::ext::oneapi::experimental; +# namespace syclext = sycl::ext::oneapi; +# +# extern "C" SYCL_EXTERNAL +# SYCL_EXT_ONEAPI_FUNCTION_PROPERTY((syclexp::nd_range_kernel<1>)) +# void local_accessor_kernel(sycl::local_accessor lmem, int *x) { +# auto item = syclext::this_work_item::get_nd_item<1>(); +# size_t lid = item.get_local_linear_id(); +# lmem[lid] = x[item.get_global_linear_id()]; +# sycl::group_barrier(item.get_group()); +# x[item.get_global_linear_id()] = +# lmem[item.get_local_range(0) - 1 - lid]; +# } +# +# int main() { return 0; } +def test_submit_local_accessor_arg_spirv_from_sycl(): + try: + q = dpctl.SyclQueue() + except dpctl.SyclQueueCreationError: + pytest.skip("Could not create default queue") + fn = get_spirv_abspath("local-accessor-free-function-kernel.spv") + with open(fn, "br") as f: + spirv_bytes = f.read() + kb = dpc.create_kernel_bundle_from_spirv(q, spirv_bytes) + krn = kb.get_sycl_kernel("__sycl_kernel_local_accessor_kernel") + # the local accessor is the pointer, access range, memory range and + # offset in this SPIR-V + assert krn.num_args == 5 + + lws = 16 + gws = lws * 4 + x = np.arange(gws, dtype="i4") + x_usm = dpm.MemoryUSMDevice(x.nbytes, queue=q) + q.memcpy(dest=x_usm, src=x, count=x.nbytes) + la = dpctl.LocalAccessor("i4", (lws,)) + with pytest.raises(ValueError, match="LocalAccessor"): + q.submit_async(krn, [la], [gws], [lws]) + with pytest.raises(ValueError) as e: + q.submit_async(krn, [x_usm], [gws], [lws]) + assert "LocalAccessor" not in str(e.value) + + sz = ctypes.c_size_t + q.submit(krn, [la, sz(lws), sz(lws), sz(0), x_usm], [gws], [lws]).wait() + res = np.empty_like(x) + q.memcpy(dest=res, src=x_usm, count=x.nbytes) + assert np.array_equal(res, x.reshape(-1, lws)[:, ::-1].ravel()) + + +def test_submit_wrong_number_of_args_opencl_source(): + try: + q = dpctl.SyclQueue("opencl") + except dpctl.SyclQueueCreationError: + pytest.skip("OpenCL queue could not be created") + kb = dpc.create_kernel_bundle_from_source( + q, "kernel void set(global int *a, int v) { a[0] = v; }" + ) + krn = kb.get_sycl_kernel("set") + assert krn.num_args == 2 + + x_usm = dpm.MemoryUSMDevice(4, queue=q) + with pytest.raises(ValueError): + q.submit_async(krn, [x_usm], [1]) + with pytest.raises(ValueError): + q.submit_async(krn, [x_usm, ctypes.c_int(1), ctypes.c_int(2)], [1])