threadpoolctl.py 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280
  1. """threadpoolctl
  2. This module provides utilities to introspect native libraries that relies on
  3. thread pools (notably BLAS and OpenMP implementations) and dynamically set the
  4. maximal number of threads they can use.
  5. """
  6. # License: BSD 3-Clause
  7. # The code to introspect dynamically loaded libraries on POSIX systems is
  8. # adapted from code by Intel developer @anton-malakhov available at
  9. # https://github.com/IntelPython/smp (Copyright (c) 2017, Intel Corporation)
  10. # and also published under the BSD 3-Clause license
  11. import os
  12. import re
  13. import sys
  14. import ctypes
  15. import itertools
  16. import textwrap
  17. from typing import final
  18. import warnings
  19. from ctypes.util import find_library
  20. from abc import ABC, abstractmethod
  21. from functools import lru_cache
  22. from contextlib import ContextDecorator
  23. __version__ = "3.5.0"
  24. __all__ = [
  25. "threadpool_limits",
  26. "threadpool_info",
  27. "ThreadpoolController",
  28. "LibController",
  29. "register",
  30. ]
  31. # One can get runtime errors or even segfaults due to multiple OpenMP libraries
  32. # loaded simultaneously which can happen easily in Python when importing and
  33. # using compiled extensions built with different compilers and therefore
  34. # different OpenMP runtimes in the same program. In particular libiomp (used by
  35. # Intel ICC) and libomp used by clang/llvm tend to crash. This can happen for
  36. # instance when calling BLAS inside a prange. Setting the following environment
  37. # variable allows multiple OpenMP libraries to be loaded. It should not degrade
  38. # performances since we manually take care of potential over-subscription
  39. # performance issues, in sections of the code where nested OpenMP loops can
  40. # happen, by dynamically reconfiguring the inner OpenMP runtime to temporarily
  41. # disable it while under the scope of the outer OpenMP parallel section.
  42. os.environ.setdefault("KMP_DUPLICATE_LIB_OK", "True")
  43. # Structure to cast the info on dynamically loaded library. See
  44. # https://linux.die.net/man/3/dl_iterate_phdr for more details.
  45. _SYSTEM_UINT = ctypes.c_uint64 if sys.maxsize > 2**32 else ctypes.c_uint32
  46. _SYSTEM_UINT_HALF = ctypes.c_uint32 if sys.maxsize > 2**32 else ctypes.c_uint16
  47. class _dl_phdr_info(ctypes.Structure):
  48. _fields_ = [
  49. ("dlpi_addr", _SYSTEM_UINT), # Base address of object
  50. ("dlpi_name", ctypes.c_char_p), # path to the library
  51. ("dlpi_phdr", ctypes.c_void_p), # pointer on dlpi_headers
  52. ("dlpi_phnum", _SYSTEM_UINT_HALF), # number of elements in dlpi_phdr
  53. ]
  54. # The RTLD_NOLOAD flag for loading shared libraries is not defined on Windows.
  55. try:
  56. _RTLD_NOLOAD = os.RTLD_NOLOAD
  57. except AttributeError:
  58. _RTLD_NOLOAD = ctypes.DEFAULT_MODE
  59. class LibController(ABC):
  60. """Abstract base class for the individual library controllers
  61. A library controller must expose the following class attributes:
  62. - user_api : str
  63. Usually the name of the library or generic specification the library
  64. implements, e.g. "blas" is a specification with different implementations.
  65. - internal_api : str
  66. Usually the name of the library or concrete implementation of some
  67. specification, e.g. "openblas" is an implementation of the "blas"
  68. specification.
  69. - filename_prefixes : tuple
  70. Possible prefixes of the shared library's filename that allow to
  71. identify the library. e.g. "libopenblas" for libopenblas.so.
  72. and implement the following methods: `get_num_threads`, `set_num_threads` and
  73. `get_version`.
  74. Threadpoolctl loops through all the loaded shared libraries and tries to match
  75. the filename of each library with the `filename_prefixes`. If a match is found, a
  76. controller is instantiated and a handler to the library is stored in the `dynlib`
  77. attribute as a `ctypes.CDLL` object. It can be used to access the necessary symbols
  78. of the shared library to implement the above methods.
  79. The following information will be exposed in the info dictionary:
  80. - user_api : standardized API, if any, or a copy of internal_api.
  81. - internal_api : implementation-specific API.
  82. - num_threads : the current thread limit.
  83. - prefix : prefix of the shared library's filename.
  84. - filepath : path to the loaded shared library.
  85. - version : version of the library (if available).
  86. In addition, each library controller may expose internal API specific entries. They
  87. must be set as attributes in the `set_additional_attributes` method.
  88. """
  89. @final
  90. def __init__(self, *, filepath=None, prefix=None, parent=None):
  91. """This is not meant to be overriden by subclasses."""
  92. self.parent = parent
  93. self.prefix = prefix
  94. self.filepath = filepath
  95. self.dynlib = ctypes.CDLL(filepath, mode=_RTLD_NOLOAD)
  96. self._symbol_prefix, self._symbol_suffix = self._find_affixes()
  97. self.version = self.get_version()
  98. self.set_additional_attributes()
  99. def info(self):
  100. """Return relevant info wrapped in a dict"""
  101. hidden_attrs = ("dynlib", "parent", "_symbol_prefix", "_symbol_suffix")
  102. return {
  103. "user_api": self.user_api,
  104. "internal_api": self.internal_api,
  105. "num_threads": self.num_threads,
  106. **{k: v for k, v in vars(self).items() if k not in hidden_attrs},
  107. }
  108. def set_additional_attributes(self):
  109. """Set additional attributes meant to be exposed in the info dict"""
  110. @property
  111. def num_threads(self):
  112. """Exposes the current thread limit as a dynamic property
  113. This is not meant to be used or overriden by subclasses.
  114. """
  115. return self.get_num_threads()
  116. @abstractmethod
  117. def get_num_threads(self):
  118. """Return the maximum number of threads available to use"""
  119. @abstractmethod
  120. def set_num_threads(self, num_threads):
  121. """Set the maximum number of threads to use"""
  122. @abstractmethod
  123. def get_version(self):
  124. """Return the version of the shared library"""
  125. def _find_affixes(self):
  126. """Return the affixes for the symbols of the shared library"""
  127. return "", ""
  128. def _get_symbol(self, name):
  129. """Return the symbol of the shared library accounding for the affixes"""
  130. return getattr(
  131. self.dynlib, f"{self._symbol_prefix}{name}{self._symbol_suffix}", None
  132. )
  133. class OpenBLASController(LibController):
  134. """Controller class for OpenBLAS"""
  135. user_api = "blas"
  136. internal_api = "openblas"
  137. filename_prefixes = ("libopenblas", "libblas", "libscipy_openblas")
  138. _symbol_prefixes = ("", "scipy_")
  139. _symbol_suffixes = ("", "64_", "_64")
  140. # All variations of "openblas_get_num_threads", accounting for the affixes
  141. check_symbols = tuple(
  142. f"{prefix}openblas_get_num_threads{suffix}"
  143. for prefix, suffix in itertools.product(_symbol_prefixes, _symbol_suffixes)
  144. )
  145. def _find_affixes(self):
  146. for prefix, suffix in itertools.product(
  147. self._symbol_prefixes, self._symbol_suffixes
  148. ):
  149. if hasattr(self.dynlib, f"{prefix}openblas_get_num_threads{suffix}"):
  150. return prefix, suffix
  151. def set_additional_attributes(self):
  152. self.threading_layer = self._get_threading_layer()
  153. self.architecture = self._get_architecture()
  154. def get_num_threads(self):
  155. get_num_threads_func = self._get_symbol("openblas_get_num_threads")
  156. if get_num_threads_func is not None:
  157. return get_num_threads_func()
  158. return None
  159. def set_num_threads(self, num_threads):
  160. set_num_threads_func = self._get_symbol("openblas_set_num_threads")
  161. if set_num_threads_func is not None:
  162. return set_num_threads_func(num_threads)
  163. return None
  164. def get_version(self):
  165. # None means OpenBLAS is not loaded or version < 0.3.4, since OpenBLAS
  166. # did not expose its version before that.
  167. get_version_func = self._get_symbol("openblas_get_config")
  168. if get_version_func is not None:
  169. get_version_func.restype = ctypes.c_char_p
  170. config = get_version_func().split()
  171. if config[0] == b"OpenBLAS":
  172. return config[1].decode("utf-8")
  173. return None
  174. return None
  175. def _get_threading_layer(self):
  176. """Return the threading layer of OpenBLAS"""
  177. get_threading_layer_func = self._get_symbol("openblas_get_parallel")
  178. if get_threading_layer_func is not None:
  179. threading_layer = get_threading_layer_func()
  180. if threading_layer == 2:
  181. return "openmp"
  182. elif threading_layer == 1:
  183. return "pthreads"
  184. return "disabled"
  185. return "unknown"
  186. def _get_architecture(self):
  187. """Return the architecture detected by OpenBLAS"""
  188. get_architecture_func = self._get_symbol("openblas_get_corename")
  189. if get_architecture_func is not None:
  190. get_architecture_func.restype = ctypes.c_char_p
  191. return get_architecture_func().decode("utf-8")
  192. return None
  193. class BLISController(LibController):
  194. """Controller class for BLIS"""
  195. user_api = "blas"
  196. internal_api = "blis"
  197. filename_prefixes = ("libblis", "libblas")
  198. check_symbols = (
  199. "bli_thread_get_num_threads",
  200. "bli_thread_set_num_threads",
  201. "bli_info_get_version_str",
  202. "bli_info_get_enable_openmp",
  203. "bli_info_get_enable_pthreads",
  204. "bli_arch_query_id",
  205. "bli_arch_string",
  206. )
  207. def set_additional_attributes(self):
  208. self.threading_layer = self._get_threading_layer()
  209. self.architecture = self._get_architecture()
  210. def get_num_threads(self):
  211. get_func = getattr(self.dynlib, "bli_thread_get_num_threads", lambda: None)
  212. num_threads = get_func()
  213. # by default BLIS is single-threaded and get_num_threads
  214. # returns -1. We map it to 1 for consistency with other libraries.
  215. return 1 if num_threads == -1 else num_threads
  216. def set_num_threads(self, num_threads):
  217. set_func = getattr(
  218. self.dynlib, "bli_thread_set_num_threads", lambda num_threads: None
  219. )
  220. return set_func(num_threads)
  221. def get_version(self):
  222. get_version_ = getattr(self.dynlib, "bli_info_get_version_str", None)
  223. if get_version_ is None:
  224. return None
  225. get_version_.restype = ctypes.c_char_p
  226. return get_version_().decode("utf-8")
  227. def _get_threading_layer(self):
  228. """Return the threading layer of BLIS"""
  229. if getattr(self.dynlib, "bli_info_get_enable_openmp", lambda: False)():
  230. return "openmp"
  231. elif getattr(self.dynlib, "bli_info_get_enable_pthreads", lambda: False)():
  232. return "pthreads"
  233. return "disabled"
  234. def _get_architecture(self):
  235. """Return the architecture detected by BLIS"""
  236. bli_arch_query_id = getattr(self.dynlib, "bli_arch_query_id", None)
  237. bli_arch_string = getattr(self.dynlib, "bli_arch_string", None)
  238. if bli_arch_query_id is None or bli_arch_string is None:
  239. return None
  240. # the true restype should be BLIS' arch_t (enum) but int should work
  241. # for us:
  242. bli_arch_query_id.restype = ctypes.c_int
  243. bli_arch_string.restype = ctypes.c_char_p
  244. return bli_arch_string(bli_arch_query_id()).decode("utf-8")
  245. class FlexiBLASController(LibController):
  246. """Controller class for FlexiBLAS"""
  247. user_api = "blas"
  248. internal_api = "flexiblas"
  249. filename_prefixes = ("libflexiblas",)
  250. check_symbols = (
  251. "flexiblas_get_num_threads",
  252. "flexiblas_set_num_threads",
  253. "flexiblas_get_version",
  254. "flexiblas_list",
  255. "flexiblas_list_loaded",
  256. "flexiblas_current_backend",
  257. )
  258. @property
  259. def loaded_backends(self):
  260. return self._get_backend_list(loaded=True)
  261. @property
  262. def current_backend(self):
  263. return self._get_current_backend()
  264. def info(self):
  265. """Return relevant info wrapped in a dict"""
  266. # We override the info method because the loaded and current backends
  267. # are dynamic properties
  268. exposed_attrs = super().info()
  269. exposed_attrs["loaded_backends"] = self.loaded_backends
  270. exposed_attrs["current_backend"] = self.current_backend
  271. return exposed_attrs
  272. def set_additional_attributes(self):
  273. self.available_backends = self._get_backend_list(loaded=False)
  274. def get_num_threads(self):
  275. get_func = getattr(self.dynlib, "flexiblas_get_num_threads", lambda: None)
  276. num_threads = get_func()
  277. # by default BLIS is single-threaded and get_num_threads
  278. # returns -1. We map it to 1 for consistency with other libraries.
  279. return 1 if num_threads == -1 else num_threads
  280. def set_num_threads(self, num_threads):
  281. set_func = getattr(
  282. self.dynlib, "flexiblas_set_num_threads", lambda num_threads: None
  283. )
  284. return set_func(num_threads)
  285. def get_version(self):
  286. get_version_ = getattr(self.dynlib, "flexiblas_get_version", None)
  287. if get_version_ is None:
  288. return None
  289. major = ctypes.c_int()
  290. minor = ctypes.c_int()
  291. patch = ctypes.c_int()
  292. get_version_(ctypes.byref(major), ctypes.byref(minor), ctypes.byref(patch))
  293. return f"{major.value}.{minor.value}.{patch.value}"
  294. def _get_backend_list(self, loaded=False):
  295. """Return the list of available backends for FlexiBLAS.
  296. If loaded is False, return the list of available backends from the FlexiBLAS
  297. configuration. If loaded is True, return the list of actually loaded backends.
  298. """
  299. func_name = f"flexiblas_list{'_loaded' if loaded else ''}"
  300. get_backend_list_ = getattr(self.dynlib, func_name, None)
  301. if get_backend_list_ is None:
  302. return None
  303. n_backends = get_backend_list_(None, 0, 0)
  304. backends = []
  305. for i in range(n_backends):
  306. backend_name = ctypes.create_string_buffer(1024)
  307. get_backend_list_(backend_name, 1024, i)
  308. if backend_name.value.decode("utf-8") != "__FALLBACK__":
  309. # We don't know when to expect __FALLBACK__ but it is not a real
  310. # backend and does not show up when running flexiblas list.
  311. backends.append(backend_name.value.decode("utf-8"))
  312. return backends
  313. def _get_current_backend(self):
  314. """Return the backend of FlexiBLAS"""
  315. get_backend_ = getattr(self.dynlib, "flexiblas_current_backend", None)
  316. if get_backend_ is None:
  317. return None
  318. backend = ctypes.create_string_buffer(1024)
  319. get_backend_(backend, ctypes.sizeof(backend))
  320. return backend.value.decode("utf-8")
  321. def switch_backend(self, backend):
  322. """Switch the backend of FlexiBLAS
  323. Parameters
  324. ----------
  325. backend : str
  326. The name or the path to the shared library of the backend to switch to. If
  327. the backend is not already loaded, it will be loaded first.
  328. """
  329. if backend not in self.loaded_backends:
  330. if backend in self.available_backends:
  331. load_func = getattr(self.dynlib, "flexiblas_load_backend", lambda _: -1)
  332. else: # assume backend is a path to a shared library
  333. load_func = getattr(
  334. self.dynlib, "flexiblas_load_backend_library", lambda _: -1
  335. )
  336. res = load_func(str(backend).encode("utf-8"))
  337. if res == -1:
  338. raise RuntimeError(
  339. f"Failed to load backend {backend!r}. It must either be the name of"
  340. " a backend available in the FlexiBLAS configuration "
  341. f"{self.available_backends} or the path to a valid shared library."
  342. )
  343. # Trigger a new search of loaded shared libraries since loading a new
  344. # backend caused a dlopen.
  345. self.parent._load_libraries()
  346. switch_func = getattr(self.dynlib, "flexiblas_switch", lambda _: -1)
  347. idx = self.loaded_backends.index(backend)
  348. res = switch_func(idx)
  349. if res == -1:
  350. raise RuntimeError(f"Failed to switch to backend {backend!r}.")
  351. class MKLController(LibController):
  352. """Controller class for MKL"""
  353. user_api = "blas"
  354. internal_api = "mkl"
  355. filename_prefixes = ("libmkl_rt", "mkl_rt", "libblas")
  356. check_symbols = (
  357. "MKL_Get_Max_Threads",
  358. "MKL_Set_Num_Threads",
  359. "MKL_Get_Version_String",
  360. "MKL_Set_Threading_Layer",
  361. )
  362. def set_additional_attributes(self):
  363. self.threading_layer = self._get_threading_layer()
  364. def get_num_threads(self):
  365. get_func = getattr(self.dynlib, "MKL_Get_Max_Threads", lambda: None)
  366. return get_func()
  367. def set_num_threads(self, num_threads):
  368. set_func = getattr(self.dynlib, "MKL_Set_Num_Threads", lambda num_threads: None)
  369. return set_func(num_threads)
  370. def get_version(self):
  371. if not hasattr(self.dynlib, "MKL_Get_Version_String"):
  372. return None
  373. res = ctypes.create_string_buffer(200)
  374. self.dynlib.MKL_Get_Version_String(res, 200)
  375. version = res.value.decode("utf-8")
  376. group = re.search(r"Version ([^ ]+) ", version)
  377. if group is not None:
  378. version = group.groups()[0]
  379. return version.strip()
  380. def _get_threading_layer(self):
  381. """Return the threading layer of MKL"""
  382. # The function mkl_set_threading_layer returns the current threading
  383. # layer. Calling it with an invalid threading layer allows us to safely
  384. # get the threading layer
  385. set_threading_layer = getattr(
  386. self.dynlib, "MKL_Set_Threading_Layer", lambda layer: -1
  387. )
  388. layer_map = {
  389. 0: "intel",
  390. 1: "sequential",
  391. 2: "pgi",
  392. 3: "gnu",
  393. 4: "tbb",
  394. -1: "not specified",
  395. }
  396. return layer_map[set_threading_layer(-1)]
  397. class OpenMPController(LibController):
  398. """Controller class for OpenMP"""
  399. user_api = "openmp"
  400. internal_api = "openmp"
  401. filename_prefixes = ("libiomp", "libgomp", "libomp", "vcomp")
  402. check_symbols = (
  403. "omp_get_max_threads",
  404. "omp_get_num_threads",
  405. )
  406. def get_num_threads(self):
  407. get_func = getattr(self.dynlib, "omp_get_max_threads", lambda: None)
  408. return get_func()
  409. def set_num_threads(self, num_threads):
  410. set_func = getattr(self.dynlib, "omp_set_num_threads", lambda num_threads: None)
  411. return set_func(num_threads)
  412. def get_version(self):
  413. # There is no way to get the version number programmatically in OpenMP.
  414. return None
  415. # Controllers for the libraries that we'll look for in the loaded libraries.
  416. # Third party libraries can register their own controllers.
  417. _ALL_CONTROLLERS = [
  418. OpenBLASController,
  419. BLISController,
  420. MKLController,
  421. OpenMPController,
  422. FlexiBLASController,
  423. ]
  424. # Helpers for the doc and test names
  425. _ALL_USER_APIS = list(set(lib.user_api for lib in _ALL_CONTROLLERS))
  426. _ALL_INTERNAL_APIS = [lib.internal_api for lib in _ALL_CONTROLLERS]
  427. _ALL_PREFIXES = list(
  428. set(prefix for lib in _ALL_CONTROLLERS for prefix in lib.filename_prefixes)
  429. )
  430. _ALL_BLAS_LIBRARIES = [
  431. lib.internal_api for lib in _ALL_CONTROLLERS if lib.user_api == "blas"
  432. ]
  433. _ALL_OPENMP_LIBRARIES = OpenMPController.filename_prefixes
  434. def register(controller):
  435. """Register a new controller"""
  436. _ALL_CONTROLLERS.append(controller)
  437. _ALL_USER_APIS.append(controller.user_api)
  438. _ALL_INTERNAL_APIS.append(controller.internal_api)
  439. _ALL_PREFIXES.extend(controller.filename_prefixes)
  440. def _format_docstring(*args, **kwargs):
  441. def decorator(o):
  442. if o.__doc__ is not None:
  443. o.__doc__ = o.__doc__.format(*args, **kwargs)
  444. return o
  445. return decorator
  446. @lru_cache(maxsize=10000)
  447. def _realpath(filepath):
  448. """Small caching wrapper around os.path.realpath to limit system calls"""
  449. return os.path.realpath(filepath)
  450. @_format_docstring(USER_APIS=list(_ALL_USER_APIS), INTERNAL_APIS=_ALL_INTERNAL_APIS)
  451. def threadpool_info():
  452. """Return the maximal number of threads for each detected library.
  453. Return a list with all the supported libraries that have been found. Each
  454. library is represented by a dict with the following information:
  455. - "user_api" : user API. Possible values are {USER_APIS}.
  456. - "internal_api": internal API. Possible values are {INTERNAL_APIS}.
  457. - "prefix" : filename prefix of the specific implementation.
  458. - "filepath": path to the loaded library.
  459. - "version": version of the library (if available).
  460. - "num_threads": the current thread limit.
  461. In addition, each library may contain internal_api specific entries.
  462. """
  463. return ThreadpoolController().info()
  464. class _ThreadpoolLimiter:
  465. """The guts of ThreadpoolController.limit
  466. Refer to the docstring of ThreadpoolController.limit for more details.
  467. It will only act on the library controllers held by the provided `controller`.
  468. Using the default constructor sets the limits right away such that it can be used as
  469. a callable. Setting the limits can be delayed by using the `wrap` class method such
  470. that it can be used as a decorator.
  471. """
  472. def __init__(self, controller, *, limits=None, user_api=None):
  473. self._controller = controller
  474. self._limits, self._user_api, self._prefixes = self._check_params(
  475. limits, user_api
  476. )
  477. self._original_info = self._controller.info()
  478. self._set_threadpool_limits()
  479. def __enter__(self):
  480. return self
  481. def __exit__(self, type, value, traceback):
  482. self.restore_original_limits()
  483. @classmethod
  484. def wrap(cls, controller, *, limits=None, user_api=None):
  485. """Return an instance of this class that can be used as a decorator"""
  486. return _ThreadpoolLimiterDecorator(
  487. controller=controller, limits=limits, user_api=user_api
  488. )
  489. def restore_original_limits(self):
  490. """Set the limits back to their original values"""
  491. for lib_controller, original_info in zip(
  492. self._controller.lib_controllers, self._original_info
  493. ):
  494. lib_controller.set_num_threads(original_info["num_threads"])
  495. # Alias of `restore_original_limits` for backward compatibility
  496. unregister = restore_original_limits
  497. def get_original_num_threads(self):
  498. """Original num_threads from before calling threadpool_limits
  499. Return a dict `{user_api: num_threads}`.
  500. """
  501. num_threads = {}
  502. warning_apis = []
  503. for user_api in self._user_api:
  504. limits = [
  505. lib_info["num_threads"]
  506. for lib_info in self._original_info
  507. if lib_info["user_api"] == user_api
  508. ]
  509. limits = set(limits)
  510. n_limits = len(limits)
  511. if n_limits == 1:
  512. limit = limits.pop()
  513. elif n_limits == 0:
  514. limit = None
  515. else:
  516. limit = min(limits)
  517. warning_apis.append(user_api)
  518. num_threads[user_api] = limit
  519. if warning_apis:
  520. warnings.warn(
  521. "Multiple value possible for following user apis: "
  522. + ", ".join(warning_apis)
  523. + ". Returning the minimum."
  524. )
  525. return num_threads
  526. def _check_params(self, limits, user_api):
  527. """Suitable values for the _limits, _user_api and _prefixes attributes"""
  528. if isinstance(limits, str) and limits == "sequential_blas_under_openmp":
  529. (
  530. limits,
  531. user_api,
  532. ) = self._controller._get_params_for_sequential_blas_under_openmp().values()
  533. if limits is None or isinstance(limits, int):
  534. if user_api is None:
  535. user_api = _ALL_USER_APIS
  536. elif user_api in _ALL_USER_APIS:
  537. user_api = [user_api]
  538. else:
  539. raise ValueError(
  540. f"user_api must be either in {_ALL_USER_APIS} or None. Got "
  541. f"{user_api} instead."
  542. )
  543. if limits is not None:
  544. limits = {api: limits for api in user_api}
  545. prefixes = []
  546. else:
  547. if isinstance(limits, list):
  548. # This should be a list of dicts of library info, for
  549. # compatibility with the result from threadpool_info.
  550. limits = {
  551. lib_info["prefix"]: lib_info["num_threads"] for lib_info in limits
  552. }
  553. elif isinstance(limits, ThreadpoolController):
  554. # To set the limits from the library controllers of a
  555. # ThreadpoolController object.
  556. limits = {
  557. lib_controller.prefix: lib_controller.num_threads
  558. for lib_controller in limits.lib_controllers
  559. }
  560. if not isinstance(limits, dict):
  561. raise TypeError(
  562. "limits must either be an int, a list, a dict, or "
  563. f"'sequential_blas_under_openmp'. Got {type(limits)} instead"
  564. )
  565. # With a dictionary, can set both specific limit for given
  566. # libraries and global limit for user_api. Fetch each separately.
  567. prefixes = [prefix for prefix in limits if prefix in _ALL_PREFIXES]
  568. user_api = [api for api in limits if api in _ALL_USER_APIS]
  569. return limits, user_api, prefixes
  570. def _set_threadpool_limits(self):
  571. """Change the maximal number of threads in selected thread pools.
  572. Return a list with all the supported libraries that have been found
  573. matching `self._prefixes` and `self._user_api`.
  574. """
  575. if self._limits is None:
  576. return
  577. for lib_controller in self._controller.lib_controllers:
  578. # self._limits is a dict {key: num_threads} where key is either
  579. # a prefix or a user_api. If a library matches both, the limit
  580. # corresponding to the prefix is chosen.
  581. if lib_controller.prefix in self._limits:
  582. num_threads = self._limits[lib_controller.prefix]
  583. elif lib_controller.user_api in self._limits:
  584. num_threads = self._limits[lib_controller.user_api]
  585. else:
  586. continue
  587. if num_threads is not None:
  588. lib_controller.set_num_threads(num_threads)
  589. class _ThreadpoolLimiterDecorator(_ThreadpoolLimiter, ContextDecorator):
  590. """Same as _ThreadpoolLimiter but to be used as a decorator"""
  591. def __init__(self, controller, *, limits=None, user_api=None):
  592. self._limits, self._user_api, self._prefixes = self._check_params(
  593. limits, user_api
  594. )
  595. self._controller = controller
  596. def __enter__(self):
  597. # we need to set the limits here and not in the __init__ because we want the
  598. # limits to be set when calling the decorated function, not when creating the
  599. # decorator.
  600. self._original_info = self._controller.info()
  601. self._set_threadpool_limits()
  602. return self
  603. @_format_docstring(
  604. USER_APIS=", ".join(f'"{api}"' for api in _ALL_USER_APIS),
  605. BLAS_LIBS=", ".join(_ALL_BLAS_LIBRARIES),
  606. OPENMP_LIBS=", ".join(_ALL_OPENMP_LIBRARIES),
  607. )
  608. class threadpool_limits(_ThreadpoolLimiter):
  609. """Change the maximal number of threads that can be used in thread pools.
  610. This object can be used either as a callable (the construction of this object
  611. limits the number of threads), as a context manager in a `with` block to
  612. automatically restore the original state of the controlled libraries when exiting
  613. the block, or as a decorator through its `wrap` method.
  614. Set the maximal number of threads that can be used in thread pools used in
  615. the supported libraries to `limit`. This function works for libraries that
  616. are already loaded in the interpreter and can be changed dynamically.
  617. This effect is global and impacts the whole Python process. There is no thread level
  618. isolation as these libraries do not offer thread-local APIs to configure the number
  619. of threads to use in nested parallel calls.
  620. Parameters
  621. ----------
  622. limits : int, dict, 'sequential_blas_under_openmp' or None (default=None)
  623. The maximal number of threads that can be used in thread pools
  624. - If int, sets the maximum number of threads to `limits` for each
  625. library selected by `user_api`.
  626. - If it is a dictionary `{{key: max_threads}}`, this function sets a
  627. custom maximum number of threads for each `key` which can be either a
  628. `user_api` or a `prefix` for a specific library.
  629. - If 'sequential_blas_under_openmp', it will chose the appropriate `limits`
  630. and `user_api` parameters for the specific use case of sequential BLAS
  631. calls within an OpenMP parallel region. The `user_api` parameter is
  632. ignored.
  633. - If None, this function does not do anything.
  634. user_api : {USER_APIS} or None (default=None)
  635. APIs of libraries to limit. Used only if `limits` is an int.
  636. - If "blas", it will only limit BLAS supported libraries ({BLAS_LIBS}).
  637. - If "openmp", it will only limit OpenMP supported libraries
  638. ({OPENMP_LIBS}). Note that it can affect the number of threads used
  639. by the BLAS libraries if they rely on OpenMP.
  640. - If None, this function will apply to all supported libraries.
  641. """
  642. def __init__(self, limits=None, user_api=None):
  643. super().__init__(ThreadpoolController(), limits=limits, user_api=user_api)
  644. @classmethod
  645. def wrap(cls, limits=None, user_api=None):
  646. return super().wrap(ThreadpoolController(), limits=limits, user_api=user_api)
  647. class ThreadpoolController:
  648. """Collection of LibController objects for all loaded supported libraries
  649. Attributes
  650. ----------
  651. lib_controllers : list of `LibController` objects
  652. The list of library controllers of all loaded supported libraries.
  653. """
  654. # Cache for libc under POSIX and a few system libraries under Windows.
  655. # We use a class level cache instead of an instance level cache because
  656. # it's very unlikely that a shared library will be unloaded and reloaded
  657. # during the lifetime of a program.
  658. _system_libraries = dict()
  659. def __init__(self):
  660. self.lib_controllers = []
  661. self._load_libraries()
  662. self._warn_if_incompatible_openmp()
  663. @classmethod
  664. def _from_controllers(cls, lib_controllers):
  665. new_controller = cls.__new__(cls)
  666. new_controller.lib_controllers = lib_controllers
  667. return new_controller
  668. def info(self):
  669. """Return lib_controllers info as a list of dicts"""
  670. return [lib_controller.info() for lib_controller in self.lib_controllers]
  671. def select(self, **kwargs):
  672. """Return a ThreadpoolController containing a subset of its current
  673. library controllers
  674. It will select all libraries matching at least one pair (key, value) from kwargs
  675. where key is an entry of the library info dict (like "user_api", "internal_api",
  676. "prefix", ...) and value is the value or a list of acceptable values for that
  677. entry.
  678. For instance, `ThreadpoolController().select(internal_api=["blis", "openblas"])`
  679. will select all library controllers whose internal_api is either "blis" or
  680. "openblas".
  681. """
  682. for key, vals in kwargs.items():
  683. kwargs[key] = [vals] if not isinstance(vals, list) else vals
  684. lib_controllers = [
  685. lib_controller
  686. for lib_controller in self.lib_controllers
  687. if any(
  688. getattr(lib_controller, key, None) in vals
  689. for key, vals in kwargs.items()
  690. )
  691. ]
  692. return ThreadpoolController._from_controllers(lib_controllers)
  693. def _get_params_for_sequential_blas_under_openmp(self):
  694. """Return appropriate params to use for a sequential BLAS call in an OpenMP loop
  695. This function takes into account the unexpected behavior of OpenBLAS with the
  696. OpenMP threading layer.
  697. """
  698. if self.select(
  699. internal_api="openblas", threading_layer="openmp"
  700. ).lib_controllers:
  701. return {"limits": None, "user_api": None}
  702. return {"limits": 1, "user_api": "blas"}
  703. @_format_docstring(
  704. USER_APIS=", ".join('"{}"'.format(api) for api in _ALL_USER_APIS),
  705. BLAS_LIBS=", ".join(_ALL_BLAS_LIBRARIES),
  706. OPENMP_LIBS=", ".join(_ALL_OPENMP_LIBRARIES),
  707. )
  708. def limit(self, *, limits=None, user_api=None):
  709. """Change the maximal number of threads that can be used in thread pools.
  710. This function returns an object that can be used either as a callable (the
  711. construction of this object limits the number of threads) or as a context
  712. manager, in a `with` block to automatically restore the original state of the
  713. controlled libraries when exiting the block.
  714. Set the maximal number of threads that can be used in thread pools used in
  715. the supported libraries to `limits`. This function works for libraries that
  716. are already loaded in the interpreter and can be changed dynamically.
  717. This effect is global and impacts the whole Python process. There is no thread
  718. level isolation as these libraries do not offer thread-local APIs to configure
  719. the number of threads to use in nested parallel calls.
  720. Parameters
  721. ----------
  722. limits : int, dict, 'sequential_blas_under_openmp' or None (default=None)
  723. The maximal number of threads that can be used in thread pools
  724. - If int, sets the maximum number of threads to `limits` for each
  725. library selected by `user_api`.
  726. - If it is a dictionary `{{key: max_threads}}`, this function sets a
  727. custom maximum number of threads for each `key` which can be either a
  728. `user_api` or a `prefix` for a specific library.
  729. - If 'sequential_blas_under_openmp', it will chose the appropriate `limits`
  730. and `user_api` parameters for the specific use case of sequential BLAS
  731. calls within an OpenMP parallel region. The `user_api` parameter is
  732. ignored.
  733. - If None, this function does not do anything.
  734. user_api : {USER_APIS} or None (default=None)
  735. APIs of libraries to limit. Used only if `limits` is an int.
  736. - If "blas", it will only limit BLAS supported libraries ({BLAS_LIBS}).
  737. - If "openmp", it will only limit OpenMP supported libraries
  738. ({OPENMP_LIBS}). Note that it can affect the number of threads used
  739. by the BLAS libraries if they rely on OpenMP.
  740. - If None, this function will apply to all supported libraries.
  741. """
  742. return _ThreadpoolLimiter(self, limits=limits, user_api=user_api)
  743. @_format_docstring(
  744. USER_APIS=", ".join('"{}"'.format(api) for api in _ALL_USER_APIS),
  745. BLAS_LIBS=", ".join(_ALL_BLAS_LIBRARIES),
  746. OPENMP_LIBS=", ".join(_ALL_OPENMP_LIBRARIES),
  747. )
  748. def wrap(self, *, limits=None, user_api=None):
  749. """Change the maximal number of threads that can be used in thread pools.
  750. This function returns an object that can be used as a decorator.
  751. Set the maximal number of threads that can be used in thread pools used in
  752. the supported libraries to `limits`. This function works for libraries that
  753. are already loaded in the interpreter and can be changed dynamically.
  754. Parameters
  755. ----------
  756. limits : int, dict or None (default=None)
  757. The maximal number of threads that can be used in thread pools
  758. - If int, sets the maximum number of threads to `limits` for each
  759. library selected by `user_api`.
  760. - If it is a dictionary `{{key: max_threads}}`, this function sets a
  761. custom maximum number of threads for each `key` which can be either a
  762. `user_api` or a `prefix` for a specific library.
  763. - If None, this function does not do anything.
  764. user_api : {USER_APIS} or None (default=None)
  765. APIs of libraries to limit. Used only if `limits` is an int.
  766. - If "blas", it will only limit BLAS supported libraries ({BLAS_LIBS}).
  767. - If "openmp", it will only limit OpenMP supported libraries
  768. ({OPENMP_LIBS}). Note that it can affect the number of threads used
  769. by the BLAS libraries if they rely on OpenMP.
  770. - If None, this function will apply to all supported libraries.
  771. """
  772. return _ThreadpoolLimiter.wrap(self, limits=limits, user_api=user_api)
  773. def __len__(self):
  774. return len(self.lib_controllers)
  775. def _load_libraries(self):
  776. """Loop through loaded shared libraries and store the supported ones"""
  777. if sys.platform == "darwin":
  778. self._find_libraries_with_dyld()
  779. elif sys.platform == "win32":
  780. self._find_libraries_with_enum_process_module_ex()
  781. elif "pyodide" in sys.modules:
  782. self._find_libraries_pyodide()
  783. else:
  784. self._find_libraries_with_dl_iterate_phdr()
  785. def _find_libraries_with_dl_iterate_phdr(self):
  786. """Loop through loaded libraries and return binders on supported ones
  787. This function is expected to work on POSIX system only.
  788. This code is adapted from code by Intel developer @anton-malakhov
  789. available at https://github.com/IntelPython/smp
  790. Copyright (c) 2017, Intel Corporation published under the BSD 3-Clause
  791. license
  792. """
  793. libc = self._get_libc()
  794. if not hasattr(libc, "dl_iterate_phdr"): # pragma: no cover
  795. warnings.warn(
  796. "Could not find dl_iterate_phdr in the C standard library.",
  797. RuntimeWarning,
  798. )
  799. return []
  800. # Callback function for `dl_iterate_phdr` which is called for every
  801. # library loaded in the current process until it returns 1.
  802. def match_library_callback(info, size, data):
  803. # Get the path of the current library
  804. filepath = info.contents.dlpi_name
  805. if filepath:
  806. filepath = filepath.decode("utf-8")
  807. # Store the library controller if it is supported and selected
  808. self._make_controller_from_path(filepath)
  809. return 0
  810. c_func_signature = ctypes.CFUNCTYPE(
  811. ctypes.c_int, # Return type
  812. ctypes.POINTER(_dl_phdr_info),
  813. ctypes.c_size_t,
  814. ctypes.c_char_p,
  815. )
  816. c_match_library_callback = c_func_signature(match_library_callback)
  817. data = ctypes.c_char_p(b"")
  818. libc.dl_iterate_phdr(c_match_library_callback, data)
  819. def _find_libraries_with_dyld(self):
  820. """Loop through loaded libraries and return binders on supported ones
  821. This function is expected to work on OSX system only
  822. """
  823. libc = self._get_libc()
  824. if not hasattr(libc, "_dyld_image_count"): # pragma: no cover
  825. warnings.warn(
  826. "Could not find _dyld_image_count in the C standard library.",
  827. RuntimeWarning,
  828. )
  829. return []
  830. n_dyld = libc._dyld_image_count()
  831. libc._dyld_get_image_name.restype = ctypes.c_char_p
  832. for i in range(n_dyld):
  833. filepath = ctypes.string_at(libc._dyld_get_image_name(i))
  834. filepath = filepath.decode("utf-8")
  835. # Store the library controller if it is supported and selected
  836. self._make_controller_from_path(filepath)
  837. def _find_libraries_with_enum_process_module_ex(self):
  838. """Loop through loaded libraries and return binders on supported ones
  839. This function is expected to work on windows system only.
  840. This code is adapted from code by Philipp Hagemeister @phihag available
  841. at https://stackoverflow.com/questions/17474574
  842. """
  843. from ctypes.wintypes import DWORD, HMODULE, MAX_PATH
  844. PROCESS_QUERY_INFORMATION = 0x0400
  845. PROCESS_VM_READ = 0x0010
  846. LIST_LIBRARIES_ALL = 0x03
  847. ps_api = self._get_windll("Psapi")
  848. kernel_32 = self._get_windll("kernel32")
  849. h_process = kernel_32.OpenProcess(
  850. PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, False, os.getpid()
  851. )
  852. if not h_process: # pragma: no cover
  853. raise OSError(f"Could not open PID {os.getpid()}")
  854. try:
  855. buf_count = 256
  856. needed = DWORD()
  857. # Grow the buffer until it becomes large enough to hold all the
  858. # module headers
  859. while True:
  860. buf = (HMODULE * buf_count)()
  861. buf_size = ctypes.sizeof(buf)
  862. if not ps_api.EnumProcessModulesEx(
  863. h_process,
  864. ctypes.byref(buf),
  865. buf_size,
  866. ctypes.byref(needed),
  867. LIST_LIBRARIES_ALL,
  868. ):
  869. raise OSError("EnumProcessModulesEx failed")
  870. if buf_size >= needed.value:
  871. break
  872. buf_count = needed.value // (buf_size // buf_count)
  873. count = needed.value // (buf_size // buf_count)
  874. h_modules = map(HMODULE, buf[:count])
  875. # Loop through all the module headers and get the library path
  876. buf = ctypes.create_unicode_buffer(MAX_PATH)
  877. n_size = DWORD()
  878. for h_module in h_modules:
  879. # Get the path of the current module
  880. if not ps_api.GetModuleFileNameExW(
  881. h_process, h_module, ctypes.byref(buf), ctypes.byref(n_size)
  882. ):
  883. raise OSError("GetModuleFileNameEx failed")
  884. filepath = buf.value
  885. # Store the library controller if it is supported and selected
  886. self._make_controller_from_path(filepath)
  887. finally:
  888. kernel_32.CloseHandle(h_process)
  889. def _find_libraries_pyodide(self):
  890. """Pyodide specific implementation for finding loaded libraries.
  891. Adapted from suggestion in https://github.com/joblib/threadpoolctl/pull/169#issuecomment-1946696449.
  892. One day, we may have a simpler solution. libc dl_iterate_phdr needs to
  893. be implemented in Emscripten and exposed in Pyodide, see
  894. https://github.com/emscripten-core/emscripten/issues/21354 for more
  895. details.
  896. """
  897. try:
  898. from pyodide_js._module import LDSO
  899. except ImportError:
  900. warnings.warn(
  901. "Unable to import LDSO from pyodide_js._module. This should never "
  902. "happen."
  903. )
  904. return
  905. for filepath in LDSO.loadedLibsByName.as_object_map():
  906. # Some libraries are duplicated by Pyodide and do not exist in the
  907. # filesystem, so we first check for the existence of the file. For
  908. # more details, see
  909. # https://github.com/joblib/threadpoolctl/pull/169#issuecomment-1947946728
  910. if os.path.exists(filepath):
  911. self._make_controller_from_path(filepath)
  912. def _make_controller_from_path(self, filepath):
  913. """Store a library controller if it is supported and selected"""
  914. # Required to resolve symlinks
  915. filepath = _realpath(filepath)
  916. # `lower` required to take account of OpenMP dll case on Windows
  917. # (vcomp, VCOMP, Vcomp, ...)
  918. filename = os.path.basename(filepath).lower()
  919. # Loop through supported libraries to find if this filename corresponds
  920. # to a supported one.
  921. for controller_class in _ALL_CONTROLLERS:
  922. # check if filename matches a supported prefix
  923. prefix = self._check_prefix(filename, controller_class.filename_prefixes)
  924. # filename does not match any of the prefixes of the candidate
  925. # library. move to next library.
  926. if prefix is None:
  927. continue
  928. # workaround for BLAS libraries packaged by conda-forge on windows, which
  929. # are all renamed "libblas.dll". We thus have to check to which BLAS
  930. # implementation it actually corresponds looking for implementation
  931. # specific symbols.
  932. if prefix == "libblas":
  933. if filename.endswith(".dll"):
  934. libblas = ctypes.CDLL(filepath, _RTLD_NOLOAD)
  935. if not any(
  936. hasattr(libblas, func)
  937. for func in controller_class.check_symbols
  938. ):
  939. continue
  940. else:
  941. # We ignore libblas on other platforms than windows because there
  942. # might be a libblas dso comming with openblas for instance that
  943. # can't be used to instantiate a pertinent LibController (many
  944. # symbols are missing) and would create confusion by making a
  945. # duplicate entry in threadpool_info.
  946. continue
  947. # filename matches a prefix. Now we check if the library has the symbols we
  948. # are looking for. If none of the symbols exists, it's very likely not the
  949. # expected library (e.g. a library having a common prefix with one of the
  950. # our supported libraries). Otherwise, create and store the library
  951. # controller.
  952. lib_controller = controller_class(
  953. filepath=filepath, prefix=prefix, parent=self
  954. )
  955. if filepath in (lib.filepath for lib in self.lib_controllers):
  956. # We already have a controller for this library.
  957. continue
  958. if not hasattr(controller_class, "check_symbols") or any(
  959. hasattr(lib_controller.dynlib, func)
  960. for func in controller_class.check_symbols
  961. ):
  962. self.lib_controllers.append(lib_controller)
  963. def _check_prefix(self, library_basename, filename_prefixes):
  964. """Return the prefix library_basename starts with
  965. Return None if none matches.
  966. """
  967. for prefix in filename_prefixes:
  968. if library_basename.startswith(prefix):
  969. return prefix
  970. return None
  971. def _warn_if_incompatible_openmp(self):
  972. """Raise a warning if llvm-OpenMP and intel-OpenMP are both loaded"""
  973. prefixes = [lib_controller.prefix for lib_controller in self.lib_controllers]
  974. msg = textwrap.dedent(
  975. """
  976. Found Intel OpenMP ('libiomp') and LLVM OpenMP ('libomp') loaded at
  977. the same time. Both libraries are known to be incompatible and this
  978. can cause random crashes or deadlocks on Linux when loaded in the
  979. same Python program.
  980. Using threadpoolctl may cause crashes or deadlocks. For more
  981. information and possible workarounds, please see
  982. https://github.com/joblib/threadpoolctl/blob/master/multiple_openmp.md
  983. """
  984. )
  985. if "libomp" in prefixes and "libiomp" in prefixes:
  986. warnings.warn(msg, RuntimeWarning)
  987. @classmethod
  988. def _get_libc(cls):
  989. """Load the lib-C for unix systems."""
  990. libc = cls._system_libraries.get("libc")
  991. if libc is None:
  992. # Remark: If libc is statically linked or if Python is linked against an
  993. # alternative implementation of libc like musl, find_library will return
  994. # None and CDLL will load the main program itself which should contain the
  995. # libc symbols. We still name it libc for convenience.
  996. # If the main program does not contain the libc symbols, it's ok because
  997. # we check their presence later anyway.
  998. libc = ctypes.CDLL(find_library("c"), mode=_RTLD_NOLOAD)
  999. cls._system_libraries["libc"] = libc
  1000. return libc
  1001. @classmethod
  1002. def _get_windll(cls, dll_name):
  1003. """Load a windows DLL"""
  1004. dll = cls._system_libraries.get(dll_name)
  1005. if dll is None:
  1006. dll = ctypes.WinDLL(f"{dll_name}.dll")
  1007. cls._system_libraries[dll_name] = dll
  1008. return dll
  1009. def _main():
  1010. """Commandline interface to display thread-pool information and exit."""
  1011. import argparse
  1012. import importlib
  1013. import json
  1014. import sys
  1015. parser = argparse.ArgumentParser(
  1016. usage="python -m threadpoolctl -i numpy scipy.linalg xgboost",
  1017. description="Display thread-pool information and exit.",
  1018. )
  1019. parser.add_argument(
  1020. "-i",
  1021. "--import",
  1022. dest="modules",
  1023. nargs="*",
  1024. default=(),
  1025. help="Python modules to import before introspecting thread-pools.",
  1026. )
  1027. parser.add_argument(
  1028. "-c",
  1029. "--command",
  1030. help="a Python statement to execute before introspecting thread-pools.",
  1031. )
  1032. options = parser.parse_args(sys.argv[1:])
  1033. for module in options.modules:
  1034. try:
  1035. importlib.import_module(module, package=None)
  1036. except ImportError:
  1037. print("WARNING: could not import", module, file=sys.stderr)
  1038. if options.command:
  1039. exec(options.command)
  1040. print(json.dumps(threadpool_info(), indent=2))
  1041. if __name__ == "__main__":
  1042. _main()