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(runtime): unify process device decisions and expose health device
myhlolic3e1c478c79c
diff --git a/docs/next/api/health-models.md b/docs/next/api/health-models.mdindex 41e75d38..bb615952 100644--- a/docs/next/api/health-models.md+++ b/docs/next/api/health-models.md@@ -12,6 +12,16 @@ Python Server 的 features 包含 `webhook=false`、`task_output_formats=["defau`sources=["upload","url"]`。Router 从健康 worker 合并格式和输入类型,没有健康 worker 时返回 503。健康检查不执行完整推理;成功不代表任意输入必定解析成功。+Python Server 已完成设备选型时,附加 `runtime: {"device": "cpu"}` 或+`runtime: {"device": "gpu"}`。该值来自不可变进程快照,表示默认本地推理模式;+gpu 包含 MPS、XPU、NPU 等非 CPU 加速器,不代表每个模型、显式覆盖或远程 VLM 的实际设备。+模型局部 CPU 回退不会改写该模式。++尚未选型时省略 `runtime`,不填充 CPU 占位。显式 tier 的惰性启动可能没有此字段;+自动 tier 在启动时完成选型后即能返回。health 请求本身不探测设备、下载模型或执行校准。+客户端应接受字段缺失,并将其解释为未提供设备信息;旧服务同样可能缺少该字段。+Router 不返回单一 `runtime.device`,因为其健康 worker 可能混合 CPU/GPU,Router 自身设备也不能代表 worker。+模型预加载失败使用 `model_preload_dependency_missing/model_preload_files_missing/model_preload_device_unavailable/model_preload_failed` 等错误码。## GET `/v1/models` 与 `/v1/models/{model}`diff --git a/docs/next/cli/mineru-kit-api-server.md b/docs/next/cli/mineru-kit-api-server.mdindex c605fe2c..d6da43d9 100644--- a/docs/next/cli/mineru-kit-api-server.md+++ b/docs/next/cli/mineru-kit-api-server.md@@ -69,11 +69,11 @@ CPU 数沿用进程可用逻辑核数,考虑亲和性和 Linux cgroup 配额ONNX 分支直接调用现有设备选择入口,不再进行显卡库存初选或显存检查。无论 CPU 核数多少,均在发布服务能力前完成适用选型:GPU 开放全部四档,CPU 按表中核数规则推荐。不受支持平台的 CPU 回退由 ONNX 入口处理,不额外探测 Apple Metal。显式 `--tier` 和 Python 精确集合跳过自动推荐。-推荐与 llama.cpp 自动模式复用相同的小模型设备选择入口,不读取 llama 专用参数,也不增加显卡匹配或独立测速。显存容量未知、偏小或查询失败均不参与推荐;`hardware detect --json` 为兼容保留 `gpu_memory: null`。+推荐、llama.cpp 自动模式和默认模型加载统一复用 `resolve_runtime_device()` 的不可变进程快照,不读取 llama 专用参数,也不增加显卡匹配或独立测速。显存容量未知、偏小或查询失败均不参与推荐;`hardware detect --json` 为兼容保留 `gpu_memory: null`。启动选型继续遵守 `model.onnx_device`:`auto` 才按设备策略决定是否测速,显式或已保存的 `cpu/gpu` 不强制重新校准。Windows 确认的独显,以及 Linux 通过兼容检查、由 Vulkan 唯一识别并配置物理绑定的独显,均跳过 OCR 校准;首次真实 GPU 会话成功后才保存设备偏好。集显或类型无法确认的候选继续按 0.8 阈值测速。需要测速时会按正常模型生命周期准备或下载 OCR rec 权重,并复用已有进程缓存、文件锁、采样阈值及失败回退。下载和模型准备不计入 15 秒校准子进程超时。校准失败或结果不稳定不会阻止后续推荐,但不作为 GPU 胜出证据。-实际 OCR 校准把证据保存在 `<配置文件路径>.onnx-calibration.json`。自动推荐直接采用本次设备结论,历史记录只供诊断,不额外要求有效性能证据。显式或已保存的 `gpu` 只要实际选型为 GPU 就开放全部四档;本次 CPU 或失败结果不会被静态库存覆盖。之后 `/v1/tiers` 在服务生命周期内固定。+实际 OCR 校准把证据保存在 `<配置文件路径>.onnx-calibration.json`。自动推荐直接采用本次设备结论,历史记录只供诊断,不额外要求有效性能证据。显式或已保存的 `gpu` 只要实际选型为 GPU 就开放全部四档;本次 CPU 或失败结果不会被静态库存覆盖。之后 `/v1/tiers` 和默认设备决策在进程生命周期内固定;配置写回不会改变当前模型缓存。远程 VLM 配置不自动扩大推荐上限,也不增加 VLM 性能测试。上述 OCR 选型不要求 `--preload-models`;该参数仍另外控制完整模型或 VLM 客户端的提前初始化。diff --git a/docs/next/cli/mineru-kit-hardware.md b/docs/next/cli/mineru-kit-hardware.mdindex 8efed6d4..c8f4885d 100644--- a/docs/next/cli/mineru-kit-hardware.md+++ b/docs/next/cli/mineru-kit-hardware.md@@ -28,7 +28,7 @@ CPU 计数沿用进程亲和性和 Linux cgroup 配额限制。读取失败回Torch(包括 `small_backend=auto` 最终选择 Torch)使用经过可用性验证的加速设备结论,包括 CUDA/ROCm、MPS、XPU 等。显式 CPU、设备不可用或探测失败时按 CPU 规则推荐,并保留原因与警告。该分支不调用 ONNX 选型、不下载 OCR 校准权重,也不修改 ONNX 配置或校准记录。-ONNX 分支在所有 CPU 核数下调用现有 `resolve_onnx_device()`,复用进程缓存、兼容策略、显式配置和校准。Windows 确认的独显,以及 Linux 通过兼容检查、由 Vulkan 唯一识别并配置物理绑定的独显,保留免 OCR 校准路径。`onnx_device=auto` 下需要测速的候选沿用 0.8 阈值;首次可能准备或下载 OCR rec 模型。下载和派生图准备不计入 15 秒校准 worker 超时。校准失败、超时或不稳定时使用本次 CPU 结果推荐。+统一 `resolve_runtime_device()` 在 ONNX 分支的所有 CPU 核数下完成选型,复用进程快照、兼容策略、显式配置和校准。Windows 确认的独显,以及 Linux 通过兼容检查、由 Vulkan 唯一识别并配置物理绑定的独显,保留免 OCR 校准路径。`onnx_device=auto` 下需要测速的候选沿用 0.8 阈值;首次可能准备或下载 OCR rec 模型。下载和派生图准备不计入 15 秒校准 worker 超时。校准失败、超时或不稳定时使用本次 CPU 结果推荐。`onnx_device=gpu` 无论来自用户配置还是先前自动选型,都不强制测速。实际选中 GPU 就开放全部四档;校准记录缺失、损坏、过期或记录 GPU 较慢均不额外阻止开放。此时推荐原因是 `configured_gpu`,校准状态为 `status=skipped, reason=configured_gpu`。记录摘要仅供诊断,读取失败附带警告,不改变设备和档位结论。`onnx_device=cpu` 及不受支持平台的 ONNX CPU 回退均遵循 CPU 规则;ONNX 分支不额外探测 Apple Metal。@@ -40,6 +40,8 @@ JSON 报告保持 `schema_version=1`,包含 `ceiling`、`pdf_image_tiers`、`d## 环境报告+`effective_config.process_runtime` 只展示报告进程自身已初始化的快照(含 PID);未初始化时 device 和 small_backend 为 null。隔离子进程的 selected_device 是只读候选,不代表正在运行的 API Server 的设备。+`info` 不调用自动推荐或 OCR 校准,不下载、加载模型权重或写配置。运行时导入和原生 GPU 探测使用独立子进程,最多并发 4 项,并与系统信息采集重叠进行;每项子进程启动后最多等待 15 秒。某项失败时继续报告其他信息,并区分未安装、导入失败和超时。默认文本使用英文,先输出系统、Python 和 MinerU 版本,再依次输出 CPU/内存、已安装软件、完成合并的显卡库存、运行时探测、有效配置及设备选择与校准信息。每节完成后立即刷新,重定向到管道时也无需等到整份报告完成。`--json` 仍一次输出完整对象,原有字段和结果顺序保持稳定,`schema_version=1`;ONNX 运行时结果补充 `selected_device`,记录只读选型及原因。diff --git a/docs/next/config.md b/docs/next/config.mdindex 10136d73..cbac73e2 100644--- a/docs/next/config.md+++ b/docs/next/config.md@@ -12,6 +12,7 @@ONNX 小模型新增 `model.onnx_device: auto | cpu | gpu`,环境变量为`MINERU_MODEL_ONNX_DEVICE`。首次实际使用时自动选择并保存,独显优先;+该字段只作为 ONNX 选型输入和持久化偏好;模块间运行设备通过进程快照共享,修改默认设备需重启进程。集显测速、重新选择及 DirectML 厂商预设见 [ONNX 设备选择](onnx-device.md)。配置体系定义 MinerU 如何在不同启动阶段得到最终行为。diff --git a/docs/next/decisions/0036-process-runtime-device.md b/docs/next/decisions/0036-process-runtime-device.mdnew file mode 100644index 00000000..874746bd--- /dev/null+++ b/docs/next/decisions/0036-process-runtime-device.md@@ -0,0 +1,57 @@+# ADR-0036: 进程默认设备决策++状态: Accepted,已实现+日期: 2026-11-09++## 契约++`model.onnx_device` 只作为 ONNX 选型输入及持久化偏好。运行时通过+`resolve_runtime_device()` 获得同一份不可变快照,包含小模型后端、cpu/gpu+模式及完整后端设备描述。gpu 泛指已选定的非 CPU 加速模式。++- 首次正式选型固定进程默认后端与设备;配置及环境变化在新进程生效。+- `cached_runtime_device()` 只读;未初始化或初始化中返回 None,不触发探测。+- 线程共享一次初始化;子进程不继承父进程的快照或初始化锁。+- 初始化入口的下载权限和线程选项仅用于首次选型,不构成多份缓存键。+- 底层 ONNX/Torch 选型不持有正式运行缓存。只读诊断与独立预探测不发布默认决策。+- 正式离线运行可以固定 CPU 回退;后续在线调用也复用该决策,重新选型需要新进程。+- 显式模型后端/设备覆盖只影响对应模型构造,不改写进程默认快照。+- 模型局部回退不修改默认策略。具体 provider、远程 VLM 和局部覆盖不由二值代表。+- 不提供生产环境清空默认决策的接口;模型卸载不清空设备决策。++## 依赖方向++轻量类型 → 底层后端选择 → 统一进程决策 → tier、llama、模型加载、health。+基础小模型后端选择不读取统一决策;校准直接创建显式设备会话,避免递归选型。+模型构造前确定设备,设备选型不获取模型缓存或 llama 引擎锁。++## 迁移清单++| 使用点 | 目标职责 |+|---|---|+| config.py | 配置输入和 ONNX 偏好持久化 |+| onnx_device.py / device.py | 底层选型,保留既有兼容、校准和失败规则 |+| device_state.py | 唯一正式运行缓存、局部模型覆盖 |+| hybrid.py / onnx.py | 消费具体设备,模型缓存不使用配置值 |+| registry.py / parser/tier.py | 已初始化后按稳定后端选择资产与预检依赖,查询不触发选型 |+| tier_recommendation.py / llama_device.py | 消费统一 CPU/GPU 模式 |+| hardware.py / hardware_probe.py / models 命令 | 分开展示配置、探测候选和本进程决策 |+| API health | 只读返回 runtime.device,未初始化时省略 runtime |+| Router health | 不用 Router 自身设备代表 worker;本次不增加单值聚合 |++## 验收++覆盖并发、进程隔离、无副作用查询、配置稳定性、局部覆盖、失败回退及不同入口顺序。+ONNX 校准、独显确认后持久化、Torch 免 ONNX 校准、llama 显式参数和 macOS 原生路由保持原有规则。+验证模型所有权及缓存复用,真实转换检查实际设备与输出。跨平台模拟覆盖与真实设备证据分别记录。++## 实施验证(2026-11-09)++- `.venv4/bin/python -m pytest tests/unittest -q --no-cov`:6027 通过、9 跳过。+- 全量运行后补充资产/依赖与显式上下文边界,相关设备、所有权、模型管理和 health 回归 250 通过。+- 核心变更通过 Ruff;修改文件中的既有检查问题与 HEAD 对比,无新增问题。新增函数均有中文说明。+- macOS 真实 Torch/MPS:`demo/pdfs/demo1.pdf` 第 1 页,Basic 解析成功,模式 gpu,具体设备 mps。+- macOS 真实 ONNX/CPU:同一 PDF 第 2 页,Layout/OCR 会话为 CPUExecutionProvider,Basic 解析成功。+- 两条真实路径均检查 Markdown 正文、JSON 及配置变化后的设备/上下文复用。+- ONNX 第 1 页所需公式权重本地缺失,下载未完成;ONNX 实测范围不包含公式模型。+- Windows DirectML、Linux WebGPU 为模拟回归覆盖,本轮没有相应真实 GPU 设备验证。diff --git a/docs/next/decisions/README.md b/docs/next/decisions/README.mdindex a37b1043..8c1050ad 100644--- a/docs/next/decisions/README.md+++ b/docs/next/decisions/README.md@@ -63,6 +63,7 @@| [ADR-0033](0033-middle-json-inline-spans.md) | Accepted | Middle JSON 2.0 结构化行内 Span || [ADR-0034](0034-tsv-independent-file-suffix.md) | Accepted | TSV 独立文件后缀 || [ADR-0035](0035-doclib-persistent-token.md) | Accepted | Doclib 持久本机凭证(替代 ADR-0021 的无认证策略) |+| [ADR-0036](0036-process-runtime-device.md) | Accepted | 进程默认设备决策与 ONNX 配置边界 |## 模板diff --git a/docs/next/model-assets.md b/docs/next/model-assets.mdindex 627cca90..94797725 100644--- a/docs/next/model-assets.md+++ b/docs/next/model-assets.md@@ -30,11 +30,11 @@ mineru-kit parse input.pdf --tier basic -o output.md````MINERU_MODEL_BASE_DIR` 可指定独立模型根目录。`--small-backend`、`--vlm-engine` 只覆盖当前模型管理命令;解析和服务运行时读取环境变量或配置文件。-Layout、OCR-det/rec、公式主批次和 UNet 通过 `model.onnx_device=auto/cpu/gpu` 共享 Windows DirectML/Linux WebGPU 设备选择。+Layout、OCR-det/rec、公式主批次和 UNet 通过统一进程快照共享 Windows DirectML/Linux WebGPU 设备选择;`model.onnx_device=auto/cpu/gpu` 仅作为 ONNX 选型输入和持久化偏好。环境变量为 `MINERU_MODEL_ONNX_DEVICE`。自动模式复用六图 rec 校准与输出检查;Linux 还执行 Intel 架构策略。其他 ONNX 会话及规定的公式尾批次保持 CPU 路线,具体以日志中的实际 provider 为准。CPU 算子线程读取 `MINERU_INTRA_OP_NUM_THREADS` 和 `MINERU_INTER_OP_NUM_THREADS`,默认 4/1。-llama.cpp 自动模式直接复用小模型后端的 CPU/GPU 结论:ONNX 使用现有 DirectML/WebGPU 选型与缓存,+llama.cpp 自动模式直接复用小模型后端的 CPU/GPU 结论:ONNX 使用进程快照中的 DirectML/WebGPU 具体选型,Torch 使用已验证的加速器可用性。兼容独显优先和集显 OCR 校准由 ONNX 统一处理;不增加 VLM 测速。MinerU 不再枚举 ggml、匹配跨后端身份、过滤显卡或重映射设备名;GPU 模式下由原生引擎选择具体显卡,不要求与 ONNX 同卡。显式后端、GPU 层数、server 设备和投影参数优先,支持主模型 CPU、投影 GPU 的组合。diff --git a/docs/next/onnx-device.md b/docs/next/onnx-device.mdindex d5009568..64cd1d49 100644--- a/docs/next/onnx-device.md+++ b/docs/next/onnx-device.md@@ -114,11 +114,28 @@ Linux 插件缺失、没有可用设备、物理绑定失败、校准超时或要重新测量,将配置改回 `auto` 并重启应用。修改程序阈值也不主动覆盖已保存的选择。+## 进程设备快照++`model.onnx_device` 是选型输入和跨进程保存的偏好,不承担模块间运行状态传递。+自动 tier、llama 自动模式及默认小模型加载统一调用 `resolve_runtime_device()`,+首次选型后固定本进程后端、CPU/GPU 模式及具体设备;配置写回或运行期间修改环境不会创建第二份决策。+模型卸载后再次加载仍复用原决策;修改默认设备需要新进程。++`cached_runtime_device()` 只读,尚未初始化时返回 None,不执行探测或校准。+GPU 泛指非 CPU 加速模式,包括 Torch MPS、XPU、NPU 等;它不保证每个模型或远程 VLM 都在 GPU 上执行。+单个模型回退 CPU、显式设备覆盖和 llama 原生选卡不修改默认快照。+显式模型覆盖通过构造作用域传给嵌套会话,不影响其他线程。++正式离线运行缺少校准权重而采用 CPU 后,该决策也固定到进程结束;后续允许下载不会重新选型。+独立底层预探测和 `hardware info` 不发布正式决策,因此预探测失败不会污染后续正式初始化。+具体契约见 [ADR-0036](decisions/0036-process-runtime-device.md)。++## llama.cpp 自动模式与手动覆盖 {#llama-auto-mode}Windows/Linux 的 Engine 和 `llama-server` 复用同一 CPU/GPU 决策:-- 小模型为 ONNX:使用 `resolve_onnx_device()` 的结果和进程缓存。兼容独显免测速;集显或类型未知按既有 OCR 校准决定。+- 小模型为 ONNX:使用 `resolve_runtime_device()` 快照中的 ONNX 具体选型。兼容独显免测速;集显或类型未知按既有 OCR 校准决定。- 小模型为 Torch:使用已核验的 Torch 加速器可用性,不调用 ONNX、不下载 OCR 校准模型。- CPU:模型、视觉投影均使用 CPU,server 同时关闭额外算子卸载。- GPU:允许原生运行时按默认规则选择显卡;不要求它与 ONNX 使用同一物理卡,不新增 VLM 测速。@@ -147,7 +164,7 @@ GPU 开放全部四档;CPU 至少 12 核开放到 Standard,至少 4 核开| 印章检测 / 表格分类 / SLANet Plus | CPU | CPU |普通文字检测和印章检测在模型入口通过 `ocr_det` / `seal_det` 明确区分。-UNet 与其他模型共享 `model.onnx_device` 的进程内选择,不单独测速;ONNX 栈的 UNet 不受旧 `MINERU_TABLE_DEVICE` 覆盖。+UNet 与其他模型共享 `RuntimeDevice` 中的 ONNX 选型,不单独测速;ONNX 栈的 UNet 不受旧 `MINERU_TABLE_DEVICE` 覆盖。Torch 栈中的表格仍使用其原有 CPU/CUDA 策略。旧实验引擎和实验开关已经移除。| 厂商 | layout | MFR | rec | UNet |diff --git a/mineru/kit/commands/hardware.py b/mineru/kit/commands/hardware.pyindex 1ee3392a..c813fd08 100644--- a/mineru/kit/commands/hardware.py+++ b/mineru/kit/commands/hardware.py@@ -153,7 +153,11 @@ def _render_device_selection(data: dict[str, Any]) -> list[str]:backend = (data["effective_config"].get("resolved") or {}).get("small_backend")probe = next((probe for probe in data["runtimes"] if probe["name"] == backend), None)selection = probe["data"].get("selected_device") if probe and probe["status"] == "ok" else None- lines = ["Device selection and calibration:", f" Small model backend: {_value(backend)}"]+ lines = [+ "Device selection and calibration:",+ " Probe scope: isolated subprocess; not the running server's device state",+ f" Small model backend: {_value(backend)}",+ ]reason = selection.get("reason") if selection else Nonereasons = {"torch_accelerator": "A Torch accelerator is available",diff --git a/mineru/model/ocr/pytorch_paddle.py b/mineru/model/ocr/pytorch_paddle.pyindex 836be732..97d098fe 100644--- a/mineru/model/ocr/pytorch_paddle.py+++ b/mineru/model/ocr/pytorch_paddle.py@@ -11,7 +11,7 @@ from PIL import Image, ImageDrawfrom loguru import loggerfrom ..registry import MINERU_4_MODELS_TORCH-from ..runtime.device import get_device+from ..runtime.device_state import resolve_model_devicefrom .._internal.pytorchocr.infer import pytorchocr_utility as utilityfrom .._internal.pytorchocr.infer.predict_system import TextSystemfrom .geometry import merge_det_boxes, sorted_boxes, update_det_boxes@@ -53,7 +53,7 @@ class PytorchPaddleOCR(TextSystem):self.is_seal = requested_lang in ['seal', 'seal_lite']self.enable_merge_det_boxes = kwargs.get("enable_merge_det_boxes", True)- device = kwargs.get("device") or get_device()+ device = resolve_model_device("torch", kwargs.get("device")).model_devicemodels_config_path = PYTORCHOCR_RESOURCE_DIR / "models_config.yml"with open(models_config_path, encoding='utf-8') as file:config = yaml.safe_load(file)diff --git a/mineru/model/registry.py b/mineru/model/registry.pyindex 384204be..432f2de0 100644--- a/mineru/model/registry.py+++ b/mineru/model/registry.py@@ -100,9 +100,9 @@ _VLM_MODEL_REPOS: dict[str, ModelRepo] = {def small_model_repo(backend: str | None = None) -> ModelRepo:"""独立选择小模型仓库,不读取 VLM 引擎或其权重格式。"""- from .runtime.device import resolve_small_model_backend+ from .runtime.device_state import resolve_model_backend- return _SMALL_MODEL_REPOS[resolve_small_model_backend(backend)]+ return _SMALL_MODEL_REPOS[resolve_model_backend(backend)]def vlm_model_repo(engine: str | None = None) -> ModelRepo:diff --git a/mineru/model/runtime/__init__.py b/mineru/model/runtime/__init__.pyindex 8f3ee9ab..5b34ffec 100644--- a/mineru/model/runtime/__init__.py+++ b/mineru/model/runtime/__init__.py@@ -4,9 +4,14 @@from .contracts import AtomicModelNamefrom .device import get_device, resolve_small_model_backendfrom .memory import clean_memory, get_vram+from .device_types import RuntimeDevice+from .device_state import cached_runtime_device, resolve_runtime_device__all__ = ["AtomicModelName",+ "RuntimeDevice",+ "cached_runtime_device",+ "resolve_runtime_device","clean_memory","get_device","resolve_small_model_backend",diff --git a/mineru/model/runtime/device.py b/mineru/model/runtime/device.pyindex c3ae139d..1b99f9a1 100644--- a/mineru/model/runtime/device.py+++ b/mineru/model/runtime/device.py@@ -4,10 +4,11 @@from __future__ import annotationsimport importlib.util-from dataclasses import dataclassimport osfrom typing import Literal+from .device_types import TorchDeviceSelection+# 通过 getattr(torch, name) 探测可用性的附加加速后端,按优先级排列;xpu 为 Intel GPU 原生后端。PROBE_TORCH_DEVICE_APIS: tuple[str, ...] = ("xpu", "gcu", "musa", "mlu", "sdaa")@@ -54,20 +55,6 @@ def get_device() -> str:TORCH_REQUIRED_MODULES: tuple[str, ...] = ("torch", "torchvision", "transformers", "accelerate", "safetensors")-@dataclass(frozen=True)-class TorchDeviceSelection:- """记录经过可用性检查的 Torch 设备,不包含模型性能结论。"""-- device: str = "cpu"- reason: str = "torch_cpu"- warning: str | None = None-- @property- def accelerated(self) -> bool:- """只有验证成功的非 CPU 设备才允许按加速设备推荐。"""- return self.device.split(":", 1)[0] != "cpu"--def resolve_torch_device() -> TorchDeviceSelection:"""核验显式或自动 Torch 设备,不分配模型或执行校准,也不改写配置。"""try:diff --git a/mineru/model/runtime/device_state.py b/mineru/model/runtime/device_state.pynew file mode 100644index 00000000..9f961c2d--- /dev/null+++ b/mineru/model/runtime/device_state.py@@ -0,0 +1,139 @@+# Copyright (c) Opendatalab. All rights reserved.+"""进程默认设备的一次决策及不影响默认状态的显式模型覆盖。"""++from __future__ import annotations++from collections.abc import Iterator+from contextlib import contextmanager+from contextvars import ContextVar+from dataclasses import dataclass, field+import os+import threading+from typing import Literal++from loguru import logger++from .device_types import RuntimeDevice, TorchDeviceSelection+++@dataclass+class _ProcessState:+ """每个 PID 独立持有初始化锁及完整快照,不使用继承的父进程锁。"""++ lock: threading.RLock = field(default_factory=threading.RLock)+ decision: RuntimeDevice | None = None+ initializing: bool = False+++_states: dict[int, _ProcessState] = {}+_model_device: ContextVar[tuple[int, RuntimeDevice] | None] = ContextVar("mineru_model_device", default=None)+++def cached_runtime_device() -> RuntimeDevice | None:+ """无副作用地读取本进程已发布快照,初始化期间也不阻塞调用者。"""+ state = _states.get(os.getpid())+ return state.decision if state is not None else None+++def resolve_runtime_device(+ *, allow_download: bool = True, intra_op_num_threads: int = 0, inter_op_num_threads: int = 0+) -> RuntimeDevice:+ """首次正式选型后固定整个进程,后续参数和配置变化不重新选型。"""+ from .device import resolve_small_model_backend, resolve_torch_device++ pid = os.getpid()+ state = _states.get(pid)+ if state is None:+ # setdefault 原子地选出同一进程的初始化锁,子进程不会等待父进程持有的锁。+ state = _states.setdefault(pid, _ProcessState())+ with state.lock:+ if state.decision is not None:+ return state.decision+ if state.initializing:+ raise RuntimeError("Recursive runtime device selection")+ state.initializing = True+ try:+ backend = resolve_small_model_backend()+ if backend == "torch":+ selection = resolve_torch_device()+ else:+ from .onnx_device import resolve_onnx_device++ selection = resolve_onnx_device(+ allow_download=allow_download,+ intra_op_num_threads=intra_op_num_threads,+ inter_op_num_threads=inter_op_num_threads,+ )+ state.decision = RuntimeDevice(selection)+ logger.info(+ "Runtime device selected: backend={}, mode={}, reason={}", backend, state.decision.device, selection.reason+ )+ return state.decision+ finally:+ state.initializing = False+++def resolve_model_device(+ backend: str | None = None,+ device: str | None = None,+ *,+ intra_op_num_threads: int = 0,+ inter_op_num_threads: int = 0,+) -> RuntimeDevice:+ """默认模型复用进程决策;显式后端或 Torch 设备覆盖仅作用于当前构造。"""+ from .device import resolve_small_model_backend, resolve_torch_device+ from .onnx_device import resolve_onnx_device++ scoped = _model_device.get()+ current = scoped[1] if scoped is not None and scoped[0] == os.getpid() else cached_runtime_device()+ if backend in (None, "auto"):+ current = current or resolve_runtime_device(+ intra_op_num_threads=intra_op_num_threads, inter_op_num_threads=inter_op_num_threads+ )+ selected = current.backend+ else:+ selected = resolve_small_model_backend(backend)+ if selected == "torch" and device is not None:+ if current is not None and current.backend == "torch" and current.model_device == device:+ return current+ return RuntimeDevice(TorchDeviceSelection(device, "explicit_model_device"))+ if current is not None and current.backend == selected:+ return current+ if current is None and selected == resolve_small_model_backend():+ return resolve_runtime_device(intra_op_num_threads=intra_op_num_threads, inter_op_num_threads=inter_op_num_threads)+ selection = (+ resolve_torch_device()+ if selected == "torch"+ else resolve_onnx_device(intra_op_num_threads=intra_op_num_threads, inter_op_num_threads=inter_op_num_threads)+ )+ return RuntimeDevice(selection)+++def resolve_model_backend(backend: str | None = None) -> Literal["onnx", "torch"]:+ """CPU 专用会话只解析后端,已初始化时复用快照,不为了后端名称启动校准。"""+ from .device import resolve_small_model_backend++ if backend not in (None, "auto"):+ return resolve_small_model_backend(backend)+ scoped = _model_device.get()+ current = scoped[1] if scoped is not None and scoped[0] == os.getpid() else cached_runtime_device()+ return current.backend if current is not None else resolve_small_model_backend()+++@contextmanager+def model_device_scope(decision: RuntimeDevice) -> Iterator[None]:+ """将显式选型传给嵌套模型和会话,不污染其他线程或进程默认决策。"""+ token = _model_device.set((os.getpid(), decision))+ try:+ yield+ finally:+ _model_device.reset(token)+++__all__ = [+ "cached_runtime_device",+ "model_device_scope",+ "resolve_model_backend",+ "resolve_model_device",+ "resolve_runtime_device",+]diff --git a/mineru/model/runtime/device_types.py b/mineru/model/runtime/device_types.pynew file mode 100644index 00000000..f8684c29--- /dev/null+++ b/mineru/model/runtime/device_types.py@@ -0,0 +1,67 @@+# Copyright (c) Opendatalab. All rights reserved.+"""不加载推理后端的设备选型值类型。"""++from __future__ import annotations++from dataclasses import dataclass+from typing import TYPE_CHECKING, Literal++if TYPE_CHECKING:+ from .webgpu import WebGPUDevice+ from .windows_gpu import GpuAdapter+++@dataclass(frozen=True)+class TorchDeviceSelection:+ """记录经过可用性检查的 Torch 设备,不包含模型性能结论。"""++ device: str = "cpu"+ reason: str = "torch_cpu"+ warning: str | None = None++ @property+ def accelerated(self) -> bool:+ """将已验证的非 CPU 设备归为加速模式。"""+ return self.device.split(":", 1)[0] != "cpu"+++@dataclass(frozen=True)+class OnnxSelection:+ """保存 ONNX 具体路由,适配器身份只在本进程有效。"""++ device: Literal["cpu", "gpu"] = "cpu"+ adapter: GpuAdapter | WebGPUDevice | None = None+ reason: str = "cpu"+ backend: Literal["dml", "webgpu"] | None = None+++@dataclass(frozen=True)+class RuntimeDevice:+ """从同一具体选型派生默认后端和 CPU/GPU 模式,避免冗余状态不一致。"""++ selection: OnnxSelection | TorchDeviceSelection++ @property+ def backend(self) -> Literal["onnx", "torch"]:+ """返回具体选型所属的小模型后端。"""+ return "torch" if isinstance(self.selection, TorchDeviceSelection) else "onnx"++ @property+ def device(self) -> Literal["cpu", "gpu"]:+ """统一把 Torch 非 CPU 加速器及 ONNX GPU 路由映射为 gpu。"""+ if isinstance(self.selection, TorchDeviceSelection):+ return "gpu" if self.selection.accelerated else "cpu"+ return self.selection.device++ @property+ def is_cpu(self) -> bool:+ """供策略消费者判断是否采用 CPU 模式。"""+ return self.device == "cpu"++ @property+ def model_device(self) -> str:+ """Torch 使用具体设备字符串,ONNX 的包装层保持 CPU 字符串并单独传递适配器。"""+ return self.selection.device if isinstance(self.selection, TorchDeviceSelection) else "cpu"+++__all__ = ["OnnxSelection", "RuntimeDevice", "TorchDeviceSelection"]diff --git a/mineru/model/runtime/hardware.py b/mineru/model/runtime/hardware.pyindex 3880e6c0..a5b6ff65 100644--- a/mineru/model/runtime/hardware.py+++ b/mineru/model/runtime/hardware.py@@ -77,8 +77,10 @@ def installed_packages() -> list[PackageInfo]:def config_summary() -> dict[str, Any]:"""按白名单输出设备相关配置及来源,远程地址只暴露是否启用。"""from ...config import get_config, get_config_file_path, get_config_source+ from .device_state import cached_runtime_deviceconfig = get_config()+ runtime = cached_runtime_device()fields = {"model.small_backend": config.model.small_backend,"model.onnx_device": config.model.onnx_device,@@ -89,6 +91,11 @@ def config_summary() -> dict[str, Any]:"settings": {key: {"value": value, "source": get_config_source(key)} for key, value in fields.items()},"remote_vlm": {"enabled": bool(config.model.vlm.server_url), "source": get_config_source("model.vlm.server_url")},"environment": {key: os.environ[key] for key in DEVICE_ENVIRONMENT if key in os.environ},+ "process_runtime": {+ "pid": os.getpid(),+ "device": runtime.device if runtime is not None else None,+ "small_backend": runtime.backend if runtime is not None else None,+ },}diff --git a/mineru/model/runtime/hybrid.py b/mineru/model/runtime/hybrid.pyindex 69eb7f49..6de72771 100644--- a/mineru/model/runtime/hybrid.py+++ b/mineru/model/runtime/hybrid.py@@ -36,7 +36,7 @@ if TYPE_CHECKING:from ..mfr.pp_formulanet.predict_formula import FormulaRecognizerfrom ..ocr.pytorch_paddle import PytorchPaddleOCR-from .device import get_device, resolve_small_model_backend+from .device_state import model_device_scope, resolve_model_backend, resolve_model_device, resolve_runtime_deviceLOCAL_MODEL_INIT_LOCK = LOCAL_MODEL_CACHE_LOCK# 这些锁保护 Hybrid medium/high/xhigh 共享的 atom model/native 模型推理调用,避免多线程同时进入同一个模型对象。@@ -219,12 +219,13 @@ class AtomModelSingleton:def get_atom_model(self, atom_model_name: str, **kwargs: Any) -> Any:"""根据模型名称和关键配置生成缓存键,并获取对应原子模型。"""- small_backend = resolve_small_model_backend(kwargs.get("small_backend"))+ decision = resolve_model_device(kwargs.get("small_backend"), kwargs.get("device"))+ small_backend = decision.backendif small_backend == "torch":from .cpu_threads import initialize_torch_threadsinitialize_torch_threads()- device = "cpu" if small_backend == "onnx" else (kwargs.get("device") or get_device())+ device = decision.model_devicekwargs = {**kwargs, "small_backend": small_backend, "device": device}lang = kwargs.get("lang", None)ocr_singleton_lang = normalize_ocr_model_lang(lang)@@ -247,12 +248,14 @@ class AtomModelSingleton:else:key = atom_model_name- key = (small_backend, device, key)- if small_backend == "onnx":- from .onnx_device import resolve_onnx_device+ key = (decision, key)++ def initialize() -> Any:+ """在已确定的设备作用域中创建模型,使嵌套 ONNX 会话复用相同选型。"""+ with model_device_scope(decision):+ return atom_model_init(model_name=atom_model_name, **kwargs)- key = (*key, resolve_onnx_device())- return get_local_model(self._models, key, lambda: atom_model_init(model_name=atom_model_name, **kwargs))+ return get_local_model(self._models, key, initialize)def release_owner(self, owner: RuntimeOwner) -> None:"""释放应用直接持有的原子模型,仍被其它上下文引用的依赖继续保留。"""@@ -262,7 +265,14 @@ class AtomModelSingleton:@stage_timer("model.initialize")def atom_model_init(model_name: str, **kwargs: Any) -> Any:"""将原子模型名称分派到具体初始化函数,并校验初始化结果。"""- small_backend = resolve_small_model_backend(kwargs.get("small_backend"))+ decision = resolve_model_device(kwargs.get("small_backend"), kwargs.get("device"))+ with model_device_scope(decision):+ return _create_atom_model(model_name, **{**kwargs, "small_backend": decision.backend, "device": decision.model_device})+++def _create_atom_model(model_name: str, **kwargs: Any) -> Any:+ """在调用者已固定的设备作用域内执行具体模型构造。"""+ small_backend = kwargs["small_backend"]if small_backend == "torch":from .cpu_threads import initialize_torch_threads@@ -372,13 +382,15 @@ class HybridLocalModelContextSingleton:def get_model(self,) -> HybridLocalModelContext:- """按小模型后端与实际设备缓存上下文,避免切换配置后混用模型。"""- small_backend = resolve_small_model_backend()- device = "cpu" if small_backend == "onnx" else get_device()- from ...config import get_config+ """按进程稳定设备复用上下文,配置写回不创建另一份模型。"""+ decision = resolve_runtime_device()++ def initialize() -> HybridLocalModelContext:+ """在同一设备作用域内创建上下文及其嵌套原子模型。"""+ with model_device_scope(decision):+ return HybridLocalModelContext(device=decision.model_device, small_backend=decision.backend)- key = (small_backend, device, get_config().model.onnx_device if small_backend == "onnx" else None)- return get_local_model(self._models, key, lambda: HybridLocalModelContext(device=device, small_backend=small_backend))+ return get_local_model(self._models, decision, initialize)def release_owner(self, owner: RuntimeOwner) -> None:"""释放应用对上下文的租约,并按依赖关系回收无人持有的原子模型。"""@@ -387,7 +399,7 @@ class HybridLocalModelContextSingleton:def ocr_det_batch_setting() -> bool:"""根据运行设备和 PyTorch 版本确定是否启用 OCR 检测批处理。"""- if resolve_small_model_backend() == "onnx":+ if resolve_model_backend() == "onnx":return Truetry:@@ -418,9 +430,11 @@ class HybridLocalModelContext:) -> None:"""初始化 Hybrid 基础运行时,其他模型在首次访问对应属性时加载。"""self._resource = current_local_resource()- self.small_backend = resolve_small_model_backend(small_backend)- self.device = "cpu" if self.small_backend == "onnx" else (device or get_device())- self.enable_ocr_det_batch = True if self.small_backend == "onnx" else ocr_det_batch_setting()+ self._device_decision = resolve_model_device(small_backend, device)+ self.small_backend = self._device_decision.backend+ self.device = self._device_decision.model_device+ with model_device_scope(self._device_decision):+ self.enable_ocr_det_batch = True if self.small_backend == "onnx" else ocr_det_batch_setting()if str(self.device).startswith("npu"):try:@@ -444,7 +458,7 @@ class HybridLocalModelContext:def _get_atom_model(self, atom_model_name: str, **kwargs: Any) -> Any:"""把惰性模型登记为上下文依赖,复用 cached_property 时无需重复登记应用。"""- with local_resource_scope(self._resource):+ with local_resource_scope(self._resource), model_device_scope(self._device_decision):return self.atom_model_manager.get_atom_model(atom_model_name=atom_model_name, **kwargs)@cached_propertydiff --git a/mineru/model/runtime/llama_device.py b/mineru/model/runtime/llama_device.pyindex 3c6a0ced..15f04887 100644--- a/mineru/model/runtime/llama_device.py+++ b/mineru/model/runtime/llama_device.py@@ -13,6 +13,8 @@ from typing import Literalfrom loguru import logger+from .device_state import resolve_runtime_device+from .device_types import OnnxSelection, TorchDeviceSelectionfrom .intel_gpu import INTEL_VENDOR_ID, intel_architecturefrom .vulkan import vulkan_environment_lock@@ -71,21 +73,18 @@ def _resolve(*, n_gpu_layers: int | None, device_names: tuple[str, ...] | None,if requested != "auto" or n_gpu_layers is not None or device_names is not None:return LlamaSelection(reason="explicit_gpu")- from .device import resolve_small_model_backend, resolve_torch_device-- if resolve_small_model_backend() == "torch":- choice = resolve_torch_device()+ runtime = resolve_runtime_device(allow_download=allow_download)+ choice = runtime.selection+ if isinstance(choice, TorchDeviceSelection):if choice.warning:logger.warning("llama.cpp follows Torch device decision: {}", choice.warning)- return LlamaSelection("gpu" if choice.accelerated else "cpu", reason=choice.reason)-- from .onnx_device import resolve_onnx_device+ return LlamaSelection(runtime.device, reason=choice.reason)- choice = resolve_onnx_device() if allow_download else resolve_onnx_device(allow_download=False)+ assert isinstance(choice, OnnxSelection)adapter = choice.adapterenvironment = ()if (- choice.device == "gpu"+ not runtime.is_cpuand sys.platform == "linux"and choice.backend == "webgpu"and adapter is not None@@ -94,7 +93,7 @@ def _resolve(*, n_gpu_layers: int | None, device_names: tuple[str, ...] | None,and SERIALIZE_ENV not in os.environ):environment = ((SERIALIZE_ENV, "1"),)- return LlamaSelection(choice.device, reason=f"onnx_{choice.reason}", environment=environment)+ return LlamaSelection(runtime.device, reason=f"onnx_{choice.reason}", environment=environment)@contextmanagerdiff --git a/mineru/model/runtime/onnx.py b/mineru/model/runtime/onnx.pyindex e8cfc8f4..ab910b02 100644--- a/mineru/model/runtime/onnx.py+++ b/mineru/model/runtime/onnx.py@@ -11,7 +11,9 @@ from typing import Anyimport onnxruntime as ortfrom loguru import logger-from .onnx_device import OnnxSelection, confirm_gpu_session, metacommands_enabled, resolve_onnx_device+from .onnx_device import confirm_gpu_session, metacommands_enabled+from .device_types import OnnxSelection+from .device_state import resolve_model_backend, resolve_model_devicefrom .windows_gpu import GpuAdapterfrom .webgpu import WEBGPU_PROVIDER, WebGPUDevice, attach_webgpu_provider, execution_lock, webgpu_session_scope@@ -180,10 +182,15 @@ def ort_session(selection_threads = sess_options.intra_op_num_threadsroute = OnnxSelection()if eligible:- route = selection or resolve_onnx_device(- intra_op_num_threads=selection_threads,- inter_op_num_threads=sess_options.inter_op_num_threads if sess_options is not None else 0,+ route = (+ selection+ or resolve_model_device(+ "onnx",+ intra_op_num_threads=selection_threads,+ inter_op_num_threads=sess_options.inter_op_num_threads if sess_options is not None else 0,+ ).selection)+ assert isinstance(route, OnnxSelection)adapter = route.adapter if route.device == "gpu" else Noneif model_kind == "ocr_det" and not isinstance(adapter, WebGPUDevice):adapter = None@@ -225,9 +232,7 @@ def table_ort_session(model_kind: str = "",) -> ort.InferenceSession | DirectMLSession | WebGPUSession:"""ONNX 栈的 UNet 复用统一设备选择;其他表格保留原有 CPU/CUDA 策略。"""- from .device import resolve_small_model_backend-- onnx_backend = resolve_small_model_backend(small_backend) == "onnx"+ onnx_backend = resolve_model_backend(small_backend) == "onnx"unified_unet = onnx_backend and model_kind == "unet"device = "cpu"if not unified_unet:diff --git a/mineru/model/runtime/onnx_device.py b/mineru/model/runtime/onnx_device.pyindex c0eba154..7224c74b 100644--- a/mineru/model/runtime/onnx_device.py+++ b/mineru/model/runtime/onnx_device.py@@ -1,13 +1,10 @@# Copyright (c) Opendatalab. All rights reserved.-"""Process-local ONNX selection, with a single persisted cpu/gpu preference."""+"""ONNX 底层选型与偏好持久化;正式进程缓存由 device_state 负责。"""from __future__ import annotations-from dataclasses import dataclass-import osfrom pathlib import Pathimport sys-import threadingfrom typing import Literalfrom filelock import FileLock@@ -16,6 +13,7 @@ from loguru import loggerfrom .windows_gpu import GpuAdapter, discover_gpus, preferred_gpufrom .webgpu import WebGPUDevice, discover_webgpu_devices, select_webgpu_devicefrom .gpu import is_discrete_gpu+from .device_types import OnnxSelection# Require at least 20% lower GPU inference time; simplified to 0.8 at the user's request.# Evidence: docs/next/onnx-selection-validation.md. Each backend can be calibrated independently.@@ -27,35 +25,6 @@ METACOMMANDS: dict[str, dict[str, bool]] = {}-@dataclass(frozen=True)-class OnnxSelection:- """Immutable actual route. Adapter identity is valid only in this process."""-- device: Literal["cpu", "gpu"] = "cpu"- adapter: GpuAdapter | WebGPUDevice | None = None- reason: str = "cpu"- backend: Literal["dml", "webgpu"] | None = None---_lock = threading.RLock()-_selections: dict[tuple[int, str, str, str, bool], OnnxSelection] = {}---def cached_onnx_device(*, allow_download: bool = True) -> OnnxSelection | None:- """只读查询当前配置的进程内选择,用于区分本次选型与已缓存结果。"""- from ...config import get_config, get_config_file_path, get_config_source-- key = (- os.getpid(),- get_config_file_path(),- get_config().model.onnx_device,- get_config_source("model.onnx_device"),- allow_download,- )- with _lock:- return _selections.get(key)--def metacommands_enabled(vendor: str, model_kind: str) -> bool | None:"""None leaves an unknown vendor on the ORT default."""return METACOMMANDS.get(vendor, {}).get(model_kind)@@ -159,6 +128,7 @@ def _select(def _select_and_save(requested: str, source: str, intra_op_num_threads: int, inter_op_num_threads: int, *, allow_download: bool = True) -> OnnxSelection:+ """在文件锁保护下重读已有偏好,仅保存已完成的自动选型。"""from ...config import read_onnx_device_from_file, update_config_fileif requested == "auto" and source != "env":@@ -175,43 +145,38 @@ def _select_and_save(def resolve_onnx_device(*, intra_op_num_threads: int = 0, inter_op_num_threads: int = 0, allow_download: bool = True) -> OnnxSelection:- """在首次模型使用或 CPU/GPU 候选达标的 API 自动推荐时选型;导入和只读诊断不调用。"""+ """执行一次底层选型并保留持久化规则,不读取或发布进程默认设备快照。"""from ...config import get_config, get_config_file_path, get_config_sourcerequested = get_config().model.onnx_devicesource = get_config_source("model.onnx_device")path = get_config_file_path()- key = (os.getpid(), path, requested, source, allow_download)- with _lock:- if key in _selections:- return _selections[key]- try:- if requested != "auto" or sys.platform not in {"win32", "linux"}:+ try:+ if requested != "auto" or sys.platform not in {"win32", "linux"}:+ selection = _select_and_save(+ requested, source, intra_op_num_threads, inter_op_num_threads, allow_download=allow_download+ )+ else:+ try:+ Path(path).parent.mkdir(parents=True, exist_ok=True)+ selection_lock = FileLock(f"{path}.onnx-selection.lock", timeout=30)+ selection_lock.acquire()+ except OSError:selection = _select_and_save(requested, source, intra_op_num_threads, inter_op_num_threads, allow_download=allow_download)else:try:- Path(path).parent.mkdir(parents=True, exist_ok=True)- selection_lock = FileLock(f"{path}.onnx-selection.lock", timeout=30)- selection_lock.acquire()- except OSError:selection = _select_and_save(requested, source, intra_op_num_threads, inter_op_num_threads, allow_download=allow_download)- else:- try:- selection = _select_and_save(- requested, source, intra_op_num_threads, inter_op_num_threads, allow_download=allow_download- )- finally:- selection_lock.release()- except Exception as error:- logger.warning("ONNX device selection failed; using CPU for this process: {}", error)- selection = OnnxSelection(reason="selection_failed")- _selections[key] = selection- logger.info("ONNX device selected: {}", selection)- return selection+ finally:+ selection_lock.release()+ except Exception as error:+ logger.warning("ONNX device selection failed; using CPU: {}", error)+ selection = OnnxSelection(reason="selection_failed")+ logger.info("ONNX device selected: {}", selection)+ return selectiondef confirm_gpu_session(selection: OnnxSelection) -> None:@@ -232,7 +197,6 @@ __all__ = ["ONNX_GPU_TIME_RATIO_THRESHOLDS","OnnxSelection","choose_gpu",- "cached_onnx_device","confirm_gpu_session","inspect_onnx_candidate","metacommands_enabled",diff --git a/mineru/model/runtime/tier_recommendation.py b/mineru/model/runtime/tier_recommendation.pyindex fd7fce75..84164f77 100644--- a/mineru/model/runtime/tier_recommendation.py+++ b/mineru/model/runtime/tier_recommendation.py@@ -10,7 +10,8 @@ from loguru import loggerfrom ...types import TIERS, Tier, select_default_task_tierfrom .cpu_threads import effective_cpu_count-from .device import resolve_small_model_backend, resolve_torch_device+from .device_state import cached_runtime_device, resolve_runtime_device+from .device_types import OnnxSelection, TorchDeviceSelectionfrom .onnx_calibration_cache import CalibrationInfo, inspect_calibration_recordif TYPE_CHECKING:@@ -72,7 +73,9 @@ def recommend_tiers(*, vlm_config: VlmConfig | None = None) -> TierRecommendatiosettings = vlm_config if vlm_config is not None else get_config().model.vlmsettings.validate_environment()- small_backend = resolve_small_model_backend()+ cached = cached_runtime_device()+ runtime = resolve_runtime_device()+ small_backend = runtime.backendvlm_engine = "http-client" if settings.server_url else resolve_vlm_engine(settings.engine)warnings: list[str] = []try:@@ -83,48 +86,39 @@ def recommend_tiers(*, vlm_config: VlmConfig | None = None) -> TierRecommendatiodevice = "cpu"if small_backend == "torch":- choice = resolve_torch_device()- hardware = TierHardware(count, choice.accelerated, choice.reason)+ choice = runtime.selection+ assert isinstance(choice, TorchDeviceSelection)+ hardware = TierHardware(count, not runtime.is_cpu, choice.reason)device = choice.devicecalibration = CalibrationDecision("skipped", "torch_backend")if choice.warning:warnings.append(choice.warning)else:- logger.info("Automatic API tier selection is resolving the ONNX device before finalizing tiers")+ onnx_choice = runtime.selection+ assert isinstance(onnx_choice, OnnxSelection)+ accelerated = not runtime.is_cpu+ device = f"{onnx_choice.backend}:gpu" if accelerated else "cpu"+ reason = "ocr_calibrated_gpu" if accelerated and onnx_choice.reason == "rec_calibration" else onnx_choice.reason+ hardware = TierHardware(count, accelerated, reason)try:- from .onnx_device import cached_onnx_device, resolve_onnx_device-- # 与 llama 自动模式复用相同入口;缓存、显式配置和免校准规则均由 ONNX 选型负责。- cached = cached_onnx_device()- onnx_choice = resolve_onnx_device()- accelerated = onnx_choice.device == "gpu"- device = f"{onnx_choice.backend}:gpu" if accelerated else "cpu"- reason = "ocr_calibrated_gpu" if accelerated and onnx_choice.reason == "rec_calibration" else onnx_choice.reason- hardware = TierHardware(count, accelerated, reason)- try:- evidence = inspect_calibration_record((onnx_choice.adapter,) if onnx_choice.adapter is not None else None)- except Exception as error:- evidence = None- warnings.append(f"ONNX calibration diagnostics unavailable: {error}")- status = "skipped"- if onnx_choice.reason == "rec_calibration":- status = "reused" if cached is not None else "completed"- elif onnx_choice.reason in {- "selection_failed",- "calibration_unstable",- "directml_unavailable",- "calibration_pending",- }:- status = "failed"- warnings.append(f"ONNX selection used CPU: {onnx_choice.reason}")- elif onnx_choice.reason == "configured_cpu" and evidence is not None:- status = "reused" if evidence.matches_environment and evidence.decision_valid else "skipped"- calibration = CalibrationDecision(status, onnx_choice.reason, evidence)+ evidence = inspect_calibration_record((onnx_choice.adapter,) if onnx_choice.adapter is not None else None)except Exception as error:- logger.warning("Startup ONNX selection unavailable; using CPU recommendation rules: {}", error)- warnings.append(f"ONNX selection unavailable: {error}")- calibration = CalibrationDecision("failed", "selection_unavailable")- hardware = TierHardware(count, reason="selection_unavailable")+ evidence = None+ warnings.append(f"ONNX calibration diagnostics unavailable: {error}")+ status = "skipped"+ if onnx_choice.reason == "rec_calibration":+ status = "reused" if cached is not None else "completed"+ elif onnx_choice.reason in {+ "selection_failed",+ "calibration_unstable",+ "directml_unavailable",+ "calibration_pending",+ }:+ status = "failed"+ warnings.append(f"ONNX selection used CPU: {onnx_choice.reason}")+ elif onnx_choice.reason == "configured_cpu" and evidence is not None:+ status = "reused" if evidence.matches_environment and evidence.decision_valid else "skipped"+ calibration = CalibrationDecision(status, onnx_choice.reason, evidence)tiers = tiers_for_hardware(hardware)ordered = tuple(tier for tier in TIERS if tier in tiers)diff --git a/mineru/parser/api_server.py b/mineru/parser/api_server.pyindex de226bc8..6ba12955 100644--- a/mineru/parser/api_server.py+++ b/mineru/parser/api_server.py@@ -186,11 +186,19 @@ class HealthFeatures(BaseModel):sources: list[Literal["upload", "url"]] = Field(default_factory=lambda: ["upload", "url"])+class HealthRuntime(BaseModel):+ """只展示服务进程已确定的默认模式,不代表每个模型的实际 provider。"""++ model_config = _PYDANTIC_CONFIG+ device: Literal["cpu", "gpu"]++class HealthResponse(BaseModel):model_config = _PYDANTIC_CONFIGstatus: str = "ok"version: strfeatures: HealthFeatures = Field(default_factory=HealthFeatures)+ runtime: HealthRuntime | None = None# ── Models API ───────────────────────────────────────────────────────@@ -1368,16 +1376,21 @@ def _require_model_preload_ready(request: Request) -> None:@_router.get("/health",response_model=HealthResponse,+ response_model_exclude_none=True,status_code=status.HTTP_200_OK,responses={503: {"model": ErrorResponse}},tags=["Health"],)async def get_health(request: Request) -> HealthResponse:- """Health check endpoint."""+ """只读健康状态与已发布设备快照,不在请求中触发选型或模型初始化。"""+ from ..model.runtime.device_state import cached_runtime_device+_require_model_preload_ready(request)+ runtime = cached_runtime_device()return HealthResponse(version=__version__,features=HealthFeatures(),+ runtime=HealthRuntime(device=runtime.device) if runtime is not None else None,)diff --git a/mineru/parser/tier.py b/mineru/parser/tier.pyindex e6a61466..c6ba73e0 100644--- a/mineru/parser/tier.py+++ b/mineru/parser/tier.py@@ -63,13 +63,14 @@ def runtime_options_for_tier(tier: Tier) -> ParserRuntimeOptions:def required_modules_for_tier(tier: DeploymentTier, *, vlm_config: VlmConfig | None = None) -> list[str]:"""按独立后端组合预检依赖,远程 VLM 不要求本地引擎。"""from ..config import get_config- from ..model.runtime.device import TORCH_REQUIRED_MODULES, resolve_small_model_backend+ from ..model.runtime.device import TORCH_REQUIRED_MODULES+ from ..model.runtime.device_state import resolve_model_backendfrom ..model.vlm.selector import VLM_REQUIRED_MODULES, resolve_vlm_engineif tier not in DEPLOYMENT_TIERS:raise ValueError(f"Unsupported deployment tier '{tier}'. Supported tiers: {', '.join(DEPLOYMENT_TIERS)}")modules = ["onnxruntime"]- if resolve_small_model_backend() == "torch":+ if resolve_model_backend() == "torch":modules.extend(TORCH_REQUIRED_MODULES)settings = vlm_config if vlm_config is not None else get_config().model.vlmif tier == "standard" and not settings.server_url:diff --git a/tests/unittest/conftest.py b/tests/unittest/conftest.pyindex 2e38e96c..d2f5a636 100644--- a/tests/unittest/conftest.py+++ b/tests/unittest/conftest.py@@ -7,9 +7,9 @@ import pytest@pytest.fixture(autouse=True)def isolate_onnx_device_selection(monkeypatch: pytest.MonkeyPatch) -> None:- """Individual policy tests explicitly override this CPU default with isolated files."""+ """隔离进程设备快照和 ONNX 偏好,策略测试显式注入独立配置与探测替身。"""from mineru.config import get_config- from mineru.model.runtime import onnx_device+ from mineru.model.runtime import device_statemonkeypatch.setattr(get_config().model, "onnx_device", "cpu")- monkeypatch.setattr(onnx_device, "_selections", {})+ monkeypatch.setattr(device_state, "_states", {})diff --git a/tests/unittest/test_directml_runtime.py b/tests/unittest/test_directml_runtime.pyindex 90e6ef33..b9b38362 100644--- a/tests/unittest/test_directml_runtime.py+++ b/tests/unittest/test_directml_runtime.py@@ -9,6 +9,9 @@ from types import SimpleNamespacefrom unittest.mock import Mockimport numpy as np+from mineru.model.runtime import onnx_device+from mineru.config import get_config+import pytestfrom mineru.model.runtime.gpu import classify_d3d12_gpu, with_gpu_classification@@ -48,7 +51,8 @@ def test_cpu_models_do_not_select_gpu(monkeypatch: pytest.MonkeyPatch) -> None:monkeypatch.setattr(onnx, "sys", SimpleNamespace(platform="win32"))select = Mock(side_effect=AssertionError("selection"))factory = Mock(return_value=SimpleNamespace(get_providers=lambda: ["CPUExecutionProvider"]))- monkeypatch.setattr(onnx, "resolve_onnx_device", select)+ monkeypatch.setattr(get_config().model, "small_backend", "onnx")+ monkeypatch.setattr(onnx_device, "resolve_onnx_device", select)monkeypatch.setattr(onnx.ort, "InferenceSession", factory)for kind in ("", "ocr_det", "seal_det", "table", "mfr_tail_cpu"):onnx.ort_session("test.onnx", model_kind=kind)diff --git a/tests/unittest/test_llama_device_policy.py b/tests/unittest/test_llama_device_policy.pyindex 3f0b0dd9..022d40da 100644--- a/tests/unittest/test_llama_device_policy.py+++ b/tests/unittest/test_llama_device_policy.py@@ -62,7 +62,7 @@ def test_automatic_route_consumes_onnx_result(select = onnx(monkeypatch, OnnxSelection(decision, reason=reason))result = policy.resolve_llama_device()assert result == policy.LlamaSelection(decision, reason=f"onnx_{reason}")- select.assert_called_once_with()+ select.assert_called_once_with(allow_download=True, intra_op_num_threads=0, inter_op_num_threads=0)def test_repeated_resolution_reuses_onnx_cache(monkeypatch: pytest.MonkeyPatch) -> None:@@ -76,7 +76,7 @@ def test_repeated_resolution_reuses_onnx_cache(monkeypatch: pytest.MonkeyPatch)def test_offline_resolution_preserves_download_constraint(monkeypatch: pytest.MonkeyPatch) -> None:select = onnx(monkeypatch, OnnxSelection(reason="selection_failed"))assert policy.resolve_llama_device(allow_download=False).device == "cpu"- select.assert_called_once_with(allow_download=False)+ select.assert_called_once_with(allow_download=False, intra_op_num_threads=0, inter_op_num_threads=0)@pytest.mark.parametrize("accelerated", [False, True])diff --git a/tests/unittest/test_llama_server_device_policy.py b/tests/unittest/test_llama_server_device_policy.pyindex 6fae0537..f4b53d2b 100644--- a/tests/unittest/test_llama_server_device_policy.py+++ b/tests/unittest/test_llama_server_device_policy.py@@ -172,7 +172,9 @@ def test_only_automatic_onnx_route_adds_intel_compatibility(@pytest.mark.parametrize("decision", ["cpu", "gpu"])def test_server_main_applies_automatic_mode_before_gpu_defaults(monkeypatch: pytest.MonkeyPatch, decision: str) -> None:- monkeypatch.setattr(onnx_device, "resolve_onnx_device", lambda: OnnxSelection(decision, reason="configured_" + decision))+ monkeypatch.setattr(+ onnx_device, "resolve_onnx_device", lambda **_: OnnxSelection(decision, reason="configured_" + decision)+ )monkeypatch.setattr(server.sys, "argv", ["llama-server", "-m", "model.gguf", "--mmproj", "mmproj.gguf"])monkeypatch.setattr(server, "_read_gguf_context_length", lambda path: 0)execute = Mock()diff --git a/tests/unittest/test_onnx_device_selection.py b/tests/unittest/test_onnx_device_selection.pyindex 7bf9f8ec..67f8425c 100644--- a/tests/unittest/test_onnx_device_selection.py+++ b/tests/unittest/test_onnx_device_selection.py@@ -8,6 +8,7 @@ from pathlib import Pathfrom types import SimpleNamespacefrom unittest.mock import Mock+from mineru.model.runtime import device_stateimport pytestimport yamlfrom pydantic import ValidationError@@ -33,7 +34,8 @@ def config_file(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:monkeypatch.setattr(settings, "get_config_source", lambda key: "file")monkeypatch.setattr(settings.get_config().model, "onnx_device", "auto")monkeypatch.setattr(policy, "sys", SimpleNamespace(platform="win32"))- monkeypatch.setattr(policy, "_selections", {})+ monkeypatch.setattr(device_state, "_states", {})+ monkeypatch.setattr(settings.get_config().model, "small_backend", "onnx")monkeypatch.setattr(policy, "ONNX_GPU_TIME_RATIO_THRESHOLDS", {"dml": 0.75, "webgpu": 0.8})monkeypatch.setattr(policy, "discover_gpus", lambda **_: (adapter(),))import onnxruntime@@ -89,7 +91,7 @@ def test_gpu_mode_requests_fast_probe(config_file: Path, monkeypatch: pytest.Monmonkeypatch.setattr(settings.get_config().model, "onnx_device", "gpu")discover = Mock(return_value=(adapter(uma=None),))monkeypatch.setattr(policy, "discover_gpus", discover)- assert policy.resolve_onnx_device().device == "gpu"+ assert device_state.resolve_runtime_device().selection.device == "gpu"discover.assert_called_once_with(classify=False)@@ -108,7 +110,7 @@ def test_cpu_never_discovers_or_benchmarks(config_file: Path, monkeypatch: pytesmonkeypatch.setattr(settings.get_config().model, "onnx_device", "cpu")discover = Mock(side_effect=AssertionError("discovery"))monkeypatch.setattr(policy, "discover_gpus", discover)- assert policy.resolve_onnx_device().device == "cpu"+ assert device_state.resolve_runtime_device().selection.device == "cpu"discover.assert_not_called()@@ -118,12 +120,12 @@ def test_calibration_saved_once(config_file: Path, monkeypatch: pytest.MonkeyPatmeasure = Mock(return_value={"decision_valid": True, "cpu_elapsed": 2.0, "gpu_elapsed": gpu_time})monkeypatch.setattr(onnx_calibration, "run_calibration", measure)- assert policy.resolve_onnx_device().device == expected- assert policy.resolve_onnx_device().device == expected+ assert device_state.resolve_runtime_device().selection.device == expected+ assert device_state.resolve_runtime_device().selection.device == expectedassert measure.call_count == 1assert yaml.safe_load(config_file.read_text())["model"] == {"onnx_device": expected, "source": "local"}- policy._selections.clear() # A new process reads the persisted choice instead of benchmarking again.- assert policy.resolve_onnx_device().device == expected+ device_state._states.clear() # A new process reads the persisted choice instead of benchmarking again.+ assert device_state.resolve_runtime_device().selection.device == expectedassert measure.call_count == 1@@ -140,14 +142,14 @@ def test_offline_calibration_never_downloads_or_poison_online_cache(config_file:assert policy.resolve_onnx_device(allow_download=False).device == "cpu"loader.assert_called_once_with(source="local")assert yaml.safe_load(config_file.read_text())["model"]["onnx_device"] == "auto"- assert policy.resolve_onnx_device().device == "gpu"+ assert device_state.resolve_runtime_device().selection.device == "gpu"def test_discrete_skips_calibration_and_persists_only_after_session(config_file: Path, monkeypatch: pytest.MonkeyPatch) -> None:from mineru.model.runtime import onnx_calibrationmonkeypatch.setattr(policy, "discover_gpus", lambda **_: (adapter(uma=False),))- result = policy.resolve_onnx_device()+ result = device_state.resolve_runtime_device().selectionassert result.device == "gpu"onnx_calibration.run_calibration.assert_not_called()assert yaml.safe_load(config_file.read_text())["model"]["onnx_device"] == "auto"@@ -161,15 +163,15 @@ def test_failures_do_not_save_or_retry(config_file: Path, monkeypatch: pytest.Momeasure = Mock(side_effect=failure)monkeypatch.setattr(onnx_calibration, "run_calibration", measure)- assert policy.resolve_onnx_device().device == "cpu"- assert policy.resolve_onnx_device().device == "cpu"+ assert device_state.resolve_runtime_device().selection.device == "cpu"+ assert device_state.resolve_runtime_device().selection.device == "cpu"assert measure.call_count == 1assert yaml.safe_load(config_file.read_text())["model"]["onnx_device"] == "auto"def test_environment_choice_is_not_saved(config_file: Path, monkeypatch: pytest.MonkeyPatch) -> None:monkeypatch.setattr(settings, "get_config_source", lambda key: "env")- assert policy.resolve_onnx_device().device == "gpu"+ assert device_state.resolve_runtime_device().selection.device == "gpu"assert yaml.safe_load(config_file.read_text())["model"]["onnx_device"] == "auto"@@ -177,12 +179,12 @@ def test_user_edit_wins_compare_and_swap(config_file: Path) -> None:config_file.write_text("model:\n onnx_device: cpu\n source: local\n", encoding="utf-8")assert not settings.update_config_file({"model": {"onnx_device": "gpu"}}, only_if_onnx_auto=True)assert yaml.safe_load(config_file.read_text())["model"]["onnx_device"] == "cpu"- assert policy.resolve_onnx_device().device == "cpu"+ assert device_state.resolve_runtime_device().selection.device == "cpu"def test_unwritable_config_keeps_process_choice(config_file: Path, monkeypatch: pytest.MonkeyPatch) -> None:monkeypatch.setattr(settings, "update_config_file", Mock(side_effect=PermissionError("read only")))- assert policy.resolve_onnx_device().device == "gpu"+ assert device_state.resolve_runtime_device().selection.device == "gpu"assert yaml.safe_load(config_file.read_text())["model"]["onnx_device"] == "auto"@@ -200,7 +202,7 @@ def test_discovery_and_unavailable_states(config_file: Path, monkeypatch: pytestmonkeypatch.setitem(policy.ONNX_GPU_TIME_RATIO_THRESHOLDS, "dml", None)else:monkeypatch.setattr(policy, "sys", SimpleNamespace(platform="darwin"))- assert policy.resolve_onnx_device().device == "cpu"+ assert device_state.resolve_runtime_device().selection.device == "cpu"assert yaml.safe_load(config_file.read_text())["model"]["onnx_device"] == ("cpu" if mode == "no_gpu" else "auto")@@ -208,7 +210,7 @@ def test_manual_gpu_retained_without_gpu(config_file: Path, monkeypatch: pytest.monkeypatch.setattr(settings.get_config().model, "onnx_device", "gpu")config_file.write_text("model:\n onnx_device: gpu\n", encoding="utf-8")monkeypatch.setattr(policy, "discover_gpus", lambda **_: ())- assert policy.resolve_onnx_device().device == "cpu"+ assert device_state.resolve_runtime_device().selection.device == "cpu"assert yaml.safe_load(config_file.read_text())["model"]["onnx_device"] == "gpu"@@ -223,7 +225,7 @@ def test_waiting_process_rechecks_choice_after_lock(config_file: Path, monkeypatpassmonkeypatch.setattr(policy, "FileLock", lambda *args, **kwargs: OtherProcessSaved())- assert policy.resolve_onnx_device().device == "cpu"+ assert device_state.resolve_runtime_device().selection.device == "cpu"onnx_calibration.run_calibration.assert_not_called()@@ -232,7 +234,7 @@ def test_concurrent_model_initializers_share_one_decision(config_file: Path) ->from mineru.model.runtime import onnx_calibrationwith ThreadPoolExecutor(max_workers=4) as pool:- choices = list(pool.map(lambda _: policy.resolve_onnx_device(), range(8)))+ choices = list(pool.map(lambda _: device_state.resolve_runtime_device().selection, range(8)))assert all(choice is choices[0] for choice in choices)assert onnx_calibration.run_calibration.call_count == 1@@ -240,10 +242,10 @@ def test_concurrent_model_initializers_share_one_decision(config_file: Path) ->def test_manual_reset_to_auto_recalibrates(config_file: Path) -> None:from mineru.model.runtime import onnx_calibration- policy.resolve_onnx_device()+ device_state.resolve_runtime_device().selectionsettings.update_config_file({"model": {"onnx_device": "auto"}})- policy._selections.clear() # New process after the explicit reset.- policy.resolve_onnx_device()+ device_state._states.clear() # New process after the explicit reset.+ device_state.resolve_runtime_device().selectionassert onnx_calibration.run_calibration.call_count == 2@@ -326,9 +328,9 @@ def test_linux_calibration_uses_vulkan_type_instead_of_ep_metadata(monkeypatch.setattr(policy, "discover_webgpu_devices", Mock(return_value=(descriptor,)))measure = Mock(return_value={"decision_valid": True, "cpu_elapsed": 2.0, "gpu_elapsed": gpu_time})monkeypatch.setattr(onnx_calibration, "run_calibration", measure)- selection = policy.resolve_onnx_device()+ selection = device_state.resolve_runtime_device().selectionassert selection.device == expected and selection.backend == "webgpu"- assert policy.resolve_onnx_device() is selection+ assert device_state.resolve_runtime_device().selection is selectionmeasure.assert_called_once_with("rec.onnx",with_gpu_classification(descriptor, classify_vulkan_gpu(1)),@@ -378,8 +380,8 @@ def test_linux_discrete_skips_calibration_and_saves_after_actual_session("gpu" if source == "file" else "auto")assert not Path(f"{linux_config}.onnx-calibration.json").exists()- policy._selections.clear()- assert policy.resolve_onnx_device().reason == ("configured_gpu" if source == "file" else "discrete_gpu")+ device_state._states.clear()+ assert device_state.resolve_runtime_device().selection.reason == ("configured_gpu" if source == "file" else "discrete_gpu")download.assert_not_called()onnx_calibration.run_calibration.assert_not_called()@@ -398,7 +400,7 @@ def test_linux_discrete_session_failure_preserves_auto(monkeypatch.setattr(vulkan, "enumerate_vulkan_devices", lambda: (integrated, discrete) if failure == "binding" else (discrete,))- selected = policy.resolve_onnx_device()+ selected = device_state.resolve_runtime_device().selectionassert selected.reason == "discrete_gpu"cpu = SimpleNamespace(get_providers=lambda: ["CPUExecutionProvider"])factory = Mock(side_effect=[RuntimeError("GPU failed"), cpu] if failure == "initialization" else None, return_value=cpu)@@ -428,7 +430,7 @@ def test_linux_unconfirmed_discrete_still_calibrates(linux_config: Path, monkeypreturn_value=(physical, physical) if state == "duplicate" else (physical,),),)- assert policy.resolve_onnx_device().reason == "rec_calibration"+ assert device_state.resolve_runtime_device().selection.reason == "rec_calibration"onnx_calibration.run_calibration.assert_called_once()@@ -438,7 +440,7 @@ def test_linux_hidden_discrete_does_not_exempt_visible_integrated(linux_config:integrated = WebGPUDevice(0x1002, 1)monkeypatch.setattr(policy, "discover_webgpu_devices", lambda: (WebGPUDevice(0x10DE, 0x2489), integrated))- selected = policy.resolve_onnx_device()+ selected = device_state.resolve_runtime_device().selectionassert selected.reason == "rec_calibration" and selected.adapter == with_gpu_classification(integrated, classify_vulkan_gpu(1))@@ -450,7 +452,7 @@ def test_linux_explicit_modes_do_not_calibrate(linux_config: Path, monkeypatch:from mineru.model.runtime import onnx_calibrationmonkeypatch.setattr(settings.get_config().model, "onnx_device", requested)- assert policy.resolve_onnx_device().device == requested+ assert device_state.resolve_runtime_device().selection.device == requestedonnx_calibration.run_calibration.assert_not_called()assert policy.discover_webgpu_devices.call_count == (0 if requested == "cpu" else 1)@@ -467,14 +469,14 @@ def test_linux_failures_preserve_auto_and_do_not_retry(else:monkeypatch.setattr(onnx_calibration, "run_calibration", failing)for _ in range(2):- assert policy.resolve_onnx_device().device == "cpu"+ assert device_state.resolve_runtime_device().selection.device == "cpu"assert failing.call_count == 1assert yaml.safe_load(linux_config.read_text())["model"]["onnx_device"] == "auto"def test_linux_environment_override_never_persists(linux_config: Path, monkeypatch: pytest.MonkeyPatch) -> None:monkeypatch.setattr(settings, "get_config_source", lambda key: "env")- assert policy.resolve_onnx_device().device == "gpu"+ assert device_state.resolve_runtime_device().selection.device == "gpu"assert yaml.safe_load(linux_config.read_text())["model"]["onnx_device"] == "auto"@@ -486,7 +488,7 @@ def test_linux_unavailable_state_preserves_auto(linux_config: Path, monkeypatch:monkeypatch.setattr(policy, "discover_webgpu_devices", Mock(return_value=()))else:monkeypatch.setitem(policy.ONNX_GPU_TIME_RATIO_THRESHOLDS, "webgpu", None)- assert policy.resolve_onnx_device().device == "cpu"+ assert device_state.resolve_runtime_device().selection.device == "cpu"onnx_calibration.run_calibration.assert_not_called()assert yaml.safe_load(linux_config.read_text())["model"]["onnx_device"] == "auto"@@ -500,7 +502,7 @@ def test_linux_waiting_process_rechecks_saved_choice(linux_config: Path, monkeyppassmonkeypatch.setattr(policy, "FileLock", lambda *args, **kwargs: OtherProcessSaved())- assert policy.resolve_onnx_device().device == "cpu"+ assert device_state.resolve_runtime_device().selection.device == "cpu"policy.discover_webgpu_devices.assert_not_called()@@ -518,10 +520,10 @@ def test_unstable_calibration_keeps_auto(config_file: Path, monkeypatch: pytest.monkeypatch.setattr(policy, "discover_webgpu_devices", lambda: (WebGPUDevice(0x8086, 0x7D51),))measure = Mock(return_value={"decision_valid": False, "cpu_elapsed": 2.0, "gpu_elapsed": 1.0})monkeypatch.setattr(onnx_calibration, "run_calibration", measure)- selected = policy.resolve_onnx_device()+ selected = device_state.resolve_runtime_device().selectionassert selected.device == "cpu" and selected.reason == "calibration_unstable"assert yaml.safe_load(config_file.read_text())["model"]["onnx_device"] == "auto"- assert policy.resolve_onnx_device() == selected+ assert device_state.resolve_runtime_device().selection == selectedmeasure.assert_called_once()diff --git a/tests/unittest/test_onnx_model_stack.py b/tests/unittest/test_onnx_model_stack.pyindex 4420f768..b00fded8 100644--- a/tests/unittest/test_onnx_model_stack.py+++ b/tests/unittest/test_onnx_model_stack.py@@ -236,12 +236,13 @@ def test_atom_and_context_caches_are_isolated_by_stack(monkeypatch: pytest.Monkeassert full is not lightassert manager.get_atom_model("ocr", small_backend="onnx", device="cpu") is lightmonkeypatch.setattr(hybrid, "HybridLocalModelContext", factory)- monkeypatch.setattr(hybrid, "get_device", lambda: "cpu")+ from mineru.config import get_config++ monkeypatch.setattr(get_config().model, "small_backend", "onnx")context_manager = hybrid.HybridLocalModelContextSingleton()- monkeypatch.setattr(hybrid, "resolve_small_model_backend", lambda: "torch")- full_context = context_manager.get_model()- monkeypatch.setattr(hybrid, "resolve_small_model_backend", lambda: "onnx")- assert context_manager.get_model() is not full_context+ context = context_manager.get_model()+ monkeypatch.setattr(get_config().model, "small_backend", "torch")+ assert context_manager.get_model() is contextassert factory.call_args.kwargs == {"small_backend": "onnx", "device": "cpu"}diff --git a/tests/unittest/test_parser_api_contract.py b/tests/unittest/test_parser_api_contract.pyindex 344da841..193e569f 100644--- a/tests/unittest/test_parser_api_contract.py+++ b/tests/unittest/test_parser_api_contract.py@@ -285,7 +285,10 @@ def test_hybrid_context_does_not_resolve_full_weights_before_stack_selection() -manager = _RecordingAtomManager()context.device = "cpu"context.small_backend = "onnx"+ from mineru.model.runtime.device_types import OnnxSelection, RuntimeDevice+context._resource = None+ context._device_decision = RuntimeDevice(OnnxSelection())context.atom_model_manager = manager # type: ignore[assignment]with patch.object(ModelPath, "ensure", side_effect=AssertionError("full weight path resolved too early")):diff --git a/tests/unittest/test_runtime_device_health.py b/tests/unittest/test_runtime_device_health.pynew file mode 100644index 00000000..9f991d57--- /dev/null+++ b/tests/unittest/test_runtime_device_health.py@@ -0,0 +1,72 @@+"""验证 health 的设备字段只读、惰性出现及启动选型一致性。"""++from __future__ import annotations++from pathlib import Path+from unittest.mock import Mock++from fastapi.testclient import TestClient+import pytest+from pydantic import ValidationError++from mineru.config import VlmConfig, get_config+from mineru.model.runtime import device, device_state, onnx_device+from mineru.model.runtime.device_types import OnnxSelection, TorchDeviceSelection+from mineru.parser import api_server+++def test_lazy_health_does_not_initialize_device(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ """未初始化时保持原 health 形状,重复请求也不能触发设备选型。"""+ forbidden = Mock(side_effect=AssertionError("health must not select devices"))+ monkeypatch.setattr(device_state, "resolve_runtime_device", forbidden)+ monkeypatch.setattr(onnx_device, "resolve_onnx_device", forbidden)+ monkeypatch.setattr(device, "resolve_torch_device", forbidden)+ app = api_server.create_app(upload_dir=str(tmp_path), tiers={"flash"})+ with TestClient(app) as client:+ for _ in range(3):+ response = client.get("/v1/health")+ assert response.status_code == 200+ assert set(response.json()) == {"status", "version", "features"}+ forbidden.assert_not_called()+ assert device_state.cached_runtime_device() is None++[email protected]("selection", [OnnxSelection(), OnnxSelection("gpu"), TorchDeviceSelection("mps")])+def test_health_reports_published_mode_without_reselection(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, selection: OnnxSelection | TorchDeviceSelection+) -> None:+ """首次发布后 health 只读同一模式,配置及局部模型覆盖不改变响应。"""+ backend = "torch" if isinstance(selection, TorchDeviceSelection) else "onnx"+ monkeypatch.setattr(get_config().model, "small_backend", backend)+ probe = Mock(return_value=selection)+ monkeypatch.setattr(device if backend == "torch" else onnx_device, f"resolve_{backend}_device", probe)+ app = api_server.create_app(upload_dir=str(tmp_path), tiers={"flash"})+ with TestClient(app) as client:+ assert "runtime" not in client.get("/v1/health").json()+ runtime = device_state.resolve_runtime_device()+ monkeypatch.setattr(get_config().model, "onnx_device", "gpu")+ with device_state.model_device_scope(device_state.resolve_model_device("torch", "cpu")):+ response = client.get("/v1/health")+ assert response.status_code == 200+ assert response.json()["runtime"] == {"device": runtime.device}+ probe.assert_called_once()+++def test_auto_tier_and_health_share_startup_decision(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ """自动启动产生的设备决策在 health 中直接可见,无需模型预加载。"""+ monkeypatch.setattr(get_config().model, "small_backend", "torch")+ probe = Mock(return_value=TorchDeviceSelection("cuda:1"))+ monkeypatch.setattr(device, "resolve_torch_device", probe)+ monkeypatch.setattr(api_server, "ensure_tier_runtime_dependencies", Mock())+ app = api_server.create_app(upload_dir=str(tmp_path), vlm_config=VlmConfig(engine="llama-cpp"))+ with TestClient(app) as client:+ assert client.get("/v1/health").json()["runtime"] == {"device": "gpu"}+ assert len(client.get("/v1/tiers").json()["data"]) == 4+ probe.assert_called_once()+++def test_health_model_accepts_legacy_payload_and_rejects_invalid_mode() -> None:+ """旧服务缺少设备字段仍合法,新字段仅接受 CPU/GPU 二值。"""+ assert api_server.HealthResponse.model_validate({"status": "ok", "version": "test"}).runtime is None+ with pytest.raises(ValidationError):+ api_server.HealthResponse.model_validate({"version": "test", "runtime": {"device": "mps"}})diff --git a/tests/unittest/test_runtime_device_state.py b/tests/unittest/test_runtime_device_state.pynew file mode 100644index 00000000..9e784dfa--- /dev/null+++ b/tests/unittest/test_runtime_device_state.py@@ -0,0 +1,275 @@+"""验证进程设备快照、并发初始化与局部模型覆盖。"""++from __future__ import annotations++from concurrent.futures import ThreadPoolExecutor+from itertools import permutations+import os+import subprocess+import sys+import threading+from types import SimpleNamespace+from unittest.mock import Mock++import pytest++from mineru.config import get_config+from mineru.model.runtime import device, device_state, onnx_device+from mineru.model.runtime.device_types import OnnxSelection, RuntimeDevice, TorchDeviceSelection+++ "selection,backend,mode",+ [+ (TorchDeviceSelection("cpu"), "torch", "cpu"),+ (TorchDeviceSelection("cuda:1"), "torch", "gpu"),+ (TorchDeviceSelection("mps"), "torch", "gpu"),+ (TorchDeviceSelection("npu:0"), "torch", "gpu"),+ (OnnxSelection(), "onnx", "cpu"),+ (OnnxSelection("gpu"), "onnx", "gpu"),+ ],+)+def test_device_mode_is_derived(selection: OnnxSelection | TorchDeviceSelection, backend: str, mode: str) -> None:+ """模式与后端从同一选型派生,不能构造相互矛盾的字段。"""+ result = RuntimeDevice(selection)+ assert result.backend == backend and result.device == mode+ assert result.is_cpu == (mode == "cpu")+++def test_import_and_cached_read_do_not_load_inference_backends() -> None:+ """独立解释器导入及查询不加载重依赖,也不创建初始化状态。"""+ script = """+import sys+from mineru.model.runtime import device_state+assert device_state.cached_runtime_device() is None+assert not device_state._states+assert not ({'torch', 'onnxruntime', 'transformers', 'mineru_llama_cpp'} & sys.modules.keys())+"""+ subprocess.run([sys.executable, "-c", script], check=True, capture_output=True, text=True, timeout=30)+++def test_concurrent_initialization_is_once_and_peek_does_not_wait(monkeypatch: pytest.MonkeyPatch) -> None:+ """初始化期间只读查询立即返回 None,所有等待者最终共享同一快照。"""+ monkeypatch.setattr(get_config().model, "small_backend", "onnx")+ entered, release = threading.Event(), threading.Event()++ def select(**kwargs: object) -> OnnxSelection:+ """阻塞底层选型以验证实际等待者及无锁查询。"""+ entered.set()+ assert release.wait(5)+ return OnnxSelection("gpu", reason="test")++ probe = Mock(side_effect=select)+ monkeypatch.setattr(onnx_device, "resolve_onnx_device", probe)+ with ThreadPoolExecutor(max_workers=8) as executor:+ futures = [executor.submit(device_state.resolve_runtime_device) for _ in range(8)]+ try:+ assert entered.wait(5)+ assert device_state.cached_runtime_device() is None+ finally:+ release.set()+ results = [future.result(timeout=5) for future in futures]+ assert all(value is results[0] for value in results)+ probe.assert_called_once()+++def test_backend_config_environment_and_options_are_frozen(monkeypatch: pytest.MonkeyPatch) -> None:+ """首轮后的配置、环境和参数变化都不能改变正式快照。"""+ monkeypatch.setattr(get_config().model, "small_backend", "torch")+ torch = Mock(return_value=TorchDeviceSelection("cuda:1"))+ monkeypatch.setattr(device, "resolve_torch_device", torch)+ onnx = Mock(side_effect=AssertionError("unrelated ONNX"))+ monkeypatch.setattr(onnx_device, "resolve_onnx_device", onnx)+ first = device_state.resolve_runtime_device()+ monkeypatch.setattr(get_config().model, "small_backend", "onnx")+ monkeypatch.setattr(get_config().model, "onnx_device", "gpu")+ monkeypatch.setenv("MINERU_DEVICE_MODE", "cpu")+ assert device_state.resolve_runtime_device(allow_download=False, intra_op_num_threads=8) is first+ assert device_state.resolve_model_device() is first+ torch.assert_called_once()+ onnx.assert_not_called()+++def test_failed_initialization_does_not_publish_partial_state(monkeypatch: pytest.MonkeyPatch) -> None:+ """未完成选型的异常不留下 CPU 占位,也不阻止后续合法初始化。"""+ monkeypatch.setattr(get_config().model, "small_backend", "onnx")+ probe = Mock(side_effect=[ValueError("invalid startup"), OnnxSelection("gpu")])+ monkeypatch.setattr(onnx_device, "resolve_onnx_device", probe)+ with pytest.raises(ValueError, match="invalid startup"):+ device_state.resolve_runtime_device()+ assert device_state.cached_runtime_device() is None+ assert device_state.resolve_runtime_device().device == "gpu"+++def test_formal_offline_cpu_is_stable(monkeypatch: pytest.MonkeyPatch) -> None:+ """正式离线运行确认 CPU 回退后,在线调用不能悄悄重新选型。"""+ monkeypatch.setattr(get_config().model, "small_backend", "onnx")+ probe = Mock(return_value=OnnxSelection(reason="selection_failed"))+ monkeypatch.setattr(onnx_device, "resolve_onnx_device", probe)+ first = device_state.resolve_runtime_device(allow_download=False)+ assert first.is_cpu+ assert device_state.resolve_runtime_device() is first+ probe.assert_called_once_with(allow_download=False, intra_op_num_threads=0, inter_op_num_threads=0)+++def test_new_pid_does_not_reuse_parent_decision_or_lock(monkeypatch: pytest.MonkeyPatch) -> None:+ """子进程按新 PID 创建状态,不读取父进程快照或等待父进程锁。"""+ monkeypatch.setattr(get_config().model, "small_backend", "onnx")+ probe = Mock(side_effect=[OnnxSelection(), OnnxSelection("gpu")])+ monkeypatch.setattr(onnx_device, "resolve_onnx_device", probe)+ parent_pid = os.getpid()+ parent = device_state.resolve_runtime_device()+ parent_state = device_state._states[parent_pid]+ monkeypatch.setattr(device_state, "os", SimpleNamespace(getpid=lambda: parent_pid + 1))+ assert device_state.cached_runtime_device() is None+ child = device_state.resolve_runtime_device()+ assert child is not parent and child.device == "gpu"+ assert device_state._states[parent_pid + 1].lock is not parent_state.lock+++def test_explicit_model_scope_preserves_default_and_threads(monkeypatch: pytest.MonkeyPatch) -> None:+ """局部模型覆盖只传递给嵌套构造,其他线程和默认策略继续使用原快照。"""+ monkeypatch.setattr(get_config().model, "small_backend", "onnx")+ default = device_state.resolve_runtime_device()+ override = device_state.resolve_model_device("torch", "cuda:2")+ with device_state.model_device_scope(override):+ assert device_state.resolve_model_device() is override+ assert device_state.resolve_runtime_device() is default+ with ThreadPoolExecutor(max_workers=1) as executor:+ assert executor.submit(device_state.resolve_model_device).result(timeout=5) is default+ assert device_state.resolve_model_device() is default+++def test_explicit_torch_cpu_does_not_initialize_default(monkeypatch: pytest.MonkeyPatch) -> None:+ """明确的局部 Torch CPU 构造不触发无关默认后端的下载或校准。"""+ monkeypatch.setattr(get_config().model, "small_backend", "onnx")+ forbidden = Mock(side_effect=AssertionError("default selection"))+ monkeypatch.setattr(onnx_device, "resolve_onnx_device", forbidden)+ assert device_state.resolve_model_device("torch", "cpu").is_cpu+ assert device_state.cached_runtime_device() is None+ forbidden.assert_not_called()+++def test_asset_and_dependency_selection_follow_frozen_backend(monkeypatch: pytest.MonkeyPatch) -> None:+ """运行前的资产和依赖查询无副作用,决策发布后也不能随配置切换到另一后端。"""+ from mineru.model.registry import MINERU_4_MODELS_ONNX, MINERU_4_MODELS_TORCH, small_model_repo+ from mineru.parser.tier import required_modules_for_tier++ monkeypatch.setattr(get_config().model, "small_backend", "onnx")+ assert small_model_repo() is MINERU_4_MODELS_ONNX+ assert required_modules_for_tier("basic") == ["onnxruntime"]+ assert device_state.cached_runtime_device() is None+ device_state.resolve_runtime_device()+ monkeypatch.setattr(get_config().model, "small_backend", "torch")+ assert small_model_repo() is MINERU_4_MODELS_ONNX+ assert required_modules_for_tier("basic") == ["onnxruntime"]+ assert small_model_repo("torch") is MINERU_4_MODELS_TORCH++[email protected]("order", list(permutations(("tier", "llama", "model"))))[email protected]("mode", ["cpu", "gpu"])+def test_consumers_share_one_decision_in_any_order(monkeypatch: pytest.MonkeyPatch, order: tuple[str, ...], mode: str) -> None:+ """档位、llama 和实际 ONNX 会话的不同首次调用顺序都只执行一次选型。"""+ from mineru.model.runtime import llama_device, onnx, tier_recommendation+ from mineru.model.runtime.windows_gpu import GpuAdapter++ monkeypatch.setattr(get_config().model, "small_backend", "onnx")+ monkeypatch.setattr(get_config().model.vlm, "engine", "llama-cpp")+ monkeypatch.delenv("MINERU_LLAMA_CPP_BACKEND", raising=False)+ monkeypatch.setattr(llama_device, "sys", SimpleNamespace(platform="win32"))+ monkeypatch.setattr(tier_recommendation, "effective_cpu_count", lambda: 8)+ monkeypatch.setattr(tier_recommendation, "inspect_calibration_record", lambda _: None)+ adapter = GpuAdapter(1, "id", "test", 0x10DE, 1, 0) if mode == "gpu" else None+ choice = OnnxSelection(mode, adapter, "rec_calibration", "dml")+ probe = Mock(return_value=choice)+ monkeypatch.setattr(onnx_device, "resolve_onnx_device", probe)+ session = SimpleNamespace(get_providers=lambda: ["DmlExecutionProvider" if adapter else "CPUExecutionProvider"])+ factory = Mock(return_value=session)+ monkeypatch.setattr(onnx, "create_ort_session", factory)+ for consumer in order:+ if consumer == "tier":+ report = tier_recommendation.recommend_tiers()+ assert report.ceiling == ("advanced" if mode == "gpu" else "basic")+ elif consumer == "llama":+ assert llama_device.resolve_llama_device().device == mode+ else:+ assert onnx.ort_session("test.onnx", model_kind="layout") is session+ assert factory.call_args.kwargs["adapter"] is adapter+ # 配置写回或用户修改不应改变后续消费者的运行设备。+ monkeypatch.setattr(get_config().model, "onnx_device", "cpu" if mode == "gpu" else "gpu")+ probe.assert_called_once()+ assert device_state.cached_runtime_device().selection is choice+++def test_session_cpu_fallback_does_not_change_default_policy(monkeypatch: pytest.MonkeyPatch) -> None:+ """单个模型 GPU 初始化失败后实际使用 CPU,进程默认策略仍保持最初决策。"""+ from mineru.model.runtime import onnx+ from mineru.model.runtime.windows_gpu import GpuAdapter++ monkeypatch.setattr(get_config().model, "small_backend", "onnx")+ choice = OnnxSelection("gpu", GpuAdapter(1, "id", "test", 0x10DE, 1, 0), "discrete_gpu", "dml")+ monkeypatch.setattr(onnx_device, "resolve_onnx_device", Mock(return_value=choice))+ cpu = SimpleNamespace(get_providers=lambda: ["CPUExecutionProvider"])+ factory = Mock(side_effect=[RuntimeError("GPU init"), cpu])+ monkeypatch.setattr(onnx, "create_ort_session", factory)+ confirm = Mock()+ monkeypatch.setattr(onnx, "confirm_gpu_session", confirm)+ assert onnx.ort_session("test.onnx", model_kind="layout") is cpu+ assert device_state.cached_runtime_device().device == "gpu"+ assert factory.call_count == 2+ confirm.assert_not_called()+++def test_hardware_summary_reads_only_current_process(monkeypatch: pytest.MonkeyPatch) -> None:+ """诊断将配置与本进程快照分开展示,查询本身不触发正式选型。"""+ from mineru.model.runtime.hardware import config_summary++ monkeypatch.setattr(get_config().model, "small_backend", "onnx")+ summary = config_summary()+ assert summary["process_runtime"] == {"pid": os.getpid(), "device": None, "small_backend": None}+ assert device_state.cached_runtime_device() is None+ device_state.resolve_runtime_device()+ monkeypatch.setattr(get_config().model, "onnx_device", "gpu")+ summary = config_summary()+ assert summary["settings"]["model.onnx_device"]["value"] == "gpu"+ assert summary["process_runtime"]["device"] == "cpu"++[email protected](not hasattr(os, "fork"), reason="需要 POSIX fork 验证继承锁边界")+def test_fork_child_ignores_lock_held_by_parent_thread() -> None:+ """独立解释器实际 fork 时,子进程绕过被父线程占用的初始化锁。"""+ script = """+import os+import threading+from mineru.config import get_config+from mineru.model.runtime import device_state+get_config().model.small_backend = 'torch'+os.environ['MINERU_DEVICE_MODE'] = 'cpu'+parent = device_state.resolve_runtime_device()+state = device_state._states[os.getpid()]+held, release = threading.Event(), threading.Event()+def hold():+ # 在父线程占用初始化锁,复现 fork 时继承不可释放锁的边界。+ with state.lock:+ held.set()+ release.wait(10)+thread = threading.Thread(target=hold)+thread.start()+assert held.wait(5)+pid = os.fork()+if pid == 0:+ try:+ assert device_state.cached_runtime_device() is None+ child = device_state.resolve_runtime_device()+ assert child is not parent and child.is_cpu+ except BaseException:+ os._exit(1)+ os._exit(0)+try:+ _, status = os.waitpid(pid, 0)+ assert status == 0+finally:+ release.set()+ thread.join(5)+"""+ subprocess.run([sys.executable, "-c", script], check=True, capture_output=True, text=True, timeout=20)diff --git a/tests/unittest/test_runtime_ownership.py b/tests/unittest/test_runtime_ownership.pyindex f228548d..973c5cef 100644--- a/tests/unittest/test_runtime_ownership.py+++ b/tests/unittest/test_runtime_ownership.py@@ -53,11 +53,10 @@ def local_models(monkeypatch: pytest.MonkeyPatch) -> list[_Atom]:monkeypatch.setattr(ModelSingleton, "_models", {})monkeypatch.setattr(ModelSingleton, "_closing", {})monkeypatch.setattr(ModelSingleton, "_initializing", {})- monkeypatch.setattr(hybrid, "resolve_small_model_backend", lambda backend=None: backend or "onnx")- monkeypatch.setattr(hybrid, "get_device", lambda: "cpu")+ monkeypatch.setattr(get_config().model, "small_backend", "onnx")monkeypatch.setattr(hybrid, "ocr_det_batch_setting", lambda: True)monkeypatch.setattr(cpu_threads, "initialize_torch_threads", lambda: 2)- monkeypatch.setattr(onnx_device, "resolve_onnx_device", lambda: "cpu")+ monkeypatch.setattr(onnx_device, "resolve_onnx_device", lambda **_: onnx_device.OnnxSelection())def create(model_name: str, **options: Any) -> _Atom:"""表格模型像生产构造器一样借用不同配置的 OCR,形成真实二级依赖。"""@@ -97,10 +96,10 @@ def test_shared_context_keeps_cached_properties_until_last_owner(local_models: lassert not hybrid.AtomModelSingleton._models-def test_distinct_contexts_preserve_shared_atom_dependencies(+def test_config_writeback_reuses_context_and_preserves_dependencies(local_models: list[_Atom], monkeypatch: pytest.MonkeyPatch) -> None:- """不同 ONNX 配置上下文解析到同一设备时,共享的表格及其 OCR 依赖按最后持有者释放。"""+ """ONNX 配置写回不拆分上下文,共享模型及 OCR 依赖仍按最后持有者释放。"""first, second = RuntimeOwner(), RuntimeOwner()manager = hybrid.HybridLocalModelContextSingleton()monkeypatch.setattr(get_config().model, "onnx_device", "auto")@@ -110,7 +109,7 @@ def test_distinct_contexts_preserve_shared_atom_dependencies(monkeypatch.setattr(get_config().model, "onnx_device", "cpu")with _owned(second):right = manager.get_model()- assert right is not left+ assert right is leftassert right.ocr_model is left.ocr_modelassert right.wireless_table_model is tablerelease_runtime_owner(first)@@ -122,24 +121,24 @@ def test_distinct_contexts_preserve_shared_atom_dependencies(assert not hybrid.AtomModelSingleton._models-def test_backend_and_device_changes_release_only_their_context(+def test_explicit_model_override_releases_only_its_owner(local_models: list[_Atom], monkeypatch: pytest.MonkeyPatch) -> None:- """后端或设备切换仍沿原缓存键隔离,关闭一个配置不会回收另一个配置。"""+ """显式 Torch 模型与默认 ONNX 上下文各自按所有权释放,配置变化不切换默认上下文。"""first, second = RuntimeOwner(), RuntimeOwner()manager = hybrid.HybridLocalModelContextSingleton()with _owned(first):onnx_context = manager.get_model()- monkeypatch.setattr(hybrid, "resolve_small_model_backend", lambda backend=None: backend or "torch")- monkeypatch.setattr(hybrid, "get_device", lambda: "cuda:0")+ monkeypatch.setattr(get_config().model, "small_backend", "torch")with _owned(second):- torch_context = manager.get_model()- assert torch_context.ocr_model is not onnx_context.ocr_model+ assert manager.get_model() is onnx_context+ explicit = hybrid.AtomModelSingleton().get_atom_model("ocr", small_backend="torch", device="cuda:0")+ assert explicit is not onnx_context.ocr_modelrelease_runtime_owner(first)assert len(manager._models) == 1- assert len(hybrid.AtomModelSingleton._models) == 2+ assert len(hybrid.AtomModelSingleton._models) == 3with _owned(second):- assert manager.get_model() is torch_context+ assert manager.get_model() is onnx_contextrelease_runtime_owner(second)assert not manager._modelsassert not hybrid.AtomModelSingleton._models@@ -159,6 +158,23 @@ def test_cli_pin_survives_application_release(local_models: list[_Atom]) -> Noneassert len(hybrid.AtomModelSingleton._models) == 2+def test_explicit_context_does_not_initialize_unrelated_default(+ local_models: list[_Atom], monkeypatch: pytest.MonkeyPatch+) -> None:+ """显式 Torch CPU 上下文连同批处理策略和嵌套模型都不触发默认 ONNX 选型。"""+ from mineru.model.runtime import device_state++ def batch_setting() -> bool:+ """策略读取当前构造作用域,而不是尚未初始化的进程默认后端。"""+ assert device_state.resolve_model_device().backend == "torch"+ return True++ monkeypatch.setattr(hybrid, "ocr_det_batch_setting", batch_setting)+ context = hybrid.HybridLocalModelContext(device="cpu", small_backend="torch")+ assert context.small_backend == "torch" and context.device == "cpu"+ assert device_state.cached_runtime_device() is None++def test_empty_and_shared_owner_release_do_not_force_full_gc(local_models: list[_Atom], monkeypatch: pytest.MonkeyPatch) -> None:diff --git a/tests/unittest/test_table_onnx_runtime.py b/tests/unittest/test_table_onnx_runtime.pyindex a7f25677..8a0941e5 100644--- a/tests/unittest/test_table_onnx_runtime.py+++ b/tests/unittest/test_table_onnx_runtime.py@@ -4,6 +4,9 @@ from types import SimpleNamespacefrom unittest.mock import Mockfrom pathlib import Path+from mineru.model.runtime import onnx_device+from mineru.config import get_config+import pytestfrom mineru.model.runtime.gpu import classify_d3d12_gpu, with_gpu_classification@@ -233,14 +236,15 @@ def test_onnx_unet_preserves_options_profile_and_dml_lock(monkeypatch: pytest.Mo"gpu", with_gpu_classification(GpuAdapter(7, "id", "intel", 0x8086, 1, 0), classify_d3d12_gpu(True)), backend="dml"))- monkeypatch.setattr(onnx, "resolve_onnx_device", select)+ monkeypatch.setattr(get_config().model, "small_backend", "onnx")+ monkeypatch.setattr(onnx_device, "resolve_onnx_device", select)monkeypatch.setattr(onnx.ort, "get_available_providers", lambda: ["DmlExecutionProvider", "CPUExecutionProvider"])native = SimpleNamespace(get_providers=lambda: ["DmlExecutionProvider", "CPUExecutionProvider"], disable_fallback=Mock())factory = Mock(return_value=native)monkeypatch.setattr(onnx.ort, "InferenceSession", factory)model = TSRUnet({"model_path": "unet.onnx", "small_backend": "onnx", "intra_op_num_threads": 2})assert isinstance(model.session.session, onnx.DirectMLSession)- select.assert_called_once_with(intra_op_num_threads=2, inter_op_num_threads=1)+ select.assert_called_once_with(allow_download=True, intra_op_num_threads=2, inter_op_num_threads=1)opts = factory.call_args.kwargs["sess_options"]assert (opts.intra_op_num_threads, opts.inter_op_num_threads) == (2, 1)assert not opts.enable_cpu_mem_arena and not opts.enable_mem_pattern@@ -256,7 +260,7 @@ def test_onnx_unet_preserves_options_profile_and_dml_lock(monkeypatch: pytest.Mo@pytest.mark.parametrize("legacy_device", ["cpu", "auto", "cuda"])def test_torch_unet_retains_legacy_table_device(monkeypatch: pytest.MonkeyPatch, legacy_device: str) -> None:monkeypatch.setenv("MINERU_TABLE_DEVICE", legacy_device)- monkeypatch.setattr(onnx, "resolve_onnx_device", Mock(side_effect=AssertionError("ONNX selection")))+ monkeypatch.setattr(onnx_device, "resolve_onnx_device", Mock(side_effect=AssertionError("ONNX selection")))monkeypatch.setattr(onnx.ort, "get_available_providers", lambda: ["CUDAExecutionProvider", "CPUExecutionProvider"])factory = Mock(return_value=SimpleNamespace(get_providers=lambda: ["CPUExecutionProvider"]))monkeypatch.setattr(onnx.ort, "InferenceSession", factory)diff --git a/tests/unittest/test_tier_recommendation.py b/tests/unittest/test_tier_recommendation.pyindex 84d736e1..6b6bc72b 100644--- a/tests/unittest/test_tier_recommendation.py+++ b/tests/unittest/test_tier_recommendation.py@@ -12,6 +12,7 @@ from types import SimpleNamespacefrom typing import Anyfrom unittest.mock import Mock+from mineru.model.runtime import device_stateimport pytestimport yaml@@ -26,7 +27,7 @@ from mineru.types import TIERS@pytest.fixture(autouse=True)def onnx_recommendation_backend(monkeypatch: pytest.MonkeyPatch) -> Iterator[None]:"""本文件验证 ONNX 既有推荐规则,隔离宿主可能自动选择的 Torch 后端。"""- from mineru.model.runtime import gpu_memory, llama_probe, onnx_device+ from mineru.model.runtime import gpu_memory, llama_probeimport subprocessforbidden = Mock(side_effect=AssertionError("recommendation must not probe llama devices"))@@ -39,12 +40,12 @@ def onnx_recommendation_backend(monkeypatch: pytest.MonkeyPatch) -> Iterator[Nonreturn run(args, **kwargs)monkeypatch.setattr(subprocess, "run", guarded_run)- monkeypatch.setattr(recommendation, "resolve_small_model_backend", lambda: "onnx")from mineru.config import get_config+ monkeypatch.setattr(get_config().model, "small_backend", "onnx")monkeypatch.setattr(get_config().model, "onnx_device", "auto")monkeypatch.setattr(get_config().model.vlm, "engine", "llama-cpp")- monkeypatch.setattr(onnx_device, "_selections", {})+ monkeypatch.setattr(device_state, "_states", {})memory_probe = Mock(side_effect=AssertionError("recommendation must not query GPU memory"))monkeypatch.setattr(gpu_memory, "native_gpu_memory", memory_probe)monkeypatch.setattr(gpu_memory, "torch_gpu_memory", memory_probe)@@ -89,7 +90,7 @@ def test_recommendation_respects_affinity_and_quota(return read_text(path, *args, **kwargs)monkeypatch.setattr(cpu_threads.Path, "read_text", read_quota)- monkeypatch.setattr(onnx_device, "resolve_onnx_device", lambda: onnx_device.OnnxSelection())+ monkeypatch.setattr(onnx_device, "resolve_onnx_device", lambda **_: onnx_device.OnnxSelection())report = recommendation.recommend_tiers()assert report.cpu_count == expectedassert report.pdf_image_tiers == (TIERS[:3] if expected >= 12 else TIERS[:2] if expected >= 4 else TIERS[:1])@@ -190,7 +191,7 @@ def test_onnx_unsupported_platform_uses_cpu_without_torch(monkeypatch.delenv("MINERU_LLAMA_CPP_BACKEND", raising=False)monkeypatch.setattr(onnx_device, "sys", SimpleNamespace(platform=platform))- monkeypatch.setattr(onnx_device, "_selections", {})+ monkeypatch.setattr(device_state, "_states", {})monkeypatch.setitem(sys.modules, "torch", None)monkeypatch.setattr(recommendation, "effective_cpu_count", lambda: 12)report = recommendation.recommend_tiers()@@ -232,7 +233,7 @@ def startup_calibration(lambda: (with_gpu_classification(vulkan.VulkanDevice(0x8086, 0x7D51, "test"), classify_vulkan_gpu(1)),),)monkeypatch.setattr(recommendation, "effective_cpu_count", lambda: 8)- monkeypatch.setattr(onnx_device, "_selections", {})+ monkeypatch.setattr(device_state, "_states", {})monkeypatch.setattr(onnxruntime, "get_available_providers", lambda: ["DmlExecutionProvider", "CPUExecutionProvider"])for module in (onnx_device, windows_gpu):monkeypatch.setattr(module, "discover_gpus", lambda **kwargs: (_adapter(),))@@ -278,7 +279,6 @@ def test_auto_startup_calibrates_before_publishing("""真实服务工厂在发布能力前读取本次校准,失败保持 Basic 上限且不伪造 CPU 胜出。"""from fastapi.testclient import TestClient- from mineru.model.runtime import onnx_devicefrom mineru.parser import api_serverconfig_file, measurement = startup_calibration@@ -301,7 +301,7 @@ def test_auto_startup_calibrates_before_publishing(assert tuple(row["id"] for row in client.get("/v1/tiers").json()["data"]) == expectedpreload.assert_not_called()# 随后的模型初始化复用本进程选择,不再开启第二次校准。- selected = onnx_device.resolve_onnx_device()+ selected = device_state.resolve_runtime_device().selectionassert selected.device == ("gpu" if outcome == "fast" else "cpu")measurement.assert_called_once()saved = "gpu" if outcome == "fast" else "cpu" if outcome == "slow" else "auto"@@ -356,7 +356,7 @@ def test_low_cpu_advanced_recommendation_still_selects_device(assert frozenset(report.pdf_image_tiers) == frozenset(TIERS)assert report.calibration.status == "skipped" and report.calibration.reason == "discrete_gpu"assert report.default_request_tier == "standard"- assert onnx_device._selections+ assert device_state.cached_runtime_device() is not Nonestartup_calibration[1].assert_not_called()config_file = startup_calibration[0]assert yaml.safe_load(config_file.read_text(encoding="utf-8"))["model"]["onnx_device"] == "auto"@@ -366,13 +366,12 @@ def test_low_cpu_advanced_recommendation_still_selects_device(@pytest.mark.parametrize("tier", TIERS)def test_explicit_ceiling_skips_startup_selection(startup_calibration: tuple[Path, Mock], tier: str) -> None:"""显式启动上限和 Python 精确集合均不进入自动推荐的设备选择。"""- from mineru.model.runtime import onnx_devicefrom mineru.parser.server_tiers import parse_server_tier, resolve_server_tiersselected = parse_server_tier(tier)assert resolve_server_tiers(selected) == selectedstartup_calibration[1].assert_not_called()- assert not onnx_device._selections+ assert device_state.cached_runtime_device() is None@pytest.mark.parametrize("requested", ["cpu", "gpu"])@@ -395,10 +394,9 @@ def test_startup_preserves_explicit_device_without_performance_evidence(@pytest.mark.parametrize("remove_evidence", [False, True])def test_next_startup_reuses_saved_device(startup_calibration: tuple[Path, Mock], remove_evidence: bool) -> None:"""自动校准保存 GPU 后,即使记录丢失也直接采用已保存的 GPU 设备选择。"""- from mineru.model.runtime import onnx_deviceassert frozenset(recommendation.recommend_tiers().pdf_image_tiers) == frozenset(TIERS)- onnx_device._selections.clear()+ device_state._states.clear()if remove_evidence:cache.calibration_record_path().unlink()report = recommendation.recommend_tiers()@@ -406,7 +404,7 @@ def test_next_startup_reuses_saved_device(startup_calibration: tuple[Path, Mock]assert report.reason == "configured_gpu"assert report.calibration.status == "skipped" and report.calibration.reason == "configured_gpu"startup_calibration[1].assert_called_once()- assert onnx_device.resolve_onnx_device().reason == "configured_gpu"+ assert device_state.resolve_runtime_device().selection.reason == "configured_gpu"@pytest.mark.parametrize("record", ["missing", "invalid", "stale", "slow", "unstable", "valid", "read_error"])@@ -541,7 +539,10 @@ def test_final_cpu_result_cannot_be_upgraded_by_discrete_inventory(return_value=onnx_device.OnnxSelection(reason=failure),side_effect=RuntimeError("driver") if failure == "raise" else None,)- monkeypatch.setattr(onnx_device, "resolve_onnx_device", selection)+ if failure == "raise":+ monkeypatch.setattr(onnx_device, "_select_and_save", selection)+ else:+ monkeypatch.setattr(onnx_device, "resolve_onnx_device", selection)report = recommendation.recommend_tiers()expected = TIERS[:3] if cores >= 12 else TIERS[:2] if cores >= 4 else TIERS[:1]assert report.pdf_image_tiers == expected and report.default_request_tier == expected[-1]@@ -572,11 +573,10 @@ def test_onnx_recommendation_without_torch_or_memory_queries(from mineru.model.runtime import device, gpu_memorymonkeypatch.setattr(get_config().model, "small_backend", "auto")- monkeypatch.setattr(recommendation, "resolve_small_model_backend", device.resolve_small_model_backend)monkeypatch.setitem(sys.modules, "torch", None)monkeypatch.setitem(sys.modules, "torchvision", None)torch_probe = Mock(side_effect=AssertionError("ONNX recommendation must not probe Torch"))- monkeypatch.setattr(recommendation, "resolve_torch_device", torch_probe)+ monkeypatch.setattr(device, "resolve_torch_device", torch_probe)memory = Mock(return_value=amount, side_effect=RuntimeError("memory unavailable") if amount == "error" else None)monkeypatch.setattr(gpu_memory, "native_gpu_memory", memory)report = recommendation.recommend_tiers()diff --git a/tests/unittest/test_webgpu_architecture.py b/tests/unittest/test_webgpu_architecture.pyindex 68cec8da..84ff8bee 100644--- a/tests/unittest/test_webgpu_architecture.py+++ b/tests/unittest/test_webgpu_architecture.py@@ -11,6 +11,7 @@ from pathlib import Pathfrom types import SimpleNamespacefrom unittest.mock import Mock+from mineru.model.runtime import device_stateimport pytestfrom mineru.model.runtime.gpu import classify_d3d12_gpu, classify_vulkan_gpu, with_gpu_classification@@ -111,17 +112,18 @@ def test_blocked_policy_never_downloads_measures_or_saves(monkeypatch.setattr(settings.get_config().model, "onnx_device", requested)monkeypatch.setattr(settings, "get_config_file_path", lambda: str(path))monkeypatch.setattr(settings, "get_config_source", lambda _: "file")- monkeypatch.setattr(onnx_device, "_selections", {})+ monkeypatch.setattr(device_state, "_states", {})+ monkeypatch.setattr(settings.get_config().model, "small_backend", "onnx")monkeypatch.setattr(onnx_device, "sys", SimpleNamespace(platform="linux"))monkeypatch.setattr(onnx_device, "discover_webgpu_devices", lambda: (webgpu.WebGPUDevice(0x8086, device_id),))download = Mock(side_effect=AssertionError("download"))monkeypatch.setattr(registry, "MINERU_4_MODELS_ONNX", SimpleNamespace(ocr_rec=SimpleNamespace(ensure=download)))measure = Mock(side_effect=AssertionError("calibration"))monkeypatch.setattr(onnx_calibration, "run_calibration", measure)- selected = onnx_device.resolve_onnx_device()+ selected = device_state.resolve_runtime_device().selectionassert selected.device == "cpu" and selected.reason == "webgpu_architecture_policy"assert path.read_bytes() == before- assert onnx_device.resolve_onnx_device() is selected+ assert device_state.resolve_runtime_device().selection is selecteddownload.assert_not_called()measure.assert_not_called()diff --git a/tests/unittest/test_webgpu_runtime.py b/tests/unittest/test_webgpu_runtime.pyindex 4b3c672e..0d6fe35e 100644--- a/tests/unittest/test_webgpu_runtime.py+++ b/tests/unittest/test_webgpu_runtime.py@@ -10,6 +10,9 @@ import timefrom types import SimpleNamespacefrom unittest.mock import Mock+from mineru.model.runtime import onnx_device+from mineru.config import get_config+import pytestfrom mineru.model.runtime.gpu import classify_vulkan_gpu, with_gpu_classification@@ -136,16 +139,17 @@ def test_linux_routes_only_five_models(monkeypatch: pytest.MonkeyPatch) -> None:monkeypatch.setattr(onnx, "sys", SimpleNamespace(platform="linux"))select = Mock(return_value=OnnxSelection("gpu", device(), backend="webgpu"))factory = Mock(return_value=SimpleNamespace(get_providers=lambda: [webgpu.WEBGPU_PROVIDER]))- monkeypatch.setattr(onnx, "resolve_onnx_device", select)+ monkeypatch.setattr(get_config().model, "small_backend", "onnx")+ monkeypatch.setattr(onnx_device, "resolve_onnx_device", select)monkeypatch.setattr(onnx, "create_ort_session", factory)for kind in ("layout", "mfr", "ocr_det", "ocr_rec", "unet"):onnx.ort_session("test.onnx", model_kind=kind)assert factory.call_args.kwargs["adapter"] == device()- assert select.call_count == 5+ assert select.call_count == 1for kind in ("", "seal_det", "table", "slanet_plus", "mfr_tail_cpu"):onnx.ort_session("test.onnx", model_kind=kind)assert factory.call_args.kwargs["adapter"] is None- assert select.call_count == 5+ assert select.call_count == 1def test_webgpu_creation_and_two_session_runs_share_lock(monkeypatch: pytest.MonkeyPatch) -> None: