|
| 1 | +# Copyright Motphys Technology Co., Ltd. 2025, 2026 |
| 2 | +# SPDX-License-Identifier: Apache-2.0 |
| 3 | + |
| 4 | +"""Runtime threading-layer helpers for numba parallel kernels. |
| 5 | +
|
| 6 | +On many-core machines the default OpenMP layer pays a per-region thread-wakeup |
| 7 | +storm (``OMP_WAIT_POLICY=PASSIVE`` parks every worker between calls, and each |
| 8 | +``prange`` region must wake them all before any work starts). For short kernels |
| 9 | +called every environment step this overhead dominates the kernel itself. The |
| 10 | +TBB layer keeps a resident work-stealing pool and does not have this problem. |
| 11 | +
|
| 12 | +The PyPI ``tbb`` wheel installs ``libtbb.so.12`` into ``<venv>/lib`` instead of |
| 13 | +``site-packages``, so numba's plain ``CDLL("libtbb.so.12")`` lookup cannot find |
| 14 | +it without ``LD_LIBRARY_PATH``. Preloading the library by full path with |
| 15 | +``RTLD_GLOBAL`` registers its SONAME in the process, and numba's later lookup by |
| 16 | +the same SONAME reuses the loaded handle. |
| 17 | +""" |
| 18 | + |
| 19 | +from __future__ import annotations |
| 20 | + |
| 21 | +import ctypes |
| 22 | +import glob |
| 23 | +import sys |
| 24 | +from pathlib import Path |
| 25 | + |
| 26 | +_TBB_SONAME = "libtbb.so.12" |
| 27 | +_tbb_preload_result: bool | None = None |
| 28 | + |
| 29 | + |
| 30 | +def preload_tbb() -> bool: |
| 31 | + """Preload ``libtbb.so.12`` from the active environment, if present. |
| 32 | +
|
| 33 | + Returns ``True`` when the library was loaded (or was already loaded), which |
| 34 | + lets numba select the TBB threading layer for parallel kernels. Returns |
| 35 | + ``False`` when the ``tbb`` extra is not installed — callers keep the numba |
| 36 | + default layer in that case. The probe runs once and is cached: every |
| 37 | + ``ManagerEnv`` construction calls this, and the glob + CDLL work should |
| 38 | + not repeat per instance. |
| 39 | + """ |
| 40 | + global _tbb_preload_result |
| 41 | + if _tbb_preload_result is None: |
| 42 | + _tbb_preload_result = _probe_tbb() |
| 43 | + return _tbb_preload_result |
| 44 | + |
| 45 | + |
| 46 | +def _probe_tbb() -> bool: |
| 47 | + if not sys.platform.startswith("linux"): |
| 48 | + return False |
| 49 | + candidates = sorted(glob.glob(str(Path(sys.prefix) / "lib" / f"{_TBB_SONAME}*")), reverse=True) |
| 50 | + for path in candidates: |
| 51 | + try: |
| 52 | + ctypes.CDLL(path, mode=ctypes.RTLD_GLOBAL) |
| 53 | + except OSError: |
| 54 | + continue |
| 55 | + return True |
| 56 | + return False |
| 57 | + |
| 58 | + |
| 59 | +__all__ = ["preload_tbb"] |
0 commit comments