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: 1 addition & 1 deletion .github/workflows/generate-coverage.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ jobs:
- name: Install dpctl dependencies
shell: bash -l {0}
run: |
pip install numpy cython setuptools"<80" pytest pytest-cov scikit-build"<1.0" cmake coverage[toml] versioneer[toml]==0.29
pip install numpy cython setuptools"<80" pytest pytest-cov ml_dtypes scikit-build"<1.0" cmake coverage[toml] versioneer[toml]==0.29

- name: Build dpctl with coverage
shell: bash -l {0}
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/os-llvm-sycl-build-windows.yml
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ jobs:
run: |
$ErrorActionPreference = 'Stop'
$PSNativeCommandUseErrorActionPreference = $true
python -m pip install numpy cython "setuptools<80" pytest "scikit-build<1.0" cmake ninja "versioneer[toml]==0.29"
python -m pip install numpy cython "setuptools<80" pytest ml_dtypes "scikit-build<1.0" cmake ninja "versioneer[toml]==0.29"

- name: Build GTest
shell: pwsh
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/os-llvm-sycl-build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ jobs:
- name: Install dpctl dependencies
shell: bash -l {0}
run: |
pip install numpy cython setuptools"<80" pytest scikit-build"<1.0" cmake ninja versioneer[toml]==0.29
pip install numpy cython setuptools"<80" pytest ml_dtypes scikit-build"<1.0" cmake ninja versioneer[toml]==0.29

- name: Create set_allvars.sh
shell: bash -l {0}
Expand Down
9 changes: 9 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [dev] - XXX. XX, XXXX

**NOTE**: This release contains breaking changes:

* The value of the `DPCTL_UNSUPPORTED_KERNEL_ARG` enumerator of `DPCTLKernelArgType` increased by one, as `DPCTL_BYTES16_T` was added before it [gh-2335](https://github.com/IntelPython/dpctl/pull/2335)

### Added
* Added `dpctl.SyclQueue.keep_args_alive` method, which keeps Python objects alive until the work on that queue using them completes [gh-2359](https://github.com/IntelPython/dpctl/pull/2359)
* Added `add_event` and `add_cleanup_event` methods and `cleanup_events` and `num_cleanup_events` properties to the order manager, for tracking the events that gate the release of objects used by offloaded tasks [gh-2359](https://github.com/IntelPython/dpctl/pull/2359)
Expand All @@ -17,13 +21,18 @@ 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)
* `dpctl.SyclQueue.submit` and `dpctl.SyclQueue.submit_async` accept NumPy scalars of any data type whose values are plain bytes, including structured data types and those of `ml_dtypes` such as `bfloat16` and `complex32` [gh-2335](https://github.com/IntelPython/dpctl/pull/2335)
* Added `DPCTL_BYTES16_T` enumerator to `DPCTLKernelArgType` for 16-byte scalar and local accessor kernel arguments [gh-2335](https://github.com/IntelPython/dpctl/pull/2335)
* Added a `sycl::ext::oneapi::bfloat16` type caster to `dpctl4pybind11.hpp`, defined when the compiler provides the `sycl_ext_oneapi_bfloat16` extension [gh-2335](https://github.com/IntelPython/dpctl/pull/2335)

### Changed
* Object lifetime during offload is now managed by a list of releases deferred until the events that gate them have completed, rather than by a `host_task`. `dpctl` keeps one thread for looking over the list and running the releases that have come due, started by the first release deferred and again in the child of a `fork`, which takes the GIL to do so and lets a release call into the interpreter and free USM allocations [gh-2359](https://github.com/IntelPython/dpctl/pull/2359)
* `import_dpctl()` now returns 0 on success and -1 with a Python exception set on failure, and `dpctl4pybind11.hpp` raises that exception rather than failing on the first C-API call [gh-2359](https://github.com/IntelPython/dpctl/pull/2359)
* The event returned by `dpctl.SyclQueue.keep_args_alive`, `dpctl::utils::keep_args_alive` and `dpctl.SyclQueue._submit_keep_args_alive` is now for an empty kernel that gates the deferred release rather than for a `host_task` that performs it, so its completion means that the objects are no longer in use rather than that they have been released [gh-2359](https://github.com/IntelPython/dpctl/pull/2359)
* `dpctl.utils.SequentialOrderManager[q].submitted_events` includes the queue's last event for in-order queues when `sycl_ext_oneapi_in_order_queue_events` is available, and `wait()` waits for all work on an in-order queue [gh-2299](https://github.com/IntelPython/dpctl/pull/2299)
* 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)
* `dpctl.SyclQueue.copy`, `dpctl.SyclQueue.copy_async`, `dpctl.SyclQueue.fill`, `dpctl.SyclQueue.fill_async`, `dpctl.LocalAccessor`, `dpctl.WorkGroupMemory`, and `dpctl.compiler.SpecializationConstant` accept a data type in any form `numpy.dtype` accepts, for any data type whose values are plain bytes, rather than a fixed set of type strings [gh-2335](https://github.com/IntelPython/dpctl/pull/2335)
* `dpctl.compiler.SpecializationConstant` accepts NumPy scalars [gh-2335](https://github.com/IntelPython/dpctl/pull/2335)

### 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)
Expand Down
2 changes: 1 addition & 1 deletion ci/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
| `hooks.py` | The workflow's test jobs: installs one package into a clean environment with the requirements in `config.yml`, and runs `test.py`. A conda package's environment comes from conda-forge; a wheel's has only Python from conda-forge and everything else from PyPI. Of the runner's environment the tests see only what `KEEP` lists, which has `GH_CI_DEVICE` and `ONEAPI_DEVICE_SELECTOR`. |
| `install_icx.py` | Installs Intel's icx, which the conda recipe builds with too, and the Level Zero headers for the wheel builds, which `[tool.cibuildwheel]`'s `before-all` in `../pyproject.toml` runs: icx from conda-forge on Windows and from Intel's yum repository on Linux, the headers from a pinned tag of their GitHub repository. It holds the compiler version and that tag for both platforms, and prints the compiler version for `build.py`. |
| `package_spec.py` | Prints the specs the examples jobs install the built conda package with: its exact build, and the Python of its ABI. |
| `config.yml` | Names the workflow that builds the packages, its artifact names, and what the tests and benchmarks need. |
| `config.yml` | Names the workflow that builds the packages, its artifact names, and what the tests and benchmarks need. A test requirement written `{spec: SPEC, skip: [VERSION, ...]}` is not installed on those Python versions, for a package that has no build for them yet. |
| `test.py` | Runs the installed package's test suite with pytest. |
| `benchmark.py` | Runs the asv suite in `../benchmarks/` against the installed package. |

Expand Down
7 changes: 5 additions & 2 deletions ci/config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,12 @@ artifacts:
wheel: "dpctl {platform} Wheels Python {python}"
test:
# The compilers build the extensions two tests compile; intel-opencl-rt is the OpenCL CPU device.
requires: [pytest, cython, setuptools, intel-opencl-rt, c-compiler, cxx-compiler]
# An entry {spec: SPEC, skip: [VERSION, ...]} is left out on those Python versions.
# conda-forge has no ml_dtypes for 3.15t.
requires:
[pytest, cython, setuptools, intel-opencl-rt, c-compiler, cxx-compiler, {spec: ml_dtypes, skip: ["3.15t"]}]
# A wheel's environment has the system's compilers only, and the SYCL runtime comes with the wheel.
wheel_requires: [pytest, cython, setuptools, intel-opencl-rt]
wheel_requires: [pytest, cython, setuptools, intel-opencl-rt, ml_dtypes]
benchmark:
# PyYAML, which asv needs, has no PyPI wheel for every Python the recipe declares.
requires: [numpy, intel-opencl-rt, pyyaml]
Expand Down
74 changes: 60 additions & 14 deletions ci/hooks.py
Original file line number Diff line number Diff line change
Expand Up @@ -196,10 +196,29 @@ def test_python(version: str) -> str:
return f'3.{minor}.* *_cp3{minor}{"t" if threaded else ""}'


def test_requirements() -> tuple[list[str], list[str], list[str] | None]:
def requirement(value: object, key: str) -> tuple[str, list[str]]:
"""(spec, skipped versions) of one ci/config.yml test requirement."""
if isinstance(value, str):
return value, []
if (
isinstance(value, dict)
and set(value) == {"spec", "skip"}
and isinstance(value["spec"], str)
and isinstance(value["skip"], list)
and all(isinstance(v, str) for v in value["skip"])
):
return value["spec"], value["skip"]
raise HookError(
f"ci/config.yml: test.{key} entries must be package specs or "
f"{{spec: SPEC, skip: [VERSION, ...]}}, not {value!r}"
)


def test_requirements() -> dict[str, list[tuple[str, list[str]]] | None]:
"""
The conda-forge and pip packages ci/config.yml installs next to the
artifact, and a wheel's PyPI requirements, None when it gives none.
artifact, and a wheel's PyPI requirements, None when it gives none, each
as (spec, versions it skips) by key.
"""
text = (ROOT / "ci" / "config.yml").read_text(encoding="utf-8")
if PYYAML is not None:
Expand All @@ -209,18 +228,38 @@ def test_requirements() -> tuple[list[str], list[str], list[str] | None]:
else:
raise HookError("reading ci/config.yml needs PyYAML or ruamel.yaml")
test = (config or {}).get("test") or {}
lists = []
lists = {}
for key in ("requires", "pip_requires", "wheel_requires"):
values = test.get(key)
if values is not None and (
not isinstance(values, list)
or not all(isinstance(v, str) for v in values)
):
if values is not None and not isinstance(values, list):
raise HookError(f"ci/config.yml: test.{key} must be a list")
lists[key] = (
None if values is None else [requirement(v, key) for v in values]
)
return lists


def specs_for(
requirements: list[tuple[str, list[str]]] | None,
key: str,
python: str,
declared: dict[str, matrix.Python],
) -> list[str]:
"""The specs of a test.KEY list that apply to one Python version."""
specs = []
for spec, skip in requirements or []:
unknown = [version for version in skip if version not in declared]
if unknown:
raise HookError(
f"ci/config.yml: test.{key} must be a list of package specs"
f"ci/config.yml: test.{key}: {spec} skips "
f'{", ".join(unknown)}, which is not declared'
)
lists.append(values)
return lists[0] or [], lists[1] or [], lists[2]
if python in skip:
print(f"hooks: {spec} is skipped on Python {python}", flush=True)
summarize([f"test.{key} skips {spec} on Python {python}", ""])
else:
specs.append(spec)
return specs


def exact_spec(package: Path) -> str:
Expand Down Expand Up @@ -311,24 +350,31 @@ def install(args: argparse.Namespace) -> Path:
)
if not packages:
raise HookError(f"{args.artifacts} holds no {args.kind} package")
requires, pip_requires, wheel_requires = test_requirements()
lists = test_requirements()

def specs(key: str) -> list[str]:
return specs_for(lists[key], key, args.python, declared)

env_dir = args.work / "env"
pip = [str(env_python(env_dir)), "-m", "pip", "install", "--no-input"]
python = f"python {test_python(args.python)}"
if args.kind == "wheel":
conda_create(env_dir, python, "pip")
wheel_specs = requires if wheel_requires is None else wheel_requires
run([*pip, *map(str, packages), *wheel_specs])
key = (
"requires" if lists["wheel_requires"] is None else "wheel_requires"
)
run([*pip, *map(str, packages), *specs(key)])
else:
channel = args.work / "channel"
stage_channel(packages, channel)
conda_create(
env_dir,
python,
*requires,
*specs("requires"),
*map(exact_spec, packages),
channels=(channel.as_uri(),),
)
pip_requires = specs("pip_requires")
if pip_requires:
run([*pip, *pip_requires])
return env_dir
Expand Down
34 changes: 34 additions & 0 deletions docs/doc_sources/api_reference/dpctl/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,40 @@
* - :py:class:`dpctl.global_mem_cache_type`
- An :class:`enum.Enum` of global memory cache types for a device.

.. rubric:: Data types of kernel arguments

.. _dpctl_data_types:

Every :py:mod:`dpctl` function or class taking a data type, such as
:py:meth:`dpctl.SyclQueue.copy`, :py:meth:`dpctl.SyclQueue.fill`,
:py:class:`dpctl.LocalAccessor`, :py:class:`dpctl.WorkGroupMemory` and
:py:class:`dpctl.compiler.SpecializationConstant`, accepts it in any form
:py:class:`numpy.dtype` accepts, e.g. ``"f4"``, ``"float32"``,
:py:class:`numpy.float32` or a :py:class:`numpy.dtype`. Any data type whose
values are plain bytes is supported, including structured data types and data
types registered with :py:mod:`numpy` by other packages, such as those of
``ml_dtypes``. Extended precision ``numpy.longdouble`` is not supported.

A NumPy scalar kernel argument is passed as its bytes, so the kernel determines
how they are interpreted.

.. code-block:: python

import ml_dtypes

bf16 = ml_dtypes.bfloat16(1.5) # sycl::ext::oneapi::bfloat16
c = ml_dtypes.complex32(1 - 2j) # std::complex<sycl::half>

q.submit(kernel, [x_usm, bf16, c], [n])

Scalars of 1, 2, 4, 8 or 16 bytes are always supported. Scalars of other sizes,
such as a structured scalar matching a C++ ``struct``, require the
``raw_kernel_arg`` DPC++ extension.

Python scalars are not supported as kernel arguments, as the kernel parameter
types are not known. Pass a NumPy scalar of the parameter type instead, e.g.
``numpy.float32(1.5)`` for a ``float`` parameter.

.. rubric:: Exceptions

.. autosummary::
Expand Down
23 changes: 23 additions & 0 deletions docs/doc_sources/api_reference/dpctl_pybind11.rst
Original file line number Diff line number Diff line change
Expand Up @@ -44,4 +44,27 @@ We can now use it from Python:
# device descriptor
print(dev.name)

Type caster for ``bfloat16``
----------------------------

When the DPC++ compiler used to compile an extension provides the
``sycl_ext_oneapi_bfloat16`` extension, ``dpctl4pybind11.hpp`` defines the macro
``DPCTL_HAS_BFLOAT16`` and a type caster connecting
``sycl::ext::oneapi::bfloat16`` to Python. A function taking such an argument
accepts any Python object convertible to a :py:class:`float`, such as an
``ml_dtypes.bfloat16`` scalar. Its value is rounded to C++ ``float`` and then
to ``bfloat16``, so it is not always the nearest ``bfloat16``. A returned
``bfloat16`` becomes a Python :py:class:`float`.

Since the caster is only defined when the extension is available, code that has
to build with compilers that do not provide it should guard its use:

.. code-block:: c++

#ifdef DPCTL_HAS_BFLOAT16
sycl::ext::oneapi::bfloat16 round_trip(sycl::ext::oneapi::bfloat16 value) {
return value;
}
#endif

.. _pybind11_url: https://pybind11.readthedocs.io/
2 changes: 2 additions & 0 deletions docs/doc_sources/known_words.txt
Original file line number Diff line number Diff line change
Expand Up @@ -81,3 +81,5 @@ profiler
keepdims
broadcasted
broadcastable
bfloat
dtypes
1 change: 1 addition & 0 deletions dpctl/_backend.pxd
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ cdef extern from "syclinterface/dpctl_sycl_enum_types.h":
_LOCAL_ACCESSOR "DPCTL_LOCAL_ACCESSOR",
_WORK_GROUP_MEMORY "DPCTL_WORK_GROUP_MEMORY"
_RAW_KERNEL_ARG "DPCTL_RAW_KERNEL_ARG"
_BYTES16 "DPCTL_BYTES16_T"

ctypedef enum _queue_property_type "DPCTLQueuePropertyType":
_DEFAULT_PROPERTY "DPCTL_DEFAULT_PROPERTY"
Expand Down
100 changes: 100 additions & 0 deletions dpctl/_dtype_utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
# 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.

"""Data type handling shared by the dpctl functions taking a data type."""

import struct

import numpy as np

# kinds of NumPy data types whose values are not plain bytes
_NON_POD_KINDS = frozenset("OSUMmT")

# extended precision types, which devices do not support
_EXTENDED_PRECISION_NUMS = frozenset(
np.dtype(t).num
for t in (np.longdouble, np.clongdouble)
if np.finfo(t).nmant > np.finfo(np.float64).nmant
)

# struct formats of the data types whose values are range checked when packed
_STRUCT_FORMATS = {
("b", 1): "?",
("i", 1): "b",
("i", 2): "h",
("i", 4): "i",
("i", 8): "q",
("u", 1): "B",
("u", 2): "H",
("u", 4): "I",
("u", 8): "Q",
("f", 2): "e",
("f", 4): "f",
("f", 8): "d",
("c", 8): "ff",
("c", 16): "dd",
}


def is_supported_dtype(dt):
"""Returns whether values of :class:`numpy.dtype` ``dt`` can be used on a
device."""
return not (
dt.hasobject
or dt.kind in _NON_POD_KINDS
or dt.itemsize == 0
or dt.num in _EXTENDED_PRECISION_NUMS
)


def as_dtype(dtype):
"""Returns ``numpy.dtype(dtype)``.

Raises:
ValueError: if ``dtype`` is ``None``, not a supported data type, or not
in native byte order.
"""
if dtype is None:
raise ValueError("dtype must not be None")
try:
dt = np.dtype(dtype)
Comment thread
ndgrigorian marked this conversation as resolved.
Resolved
except TypeError:
raise ValueError(f"Unrecognized dtype '{dtype}'") from None
if not is_supported_dtype(dt):
raise ValueError(f"Unsupported dtype '{dt}'")
if not dt.isnative:
raise ValueError(f"dtype '{dt}' is not in native byte order")
return dt


def pack_value(value, dt):
"""Returns the bytes of ``value`` converted to :class:`numpy.dtype` ``dt``.

Raises:
ValueError: if ``value`` can not be represented in ``dt``.
"""
fmt = _STRUCT_FORMATS.get((dt.kind, dt.itemsize))
try:
if fmt is None:
return np.asarray(value, dtype=dt).tobytes()
if dt.kind == "c":
cval = complex(value)
return struct.pack("=" + fmt, cval.real, cval.imag)
return struct.pack("=" + fmt, value)
except (struct.error, OverflowError, TypeError, ValueError) as e:
raise ValueError(
f"Value {value!r} cannot be represented as dtype '{dt}': {e}"
) from None
Loading
Loading