Transforms complex documents like PDFs and Office docs into LLM-ready markdown/JSON for your Agentic workflows.
Python ai4sciencedocument-analysisdocxextract-datalayout-analysisocrparserpdfpdf-converterpdf-extractor-llmpdf-extractor-pretrainpdf-extractor-ragpdf-parserpptxpythonxlsx
Bound Torch CPU threads at initialization and worker entry; Refs #5477
myhloliae2f957ed422
diff --git a/mineru/model/runtime/cpu_threads.py b/mineru/model/runtime/cpu_threads.pynew file mode 100644index 00000000..555c0076--- /dev/null+++ b/mineru/model/runtime/cpu_threads.py@@ -0,0 +1,75 @@+# Copyright (c) Opendatalab. All rights reserved.+"""在首次 Torch 模型初始化和工作线程执行前限制 CPU 算子线程。"""++from __future__ import annotations++import math+import os+import threading+from pathlib import Path++_lock = threading.RLock()+_threads = threading.local()+_limit: int | None = None+++def effective_cpu_count() -> int:+ """取 CPU 数、进程亲和性和 Linux cgroup 配额的最小有效值。"""+ count = os.cpu_count() or 1+ if hasattr(os, "sched_getaffinity"):+ count = min(count, len(os.sched_getaffinity(0)) or 1)+ for quota_path, period_path in (+ ("/sys/fs/cgroup/cpu.max", None),+ ("/sys/fs/cgroup/cpu/cpu.cfs_quota_us", "/sys/fs/cgroup/cpu/cpu.cfs_period_us"),+ ):+ try:+ values = Path(quota_path).read_text().split()+ quota = int(values[0])+ period = int(Path(period_path).read_text()) if period_path else int(values[1])+ if quota > 0 and period > 0:+ count = min(count, max(1, math.ceil(quota / period)))+ except (OSError, ValueError, IndexError):+ continue+ return max(1, count)+++def _positive_env(name: str) -> int | None:+ """忽略缺失、零和非法线程配置,沿既有配置优先级回退。"""+ try:+ value = int(os.environ.get(name, ""))+ except ValueError:+ return None+ return value if value > 0 else None+++def initialize_torch_threads() -> int:+ """仅在 Torch 模型边界加载 Torch,不调高调用方已有的更低线程数。"""+ global _limit+ import torch++ with _lock:+ if _limit is None:+ explicit = [_positive_env(name) for name in ("OMP_NUM_THREADS", "MKL_NUM_THREADS")]+ configured = (+ min(value for value in explicit if value is not None)+ if any(explicit)+ else (_positive_env("MINERU_CPU_NUM_THREADS") or _positive_env("MINERU_INTRA_OP_NUM_THREADS") or 8)+ )+ torch.init_num_threads()+ _limit = min(configured, effective_cpu_count(), torch.get_num_threads())+ if getattr(_threads, "limit", None) != _limit:+ torch.init_num_threads()+ current = torch.get_num_threads()+ if current > _limit:+ torch.set_num_threads(_limit)+ _threads.limit = _limit+ return min(_limit, torch.get_num_threads())+++def prepare_torch_thread() -> None:+ """把已选线程上限传播到后续线程;纯 ONNX/Flash 路径不会触发 Torch 导入。"""+ if _limit is not None:+ initialize_torch_threads()+++__all__ = ["effective_cpu_count", "initialize_torch_threads", "prepare_torch_thread"]diff --git a/mineru/model/runtime/execution.py b/mineru/model/runtime/execution.pyindex 96f2c75b..9be209e5 100644--- a/mineru/model/runtime/execution.py+++ b/mineru/model/runtime/execution.py@@ -30,6 +30,9 @@ def _device_execution(device: str) -> _DeviceExecution:@contextmanagerdef local_model_stage(device: str) -> Iterator[None]:"""只保护同步本地模型阶段,不能跨越 VLM 等待持有该锁。"""+ from .cpu_threads import prepare_torch_thread++ prepare_torch_thread()with _device_execution(device).lock:yielddiff --git a/mineru/model/runtime/hybrid.py b/mineru/model/runtime/hybrid.pyindex 46bb57f8..79afab51 100644--- a/mineru/model/runtime/hybrid.py+++ b/mineru/model/runtime/hybrid.py@@ -205,6 +205,10 @@ class AtomModelSingleton:def get_atom_model(self, atom_model_name: str, **kwargs: Any) -> Any:"""根据模型名称和关键配置生成缓存键,并获取对应原子模型。"""small_backend = resolve_small_model_backend(kwargs.get("small_backend"))+ if small_backend == "torch":+ from .cpu_threads import initialize_torch_threads++ initialize_torch_threads()device = "cpu" if small_backend == "onnx" else (kwargs.get("device") or get_device())kwargs = {**kwargs, "small_backend": small_backend, "device": device}lang = kwargs.get("lang", None)@@ -239,6 +243,10 @@ class AtomModelSingleton:def atom_model_init(model_name: str, **kwargs: Any) -> Any:"""将原子模型名称分派到具体初始化函数,并校验初始化结果。"""small_backend = resolve_small_model_backend(kwargs.get("small_backend"))+ if small_backend == "torch":+ from .cpu_threads import initialize_torch_threads++ initialize_torch_threads()atom_model = Noneif model_name == AtomicModelName.Layout:if small_backend == "onnx":diff --git a/mineru/model/vlm/runtime.py b/mineru/model/vlm/runtime.pyindex 8e2993fb..1dc23117 100644--- a/mineru/model/vlm/runtime.py+++ b/mineru/model/vlm/runtime.py@@ -180,6 +180,9 @@ class ModelSingleton:llama_cpp_engine = Engine(model_gguf, mmproj_gguf, **engine_kwargs)elif backend == "transformers":+ from ..runtime.cpu_threads import initialize_torch_threads++ initialize_torch_threads()try:from mineru_vl_utils.transformers_loading import (load_transformers_model,diff --git a/tests/unittest/test_torch_cpu_threads.py b/tests/unittest/test_torch_cpu_threads.pynew file mode 100644index 00000000..722b430c--- /dev/null+++ b/tests/unittest/test_torch_cpu_threads.py@@ -0,0 +1,94 @@+"""Torch 线程上限、配置优先级与惰性导入回归。"""++from __future__ import annotations++import subprocess+import sys+import threading+from concurrent.futures import ThreadPoolExecutor+from types import SimpleNamespace++import pytest++from mineru.model.runtime import cpu_threads+++ "env,existing,expected",+ [+ ({}, 32, 8),+ ({"OPENBLAS_NUM_THREADS": "1"}, 32, 8),+ ({"MINERU_CPU_NUM_THREADS": "6"}, 32, 6),+ ({"MINERU_INTRA_OP_NUM_THREADS": "3"}, 32, 3),+ ({"OMP_NUM_THREADS": "2", "MINERU_CPU_NUM_THREADS": "8"}, 32, 2),+ ({"MKL_NUM_THREADS": "4"}, 32, 4),+ ({}, 2, 2),+ ({"MINERU_CPU_NUM_THREADS": "bad"}, 32, 8),+ ({"MINERU_CPU_NUM_THREADS": "100"}, 32, 12),+ ],+)+def test_torch_thread_limits(monkeypatch: pytest.MonkeyPatch, env: dict[str, str], existing: int, expected: int) -> None:+ """显式 OMP/MKL 优先,OpenBLAS 不阻止限制,已有小值和有效 CPU 数受到保护。"""+ for name in (+ "OMP_NUM_THREADS",+ "MKL_NUM_THREADS",+ "OPENBLAS_NUM_THREADS",+ "MINERU_CPU_NUM_THREADS",+ "MINERU_INTRA_OP_NUM_THREADS",+ ):+ monkeypatch.delenv(name, raising=False)+ for name, value in env.items():+ monkeypatch.setenv(name, value)+ monkeypatch.setattr(cpu_threads, "_limit", None)+ monkeypatch.setattr(cpu_threads, "_threads", threading.local())+ monkeypatch.setattr(cpu_threads, "effective_cpu_count", lambda: 12)+ local = threading.local()+ calls: list[int] = []++ def init() -> None:+ """模拟新 OpenMP 工作线程需要显式初始化线程状态。"""+ local.count = getattr(local, "count", existing)+ calls.append(threading.get_ident())++ def set_threads(count: int) -> None:+ """只修改当前模拟工作线程,检测配置是否传播。"""+ local.count = count++ fake = SimpleNamespace(init_num_threads=init, get_num_threads=lambda: local.count, set_num_threads=set_threads)+ monkeypatch.setitem(sys.modules, "torch", fake)+ assert cpu_threads.initialize_torch_threads() == expected+ with ThreadPoolExecutor(max_workers=3) as pool:+ assert pool.submit(cpu_threads.initialize_torch_threads).result() == expected+ assert len(set(calls)) >= 2+++def test_thread_module_import_and_uninitialized_stage_are_light() -> None:+ """未初始化 Torch 的线程执行边界不加载重依赖。"""+ code = """from mineru.model.runtime.cpu_threads import prepare_torch_thread+from mineru.model.runtime.execution import local_model_stage+import sys+prepare_torch_thread()+with local_model_stage("cpu"): pass+assert "torch" not in sys.modules+"""+ subprocess.run([sys.executable, "-c", code], check=True)+++def test_real_torch_thread_pool_propagation() -> None:+ """用独立进程验证实际 PyTorch 的后续线程按首次选定上限执行算子。"""+ code = """import os+os.environ["MINERU_CPU_NUM_THREADS"]="2"+os.environ.pop("OMP_NUM_THREADS",None)+os.environ.pop("MKL_NUM_THREADS",None)+from mineru.model.runtime.cpu_threads import initialize_torch_threads+from concurrent.futures import ThreadPoolExecutor+import torch+initialize_torch_threads()+def run(_):+ initialize_torch_threads()+ assert torch.get_num_threads() <= 2+ return (torch.ones(64,64) @ torch.ones(64,64)).sum().item()+with ThreadPoolExecutor(max_workers=3) as pool:+ assert list(pool.map(run,range(6))) == [262144.0]*6+"""+ subprocess.run([sys.executable, "-c", code], check=True, timeout=60)