Skip to content

Release the GIL around waits in _cumsum_1d and other blocking paths - #3227

Open
ndgrigorian wants to merge 2 commits into
masterfrom
gil-release-around-waits
Open

ndgrigorian wants to merge 2 commits into
masterfrom
gil-release-around-waits

Conversation

@ndgrigorian

@ndgrigorian ndgrigorian commented Dec 5, 2026 •

Copy link
Copy Markdown
Collaborator

This PR releases the GIL in _cumsum_1d and other libtensor paths that waited with the GIL held.

py_cumsum_1d called its kernels with the GIL held, waiting for a copy of the total to the host. On an in-order queue that copy is ordered after earlier host tasks, and the one keep_args_alive submits for non-USM arguments (such as the index tuple of _take) takes the GIL, so _cumsum_1d could deadlock.

The other waits made with the GIL held:

  • _take and _put waited on host tasks before raising for non-integer indices.
  • _gesv copies the failing pivot to the host and waits for it in the oneapi::mkl::lapack::exception handler, which runs after the try block's gil_scoped_release is gone. The handler now runs with the GIL released.
  • sparse gemv init (oneMKL) waits for release_matrix_handle on its error paths, now with the GIL released
  • radix select waits for its kernels in wait_on_throw when a submission throws, and _topk, _partition and _median called it with the GIL held. They now release it around the call, reading the data pointers of the arrays first
  • 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? Not measured; the change adds one GIL release and reacquire per call of _topk, _partition and _median
  • Have you added documentation for your changes, if necessary?
  • Have you added your changes to the changelog?

`py_cumsum_1d` called its kernels, which wait for a copy of the total to
the host, with the GIL held. On an in-order queue that copy is ordered
after earlier host tasks, and the one `keep_args_alive` submits for
non-USM arguments takes the GIL, so the call deadlocked. The kernels now
run with the GIL released, as in `py_mask_positions`.

The other waits made with the GIL held are fixed too:
- `_take` and `_put` look up the kernel before packing the temporaries,
  so raising for non-integer indices no longer waits on host tasks
- `_gesv` releases the GIL in the exception handler that copies the
  failing pivot to the host
- sparse `gemv` init releases it while waiting for the matrix handle
  release on its error paths
- `_topk`, `_partition` and `_median` release it around radix select,
  which waits for its kernels if a submission throws
@github-actions

github-actions Bot commented Dec 5, 2026

Copy link
Copy Markdown
Contributor

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

@github-actions

github-actions Bot commented Dec 5, 2026

Copy link
Copy Markdown
Contributor

Array API standard conformance tests for dpnp=0.22.0dev3+80.gc5e19189e ran successfully.
Passed: 1491
Failed: 0
Skipped: 6

@coveralls

Copy link
Copy Markdown
Collaborator

Coverage Status

coverage: 84.606% (-0.004%) from 84.61% — gil-release-around-waits into master

@antonwolfy antonwolfy added this to the 0.22.0 release milestone Dec 5, 2026

@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 a Data Center GPU Max 1100 (Level Zero) and the Xeon Platinum 8480+ of the same host (OpenCL CPU), with compute-runtime 25.18 / IGC 2.11, oneAPI 2026.2 and Python 3.13, building master and this head in place.

The fix works. test_cumsum_1d_after_gil_host_tasks passes 5 of 5 times on both devices, and on master it hangs in 2 of 2 runs (both parametrizations time out). The full dpnp/tests suite has no failure on either device. The released regions touch no Python object. Each point below has an inline comment:

  1. _topk, _partition and _median now hand the GIL back on every call, though they wait only when a submission throws. With a second busy Python thread they drop to about 195 calls/s, 2-24 % of master. Single-threaded there is no change.
  2. The gesv handler fix has no test that fails without it. A singular solve or inv hangs on master only while another thread keeps queuing host tasks. A candidate test is in the comment.
  3. The changelog entry misses dpnp.linalg.inv.

Follow-ups

Neither comes from this PR, and neither needs to block it:

  • dpnp.fft on the OpenCL CPU device hangs on master and on this head, 2 of 2 runs each, while another thread keeps submitting dpt.take (a host task that takes the GIL) to the same in-order queue.
    • On that device the oneMKL DFT descriptor holds a sycl::buffer, and the buffer's destructor waits for the queue.
    • DescriptorWrapper (extensions/fft/common.hpp:51) is destroyed when Python deallocates the descriptor object, with the GIL held. Meanwhile the host-task thread waits in take_gil.
    • Level Zero doesn't show it.
    • It is the same class as this PR. Releasing the GIL in ~DescriptorWrapper would cover it.
  • A lock-order deadlock between the GIL and the SYCL scheduler, rare, on the OpenCL CPU device with the same second thread. It showed up once in 15 runs of a singular float32 solve on this head. An earlier driver hit it in _copy_usm_ndarray_into_usm_ndarray.
    • The thread holding the GIL waits in Scheduler::addCG for the scheduler's write lock.
    • The main thread has released the GIL. It waits in oneapi::mkl::lapack::gesv → Scheduler::waitForEvent, holding the read lock until a host task finishes.
    • That host task waits for the GIL.
    • Releasing the GIL around waits can't fix this. It needs host tasks that don't take the GIL, or a runtime that doesn't hold the lock while it waits.
    • Single hangs in dpt.asnumpy, unique, cholesky and a batched singular solve, on master and this head alike, didn't reproduce in 15 retries each and may be the same thing.

Tests

Check (Max 1100 and Xeon) Result
The two new tests: 5 runs on this head, 2 on master with this head's test files this head passes every run. On master test_cumsum_1d_after_gil_host_tasks times out 2/2; test_take_put_non_integer_indices passes there too
Full dpnp/tests incl. tensor, -n 8 no failure: 101580 passed on the GPU, 101600 on the CPU
test_blas_lapack_gil.py with the slow tests, GPU 5 passed, this head and master
Hang sweep: 65 cases of about 30 public functions, each in a subprocess with -X gil=1 and a timeout, in an in-order queue behind a pending dpt.take host task, run once single-threaded and once with a second thread queuing such host tasks fixed here: repeat with an array of repeats, and singular solve/inv (float32, float64, complex128). Still hanging: fft on the CPU (follow-up). No hang in dpnp.asnumpy, int(), bool(), boolean indexing, nonzero, place, searchsorted, bincount, histogram, cumsum, det, eigh, svd, lstsq, qr, matmul, csr matvec, partition, top_k, median
sort/argsort through the paths with a sycl::buffer temporary (merge sort, and radix sort with the values in global memory), confirmed by counting buffer constructions no hang: a buffer without host data doesn't block in its destructor
Progress of a second thread during dpnp.repeat(a, r) with 2**28 int64 repeats GPU: the longest stall is 11.9 ms on master and none on this head. CPU: 109-121 ms on master, 1-4 ms in 3 of 5 calls on this head

Comment on lines +191 to +197
sycl::event comp_ev;
{
// radix select waits for its kernels if a submission throws
py::gil_scoped_release release;
comp_ev =
fn(exec_q, n_iters, n_values, kth, src_data, dst_data, depends);
}

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 release runs on every call, and so do the ones in topk.cpp and median.cpp, but the only wait in radix select is wait_on_throw, when a submission throws. While another Python thread is busy, each call now has to win the GIL back from it, which takes up to the switch interval (5 ms).

Calls per second on the Max 1100, float32, median of 4 fresh processes alternating master and this head:

Call single thread, head / master with a busy second thread, master → head
dpnp.partition(a, 100), 1024 1.01 7399 → 195
dpnp.partition(a, 100), 64×1024 1.01 3647 → 194
dpt.top_k(a, 10), 1024 0.96 1166 → 190
dpt.top_k(a, 10), 64×1024 1.00 614 → 149
dpnp.median(a), 1024 0.99 8150 → 193
dpnp.median(a, axis=-1), 64×1024 0.98 3938 → 194

dpnp.add already sits at this floor on master, 195 calls/s in the same setup, and dpt.sort, which this PR doesn't touch, is at 0.89-1.00 of master.

Radix select could avoid the wait: when a submission throws, it could hand the temporaries to async_smart_free after last_ev, as it already does on success (radix_select.hpp:1875). Then nothing in it blocks, and these three releases can go. If that submission throws as well (a broken queue), falling back to the wait keeps today's safety.

Comment on lines +156 to +157
// the handler waits for a copy of the failing pivot
py::gil_scoped_release lock{};

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 fix is right, but no test fails without it. A single-threaded pending host task doesn't reach this wait: by the time it throws, the oneMKL call has drained the queue, and it made that call with the GIL released.

The wait is reached when another thread keeps queuing host tasks that take the GIL onto the same in-order queue. Then master hangs in 4 of 4 runs (solve and inv, GPU and CPU). The main thread sits in the pivot copy's .wait() (gesv_common_utils.hpp:157-159), and the host-task threads sit in take_gil. This head passes.

The test below follows the style of the cumsum test. It fails on master by timeout on both devices, and both cases pass here in 5-7 s:

_SINGULAR_AFTER_HOST_TASKS = """
import sys, threading, time
import dpctl
import numpy as np
import dpnp
import dpnp.tensor as dpt

func = sys.argv[1]
q = dpctl.SyclQueue(property="in_order")
dt = dpnp.default_float_type(q)
x = dpt.arange(2**18, 0, -1, sycl_queue=q)
idx = dpt.argsort(x)
q.wait()
a = dpnp.asarray(np.arange(8.0)[:, None] * np.ones((1, 8)), dtype=dt, sycl_queue=q)
b = dpnp.ones(8, dtype=dt, sycl_queue=q)
stop = False

def submit_host_tasks():
    while not stop:
        dpt.take(x, idx)  # its host task takes the GIL
        time.sleep(0.01)

t = threading.Thread(target=submit_host_tasks)
t.start()
try:
    n = 0
    end = time.time() + 2
    while time.time() < end:
        try:
            dpnp.linalg.solve(a, b) if func == "solve" else dpnp.linalg.inv(a)
        except dpnp.linalg.LinAlgError:
            n += 1
        else:
            raise AssertionError("no LinAlgError")
finally:
    stop = True
    t.join()
q.wait()
print(n)
"""


@pytest.mark.parametrize("func", ["solve", "inv"])
def test_singular_after_gil_host_tasks(func):
    timeout = 60  # seconds, a run takes a few
    try:
        # `-X gil=1` so the GIL is held on free-threaded builds too
        res = subprocess.run(
            [sys.executable, "-X", "gil=1", "-c", _SINGULAR_AFTER_HOST_TASKS, func],
            capture_output=True,
            text=True,
            timeout=timeout,
        )
    except subprocess.TimeoutExpired:
        pytest.fail(
            f"no progress in {timeout}s: the gesv exception handler waits "
            "with the GIL held behind a host task that needs it"
        )
    assert res.returncode == 0, res.stderr
    assert int(res.stdout) > 0

Comment thread CHANGELOG.md
* Fixed the comparison functions, `dpnp.divide`, the logical functions and the binary functions that compute in floating point for an integer or boolean array, such as `dpnp.arctan2`, raising `OverflowError` or `ValueError` for a Python integer outside the range of the array data type. The logical functions now raise `OverflowError` for a Python integer outside the `int64` range for any data type [#3202](https://github.com/IntelPython/dpnp/pull/3202)
* Fixed the misleading `ValueError` about an unsupported data type that `dpnp.tensor` comparison functions, `dpnp.tensor.divide`, `dpnp.tensor.isin` and `dpnp.tensor.searchsorted` raised for a Python integer outside the `int64` and `uint64` ranges, which now raise `OverflowError` [#3202](https://github.com/IntelPython/dpnp/pull/3202)
* Fixed `ValueError` in `dpnp.from_dlpack` and `dpnp.tensor.from_dlpack` when copying an empty host array to a SYCL device [#3208](https://github.com/IntelPython/dpnp/pull/3208)
* Released the GIL while `dpnp.repeat` and `dpnp.tensor.repeat` with an array of repeats, and `dpnp.linalg.solve` of a singular matrix, wait for the device, which blocked other Python threads and could deadlock on an in-order queue [#3227](https://github.com/IntelPython/dpnp/pull/3227)

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.

dpnp.linalg.inv also calls _gesv (dpnp_inv, dpnp_utils_linalg.py:2171), and a singular inv hung on master the same way (comment on gesv.cpp). It belongs here too, for example "and dpnp.linalg.solve and dpnp.linalg.inv of a singular matrix".

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.

3 participants