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
feat(threading): implement default thread policy for GPU models
myhloli3c60e6f03880
diff --git a/mineru/kit/vlm_server/llama_cpp_server.py b/mineru/kit/vlm_server/llama_cpp_server.pyindex 59d882c6..715b255a 100644--- a/mineru/kit/vlm_server/llama_cpp_server.py+++ b/mineru/kit/vlm_server/llama_cpp_server.py@@ -18,7 +18,7 @@ import typingfrom pathlib import Pathfrom ...model.registry import vlm_model_repo-from ...model.runtime.llama_device import LlamaSelection, resolve_llama_device+from ...model.runtime.llama_device import DEFAULT_GPU_THREADS, LlamaSelection, default_llama_threads, resolve_llama_deviceDEFAULT_PORT = "30000"DEFAULT_N_GPU_LAYERS = 99@@ -58,6 +58,7 @@ MODEL_SOURCE_ENV = (PROJECTOR_SELECTOR_FLAGS = ("-mm", "--mmproj", "-mmu", "--mmproj-url")PROJECTOR_SOURCE_ENV = ("LLAMA_ARG_MMPROJ", "LLAMA_ARG_MMPROJ_URL")PARALLEL_FLAGS = ("-np", "--parallel")+THREAD_FLAGS = ("-t", "--threads")# router 模式的模型来源(llama-server 未指定模型时按目录/预设自组路由):# 视为用户已提供模型,注入默认 -m 会关掉 router 模式并强制下载官方模型。ROUTER_SOURCE_FLAGS = ("--models-dir", "--models-preset")@@ -268,6 +269,20 @@ def _apply_device_policy(args: list[str], selection: LlamaSelection) -> None:args.append("--mmproj-offload")+def _apply_thread_policy(args: list[str], selection: LlamaSelection) -> None:+ """仅补 GPU 主模型的生成线程数,批处理默认继承;用户 CLI/env 优先。"""+ if _has_arg(args, *THREAD_FLAGS) or _has_env("LLAMA_ARG_THREADS"):+ return+ threads = default_llama_threads(selection)+ if selection.reason == "explicit_projector":+ # _apply_device_policy 已把 CPU 主模型的各种显式选择规范化为 ngl=0。+ # CPU 主模型 + GPU 投影仍保留主模型的自动线程数。+ if _flag_value(args, "--n-gpu-layers", "-ngl", "--gpu-layers") != "0":+ threads = DEFAULT_GPU_THREADS+ if threads is not None:+ args.extend(["--threads", str(threads)])++def main() -> None:args = sys.argv[1:]@@ -337,6 +352,7 @@ def main() -> None:# ---- 对齐 EngineCore::EngineCore 写死的 common_params(用户 CLI 或环境变量设定时逐项让位)----selection = _device_policy(args)_apply_device_policy(args, selection)+ _apply_thread_policy(args, selection)user_defined_parallel = _has_arg(args, *PARALLEL_FLAGS) or _has_env("LLAMA_ARG_N_PARALLEL")user_defined_ctx = _has_arg(args, "-c", "--ctx-size") or _has_env("LLAMA_ARG_CTX_SIZE")if not user_defined_parallel:diff --git a/mineru/model/runtime/llama_device.py b/mineru/model/runtime/llama_device.pyindex 307740c1..3c6a0ced 100644--- a/mineru/model/runtime/llama_device.py+++ b/mineru/model/runtime/llama_device.py@@ -17,6 +17,7 @@ from .intel_gpu import INTEL_VENDOR_ID, intel_architecturefrom .vulkan import vulkan_environment_lockSERIALIZE_ENV = "GGML_VK_SERIALIZE_SUBMISSIONS"+DEFAULT_GPU_THREADS = 4_lock = threading.RLock()_runtime_environment: tuple[int, tuple[tuple[str, str | None], ...]] | None = None_BACKEND_ENV = (@@ -39,6 +40,13 @@ class LlamaSelection:environment: tuple[tuple[str, str], ...] = ()+def default_llama_threads(selection: LlamaSelection) -> int | None:+ """GPU 减少 CPU 线程开销;CPU 和未决原生路由保留 llama.cpp 的自动计算。"""+ if selection.device == "gpu" or selection.reason == "explicit_gpu":+ return DEFAULT_GPU_THREADS+ return None++def resolve_llama_device(*,n_gpu_layers: int | None = None,@@ -120,4 +128,4 @@ def llama_engine_scope(selection: LlamaSelection) -> Iterator[None]:os.environ[name] = value-__all__ = ["LlamaSelection", "llama_engine_scope", "resolve_llama_device"]+__all__ = ["DEFAULT_GPU_THREADS", "LlamaSelection", "default_llama_threads", "llama_engine_scope", "resolve_llama_device"]diff --git a/mineru/model/vlm/runtime.py b/mineru/model/vlm/runtime.pyindex c74cff8b..f377b798 100644--- a/mineru/model/vlm/runtime.py+++ b/mineru/model/vlm/runtime.py@@ -273,17 +273,20 @@ class ModelSingleton:# Engine-specific kwargs are pulled out of **kwargs so they# are not forwarded to MinerUClient (which doesn't accept- # them). Defaults mirror Engine's own constructor defaults.+ # them). CPU threads default to 4 on GPU, otherwise Engine's auto.engine_kwargs = {}for key in ("n_ctx_seq", "n_gpu_layers", "n_parallel", "verbosity", "n_threads"):if key in kwargs:engine_kwargs[key] = kwargs.pop(key)- from ..runtime.llama_device import llama_engine_scope, resolve_llama_device+ from ..runtime.llama_device import default_llama_threads, llama_engine_scope, resolve_llama_deviceselection = resolve_llama_device(n_gpu_layers=engine_kwargs.get("n_gpu_layers"))if selection.device == "cpu":engine_kwargs["n_gpu_layers"] = 0+ default_threads = default_llama_threads(selection)+ if default_threads is not None:+ engine_kwargs.setdefault("n_threads", default_threads)try:from mineru_llama_cpp import Engineexcept ImportError:diff --git a/tests/unittest/test_llama_device_policy.py b/tests/unittest/test_llama_device_policy.pyindex 9b0d1b5e..3f0b0dd9 100644--- a/tests/unittest/test_llama_device_policy.py+++ b/tests/unittest/test_llama_device_policy.py@@ -201,8 +201,9 @@ def test_environment_restored_and_cached_vulkan_setting_cannot_change() -> None:"chip,forced,calibrated_gpu",[(0x4680, False, False), (0x4680, True, False), (0x7D51, False, False), (0x7D51, True, False), (0x7D51, False, True)],)[email protected]("threads", [None, -1, 6])def test_real_model_factory_applies_plan_at_engine_construction(- monkeypatch: pytest.MonkeyPatch, tmp_path: Path, chip: int, forced: bool, calibrated_gpu: bool+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, chip: int, forced: bool, calibrated_gpu: bool, threads: int | None) -> None:from mineru.model.vlm import runtime@@ -223,10 +224,14 @@ def test_real_model_factory_applies_plan_at_engine_construction(runtime, "vlm_model_repo", lambda name: SimpleNamespace(paths={"main": "main.gguf", "mmproj": "mmproj.gguf"}))monkeypatch.setattr(runtime, "MinerUClient", lambda **kwargs: SimpleNamespace())- runtime.ModelSingleton()._create_model("llama-cpp-engine", str(tmp_path), None, **({"n_gpu_layers": 99} if forced else {}))+ options = {"n_gpu_layers": 99} if forced else {}+ if threads is not None:+ options["n_threads"] = threads+ runtime.ModelSingleton()._create_model("llama-cpp-engine", str(tmp_path), None, **options)kwargs, serialize, backend = captured[0]use_gpu = forced or calibrated_gpuassert kwargs.get("n_gpu_layers") == (99 if forced else None if use_gpu else 0)+ assert kwargs.get("n_threads") == (threads if threads is not None else 4 if use_gpu else None)assert serialize == ("1" if calibrated_gpu and not forced else None)assert backend == (None if use_gpu else "cpu")assert policy.SERIALIZE_ENV not in os.environ and "MINERU_LLAMA_CPP_BACKEND" not in os.environdiff --git a/tests/unittest/test_llama_server_device_policy.py b/tests/unittest/test_llama_server_device_policy.pyindex 4f5feef1..6fae0537 100644--- a/tests/unittest/test_llama_server_device_policy.py+++ b/tests/unittest/test_llama_server_device_policy.py@@ -29,6 +29,8 @@ def isolated(monkeypatch: pytest.MonkeyPatch) -> None:"MTMD_BACKEND_DEVICE","LLAMA_ARG_MMPROJ_OFFLOAD","LLAMA_ARG_OFFLINE",+ "LLAMA_ARG_THREADS",+ "LLAMA_ARG_THREADS_BATCH",):monkeypatch.delenv(name, raising=False)forbidden = Mock(side_effect=AssertionError("server must not probe llama devices"))@@ -86,13 +88,16 @@ def test_explicit_projector_preserves_native_names_and_mixed_routing(selected = server._device_policy(args)assert selected.device == "native" and not selected.environmentserver._apply_device_policy(args, selected)+ server._apply_thread_policy(args, selected)assert (server._flag_value(args, "--mmproj-device") or os.environ.get("MTMD_BACKEND_DEVICE")) == "Vulkan9"assert "--mmproj-offload" in argsif cpu_model:assert server._flag_value(args, "--n-gpu-layers", "-ngl") == "0"assert "--no-op-offload" in args+ assert "--threads" not in argselse:assert server._flag_value(args, "--device") == "Vulkan1"+ assert server._flag_value(args, "--threads") == "4"select.assert_not_called()@@ -178,3 +183,57 @@ def test_server_main_applies_automatic_mode_before_gpu_defaults(monkeypatch: pytassert server._flag_value(args, "--n-gpu-layers") == ("0" if decision == "cpu" else "99")assert ("--no-mmproj-offload" in args) is (decision == "cpu")assert ("--no-op-offload" in args) is (decision == "cpu")+ assert server._flag_value(args, "--threads") == (None if decision == "cpu" else "4")++[email protected]("source", ["short", "long", "inline", "env"])[email protected]("threads", ["6", "-1"])+def test_explicit_threads_override_gpu_default(monkeypatch: pytest.MonkeyPatch, source: str, threads: str) -> None:+ args = {+ "short": ["-t", threads],+ "long": ["--threads", threads],+ "inline": [f"--threads={threads}"],+ "env": [],+ }[source]+ if source == "env":+ monkeypatch.setenv("LLAMA_ARG_THREADS", threads)+ original = list(args)+ server._apply_thread_policy(args, LlamaSelection("gpu"))+ assert args == original++[email protected]("source", ["cli", "env"])+def test_batch_threads_remain_independent(monkeypatch: pytest.MonkeyPatch, source: str) -> None:+ args = ["--threads-batch", "8"] if source == "cli" else []+ if source == "env":+ monkeypatch.setenv("LLAMA_ARG_THREADS_BATCH", "8")+ original = list(args)+ server._apply_thread_policy(args, LlamaSelection("gpu"))+ assert args == [*original, "--threads", "4"]+++ "args,backend,expected",+ [+ (["--device", "Vulkan1"], "auto", "4"),+ (["-ngl", "99"], "auto", "4"),+ ([], "vulkan", "4"),+ ([], "cpu", None),+ (["-ngl", "0"], "auto", None),+ (["--device", "none"], "auto", None),+ ],+)+def test_manual_device_routes_apply_thread_defaults(+ monkeypatch: pytest.MonkeyPatch, args: list[str], backend: str, expected: str | None+) -> None:+ monkeypatch.setenv("MINERU_LLAMA_CPP_BACKEND", backend)+ selected = server._device_policy(args)+ server._apply_device_policy(args, selected)+ server._apply_thread_policy(args, selected)+ assert server._flag_value(args, "--threads") == expected+++def test_unresolved_native_route_retains_native_thread_default() -> None:+ args: list[str] = []+ server._apply_thread_policy(args, LlamaSelection(reason="platform_native"))+ assert not args