From f12aa2439dfaac451e4a1eb7580d8d7ce51bf2b9 Mon Sep 17 00:00:00 2001 From: Nikita Grigorian Date: Sun, 1 Nov 2026 22:16:22 -0800 Subject: [PATCH 1/7] Implement filter selector strings without the DPC++ extension DPC++ 2026.2 deprecates sycl::ext::oneapi::filter_selector. dpctl_filter_selector now parses filter strings and matches devices itself, keeping the extension's syntax and default_selector_v ranking. Device numbers are resolved once at construction, counted the same way as SyclDevice.filter_string. The selector is now stateless, so DPCTLDeviceSelector_Score gives correct results for numbered filters, and overlapping filters such as "0,1" select devices 0 and 1. --- .../dpctl/filter_selector_string.rst | 20 +- dpctl/_sycl_device.pyx | 2 +- dpctl/tests/_device_attributes_checks.py | 6 + .../helper/include/dpctl_utils_helper.h | 2 +- .../syclinterface/dpctl_device_selection.hpp | 29 ++- .../dpctl_sycl_device_selector_interface.h | 6 +- .../source/dpctl_device_selection.cpp | 242 ++++++++++-------- .../test_sycl_device_selector_interface.cpp | 73 +++++- 8 files changed, 245 insertions(+), 135 deletions(-) diff --git a/docs/doc_sources/api_reference/dpctl/filter_selector_string.rst b/docs/doc_sources/api_reference/dpctl/filter_selector_string.rst index f96a8764df..0b2ab01754 100644 --- a/docs/doc_sources/api_reference/dpctl/filter_selector_string.rst +++ b/docs/doc_sources/api_reference/dpctl/filter_selector_string.rst @@ -3,12 +3,10 @@ Filter Selector String ====================== -Filter selector string is a way to refer to unpartitioned SYCL devices -proposed in :oneapi_filter_selection:`sycl_ext_oneapi_filter_selector <>` -extension to SYCL standard. - -This document captures aspects of the referenced document relevant -to :mod:`dpctl`. +Filter selector string is a way to refer to unpartitioned SYCL devices. +:mod:`dpctl` implements the syntax of the DPC++ +:oneapi_filter_selection:`sycl_ext_oneapi_filter_selector <>` extension +without relying on the extension itself. A filter selector string defines one or more filters, which must be separated using ``","`` character. A filter is specified as a @@ -18,8 +16,8 @@ triple of the form: Backend:DeviceType:RelativeDeviceNumber -Every element of the triple is optional, but a filter must contain at -least one component. +Every element of the triple is optional and the elements may be given in +any order. ``Backend`` specifies the desired backend of targeted devices, while ``DeviceType`` specifies the type of targeted devices. @@ -27,6 +25,9 @@ least one component. any other given requirements, starting from 0 to marking the "first device that matches the requirements". +If several devices match, the one with the highest default selector +score is selected. + Attempting to use a non-conforming string in places where filter selector string is expected will raise an exception. @@ -39,6 +40,9 @@ Supported values for ``Backend`` are: - level_zero - hip +When :mod:`dpctl` is built with AdaptiveCpp, ``openmp`` selects the +AdaptiveCpp OpenMP host device. + Supported values for ``DeviceType`` are: .. list-table:: diff --git a/dpctl/_sycl_device.pyx b/dpctl/_sycl_device.pyx index 78691e0ddc..a14e210869 100644 --- a/dpctl/_sycl_device.pyx +++ b/dpctl/_sycl_device.pyx @@ -406,7 +406,7 @@ cdef class SyclDevice(_SyclDevice): - by directly passing in a filter string to the class constructor. The filter string needs to conform to the - :oneapi_filter_selection:`DPC++ filter selector SYCL extension <>`. + :ref:`filter selector string ` syntax. :Example: diff --git a/dpctl/tests/_device_attributes_checks.py b/dpctl/tests/_device_attributes_checks.py index 0236fb0934..fe7e312143 100644 --- a/dpctl/tests/_device_attributes_checks.py +++ b/dpctl/tests/_device_attributes_checks.py @@ -53,6 +53,12 @@ "opencl:gpu:-1", "cuda:cpu:0", "abc", + "OPENCL", + "opencl:gpu:cpu", + "opencl:level_zero", + "0:1", + "opencl:gpu:0:0", + "", 1, ] diff --git a/libsyclinterface/helper/include/dpctl_utils_helper.h b/libsyclinterface/helper/include/dpctl_utils_helper.h index daaf88cc3a..0a4c192289 100644 --- a/libsyclinterface/helper/include/dpctl_utils_helper.h +++ b/libsyclinterface/helper/include/dpctl_utils_helper.h @@ -312,7 +312,7 @@ int64_t DPCTL_GetRelativeDeviceId(const sycl::device &Device); /*! * @brief Gives the filter string which would select given root device if - * used as argument to ``sycl::ext::oneapi::filter_selector``. Throws exception + * used as argument to ``DPCTLFilterSelector_Create``. Throws exception * if filter string can not be constructed. * * @param Device A ``sycl::device`` object whose filter selector diff --git a/libsyclinterface/include/syclinterface/dpctl_device_selection.hpp b/libsyclinterface/include/syclinterface/dpctl_device_selection.hpp index f461510545..ed84872b6a 100644 --- a/libsyclinterface/include/syclinterface/dpctl_device_selection.hpp +++ b/libsyclinterface/include/syclinterface/dpctl_device_selection.hpp @@ -27,6 +27,7 @@ #pragma once #include "Support/DllExport.h" +#include #include #include #include @@ -72,20 +73,32 @@ class DPCTL_API dpctl_cpu_selector : public dpctl_device_selector int operator()(const sycl::device &d) const override; }; +/*! + * @brief Selects devices matching a filter selector string. + * + * The string is a comma-separated list of filters, each of the form + * ``backend:device_type:device_num`` with every component optional and in + * any order. ``device_num`` counts devices from ``sycl::device::get_devices()`` + * that match the filter's backend and device type and that + * ``sycl::default_selector_v`` does not reject. Matching devices are + * scored by ``sycl::default_selector_v``. + * + * Throws ``std::invalid_argument`` if the string is malformed. + */ class DPCTL_API dpctl_filter_selector : public dpctl_device_selector { public: - dpctl_filter_selector(const std::string &fs); + explicit dpctl_filter_selector(const std::string &fs); int operator()(const sycl::device &d) const override; private: -#ifndef __ADAPTIVECPP__ - sycl::ext::oneapi::filter_selector _impl; -#else - // AdaptiveCpp has no filter_selector extension, so the filter string is - // resolved to devices when the selector is constructed. - std::vector _matches; -#endif + struct filter + { + std::optional backend; + std::optional device_type; + std::optional device; + }; + std::vector _filters; }; } // namespace syclinterface diff --git a/libsyclinterface/include/syclinterface/dpctl_sycl_device_selector_interface.h b/libsyclinterface/include/syclinterface/dpctl_sycl_device_selector_interface.h index 74d04a256f..e4d7a83823 100644 --- a/libsyclinterface/include/syclinterface/dpctl_sycl_device_selector_interface.h +++ b/libsyclinterface/include/syclinterface/dpctl_sycl_device_selector_interface.h @@ -65,12 +65,12 @@ DPCTL_API __dpctl_give DPCTLSyclDeviceSelectorRef DPCTLCPUSelector_Create(void); /*! - * @brief Returns an opaque wrapper for sycl::ext::oneapi::filter_selector - * object based on the passed in filter string. + * @brief Returns a device selector for the passed in filter string. * * @param filter_str A C string providing a filter based on which to * create a device selector. - * @return An opaque pointer to a sycl::ext::oneapi::filter_selector object. + * @return An opaque pointer to a device selector, or nullptr if the + * filter string is malformed. * @ingroup DeviceSelectors */ DPCTL_API diff --git a/libsyclinterface/source/dpctl_device_selection.cpp b/libsyclinterface/source/dpctl_device_selection.cpp index 24836fcdc2..3e3caed995 100644 --- a/libsyclinterface/source/dpctl_device_selection.cpp +++ b/libsyclinterface/source/dpctl_device_selection.cpp @@ -27,10 +27,13 @@ #include "dpctl_device_selection.hpp" #include "Config/dpctl_config.h" +#include #include +#include #include #include #include +#include #include namespace @@ -39,122 +42,96 @@ namespace static_assert(__SYCL_COMPILER_VERSION >= __SYCL_COMPILER_VERSION_REQUIRED, "The compiler does not meet minimum version requirement"); #endif -} // namespace -#ifdef __ADAPTIVECPP__ -namespace -{ +/*! Splits s on delim, dropping empty tokens. */ +std::vector tokenize(const std::string &s, char delim) +{ + std::vector tokens; + std::size_t start = 0; + while (start <= s.size()) { + auto end = s.find(delim, start); + if (end == std::string::npos) + end = s.size(); + if (end > start) + tokens.emplace_back(s, start, end - start); + start = end + 1; + } + return tokens; +} -std::vector split_string(const std::string &s, char sep) +std::optional backend_from_token(const std::string &tok) { - std::vector terms{}; - std::string::size_type pos = 0; - while (true) { - auto next = s.find(sep, pos); - if (next == std::string::npos) { - terms.emplace_back(s.substr(pos)); - return terms; - } - terms.emplace_back(s.substr(pos, next - pos)); - pos = next + 1; - } +#ifndef __ADAPTIVECPP__ + if (tok == "opencl") + return sycl::backend::opencl; + if (tok == "level_zero") + return sycl::backend::ext_oneapi_level_zero; + if (tok == "cuda") + return sycl::backend::ext_oneapi_cuda; + if (tok == "hip") + return sycl::backend::ext_oneapi_hip; +#else + if (tok == "opencl") + return sycl::backend::ocl; + if (tok == "level_zero") + return sycl::backend::level_zero; + if (tok == "cuda") + return sycl::backend::cuda; + if (tok == "hip") + return sycl::backend::hip; + if (tok == "openmp") + return sycl::backend::omp; +#endif + return std::nullopt; } -bool parse_backend(const std::string &term, sycl::backend &backend) -{ - if (term == "opencl") - backend = sycl::backend::ocl; - else if (term == "level_zero") - backend = sycl::backend::level_zero; - else if (term == "cuda") - backend = sycl::backend::cuda; - else if (term == "hip") - backend = sycl::backend::hip; - else if (term == "openmp") - backend = sycl::backend::omp; - else - return false; - return true; +std::optional +device_type_from_token(const std::string &tok) +{ + if (tok == "cpu") + return sycl::info::device_type::cpu; + if (tok == "gpu") + return sycl::info::device_type::gpu; + if (tok == "accelerator") + return sycl::info::device_type::accelerator; + return std::nullopt; } -bool parse_device_type(const std::string &term, - sycl::info::device_type &device_type) -{ - if (term == "cpu") - device_type = sycl::info::device_type::cpu; - else if (term == "gpu") - device_type = sycl::info::device_type::gpu; - else if (term == "accelerator") - device_type = sycl::info::device_type::accelerator; - else if (term == "custom") - device_type = sycl::info::device_type::custom; - else - return false; - return true; +/*! Parses a non-negative decimal int; nullopt on any other input. */ +std::optional device_num_from_token(const std::string &tok) +{ + for (char c : tok) { + if (c < '0' || c > '9') + return std::nullopt; + } + int num = 0; + const char *first = tok.data(); + const char *last = first + tok.size(); + auto [ptr, ec] = std::from_chars(first, last, num); + if (ec != std::errc{} || ptr != last) + return std::nullopt; + return num; } -bool parse_index(const std::string &term, long long &index) +bool matches_backend_and_type(const std::optional &be, + const std::optional &dt, + const sycl::device &d) { - if (term.empty() || - term.find_first_not_of("0123456789") != std::string::npos) + if (be && d.get_backend() != *be) + return false; + if (dt && d.get_info() != *dt) return false; - index = std::stoll(term); return true; } -/*! - * @brief Appends devices matched by a single "backend:device_type:index" - * filter, each term of which is optional, to the selected vector. - * - * Devices are enumerated the way DPCTLDeviceMgr_GetDevices enumerates them, so - * that an index term agrees with the relative id in a device's filter string. - */ -void resolve_filter(const std::string &filter, - std::vector &selected) -{ - auto terms = split_string(filter, ':'); - sycl::backend backend{}; - sycl::info::device_type device_type{}; - long long index = -1; - bool has_backend = false; - bool has_device_type = false; - - std::size_t pos = 0; - if (pos < terms.size() && parse_backend(terms[pos], backend)) { - has_backend = true; - ++pos; - } - if (pos < terms.size() && parse_device_type(terms[pos], device_type)) { - has_device_type = true; - ++pos; - } - if (pos < terms.size() && parse_index(terms[pos], index)) - ++pos; - if (pos != terms.size()) - throw std::invalid_argument("Could not parse filter string '" + filter + - "'"); - - dpctl::syclinterface::dpctl_default_selector ranker; - long long matched = 0; - for (const auto &d : sycl::device::get_devices()) { - if (ranker(d) < 0) - continue; - if (has_backend && d.get_platform().get_backend() != backend) - continue; - if (has_device_type && - d.get_info() != device_type) - continue; - if (index < 0) - selected.emplace_back(d); - else if (matched++ == index) { - selected.emplace_back(d); - break; - } - } +[[noreturn]] void throw_invalid_filter(const std::string &fs) +{ + throw std::invalid_argument( + "Invalid filter string '" + fs + + "'. Filters are comma-separated and have the form " + "backend:device_type:device_num, where each component is optional."); } - } // namespace -#endif namespace dpctl { @@ -197,32 +174,73 @@ int dpctl_cpu_selector::operator()(const sycl::device &d) const return sycl::cpu_selector_v(d); } -#ifndef __ADAPTIVECPP__ -dpctl_filter_selector::dpctl_filter_selector(const std::string &fs) : _impl(fs) -{ -} -#else dpctl_filter_selector::dpctl_filter_selector(const std::string &fs) { - for (const auto &filter : split_string(fs, ',')) - resolve_filter(filter, _matches); + std::vector>> parsed; + for (const auto &filter_str : tokenize(fs, ',')) { + auto tokens = tokenize(filter_str, ':'); + if (tokens.size() > 3) + throw_invalid_filter(fs); + + filter f; + std::optional device_num; + for (const auto &tok : tokens) { + if (auto be = backend_from_token(tok); be && !f.backend) + f.backend = be; + else if (auto dt = device_type_from_token(tok); + dt && !f.device_type) + f.device_type = dt; + else if (auto num = device_num_from_token(tok); num && !device_num) + device_num = num; + else + throw_invalid_filter(fs); + } + parsed.emplace_back(std::move(f), device_num); + } + + // Resolve device numbers; a filter whose device does not exist is dropped + std::vector devices; + bool have_devices = false; + for (auto &[f, device_num] : parsed) { + if (device_num) { + if (!have_devices) { + devices = sycl::device::get_devices(); + have_devices = true; + } + int idx = 0; + for (const auto &d : devices) { + if (sycl::default_selector_v(d) < 0 || + !matches_backend_and_type(f.backend, f.device_type, d)) + continue; + if (idx++ == *device_num) { + f.device = d; + break; + } + } + if (!f.device) + continue; + } + _filters.push_back(std::move(f)); + } } -#endif int dpctl_filter_selector::operator()(const sycl::device &d) const { + for (const auto &f : _filters) { + if (matches_backend_and_type(f.backend, f.device_type, d) && + (!f.device || *f.device == d)) + { #ifndef __ADAPTIVECPP__ - return _impl(d); + return sycl::default_selector_v(d); #else - for (const auto &m : _matches) - if (m == d) { // scores of matched devices are shifted to be strictly positive, // since AdaptiveCpp scores the OpenMP host device 0 auto score = sycl::default_selector_v(d); return (score < 0) ? REJECT_DEVICE : score + 1; +#endif } + } return REJECT_DEVICE; -#endif } } // namespace syclinterface diff --git a/libsyclinterface/tests/test_sycl_device_selector_interface.cpp b/libsyclinterface/tests/test_sycl_device_selector_interface.cpp index d6a9d3f4ee..9a951507ef 100644 --- a/libsyclinterface/tests/test_sycl_device_selector_interface.cpp +++ b/libsyclinterface/tests/test_sycl_device_selector_interface.cpp @@ -28,7 +28,9 @@ #include "dpctl_sycl_device_manager.h" #include "dpctl_sycl_device_selector_interface.h" #include "dpctl_sycl_type_casters.hpp" +#include "dpctl_utils_helper.h" #include +#include #include using namespace sycl; @@ -205,6 +207,56 @@ TEST_F(TestDeviceSelectorInterface, ChkDPCTLGPUSelectorScore) ASSERT_TRUE(score < 0); } +TEST_F(TestDeviceSelectorInterface, ChkDPCTLFilterSelectorScore) +{ + using dpctl::syclinterface::unwrap; + using dpctl::syclinterface::wrap; + + const auto devices = sycl::device::get_devices(); + for (std::size_t i = 0; i < devices.size(); ++i) { + const std::string filters[] = {std::to_string(i), + DPCTL_GetDeviceFilterString(devices[i])}; + for (const auto &fs : filters) { + DPCTLSyclDeviceSelectorRef DSRef = nullptr; + EXPECT_NO_FATAL_FAILURE(DSRef = + DPCTLFilterSelector_Create(fs.c_str())); + ASSERT_TRUE(DSRef != nullptr); + for (std::size_t j = 0; j < devices.size(); ++j) { + auto D = devices[j]; + auto DRef = wrap(&D); + int score = DPCTLDeviceSelector_Score(DSRef, DRef); + if (i == j) + EXPECT_TRUE(score >= 0) << fs; + else + EXPECT_TRUE(score < 0) << fs; + } + EXPECT_NO_FATAL_FAILURE(DPCTLDeviceSelector_Delete(DSRef)); + } + } +} + +TEST_F(TestDeviceSelectorInterface, ChkDPCTLFilterSelectorList) +{ + const auto devices = sycl::device::get_devices(); + if (devices.size() < 2) + GTEST_SKIP_("Need at least two devices."); + + // "0,1" must accept both device 0 and device 1 + DPCTLSyclDeviceSelectorRef DSRef = nullptr; + EXPECT_NO_FATAL_FAILURE(DSRef = DPCTLFilterSelector_Create("0,1")); + ASSERT_TRUE(DSRef != nullptr); + for (std::size_t j = 0; j < devices.size(); ++j) { + auto D = devices[j]; + auto DRef = dpctl::syclinterface::wrap(&D); + int score = DPCTLDeviceSelector_Score(DSRef, DRef); + if (j < 2) + EXPECT_TRUE(score >= 0); + else + EXPECT_TRUE(score < 0); + } + EXPECT_NO_FATAL_FAILURE(DPCTLDeviceSelector_Delete(DSRef)); +} + INSTANTIATE_TEST_SUITE_P(FilterSelectorCreation, TestFilterSelector, ::testing::Values("opencl", @@ -220,8 +272,25 @@ INSTANTIATE_TEST_SUITE_P(FilterSelectorCreation, "gpu:0", "gpu:1", "1", - "0")); + "0", + "gpu:opencl", + "0:gpu", + "opencl::0", + ":", + "gpu,cpu", + "cuda,cpu")); INSTANTIATE_TEST_SUITE_P(NegativeFilterSelectorCreation, TestUnsupportedFilters, - ::testing::Values("abc", "-1", "cuda:cpu:0")); + ::testing::Values("abc", + "-1", + "cuda:cpu:0", + "", + ",", + "OPENCL", + " opencl", + "opencl:gpu:cpu", + "opencl:level_zero", + "0:1", + "opencl:gpu:0:0", + "99999999999")); From 46e70d51bc5e4870f2af8662932a01df5d8fa18b Mon Sep 17 00:00:00 2001 From: Nikita Grigorian Date: Wed, 4 Nov 2026 16:12:28 -0800 Subject: [PATCH 2/7] raise ValueError for filter strings that can not be parsed SyclDevice.filter_string and get_filter_string used to return "unknown" for backends and device types without a filter string spelling. --- dpctl/_sycl_device.pyx | 99 +++++++++++++++++++++++++----------------- 1 file changed, 58 insertions(+), 41 deletions(-) diff --git a/dpctl/_sycl_device.pyx b/dpctl/_sycl_device.pyx index a14e210869..9ff858d26c 100644 --- a/dpctl/_sycl_device.pyx +++ b/dpctl/_sycl_device.pyx @@ -242,6 +242,7 @@ cdef tuple _to_enum_tuple( cdef str _backend_type_to_filter_string_part(_backend_type BTy): + """ Returns the filter string part for the backend, or ``None``.""" if BTy == _backend_type._CUDA: return "cuda" elif BTy == _backend_type._HIP: @@ -253,20 +254,55 @@ cdef str _backend_type_to_filter_string_part(_backend_type BTy): elif BTy == _backend_type._OPENMP: return "openmp" else: - return "unknown" + return None cdef str _device_type_to_filter_string_part(_device_type DTy): + """ Returns the filter string part for the device type, or ``None``.""" if DTy == _device_type._ACCELERATOR: return "accelerator" - elif DTy == _device_type._AUTOMATIC: - return "automatic" elif DTy == _device_type._CPU: return "cpu" elif DTy == _device_type._GPU: return "gpu" else: - return "unknown" + return None + + +cdef str _make_filter_string( + DPCTLSyclDeviceRef DRef, + bint include_backend, + bint include_device_type, + int64_t relId, +): + """ Joins the requested parts of the filter string of a root device. + + Raises ``ValueError`` if the backend or device type has no filter + string representation. + """ + cdef list parts = [] + if include_backend: + be_str = _backend_type_to_filter_string_part( + DPCTLDevice_GetBackend(DRef) + ) + if be_str is None: + raise ValueError( + "The backend of this SyclDevice is not supported in filter " + "strings" + ) + parts.append(be_str) + if include_device_type: + dt_str = _device_type_to_filter_string_part( + DPCTLDevice_GetDeviceType(DRef) + ) + if dt_str is None: + raise ValueError( + "The device type of this SyclDevice is not supported in " + "filter strings" + ) + parts.append(dt_str) + parts.append(str(relId)) + return ":".join(parts) cdef void _init_helper(_SyclDevice device, DPCTLSyclDeviceRef DRef) except *: @@ -324,22 +360,17 @@ cdef inline void _raise_invalid_peer_access( ] cdef _backend_type BTy1 = DPCTLDevice_GetBackend(dev._device_ref) cdef _backend_type BTy2 = DPCTLDevice_GetBackend(peer.get_device_ref()) + be1 = _backend_type_to_filter_string_part(BTy1) or "unknown" + be2 = _backend_type_to_filter_string_part(BTy2) or "unknown" if (BTy1 != BTy2): raise ValueError( - f"Device with backend {_backend_type_to_filter_string_part(BTy1)} " - "cannot peer access device with backend " - f"{_backend_type_to_filter_string_part(BTy2)}" + f"Device with backend {be1} " + f"cannot peer access device with backend {be2}" ) if (BTy1 not in _peer_access_backends): - raise ValueError( - "Peer access not supported for backend " - f"{_backend_type_to_filter_string_part(BTy1)}" - ) + raise ValueError(f"Peer access not supported for backend {be1}") if (BTy2 not in _peer_access_backends): - raise ValueError( - "Peer access not supported for backend " - f"{_backend_type_to_filter_string_part(BTy2)}" - ) + raise ValueError(f"Peer access not supported for backend {be2}") if (dev == peer): raise ValueError( "Peer access cannot be enabled between a device and itself" @@ -362,20 +393,15 @@ def _cached_filter_string(d : SyclDevice): if the device is a root (unpartitioned) device. Raises: - ValueError: if the input device is a sub-device. + ValueError: if the input device is a sub-device, or its backend or + device type is not supported in filter strings. """ - cdef _backend_type BTy - cdef _device_type DTy cdef int64_t relId = -1 cdef SyclDevice cd = d relId = DPCTLDeviceMgr_GetRelativeId(cd._device_ref) if (relId == -1): raise ValueError("This SyclDevice is not a root device") - BTy = DPCTLDevice_GetBackend(cd._device_ref) - br_str = _backend_type_to_filter_string_part(BTy) - DTy = DPCTLDevice_GetDeviceType(cd._device_ref) - dt_str = _device_type_to_filter_string_part(DTy) - return ":".join((br_str, dt_str, str(relId))) + return _make_filter_string(cd._device_ref, True, True, relId) def _rebuild_device(str filter_string, str name): @@ -2702,6 +2728,9 @@ cdef class SyclDevice(_SyclDevice): ValueError: If the device is a sub-device. + If the backend or device type of the device is not + supported in filter strings. + :Example: .. code-block:: python @@ -2808,6 +2837,9 @@ cdef class SyclDevice(_SyclDevice): If no match for the device was found in the vector returned by ``sycl::device::get_devices()`` + If the requested backend or device type of the device is + not supported in filter strings. + :Example: .. code-block:: python @@ -2822,8 +2854,6 @@ cdef class SyclDevice(_SyclDevice): """ cdef int relId = -1 cdef DPCTLSyclDeviceRef pDRef = NULL - cdef _device_type DTy - cdef _backend_type BTy if include_backend: if include_device_type: @@ -2845,22 +2875,9 @@ cdef class SyclDevice(_SyclDevice): DPCTLDevice_Delete(pDRef) raise ValueError("This SyclDevice is not a root device") else: - if include_backend: - BTy = DPCTLDevice_GetBackend(self._device_ref) - be_str = _backend_type_to_filter_string_part(BTy) - if include_device_type: - DTy = DPCTLDevice_GetDeviceType(self._device_ref) - dt_str = _device_type_to_filter_string_part(DTy) - return ":".join((be_str, dt_str, str(relId))) - else: - return ":".join((be_str, str(relId))) - else: - if include_device_type: - DTy = DPCTLDevice_GetDeviceType(self._device_ref) - dt_str = _device_type_to_filter_string_part(DTy) - return ":".join((dt_str, str(relId))) - else: - return str(relId) + return _make_filter_string( + self._device_ref, include_backend, include_device_type, relId + ) def get_unpartitioned_parent_device(self): """ get_unpartitioned_parent_device() From 67eecb9e9c49f35e0f59b5d8f058fca60ea58d8a Mon Sep 17 00:00:00 2001 From: Nikita Grigorian Date: Wed, 4 Nov 2026 16:12:30 -0800 Subject: [PATCH 3/7] support custom device type in filter strings The filter selector accepts "custom", and filter_string of a custom device is "backend:custom:N". --- .../dpctl/filter_selector_string.rst | 1 + dpctl/_sycl_device.pyx | 2 ++ .../source/dpctl_device_selection.cpp | 2 ++ .../test_sycl_device_selector_interface.cpp | 17 +++++++++++++++++ 4 files changed, 22 insertions(+) diff --git a/docs/doc_sources/api_reference/dpctl/filter_selector_string.rst b/docs/doc_sources/api_reference/dpctl/filter_selector_string.rst index 0b2ab01754..5cb63269af 100644 --- a/docs/doc_sources/api_reference/dpctl/filter_selector_string.rst +++ b/docs/doc_sources/api_reference/dpctl/filter_selector_string.rst @@ -49,6 +49,7 @@ Supported values for ``DeviceType`` are: * - accelerator - cpu + - custom - gpu Filter selector strings can be used as arguments to constructors of diff --git a/dpctl/_sycl_device.pyx b/dpctl/_sycl_device.pyx index 9ff858d26c..d48044a2aa 100644 --- a/dpctl/_sycl_device.pyx +++ b/dpctl/_sycl_device.pyx @@ -263,6 +263,8 @@ cdef str _device_type_to_filter_string_part(_device_type DTy): return "accelerator" elif DTy == _device_type._CPU: return "cpu" + elif DTy == _device_type._CUSTOM: + return "custom" elif DTy == _device_type._GPU: return "gpu" else: diff --git a/libsyclinterface/source/dpctl_device_selection.cpp b/libsyclinterface/source/dpctl_device_selection.cpp index 3e3caed995..2d4f36b92d 100644 --- a/libsyclinterface/source/dpctl_device_selection.cpp +++ b/libsyclinterface/source/dpctl_device_selection.cpp @@ -94,6 +94,8 @@ device_type_from_token(const std::string &tok) return sycl::info::device_type::gpu; if (tok == "accelerator") return sycl::info::device_type::accelerator; + if (tok == "custom") + return sycl::info::device_type::custom; return std::nullopt; } diff --git a/libsyclinterface/tests/test_sycl_device_selector_interface.cpp b/libsyclinterface/tests/test_sycl_device_selector_interface.cpp index 9a951507ef..d7a0b7e650 100644 --- a/libsyclinterface/tests/test_sycl_device_selector_interface.cpp +++ b/libsyclinterface/tests/test_sycl_device_selector_interface.cpp @@ -257,6 +257,23 @@ TEST_F(TestDeviceSelectorInterface, ChkDPCTLFilterSelectorList) EXPECT_NO_FATAL_FAILURE(DPCTLDeviceSelector_Delete(DSRef)); } +TEST_F(TestDeviceSelectorInterface, ChkDPCTLFilterSelectorCustom) +{ + for (const char *fs : {"custom", "opencl:custom", "custom:0"}) { + DPCTLSyclDeviceSelectorRef DSRef = nullptr; + EXPECT_NO_FATAL_FAILURE(DSRef = DPCTLFilterSelector_Create(fs)); + ASSERT_TRUE(DSRef != nullptr) << fs; + for (auto D : sycl::device::get_devices()) { + if (D.get_info() == + sycl::info::device_type::custom) + continue; + auto DRef = dpctl::syclinterface::wrap(&D); + EXPECT_TRUE(DPCTLDeviceSelector_Score(DSRef, DRef) < 0) << fs; + } + EXPECT_NO_FATAL_FAILURE(DPCTLDeviceSelector_Delete(DSRef)); + } +} + INSTANTIATE_TEST_SUITE_P(FilterSelectorCreation, TestFilterSelector, ::testing::Values("opencl", From 9becb1e4101ead96ab3b02f2f2eb0233a86eb981 Mon Sep 17 00:00:00 2001 From: Nikita Grigorian Date: Wed, 4 Nov 2026 16:43:33 -0800 Subject: [PATCH 4/7] add changelog entries for gh-2420 --- CHANGELOG.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 91a5d08423..7b5c2d3587 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,7 @@ 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 `custom` device type to filter selector strings [gh-2420](https://github.com/IntelPython/dpctl/pull/2420) ### 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,6 +26,8 @@ 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) +* Filter selector strings are implemented in `dpctl` instead of relying on the deprecated DPC++ `sycl_ext_oneapi_filter_selector` extension, and device numbers in a list of filters, such as `"0,1"`, now refer to the same devices as when used in separate filters [gh-2420](https://github.com/IntelPython/dpctl/pull/2420) +* `dpctl.SyclDevice.filter_string` and `dpctl.SyclDevice.get_filter_string` raise `ValueError` for backends and device types not supported in filter selector strings, instead of returning a string containing `"unknown"` [gh-2420](https://github.com/IntelPython/dpctl/pull/2420) ### 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) @@ -43,6 +46,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) +* `DPCTLDeviceSelector_Score` returns correct scores for filter selectors with device numbers [gh-2420](https://github.com/IntelPython/dpctl/pull/2420) ### 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) From 3fa1ba28fa64f1650134379d6f3239f09fd60770 Mon Sep 17 00:00:00 2001 From: Nikita Grigorian Date: Fri, 6 Nov 2026 11:57:19 -0800 Subject: [PATCH 5/7] score each device twice in ChkDPCTLFilterSelectorScore Catches selectors whose scores depend on earlier calls, even with one device. --- .../test_sycl_device_selector_interface.cpp | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/libsyclinterface/tests/test_sycl_device_selector_interface.cpp b/libsyclinterface/tests/test_sycl_device_selector_interface.cpp index d7a0b7e650..37f5f17de2 100644 --- a/libsyclinterface/tests/test_sycl_device_selector_interface.cpp +++ b/libsyclinterface/tests/test_sycl_device_selector_interface.cpp @@ -221,14 +221,17 @@ TEST_F(TestDeviceSelectorInterface, ChkDPCTLFilterSelectorScore) EXPECT_NO_FATAL_FAILURE(DSRef = DPCTLFilterSelector_Create(fs.c_str())); ASSERT_TRUE(DSRef != nullptr); - for (std::size_t j = 0; j < devices.size(); ++j) { - auto D = devices[j]; - auto DRef = wrap(&D); - int score = DPCTLDeviceSelector_Score(DSRef, DRef); - if (i == j) - EXPECT_TRUE(score >= 0) << fs; - else - EXPECT_TRUE(score < 0) << fs; + // scores must not depend on earlier calls + for (int pass = 0; pass < 2; ++pass) { + for (std::size_t j = 0; j < devices.size(); ++j) { + auto D = devices[j]; + auto DRef = wrap(&D); + int score = DPCTLDeviceSelector_Score(DSRef, DRef); + if (i == j) + EXPECT_TRUE(score >= 0) << fs << " pass " << pass; + else + EXPECT_TRUE(score < 0) << fs << " pass " << pass; + } } EXPECT_NO_FATAL_FAILURE(DPCTLDeviceSelector_Delete(DSRef)); } From 6b8675c997102bb8c796a7ee9b79a0e67ae2425a Mon Sep 17 00:00:00 2001 From: Nikita Grigorian Date: Wed, 2 Dec 2026 00:28:20 -0800 Subject: [PATCH 6/7] reject filters with no components A filter made only of ":" separators, such as ":" or "gpu:0,:", matched any device, so a missing gpu:0 fell back to whatever else was available. Such filters are now malformed. --- CHANGELOG.md | 1 + .../api_reference/dpctl/filter_selector_string.rst | 2 +- dpctl/tests/_device_attributes_checks.py | 2 ++ .../include/syclinterface/dpctl_device_selection.hpp | 8 ++++---- libsyclinterface/source/dpctl_device_selection.cpp | 2 +- .../tests/test_sycl_device_selector_interface.cpp | 4 +++- 6 files changed, 12 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7b5c2d3587..dd6e679a2c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -28,6 +28,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 * NumPy is no longer a build dependency of `dpctl`, only a run-time dependency [gh-2436](https://github.com/IntelPython/dpctl/pull/2436) * Filter selector strings are implemented in `dpctl` instead of relying on the deprecated DPC++ `sycl_ext_oneapi_filter_selector` extension, and device numbers in a list of filters, such as `"0,1"`, now refer to the same devices as when used in separate filters [gh-2420](https://github.com/IntelPython/dpctl/pull/2420) * `dpctl.SyclDevice.filter_string` and `dpctl.SyclDevice.get_filter_string` raise `ValueError` for backends and device types not supported in filter selector strings, instead of returning a string containing `"unknown"` [gh-2420](https://github.com/IntelPython/dpctl/pull/2420) +* A filter selector string with a filter that has no components, such as `":"` or `"gpu:0,:"`, is rejected as malformed instead of selecting any device [gh-2420](https://github.com/IntelPython/dpctl/pull/2420) ### 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) diff --git a/docs/doc_sources/api_reference/dpctl/filter_selector_string.rst b/docs/doc_sources/api_reference/dpctl/filter_selector_string.rst index 5cb63269af..71c5debe68 100644 --- a/docs/doc_sources/api_reference/dpctl/filter_selector_string.rst +++ b/docs/doc_sources/api_reference/dpctl/filter_selector_string.rst @@ -17,7 +17,7 @@ triple of the form: Backend:DeviceType:RelativeDeviceNumber Every element of the triple is optional and the elements may be given in -any order. +any order, but a filter must contain at least one component. ``Backend`` specifies the desired backend of targeted devices, while ``DeviceType`` specifies the type of targeted devices. diff --git a/dpctl/tests/_device_attributes_checks.py b/dpctl/tests/_device_attributes_checks.py index fe7e312143..979d5032d8 100644 --- a/dpctl/tests/_device_attributes_checks.py +++ b/dpctl/tests/_device_attributes_checks.py @@ -59,6 +59,8 @@ "0:1", "opencl:gpu:0:0", "", + ":", + "gpu:0,:", 1, ] diff --git a/libsyclinterface/include/syclinterface/dpctl_device_selection.hpp b/libsyclinterface/include/syclinterface/dpctl_device_selection.hpp index ed84872b6a..88434c8f52 100644 --- a/libsyclinterface/include/syclinterface/dpctl_device_selection.hpp +++ b/libsyclinterface/include/syclinterface/dpctl_device_selection.hpp @@ -78,10 +78,10 @@ class DPCTL_API dpctl_cpu_selector : public dpctl_device_selector * * The string is a comma-separated list of filters, each of the form * ``backend:device_type:device_num`` with every component optional and in - * any order. ``device_num`` counts devices from ``sycl::device::get_devices()`` - * that match the filter's backend and device type and that - * ``sycl::default_selector_v`` does not reject. Matching devices are - * scored by ``sycl::default_selector_v``. + * any order, but at least one given. ``device_num`` counts devices from + * ``sycl::device::get_devices()`` that match the filter's backend and device + * type and that ``sycl::default_selector_v`` does not reject. Matching devices + * are scored by ``sycl::default_selector_v``. * * Throws ``std::invalid_argument`` if the string is malformed. */ diff --git a/libsyclinterface/source/dpctl_device_selection.cpp b/libsyclinterface/source/dpctl_device_selection.cpp index 2d4f36b92d..48dcaf5003 100644 --- a/libsyclinterface/source/dpctl_device_selection.cpp +++ b/libsyclinterface/source/dpctl_device_selection.cpp @@ -181,7 +181,7 @@ dpctl_filter_selector::dpctl_filter_selector(const std::string &fs) std::vector>> parsed; for (const auto &filter_str : tokenize(fs, ',')) { auto tokens = tokenize(filter_str, ':'); - if (tokens.size() > 3) + if (tokens.empty() || tokens.size() > 3) throw_invalid_filter(fs); filter f; diff --git a/libsyclinterface/tests/test_sycl_device_selector_interface.cpp b/libsyclinterface/tests/test_sycl_device_selector_interface.cpp index 37f5f17de2..f00ab56c40 100644 --- a/libsyclinterface/tests/test_sycl_device_selector_interface.cpp +++ b/libsyclinterface/tests/test_sycl_device_selector_interface.cpp @@ -296,7 +296,6 @@ INSTANTIATE_TEST_SUITE_P(FilterSelectorCreation, "gpu:opencl", "0:gpu", "opencl::0", - ":", "gpu,cpu", "cuda,cpu")); @@ -307,6 +306,9 @@ INSTANTIATE_TEST_SUITE_P(NegativeFilterSelectorCreation, "cuda:cpu:0", "", ",", + ":", + "::", + "gpu:0,:", "OPENCL", " opencl", "opencl:gpu:cpu", From e7676b8156d4ca48aed2497adb8db1d78582ab09 Mon Sep 17 00:00:00 2001 From: Nikita Grigorian Date: Fri, 4 Dec 2026 10:28:52 -0800 Subject: [PATCH 7/7] drop unreachable unknown check in SyclDevice.__reduce__ filter_string now raises ValueError for unsupported backends and device types, which __reduce__ already turns into PicklingError. --- dpctl/_sycl_device.pyx | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/dpctl/_sycl_device.pyx b/dpctl/_sycl_device.pyx index d48044a2aa..044c303bc6 100644 --- a/dpctl/_sycl_device.pyx +++ b/dpctl/_sycl_device.pyx @@ -1722,18 +1722,12 @@ cdef class SyclDevice(_SyclDevice): of the same name. Raises: - pickle.PicklingError: if the device is not a root device, or its - filter string has an ``unknown`` backend or device type. + pickle.PicklingError: if the device has no filter string. """ try: filter_string = self.filter_string except ValueError as e: raise pickle.PicklingError(f"Cannot pickle {self!r}: {e}") from e - if "unknown" in filter_string.split(":")[:2]: - raise pickle.PicklingError( - f"Cannot pickle device '{self.name}': filter string " - f"'{filter_string}' can not select it" - ) return _rebuild_device, (filter_string, self.name) def __copy__(self):