diff --git a/CHANGELOG.md b/CHANGELOG.md index 5d0fb5cacd24..07df7dc997ef 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -31,6 +31,8 @@ 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. 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 @@ -66,6 +68,8 @@ 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) +* 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/benchmarks/benchmarks/bench_elementwise.py b/benchmarks/benchmarks/bench_elementwise.py index ac09887a247e..54a2ec784700 100644 --- a/benchmarks/benchmarks/bench_elementwise.py +++ b/benchmarks/benchmarks/bench_elementwise.py @@ -165,3 +165,29 @@ 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``.""" + + # 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) + 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)) 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/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/libtensor/include/kernels/constructors.hpp b/dpnp/libtensor/include/kernels/constructors.hpp index ac03b15004d4..146dad2eafb8 100644 --- a/dpnp/libtensor/include/kernels/constructors.hpp +++ b/dpnp/libtensor/include/kernels/constructors.hpp @@ -60,8 +60,12 @@ 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; +template class eye_kernel; using namespace dpnp::tensor::offset_utils; @@ -248,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. @@ -271,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; @@ -348,6 +373,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/tensor/_copy_utils.py b/dpnp/tensor/_copy_utils.py index e54147366abe..6dfc4354ad23 100644 --- a/dpnp/tensor/_copy_utils.py +++ b/dpnp/tensor/_copy_utils.py @@ -101,12 +101,65 @@ 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 as + `_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 + # 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"): + 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 + _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"): + fill_val = np_ary.astype(dst_dt)[()].item() + hev, fill_ev = ti._full_usm_ndarray( + fill_val, dst, sycl_queue=copy_q, depends=depends + ) + _manager.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: @@ -126,10 +179,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 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/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/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/elementwise/test_elementwise_classes.py b/dpnp/tests/tensor/elementwise/test_elementwise_classes.py index 04b92937f371..f4ec085af570 100644 --- a/dpnp/tests/tensor/elementwise/test_elementwise_classes.py +++ b/dpnp/tests/tensor/elementwise/test_elementwise_classes.py @@ -26,11 +26,12 @@ # THE POSSIBILITY OF SUCH DAMAGE. # ***************************************************************************** +import numpy as np import pytest 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 @@ -148,3 +149,24 @@ def test_binary_no_inplace_op(): with pytest.raises(ValueError): dpt.logaddexp._inplace_op(x1, x2) + + +@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(op, expected): + q = get_queue_or_skip() + x = dpt.ones(16, dtype="f4", sycl_queue=q) + + 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..1c84fad818a8 100644 --- a/dpnp/tests/tensor/helper/__init__.py +++ b/dpnp/tests/tensor/helper/__init__.py @@ -34,6 +34,8 @@ has_cpu, has_gpu, has_sycl_platforms, + no_host_copy, + queue_long_kernel, skip_if_dtype_not_supported, ) @@ -43,5 +45,7 @@ "has_gpu", "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 5d0b4825e953..d33f4075b3ad 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,29 @@ def skip_if_dtype_not_supported(dt, q_or_dev): pytest.skip( f"{dev.name} does not support half precision floating point type" ) + + +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") + + +@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 d4b09ef30312..9c93f2005137 100644 --- a/dpnp/tests/tensor/test_tensor_asarray.py +++ b/dpnp/tests/tensor/test_tensor_asarray.py @@ -34,6 +34,7 @@ from .helper import ( get_queue_or_skip, + no_host_copy, skip_if_dtype_not_supported, ) @@ -662,3 +663,76 @@ 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 + + +@pytest.mark.parametrize("dt", _all_dtypes) +@pytest.mark.parametrize("kind", ["python", "numpy", "0d"]) +def test_asarray_scalar_no_host_copy(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 + + 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(): + q = get_queue_or_skip() + if q.sycl_device.has_aspect_fp64: + pytest.skip("Device supports double precision") + + 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 + 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), + (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): + q = get_queue_or_skip() + + with no_host_copy(): + x = dpt.asarray(obj, dtype=dt, sycl_queue=q) + + 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 419910b034e6..bbf9a48e8b9d 100644 --- a/dpnp/tests/tensor/test_usm_ndarray_ctor.py +++ b/dpnp/tests/tensor/test_usm_ndarray_ctor.py @@ -43,6 +43,8 @@ from .elementwise.utils import _all_dtypes, _integral_dtypes, _real_fp_dtypes from .helper import ( get_queue_or_skip, + no_host_copy, + queue_long_kernel, skip_if_dtype_not_supported, ) @@ -532,6 +534,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) @@ -751,6 +755,126 @@ 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), + slice(None, None, -1), + (slice(None, None, -1), slice(None, None, 2)), + (slice(None, None, -1), slice(None, None, 4)), + ], + ids=[ + "ellipsis", + "int", + "slice", + "step", + "column", + "reversed", + "reversed_step", + "reversed_nd", + ], +) +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 + + with no_host_copy(): + X[key] = 1 + + assert np.array_equal(dpt.asnumpy(X), expected) + + +# 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), + (1.5 - 2j, "i4", 1), + (1j, "?", True), + (0j, "?", False), + (float("nan"), "?", True), + ], +) +@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(): + X[...] = val + + 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) +@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) @@ -949,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..d0d9d8899e89 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 ( @@ -381,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"] ) @@ -502,6 +518,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") diff --git a/dpnp/tests/test_dlpack.py b/dpnp/tests/test_dlpack.py index 22c19a39e5b7..d5d24db9c9a2 100644 --- a/dpnp/tests/test_dlpack.py +++ b/dpnp/tests/test_dlpack.py @@ -71,6 +71,21 @@ def test_dlpack_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) 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