Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

perf(memory): give numpy and scipy one BLAS thread instead of one per core (#580)

Ruben Lütke262e2ed8be47
diff --git a/jarvis/__init__.py b/jarvis/__init__.py
index 358b3b0cf1..37eb8c8afe 100644
--- a/jarvis/__init__.py
+++ b/jarvis/__init__.py
@@ -9,3 +9,11 @@ from jarvis.core.shared_tls import install_when_imported as _install_shared_tls
_install_shared_tls()
del _install_shared_tls
+
+# numpy and scipy each start one BLAS thread per CPU core and commit 32 MB for
+# every one (~1 GB per process on a 16-thread Windows box). Cap that pool the
+# moment either package is first imported; nothing is loaded here.
+from jarvis.core.blas_threads import install_when_imported as _install_blas_cap # noqa: E402
+
+_install_blas_cap()
+del _install_blas_cap
diff --git a/jarvis/core/blas_threads.py b/jarvis/core/blas_threads.py
new file mode 100644
index 0000000000..4aa546be94
--- /dev/null
+++ b/jarvis/core/blas_threads.py
@@ -0,0 +1,145 @@
+"""One BLAS thread per process instead of one per CPU core (Windows).
+
+The numpy and the scipy wheel each bundle their own OpenBLAS. The moment such a
+copy is loaded it starts one worker thread per logical CPU and commits a 32 MB
+scratch buffer for every one of them. Windows charges committed memory against
+the page file whether or not a page is ever touched, so the bill grows with the
+core count. Measured on a 16-thread box (numpy 2.1, scipy 1.18):
+
+* ``import numpy`` 9 MB -> 500 MB committed
+* ``+ import scipy.signal`` -> 1,070 MB committed
+
+The desktop app pays that in every process that touches audio: the backend,
+both dictation engine workers and the screen-recording standby worker, about
+3 GB together, for threads nothing here uses. The app's own array work is audio
+buffers and mel filters, far below the size where OpenBLAS threads at all. A
+single-threaded pool is also the faster one on a busy machine: 16 spinning
+BLAS workers fighting other processes for cores took 4.7 s for an 800 x 800
+inversion that one thread finished in 51 ms.
+
+OpenBLAS reads ``OPENBLAS_NUM_THREADS`` exactly once, while its DLL loads.
+Setting the variable for the whole process would hand it to every child too,
+and the terminal panes run the user's own programs: their numpy must keep all
+of its cores. So the variable exists only for the instant the DLL loads:
+:func:`preload` sets it, loads the bundled OpenBLAS by path, and removes it
+again. The later ``import numpy`` finds the library already in the process and
+keeps the pool it was started with. A child spawned from another thread inside
+that load (about a millisecond) would inherit the cap; that window is accepted.
+
+:func:`install_when_imported` wires this in without importing either package:
+a ``sys.meta_path`` finder runs the preload right before the first
+``import numpy`` / ``import scipy``. ``jarvis/__init__.py`` calls it, so every
+process of the app gets it. A value the user set themselves is left alone.
+
+Windows only. Linux and macOS do not charge untouched allocations, so the same
+buffers cost nothing there and the pool is left as the wheel configures it.
+"""
+
+from __future__ import annotations
+
+import os
+import sys
+from typing import TYPE_CHECKING, Any, Final
+
+if TYPE_CHECKING: # pragma: no cover - typing only
+ from collections.abc import Callable
+ from pathlib import Path
+
+#: Read by OpenBLAS once, at DLL load. Wins over GOTO_/OMP_NUM_THREADS.
+THREADS_ENV: Final[str] = "OPENBLAS_NUM_THREADS"
+_THREADS: Final[str] = "1"
+#: Packages whose wheel ships a private OpenBLAS in ``<package>.libs``.
+_PACKAGES: Final[frozenset[str]] = frozenset({"numpy", "scipy"})
+
+
+def blas_libraries(package: str) -> list[Path]:
+ """The OpenBLAS DLLs bundled with ``package``, without importing it.
+
+ Empty for a build that brings no private OpenBLAS (a conda numpy on MKL, a
+ system BLAS): there is nothing to cap then.
+ """
+ from importlib.machinery import PathFinder
+ from pathlib import Path
+
+ spec = PathFinder.find_spec(package)
+ origin = getattr(spec, "origin", None)
+ if not origin:
+ return []
+ libs = Path(origin).parent.parent / f"{package}.libs"
+ if not libs.is_dir():
+ return []
+ return sorted(libs.glob("*openblas*.dll"))
+
+
+def _load_library(path: str) -> None:
+ import ctypes
+
+ # Never freed: the handle keeps the library, and so its thread pool, alive
+ # until the package's own extension modules bind to it.
+ ctypes.WinDLL(path) # type: ignore[attr-defined]
+
+
+def preload(package: str, *, load: Callable[[str], Any] | None = None) -> bool:
+ """Load ``package``'s OpenBLAS with a one-thread pool; ``True`` if it did.
+
+ Never raises: this is an optimisation in front of an import, and a wheel
+ laid out differently must import exactly as it did before.
+ """
+ if THREADS_ENV in os.environ:
+ return False # the user's own setting is not ours to replace
+ try:
+ libraries = blas_libraries(package)
+ if not libraries:
+ return False
+ loader = load or _load_library
+ os.environ[THREADS_ENV] = _THREADS
+ try:
+ for library in libraries:
+ loader(str(library))
+ finally:
+ os.environ.pop(THREADS_ENV, None)
+ except Exception as exc: # noqa: BLE001 - see docstring: must not break the import
+ import logging
+
+ logging.getLogger(__name__).debug(
+ "blas-threads: could not preload the %s BLAS, keeping its default pool: %s",
+ package,
+ exc,
+ )
+ return False
+ return True
+
+
+class _PreloadOnImport:
+ """``sys.meta_path`` finder: cap a package's BLAS right before it loads.
+
+ It never resolves anything itself and stays installed (removing an entry
+ while the import system walks the list would skip the finder behind it);
+ once both packages were seen it is one failed set lookup per import.
+ """
+
+ def __init__(self, preloader: Callable[[str], Any] = preload) -> None:
+ self._pending = set(_PACKAGES)
+ self._preload = preloader
+
+ def find_spec(self, fullname: str, path: Any = None, target: Any = None) -> None:
+ if fullname in self._pending:
+ self._pending.discard(fullname)
+ self._preload(fullname)
+ return None
+
+
+def install_when_imported() -> None:
+ """Arrange the preload for the first ``import numpy`` / ``import scipy``."""
+ if sys.platform != "win32":
+ return
+ if any(isinstance(finder, _PreloadOnImport) for finder in sys.meta_path):
+ return
+ finder = _PreloadOnImport()
+ # A package that is already imported has its pool; only the rest can be capped.
+ finder._pending -= sys.modules.keys() # noqa: SLF001 - own instance
+ if finder._pending: # noqa: SLF001
+ sys.meta_path.insert(0, finder)
+
+
+__all__ = ["THREADS_ENV", "blas_libraries", "install_when_imported", "preload"]
diff --git a/tests/unit/core/test_blas_threads.py b/tests/unit/core/test_blas_threads.py
new file mode 100644
index 0000000000..2691f87e0a
--- /dev/null
+++ b/tests/unit/core/test_blas_threads.py
@@ -0,0 +1,162 @@
+"""The one-thread BLAS pool numpy and scipy get on Windows (jarvis.core.blas_threads)."""
+
+from __future__ import annotations
+
+import os
+import subprocess
+import sys
+from pathlib import Path
+
+import pytest
+
+from jarvis.core import blas_threads
+from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS
+
+REPO_ROOT = Path(__file__).resolve().parents[3]
+
+
[email protected](autouse=True)
+def _no_thread_env(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.delenv(blas_threads.THREADS_ENV, raising=False)
+
+
+def fake_wheel(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
+ """A site directory holding ``fakeblas`` laid out like the numpy wheel."""
+ site = tmp_path / "site"
+ (site / "fakeblas").mkdir(parents=True)
+ (site / "fakeblas" / "__init__.py").write_text("", encoding="utf-8")
+ libs = site / "fakeblas.libs"
+ libs.mkdir()
+ (libs / "libscipy_openblas64_-abc123.dll").write_bytes(b"")
+ (libs / "msvcp140-def456.dll").write_bytes(b"")
+ monkeypatch.syspath_prepend(str(site))
+ return libs
+
+
+def test_finds_the_bundled_openblas_without_importing_the_package(fake_wheel: Path) -> None:
+ found = blas_threads.blas_libraries("fakeblas")
+ assert [path.name for path in found] == ["libscipy_openblas64_-abc123.dll"]
+ assert "fakeblas" not in sys.modules
+
+
+def test_a_package_without_a_private_blas_has_nothing_to_cap(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ (tmp_path / "plainpkg").mkdir()
+ (tmp_path / "plainpkg" / "__init__.py").write_text("", encoding="utf-8")
+ monkeypatch.syspath_prepend(str(tmp_path))
+ assert blas_threads.blas_libraries("plainpkg") == []
+ assert blas_threads.blas_libraries("no_such_package_anywhere") == []
+
+
+def test_the_cap_exists_only_while_the_library_loads(fake_wheel: Path) -> None:
+ seen: list[tuple[str, str | None]] = []
+
+ def load(path: str) -> None:
+ seen.append((Path(path).name, os.environ.get(blas_threads.THREADS_ENV)))
+
+ assert blas_threads.preload("fakeblas", load=load) is True
+ assert seen == [("libscipy_openblas64_-abc123.dll", "1")]
+ # Children spawned afterwards (terminal panes, agents) inherit no cap.
+ assert blas_threads.THREADS_ENV not in os.environ
+
+
+def test_a_thread_count_the_user_set_is_left_alone(
+ fake_wheel: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setenv(blas_threads.THREADS_ENV, "8")
+ loaded: list[str] = []
+ assert blas_threads.preload("fakeblas", load=loaded.append) is False
+ assert loaded == []
+ assert os.environ[blas_threads.THREADS_ENV] == "8"
+
+
+def test_a_library_that_will_not_load_never_breaks_the_import(fake_wheel: Path) -> None:
+ def load(path: str) -> None:
+ raise OSError("not a valid Win32 application")
+
+ assert blas_threads.preload("fakeblas", load=load) is False
+ assert blas_threads.THREADS_ENV not in os.environ
+
+
+def test_the_finder_preloads_each_package_once_and_resolves_nothing() -> None:
+ calls: list[str] = []
+ finder = blas_threads._PreloadOnImport(calls.append)
+ assert finder.find_spec("numpy") is None
+ assert finder.find_spec("numpy") is None
+ assert finder.find_spec("numpy.linalg") is None
+ assert finder.find_spec("scipy") is None
+ assert finder.find_spec("json") is None
+ assert calls == ["numpy", "scipy"]
+
+
+def test_install_is_windows_only_and_idempotent(monkeypatch: pytest.MonkeyPatch) -> None:
+ def installed() -> int:
+ return sum(isinstance(f, blas_threads._PreloadOnImport) for f in sys.meta_path)
+
+ others = [f for f in sys.meta_path if not isinstance(f, blas_threads._PreloadOnImport)]
+ monkeypatch.setattr(sys, "meta_path", others)
+ monkeypatch.setattr(sys, "modules", {k: v for k, v in sys.modules.items() if k != "numpy"})
+
+ monkeypatch.setattr(sys, "platform", "linux")
+ blas_threads.install_when_imported()
+ assert installed() == 0
+
+ monkeypatch.setattr(sys, "platform", "win32")
+ blas_threads.install_when_imported()
+ blas_threads.install_when_imported()
+ assert installed() == 1
+
+
+_PROBE = """
+import ctypes, json, os
+from ctypes import wintypes as w
+import jarvis
+import numpy
+
+SIZES = ("peak_ws", "ws", "qpp", "qp", "qpnp", "qnp", "pagefile", "peak_pagefile", "private")
+
+class Counters(ctypes.Structure):
+ _fields_ = [("cb", w.DWORD), ("faults", w.DWORD)] + [(n, ctypes.c_size_t) for n in SIZES]
+
+kernel32, psapi = ctypes.WinDLL("kernel32"), ctypes.WinDLL("psapi")
+kernel32.GetCurrentProcess.restype = w.HANDLE
+psapi.GetProcessMemoryInfo.argtypes = [w.HANDLE, ctypes.POINTER(Counters), w.DWORD]
+counters = Counters()
+counters.cb = ctypes.sizeof(counters)
+psapi.GetProcessMemoryInfo(kernel32.GetCurrentProcess(), ctypes.byref(counters), counters.cb)
+matrix = numpy.arange(16.0).reshape(4, 4)
+print(json.dumps({
+ "private_mb": counters.private / 2**20,
+ "leaked": "OPENBLAS_NUM_THREADS" in os.environ,
+ "trace": float((matrix @ matrix).trace()),
+}))
+"""
+
+
[email protected](sys.platform != "win32", reason="commit charge is a Windows cost")
+def test_a_real_numpy_import_commits_one_buffer_not_one_per_core() -> None:
+ pytest.importorskip("numpy")
+ if not blas_threads.blas_libraries("numpy"):
+ pytest.skip("this numpy brings no private OpenBLAS")
+ if (os.cpu_count() or 1) < 4:
+ pytest.skip("too few cores to tell a capped pool from the default")
+ import json
+
+ env = {k: v for k, v in os.environ.items() if k != blas_threads.THREADS_ENV}
+ result = subprocess.run(
+ [sys.executable, "-X", "utf8", "-c", _PROBE],
+ cwd=REPO_ROOT,
+ env=env,
+ capture_output=True,
+ encoding="utf-8",
+ timeout=120,
+ check=True,
+ creationflags=NO_WINDOW_CREATIONFLAGS,
+ )
+ report = json.loads(result.stdout.strip().splitlines()[-1])
+ # Uncapped, four cores already commit 4 x 32 MB on top of the interpreter.
+ assert report["private_mb"] < 100, report
+ assert report["leaked"] is False
+ assert report["trace"] == 1060.0 # BLAS still computes