From eaef6510bb686bcb7f176214cbf89f49edc83fd6 Mon Sep 17 00:00:00 2001 From: Yitao Jiang <22387156+cccat6@users.noreply.github.com> Date: Tue, 1 Dec 2026 02:24:59 +0800 Subject: [PATCH 1/4] Fix thread-count restoration when OpenBLAS libraries share state --- threadpoolctl.py | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/threadpoolctl.py b/threadpoolctl.py index eba58089..92a1d311 100644 --- a/threadpoolctl.py +++ b/threadpoolctl.py @@ -1148,6 +1148,8 @@ def __init__(self, controller, *, limits=None, user_api=None): self._original_info = dict( zip(self._controller.lib_controllers, self._controller.info()) ) + # The undo log must not include libraries we did not change. + self._restore_info = {} self._set_threadpool_limits() def __enter__(self): @@ -1167,7 +1169,8 @@ def wrap(cls, controller, *, limits=None, user_api=None): def restore_original_limits(self): """Set the limits back to their original values""" - for lib_controller, original_info in self._original_info.items(): + # Undo in reverse order: multiple controllers can share native state. + for lib_controller, original_info in reversed(self._restore_info.items()): lib_controller.set_num_threads(original_info["num_threads"]) # Alias of `restore_original_limits` for backward compatibility @@ -1212,6 +1215,8 @@ def get_original_num_threads(self): def _set_threadpool_limits(self): """Change the maximal number of threads in selected thread pools.""" if self._limits is None: + # limits=None is also used to explicitly save and restore a snapshot. + self._restore_info.update(self._original_info) return took_control = False @@ -1230,6 +1235,7 @@ def _set_threadpool_limits(self): continue if num_threads is not None: + self._restore_info[lib_controller] = self._original_info[lib_controller] if ( type(lib_controller) is not OpenBLASController or lib_controller.threading_layer == "openmp" @@ -1247,6 +1253,7 @@ def _set_threadpool_limits(self): # this thread later became the controlling thread during # restoration, it might restore the wrong value. self._original_info.pop(lib_controller, None) + self._restore_info.pop(lib_controller, None) elif isinstance(result, _THIS_THREAD_TOOK_CONTROL): # Now that we took control: # From b1a67a7ac6654bad9e1d2d18079a2401cfdbfb78 Mon Sep 17 00:00:00 2001 From: Yitao Jiang <22387156+cccat6@users.noreply.github.com> Date: Tue, 1 Dec 2026 06:00:30 +0800 Subject: [PATCH 2/4] CI Retry intermittent Windows OpenBLAS crash Retrigger CI after the same access violation tracked in upstream issue #261. No code changes. From 24571eb9607e03d0a0b83b8246497e1e89745508 Mon Sep 17 00:00:00 2001 From: Yitao Jiang <22387156+cccat6@users.noreply.github.com> Date: Fri, 4 Dec 2026 06:50:50 +0800 Subject: [PATCH 3/4] Test restoring a thread count shared by two OpenBLAS libraries --- tests/test_threadpoolctl.py | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/tests/test_threadpoolctl.py b/tests/test_threadpoolctl.py index c8831b93..44814be7 100644 --- a/tests/test_threadpoolctl.py +++ b/tests/test_threadpoolctl.py @@ -9,6 +9,7 @@ import sys import time from threading import Event, Lock, Thread, current_thread +from unittest.mock import Mock import pytest @@ -114,6 +115,34 @@ def test_controller_info_actualized(): assert controller.info() == original_info +def test_restore_openblas_libraries_with_shared_thread_count(monkeypatch): + num_threads = 16 + + def set_num_threads(value): + nonlocal num_threads + num_threads = value + + # Model two OpenBLAS libraries whose getters and setters affect the same + # native state, without depending on how the installed BLAS is linked. + libraries = {} + for name in ("libopenblas_a.so", "libopenblas_b.so"): + library = Mock(spec=[]) + library.openblas_get_num_threads = Mock(side_effect=lambda: num_threads) + library.openblas_set_num_threads = Mock(side_effect=set_num_threads) + library.openblas_get_parallel = Mock(return_value=1) + libraries[name] = library + + monkeypatch.setattr(threadpoolctl._CDLL_CACHE, "get_cdll", libraries.__getitem__) + monkeypatch.setattr(OpenBLASController._SHARED_STATE, "controlling_thread", None) + controller = ThreadpoolController._from_controllers( + [OpenBLASController(filepath=name, prefix="libopenblas") for name in libraries] + ) + + with controller.limit(limits=1, user_api="blas"): + assert num_threads == 1 + assert num_threads == 16 + + @pytest.mark.parametrize( "kwargs", [ From 478ee42d2b765ffacbe13e7000356f4d7226360a Mon Sep 17 00:00:00 2001 From: Yitao Jiang <22387156+cccat6@users.noreply.github.com> Date: Sat, 5 Dec 2026 04:30:35 +0800 Subject: [PATCH 4/4] Refresh shared thread counts before applying any limits --- CHANGES.md | 4 + tests/test_threadpoolctl.py | 50 +++++------ threadpoolctl.py | 171 ++++++++++-------------------------- 3 files changed, 72 insertions(+), 153 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index a5509149..131eb056 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,6 +1,10 @@ 3.9.0 (under development) ========================= +- Fix thread limits being restored or reported incorrectly when multiple + controllers share the same OpenBLAS thread pool. + https://github.com/joblib/threadpoolctl/pull/310 + - Fix a bug in `limiter.restore_original_limits()` where all limits were always restored, even if `limiter` is scoped to a strict subset of the controllable libraries. Similarly, diff --git a/tests/test_threadpoolctl.py b/tests/test_threadpoolctl.py index 44814be7..53e0957d 100644 --- a/tests/test_threadpoolctl.py +++ b/tests/test_threadpoolctl.py @@ -9,7 +9,6 @@ import sys import time from threading import Event, Lock, Thread, current_thread -from unittest.mock import Mock import pytest @@ -115,32 +114,31 @@ def test_controller_info_actualized(): assert controller.info() == original_info -def test_restore_openblas_libraries_with_shared_thread_count(monkeypatch): - num_threads = 16 - - def set_num_threads(value): - nonlocal num_threads - num_threads = value - - # Model two OpenBLAS libraries whose getters and setters affect the same - # native state, without depending on how the installed BLAS is linked. - libraries = {} - for name in ("libopenblas_a.so", "libopenblas_b.so"): - library = Mock(spec=[]) - library.openblas_get_num_threads = Mock(side_effect=lambda: num_threads) - library.openblas_set_num_threads = Mock(side_effect=set_num_threads) - library.openblas_get_parallel = Mock(return_value=1) - libraries[name] = library - - monkeypatch.setattr(threadpoolctl._CDLL_CACHE, "get_cdll", libraries.__getitem__) - monkeypatch.setattr(OpenBLASController._SHARED_STATE, "controlling_thread", None) - controller = ThreadpoolController._from_controllers( - [OpenBLASController(filepath=name, prefix="libopenblas") for name in libraries] +@pytest.mark.skipif( + sys.platform != "linux" or os.getenv("INSTALL_BLAS") != "flexiblas", + reason="requires the FlexiBLAS + pthreads OpenBLAS setup", +) +def test_restore_shared_openblas_thread_count(request): + controller = ThreadpoolController() + (backend,) = controller.select(prefix="libopenblas").lib_controllers + wrapper = next( + lib + for lib in controller.select(internal_api="flexiblas").lib_controllers + if os.path.basename(lib.filepath).startswith("libflexiblas.so") ) - - with controller.limit(limits=1, user_api="blas"): - assert num_threads == 1 - assert num_threads == 16 + assert backend.threading_layer == "pthreads" + original = wrapper.num_threads + request.addfinalizer(lambda: wrapper.set_num_threads(original)) + wrapper.set_num_threads(2) + assert backend.num_threads == 2 + + # Exercise the order where the wrapper would change the backend before + # the OpenBLAS controller gets a chance to save its thread count. + pair = ThreadpoolController._from_controllers([wrapper, backend]) + with pair.limit(limits=1, user_api="blas") as ctx: + assert wrapper.num_threads == backend.num_threads == 1 + assert ctx.get_original_num_threads() == {"blas": 2} + assert wrapper.num_threads == backend.num_threads == 2 @pytest.mark.parametrize( diff --git a/threadpoolctl.py b/threadpoolctl.py index 92a1d311..cf506feb 100644 --- a/threadpoolctl.py +++ b/threadpoolctl.py @@ -201,31 +201,6 @@ def get_and_set() -> None: OpenBLASController.clear_controlling_thread(force=True) -# Returned from set_num_threads() to indicate that setting did not happen, -# typically because the current thread is not the controlling thread. -_DID_NOT_SET = object() - - -@dataclass -class _THIS_THREAD_TOOK_CONTROL: - """Indicates the current thread took control when calling ``set_num_threads()``. - - Includes number of threads set previously, right after control was released. - """ - - previous_num_threads: int - - -@dataclass -class _ALREADY_HAD_CONTROL: - """Indicates control was needed, but this thread already had it. - - Includes number of threads set previously. - """ - - previous_num_threads: int - - class LibController(ABC): """Abstract base class for the individual library controllers @@ -575,43 +550,22 @@ def clear_controlling_thread(cls, force: bool = False): cls._SHARED_STATE.controlling_thread = None def set_num_threads(self, num_threads): - self._set_num_threads_with_extra_info(num_threads) - - def _set_num_threads_with_extra_info(self, num_threads): - if self.threading_layer == "openmp": - # Per-thread limits, so no need to be constraining: - return self._real_set_num_threads(num_threads) + if self.threading_layer == "openmp" or self._claim_control(): + self._real_set_num_threads(num_threads) - # A shared process-wide thread pool, so don't want different Python - # threads fighting over limits: + @classmethod + def _claim_control(cls): + """Claim the process-wide OpenBLAS pools without modifying any of them.""" this_thread = current_thread() - controlling_thread = self._SHARED_STATE.controlling_thread - if controlling_thread is this_thread: - # This thread already controls OpenBLAS: - previous_threads = self.get_num_threads() - self._real_set_num_threads(num_threads) - return _ALREADY_HAD_CONTROL(previous_threads) - elif controlling_thread is None or not controlling_thread.is_alive(): - # No thread controls OpenBLAS, so try to take control: - previous_num_threads = None - with self._SHARED_STATE.lock: - # Another thread might have changed it, so ensure that's not - # the case: - if ( - self._SHARED_STATE.controlling_thread is None - or not self._SHARED_STATE.controlling_thread.is_alive() - ): - self._SHARED_STATE.controlling_thread = this_thread - previous_num_threads = self.get_num_threads() - if previous_num_threads is not None: - self._real_set_num_threads(num_threads) - return _THIS_THREAD_TOOK_CONTROL(previous_num_threads) - else: - # Another thread took control: - return _DID_NOT_SET - else: - # Some other thread controls OpenBLAS: do nothing. - return _DID_NOT_SET + state = cls._SHARED_STATE + if state.controlling_thread is this_thread: + return True + with state.lock: + owner = state.controlling_thread + if owner is None or not owner.is_alive(): + state.controlling_thread = this_thread + return True + return owner is this_thread def _real_set_num_threads(self, num_threads): # The OpenBLAS limiting API is process-wide, and we want current thread @@ -1148,8 +1102,6 @@ def __init__(self, controller, *, limits=None, user_api=None): self._original_info = dict( zip(self._controller.lib_controllers, self._controller.info()) ) - # The undo log must not include libraries we did not change. - self._restore_info = {} self._set_threadpool_limits() def __enter__(self): @@ -1169,9 +1121,10 @@ def wrap(cls, controller, *, limits=None, user_api=None): def restore_original_limits(self): """Set the limits back to their original values""" - # Undo in reverse order: multiple controllers can share native state. - for lib_controller, original_info in reversed(self._restore_info.items()): - lib_controller.set_num_threads(original_info["num_threads"]) + for lib_controller in self._restore_controllers: + lib_controller.set_num_threads( + self._original_info[lib_controller]["num_threads"] + ) # Alias of `restore_original_limits` for backward compatibility unregister = restore_original_limits @@ -1215,72 +1168,36 @@ def get_original_num_threads(self): def _set_threadpool_limits(self): """Change the maximal number of threads in selected thread pools.""" if self._limits is None: - # limits=None is also used to explicitly save and restore a snapshot. - self._restore_info.update(self._original_info) + self._restore_controllers = self._original_info.keys() return - took_control = False - - for lib_controller in self._controller.lib_controllers: - # self._limits is a dict {key: num_threads} where key is either a - # filepath, a prefix, or a user_api. Libraries are matched in that - # order. - if lib_controller.filepath in self._limits: - num_threads = self._limits[lib_controller.filepath] - elif lib_controller.prefix in self._limits: - num_threads = self._limits[lib_controller.prefix] - elif lib_controller.user_api in self._limits: - num_threads = self._limits[lib_controller.user_api] - else: - continue + pending = {} + for lib in self._controller.lib_controllers: + for key in (lib.filepath, lib.prefix, lib.user_api): + if key in self._limits: + if self._limits[key] is not None: + pending[lib] = self._limits[key] + break - if num_threads is not None: - self._restore_info[lib_controller] = self._original_info[lib_controller] - if ( - type(lib_controller) is not OpenBLASController - or lib_controller.threading_layer == "openmp" - ): - lib_controller.set_num_threads(num_threads) - continue + shared = [ + lib + for lib in pending + if type(lib) is OpenBLASController and lib.threading_layer != "openmp" + ] + if shared: + if OpenBLASController._claim_control(): + # The initial snapshot can predate a handoff from another thread. + # Refresh it before any setter, including a wrapper of the same BLAS. + for lib in pending: + self._original_info[lib]["num_threads"] = lib.get_num_threads() + else: + for lib in shared: + del pending[lib] + del self._original_info[lib] - # Special-case OpenBLASController API that returns additional - # information, only used in the pthreads/windows threading - # layer case: - result = lib_controller._set_num_threads_with_extra_info(num_threads) - - if result is _DID_NOT_SET: - # Didn't set, so shouldn't restore either. Lacking this, if - # this thread later became the controlling thread during - # restoration, it might restore the wrong value. - self._original_info.pop(lib_controller, None) - self._restore_info.pop(lib_controller, None) - elif isinstance(result, _THIS_THREAD_TOOK_CONTROL): - # Now that we took control: - # - # 1. Recorded limits for OpenBLAS-pthreads might be wrong, - # since they're global and another thread may have been - # in control and changed them since they were recorded - # in self._original_info. - # 2. Since this thread is now in control, no other thread - # can change that behind our back anymore - # 3. There might be multiple OpenBLAS-pthreads loaded. - # - # So, first set update info for this one, and then set - # took_control to True so later sets of OpenBLAS-pthreads - # can also be updated. - self._original_info[lib_controller]["num_threads"] = ( - result.previous_num_threads - ) - took_control = True - elif took_control and isinstance(result, _ALREADY_HAD_CONTROL): - # This happens if there are multiple OpenBLAS-pthreads - # loaded, e.g. NumPy and SciPy installed from PyPI. Only - # want to do this if we took control, cause that is the - # only case where previously set value might have been - # changed since we recorded it originally. - self._original_info[lib_controller]["num_threads"] = ( - result.previous_num_threads - ) + self._restore_controllers = pending.keys() + for lib, limit in pending.items(): + lib.set_num_threads(limit) class _ThreadpoolLimiterDecorator(ContextDecorator):