From 60f92e27d2570de745c4a5fa0d07b03f7a3ada80 Mon Sep 17 00:00:00 2001 From: Nikita Grigorian Date: Thu, 5 Nov 2026 06:16:27 -0800 Subject: [PATCH 01/17] Fill scalars on the device instead of copying them from the host A Python or NumPy scalar was turned into a 0-d array, or assigned through basic indexing, with _copy_numpy_ndarray_into_usm_ndarray. That copy waits for all work submitted to the queue, so every binary operation with a scalar operand (2 * x, x == 0), clip, where and x[0] = 1 blocked the host until the device was idle (gh-3148). _copy_from_numpy_into and asarray now fill 0-d input with _full_usm_ndarray. The value is cast on the host the way the copy kernel casts it: through float32/complex64 on devices without fp64, the real part of complex values, float-to-integer through int64 so that it wraps, and without NumPy's cast warnings. --- CHANGELOG.md | 1 + dpnp/tensor/_copy_utils.py | 34 +++++++++ dpnp/tensor/_ctors.py | 12 ++++ .../elementwise/test_elementwise_classes.py | 30 ++++++++ dpnp/tests/tensor/test_tensor_asarray.py | 71 +++++++++++++++++++ dpnp/tests/tensor/test_usm_ndarray_ctor.py | 59 +++++++++++++++ 6 files changed, 207 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5d0fb5cacd24..bd05236bdb37 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -31,6 +31,7 @@ This release drops support for Python 3.10, making Python 3.11 the minimum requi * Changed `dpnp.median`, `dpnp.nanmedian` and `dpnp.partition` with a single `kth` to use a radix select instead of a full sort for all but complex data types and, on a GPU, `dpnp.partition` of rows of 65 to 128 elements of 8-byte integers [#3138](https://github.com/IntelPython/dpnp/pull/3138) * Improved performance of `dpnp.top_k` and `dpnp.tensor.top_k` on a GPU for batches of rows of 65536 to about 10^6 elements that occupy it with a work-group per row [#3138](https://github.com/IntelPython/dpnp/pull/3138) * Changed the C++ standard used to build dpnp and the pybind11 example from C++17 to C++20. C++ extensions that include the headers shipped with dpnp (`dpnp4pybind11.hpp`, the libtensor headers) must now be built as C++20 [#3190](https://github.com/IntelPython/dpnp/pull/3190) +* Changed `dpnp.asarray`, `dpnp.tensor.asarray` and assignment through basic indexing (e.g. `x[0] = 1`, `x[:, 0] = 0`) to fill a scalar or 0-d NumPy array on the device instead of copying it from the host, which waited for all work queued on the device, so binary operators and functions with a Python or NumPy scalar operand (e.g. `2 * x`, `x == 0`, `dpnp.clip(x, 0, 1)`) no longer block the host [#3182](https://github.com/IntelPython/dpnp/pull/3182) ### Deprecated diff --git a/dpnp/tensor/_copy_utils.py b/dpnp/tensor/_copy_utils.py index e54147366abe..b402b8a71351 100644 --- a/dpnp/tensor/_copy_utils.py +++ b/dpnp/tensor/_copy_utils.py @@ -101,12 +101,46 @@ def _copy_from_numpy(np_ary, usm_type="device", sycl_queue=None): return Xusm +def _fill_from_numpy_scalar(dst, np_ary, depends): + """ + Fills `dst` with the value of 0-d `np_ary`, cast on the host as + `_copy_numpy_ndarray_into_usm_ndarray` would cast it. + """ + copy_q = dst.sycl_queue + if copy_q.sycl_device.has_aspect_fp64 is False: + if np_ary.dtype.char == "d": + np_ary = np_ary.astype(np.float32) + elif np_ary.dtype.char == "D": + np_ary = np_ary.astype(np.complex64) + dst_dt = dst.dtype + if np_ary.dtype.kind == "c" and dst_dt.kind not in "bc": + # the copy kernel keeps the real part, NumPy also warns + np_ary = np_ary.real + # the copy kernel casts NaN and out-of-range values without warning + with np.errstate(all="ignore"): + if np_ary.dtype.kind == "f" and dst_dt.kind in "iu": + # the copy kernel narrows through int64, so it wraps like NumPy + # integer casts where a direct NumPy float cast saturates + if dst_dt.itemsize < 8 or (dst_dt.kind == "u" and np_ary < 0): + np_ary = np_ary.astype(np.int64) + fill_val = np_ary.astype(dst_dt)[()].item() + hev, fill_ev = ti._full_usm_ndarray( + fill_val, dst, sycl_queue=copy_q, depends=depends + ) + SequentialOrderManager[copy_q].add_event_pair(hev, fill_ev) + + def _copy_from_numpy_into(dst, np_ary): """Copies `np_ary` into `dst` of type :class:`dpnp.tensor.usm_ndarray""" if not isinstance(np_ary, np.ndarray): raise TypeError(f"Expected numpy.ndarray, got {type(np_ary)}") if not isinstance(dst, dpt.usm_ndarray): raise TypeError(f"Expected usm_ndarray, got {type(dst)}") + if np_ary.ndim == 0: + # fill instead of the host copy, which waits for the whole queue + _manager = SequentialOrderManager[dst.sycl_queue] + _fill_from_numpy_scalar(dst, np_ary, _manager.submitted_events) + return if np_ary.flags["OWNDATA"]: Xnp = np_ary else: diff --git a/dpnp/tensor/_ctors.py b/dpnp/tensor/_ctors.py index 1aeef2408986..bfc4ea883cdd 100644 --- a/dpnp/tensor/_ctors.py +++ b/dpnp/tensor/_ctors.py @@ -39,6 +39,7 @@ from ._copy_utils import ( _empty_like_orderK, + _fill_from_numpy_scalar, _from_numpy_empty_like_orderK, ) from ._data_types import _get_dtype @@ -128,6 +129,17 @@ def _asarray_from_numpy_ndarray( # deduce device-representable output data type dtype = _map_to_device_dtype(ary.dtype, copy_q) _ensure_native_dtype_device_support(dtype, copy_q.sycl_device) + if ary.ndim == 0: + # fill instead of a host copy, which waits for the whole queue + res = dpt.usm_ndarray( + (), + dtype=dtype, + buffer=usm_type, + buffer_ctor_kwargs={"queue": copy_q}, + ) + # populating new allocation, no dependent events + _fill_from_numpy_scalar(res, ary, []) + return res f_contig = ary.flags["F"] c_contig = ary.flags["C"] fc_contig = f_contig or c_contig diff --git a/dpnp/tests/tensor/elementwise/test_elementwise_classes.py b/dpnp/tests/tensor/elementwise/test_elementwise_classes.py index 04b92937f371..cc0b77b44e99 100644 --- a/dpnp/tests/tensor/elementwise/test_elementwise_classes.py +++ b/dpnp/tests/tensor/elementwise/test_elementwise_classes.py @@ -26,8 +26,10 @@ # THE POSSIBILITY OF SUCH DAMAGE. # ***************************************************************************** +import numpy as np import pytest +import dpnp.libtensor._tensor_impl as ti import dpnp.tensor as dpt from ..helper import get_queue_or_skip @@ -148,3 +150,31 @@ def test_binary_no_inplace_op(): with pytest.raises(ValueError): dpt.logaddexp._inplace_op(x1, x2) + + +def _raise_on_host_copy(*args, **kwargs): + raise AssertionError("synchronizing host copy was used") + + +@pytest.mark.parametrize( + "op, expected", + [ + (lambda x: x * 2, 2), + (lambda x: 2 * x, 2), + (lambda x: x == np.float32(2), False), + (lambda x: dpt.add(x, 2, out=x), 3), + (lambda x: x.__iadd__(2), 3), + ], + ids=["array_scalar", "scalar_array", "numpy_scalar", "out", "inplace"], +) +def test_binary_scalar_operand_no_host_copy(monkeypatch, op, expected): + q = get_queue_or_skip() + x = dpt.ones(16, dtype="f4", sycl_queue=q) + + monkeypatch.setattr( + ti, "_copy_numpy_ndarray_into_usm_ndarray", _raise_on_host_copy + ) + res = op(x) + monkeypatch.undo() + + assert (dpt.asnumpy(res) == expected).all() diff --git a/dpnp/tests/tensor/test_tensor_asarray.py b/dpnp/tests/tensor/test_tensor_asarray.py index d4b09ef30312..dc1bd700e909 100644 --- a/dpnp/tests/tensor/test_tensor_asarray.py +++ b/dpnp/tests/tensor/test_tensor_asarray.py @@ -30,6 +30,7 @@ import numpy as np import pytest +import dpnp.libtensor._tensor_impl as ti import dpnp.tensor as dpt from .helper import ( @@ -662,3 +663,73 @@ def test_asarray_to_device_with_unsupported_dtype(dt): x = dpt.ones(10, dtype=dt, device=d0) y = dpt.asarray(x, device=d1) assert y.sycl_device == d1 + + +def _raise_on_host_copy(*args, **kwargs): + raise AssertionError("synchronizing host copy was used") + + +@pytest.mark.parametrize("dt", _all_dtypes) +@pytest.mark.parametrize("kind", ["python", "numpy", "0d"]) +def test_asarray_scalar_no_host_copy(monkeypatch, dt, kind): + q = get_queue_or_skip() + skip_if_dtype_not_supported(dt, q) + + val = {"b": True, "i": 7, "u": 7, "f": 2.5, "c": 1.5 - 2j} + expected = np.asarray(val[np.dtype(dt).kind], dtype=dt) + if kind == "python": + obj, dtype = expected.item(), dt + elif kind == "numpy": + obj, dtype = expected[()], None + else: + obj, dtype = expected, None + + monkeypatch.setattr( + ti, "_copy_numpy_ndarray_into_usm_ndarray", _raise_on_host_copy + ) + x = dpt.asarray(obj, dtype=dtype, sycl_queue=q) + monkeypatch.undo() + + assert x.shape == () + assert x.dtype == expected.dtype + assert dpt.asnumpy(x) == expected + + +def test_asarray_scalar_fp64_on_device_without_fp64(monkeypatch): + q = get_queue_or_skip() + if q.sycl_device.has_aspect_fp64: + pytest.skip("Device supports double precision") + + monkeypatch.setattr( + ti, "_copy_numpy_ndarray_into_usm_ndarray", _raise_on_host_copy + ) + x = dpt.asarray(np.float64(2.5), sycl_queue=q) + y = dpt.asarray(np.complex128(1.5 - 2j), sycl_queue=q) + monkeypatch.undo() + + assert x.dtype == dpt.float32 + assert y.dtype == dpt.complex64 + assert dpt.asnumpy(x) == np.float32(2.5) + assert dpt.asnumpy(y) == np.complex64(1.5 - 2j) + + +@pytest.mark.parametrize( + "obj, dt, expected", + [ + (np.float32(2.5), "i4", 2), + (np.int64(300), "i1", 44), + (np.array(1.5 - 2j, dtype="c8"), "f4", 1.5), + ], +) +def test_asarray_scalar_with_cast(monkeypatch, obj, dt, expected): + q = get_queue_or_skip() + + monkeypatch.setattr( + ti, "_copy_numpy_ndarray_into_usm_ndarray", _raise_on_host_copy + ) + x = dpt.asarray(obj, dtype=dt, sycl_queue=q) + monkeypatch.undo() + + assert x.shape == () + assert x.dtype == dpt.dtype(dt) + assert dpt.asnumpy(x) == np.asarray(expected, dtype=dt) diff --git a/dpnp/tests/tensor/test_usm_ndarray_ctor.py b/dpnp/tests/tensor/test_usm_ndarray_ctor.py index 419910b034e6..b155cb465e48 100644 --- a/dpnp/tests/tensor/test_usm_ndarray_ctor.py +++ b/dpnp/tests/tensor/test_usm_ndarray_ctor.py @@ -36,6 +36,7 @@ import pytest from numpy.testing import assert_raises_regex +import dpnp.libtensor._tensor_impl as ti import dpnp.tensor as dpt from dpnp.tensor import Device from dpnp.tensor._flags import Flags @@ -751,6 +752,64 @@ def test_setitem_scalar(dtype, usm_type): ) +def _raise_on_host_copy(*args, **kwargs): + raise AssertionError("synchronizing host copy was used") + + +@pytest.mark.parametrize("dtype", _all_dtypes) +@pytest.mark.parametrize( + "key", + [Ellipsis, 2, slice(1, 4), slice(None, None, 2), (slice(None), 1)], + ids=["ellipsis", "int", "slice", "step", "column"], +) +def test_setitem_scalar_no_host_copy(monkeypatch, dtype, key): + q = get_queue_or_skip() + skip_if_dtype_not_supported(dtype, q) + X = dpt.zeros((6, 6), dtype=dtype, sycl_queue=q) + expected = np.zeros((6, 6), dtype=dtype) + expected[key] = 1 + + monkeypatch.setattr( + ti, "_copy_numpy_ndarray_into_usm_ndarray", _raise_on_host_copy + ) + X[key] = 1 + monkeypatch.undo() + + assert np.array_equal(dpt.asnumpy(X), expected) + + +# expected values are those of the copy kernel, which narrows floats to +# integers through int64 and keeps the real part of complex values +@pytest.mark.parametrize( + "val, dtype, expected", + [ + (1e10, "i2", -7168), + (1e10, "u2", 58368), + (1e10, "i4", 1410065408), + (-1.0, "u1", 255), + (np.float32(-1), "u8", 2**64 - 1), + (300, "i1", 44), + (2.7, "i4", 2), + (1.5 - 2j, "f4", 1.5), + (1j, "?", True), + (0j, "?", False), + (float("nan"), "?", True), + ], +) +@pytest.mark.filterwarnings("error") +def test_setitem_scalar_cast(monkeypatch, val, dtype, expected): + q = get_queue_or_skip() + X = dpt.zeros((), dtype=dtype, sycl_queue=q) + + monkeypatch.setattr( + ti, "_copy_numpy_ndarray_into_usm_ndarray", _raise_on_host_copy + ) + X[...] = val + monkeypatch.undo() + + assert dpt.asnumpy(X) == np.asarray(expected, dtype=dtype) + + def test_setitem_errors(): q = get_queue_or_skip() X = dpt.empty((4,), dtype="u1", sycl_queue=q) From ddf3213c2e6050b2682737795639eb88a4fdae52 Mon Sep 17 00:00:00 2001 From: Nikita Grigorian Date: Mon, 23 Nov 2026 20:13:10 -0800 Subject: [PATCH 02/17] Wait for the fill before reading memory with copy_to_host in a test The scalar fill in Xusm[...] = 1 no longer blocks, and copy_to_host does not wait for it, so the test read stale memory on an out-of-order queue. --- dpnp/tests/tensor/test_usm_ndarray_ctor.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/dpnp/tests/tensor/test_usm_ndarray_ctor.py b/dpnp/tests/tensor/test_usm_ndarray_ctor.py index b155cb465e48..79add6c8cfef 100644 --- a/dpnp/tests/tensor/test_usm_ndarray_ctor.py +++ b/dpnp/tests/tensor/test_usm_ndarray_ctor.py @@ -533,6 +533,8 @@ def test_ctor_buffer_kwarg(): Xusm = dpt.usm_ndarray((10, 5), dtype="c8") Xusm[...] = 1 X2 = dpt.usm_ndarray(Xusm.shape, buffer=Xusm, dtype=Xusm.dtype) + # copy_to_host does not wait for the fill + Xusm.sycl_queue.wait() Horig_copy = Xusm.usm_data.copy_to_host() H2_copy = X2.usm_data.copy_to_host() assert np.array_equal(Horig_copy, H2_copy) From e09e80fe509a7260c4f2f288355f46b8fc6f39a9 Mon Sep 17 00:00:00 2001 From: Nikita Grigorian Date: Mon, 23 Nov 2026 20:13:41 -0800 Subject: [PATCH 03/17] Share the no-host-copy patch of the scalar tests in the tensor test helper --- .../elementwise/test_elementwise_classes.py | 16 +++------ dpnp/tests/tensor/helper/__init__.py | 2 ++ dpnp/tests/tensor/helper/_helper.py | 19 ++++++++++ dpnp/tests/tensor/test_tensor_asarray.py | 35 ++++++------------- dpnp/tests/tensor/test_usm_ndarray_ctor.py | 24 ++++--------- 5 files changed, 43 insertions(+), 53 deletions(-) diff --git a/dpnp/tests/tensor/elementwise/test_elementwise_classes.py b/dpnp/tests/tensor/elementwise/test_elementwise_classes.py index cc0b77b44e99..f4ec085af570 100644 --- a/dpnp/tests/tensor/elementwise/test_elementwise_classes.py +++ b/dpnp/tests/tensor/elementwise/test_elementwise_classes.py @@ -29,10 +29,9 @@ import numpy as np import pytest -import dpnp.libtensor._tensor_impl as ti import dpnp.tensor as dpt -from ..helper import get_queue_or_skip +from ..helper import get_queue_or_skip, no_host_copy unary_fn = dpt.negative binary_fn = dpt.divide @@ -152,10 +151,6 @@ def test_binary_no_inplace_op(): dpt.logaddexp._inplace_op(x1, x2) -def _raise_on_host_copy(*args, **kwargs): - raise AssertionError("synchronizing host copy was used") - - @pytest.mark.parametrize( "op, expected", [ @@ -167,14 +162,11 @@ def _raise_on_host_copy(*args, **kwargs): ], ids=["array_scalar", "scalar_array", "numpy_scalar", "out", "inplace"], ) -def test_binary_scalar_operand_no_host_copy(monkeypatch, op, expected): +def test_binary_scalar_operand_no_host_copy(op, expected): q = get_queue_or_skip() x = dpt.ones(16, dtype="f4", sycl_queue=q) - monkeypatch.setattr( - ti, "_copy_numpy_ndarray_into_usm_ndarray", _raise_on_host_copy - ) - res = op(x) - monkeypatch.undo() + with no_host_copy(): + res = op(x) assert (dpt.asnumpy(res) == expected).all() diff --git a/dpnp/tests/tensor/helper/__init__.py b/dpnp/tests/tensor/helper/__init__.py index 7fdb1fbe553b..770f1363d75f 100644 --- a/dpnp/tests/tensor/helper/__init__.py +++ b/dpnp/tests/tensor/helper/__init__.py @@ -34,6 +34,7 @@ has_cpu, has_gpu, has_sycl_platforms, + no_host_copy, skip_if_dtype_not_supported, ) @@ -43,5 +44,6 @@ "has_gpu", "has_sycl_platforms", "get_queue_or_skip", + "no_host_copy", "skip_if_dtype_not_supported", ] diff --git a/dpnp/tests/tensor/helper/_helper.py b/dpnp/tests/tensor/helper/_helper.py index 5d0b4825e953..25538efd3fe1 100644 --- a/dpnp/tests/tensor/helper/_helper.py +++ b/dpnp/tests/tensor/helper/_helper.py @@ -26,9 +26,13 @@ # THE POSSIBILITY OF SUCH DAMAGE. # ***************************************************************************** +import contextlib + import dpctl import pytest +import dpnp.libtensor._tensor_impl as ti + def has_gpu(backend="opencl"): return bool(dpctl.get_num_devices(backend=backend, device_type="gpu")) @@ -87,3 +91,18 @@ def skip_if_dtype_not_supported(dt, q_or_dev): pytest.skip( f"{dev.name} does not support half precision floating point type" ) + + +def _raise_on_host_copy(*args, **kwargs): + raise AssertionError("synchronizing host copy was used") + + +@contextlib.contextmanager +def no_host_copy(): + """Makes the synchronizing host copy + `_copy_numpy_ndarray_into_usm_ndarray` raise within the block.""" + with pytest.MonkeyPatch.context() as mp: + mp.setattr( + ti, "_copy_numpy_ndarray_into_usm_ndarray", _raise_on_host_copy + ) + yield diff --git a/dpnp/tests/tensor/test_tensor_asarray.py b/dpnp/tests/tensor/test_tensor_asarray.py index dc1bd700e909..c778b9fca657 100644 --- a/dpnp/tests/tensor/test_tensor_asarray.py +++ b/dpnp/tests/tensor/test_tensor_asarray.py @@ -30,11 +30,11 @@ import numpy as np import pytest -import dpnp.libtensor._tensor_impl as ti import dpnp.tensor as dpt from .helper import ( get_queue_or_skip, + no_host_copy, skip_if_dtype_not_supported, ) @@ -665,13 +665,9 @@ def test_asarray_to_device_with_unsupported_dtype(dt): assert y.sycl_device == d1 -def _raise_on_host_copy(*args, **kwargs): - raise AssertionError("synchronizing host copy was used") - - @pytest.mark.parametrize("dt", _all_dtypes) @pytest.mark.parametrize("kind", ["python", "numpy", "0d"]) -def test_asarray_scalar_no_host_copy(monkeypatch, dt, kind): +def test_asarray_scalar_no_host_copy(dt, kind): q = get_queue_or_skip() skip_if_dtype_not_supported(dt, q) @@ -684,28 +680,22 @@ def test_asarray_scalar_no_host_copy(monkeypatch, dt, kind): else: obj, dtype = expected, None - monkeypatch.setattr( - ti, "_copy_numpy_ndarray_into_usm_ndarray", _raise_on_host_copy - ) - x = dpt.asarray(obj, dtype=dtype, sycl_queue=q) - monkeypatch.undo() + with no_host_copy(): + x = dpt.asarray(obj, dtype=dtype, sycl_queue=q) assert x.shape == () assert x.dtype == expected.dtype assert dpt.asnumpy(x) == expected -def test_asarray_scalar_fp64_on_device_without_fp64(monkeypatch): +def test_asarray_scalar_fp64_on_device_without_fp64(): q = get_queue_or_skip() if q.sycl_device.has_aspect_fp64: pytest.skip("Device supports double precision") - monkeypatch.setattr( - ti, "_copy_numpy_ndarray_into_usm_ndarray", _raise_on_host_copy - ) - x = dpt.asarray(np.float64(2.5), sycl_queue=q) - y = dpt.asarray(np.complex128(1.5 - 2j), sycl_queue=q) - monkeypatch.undo() + with no_host_copy(): + x = dpt.asarray(np.float64(2.5), sycl_queue=q) + y = dpt.asarray(np.complex128(1.5 - 2j), sycl_queue=q) assert x.dtype == dpt.float32 assert y.dtype == dpt.complex64 @@ -721,14 +711,11 @@ def test_asarray_scalar_fp64_on_device_without_fp64(monkeypatch): (np.array(1.5 - 2j, dtype="c8"), "f4", 1.5), ], ) -def test_asarray_scalar_with_cast(monkeypatch, obj, dt, expected): +def test_asarray_scalar_with_cast(obj, dt, expected): q = get_queue_or_skip() - monkeypatch.setattr( - ti, "_copy_numpy_ndarray_into_usm_ndarray", _raise_on_host_copy - ) - x = dpt.asarray(obj, dtype=dt, sycl_queue=q) - monkeypatch.undo() + with no_host_copy(): + x = dpt.asarray(obj, dtype=dt, sycl_queue=q) assert x.shape == () assert x.dtype == dpt.dtype(dt) diff --git a/dpnp/tests/tensor/test_usm_ndarray_ctor.py b/dpnp/tests/tensor/test_usm_ndarray_ctor.py index 79add6c8cfef..b2b9ff5878b9 100644 --- a/dpnp/tests/tensor/test_usm_ndarray_ctor.py +++ b/dpnp/tests/tensor/test_usm_ndarray_ctor.py @@ -36,7 +36,6 @@ import pytest from numpy.testing import assert_raises_regex -import dpnp.libtensor._tensor_impl as ti import dpnp.tensor as dpt from dpnp.tensor import Device from dpnp.tensor._flags import Flags @@ -44,6 +43,7 @@ from .elementwise.utils import _all_dtypes, _integral_dtypes, _real_fp_dtypes from .helper import ( get_queue_or_skip, + no_host_copy, skip_if_dtype_not_supported, ) @@ -754,28 +754,21 @@ def test_setitem_scalar(dtype, usm_type): ) -def _raise_on_host_copy(*args, **kwargs): - raise AssertionError("synchronizing host copy was used") - - @pytest.mark.parametrize("dtype", _all_dtypes) @pytest.mark.parametrize( "key", [Ellipsis, 2, slice(1, 4), slice(None, None, 2), (slice(None), 1)], ids=["ellipsis", "int", "slice", "step", "column"], ) -def test_setitem_scalar_no_host_copy(monkeypatch, dtype, key): +def test_setitem_scalar_no_host_copy(dtype, key): q = get_queue_or_skip() skip_if_dtype_not_supported(dtype, q) X = dpt.zeros((6, 6), dtype=dtype, sycl_queue=q) expected = np.zeros((6, 6), dtype=dtype) expected[key] = 1 - monkeypatch.setattr( - ti, "_copy_numpy_ndarray_into_usm_ndarray", _raise_on_host_copy - ) - X[key] = 1 - monkeypatch.undo() + with no_host_copy(): + X[key] = 1 assert np.array_equal(dpt.asnumpy(X), expected) @@ -799,15 +792,12 @@ def test_setitem_scalar_no_host_copy(monkeypatch, dtype, key): ], ) @pytest.mark.filterwarnings("error") -def test_setitem_scalar_cast(monkeypatch, val, dtype, expected): +def test_setitem_scalar_cast(val, dtype, expected): q = get_queue_or_skip() X = dpt.zeros((), dtype=dtype, sycl_queue=q) - monkeypatch.setattr( - ti, "_copy_numpy_ndarray_into_usm_ndarray", _raise_on_host_copy - ) - X[...] = val - monkeypatch.undo() + with no_host_copy(): + X[...] = val assert dpt.asnumpy(X) == np.asarray(expected, dtype=dtype) From 124b6fc293dcc86570a1f5c0bdef3cb0e137039b Mon Sep 17 00:00:00 2001 From: Nikita Grigorian Date: Mon, 23 Nov 2026 20:51:37 -0800 Subject: [PATCH 04/17] Cast a float scalar to an integer type on the device NaN, inf and values out of the integer range have no defined integer value, so a host cast can differ from what the copy kernel gives on the device, e.g. inf into int64 on a GPU. Fill a 0-d array of the source type and cast it with the copy kernel instead. The tests compare with the copy of a 1-element array on the same device. --- dpnp/tensor/_copy_utils.py | 29 ++++++++++---- dpnp/tests/tensor/test_tensor_asarray.py | 14 +++++++ dpnp/tests/tensor/test_usm_ndarray_ctor.py | 45 ++++++++++++++++++---- 3 files changed, 73 insertions(+), 15 deletions(-) diff --git a/dpnp/tensor/_copy_utils.py b/dpnp/tensor/_copy_utils.py index b402b8a71351..53396e86310c 100644 --- a/dpnp/tensor/_copy_utils.py +++ b/dpnp/tensor/_copy_utils.py @@ -103,7 +103,7 @@ def _copy_from_numpy(np_ary, usm_type="device", sycl_queue=None): def _fill_from_numpy_scalar(dst, np_ary, depends): """ - Fills `dst` with the value of 0-d `np_ary`, cast on the host as + Fills `dst` with the value of 0-d `np_ary`, cast as `_copy_numpy_ndarray_into_usm_ndarray` would cast it. """ copy_q = dst.sycl_queue @@ -116,18 +116,31 @@ def _fill_from_numpy_scalar(dst, np_ary, depends): if np_ary.dtype.kind == "c" and dst_dt.kind not in "bc": # the copy kernel keeps the real part, NumPy also warns np_ary = np_ary.real - # the copy kernel casts NaN and out-of-range values without warning + _manager = SequentialOrderManager[copy_q] + if np_ary.dtype.kind == "f" and dst_dt.kind in "iu": + # NaN, inf and out-of-range values have no defined integer value, + # so cast with the copy kernel of the device + src_dt = np_ary.dtype + val = dpt.empty((), dtype=src_dt, sycl_queue=copy_q) + hev, fill_ev = ti._full_usm_ndarray( + np_ary[()].item(), val, sycl_queue=copy_q + ) + _manager.add_event_pair(hev, fill_ev) + src = dpt.usm_ndarray( + dst.shape, dtype=src_dt, buffer=val, strides=(0,) * dst.ndim + ) + hev, cpy_ev = ti._copy_usm_ndarray_into_usm_ndarray( + src=src, dst=dst, sycl_queue=copy_q, depends=[*depends, fill_ev] + ) + _manager.add_event_pair(hev, cpy_ev) + return + # the copy kernel casts out-of-range values without warning with np.errstate(all="ignore"): - if np_ary.dtype.kind == "f" and dst_dt.kind in "iu": - # the copy kernel narrows through int64, so it wraps like NumPy - # integer casts where a direct NumPy float cast saturates - if dst_dt.itemsize < 8 or (dst_dt.kind == "u" and np_ary < 0): - np_ary = np_ary.astype(np.int64) fill_val = np_ary.astype(dst_dt)[()].item() hev, fill_ev = ti._full_usm_ndarray( fill_val, dst, sycl_queue=copy_q, depends=depends ) - SequentialOrderManager[copy_q].add_event_pair(hev, fill_ev) + _manager.add_event_pair(hev, fill_ev) def _copy_from_numpy_into(dst, np_ary): diff --git a/dpnp/tests/tensor/test_tensor_asarray.py b/dpnp/tests/tensor/test_tensor_asarray.py index c778b9fca657..61bedc63dc8e 100644 --- a/dpnp/tests/tensor/test_tensor_asarray.py +++ b/dpnp/tests/tensor/test_tensor_asarray.py @@ -720,3 +720,17 @@ def test_asarray_scalar_with_cast(obj, dt, expected): assert x.shape == () assert x.dtype == dpt.dtype(dt) assert dpt.asnumpy(x) == np.asarray(expected, dtype=dt) + + +# these float to integer casts are undefined in C++, so the fill must give +# what the copy kernel gives on the same device +@pytest.mark.parametrize("val", [np.nan, np.inf, -np.inf, 1e300], ids=repr) +@pytest.mark.parametrize("dt", ["u1", "i8"]) +def test_asarray_scalar_cast_matches_copy(val, dt): + q = get_queue_or_skip() + + with no_host_copy(): + x = dpt.asarray(np.float64(val), dtype=dt, sycl_queue=q) + y = dpt.asarray(np.array([val]), dtype=dt, sycl_queue=q) + + assert dpt.asnumpy(x) == dpt.asnumpy(y)[0] diff --git a/dpnp/tests/tensor/test_usm_ndarray_ctor.py b/dpnp/tests/tensor/test_usm_ndarray_ctor.py index b2b9ff5878b9..e1467495a420 100644 --- a/dpnp/tests/tensor/test_usm_ndarray_ctor.py +++ b/dpnp/tests/tensor/test_usm_ndarray_ctor.py @@ -773,19 +773,15 @@ def test_setitem_scalar_no_host_copy(dtype, key): assert np.array_equal(dpt.asnumpy(X), expected) -# expected values are those of the copy kernel, which narrows floats to -# integers through int64 and keeps the real part of complex values +# the copy kernel keeps the real part of complex values @pytest.mark.parametrize( "val, dtype, expected", [ - (1e10, "i2", -7168), - (1e10, "u2", 58368), - (1e10, "i4", 1410065408), - (-1.0, "u1", 255), - (np.float32(-1), "u8", 2**64 - 1), (300, "i1", 44), (2.7, "i4", 2), + (-2.7, "i4", -2), (1.5 - 2j, "f4", 1.5), + (1.5 - 2j, "i4", 1), (1j, "?", True), (0j, "?", False), (float("nan"), "?", True), @@ -802,6 +798,41 @@ def test_setitem_scalar_cast(val, dtype, expected): assert dpt.asnumpy(X) == np.asarray(expected, dtype=dtype) +# these float to integer casts are undefined in C++, so the fill must give +# what the copy kernel gives on the same device +@pytest.mark.parametrize("dtype", _integral_dtypes) +@pytest.mark.parametrize( + "val", + [ + np.nan, + np.inf, + -np.inf, + 1e300, + -1e300, + 1e10, + -1.0, + np.float32(-1), + np.float16(-np.inf), + 1e10 + 1j, + ], + ids=repr, +) +@pytest.mark.parametrize("key", [Ellipsis, (slice(None), 1)]) +@pytest.mark.filterwarnings("error") +def test_setitem_scalar_cast_matches_copy(key, val, dtype): + q = get_queue_or_skip() + if isinstance(val, np.float16): + skip_if_dtype_not_supported("f2", q) + X = dpt.zeros((3, 3), dtype=dtype, sycl_queue=q) + + with no_host_copy(): + X[key] = val + Y = dpt.zeros(X[key].shape, dtype=dtype, sycl_queue=q) + Y[...] = np.full(Y.shape, val) + + assert np.array_equal(dpt.asnumpy(X[key]), dpt.asnumpy(Y)) + + def test_setitem_errors(): q = get_queue_or_skip() X = dpt.empty((4,), dtype="u1", sycl_queue=q) From 964f1ee7767f08a6bf3e6f03dfe8642fe0aa3775 Mon Sep 17 00:00:00 2001 From: Nikita Grigorian Date: Mon, 23 Nov 2026 20:51:43 -0800 Subject: [PATCH 05/17] Fill a 1-D strided array without packing its shape and strides The strided fill packed shape and strides into a device allocation and freed it in host tasks, so assigning a scalar to a column was slower than the blocking host copy it replaced. Simplify the iteration space first; a 1-D result passes offset and stride by value, or fills a contiguous range when the stride is 1. --- .../include/kernels/constructors.hpp | 48 ++++++++ dpnp/libtensor/source/full_ctor.cpp | 103 +++++++++++++++++- dpnp/tests/tensor/test_usm_ndarray_ctor.py | 20 +++- 3 files changed, 165 insertions(+), 6 deletions(-) diff --git a/dpnp/libtensor/include/kernels/constructors.hpp b/dpnp/libtensor/include/kernels/constructors.hpp index ac03b15004d4..7911ede4333e 100644 --- a/dpnp/libtensor/include/kernels/constructors.hpp +++ b/dpnp/libtensor/include/kernels/constructors.hpp @@ -62,6 +62,8 @@ class linear_sequence_affine_kernel; template class full_strided_kernel; template +class full_strided_1d_kernel; +template class eye_kernel; using namespace dpnp::tensor::offset_utils; @@ -348,6 +350,52 @@ sycl::event full_strided_impl(sycl::queue &q, return fill_ev; } +/*! + * @brief Function to submit kernel to fill given one-dimensional strided + * memory allocation with specified value. + * + * @param exec_q Sycl queue to which kernel is submitted for execution. + * @param nelems Length of the sequence + * @param offset Offset of the first element from `dst_p`, in elements. + * @param step Stride between consecutive elements, in elements. + * @param fill_v Value to fill the array with + * @param dst_p Kernel accessible USM pointer to the start of array to be + * populated. + * @param depends List of events to wait for before starting computations, if + * any. + * + * @return Event to wait on to ensure that computation completes. + * @defgroup CtorKernels + */ +template +sycl::event full_strided_1d_impl(sycl::queue &q, + std::size_t nelems, + ssize_t offset, + ssize_t step, + dstTy fill_v, + char *dst_p, + const std::vector &depends) +{ + dpnp::tensor::type_utils::validate_type_for_device(q); + + dstTy *dst_tp = reinterpret_cast(dst_p); + + using dpnp::tensor::offset_utils::Strided1DIndexer; + const Strided1DIndexer indexer(offset, nelems, step); + + sycl::event fill_ev = q.submit([&](sycl::handler &cgh) { + cgh.depends_on(depends); + + using KernelName = full_strided_1d_kernel; + using Impl = FullStridedFunctor; + + cgh.parallel_for(sycl::range<1>{nelems}, + Impl(dst_tp, fill_v, indexer)); + }); + + return fill_ev; +} + /* ================ Eye ================== */ typedef sycl::event (*eye_fn_ptr_t)(sycl::queue &, diff --git a/dpnp/libtensor/source/full_ctor.cpp b/dpnp/libtensor/source/full_ctor.cpp index c2820af5d536..205244e207a9 100644 --- a/dpnp/libtensor/source/full_ctor.cpp +++ b/dpnp/libtensor/source/full_ctor.cpp @@ -52,6 +52,7 @@ #include "utils/type_utils.hpp" #include "full_ctor.hpp" +#include "simplify_iteration_space.hpp" namespace py = pybind11; namespace td_ns = dpnp::tensor::type_dispatch; @@ -220,8 +221,65 @@ struct FullStridedFactory } }; +typedef sycl::event (*full_strided_1d_fn_ptr_t)( + sycl::queue &, + std::size_t, + py::ssize_t, + py::ssize_t, + const py::object &, + char *, + const std::vector &); + +/*! + * @brief Function to submit kernel to fill given one-dimensional strided + * memory allocation with specified value. + * + * @param exec_q Sycl queue to which kernel is submitted for execution. + * @param nelems Length of the sequence + * @param offset Offset of the first element from `dst_p`, in elements. + * @param step Stride between consecutive elements, in elements. + * @param py_value Python object representing the value to fill the array with. + * Must be convertible to `dstTy`. + * @param dst_p Kernel accessible USM pointer to the start of array to be + * populated. + * @param depends List of events to wait for before starting computations, if + * any. + * + * @return Event to wait on to ensure that computation completes. + * @defgroup CtorKernels + */ +template +sycl::event full_strided_1d_impl(sycl::queue &exec_q, + std::size_t nelems, + py::ssize_t offset, + py::ssize_t step, + const py::object &py_value, + char *dst_p, + const std::vector &depends) +{ + dstTy fill_v = py::cast(py_value); + + using dpnp::tensor::kernels::constructors::full_strided_1d_impl; + sycl::event fill_ev = full_strided_1d_impl( + exec_q, nelems, offset, step, fill_v, dst_p, depends); + + return fill_ev; +} + +template +struct FullStrided1DFactory +{ + fnT get() + { + fnT f = full_strided_1d_impl; + return f; + } +}; + static full_contig_fn_ptr_t full_contig_dispatch_vector[td_ns::num_types]; static full_strided_fn_ptr_t full_strided_dispatch_vector[td_ns::num_types]; +static full_strided_1d_fn_ptr_t + full_strided_1d_dispatch_vector[td_ns::num_types]; std::pair usm_ndarray_full(const py::object &py_value, @@ -264,16 +322,48 @@ std::pair } else { int nd = dst.get_ndim(); - auto const &dst_shape = dst.get_shape_vector(); + const py::ssize_t *dst_shape = dst.get_shape_raw(); auto const &dst_strides = dst.get_strides_vector(); + using shT = std::vector; + shT simplified_shape; + shT simplified_strides; + py::ssize_t dst_offset(0); + + // nd, simplified_* and dst_offset are modified by reference + simplify_iteration_space_1(nd, dst_shape, dst_strides, + // output + simplified_shape, simplified_strides, + dst_offset); + + if (nd == 1) { + // shape and stride go by value, so no packed temporaries to free + // in host tasks + sycl::event full_1d_event; + const py::ssize_t step = simplified_strides.front(); + if (step == 1) { + auto fn = full_contig_dispatch_vector[dst_typeid]; + full_1d_event = + fn(exec_q, static_cast(dst_nelems), py_value, + dst_data + dst_offset * dst.get_elemsize(), depends); + } + else { + auto fn = full_strided_1d_dispatch_vector[dst_typeid]; + full_1d_event = + fn(exec_q, static_cast(dst_nelems), dst_offset, + step, py_value, dst_data, depends); + } + return std::make_pair( + keep_args_alive(exec_q, {dst}, {full_1d_event}), full_1d_event); + } + auto fn = full_strided_dispatch_vector[dst_typeid]; std::vector host_task_events; host_task_events.reserve(2); using dpnp::tensor::offset_utils::device_allocate_and_pack; auto ptr_size_event_tuple = device_allocate_and_pack( - exec_q, host_task_events, dst_shape, dst_strides); + exec_q, host_task_events, simplified_shape, simplified_strides); auto shape_strides_owner = std::move(std::get<0>(ptr_size_event_tuple)); const sycl::event ©_shape_ev = std::get<2>(ptr_size_event_tuple); py::ssize_t *shape_strides = shape_strides_owner.get(); @@ -285,8 +375,8 @@ std::pair all_deps.push_back(copy_shape_ev); const sycl::event &full_strided_ev = - fn(exec_q, nd, dst_nelems, shape_strides, py_value, dst_data, - all_deps); + fn(exec_q, nd, dst_nelems, shape_strides, py_value, + dst_data + dst_offset * dst.get_elemsize(), all_deps); // free shape_strides const auto &temporaries_cleanup_ev = @@ -310,6 +400,11 @@ void init_full_ctor_dispatch_vectors(void) DispatchVectorBuilder dvb2; dvb2.populate_dispatch_vector(full_strided_dispatch_vector); + + DispatchVectorBuilder + dvb3; + dvb3.populate_dispatch_vector(full_strided_1d_dispatch_vector); } } // namespace dpnp::tensor::py_internal diff --git a/dpnp/tests/tensor/test_usm_ndarray_ctor.py b/dpnp/tests/tensor/test_usm_ndarray_ctor.py index e1467495a420..c3e7adb61931 100644 --- a/dpnp/tests/tensor/test_usm_ndarray_ctor.py +++ b/dpnp/tests/tensor/test_usm_ndarray_ctor.py @@ -757,8 +757,24 @@ def test_setitem_scalar(dtype, usm_type): @pytest.mark.parametrize("dtype", _all_dtypes) @pytest.mark.parametrize( "key", - [Ellipsis, 2, slice(1, 4), slice(None, None, 2), (slice(None), 1)], - ids=["ellipsis", "int", "slice", "step", "column"], + [ + Ellipsis, + 2, + slice(1, 4), + slice(None, None, 2), + (slice(None), 1), + slice(None, None, -1), + (slice(None, None, -1), slice(None, None, 2)), + ], + ids=[ + "ellipsis", + "int", + "slice", + "step", + "column", + "reversed", + "reversed_step", + ], ) def test_setitem_scalar_no_host_copy(dtype, key): q = get_queue_or_skip() From 1aaccb453626a409433b590e3fa198382d64b2f4 Mon Sep 17 00:00:00 2001 From: Nikita Grigorian Date: Mon, 23 Nov 2026 20:51:43 -0800 Subject: [PATCH 06/17] Add an ASV benchmark of binary ufuncs with a Python scalar operand --- benchmarks/benchmarks/bench_elementwise.py | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/benchmarks/benchmarks/bench_elementwise.py b/benchmarks/benchmarks/bench_elementwise.py index ac09887a247e..ef90216f25ac 100644 --- a/benchmarks/benchmarks/bench_elementwise.py +++ b/benchmarks/benchmarks/bench_elementwise.py @@ -165,3 +165,23 @@ def setup(self, executor, ufunc, size, dtype): def time_binary(self, executor, ufunc, size, dtype): self.sync(self.fn(self.a, self.b)) + + +# --------------------------------------------------------------------------- +# A Python scalar operand +# --------------------------------------------------------------------------- + + +class BinaryScalar(_Ufunc): + """Binary ufuncs with a Python scalar operand, e.g. ``2 * x``.""" + + params = [_EXECUTOR_NAMES, ["add", "multiply"], _SIZES_1D, _FLOAT_DTYPES] + + def setup(self, executor, ufunc, size, dtype): + super().setup(executor, ufunc, size, dtype) + self.a = self._input(size, dtype, _DEFAULT_RANGE) + self.sync(self.fn(self.a, 2)) + + def time_binary_scalar(self, executor, ufunc, size, dtype): + # the second call's scalar is filled behind the first call + self.sync(self.fn(self.fn(self.a, 2), 2)) From bb036045caf5aa8763bea3bfdebabd2c8f7a4e2a Mon Sep 17 00:00:00 2001 From: Nikita Grigorian Date: Wed, 2 Dec 2026 11:24:41 -0800 Subject: [PATCH 07/17] Fill contiguous memory with a kernel on CPU devices The OpenCL CPU runtime runs cgh.fill several times slower than a kernel, so assigning a scalar to a large contiguous array, which now fills instead of copying, was slower than the host copy on CPU devices. A 2048 x 2048 float32 fill took 2.1 ms with cgh.fill and 0.67 ms as a broadcast copy on a Core Ultra 7 265U. GPUs keep cgh.fill, which is faster there. --- .../include/kernels/constructors.hpp | 25 ++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/dpnp/libtensor/include/kernels/constructors.hpp b/dpnp/libtensor/include/kernels/constructors.hpp index 7911ede4333e..146dad2eafb8 100644 --- a/dpnp/libtensor/include/kernels/constructors.hpp +++ b/dpnp/libtensor/include/kernels/constructors.hpp @@ -60,6 +60,8 @@ class linear_sequence_step_kernel; template class linear_sequence_affine_kernel; template +class full_contig_kernel; +template class full_strided_kernel; template class full_strided_1d_kernel; @@ -250,6 +252,19 @@ sycl::event lin_space_affine_impl(sycl::queue &exec_q, /* ================ Full ================== */ +template +class ContigFullFunctor +{ +private: + Ty *p = nullptr; + Ty fill_v; + +public: + ContigFullFunctor(Ty *p_, const Ty &fill_v_) : p(p_), fill_v(fill_v_) {} + + void operator()(sycl::id<1> id) const { p[id.get(0)] = fill_v; } +}; + /*! * @brief Function to submit kernel to fill given contiguous memory allocation * with specified value. @@ -273,10 +288,18 @@ sycl::event full_contig_impl(sycl::queue &q, const std::vector &depends) { dpnp::tensor::type_utils::validate_type_for_device(q); + const bool is_cpu = q.get_device().is_cpu(); sycl::event fill_ev = q.submit([&](sycl::handler &cgh) { cgh.depends_on(depends); dstTy *p = reinterpret_cast(dst_p); - cgh.fill(p, fill_v, nelems); + if (is_cpu) { + // the OpenCL CPU runtime runs cgh.fill several times slower + cgh.parallel_for>( + sycl::range<1>{nelems}, ContigFullFunctor(p, fill_v)); + } + else { + cgh.fill(p, fill_v, nelems); + } }); return fill_ev; From 362e05b358ed4d7a0f3ba1d0fd04a0bf425d3326 Mon Sep 17 00:00:00 2001 From: Nikita Grigorian Date: Wed, 2 Dec 2026 11:24:42 -0800 Subject: [PATCH 08/17] Downcast float64 scalars for devices without fp64 without a warning NumPy warns when a float64 value out of the float32 range becomes inf, which made the new cast tests fail under filterwarnings("error") on devices without fp64. The copy kernel gives inf without a warning, so ignore the overflow in both the 0-d fill and the host copy. --- dpnp/tensor/_copy_utils.py | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/dpnp/tensor/_copy_utils.py b/dpnp/tensor/_copy_utils.py index 53396e86310c..ea4e48486bf6 100644 --- a/dpnp/tensor/_copy_utils.py +++ b/dpnp/tensor/_copy_utils.py @@ -108,10 +108,12 @@ def _fill_from_numpy_scalar(dst, np_ary, depends): """ copy_q = dst.sycl_queue if copy_q.sycl_device.has_aspect_fp64 is False: - if np_ary.dtype.char == "d": - np_ary = np_ary.astype(np.float32) - elif np_ary.dtype.char == "D": - np_ary = np_ary.astype(np.complex64) + # out-of-range values become inf without a warning + with np.errstate(over="ignore"): + if np_ary.dtype.char == "d": + np_ary = np_ary.astype(np.float32) + elif np_ary.dtype.char == "D": + np_ary = np_ary.astype(np.complex64) dst_dt = dst.dtype if np_ary.dtype.kind == "c" and dst_dt.kind not in "bc": # the copy kernel keeps the real part, NumPy also warns @@ -173,10 +175,12 @@ def _copy_from_numpy_into(dst, np_ary): copy_q = dst.sycl_queue if copy_q.sycl_device.has_aspect_fp64 is False: src_ary_dt_c = src_ary.dtype.char - if src_ary_dt_c == "d": - src_ary = src_ary.astype(np.float32) - elif src_ary_dt_c == "D": - src_ary = src_ary.astype(np.complex64) + # out-of-range values become inf without a warning + with np.errstate(over="ignore"): + if src_ary_dt_c == "d": + src_ary = src_ary.astype(np.float32) + elif src_ary_dt_c == "D": + src_ary = src_ary.astype(np.complex64) _manager = SequentialOrderManager[copy_q] dep_ev = _manager.submitted_events # synchronizing call From edb3bd6ff67969f9cb659a7a80bad6850e6e6cf6 Mon Sep 17 00:00:00 2001 From: Nikita Grigorian Date: Wed, 2 Dec 2026 11:25:08 -0800 Subject: [PATCH 09/17] Test scalar assignment of float values out of the destination range No case reached the host cast with an overflowing value, so removing the errstate around it passed every test. --- dpnp/tests/tensor/test_usm_ndarray_ctor.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/dpnp/tests/tensor/test_usm_ndarray_ctor.py b/dpnp/tests/tensor/test_usm_ndarray_ctor.py index c3e7adb61931..b5e20f98aafb 100644 --- a/dpnp/tests/tensor/test_usm_ndarray_ctor.py +++ b/dpnp/tests/tensor/test_usm_ndarray_ctor.py @@ -789,11 +789,14 @@ def test_setitem_scalar_no_host_copy(dtype, key): assert np.array_equal(dpt.asnumpy(X), expected) -# the copy kernel keeps the real part of complex values +# the copy kernel keeps the real part of complex values and casts +# out-of-range floats to inf without a warning @pytest.mark.parametrize( "val, dtype, expected", [ (300, "i1", 44), + (1e300, "f4", np.inf), + (-1e300, "f2", -np.inf), (2.7, "i4", 2), (-2.7, "i4", -2), (1.5 - 2j, "f4", 1.5), @@ -806,6 +809,7 @@ def test_setitem_scalar_no_host_copy(dtype, key): @pytest.mark.filterwarnings("error") def test_setitem_scalar_cast(val, dtype, expected): q = get_queue_or_skip() + skip_if_dtype_not_supported(dtype, q) X = dpt.zeros((), dtype=dtype, sycl_queue=q) with no_host_copy(): From 28ea4ab16c021008a5ca9e463877cbcc9686aacb Mon Sep 17 00:00:00 2001 From: Nikita Grigorian Date: Wed, 2 Dec 2026 11:25:08 -0800 Subject: [PATCH 10/17] Test a scalar fill of a view that stays 2-D after simplification X[::-1, ::2] of a 6 x 6 array merges to one dimension, so no case reached the n-D fill with an offset. --- dpnp/tests/tensor/test_usm_ndarray_ctor.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/dpnp/tests/tensor/test_usm_ndarray_ctor.py b/dpnp/tests/tensor/test_usm_ndarray_ctor.py index b5e20f98aafb..2e9e358af4a5 100644 --- a/dpnp/tests/tensor/test_usm_ndarray_ctor.py +++ b/dpnp/tests/tensor/test_usm_ndarray_ctor.py @@ -765,6 +765,7 @@ def test_setitem_scalar(dtype, usm_type): (slice(None), 1), slice(None, None, -1), (slice(None, None, -1), slice(None, None, 2)), + (slice(None, None, -1), slice(None, None, 4)), ], ids=[ "ellipsis", @@ -774,6 +775,7 @@ def test_setitem_scalar(dtype, usm_type): "column", "reversed", "reversed_step", + "reversed_nd", ], ) def test_setitem_scalar_no_host_copy(dtype, key): From 32e96eabeb59107498d3cf5aa8a6af3ef45f9838 Mon Sep 17 00:00:00 2001 From: Nikita Grigorian Date: Wed, 2 Dec 2026 11:25:20 -0800 Subject: [PATCH 11/17] Document the single rounding of a float64 scalar into float16 The copy kernel converts float64 to sycl::half through float, so a 0-d source can round differently from a 1-element one. --- dpnp/tensor/_copy_utils.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/dpnp/tensor/_copy_utils.py b/dpnp/tensor/_copy_utils.py index ea4e48486bf6..7af82a4e949d 100644 --- a/dpnp/tensor/_copy_utils.py +++ b/dpnp/tensor/_copy_utils.py @@ -104,7 +104,9 @@ def _copy_from_numpy(np_ary, usm_type="device", sycl_queue=None): def _fill_from_numpy_scalar(dst, np_ary, depends): """ Fills `dst` with the value of 0-d `np_ary`, cast as - `_copy_numpy_ndarray_into_usm_ndarray` would cast it. + `_copy_numpy_ndarray_into_usm_ndarray` would cast it, except that + float64 and complex128 values are rounded to float16 once, as NumPy + rounds them, where the copy kernel rounds them through float32. """ copy_q = dst.sycl_queue if copy_q.sycl_device.has_aspect_fp64 is False: From c8e11a0de149baf4ac928af872d9d549d936139a Mon Sep 17 00:00:00 2001 From: Nikita Grigorian Date: Wed, 2 Dec 2026 11:26:08 -0800 Subject: [PATCH 12/17] Fill from a 0-d array of non-native byte order A float source of non-native byte order raised in the float to integer path, which creates a device array of the source dtype. --- dpnp/tensor/_copy_utils.py | 2 ++ dpnp/tests/tensor/test_tensor_asarray.py | 2 ++ dpnp/tests/tensor/test_usm_ndarray_ctor.py | 19 +++++++++++++++++++ 3 files changed, 23 insertions(+) diff --git a/dpnp/tensor/_copy_utils.py b/dpnp/tensor/_copy_utils.py index 7af82a4e949d..6dfc4354ad23 100644 --- a/dpnp/tensor/_copy_utils.py +++ b/dpnp/tensor/_copy_utils.py @@ -109,6 +109,8 @@ def _fill_from_numpy_scalar(dst, np_ary, depends): rounds them, where the copy kernel rounds them through float32. """ copy_q = dst.sycl_queue + # dpt.empty only takes the native byte order + np_ary = np_ary.astype(np_ary.dtype.newbyteorder("="), copy=False) if copy_q.sycl_device.has_aspect_fp64 is False: # out-of-range values become inf without a warning with np.errstate(over="ignore"): diff --git a/dpnp/tests/tensor/test_tensor_asarray.py b/dpnp/tests/tensor/test_tensor_asarray.py index 61bedc63dc8e..9c93f2005137 100644 --- a/dpnp/tests/tensor/test_tensor_asarray.py +++ b/dpnp/tests/tensor/test_tensor_asarray.py @@ -709,6 +709,8 @@ def test_asarray_scalar_fp64_on_device_without_fp64(): (np.float32(2.5), "i4", 2), (np.int64(300), "i1", 44), (np.array(1.5 - 2j, dtype="c8"), "f4", 1.5), + (np.array(1.5, dtype=np.dtype("f4").newbyteorder()), "i4", 1), + (np.array(2, dtype=np.dtype("i4").newbyteorder()), "i4", 2), ], ) def test_asarray_scalar_with_cast(obj, dt, expected): diff --git a/dpnp/tests/tensor/test_usm_ndarray_ctor.py b/dpnp/tests/tensor/test_usm_ndarray_ctor.py index 2e9e358af4a5..8f2980f05086 100644 --- a/dpnp/tests/tensor/test_usm_ndarray_ctor.py +++ b/dpnp/tests/tensor/test_usm_ndarray_ctor.py @@ -820,6 +820,25 @@ def test_setitem_scalar_cast(val, dtype, expected): assert dpt.asnumpy(X) == np.asarray(expected, dtype=dtype) +@pytest.mark.parametrize("dtype", ["i4", "f4"]) +@pytest.mark.parametrize( + "val", + [ + np.array(1.5, dtype=np.dtype("f4").newbyteorder()), + np.array(2, dtype=np.dtype("i4").newbyteorder()), + ], + ids=["swapped_f4", "swapped_i4"], +) +def test_setitem_scalar_non_native_byte_order(val, dtype): + q = get_queue_or_skip() + X = dpt.zeros((), dtype=dtype, sycl_queue=q) + + with no_host_copy(): + X[...] = val + + assert dpt.asnumpy(X) == val.astype(dtype) + + # these float to integer casts are undefined in C++, so the fill must give # what the copy kernel gives on the same device @pytest.mark.parametrize("dtype", _integral_dtypes) From b97bb9ef3f2a6a0f83938f57c3aceb3179bfdb4c Mon Sep 17 00:00:00 2001 From: Nikita Grigorian Date: Wed, 2 Dec 2026 11:26:22 -0800 Subject: [PATCH 13/17] Time the scalar operand benchmark on a 16-element array too --- benchmarks/benchmarks/bench_elementwise.py | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/benchmarks/benchmarks/bench_elementwise.py b/benchmarks/benchmarks/bench_elementwise.py index ef90216f25ac..54a2ec784700 100644 --- a/benchmarks/benchmarks/bench_elementwise.py +++ b/benchmarks/benchmarks/bench_elementwise.py @@ -175,7 +175,13 @@ def time_binary(self, executor, ufunc, size, dtype): class BinaryScalar(_Ufunc): """Binary ufuncs with a Python scalar operand, e.g. ``2 * x``.""" - params = [_EXECUTOR_NAMES, ["add", "multiply"], _SIZES_1D, _FLOAT_DTYPES] + # the cost of the scalar itself shows most on small arrays + params = [ + _EXECUTOR_NAMES, + ["add", "multiply"], + [2**4, *_SIZES_1D], + _FLOAT_DTYPES, + ] def setup(self, executor, ufunc, size, dtype): super().setup(executor, ufunc, size, dtype) From fc2533dac31318a94ddef91afc2e052b6fe6a8c5 Mon Sep 17 00:00:00 2001 From: Nikita Grigorian Date: Wed, 2 Dec 2026 11:28:48 -0800 Subject: [PATCH 14/17] Keep the FFT descriptor alive until its transform completes The FFT extension keeps only the input and output arrays alive across the computation, and _compute_result dropped the descriptor on return. A blocking scalar copy when scaling the result used to hide it; with scalars filled asynchronously, builds with oneMath ran the transform on a freed descriptor. Releasing the descriptor in a host task deadlocks with oneMath, so hold it in Python until its FFT event completes. --- CHANGELOG.md | 1 + dpnp/fft/dpnp_utils_fft.py | 31 +++++++++++++++++++++++++++++++ dpnp/tests/test_fft.py | 27 +++++++++++++++++++++++++++ 3 files changed, 59 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index bd05236bdb37..65c67595384f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -67,6 +67,7 @@ This release drops support for Python 3.10, making Python 3.11 the minimum requi * Fixed wrong values from `dpnp.from_dlpack` and `dpnp.tensor.from_dlpack` when copying a `float64` or `complex128` host array to a SYCL device without fp64 support, which copied its bytes unchanged into the `float32` or `complex64` result [#3209](https://github.com/IntelPython/dpnp/pull/3209) * Fixed a random segfault of the OpenCL CPU runtime in coverage builds, and their link failure with `DPNP_TENSOR_GENERATE_COVERAGE_FOR_PYBIND11_EXTENSIONS=ON`, by instrumenting only host code [#3193](https://github.com/IntelPython/dpnp/pull/3193) * Fixed building with the open source DPC++ compiler and CMake 4.5 or newer, which identifies it as `DPClang` instead of `Clang` [#3216](https://github.com/IntelPython/dpnp/pull/3216) +* Fixed wrong results and crashes of `dpnp.fft` functions in builds with oneMath, which released the FFT descriptor before the transform ran [#3182](https://github.com/IntelPython/dpnp/pull/3182) ### Security diff --git a/dpnp/fft/dpnp_utils_fft.py b/dpnp/fft/dpnp_utils_fft.py index 78893a3c01e4..9ba74fa53137 100644 --- a/dpnp/fft/dpnp_utils_fft.py +++ b/dpnp/fft/dpnp_utils_fft.py @@ -39,8 +39,11 @@ # pylint: disable=protected-access # pylint: disable=no-name-in-module +import atexit +import threading from collections.abc import Sequence +import dpctl import dpctl.utils as dpu import numpy @@ -60,6 +63,33 @@ _standardize_strides_to_nonzero, ) +# The FFT extension keeps only the arrays alive until its kernel ends, and +# releasing a oneMath descriptor in a host task deadlocks, so each descriptor +# stays here until its FFT has completed. +# TODO: remove once dpnp uses dpctl's deferred releases, which need no host task +_pending_descriptors = [] +_pending_descriptors_lock = threading.Lock() + + +def _keep_descriptor_alive(dsc, fft_event): + """Holds `dsc` until `fft_event` completes, releasing completed ones.""" + complete = dpctl.event_status_type.complete + with _pending_descriptors_lock: + _pending_descriptors[:] = [ + (d, ev) + for d, ev in _pending_descriptors + if ev.execution_status != complete + ] + _pending_descriptors.append((dsc, fft_event)) + + +@atexit.register +def _release_pending_descriptors(): + with _pending_descriptors_lock: + for _, ev in _pending_descriptors: + ev.wait() + _pending_descriptors.clear() + def _check_norm(norm): if norm not in (None, "ortho", "forward", "backward"): @@ -240,6 +270,7 @@ def _compute_result(dsc, a, out, forward, c2c, out_strides): dsc, a_usm, res_usm, forward, depends=dep_evs ) _manager.add_event_pair(ht_fft_event, fft_event) + _keep_descriptor_alive(dsc, fft_event) if not isinstance(result, dpnp_array): return dpnp_array._create_from_usm_ndarray(result) diff --git a/dpnp/tests/test_fft.py b/dpnp/tests/test_fft.py index b0c11cd21091..6d6a9803f02b 100644 --- a/dpnp/tests/test_fft.py +++ b/dpnp/tests/test_fft.py @@ -1,3 +1,5 @@ +import weakref + import dpctl import numpy import pytest @@ -974,3 +976,28 @@ def test_1d_array(self): expected = numpy.fft.irfftn(a) flag = True if numpy_version() < "2.0.0" else False assert_dtype_allclose(result, expected, check_only_type_kind=flag) + + +@pytest.mark.parametrize("in_place", [False, True]) +def test_descriptor_outlives_its_fft(monkeypatch, in_place): + import dpnp.libtensor._fft_impl as fi + + name = "_fft_in_place" if in_place else "_fft_out_of_place" + fft_fn = getattr(fi, name) + calls = [] + + def _fft(dsc, *args, **kwargs): + ht_ev, fft_ev = fft_fn(dsc, *args, **kwargs) + calls.append((weakref.ref(dsc), fft_ev)) + return ht_ev, fft_ev + + monkeypatch.setattr(fi, name, _fft) + a = dpnp.ones(64, dtype=dpnp.complex64) + dpnp.fft.fft(a, out=a if in_place else None) + dsc_ref, fft_ev = calls[0] + # the extension keeps only the arrays alive while the FFT runs + assert dsc_ref() is not None + + fft_ev.wait() + dpnp.fft.fft(a) + assert dsc_ref() is None From c217c9381c1df218671a7f32761499fb8bb6ed73 Mon Sep 17 00:00:00 2001 From: Nikita Grigorian Date: Wed, 2 Dec 2026 11:31:32 -0800 Subject: [PATCH 15/17] Wait for submitted work before copying in to_device and __dlpack__ to_device to another context copies through the host, and __dlpack__ with copy=True submits a memcpy, both without dependencies, so they could copy an array before its fill or the kernel computing it ran. This was already the case for dpt.full; with scalars filled on the device it also affects x[...] = v and asarray. --- CHANGELOG.md | 3 ++- dpnp/tensor/_usmarray.pyx | 10 ++++++++++ dpnp/tests/tensor/helper/__init__.py | 2 ++ dpnp/tests/tensor/helper/_helper.py | 11 +++++++++++ dpnp/tests/tensor/test_usm_ndarray_ctor.py | 13 +++++++++++++ dpnp/tests/tensor/test_usm_ndarray_dlpack.py | 12 ++++++++++++ 6 files changed, 50 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 65c67595384f..77da3905dcdf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -31,7 +31,7 @@ This release drops support for Python 3.10, making Python 3.11 the minimum requi * Changed `dpnp.median`, `dpnp.nanmedian` and `dpnp.partition` with a single `kth` to use a radix select instead of a full sort for all but complex data types and, on a GPU, `dpnp.partition` of rows of 65 to 128 elements of 8-byte integers [#3138](https://github.com/IntelPython/dpnp/pull/3138) * Improved performance of `dpnp.top_k` and `dpnp.tensor.top_k` on a GPU for batches of rows of 65536 to about 10^6 elements that occupy it with a work-group per row [#3138](https://github.com/IntelPython/dpnp/pull/3138) * Changed the C++ standard used to build dpnp and the pybind11 example from C++17 to C++20. C++ extensions that include the headers shipped with dpnp (`dpnp4pybind11.hpp`, the libtensor headers) must now be built as C++20 [#3190](https://github.com/IntelPython/dpnp/pull/3190) -* Changed `dpnp.asarray`, `dpnp.tensor.asarray` and assignment through basic indexing (e.g. `x[0] = 1`, `x[:, 0] = 0`) to fill a scalar or 0-d NumPy array on the device instead of copying it from the host, which waited for all work queued on the device, so binary operators and functions with a Python or NumPy scalar operand (e.g. `2 * x`, `x == 0`, `dpnp.clip(x, 0, 1)`) no longer block the host [#3182](https://github.com/IntelPython/dpnp/pull/3182) +* Changed `dpnp.asarray`, `dpnp.tensor.asarray` and assignment through basic indexing (e.g. `x[0] = 1`, `x[:, 0] = 0`) to fill a scalar or 0-d NumPy array on the device instead of copying it from the host, which waited for all work queued on the device, so binary operators and functions with a Python or NumPy scalar operand (e.g. `2 * x`, `x == 0`, `dpnp.clip(x, 0, 1)`) no longer block the host. Code that reads the memory directly, e.g. with `x.usm_data.copy_to_host()`, must call `x.sycl_queue.wait()` first [#3182](https://github.com/IntelPython/dpnp/pull/3182) ### Deprecated @@ -68,6 +68,7 @@ This release drops support for Python 3.10, making Python 3.11 the minimum requi * Fixed a random segfault of the OpenCL CPU runtime in coverage builds, and their link failure with `DPNP_TENSOR_GENERATE_COVERAGE_FOR_PYBIND11_EXTENSIONS=ON`, by instrumenting only host code [#3193](https://github.com/IntelPython/dpnp/pull/3193) * Fixed building with the open source DPC++ compiler and CMake 4.5 or newer, which identifies it as `DPClang` instead of `Clang` [#3216](https://github.com/IntelPython/dpnp/pull/3216) * Fixed wrong results and crashes of `dpnp.fft` functions in builds with oneMath, which released the FFT descriptor before the transform ran [#3182](https://github.com/IntelPython/dpnp/pull/3182) +* Fixed `dpnp.ndarray.to_device` and `dpnp.tensor.usm_ndarray.to_device` to a device in another SYCL context, and `__dlpack__` with `copy=True`, copying the array before work queued to compute it completed [#3182](https://github.com/IntelPython/dpnp/pull/3182) ### Security diff --git a/dpnp/tensor/_usmarray.pyx b/dpnp/tensor/_usmarray.pyx index c847f9c31cff..b259a76e6779 100644 --- a/dpnp/tensor/_usmarray.pyx +++ b/dpnp/tensor/_usmarray.pyx @@ -36,6 +36,7 @@ import warnings import dpctl import dpctl.memory as dpmem import numpy as np +from dpctl.utils import SequentialOrderManager from dpctl._backend cimport DPCTLSyclUSMRef from dpctl._sycl_device_factory cimport _cached_default_device @@ -179,6 +180,11 @@ cdef object _as_zero_dim_ndarray(object usm_ary): return view +cdef void _wait_for_submitted(c_dpctl.SyclQueue q) except *: + "Wait for the work that dpnp submitted to `q`, e.g. a scalar fill" + dpctl.SyclEvent.wait_for(SequentialOrderManager[q].submitted_events) + + cdef inline void _check_0d_scalar_conversion(object usm_ary) except *: "Raise TypeError if array cannot be converted to a Python scalar" if (usm_ary.ndim != 0): @@ -1180,6 +1186,8 @@ cdef class usm_ndarray: copy_buffer = type(self.usm_data)( nbytes, queue=d.sycl_queue ) + # the copy goes through the host without dependencies + _wait_for_submitted(self.sycl_queue) copy_buffer.copy_from_device(self.usm_data) res = usm_ndarray( self.shape, @@ -1390,6 +1398,8 @@ cdef class usm_ndarray: copy_buffer = type(self.usm_data)( nbytes, queue=self.sycl_queue ) + # the copy is submitted without dependencies + _wait_for_submitted(self.sycl_queue) copy_buffer.copy_from_device(self.usm_data) _copied_arr = usm_ndarray( self.shape, diff --git a/dpnp/tests/tensor/helper/__init__.py b/dpnp/tests/tensor/helper/__init__.py index 770f1363d75f..1c84fad818a8 100644 --- a/dpnp/tests/tensor/helper/__init__.py +++ b/dpnp/tests/tensor/helper/__init__.py @@ -35,6 +35,7 @@ has_gpu, has_sycl_platforms, no_host_copy, + queue_long_kernel, skip_if_dtype_not_supported, ) @@ -45,5 +46,6 @@ "has_sycl_platforms", "get_queue_or_skip", "no_host_copy", + "queue_long_kernel", "skip_if_dtype_not_supported", ] diff --git a/dpnp/tests/tensor/helper/_helper.py b/dpnp/tests/tensor/helper/_helper.py index 25538efd3fe1..d33f4075b3ad 100644 --- a/dpnp/tests/tensor/helper/_helper.py +++ b/dpnp/tests/tensor/helper/_helper.py @@ -93,6 +93,17 @@ def skip_if_dtype_not_supported(dt, q_or_dev): ) +def queue_long_kernel(q): + """Submits matmuls to `q` that keep the device busy for a while, so that + work submitted next is still pending when the host reads the result.""" + import dpnp.tensor as dpt + + n = 1024 + a = dpt.full((n, n), 1 / n, dtype="f4", sycl_queue=q) + for _ in range(4): + a = dpt.matmul(a, a) + + def _raise_on_host_copy(*args, **kwargs): raise AssertionError("synchronizing host copy was used") diff --git a/dpnp/tests/tensor/test_usm_ndarray_ctor.py b/dpnp/tests/tensor/test_usm_ndarray_ctor.py index 8f2980f05086..bbf9a48e8b9d 100644 --- a/dpnp/tests/tensor/test_usm_ndarray_ctor.py +++ b/dpnp/tests/tensor/test_usm_ndarray_ctor.py @@ -44,6 +44,7 @@ from .helper import ( get_queue_or_skip, no_host_copy, + queue_long_kernel, skip_if_dtype_not_supported, ) @@ -1072,6 +1073,18 @@ def test_to_device_migration(): assert X1.usm_data._pointer == X2.usm_data._pointer +def test_to_device_other_context_waits_for_fill(): + q = get_queue_or_skip() + q2 = dpctl.SyclQueue(dpctl.SyclContext([q.sycl_device]), q.sycl_device) + X = dpt.zeros(4, dtype="i4", sycl_queue=q) + queue_long_kernel(q) + X[...] = 7 + + Y = X.to_device(q2) + assert Y.sycl_context != X.sycl_context + assert np.array_equal(dpt.asnumpy(Y), np.full(4, 7, dtype="i4")) + + def test_astype(): try: X = dpt.empty((5, 5), dtype="i4") diff --git a/dpnp/tests/tensor/test_usm_ndarray_dlpack.py b/dpnp/tests/tensor/test_usm_ndarray_dlpack.py index 7339248e6c5a..b0cf2630f0fa 100644 --- a/dpnp/tests/tensor/test_usm_ndarray_dlpack.py +++ b/dpnp/tests/tensor/test_usm_ndarray_dlpack.py @@ -39,6 +39,7 @@ from .helper import ( get_queue_or_skip, + queue_long_kernel, skip_if_dtype_not_supported, ) from .helper._dlpack_ctypes import ( @@ -502,6 +503,17 @@ def test_from_dlpack_kwargs(): assert z._pointer == x._pointer +def test_from_dlpack_copy_waits_for_fill(): + q = get_queue_or_skip() + x = dpt.zeros(4, dtype="i4", sycl_queue=q) + queue_long_kernel(q) + x[...] = 7 + + y = dpt.from_dlpack(x, copy=True) + assert x._pointer != y._pointer + assert np.array_equal(dpt.asnumpy(y), np.full(4, 7, dtype="i4")) + + def test_dlpack_deleters(): try: x = dpt.arange(100, dtype="i4") From 020228c596b4068c0fdf1e49878294bbba823007 Mon Sep 17 00:00:00 2001 From: Nikita Grigorian Date: Wed, 2 Dec 2026 11:43:20 -0800 Subject: [PATCH 16/17] Order a DLPack import after the work on the exporter's queue from_dlpack of a usm_ndarray imports it onto the cached queue of its device, but called __dlpack__ without a stream, so work on the import could run before work already submitted to the exporter's queue, e.g. a scalar fill. Pass the cached queue as the stream, which makes __dlpack__ submit a barrier ordering it after the exporter's queue. dpnp.from_dlpack passes the usm_ndarray of a dpnp.ndarray for the same. Reading through the exporter still waits only for its own queue, so the 0-d view test waits for the queue of the import first. --- dpnp/dpnp_iface_arraycreation.py | 3 +++ dpnp/tensor/_dlpack.pyx | 12 +++++++++++- dpnp/tests/tensor/test_usm_ndarray_dlpack.py | 15 +++++++++++++++ dpnp/tests/test_dlpack.py | 15 +++++++++++++++ 4 files changed, 44 insertions(+), 1 deletion(-) diff --git a/dpnp/dpnp_iface_arraycreation.py b/dpnp/dpnp_iface_arraycreation.py index 8076962178c5..d77f0770e691 100644 --- a/dpnp/dpnp_iface_arraycreation.py +++ b/dpnp/dpnp_iface_arraycreation.py @@ -2320,6 +2320,9 @@ def from_dlpack(x, /, *, device=None, copy=None): """ + if isinstance(x, dpnp_array): + # dpnp.tensor orders the import after the work on the queue of `x` + x = x.get_array() result = dpt.from_dlpack(x, device=device, copy=copy) if isinstance(result, dpt.usm_ndarray): return dpnp_array._create_from_usm_ndarray(result) diff --git a/dpnp/tensor/_dlpack.pyx b/dpnp/tensor/_dlpack.pyx index 31a687746288..884ba3cabf67 100644 --- a/dpnp/tensor/_dlpack.pyx +++ b/dpnp/tensor/_dlpack.pyx @@ -1121,13 +1121,23 @@ def from_dlpack(x, /, *, device=None, copy=None): # First DLPack version supporting dl_device, and copy requested_ver = (1, 0) cpu_dev = (device_CPU, 0) + dlpack_kwargs = {} + if isinstance(x, usm_ndarray) and ( + dl_device is None or dl_device == x.__dlpack_device__() + ): + # the import goes to the cached queue, so order its work after + # the work submitted to the queue of `x` + dlpack_kwargs["stream"] = get_device_cached_queue( + (x.sycl_context, x.sycl_device,) + ) try: # setting max_version to minimal version that supports # dl_device/copy keywords dlpack_capsule = dlpack_attr( max_version=requested_ver, dl_device=dl_device, - copy=copy + copy=copy, + **dlpack_kwargs ) except TypeError: # exporter does not support max_version keyword diff --git a/dpnp/tests/tensor/test_usm_ndarray_dlpack.py b/dpnp/tests/tensor/test_usm_ndarray_dlpack.py index b0cf2630f0fa..d0d9d8899e89 100644 --- a/dpnp/tests/tensor/test_usm_ndarray_dlpack.py +++ b/dpnp/tests/tensor/test_usm_ndarray_dlpack.py @@ -382,9 +382,24 @@ def test_from_dlpack_0d_view_is_writable(): y = dpt.from_dlpack(x) y[...] = 7 + # reading through x waits only for the queue of x + y.sycl_queue.wait() assert int(x) == 7 +def test_from_dlpack_orders_import_after_exporter(): + q = get_queue_or_skip() + x = dpt.zeros(4, dtype="i4", sycl_queue=q) + queue_long_kernel(q) + x[...] = 5 + + y = dpt.from_dlpack(x) + assert y.sycl_queue != x.sycl_queue + y[...] = 7 + y.sycl_queue.wait() + assert np.array_equal(dpt.asnumpy(x), np.full(4, 7, dtype="i4")) + + @pytest.mark.parametrize( "versioned", [True, False], ids=["versioned", "legacy"] ) diff --git a/dpnp/tests/test_dlpack.py b/dpnp/tests/test_dlpack.py index 366e3fcfc766..b166300fadbd 100644 --- a/dpnp/tests/test_dlpack.py +++ b/dpnp/tests/test_dlpack.py @@ -71,6 +71,21 @@ def test_device(self): z = y[::2] assert z.__dlpack_device__()[0] == dpnp.DLDeviceType.kDLOneAPI + def test_import_ordered_after_exporter(self): + q = dpctl.SyclQueue() + x = dpnp.zeros(4, dtype="i4", sycl_queue=q) + a = dpnp.full((1024, 1024), 1 / 1024, dtype="f4", sycl_queue=q) + for _ in range(4): + # keeps the device busy, so that the fill of x is still queued + a = dpnp.matmul(a, a) + x[...] = 5 + + y = dpnp.from_dlpack(x) + assert y.sycl_queue != x.sycl_queue + y[...] = 7 + y.sycl_queue.wait() + assert_array_equal(x, numpy.full(4, 7, dtype="i4")) + def test_ndim0(self): x = dpnp.array(1.0) y = dpnp.from_dlpack(x) From 29f2c02fc3771b783e1c1729249572ba789b5b9f Mon Sep 17 00:00:00 2001 From: Nikita Grigorian Date: Wed, 2 Dec 2026 12:29:41 -0800 Subject: [PATCH 17/17] Add a changelog entry for the faster fill on CPU devices --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 77da3905dcdf..07df7dc997ef 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -32,6 +32,7 @@ This release drops support for Python 3.10, making Python 3.11 the minimum requi * Improved performance of `dpnp.top_k` and `dpnp.tensor.top_k` on a GPU for batches of rows of 65536 to about 10^6 elements that occupy it with a work-group per row [#3138](https://github.com/IntelPython/dpnp/pull/3138) * Changed the C++ standard used to build dpnp and the pybind11 example from C++17 to C++20. C++ extensions that include the headers shipped with dpnp (`dpnp4pybind11.hpp`, the libtensor headers) must now be built as C++20 [#3190](https://github.com/IntelPython/dpnp/pull/3190) * Changed `dpnp.asarray`, `dpnp.tensor.asarray` and assignment through basic indexing (e.g. `x[0] = 1`, `x[:, 0] = 0`) to fill a scalar or 0-d NumPy array on the device instead of copying it from the host, which waited for all work queued on the device, so binary operators and functions with a Python or NumPy scalar operand (e.g. `2 * x`, `x == 0`, `dpnp.clip(x, 0, 1)`) no longer block the host. Code that reads the memory directly, e.g. with `x.usm_data.copy_to_host()`, must call `x.sycl_queue.wait()` first [#3182](https://github.com/IntelPython/dpnp/pull/3182) +* Improved performance of filling an array with a nonzero value on a CPU device, e.g. in `dpnp.full`, `dpnp.tensor.full` and `x[...] = 1` [#3182](https://github.com/IntelPython/dpnp/pull/3182) ### Deprecated