Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
20 changes: 20 additions & 0 deletions benchmarks/benchmarks/bench_elementwise.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: _SIZES_1D starts at 2**16, so this misses the small arrays where the scalar cost shows most. The issue measured 19 vs 60 us per call at shape (16,). A small size (or a separate params list with one) would catch a regression in the scalar path itself, not only the queue drain.


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))
48 changes: 48 additions & 0 deletions dpnp/libtensor/include/kernels/constructors.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,8 @@ class linear_sequence_affine_kernel;
template <typename Ty>
class full_strided_kernel;
template <typename Ty>
class full_strided_1d_kernel;
template <typename Ty>
class eye_kernel;

using namespace dpnp::tensor::offset_utils;
Expand Down Expand Up @@ -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 <typename dstTy>
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<sycl::event> &depends)
{
dpnp::tensor::type_utils::validate_type_for_device<dstTy>(q);

dstTy *dst_tp = reinterpret_cast<dstTy *>(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<dstTy>;
using Impl = FullStridedFunctor<dstTy, Strided1DIndexer>;

cgh.parallel_for<KernelName>(sycl::range<1>{nelems},
Impl(dst_tp, fill_v, indexer));
});

return fill_ev;
}

/* ================ Eye ================== */

typedef sycl::event (*eye_fn_ptr_t)(sycl::queue &,
Expand Down
103 changes: 99 additions & 4 deletions dpnp/libtensor/source/full_ctor.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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<sycl::event> &);

/*!
* @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 <typename dstTy>
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<sycl::event> &depends)
{
dstTy fill_v = py::cast<dstTy>(py_value);

using dpnp::tensor::kernels::constructors::full_strided_1d_impl;
sycl::event fill_ev = full_strided_1d_impl<dstTy>(
exec_q, nelems, offset, step, fill_v, dst_p, depends);

return fill_ev;
}

template <typename fnT, typename Ty>
struct FullStrided1DFactory
{
fnT get()
{
fnT f = full_strided_1d_impl<Ty>;
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<sycl::event, sycl::event>
usm_ndarray_full(const py::object &py_value,
Expand Down Expand Up @@ -264,16 +322,48 @@ std::pair<sycl::event, sycl::event>
}
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<py::ssize_t>;
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<std::size_t>(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<std::size_t>(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<sycl::event> 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<py::ssize_t>(
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 &copy_shape_ev = std::get<2>(ptr_size_event_tuple);
py::ssize_t *shape_strides = shape_strides_owner.get();
Expand All @@ -285,8 +375,8 @@ std::pair<sycl::event, sycl::event>
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 =
Expand All @@ -310,6 +400,11 @@ void init_full_ctor_dispatch_vectors(void)
DispatchVectorBuilder<full_strided_fn_ptr_t, FullStridedFactory, num_types>
dvb2;
dvb2.populate_dispatch_vector(full_strided_dispatch_vector);

DispatchVectorBuilder<full_strided_1d_fn_ptr_t, FullStrided1DFactory,
num_types>
dvb3;
dvb3.populate_dispatch_vector(full_strided_1d_dispatch_vector);
}

} // namespace dpnp::tensor::py_internal
47 changes: 47 additions & 0 deletions dpnp/tensor/_copy_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Comment on lines +106 to +107

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not quite for float16 destinations. Master's device cast of a float64 value to float16 rounds twice (static_cast<sycl::half>(double) goes through float, the only constructor of sycl::half), while np_ary.astype(dst_dt) rounds once. So a 0-d source and a 1-element source now give different results on the same device:

x = dpt.zeros((), dtype="f2")
x[...] = 1 + 2**-11 + 2**-40          # this PR: 0x3c01 (as NumPy), master: 0x3c00
y = dpt.zeros(1, dtype="f2")
y[...] = np.array([1 + 2**-11 + 2**-40])  # 0x3c00 on both

It is the same in all 0-d entry points (asarray(v, dtype="f2"), x[...] = v, strided views, dpnp.add(..., dtype="f2")), for both double-rounding values in the matrix (1 + 2**-11 + 2**-40 and 1 + 2**-11 + 2**-30, also as the real part of a complex source), on the Max 1100, Panther Lake-H, Arc Pro B70 and their CPUs. Devices without fp64 don't show it, since both paths round through float32 on the host there.

The PR's result is the correctly rounded one, so I'd only reword this docstring and the "results don't change" line in the description. Casting f8/c16 → f2 through f4 on the host would keep 0-d and n-d consistent, if that matters more.

All other casts match master bit for bit in a matrix of about 71,000 cases per device: 14 source and 14 destination dtypes, edge values, 10 entry points. The binary-operator control (x + v, v * x, x == v, x += v, out=, clip, where) is identical too. The only differences are NaN payload bits: signalling NaNs come back quiet, because .item() passes them through a Python float.

"""
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)
Comment on lines +110 to +114

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

On a device without fp64 (Iris Xe), test_setitem_scalar_cast_matches_copy fails in 32 cases (±1e300 into each integer type, both keys), every run. The float64 → float32 downcast raises RuntimeWarning: overflow encountered in cast, here and in the test's reference line Y[...] = np.full(Y.shape, val) (master's _copy_from_numpy_into, a few lines below), and the test runs under filterwarnings("error"). Master warns the same way, so it's the new test and the "no NumPy cast warnings" claim that don't hold on these devices.

With both downcasts under np.errstate(over="ignore") (inf is what the cast gives anyway), test_usm_ndarray_ctor.py and test_tensor_asarray.py pass on the Iris Xe and its CPU, including the two cases suggested further down:

Suggested change
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)
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)

and the same in _copy_from_numpy_into:

    if copy_q.sycl_device.has_aspect_fp64 is False:
        src_ary_dt_c = src_ary.dtype.char
        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)

Otherwise the fp64-less path works. test_asarray_scalar_fp64_on_device_without_fp64 passes on the Iris Xe, and there the cast matrix (next comment) matches master except for the bits of NaN payloads.

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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

With a non-native byte order this raises: x = dpt.zeros((), "i4"); x[...] = np.array(1.5, ">f8") gives ValueError: Input of type <class 'numpy.ndarray'> could not be copied into dpnp.tensor.usm_ndarray, and dpt.asarray(np.array(1.5, ">f8"), dtype="i4") gives ValueError: Data type '>f8' can only have native byteorder. (dpt.empty((), dtype=src_dt) with src_dt = >f8). Normalizing first would fix it:

    np_ary = np_ary.astype(np_ary.dtype.newbyteorder("="), copy=False)

at the top of the function. All other casts of non-native 0-d sources now give NumPy's value, where master copied the raw bytes: x[...] = np.array(2, ">i4") was 33554432 on master. The n-d copy still has that bug on master and with this PR (y[...] = np.array([1.5], ">f8")), which is a separate issue.

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(
Comment thread
ndgrigorian marked this conversation as resolved.
Resolved
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)
Comment on lines +152 to +155

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is what fails the "Build with nightly build of DPC++ toolchain" job, in both runs on this PR: an abort through wait_and_throw in test_random.py in the first run, a segfault in test_fft.py in the second. The same toolchain passes master (97332 passed) and other branches that day.

The FFT extension keeps only in and out alive across the computation (keep_args_alive in fft/out_of_place.tpp and fft/in_place.tpp), not the DescriptorWrapper, whose destructor doesn't wait. _fft drops dsc when it returns. On master, _scale_result's res /= norm_factor (a NumPy scalar) did the blocking copy here, which drained the queue first. Now nothing waits, so with a oneMath build the mklcpu host task can run DftiComputeBackward on a freed descriptor.

With the CI toolchain (nightly-2026-11-25, its OpenCL CPU runtime, --onemath) on a Xeon Platinum 8480+:

master this PR
test_fft.py, 5 runs 5 pass 5 segfaults, after 7-20 wrong-value failures each
full dpnp/tests 97332 passed aborts at 60 % in test_random.py::test_input_size[chisquare], after 16 FFT failures

With the released 2026.2 runtime and a --onemath build, ifftn after a long matmul is also wrong in 99 of 100 runs, then crashes. The default oneMKL build doesn't show it.

Two ways out:

  • Passing the descriptor to keep_args_alive deadlocks: the host task drops the last reference, and oneMath's descriptor destructor blocks on its sycl::buffer in the scheduler while the main thread holds the scheduler lock.
  • Keeping dsc referenced in Python until its FFT event completes works, without a host wait. This passes test_fft.py 5 of 5 and the full suite (97656 passed) with the CI toolchain:
# dpnp/fft/dpnp_utils_fft.py
_pending = []  # (descriptor, fft_event): keep each descriptor alive until its FFT ran


def _keep_descriptor(dsc, ev):
    _pending[:] = [(d, e) for d, e in _pending if e.execution_status != dpctl.event_status_type.complete]
    _pending.append((dsc, ev))

_compute_result would call _keep_descriptor(dsc, fft_event) after each of the two fi._fft_* calls. I tested the same logic as a monkeypatch around fi._fft_out_of_place/fi._fft_in_place, not this in-tree form. Since this PR turns the latent bug into crashes and wrong results, the fix should land here or before it.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

On the OpenCL CPU device this makes x[...] = scalar on a large contiguous array several times slower. The fill goes to full_contig_impl, i.e. cgh.fill<T>(...), which the CPU runtime runs at only about 5-6 GB/s; master's cast kernel was much faster there. 20 fills of a 2048 × 2048 float32 array, median of 7, interleaved rounds:

CPU master this PR ratio
Xeon Platinum 8480+ 2.9 ms 62.1 ms 21.1
Core Ultra 7 356H 7.0 ms 89.2 ms 12.7
Core Ultra 5 245K 5.6 ms 33.4 ms 6.0

dpt.full((2048, 2048), 1.0) is just as slow on master: 2.5-3.3 ms per fill on the 356H, against 0.22 ms for a USM copy of the same size. So this is the old full path, which assignment now reaches. On the GPUs the fill is faster than master's copy (0.26-0.44x).

A parallel_for in full_contig_impl, at least for CPU devices, would fix dpt.full too. Within this PR, the float → integer path's approach would work on CPU devices: fill a 0-d array and broadcast-copy it with _copy_usm_ndarray_into_usm_ndarray. That stays async. On the 245K it takes 0.17-0.19 ms per fill, against 1.6-1.9 ms for cgh.fill and 0.28 ms for master's assignment. On the B70, cgh.fill is the faster one (0.015 vs 0.059 ms), so only CPU devices would take that path.

return
Comment thread
ndgrigorian marked this conversation as resolved.
Resolved
if np_ary.flags["OWNDATA"]:
Xnp = np_ary
else:
Expand Down
12 changes: 12 additions & 0 deletions dpnp/tensor/_ctors.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Comment on lines +132 to +133

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

test_from_dlpack_0d_view_is_writable (from #3181) fails on this head in linux / Test (3.13), in all 3 attempts:

x = dpt.asarray(5, dtype="i4", sycl_queue=q)   # now an async fill
y = dpt.from_dlpack(x)                          # y gets the device's cached queue, not q
y[...] = 7                                      # ordered only after y's queue's events
assert int(x) == 7                              # 5 == 7: the fill of 5 ran last

from_dlpack calls __dlpack__ without a stream, so nothing orders y's queue after x's fill. Out of 300 runs of the snippet, x ended up 5:

Device master this PR this PR, after a long matmul
OpenCL CPU, Xeon Platinum 8480+ 0 3 166
Data Center GPU Max 1100 0 0 94

The other test jobs passed it here and in the previous run, so it will flake.

dpt.full has the same problem on master already. The fix belongs in the import, but this PR makes it reachable from asarray and scalar assignment. In-process from_dlpack could pass its target queue as stream, so that _validate_and_use_stream orders it after the exporter with a barrier. That also covers from_dlpack(x, copy=True) (next comment).

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
Expand Down
24 changes: 23 additions & 1 deletion dpnp/tests/tensor/elementwise/test_elementwise_classes.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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()
2 changes: 2 additions & 0 deletions dpnp/tests/tensor/helper/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
has_cpu,
has_gpu,
has_sycl_platforms,
no_host_copy,
skip_if_dtype_not_supported,
)

Expand All @@ -43,5 +44,6 @@
"has_gpu",
"has_sycl_platforms",
"get_queue_or_skip",
"no_host_copy",
"skip_if_dtype_not_supported",
]
Loading
Loading