Repository navigation
Make scalar operands of binary elementwise functions asynchronous - #3182
ndgrigorian wants to merge 7 commits into
Conversation
|
View rendered docs @ https://intelpython.github.io/dpnp/pull/3182/index.html |
|
Array API standard conformance tests for dpnp=0.22.0dev3=np2py314h8d9cdd5_63 ran successfully. |
|
@ndgrigorian, would it make sense to extend ASV scope with a benchmark on scalar operands in binary elementwise functions? I guess we not need to cover all elementwise functions, but few or couple of most valuable ones. |
There was a problem hiding this comment.
🔵 Needs a closer look
Replacing SYCL casts with host NumPy casts still needs device-level validation for NaN, infinity, and out-of-int64-range values, including on fp64-less devices not covered by the reported runs.
No open issues 🎉
What changed in this PR
This PR addresses #3148 by replacing synchronizing host copies of scalar operands with asynchronous device fills in dpnp’s tensor layer, allowing scalar operations to return without waiting for queued device work.
Changes:
- Uses device fills for scalar and 0-d NumPy inputs in array creation and basic indexed assignment.
- Adds host-side casting intended to preserve copy-kernel conversion behavior.
- Adds regression tests for scalar creation, assignment, and binary operations, and documents the change.
| File | Description |
|---|---|
dpnp/tests/tensor/test_usm_ndarray_ctor.py |
Tests scalar assignment without host copies and checks casting behavior. |
dpnp/tests/tensor/test_tensor_asarray.py |
Tests scalar creation, dtype conversion, and devices without fp64 support. |
dpnp/tests/tensor/elementwise/test_elementwise_classes.py |
Tests scalar binary operands, including reversed, output, and in-place operations. |
dpnp/tensor/_ctors.py |
Routes 0-d NumPy inputs through device fills. |
dpnp/tensor/_copy_utils.py |
Adds scalar casting and asynchronous fills with event tracking. |
CHANGELOG.md |
Documents the removal of blocking scalar host copies. |
Review effort: Balanced
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.
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.
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.
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.
bfa5b18 to
a07cd71
Compare
|
@antonwolfy makes sense, added in a07cd71: |
antonwolfy
left a comment
There was a problem hiding this comment.
I tested the PR on four Intel GPUs and the CPU of each host:
- Data Center GPU Max 1100 with a Xeon Platinum 8480+;
- Panther Lake-H with a Core Ultra 7 356H;
- Iris Xe without fp64 with a Core i7-12700H;
- Arc Pro B70 with a Core Ultra 5 245K.
The Max 1100 runs compute-runtime 25.18 / IGC 2.11, the others 26.40 / IGC 2.42; oneAPI 2026.2, NumPy 2.5. The merge of master changed none of the PR's files.
The fill itself is right. Scalar casts match master bit for bit on every device, apart from the float16 rounding below. The queue no longer drains: a scalar operand right after a long matmul returns in 0.1-1.5 ms instead of waiting for it (one case on the Max 1100 aside, below), and scikit-learn's LogisticRegression from the issue is 5-30 % faster on the B70. But other code relied on that drain, and some paths got slower. Each point below has an inline comment with the measurements:
- FFT crashes and gives wrong results in oneMath builds. This is what fails the nightly-toolchain job on this PR. The FFT extension doesn't keep its descriptor alive, and the blocking scalar copy in
_scale_resultused to hide that. A small Python fix is in the comment. test_from_dlpack_0d_view_is_writablefails inlinux / Test (3.13)and will flake. A fill through a DLPack view isn't ordered after theasarrayfill of the same memory, becausefrom_dlpackimports onto another queue.- The new
test_setitem_scalar_cast_matches_copyfails on devices without fp64 (32 cases): the float64 → float32 downcast warns. A two-line fix (tested on the Iris Xe) is in the comment. - Scalar assignment into a large contiguous array is 6-21x slower on the OpenCL CPU device: the contiguous fill (
cgh.fill) is slow there. An async alternative that is faster than master is in the comment. - Readers that don't wait now see unfilled scalars:
usm_data.copy_to_host(),to_deviceto another context andfrom_dlpack(copy=True). The bug is old (dpt.fullshows it on master), but users ofx[...] = vwill now hit it too. - Smaller points:
- float16 destinations round differently from a 1-element source;
- non-native byte order raises for float → integer;
- two test gaps;
- a benchmark size nit;
- a redundant branch (below).
Tests
| Check (all 4 GPUs and their CPUs unless noted) | Result |
|---|---|
| Full dpnp test suite, 261 files, head vs master | no new failure, except point 3 on Iris Xe. The test of point 2 passed on these hosts but fails in CI |
| The new and changed tests, 100 runs each | pass, except point 3 on Iris Xe. test_asarray_scalar_fp64_on_device_without_fp64 passes there |
| Cast matrix, about 71,000 cases per device (14 source dtypes plus 3 non-native, 14 destination dtypes, edge values, 10 entry points incl. dpnp's), master vs head | bit-identical, except float16 double rounding (5 source values in the 0-d entry points), NaN payload bits and non-native byte order (point 6) |
Binary operators, out=, in-place ops, clip, where with Python and NumPy scalars |
bit-identical to master |
| Edge cases: size 0, steps ±1..5, offsets, n-D negative strides, F order, writable zero-stride view, read-only view, and a 1-D strided fill of 2**32 + 4 elements (Max 1100) | identical to master, except that a writable zero-stride view now fills where master raised ValueError |
Ordering after a long kernel, 200 runs per case, out-of-order and in-order queues, immediate command lists on and off: a fill after a reader (WAR), after a writer (WAW), through a 1-D strided view; then float, asnumpy, dpnp functions |
0 failures |
| Threads: 8 threads sharing a queue with scalar fills and operands (3.13; 3.14t with the GIL off, 8 and 32 threads) | 0 failures with the GIL. On 3.14t with 32 threads, a few wrong values, the same with the fills made synchronous: not from this PR |
usm_type and queue of the scalar paths (asarray, dtype= casts, dpnp.add(..., dtype=), x * 2, clip, where) for device, shared and host |
kept |
| Mutants of the new code (9 Python, 5 C++; Max 1100, Xeon, Iris Xe) | killed: the offset and stride-sign mutations of the 1-D paths, .real, the device float → integer cast, and the 0-d branch of _copy_from_numpy_into. Survivors: the n-D offset and the errstate (two test gaps with inline suggestions), the fp64 downcast (killed on the Iris Xe), and the asarray branch (redundant, see below). Removing an ordering dependency (depends=[] in assignment, or the copy not waiting for its fill) is caught on the Iris Xe's CPU but survives on the Max 1100: the tests notice ordering bugs only by timing. A test that fills behind a long kernel writing the same array would make that deterministic |
Build: _tensor_impl size, full_ctor.cpp compile time, warnings |
+131,600 B (+0.3 %), 7.7 → 8.3 s, no new warnings |
Performance
Host time of one call issued right after a long matmul, ms, master → head (min of 3, median of 4 interleaved rounds):
| Device (long kernel) | 2*x |
x == 0 |
x * np.float32(2) |
x[0] = 1 |
asarray(5) |
where(x > 0, x, 0) |
|---|---|---|---|---|---|---|
| Max 1100 (157 ms) | 171 → 0.24 | 171 → 0.22 | 171 → 0.23 | 171 → 0.09 | 171 → 0.08 | 172 → 172 |
| Panther Lake-H (1520 ms) | 1520 → 0.22 | 1568 → 0.22 | 1560 → 0.26 | 1587 → 0.08 | 1610 → 0.08 | 1606 → 0.42 |
| Arc Pro B70 (216 ms) | 216 → 0.80 | 215 → 0.81 | 218 → 0.87 | 215 → 0.23 | 217 → 0.25 | 218 → 1.48 |
| Xeon 8480+ (24 ms) | 23.1 → 0.22 | 23.2 → 0.22 | 23.3 → 0.22 | 22.0 → 0.07 | 23.2 → 0.09 | 23.6 → 0.46 |
| Core Ultra 7 356H (216 ms) | 231 → 0.33 | 235 → 0.32 | 237 → 0.34 | 232 → 0.13 | 271 → 0.13 | 272 → 0.61 |
| Core Ultra 5 245K (147 ms) | 144 → 0.21 | 144 → 0.21 | 144 → 0.21 | 143 → 0.08 | 143 → 0.09 | 144 → 0.45 |
where(x > 0, x, 0) still waits on the Max 1100. The host blocks in _full_usm_ndarray for where's scalar, which is submitted right after the queued x > 0. A fill submitted behind another scalar op sometimes blocks on that driver: where 5 of 5 times, asarray/full 1-2 of 5. It doesn't happen on 26.40.
The issue's loop, µs per call, 200 calls and one sync, master → head:
| Device | 2*x, x.shape=(16,) |
2*x, (65536, 128) |
x == 0, (65536, 128) |
asarray(5) with a sync per call |
|---|---|---|---|---|
| Max 1100 | 106 → 121 | 198 → 173 | 319 → 283 | 12.3 → 37.3 |
| Panther Lake-H | 67 → 65 | 1159 → 1684 | 1106 → 1386 | 16.0 → 25.4 |
| Arc Pro B70 | 62 → 63 | 283 → 137 | 262 → 111 | 13.5 → 21.8 |
| Xeon 8480+ | 220 → 209 | 4094 → 3510 | 1406 → 1191 | 59.5 → 61.6 |
| Core Ultra 7 356H | 91 → 89 | 3942 → 2441 | 1666 → 1575 | 24.9 → 23.9 |
| Core Ultra 5 245K | 78 → 75 | 2548 → 2097 | 1390 → 1174 | 15.0 → 18.3 |
On the B70 (the issue's GPU family) the large case is about 2x faster, as the issue predicted. On the Panther Lake iGPU it is 1.25-1.77x slower in this loop. Head now queues all 200 results of 32 MB, as x * x already does on master (1582 µs per call there), while master's blocking copy throttled it. On the Max 1100, small arrays are 10-20 % slower per call, and so is ASV's BinaryScalar below 2**24: the fill kernel and its keep-alive host task cost more there than master's one memcpy.
Assignment, ms per batch, master → head:
| Device | z[...] = 1, 2048 × 2048, ×20 |
z[:, i] = 1 ×200 |
zi[...] = 2.5 (int) ×200 |
|---|---|---|---|
| Max 1100 | 1.56 → 0.60 | 9.55 → 4.62 | 8.6 → 9.9 |
| Panther Lake-H | 5.28 → 2.30 | 6.87 → 5.34 | 5.1 → 7.0 |
| Arc Pro B70 | 1.13 → 0.30 | 5.99 → 2.53 | 5.6 → 4.5 |
| Xeon 8480+ | 2.94 → 62.1 | 24.7 → 14.9 | 18.7 → 22.9 |
| Core Ultra 7 356H | 7.03 → 89.2 | 12.4 → 7.0 | 10.4 → 26.5 |
| Core Ultra 5 245K | 5.60 → 33.4 | 7.7 → 2.5 | 6.4 → 5.2 |
ASV (Binary, BinaryScalar from this branch, against both builds):
- B70:
BinaryScalar0.56-0.82x in 5 cases, the rest the same. - Max 1100:
BinaryScalar1.04-1.19x at 216-220 and 0.90-0.94x at 2**24. Binaryis unchanged on both.
scikit-learn 1.9.1 LogisticRegression on the B70 (the issue's shapes, median of 12 fits, 50 for the wide one after host outliers in the first run, same iteration counts):
| Shape, dtype | 36000×126 f8 | 200000×100 f4 | 20000×1000 f8 | 3200×25300 f4 | 2000000×20 f4 | 8000000×20 f8 |
|---|---|---|---|---|---|---|
| head / master | 0.77 | 0.92 | 0.93 | 0.70 | 0.91 | 0.95 |
Nit: the 0-d branch of _asarray_from_numpy_ndarray duplicates the one in _copy_from_numpy_into. With it removed, asarray reaches the same fill through res[...] = ary, and every test passes. Keep it if it's a measured fast path, otherwise one copy is enough.
| 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) |
There was a problem hiding this comment.
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_alivedeadlocks: the host task drops the last reference, and oneMath's descriptor destructor blocks on itssycl::bufferin the scheduler while the main thread holds the scheduler lock. - Keeping
dscreferenced in Python until its FFT event completes works, without a host wait. This passestest_fft.py5 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.
| if ary.ndim == 0: | ||
| # fill instead of a host copy, which waits for the whole queue |
There was a problem hiding this comment.
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 lastfrom_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).
| # copy_to_host does not wait for the fill | ||
| Xusm.sycl_queue.wait() |
There was a problem hiding this comment.
User code needs the same wait now. x[...] = v and dpt.asarray(scalar) used to be synchronous; a reader that doesn't depend on the queue's submitted events can now see the value before the fill ran. After a long matmul on an out-of-order queue, 200 runs per row (ranges: immediate command lists off and on):
| Read right after the fill | Max 1100 | Panther Lake-H | Arc Pro B70 | master, all three |
|---|---|---|---|---|
x.usm_data.copy_to_host() after x[...] = k |
187-200 | 200 | 200 | 0 |
x.to_device(...) to another context after x[...] = k |
200 | 200 | 200 | 0 |
dpt.from_dlpack(x, copy=True) after x = dpt.asarray(np.float32(k)) |
0-56 | 200 | 200 | 0 |
Without a long kernel this is your loop from the earlier thread: 5 of 2000 on the OpenCL CPU of the B70 host (Core Ultra 5 245K).
float(), int(), asnumpy and dpnp functions wait or depend correctly, and so are fine. The three readers above are broken on master for dpt.full and any computed array (up to 200 of 200 there too), so the bug isn't new. Still, it would help to fix to_device and __dlpack__(copy=True) to depend on the submitted events, or at least to mention the lost implicit sync in the changelog entry.
| 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) |
There was a problem hiding this comment.
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:
| 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.
| Fills `dst` with the value of 0-d `np_ary`, cast as | ||
| `_copy_numpy_ndarray_into_usm_ndarray` would cast it. |
There was a problem hiding this comment.
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 bothIt 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.
| # 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) |
There was a problem hiding this comment.
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.
| 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) |
There was a problem hiding this comment.
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.
| (300, "i1", 44), | ||
| (2.7, "i4", 2), | ||
| (-2.7, "i4", -2), | ||
| (1.5 - 2j, "f4", 1.5), |
There was a problem hiding this comment.
No case here reaches the host cast with an overflowing value: removing the np.errstate(all="ignore") around np_ary.astype(dst_dt) passes every test. A float64 value too big for float32 would cover it, and with filterwarnings("error") it would also check the fp64-less downcast above:
(1e300, "f4", np.inf),
(-1e300, "f2", -np.inf),| class BinaryScalar(_Ufunc): | ||
| """Binary ufuncs with a Python scalar operand, e.g. ``2 * x``.""" | ||
|
|
||
| params = [_EXECUTOR_NAMES, ["add", "multiply"], _SIZES_1D, _FLOAT_DTYPES] |
There was a problem hiding this comment.
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.
| slice(None, None, 2), | ||
| (slice(None), 1), | ||
| slice(None, None, -1), | ||
| (slice(None, None, -1), slice(None, None, 2)), |
There was a problem hiding this comment.
No key here reaches the n-D path of usm_ndarray_full with an offset: reversed_step (X[::-1, ::2] of a 6 × 6 array) merges to one dimension after simplification, so it takes the 1-D path. Dropping the dst_offset shift from the n-D call (dst_data + dst_offset * dst.get_elemsize() → dst_data in full_ctor.cpp) passes every test. A view whose strides can't merge would cover it. With that mutation, this key fails 14 cases on the Max 1100 and crashes the CPU run with a write outside the array; without it, it passes:
| (slice(None, None, -1), slice(None, None, 2)), | |
| (slice(None, None, -1), slice(None, None, 2)), | |
| (slice(None, None, -1), slice(None, None, 4)), |
with a matching "reversed_nd" id below.
vlad-perevezentsev
left a comment
There was a problem hiding this comment.
Thanks! I tested the new changes on a Max 1100, UHD 770, Arc B570, UHD 730 and their CPUs: everything from my previous round is fixed, and column assignment is now 2-9x faster than master on these GPUs. Agreed with @antonwolfy on his open points, in particular the FFT crash, the DLPack test and the new test failing without fp64 (also on UHD 770 and UHD 730).
This PR makes binary elementwise functions with a Python or NumPy scalar operand asynchronous, closes #3148
A scalar operand (
2 * x,x == 0,x * np.float32(2)), the scalar ofclipandwhere, and a scalar assigned through basic indexing (x[0] = 1) were turned into a 0-d array by_copy_numpy_ndarray_into_usm_ndarray. That copy waits for all work already submitted to the queue, so each of these calls blocked the host until the device was idle._copy_from_numpy_intoanddpnp.tensor.asarraynow fill 0-d input with_full_usm_ndarray, ordered after the queue's submitted events, instead. Arrays withndim > 0still go through the copyThe value is cast the way the copy kernel would cast it, so results don't change
float32/complex64on devices without fp64A scalar assigned to a 1-D strided view (e.g.
x[:, 0] = 0) is filled with its offset and stride passed by value, without packing shape and strides into a device allocation freed in host tasksThe new tests patch
_copy_numpy_ndarray_into_usm_ndarrayto raise, and coverasarrayof Python scalars, NumPy scalars and 0-d arrays of every dtype, casts to another dtype, fp64 scalars on devices without fp64, indexed assignment, and binary operators,out=and in-place operators with a scalar operand. They fail without the fix (131 cases). The affecteddpnp.tensortests anddpnp/tests/test_arraycreation.pypass on a Level Zero iGPU and the OpenCL CPU device. The fp64-less test only skipped here, since both devices support fp64With the reproducer from #3148 on the iGPU, the host time of one call issued right after a ~75 ms matmul:
x * x2 * xx == 0x * np.float32(2)x[0] = 1