Skip to content

Make scalar operands of binary elementwise functions asynchronous - #3182

Open
ndgrigorian wants to merge 19 commits into
masterfrom
make-scalar-operands-in-binary-ops-asynchronous
Open

ndgrigorian wants to merge 19 commits into
masterfrom
make-scalar-operands-in-binary-ops-asynchronous

Conversation

@ndgrigorian

@ndgrigorian ndgrigorian commented Nov 8, 2026 •

Copy link
Copy Markdown
Collaborator

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 of clip and where, 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_into and dpnp.tensor.asarray now fill 0-d input with _full_usm_ndarray, ordered after the queue's submitted events, instead. Arrays with ndim > 0 still go through the copy

The 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

  • Through float32/complex64 on devices without fp64
  • Complex to real keeps the real part
  • Float to integer fills a 0-d array of the source type and casts it with the copy kernel on the device, since NaN, inf and out-of-range values have no defined integer value
  • No NumPy cast warnings
  • Non-native byte order is converted first

A 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 tasks

The blocking copy also hid ordering bugs elsewhere, fixed here too:

  • The FFT extension keeps only the arrays alive, so dpnp.fft now holds each descriptor until its FFT event completes; builds with oneMath ran the transform on a freed descriptor
  • from_dlpack of a usm_ndarray passes the queue it imports onto as stream, so work on the import is ordered after the exporter's queue
  • to_device to another context and __dlpack__(copy=True) wait for the queue's submitted events before copying

full_contig_impl uses a parallel_for on CPU devices, as cgh.fill is 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_ndarray to raise, and cover asarray of 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 affected dpnp.tensor tests and dpnp/tests/test_arraycreation.py pass on a Level Zero iGPU and the OpenCL CPU device. The fp64-less test only skipped here, since both devices support fp64

With the reproducer from #3148 on the iGPU, the host time of one call issued right after a ~75 ms matmul:

call master this PR
x * x 0.45 ms 0.51 ms
2 * x 69.37 ms 1.23 ms
x == 0 80.70 ms 0.92 ms
x * np.float32(2) 75.50 ms 1.32 ms
x[0] = 1 76.07 ms 0.43 ms
  • Have you provided a meaningful PR description?
  • Have you added a test, reproducer or referred to an issue with a reproducer?
  • Have you tested your changes locally for CPU and GPU devices?
  • Have you made sure that new changes do not introduce compiler warnings?
  • Have you checked performance impact of proposed changes?
  • Have you added documentation for your changes, if necessary?
  • Have you added your changes to the changelog?

@github-actions

github-actions Bot commented Nov 8, 2026

Copy link
Copy Markdown
Contributor

View rendered docs @ https://intelpython.github.io/dpnp/pull/3182/index.html

@github-actions

github-actions Bot commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor

Array API standard conformance tests for dpnp=0.22.0dev4+20.gc66fed30 ran successfully.
Passed: 1491
Failed: 0
Skipped: 6

@coveralls

coveralls commented Nov 8, 2026 •

Copy link
Copy Markdown
Collaborator

Coverage Status

coverage: 84.64% (+0.03%) from 84.61% — make-scalar-operands-in-binary-ops-asynchronous into master

@antonwolfy

Copy link
Copy Markdown
Contributor

@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.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔵 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

@antonwolfy antonwolfy added this to the 0.22.0 release milestone Nov 9, 2026
Comment thread dpnp/tensor/_copy_utils.py Resolved
Comment thread dpnp/tensor/_copy_utils.py Resolved
Comment thread dpnp/tensor/_copy_utils.py Resolved
@ndgrigorian
ndgrigorian force-pushed the make-scalar-operands-in-binary-ops-asynchronous branch from bfa5b18 to a07cd71 Compare November 24, 2026 05:06
@ndgrigorian

Copy link
Copy Markdown
Collaborator Author

@antonwolfy makes sense, added in a07cd71: BinaryScalar in bench_elementwise.py times add and multiply with a Python scalar over the existing sizes and float dtypes. It chains two calls, since the second call's scalar is the one that used to wait for the first. Against master's copy that is 40-46 ms vs 33-34 ms at 2**24 on the iGPU, and within noise at the smaller sizes and on the CPU, so it's mostly a guard against regressions. asv check passes; I've only timed the body by hand, not through asv run.

@antonwolfy antonwolfy left a comment

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.

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:

  1. 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_result used to hide that. A small Python fix is in the comment.
  2. test_from_dlpack_0d_view_is_writable fails in linux / Test (3.13) and will flake. A fill through a DLPack view isn't ordered after the asarray fill of the same memory, because from_dlpack imports onto another queue.
  3. The new test_setitem_scalar_cast_matches_copy fails on devices without fp64 (32 cases): the float64 → float32 downcast warns. A two-line fix (tested on the Iris Xe) is in the comment.
  4. 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.
  5. Readers that don't wait now see unfilled scalars: usm_data.copy_to_host(), to_device to another context and from_dlpack(copy=True). The bug is old (dpt.full shows it on master), but users of x[...] = v will now hit it too.
  6. 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: BinaryScalar 0.56-0.82x in 5 cases, the rest the same.
  • Max 1100: BinaryScalar 1.04-1.19x at 216-220 and 0.90-0.94x at 2**24.
  • Binary is 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.

Comment thread dpnp/tensor/_copy_utils.py Resolved
Comment thread dpnp/tensor/_ctors.py Resolved
Comment thread dpnp/tensor/_copy_utils.py Resolved
Comment thread dpnp/tensor/_copy_utils.py Resolved
Comment thread dpnp/tensor/_copy_utils.py Resolved
Comment thread dpnp/tensor/_copy_utils.py Resolved

@vlad-perevezentsev vlad-perevezentsev left a comment

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.

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 vlad-perevezentsev left a comment

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.

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.
@ndgrigorian
ndgrigorian force-pushed the make-scalar-operands-in-binary-ops-asynchronous branch from 32f7811 to 33db106 Compare December 2, 2026 20:34
ndgrigorian and others added 5 commits December 3, 2026 07:20
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.
@ndgrigorian
ndgrigorian force-pushed the make-scalar-operands-in-binary-ops-asynchronous branch from 9e545b7 to 46e6313 Compare December 3, 2026 15:21
ndgrigorian added a commit that referenced this pull request Dec 3, 2026
The FFT extension kept only the input and output arrays alive, and
_compute_result drops the descriptor on return, so the transform could
run on a freed descriptor. A blocking scalar copy when scaling the
result has hidden it so far; builds with oneMath hit it once that copy
is asynchronous (#3182). With keep_args_alive deferring releases
through dpctl, the extension now keeps the Python object wrapping the
descriptor alive too, which a host task could not release with oneMath
without deadlocking.

The FFT functions also return the keep-alive event first and the
transform's event second, as the other extensions do and as
_compute_result already unpacks them.

@antonwolfy antonwolfy left a comment

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.

Thanks for the fixes. I re-tested the merged head on three Intel GPUs and the CPU of each host:

  • Panther Lake-H with a Core Ultra 9 386H;
  • Iris Xe without fp64 with a Core i7-12700H;
  • Arc Pro B70 with a Core i5-13400.

All run compute-runtime 26.40 / IGC 2.42, oneAPI 2026.2, NumPy 2.5. The Max 1100 from the first round wasn't available this time.

Every point from my first review is fixed, and the new tests catch each fix: reverting it makes them fail.

  • FFT: the nightly-toolchain job passes, and dropping _keep_descriptor_alive fails test_descriptor_outlives_its_fft (B70 and its CPU).
  • DLPack import: a write through the view read through the original (with the wait) is wrong 0 of 300 times, and a write to the original read through the view 0 of 200, on every device where that case ran. Dropping the stream fails the new test on the i5-13400's OpenCL CPU, and dropping the waits in to_device (other context) and __dlpack__(copy=True) fails their tests on the B70 and its CPU.
  • Devices without fp64: the changed test files pass on the Iris Xe with -W error::RuntimeWarning, and removing either errstate fails them.
  • CPU fill: see the table below.
  • Non-native byte order: the bytes match the native source in every case (6,864 on the Iris Xe, 8,008 on each other device), and removing the normalization fails the new test.
  • The test gaps: the n-D offset and the errstate mutations are killed now.

Two ordering points remain (inline):

  1. A same-context to_device view still isn't ordered after the source queue. With this PR it loses scalar writes, even when the reader waits for the view's queue.
  2. Writing through a DLPack view and reading the original now needs a wait, which the changelog doesn't mention yet.

About the earlier Test (3.13, ubuntu-latest) worker crashes: I couldn't reproduce them with the conda packages that run built. With 4 workers on opencl:cpu, as in CI, there were 0 crashes in 6 runs of the PR build and 6 of master on the i5-13400 and the Ultra 9 386H. On the 14 GB host the tensor suite under -n 4 leaves only 600-990 MiB free, master and the PR alike. The crashes left no Python traceback, so memory on the 16 GB runner is a plausible cause. CI on the merged head is green, but it no longer runs Linux 3.13, so a rerun there would tell more if the job comes back.

Tests

Check (all 3 GPUs and their CPUs unless noted) Result
Full dpnp test suite with 4 workers, head (Panther Lake-H and its CPU) passes on the CPU. On the iGPU the whole suite runs out of device memory with 4 workers and about 1,000 tests fail; master fails the same way (more often), and the failing files pass on both with one worker or on their own. dpnp.tests.tensor passes on both devices
The PR's test files with -W error::RuntimeWarning (Iris Xe and its CPU) pass
Cast matrix, master vs head the same differences as in round 1 (the documented float16 rounding, NaN payload bits); non-native sources, which raised on master, now match the native ones
Non-native byte order: setitem (0-d, whole array, 1-D column) and asarray(dtype=...), 11 source × 14 destination dtypes, 13 values 0 mismatches
Mutants of the PR's code (14 Python, 6 C++, 3 Cython; B70, Iris Xe and their CPUs) every behaviour mutant killed, except the redundant asarray 0-d branch (round 1's nit). Ordering-only mutants (depends=[] and the like) survive, as before

Performance

Assignment, ms per fill of a 16 MiB array (best of 2 interleaved rounds), master → head:

Device f4 2048 × 2048 z[...] = 1 bool int8 float64 complex128
Panther Lake-H iGPU 0.257 → 0.120 0.830 → 0.077 0.939 → 0.075 0.172 → 0.078 0.121 → 0.069
Arc Pro B70 0.061 → 0.018 0.150 → 0.018 0.160 → 0.017 0.047 → 0.016 0.042 → 0.016
Core i7-12700H 0.497 → 0.103 1.799 → 0.110 1.691 → 0.106 0.389 → 0.100 0.245 → 0.104
Core i5-13400 0.542 → 0.101 2.078 → 0.103 1.845 → 0.168 0.413 → 0.121 0.275 → 0.168
Core Ultra 9 386H 0.334 → 0.180 1.307 → 0.154 1.180 → 0.338 0.279 → 0.348 0.182 → 0.346

dpt.full is unchanged on the GPUs; on the CPUs its time is mostly the allocation. The float64/complex128 rows of the Ultra 9 386H are the only slower ones, and the other two CPUs don't show it.

Host time of one call issued right after a long kernel (Panther Lake-H; 1510 ms on the iGPU, 212 ms on the CPU), ms, master → head:

Device 2*x x == 0 x[0] = 1 asarray(5) where(x > 0, x, 0)
Panther Lake-H iGPU 1568 → 0.29 1569 → 0.24 1612 → 0.09 1639 → 0.10 1636 → 0.45
Core Ultra 9 386H 223 → 0.33 219 → 0.28 225 → 0.13 254 → 0.12 256 → 0.54

In the issue's loop (200 calls, one sync) at (65536, 128), the Ultra 9 386H is 0.58-0.96x of master. On the Panther Lake iGPU one run measured 2*x 2.1x slower, but its rounds ranged from master's time to 2.2x, and a separate interleaved run gave the same median for both (1459 vs 1462 µs per call): I'd call it noise on that iGPU.

Comment thread dpnp/tensor/_usmarray.pyx
Comment on lines +1189 to +1190
# the copy goes through the host without dependencies
_wait_for_submitted(self.sycl_queue)

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 wait covers to_device to another context, but the same-context branch above still hands the memory to the target queue without ordering it after the source queue. With this PR that branch now loses scalar writes: the queued fill of x lands after a write through the view, even when the reader waits for the view's queue.

x = dpt.asarray(5, dtype="i4", sycl_queue=q)   # an async fill behind a long matmul on q
y = x.to_device(q2)                             # same context: a view on q2, no barrier
y[...] = 7
q2.wait()
assert int(x) == 7                              # 5: the fill of 5 ran after the 7

Out of 200 runs, after a long matmul:

Case Device master this PR
asarray(5), write through y, read x without a wait OpenCL CPU, Core i7-12700H 0 178
same, q2.wait() before reading OpenCL CPU, Core i7-12700H 0 47
same, q2.wait() before reading OpenCL CPU, Core i5-13400 0 37
x[...] = 7, then read through y = x.to_device(q2) OpenCL CPU, Core i7-12700H 0 61
asarray(5), write through y, read x without a wait Panther Lake-H iGPU 0 1

It isn't new: an async producer shows it on master too. With 100 runs on the i7-12700H CPU (write lost / stale read through y):

Producer of x master this PR
dpt.full(4, 5) 67 / 74 71 / 59
dpt.asarray(5) 0 / 0 75 / 58
x[...] = 5 0 / 0 100 / 85

But scalar assignment and asarray(scalar) used to be the safe case, and code like x[...] = 0; y = x.to_device(q2) is common. from_dlpack got the fix in this PR by passing its queue as stream. Could the same-context branch do the same when stream is None and d.sycl_queue is not self.sycl_queue, i.e. _validate_and_use_stream(d.sycl_queue, self.sycl_queue)? A test like test_from_dlpack_orders_import_after_exporter, with to_device(q2) and both directions, would cover it.

y = dpt.from_dlpack(x)
y[...] = 7
# reading through x waits only for the queue of x
y.sycl_queue.wait()

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.

The import is ordered now (thanks), but this wait shows a user-visible change: writing through the DLPack view and then reading the original no longer works without it. On master y[...] = 7 blocked, so int(x) saw 7. Out of 300 runs of this test's body without the wait (int(x) == 5):

Device master this PR this PR, after a long matmul
Panther Lake-H iGPU 0 217 11
Iris Xe 0 185 0
Arc Pro B70 0 21 213
OpenCL CPU, Core i7-12700H 0 299 2

With y.sycl_queue.wait() it is 0 everywhere. The changelog entry asks for a wait only before reading the memory directly (usm_data.copy_to_host()). Could it also say that a scalar write through an array on another queue sharing the memory (a DLPack view, a same-context to_device view) needs that queue's wait before reading through the original?

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Python scalar operands in binary elementwise functions synchronize the queue

5 participants