diff --git a/CHANGELOG.md b/CHANGELOG.md index 24442cb0da7a..ec4643c918fe 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -30,6 +30,7 @@ This release drops support for Python 3.10, making Python 3.11 the minimum requi * Bumped the minimum required `dpctl` version to `0.24.0` [#3169](https://github.com/IntelPython/dpnp/pull/3169) * 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 `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/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)) 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/tensor/_copy_utils.py b/dpnp/tensor/_copy_utils.py index e54147366abe..53396e86310c 100644 --- a/dpnp/tensor/_copy_utils.py +++ b/dpnp/tensor/_copy_utils.py @@ -101,12 +101,59 @@ 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. + """ + 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 + _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: 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..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..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 d4b09ef30312..61bedc63dc8e 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,74 @@ 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), + ], +) +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..c3e7adb61931 100644 --- a/dpnp/tests/tensor/test_usm_ndarray_ctor.py +++ b/dpnp/tests/tensor/test_usm_ndarray_ctor.py @@ -43,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, ) @@ -532,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) @@ -751,6 +754,101 @@ 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)), + ], + ids=[ + "ellipsis", + "int", + "slice", + "step", + "column", + "reversed", + "reversed_step", + ], +) +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 +@pytest.mark.parametrize( + "val, dtype, expected", + [ + (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), + ], +) +@pytest.mark.filterwarnings("error") +def test_setitem_scalar_cast(val, dtype, expected): + q = get_queue_or_skip() + X = dpt.zeros((), dtype=dtype, sycl_queue=q) + + with no_host_copy(): + X[...] = val + + 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)