Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
@@ -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,
Expand Down
27 changes: 27 additions & 0 deletions tests/test_threadpoolctl.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,33 @@ def test_controller_info_actualized():
assert controller.info() == original_info


@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")
)
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(
"kwargs",
[
Expand Down
164 changes: 44 additions & 120 deletions threadpoolctl.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -1167,8 +1121,10 @@ 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():
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
Expand Down Expand Up @@ -1212,68 +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:
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:
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)
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):
Expand Down
Loading