Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio: make OpenBLAS thread limits work on Windows ROCm, and default numpy to up to 8 threads instead of 1 (#13048)

Daniel Hand825aaf57d6e
diff --git a/studio/backend/core/inference/worker.py b/studio/backend/core/inference/worker.py
index 8e6e0f54dcf..9349cb1963c 100644
--- a/studio/backend/core/inference/worker.py
+++ b/studio/backend/core/inference/worker.py
@@ -36,7 +36,8 @@ from core.inference.audio_errors import (
from core.inference.context_refusal import ContextBudgetExceeded
from utils.hardware import apply_gpu_ids, is_apple_silicon
-# Fresh spawned interpreter: re-apply the process-wide network injections.
+# Fresh spawned interpreter: re-apply the process-wide network injections and CPU thread caps.
+from utils.cpu_threads import install_openblas_runtime_cap
from utils.native_tls import activate_native_tls
from utils.happy_eyeballs import activate_happy_eyeballs
@@ -146,6 +147,7 @@ def narrow_load_reason(cmd: dict) -> Optional[str]:
activate_native_tls()
activate_happy_eyeballs()
+install_openblas_runtime_cap()
_SHARE_OBJECT_MAX_BYTES = 1 << 20
_SHARE_OBJECT_ERROR_SIZE = -1
diff --git a/studio/backend/core/training/worker.py b/studio/backend/core/training/worker.py
index 909daf0c753..02fffb92f62 100644
--- a/studio/backend/core/training/worker.py
+++ b/studio/backend/core/training/worker.py
@@ -43,12 +43,14 @@ if sys.platform.startswith("linux") and "HSA_ENABLE_DXG_DETECTION" not in os.env
logger = get_logger(__name__)
from utils.child_stdio import utf8_child_env
-# Fresh spawned interpreter: re-apply the process-wide network injections.
+# Fresh spawned interpreter: re-apply the process-wide network injections and CPU thread caps.
+from utils.cpu_threads import install_openblas_runtime_cap
from utils.native_tls import activate_native_tls
from utils.happy_eyeballs import activate_happy_eyeballs
activate_native_tls()
activate_happy_eyeballs()
+install_openblas_runtime_cap()
from utils.hardware import apply_gpu_ids
from utils.hf_dataset_options import hf_dataset_split_instruction_names
diff --git a/studio/backend/tests/test_cpu_threads.py b/studio/backend/tests/test_cpu_threads.py
index 78cf126bf5b..5092fca93f8 100644
--- a/studio/backend/tests/test_cpu_threads.py
+++ b/studio/backend/tests/test_cpu_threads.py
@@ -11,7 +11,12 @@ from pathlib import Path
import pytest
-from utils.cpu_threads import _THREAD_POOL_ENV_VARS, configure_cpu_threads
+import utils.cpu_threads as cpu_threads
+from utils.cpu_threads import (
+ _THREAD_POOL_ENV_VARS,
+ configure_cpu_threads,
+ default_openblas_threads,
+)
_BACKEND_DIR = Path(__file__).resolve().parent.parent
@@ -51,13 +56,85 @@ def test_cpu_thread_cap_normalises_valid_inputs(raw):
@pytest.mark.parametrize("raw", [None, "", " ", "\t"])
-def test_cpu_thread_cap_unset_limits_only_openblas(raw):
+def test_cpu_thread_cap_unset_limits_only_openblas(raw, monkeypatch):
+ monkeypatch.setattr(cpu_threads, "_usable_cpus", lambda: 32)
+ monkeypatch.setattr(cpu_threads, "_openblas_memory_headroom", lambda: None)
env = {} if raw is None else {"UNSLOTH_CPU_THREADS": raw}
snapshot = dict(env)
configure_cpu_threads(env)
- assert env == {**snapshot, "OPENBLAS_NUM_THREADS": "1"}
+ assert env == {**snapshot, "OPENBLAS_NUM_THREADS": "8"}
+
+
+ "cpus, expected", [(1, 1), (2, 1), (4, 2), (12, 6), (16, 8), (24, 8), (192, 8)]
+)
+def test_openblas_default_scales_with_cores_and_is_capped(cpus, expected, monkeypatch):
+ monkeypatch.setattr(cpu_threads, "_usable_cpus", lambda: cpus)
+ monkeypatch.setattr(cpu_threads, "_openblas_memory_headroom", lambda: None)
+
+ assert default_openblas_threads() == expected
+
+
+ "headroom_mb, expected",
+ [(None, 8), (64 << 10, 8), (2600, 8), (1280, 4), (640, 2), (320, 1), (100, 1), (0, 1)],
+)
+def test_openblas_default_shrinks_when_memory_is_short(headroom_mb, expected, monkeypatch):
+ monkeypatch.setattr(cpu_threads, "_usable_cpus", lambda: 32)
+ monkeypatch.setattr(
+ cpu_threads,
+ "_openblas_memory_headroom",
+ lambda: None if headroom_mb is None else headroom_mb << 20,
+ )
+
+ assert default_openblas_threads() == expected
+
+
+# A process pinned to one CPU of a large host (taskset, Slurm, cpusets) must not get the host's default.
+def test_the_default_follows_the_cpus_this_process_may_use(monkeypatch):
+ monkeypatch.delattr(os, "process_cpu_count", raising = False)
+ monkeypatch.setattr(os, "sched_getaffinity", lambda pid: {3}, raising = False)
+ monkeypatch.setattr(os, "cpu_count", lambda: 192)
+ monkeypatch.setattr(cpu_threads, "_openblas_memory_headroom", lambda: None)
+
+ assert cpu_threads._usable_cpus() == 1
+ assert default_openblas_threads() == 1
+
+
+def test_an_unreadable_memory_reading_keeps_the_core_count_default(monkeypatch):
+ monkeypatch.setattr(cpu_threads, "_usable_cpus", lambda: 32)
+
+ def boom():
+ raise OSError("no reading")
+
+ monkeypatch.setattr(sys, "platform", "linux")
+ monkeypatch.setattr(cpu_threads, "_address_space_headroom", boom)
+
+ assert cpu_threads._openblas_memory_headroom() is None
+ assert default_openblas_threads() == 8
+
+
+ not sys.platform.startswith("linux"), reason = "address-space rlimit is read on Linux"
+)
+def test_linux_reads_the_address_space_rlimit(monkeypatch):
+ import resource
+
+ monkeypatch.setattr(
+ resource, "getrlimit", lambda which: (resource.RLIM_INFINITY, resource.RLIM_INFINITY)
+ )
+ assert cpu_threads._address_space_headroom() is None
+ monkeypatch.setattr(resource, "getrlimit", lambda which: (1 << 40, 1 << 40))
+ assert 0 < cpu_threads._address_space_headroom() < 1 << 40
+
+
[email protected](sys.platform != "win32", reason = "Windows commit and job limits")
+def test_windows_reads_the_free_commit():
+ headroom = cpu_threads._windows_commit_headroom()
+
+ assert headroom is not None and headroom > 0
def test_openblas_default_keeps_user_value():
@@ -69,12 +146,14 @@ def test_openblas_default_keeps_user_value():
@pytest.mark.parametrize("raw", ["", " "])
-def test_openblas_default_replaces_blank_value(raw):
+def test_openblas_default_replaces_blank_value(raw, monkeypatch):
+ monkeypatch.setattr(cpu_threads, "_usable_cpus", lambda: 8)
+ monkeypatch.setattr(cpu_threads, "_openblas_memory_headroom", lambda: None)
env = {"OPENBLAS_NUM_THREADS": raw}
configure_cpu_threads(env)
- assert env == {"OPENBLAS_NUM_THREADS": "1"}
+ assert env == {"OPENBLAS_NUM_THREADS": "4"}
# Anything that is not a positive integer raises a clear ValueError.
diff --git a/studio/backend/tests/test_cpu_threads_openblas_runtime.py b/studio/backend/tests/test_cpu_threads_openblas_runtime.py
new file mode 100644
index 00000000000..25afc7920c3
--- /dev/null
+++ b/studio/backend/tests/test_cpu_threads_openblas_runtime.py
@@ -0,0 +1,328 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Runtime OpenBLAS cap for Windows ROCm (#12942); sys.platform and ctypes' Windows entry points are faked."""
+
+import ctypes
+import os
+import sys
+import types
+
+import pytest
+
+import utils.cpu_threads as cpu_threads
+from utils.cpu_threads import configure_cpu_threads
+
+
+class _FakeSetter:
+ def __init__(self, calls):
+ self.calls = calls
+ self.argtypes = None
+ self.restype = None
+
+ def __call__(self, n):
+ self.calls.append(n)
+
+
+class _FakeLib:
+ def __init__(
+ self,
+ calls,
+ has_setter = True,
+ ):
+ if has_setter:
+ self.openblas_set_num_threads = _FakeSetter(calls)
+
+
+class _Calls(list):
+ loaded: dict
+
+
+def fake_windows(monkeypatch):
+ calls = _Calls()
+ loaded = {"rocm-openblas.dll": 0x1234}
+
+ class _GetModuleHandleW:
+ restype = None
+
+ def __call__(self, name):
+ return loaded.get(name, 0)
+
+ class _Kernel32:
+ def __init__(self):
+ self.GetModuleHandleW = _GetModuleHandleW()
+
+ def fake_windll(name, use_last_error = False):
+ assert name == "kernel32"
+ return _Kernel32()
+
+ def fake_cdll(name, handle = None):
+ assert handle == loaded[name], "must bind the already loaded module, never load a new one"
+ return _FakeLib(calls)
+
+ monkeypatch.setattr(sys, "platform", "win32")
+ # Pinned: the cap clamps to the core count and the default fits free memory.
+ monkeypatch.setattr(os, "cpu_count", lambda: 32)
+ monkeypatch.setattr(cpu_threads, "_usable_cpus", lambda: 32)
+ monkeypatch.setattr(cpu_threads, "_openblas_memory_headroom", lambda: None)
+ monkeypatch.setattr(ctypes, "WinDLL", fake_windll, raising = False)
+ monkeypatch.setattr(ctypes, "CDLL", fake_cdll)
+ # A worker import on real Windows has already installed the hook.
+ monkeypatch.setattr(
+ sys,
+ "meta_path",
+ [
+ finder
+ for finder in sys.meta_path
+ if not getattr(finder, cpu_threads._OPENBLAS_CAP_SENTINEL, False)
+ ],
+ )
+ calls.loaded = loaded
+ return calls
+
+
+def clean_thread_env():
+ """monkeypatch.delenv only restores names that existed."""
+ saved = dict(os.environ)
+ for name in (
+ "UNSLOTH_CPU_THREADS",
+ "OPENBLAS_NUM_THREADS",
+ "OMP_NUM_THREADS",
+ "MKL_NUM_THREADS",
+ "NUMEXPR_NUM_THREADS",
+ "UNSLOTH_OPENBLAS_DEFAULTED",
+ ):
+ os.environ.pop(name, None)
+ yield
+ os.environ.clear()
+ os.environ.update(saved)
+
+
+def _fake_torch(threads):
+ return types.SimpleNamespace(get_num_threads = lambda: threads)
+
+
+# The defect: a user's OPENBLAS_NUM_THREADS never reached the loaded DLL.
+def test_user_openblas_one_reaches_the_dll(fake_windows, clean_thread_env, monkeypatch):
+ monkeypatch.setitem(sys.modules, "torch", _fake_torch(12))
+ monkeypatch.setenv("OPENBLAS_NUM_THREADS", "1")
+
+ configure_cpu_threads()
+
+ assert fake_windows == [1]
+
+
+def test_studio_default_gives_the_dll_torchs_thread_count(
+ fake_windows, clean_thread_env, monkeypatch
+):
+ monkeypatch.setitem(sys.modules, "torch", _fake_torch(12))
+
+ configure_cpu_threads()
+
+ assert os.environ["OPENBLAS_NUM_THREADS"] == "8"
+ assert fake_windows == [12]
+
+
[email protected]("headroom_mb, expected", [(None, 12), (64 << 10, 12), (2560, 2), (500, 1)])
+def test_studio_default_fits_the_dll_to_the_memory_left(
+ fake_windows, clean_thread_env, monkeypatch, headroom_mb, expected
+):
+ monkeypatch.setitem(sys.modules, "torch", _fake_torch(12))
+ monkeypatch.setenv("OPENBLAS_NUM_THREADS", "8")
+ monkeypatch.setenv("UNSLOTH_OPENBLAS_DEFAULTED", "8")
+ monkeypatch.setattr(
+ cpu_threads,
+ "_openblas_memory_headroom",
+ lambda: None if headroom_mb is None else headroom_mb << 20,
+ )
+
+ cpu_threads.apply_openblas_runtime_cap()
+
+ assert fake_windows == [expected]
+
+
+def test_a_user_value_reaches_the_dll_however_short_memory_is(
+ fake_windows, clean_thread_env, monkeypatch
+):
+ monkeypatch.setitem(sys.modules, "torch", _fake_torch(12))
+ monkeypatch.setenv("OPENBLAS_NUM_THREADS", "6")
+ monkeypatch.setattr(cpu_threads, "_openblas_memory_headroom", lambda: 100 << 20)
+
+ cpu_threads.apply_openblas_runtime_cap()
+
+ assert fake_windows == [6]
+
+
+def test_a_worker_inheriting_the_default_gives_the_dll_torchs_thread_count(
+ fake_windows, clean_thread_env, monkeypatch
+):
+ monkeypatch.setitem(sys.modules, "torch", _fake_torch(12))
+ monkeypatch.setenv("OPENBLAS_NUM_THREADS", "8")
+ monkeypatch.setenv("UNSLOTH_OPENBLAS_DEFAULTED", "8")
+
+ assert cpu_threads.install_openblas_runtime_cap()
+
+ assert fake_windows == [12]
+
+
+def test_user_openblas_value_is_what_reaches_the_dll(fake_windows, clean_thread_env, monkeypatch):
+ monkeypatch.setitem(sys.modules, "torch", sys.modules.get("torch") or object())
+ monkeypatch.setenv("OPENBLAS_NUM_THREADS", "6")
+
+ configure_cpu_threads()
+
+ assert fake_windows == [6]
+
+
+def test_unsloth_cpu_threads_reaches_the_dll(fake_windows, clean_thread_env, monkeypatch):
+ monkeypatch.setitem(sys.modules, "torch", sys.modules.get("torch") or object())
+ monkeypatch.setenv("UNSLOTH_CPU_THREADS", "4")
+
+ configure_cpu_threads()
+
+ assert fake_windows == [4]
+
+
+def test_cap_waits_for_torch_and_fires_after_its_module_body(
+ fake_windows, clean_thread_env, monkeypatch, tmp_path
+):
+ package = tmp_path / "torch"
+ package.mkdir()
+ (package / "__init__.py").write_text(
+ "LOADED = True\ndef get_num_threads():\n return 12\n", encoding = "utf-8"
+ )
+ monkeypatch.syspath_prepend(str(tmp_path))
+ monkeypatch.delitem(sys.modules, "torch", raising = False)
+ seen = []
+ real_apply = cpu_threads.apply_openblas_runtime_cap
+
+ def spy():
+ seen.append(getattr(sys.modules.get("torch"), "LOADED", False))
+ return real_apply()
+
+ monkeypatch.setattr(cpu_threads, "apply_openblas_runtime_cap", spy)
+
+ configure_cpu_threads()
+ assert fake_windows == [] and seen == []
+
+ import torch # noqa: F401 -- the fake package above
+
+ assert seen == [True]
+ assert fake_windows == [12]
+
+
+def test_torch_keeps_its_own_loader_and_reload_does_not_stack(
+ fake_windows, clean_thread_env, monkeypatch, tmp_path
+):
+ import importlib.util
+
+ package = tmp_path / "torch"
+ package.mkdir()
+ (package / "__init__.py").write_text(
+ "LOADED = True\ndef get_num_threads():\n return 12\n", encoding = "utf-8"
+ )
+ monkeypatch.syspath_prepend(str(tmp_path))
+ monkeypatch.delitem(sys.modules, "torch", raising = False)
+
+ # e.g. beartype.claw's SourceFileLoader subclass.
+ native = type(importlib.util.find_spec("torch").loader)
+ assert native is not cpu_threads._TorchLoader
+ configure_cpu_threads()
+ import torch
+
+ assert type(torch.__loader__) is native
+ assert torch.__spec__.loader is torch.__loader__
+ importlib.reload(torch)
+ assert type(torch.__loader__) is native
+ assert fake_windows == [12, 12]
+
+
+def test_install_is_idempotent(fake_windows, monkeypatch):
+ monkeypatch.delitem(sys.modules, "torch", raising = False)
+ before = len(sys.meta_path)
+
+ assert cpu_threads.install_openblas_runtime_cap()
+ assert cpu_threads.install_openblas_runtime_cap()
+
+ assert len(sys.meta_path) == before + 1
+
+
+def test_nothing_happens_when_the_dll_is_not_loaded(fake_windows, clean_thread_env, monkeypatch):
+ fake_windows.loaded.clear()
+ monkeypatch.setitem(sys.modules, "torch", sys.modules.get("torch") or object())
+
+ configure_cpu_threads()
+
+ assert fake_windows == []
+
+
[email protected]("raw", ["0", "-2", "abc"])
+def test_invalid_openblas_value_is_not_pushed(fake_windows, clean_thread_env, monkeypatch, raw):
+ monkeypatch.setenv("OPENBLAS_NUM_THREADS", raw)
+
+ assert cpu_threads.apply_openblas_runtime_cap() == []
+ assert fake_windows == []
+
+
+def test_a_failing_setter_never_breaks_startup(fake_windows, clean_thread_env, monkeypatch):
+ raised = []
+
+ def boom(name, handle = None):
+ raised.append(name)
+ raise OSError("bad module")
+
+ monkeypatch.setattr(ctypes, "CDLL", boom)
+ monkeypatch.setitem(sys.modules, "torch", sys.modules.get("torch") or object())
+
+ configure_cpu_threads()
+
+ assert raised == ["rocm-openblas.dll"]
+
+
+def test_cap_is_clamped_to_the_core_count(fake_windows, clean_thread_env, monkeypatch):
+ monkeypatch.setattr(os, "cpu_count", lambda: 8)
+ monkeypatch.setitem(sys.modules, "torch", sys.modules.get("torch") or object())
+ os.environ["OPENBLAS_NUM_THREADS"] = "64"
+
+ configure_cpu_threads()
+
+ assert fake_windows == [8]
+
+
+def test_off_windows_nothing_is_installed(monkeypatch, clean_thread_env):
+ monkeypatch.setattr(sys, "platform", "linux")
+ monkeypatch.setattr(sys, "meta_path", list(sys.meta_path))
+ before = list(sys.meta_path)
+
+ configure_cpu_threads()
+
+ assert sys.meta_path == before
+ assert cpu_threads.apply_openblas_runtime_cap() == []
+
+
+def test_a_mapping_env_stays_pure(fake_windows, monkeypatch):
+ monkeypatch.delitem(sys.modules, "torch", raising = False)
+ before = list(sys.meta_path)
+
+ configure_cpu_threads({})
+
+ assert sys.meta_path == before
+
+
+# Desktop-spawned workers never run run.py, so each worker module installs the cap at import.
[email protected]("worker", ["core/training/worker.py", "core/inference/worker.py"])
+def test_long_lived_workers_install_the_cap_at_import(worker):
+ import ast
+ from pathlib import Path
+
+ tree = ast.parse((Path(__file__).resolve().parent.parent / worker).read_text(encoding = "utf-8"))
+ calls = [
+ node
+ for node in tree.body
+ if isinstance(node, ast.Expr)
+ and isinstance(node.value, ast.Call)
+ and getattr(node.value.func, "id", None) == "install_openblas_runtime_cap"
+ ]
+ assert len(calls) == 1
diff --git a/studio/backend/utils/cpu_threads.py b/studio/backend/utils/cpu_threads.py
index c1998dbce4f..22b348fd542 100644
--- a/studio/backend/utils/cpu_threads.py
+++ b/studio/backend/utils/cpu_threads.py
@@ -3,7 +3,11 @@
"""Early CPU thread-pool configuration for Unsloth processes."""
+import importlib.abc
+import importlib.util
import os
+import sys
+import threading
from typing import MutableMapping, Optional
@@ -13,10 +17,154 @@ _THREAD_POOL_ENV_VARS = (
"OPENBLAS_NUM_THREADS",
"NUMEXPR_NUM_THREADS",
)
+# Every OpenBLAS worker gets its own buffer and a failed allocation kills the process (#12374); past 8 threads
+# numpy gains little on SMT siblings, so the defaults are capped and fitted to the free memory.
+_OPENBLAS_DEFAULT_MAX = 8
+_OPENBLAS_THREAD_COST = 32 << 20 # numpy's buffer
+_OPENBLAS_MEMORY_SHARE = 0.1
+_ROCM_OPENBLAS_THREAD_COST = 128 << 20 # rocm-openblas.dll keeps the stock 128 MB buffer
+
+
+def _threads_that_fit(threads: int, cost: int) -> int:
+ headroom = _openblas_memory_headroom()
+ if headroom is None:
+ return threads
+ return max(1, min(threads, int(headroom * _OPENBLAS_MEMORY_SHARE) // cost))
+
+
+def _usable_cpus() -> int:
+ """CPUs this process may run on: an affinity mask (taskset, Slurm, cpusets) can be far below the host's."""
+ count = getattr(os, "process_cpu_count", None) # 3.13+
+ if count is not None:
+ return count() or 1
+ try:
+ return len(os.sched_getaffinity(0)) or 1
+ except (AttributeError, OSError):
+ return os.cpu_count() or 1
+
+
+def default_openblas_threads() -> int:
+ """About one thread per physical core, at most 8, fewer when memory is short."""
+ threads = max(1, min(_OPENBLAS_DEFAULT_MAX, _usable_cpus() // 2))
+ return _threads_that_fit(threads, _OPENBLAS_THREAD_COST)
+
+
+def _openblas_memory_headroom() -> Optional[int]:
+ """Bytes OpenBLAS's buffers can still claim, None if unbounded. Windows commits them; Linux only reserves them."""
+ try:
+ if sys.platform == "win32":
+ return _windows_commit_headroom()
+ if sys.platform.startswith("linux"):
+ return _address_space_headroom()
+ except Exception: # noqa: BLE001 -- unknown headroom means the core-count default
+ return None
+ return None
+
+
+def _address_space_headroom() -> Optional[int]:
+ import resource
+
+ soft, _ = resource.getrlimit(resource.RLIMIT_AS)
+ if soft == resource.RLIM_INFINITY or soft <= 0:
+ return None
+ with open("/proc/self/statm", encoding = "ascii") as handle:
+ used = int(handle.read().split()[0]) * os.sysconf("SC_PAGE_SIZE")
+ return max(0, soft - used)
+
+
+def _windows_commit_headroom() -> Optional[int]:
+ import ctypes
+ from ctypes import wintypes
+
+ class MemoryStatusEx(ctypes.Structure):
+ _fields_ = [("dwLength", wintypes.DWORD), ("dwMemoryLoad", wintypes.DWORD)] + [
+ (name, ctypes.c_ulonglong)
+ for name in (
+ "ullTotalPhys",
+ "ullAvailPhys",
+ "ullTotalPageFile",
+ "ullAvailPageFile",
+ "ullTotalVirtual",
+ "ullAvailVirtual",
+ "ullAvailExtendedVirtual",
+ )
+ ]
+
+ class BasicLimits(ctypes.Structure):
+ _fields_ = [
+ ("PerProcessUserTimeLimit", ctypes.c_int64),
+ ("PerJobUserTimeLimit", ctypes.c_int64),
+ ("LimitFlags", wintypes.DWORD),
+ ("MinimumWorkingSetSize", ctypes.c_size_t),
+ ("MaximumWorkingSetSize", ctypes.c_size_t),
+ ("ActiveProcessLimit", wintypes.DWORD),
+ ("Affinity", ctypes.c_size_t),
+ ("PriorityClass", wintypes.DWORD),
+ ("SchedulingClass", wintypes.DWORD),
+ ]
+
+ class ExtendedLimits(ctypes.Structure):
+ _fields_ = [
+ ("BasicLimitInformation", BasicLimits),
+ ("IoInfo", ctypes.c_ulonglong * 6),
+ ("ProcessMemoryLimit", ctypes.c_size_t),
+ ("JobMemoryLimit", ctypes.c_size_t),
+ ("PeakProcessMemoryUsed", ctypes.c_size_t),
+ ("PeakJobMemoryUsed", ctypes.c_size_t),
+ ]
+
+ class ProcessMemoryCounters(ctypes.Structure):
+ _fields_ = [("cb", wintypes.DWORD), ("PageFaultCount", wintypes.DWORD)] + [
+ (name, ctypes.c_size_t)
+ for name in (
+ "PeakWorkingSetSize",
+ "WorkingSetSize",
+ "QuotaPeakPagedPoolUsage",
+ "QuotaPagedPoolUsage",
+ "QuotaPeakNonPagedPoolUsage",
+ "QuotaNonPagedPoolUsage",
+ "PagefileUsage",
+ "PeakPagefileUsage",
+ "PrivateUsage",
+ )
+ ]
+
+ kernel32 = ctypes.WinDLL("kernel32", use_last_error = True)
+ status = MemoryStatusEx()
+ status.dwLength = ctypes.sizeof(status)
+ if not kernel32.GlobalMemoryStatusEx(ctypes.byref(status)):
+ return None
+ headroom = int(status.ullAvailPageFile)
+ limits = ExtendedLimits()
+ # 9 = JobObjectExtendedLimitInformation of this process's job; fails outside any job.
+ if kernel32.QueryInformationJobObject(
+ None, 9, ctypes.byref(limits), ctypes.sizeof(limits), None
+ ):
+ flags = limits.BasicLimitInformation.LimitFlags
+ if flags & 0x300: # JOB_OBJECT_LIMIT_PROCESS_MEMORY | JOB_OBJECT_LIMIT_JOB_MEMORY
+ counters = ProcessMemoryCounters()
+ counters.cb = ctypes.sizeof(counters)
+ kernel32.GetCurrentProcess.restype = wintypes.HANDLE
+ kernel32.K32GetProcessMemoryInfo.argtypes = [
+ wintypes.HANDLE,
+ ctypes.c_void_p,
+ wintypes.DWORD,
+ ]
+ used = 0
+ if kernel32.K32GetProcessMemoryInfo(
+ kernel32.GetCurrentProcess(), ctypes.byref(counters), counters.cb
+ ):
+ used = int(counters.PrivateUsage)
+ if flags & 0x100:
+ headroom = min(headroom, max(0, int(limits.ProcessMemoryLimit) - used))
+ if flags & 0x200: # the whole job's commit counts, so its peak, never just this process
+ job_used = max(used, int(limits.PeakJobMemoryUsed))
+ headroom = min(headroom, max(0, int(limits.JobMemoryLimit) - job_used))
+ return headroom
def configure_cpu_threads(env: Optional[MutableMapping[str, str]] = None) -> None:
- """Apply ``UNSLOTH_CPU_THREADS`` to native CPU pools when configured, else cap OpenBLAS at one thread.
+ """Apply ``UNSLOTH_CPU_THREADS`` to native CPU pools when configured, else cap OpenBLAS at a few threads.
Must run before importing libraries that initialize an OpenMP or BLAS
pool. Library-specific vars are left untouched so users can override a
@@ -27,7 +175,13 @@ def configure_cpu_threads(env: Optional[MutableMapping[str, str]] = None) -> Non
if not configured:
# OpenBLAS reads a blank value as 0 (one thread per core), so blank counts as unset.
if not environ.get("OPENBLAS_NUM_THREADS", "").strip():
- environ["OPENBLAS_NUM_THREADS"] = "1"
+ value = str(default_openblas_threads())
+ environ["OPENBLAS_NUM_THREADS"] = value
+ if env is None:
+ # Lets spawned workers tell this default from a user's own value.
+ environ[_OPENBLAS_DEFAULT_MARKER] = value
+ if env is None:
+ install_openblas_runtime_cap()
return
try:
@@ -40,3 +194,141 @@ def configure_cpu_threads(env: Optional[MutableMapping[str, str]] = None) -> Non
value = str(thread_count)
for variable in _THREAD_POOL_ENV_VARS:
environ.setdefault(variable, value)
+ if env is None:
+ install_openblas_runtime_cap()
+
+
+# AMD's Windows ROCm torch wheels ship this OpenBLAS, which ignores OPENBLAS_NUM_THREADS; its runtime setter works (#12942).
+_RUNTIME_CAPPED_OPENBLAS = ("rocm-openblas.dll",)
+_OPENBLAS_CAP_SENTINEL = "_unsloth_openblas_cap_finder"
+_OPENBLAS_DEFAULT_MARKER = "UNSLOTH_OPENBLAS_DEFAULTED"
+
+
+def _torch_thread_count() -> Optional[int]:
+ try:
+ count = int(sys.modules["torch"].get_num_threads())
+ except Exception: # noqa: BLE001
+ return None
+ return count if count >= 1 else None
+
+
+def _openblas_thread_target(environ: Optional[MutableMapping[str, str]] = None) -> Optional[int]:
+ environ = os.environ if environ is None else environ
+ raw = environ.get("OPENBLAS_NUM_THREADS", "").strip()
+ target = None
+ if raw and raw == environ.get(_OPENBLAS_DEFAULT_MARKER):
+ # Studio's default is sized for numpy; this DLL is torch's CPU BLAS, so it gets torch's thread count.
+ target = _torch_thread_count()
+ if target is not None:
+ target = _threads_that_fit(target, _ROCM_OPENBLAS_THREAD_COST)
+ if target is None:
+ try:
+ target = int(raw)
+ except ValueError:
+ return None
+ if target < 1:
+ return None
+ # OpenBLAS clamps an env value to the core count; its runtime setter only to MAX_THREADS.
+ return min(target, os.cpu_count() or target)
+
+
+def apply_openblas_runtime_cap() -> list:
+ """Hand the thread target to an already loaded OpenBLAS that ignores the env; returns the DLLs capped."""
+ if sys.platform != "win32":
+ return []
+ target = _openblas_thread_target()
+ if target is None:
+ return []
+ capped = []
+ try:
+ import ctypes
+
+ # Private handle: argtypes on ctypes.windll's shared one would leak to every caller.
+ get_module = ctypes.WinDLL("kernel32", use_last_error = True).GetModuleHandleW
+ get_module.argtypes = [ctypes.c_wchar_p]
+ get_module.restype = ctypes.c_void_p
+ for name in _RUNTIME_CAPPED_OPENBLAS:
+ handle = get_module(name)
+ if not handle:
+ continue
+ setter = getattr(ctypes.CDLL(name, handle = handle), "openblas_set_num_threads", None)
+ if setter is None:
+ continue
+ setter.argtypes = [ctypes.c_int]
+ setter.restype = None
+ setter(target)
+ capped.append(name)
+ except Exception: # noqa: BLE001 -- a thread cap must never break startup or a torch import
+ return capped
+ return capped
+
+
+class _TorchLoader(importlib.abc.Loader):
+ __slots__ = ("_loader",)
+
+ def __init__(self, loader):
+ self._loader = loader
+
+ def create_module(self, spec):
+ create = getattr(self._loader, "create_module", None)
+ return None if create is None else create(spec)
+
+ def exec_module(self, module):
+ try:
+ self._loader.exec_module(module)
+ finally:
+ # pkg_resources dispatches on the loader's type, and a reload would wrap this wrapper again.
+ spec = getattr(module, "__spec__", None)
+ if spec is not None and spec.loader is self:
+ spec.loader = self._loader
+ if getattr(module, "__loader__", None) is self:
+ module.__loader__ = self._loader
+ apply_openblas_runtime_cap()
+
+ def __getattr__(self, attribute):
+ if attribute == "_loader":
+ raise AttributeError(attribute)
+ return getattr(self._loader, attribute)
+
+
+class _TorchImportFinder(importlib.abc.MetaPathFinder):
+ __slots__ = (_OPENBLAS_CAP_SENTINEL, "_finding")
+
+ def __init__(self):
+ setattr(self, _OPENBLAS_CAP_SENTINEL, True)
+ # Per thread: a bare find_spec("torch") on another thread must not hide the warm thread's import.
+ self._finding = threading.local()
+
+ def find_spec(
+ self,
+ fullname,
+ path = None,
+ target = None,
+ ):
+ if fullname != "torch" or getattr(self._finding, "active", False):
+ return None
+ self._finding.active = True
+ try:
+ # Not caught: a later finder's error must fail the import exactly as without this one.
+ spec = importlib.util.find_spec(fullname)
+ finally:
+ self._finding.active = False
+ if spec is None or spec.loader is None or not hasattr(spec.loader, "exec_module"):
+ return None
+ try:
+ spec.loader = _TorchLoader(spec.loader)
+ except Exception: # noqa: BLE001
+ return None
+ return spec
+
+
+def install_openblas_runtime_cap() -> bool:
+ """Cap now if torch is imported, else right after it is. Windows only; idempotent."""
+ if sys.platform != "win32":
+ return False
+ if "torch" in sys.modules:
+ apply_openblas_runtime_cap()
+ return True
+ if not any(getattr(finder, _OPENBLAS_CAP_SENTINEL, False) for finder in sys.meta_path):
+ sys.meta_path.insert(0, _TorchImportFinder())
+ return True