Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ 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)
* `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)
Expand Down
63 changes: 51 additions & 12 deletions dpctl/_sycl_queue.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ from ._backend cimport ( # noqa: E211
DPCTLEvent_Delete,
DPCTLEvent_Wait,
DPCTLFilterSelector_Create,
DPCTLKernel_GetNumArgs,
DPCTLQueue_AreEq,
DPCTLQueue_Copy,
DPCTLQueue_CopyData,
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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.
Expand All @@ -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 <size_t>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 = <void**>malloc(len(args) * sizeof(void*))
Expand Down Expand Up @@ -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 != <size_t>-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:
Expand Down Expand Up @@ -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.
Expand Down
16 changes: 15 additions & 1 deletion dpctl/compiler/_compiler.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -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 == <size_t>-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.
Expand Down
Binary file not shown.
181 changes: 181 additions & 0 deletions dpctl/tests/test_sycl_kernel_submit.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 <sycl/sycl.hpp>

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<int, 1> 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 <sycl/sycl.hpp>

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:
Expand All @@ -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=<dir>` (DPC++ 2026.2) from:
#
# #include <sycl/sycl.hpp>
#
# 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<int, 1> 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])
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
9 changes: 7 additions & 2 deletions libsyclinterface/source/dpctl_sycl_kernel_interface.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,13 @@ size_t DPCTLKernel_GetNumArgs(__dpctl_keep const DPCTLSyclKernelRef KRef)
}

auto sycl_kernel = unwrap<kernel>(KRef);
auto num_args = sycl_kernel->get_info<info::kernel::num_args>();
return static_cast<size_t>(num_args);
try {
auto num_args = sycl_kernel->get_info<info::kernel::num_args>();
return static_cast<size_t>(num_args);
} catch (std::exception const &e) {
error_handler(e, __FILE__, __func__, __LINE__);
return -1;
}
}

void DPCTLKernel_Delete(__dpctl_take DPCTLSyclKernelRef KRef)
Expand Down
Loading