Repository navigation
Make scalar operands of binary elementwise functions asynchronous - #3182
ndgrigorian wants to merge 18 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_88 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
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.
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).
vlad-perevezentsev
left a comment
There was a problem hiding this comment.
The head is the same as in my previous review. I re-ran it on an Arc B580, UHD 770, UHD 730 and their CPUs: scalar operands with float32 arrays match master on the devices without fp64, and @antonwolfy's open points still hold, the DLPack test included (details in his thread).
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.
The OpenCL CPU runtime runs cgh.fill several times slower than a kernel, so assigning a scalar to a large contiguous array, which now fills instead of copying, was slower than the host copy on CPU devices. A 2048 x 2048 float32 fill took 2.1 ms with cgh.fill and 0.67 ms as a broadcast copy on a Core Ultra 7 265U. GPUs keep cgh.fill, which is faster there.
NumPy warns when a float64 value out of the float32 range becomes inf,
which made the new cast tests fail under filterwarnings("error") on
devices without fp64. The copy kernel gives inf without a warning, so
ignore the overflow in both the 0-d fill and the host copy.
No case reached the host cast with an overflowing value, so removing the errstate around it passed every test.
X[::-1, ::2] of a 6 x 6 array merges to one dimension, so no case reached the n-D fill with an offset.
The copy kernel converts float64 to sycl::half through float, so a 0-d source can round differently from a 1-element one.
A float source of non-native byte order raised in the float to integer path, which creates a device array of the source dtype.
32f7811 to
33db106
Compare
The FFT extension keeps only the input and output arrays alive across the computation, and _compute_result dropped the descriptor on return. A blocking scalar copy when scaling the result used to hide it; with scalars filled asynchronously, builds with oneMath ran the transform on a freed descriptor. Releasing the descriptor in a host task deadlocks with oneMath, so hold it in Python until its FFT event completes.
to_device to another context copies through the host, and __dlpack__ with copy=True submits a memcpy, both without dependencies, so they could copy an array before its fill or the kernel computing it ran. This was already the case for dpt.full; with scalars filled on the device it also affects x[...] = v and asarray.
from_dlpack of a usm_ndarray imports it onto the cached queue of its device, but called __dlpack__ without a stream, so work on the import could run before work already submitted to the exporter's queue, e.g. a scalar fill. Pass the cached queue as the stream, which makes __dlpack__ submit a barrier ordering it after the exporter's queue. dpnp.from_dlpack passes the usm_ndarray of a dpnp.ndarray for the same. Reading through the exporter still waits only for its own queue, so the 0-d view test waits for the queue of the import first.
9e545b7 to
46e6313
Compare
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, except that a float64 or complex128 value going to float16 is rounded once, as in NumPy, where the copy kernel rounds it through float32
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 blocking copy also hid ordering bugs elsewhere, fixed here too:
dpnp.fftnow holds each descriptor until its FFT event completes; builds with oneMath ran the transform on a freed descriptorfrom_dlpackof ausm_ndarraypasses the queue it imports onto asstream, so work on the import is ordered after the exporter's queueto_deviceto another context and__dlpack__(copy=True)wait for the queue's submitted events before copyingfull_contig_impluses aparallel_foron CPU devices, ascgh.fillis several times slower there (2.1 vs 0.30 ms for a 2048 x 2048 float32 fill on a Core Ultra 7 265U)The 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