Skip to content

Transforms complex documents like PDFs and Office docs into LLM-ready markdown/JSON for your Agentic workflows.

feat(hardware): add hardware detection and info commands for diagnostics

myhloli3535fcdab51b
diff --git a/docs/next/api/changes.md b/docs/next/api/changes.md
index f7e504f4..e44aac17 100644
--- a/docs/next/api/changes.md
+++ b/docs/next/api/changes.md
@@ -8,6 +8,10 @@ API 启动改为 `--tier auto|flash|basic|standard|advanced`,移除 `--tiers`
Python `create_app(tiers=...)` 保留精确 PDF/图片集合,模型依赖及预加载仍按实际需求合并。HTTP 请求默认、逐文件实际档位和产物协议保持原规则。
+`--tier auto`(包括省略参数)按有效小模型后端分流。Torch 使用经过验证的实际设备可用性,有加速设备时开放 Advanced,CPU 情况按可用核数推荐,不执行 OCR 校准或改写 ONNX 配置。ONNX 在硬件初选达到 Basic 后,会在 Windows/Linux 启动阶段同步完成现有设备选型及适用的 OCR 校准,再确定最终开放上限。无需启用 `--preload-models`,首次校准可能准备或下载 OCR rec 模型。初选仅 Flash、显式启动档位以及已保存的设备选择不强制测速;模型预加载与请求默认档位保持原规则。
+
+新增 `mineru-kit hardware detect [--json]` 和 `hardware info [--json]`,分别用于同源推荐与只读问题反馈诊断。软件版本只展示指定清单内已安装的包;没有 `--quiet` 或 `auto-tier` 别名。
+
这是一轮能力语义和启动参数升级:先停收并排空在途任务,再协调更新 worker、Router 和客户端。SaaS Go 服务由部署方同步对齐,避免新客户端把原生文件交给仍限制 Flash 的旧服务。模型故障恢复、Doclib 原生执行路径及缓存语义不属于本轮改动。
## 既有 Tasks 接口迁移
diff --git a/docs/next/cli/mineru-kit-api-server.md b/docs/next/cli/mineru-kit-api-server.md
index ace7967f..064797ba 100644
--- a/docs/next/cli/mineru-kit-api-server.md
+++ b/docs/next/cli/mineru-kit-api-server.md
@@ -64,9 +64,17 @@ Tasks 的请求 `tier` 仍可选,只对 PDF/图片生效。省略或 JSON `nul
CPU 数按逻辑 CPU 计算,并考虑进程亲和性和 Linux cgroup 配额。集显沿用有效 OCR 校准的 GPU 时间不高于 CPU 时间 0.8 倍的判定。探测失败或设备身份不明确时按 CPU 条件推荐。显式上限可以覆盖推荐,随后仍执行正常依赖预检。
-推荐阶段只探测设备并读取已有校准记录,不下载模型、不执行 OCR/VLM 性能测试、不写配置,也不增加内存分级门槛。实际 OCR 校准把证据保存在 `<配置文件路径>.onnx-calibration.json`,仅复用设备、运行时版本与 CPU 配置匹配的有效结果;旧 cpu/gpu 偏好及手动 GPU 设置不视为校准证据。新证据在下次启动时生效。
+自动推荐先解析有效小模型后端。Torch(包括 auto 最终选择 Torch)只验证实际设备可用性:可用 CUDA/MPS/XPU 等加速设备推荐 advanced;显式 CPU 或设备不可用时按 CPU 条件推荐,不下载 ONNX 校准模型或改写其配置/记录。Torch 推荐不依赖 llama.cpp 库存。
-远程 VLM 配置不自动扩大推荐上限。模型正常惰性加载及显式 `--preload-models` 行为与推荐阶段独立。
+ONNX 分支先探测硬件并读取已有校准记录。如果初选达到 Basic 或更高档位,Windows/Linux 会在发布服务能力前同步执行现有 ONNX 设备选择流程,再根据最新证据确定最终上限。初选只有 Flash、macOS 及其他平台跳过这一步;显式 `--tier` 和 Python 精确集合也不触发这项启动校准。
+
+启动选型继续遵守 `model.onnx_device`:`auto` 才按既有设备策略决定是否测速,显式或已保存的 `cpu/gpu` 不强制重新校准;Windows 独显、无可用 GPU、兼容策略排除的 GPU 等仍沿用原规则。需要测速时会按正常模型生命周期准备或下载 OCR rec 权重,并复用已有进程缓存、文件锁、采样阈值及失败回退。下载和模型准备不计入 15 秒校准子进程超时。校准失败或结果不稳定不会阻止后续推荐,但不作为 GPU 胜出证据。
+
+实际 OCR 校准把证据保存在 `<配置文件路径>.onnx-calibration.json`,仅复用设备、运行时版本与 CPU 配置匹配的有效结果;旧 cpu/gpu 偏好及手动 GPU 设置不视为校准证据。启动阶段产生的新证据在本次最终推荐中生效,之后 `/v1/tiers` 在服务生命周期内固定。
+
+远程 VLM 配置不自动扩大推荐上限,也不增加 VLM 性能测试或内存分级门槛。上述 OCR 选型不要求 `--preload-models`;该参数仍另外控制完整模型或 VLM 客户端的提前初始化。
+
+`mineru-kit hardware detect` 使用同一结构化推荐流程;`hardware info` 只读输出诊断报告,详见 [hardware 命令](mineru-kit-hardware.md)。API 工厂的 VLM 配置覆盖也参与推荐,避免与实际运行配置不一致。
### 内嵌部署与 SaaS
diff --git a/docs/next/cli/mineru-kit-hardware.md b/docs/next/cli/mineru-kit-hardware.md
new file mode 100644
index 00000000..f22d6849
--- /dev/null
+++ b/docs/next/cli/mineru-kit-hardware.md
@@ -0,0 +1,53 @@
+# mineru-kit hardware
+
+状态: Implemented
+
+`hardware detect` 推荐当前环境的 API 启动上限;`hardware info` 生成只读的问题反馈报告。两者默认输出可读文本,`--json` 输出同一份结构化数据。日志与进度进入 stderr,stdout 只保存结果。
+
+```bash
+mineru-kit hardware detect
+mineru-kit hardware detect --json
+mineru-kit hardware info
+mineru-kit hardware info --json > hardware-info.json
+```
+
+`hardware` 不带子命令时显示帮助。没有 `--quiet` 或 `auto-tier` 别名。配置沿用 `MINERU_CONFIG`、`MINERU_HOME` 和现有后端/设备环境变量。
+
+## 自动推荐
+
+命令与 `api-server --tier auto` 共享结构化推荐结果。先解析有效小模型后端,再确定设备与上限:
+
+| 有效后端 | 行为 |
+|----------|------|
+| Torch + 可用 CUDA/MPS/XPU 等加速设备 | 跳过 OCR 测速,推荐 advanced |
+| Torch + 显式 CPU 或加速设备不可用 | 跳过测速,进程可用 CPU 至少 4 时推荐 standard,否则 flash |
+| ONNX | 沿用既有硬件初选;初选至少 Basic 时在 Windows/Linux 同步完成适用的 OCR 选型,再确定最终上限 |
+
+`small_backend=auto` 最终选择 Torch 时同样免校准。显式设备字符串必须经过实际可用性检查;检查失败会给出保守结果及原因,不修改设备配置。Torch 推荐不依赖 llama.cpp 库存,不下载 ONNX 校准权重,也不写入 `model.onnx_device` 或 OCR 校准记录。
+
+ONNX 分支保留既有兼容策略、0.8 阈值、进程缓存和配置保存规则。首次实际测速可能下载 OCR rec 模型;下载和派生图准备不计入 15 秒校准 worker 超时。显式或已保存的 CPU/GPU 选择不强制重测。校准失败、超时或不稳定时保守推荐,并携带警告。
+
+llama.cpp 自动集显路径同样按有效小模型后端分流:Torch 使用加速可用性结果,不再绕回 OCR 校准;ONNX 保留原有性能结果和设备身份匹配。原生独显优先、显式 CPU/GPU 参数、物理绑定和兼容处理保持不变。
+
+JSON 报告 `schema_version=1`,包含 `ceiling`、`pdf_image_tiers`、`default_request_tier`、`reason`、`cpu_count`、`small_backend`、`vlm_engine`、`device`、`calibration` 和 `warnings`。校准状态来自执行结果;Torch 使用 `status=skipped, reason=torch_backend`,不将可用性结论标成性能实测通过。
+
+开放 Advanced 后,请求省略 tier 仍默认 Standard。推荐不代表模型已准备好,API 服务继续执行依赖预检;显式启动上限和 Python 精确集合不进入自动推荐。API 工厂的 VLM 配置覆盖参与共享推荐,远程 VLM 显示为 `http-client`,不自动扩大本机上限。
+
+## 环境报告
+
+`info` 不调用自动推荐或 OCR 校准,不下载、加载模型权重或写配置。运行时导入和原生 GPU 探测使用独立子进程,每项最多等待 15 秒。某项失败时继续报告其他信息,并区分未安装、导入失败和超时。
+
+- 系统、Python 版本与解释器路径,MinerU 版本与实际模块路径。
+- CPU 型号、物理/逻辑/进程可用核数,基础/当前/最大频率(MHz);内存总量及可用量(bytes)。
+- 系统可探测到的全部独显、集显和虚拟 GPU,以及当前进程运行时可用设备。保留名称、身份、驱动及可获得的显存/共享内存信息。
+- 已安装的软件包版本与位置:MinerU、DocVortex、mineru-llama-cpp、mineru-vl-utils、torch、transformers、ONNX Runtime及EP、vLLM、LMDeploy、mlx-vlm、pypdfium2。未安装的包不列入软件版本列表。
+- Torch 导入、编译使用的 CUDA/ROCm 版本和后端可用性;ORT provider 与相关引擎的探测结果。
+- 后端、设备、线程及可见设备限制的有效配置与来源;OCR 校准记录的存在状态、环境匹配、稳定性、耗时和阈值。
+
+未知值为 JSON `null`,文本显示“未知”。例如 Apple Silicon 通常不报告可可靠读取的 CPU 主频,统一内存也不作为独立显存。系统或容器限制导致库存不完整时保留错误说明;不从型号名称猜测设备类型或频率。
+
+配置报告使用明确白名单,不输出认证信息、完整远程服务地址或整个环境变量集合。诊断报告中的本地路径用于确认解释器和实际加载位置。
+
+## 退出码
+
+能形成推荐结果或环境报告时退出码为 0,包括带警告的保守推荐和局部探测失败。参数、配置错误或无法形成结果时返回非零退出码。
diff --git a/docs/next/cli/mineru-kit.md b/docs/next/cli/mineru-kit.md
index 1973024f..242563ef 100644
--- a/docs/next/cli/mineru-kit.md
+++ b/docs/next/cli/mineru-kit.md
@@ -22,6 +22,7 @@
| 子命令 | 作用 | 文档 |
|--------|------|------|
| `mineru-kit models` | 下载、查看和校验本地模型配置 | [mineru-kit models](mineru-kit-models.md) |
+| `mineru-kit hardware` | 自动推荐档位及只读硬件/运行时诊断 | [mineru-kit hardware](mineru-kit-hardware.md) |
| `mineru-kit parse` | 无状态文件/目录批处理解析 | [mineru-kit parse](mineru-kit-parse.md) |
| `mineru-kit webui` | 基于 V1 API 的本地文档解析 Web UI | [mineru-kit webui](mineru-kit-webui.md) |
| `mineru-kit api-server` | 启动兼容统一 API 的本地解析服务 | [mineru-kit api-server](mineru-kit-api-server.md) |
diff --git a/docs/next/decisions/0017-mineru-kit-api-server-command.md b/docs/next/decisions/0017-mineru-kit-api-server-command.md
index dc473c79..4ffa22fa 100644
--- a/docs/next/decisions/0017-mineru-kit-api-server-command.md
+++ b/docs/next/decisions/0017-mineru-kit-api-server-command.md
@@ -46,7 +46,7 @@ managed 是生命周期管理方式,不是用户直接操作的独立命令产
一个 API 服务进程使用 `--tier auto|flash|basic|standard|advanced` 表示 PDF/图片的最高开放档位,上限包含自身及全部较低档位;省略等价于 auto,取硬件推荐集合的最高档。Standard 上限不再隐含 Advanced。`--tiers`、`--no-flash`、`--no-advanced` 均直接移除。
-自动推荐沿用现有 CPU、独显、有效 OCR 校准和 Apple Silicon Metal 规则;不引入新的模型实测或内存门槛。依赖预检与可选预加载仍执行,Advanced 复用 Standard 模型配置。
+自动推荐先按有效小模型后端分流。Torch 使用实际加速设备可用性,GPU 路径开放 Advanced,CPU 路径按可用核数推荐,不执行 OCR 校准或写入 ONNX 配置。ONNX 沿用现有 CPU、独显、有效 OCR 校准和 Apple Silicon Metal 规则;初选达到 Basic 时,Windows/Linux 同步完成适用选型,再按最新证据确定本次上限。初选仅 Flash 或显式指定上限不增加启动校准。不引入新的采样阈值、VLM 实测或内存门槛。依赖预检与可选预加载仍执行,Advanced 复用 Standard 模型配置。`hardware detect` 与服务使用相同结构化推荐。
`/v1/tiers` 仅发布 PDF/图片可选档位。所有服务都支持现有原生文档格式,固定使用 flash;原生支持不再从公开 flash 档位推断,不新增原生能力声明。Tasks 请求 tier 继续可选,PDF/图片按 `standard -> basic -> flash` 默认选择,advanced 仅显式使用。
diff --git a/docs/next/onnx-device.md b/docs/next/onnx-device.md
index 74adea91..3ac1f030 100644
--- a/docs/next/onnx-device.md
+++ b/docs/next/onnx-device.md
@@ -78,7 +78,9 @@ MinerU 的 WebGPU 运行时锁覆盖过滤与会话初始化,后续每次会
本机双卡及仅 Intel ICD 的验证见 [Intel 架构过滤报告](onnx-intel-architecture-policy-validation.md)。
-首次实际使用模型时才选型。界面启动、导入 SDK、查询配置和模型列表不会运行测速。
+通常在首次实际使用 ONNX 模型时选型。API 使用 `--tier auto`(或省略),有效小模型后端为 ONNX 且硬件初选达到 Basic 时,Windows/Linux 会提前同步调用相同的设备选择流程,校准证据在本次最终档位推荐中生效,不依赖 `--preload-models`。初选仅 Flash、显式启动档位或 macOS 不增加这项启动选型。有效小模型后端为 Torch 时采用实际设备可用性结果并跳过 OCR 校准,不修改 ONNX 设备偏好或证据;llama.cpp 自动集显路径也遵循这处分流。
+
+`mineru-kit hardware detect` 与 API 自动启动共享推荐逻辑;`hardware info` 只读报告环境与校准记录,不测速。界面启动本身、导入 SDK、查询配置和模型列表不会运行测速;界面托管的 API 服务仍遵循其启动参数。
自动决策成功后原子更新有效配置文件中的 `model.onnx_device`,保留其余键;进程间通过文件锁协调。
环境变量覆盖不写入文件;只读配置保留本进程选择。测速失败不保存为 CPU 性能优胜,同进程不重复尝试。
Linux 插件缺失、Vulkan/设备发现失败(包括未发现可用硬件设备)、校准超时或输出不一致时保留 `auto`。
diff --git a/docs/next/open-questions.md b/docs/next/open-questions.md
index cee3a95f..e444348d 100644
--- a/docs/next/open-questions.md
+++ b/docs/next/open-questions.md
@@ -38,7 +38,7 @@
| doclib HTTP API | 本地 doclib HTTP API 使用 `/docs`、`/parses`、`/search` 和 `POST /invalidate`,详见 [ADR-0004](decisions/0004-doclib-http-api-resources.md)。 |
| 本地 `standard` | `standard` 本地运行是正式支持能力,不是实验能力;当前代码基本 ready。 |
| mineru.net tier | `mineru.net/api` 在相当长时间内默认提供 `standard` 解析;`standard` 是绝大多数场景足够好的高质量档位,但不是最高档。 |
-| api-server tier | `mineru-kit api-server --tier` 配置最高开放档位;省略等价于 auto,按硬件和已有 OCR 校准推荐上限,HTTP 请求默认仍优先 standard。 |
+| api-server tier | `mineru-kit api-server --tier` 配置最高开放档位;省略等价于 auto,Torch 按实际设备可用性免校准,ONNX 初选达到 basic 时在适用平台同步完成 OCR 选型,HTTP 请求默认仍优先 standard;`hardware detect` 共享推荐逻辑。 |
| managed 生命周期 | managed 模式下,模型下载、预热、重试和退避由 `mineru-kit api-server` 负责。 |
| 本地 api-server 安全 | 本地 api-server 默认监听 loopback;可通过 `--api-key` 设置固定 API Key,默认不设置。 |
| P0 主链路 | P0 包含完整 watch、rules、search,不再把它们标为可选主链路。 |
diff --git a/docs/next/tiers.md b/docs/next/tiers.md
index 80bc48ae..e584914b 100644
--- a/docs/next/tiers.md
+++ b/docs/next/tiers.md
@@ -100,7 +100,9 @@ advanced 只接受显式选择:只有 advanced 时没有默认档位,返回
### 3.4 API 服务启动推荐
-`--tier auto` 或省略启动参数时:进程可用逻辑 CPU 不足 4 且没有达标 GPU,只开放 flash;CPU 至少 4 时开放 flash、basic、standard;可用独显、有效 OCR 校准达标的集显、或 Metal 可用的 Apple Silicon 开放全部四档。推荐集合在启动时固定,不进行模型性能实测或额外内存分级。
+`--tier auto` 或省略启动参数时,先解析有效小模型后端。Torch 有经核验可用的 CUDA/MPS/XPU 等加速设备时开放全部四档,跳过 OCR 校准;显式 CPU 或设备不可用时,进程可用逻辑 CPU 至少 4 开放 flash、basic、standard,否则只开放 flash。此规则也适用于 auto 最终选择 Torch,不改写 ONNX 配置或校准记录。
+
+ONNX 保留既有规则:CPU 不足 4 且没有达标 GPU 时只开放 flash;CPU 至少 4 时开放到 standard;可用独显、有效 OCR 校准达标的集显或 Metal 可用的 Apple Silicon 开放全部四档。初选达到 basic 后,Windows/Linux 同步完成现有 ONNX 选型和适用校准,再确定本次上限。最终集合在启动时固定,不增加 VLM 性能测试或额外内存分级。`mineru-kit hardware detect` 共享这套推荐;`hardware info` 只读收集环境信息。
`--tier standard` 等显式上限开放自身和全部较低档位,允许覆盖硬件推荐。`/v1/tiers` 只约束 PDF/图片,原生文档在任何正常可用服务上均固定使用 flash。请求默认仍优先 standard,advanced 不参与默认选档。详见 [启动配置与迁移说明](cli/mineru-kit-api-server.md)。
diff --git a/mineru/kit/commands/__init__.py b/mineru/kit/commands/__init__.py
index 38d00a1e..e9ab8261 100644
--- a/mineru/kit/commands/__init__.py
+++ b/mineru/kit/commands/__init__.py
@@ -1,5 +1,5 @@
"""mineru-kit command modules."""
-from . import api_server, file_parse_server, models, parse, router, vlm_server, webui
+from . import api_server, file_parse_server, hardware, models, parse, router, vlm_server, webui
-__all__ = ["api_server", "file_parse_server", "models", "parse", "router", "vlm_server", "webui"]
+__all__ = ["api_server", "file_parse_server", "hardware", "models", "parse", "router", "vlm_server", "webui"]
diff --git a/mineru/kit/commands/hardware.py b/mineru/kit/commands/hardware.py
new file mode 100644
index 00000000..40eb1032
--- /dev/null
+++ b/mineru/kit/commands/hardware.py
@@ -0,0 +1,114 @@
+"""硬件推荐和只读诊断命令;帮助展示不导入或探测模型运行时。"""
+
+from __future__ import annotations
+
+from dataclasses import asdict
+from typing import Any
+
+import typer
+
+from ...cli.contracts import CliContext
+from ...cli.runtime import run_cli
+from ...utils.i18n import t
+
+app = typer.Typer(help=t("Detect recommended tiers or inspect hardware and runtime information."), no_args_is_help=True)
+
+
+def _value(value: Any) -> str:
+ """统一可读报告中的缺失值,避免将未知信息显示成零或空字符串。"""
+ if isinstance(value, dict):
+ return "{" + ", ".join(f"{key}: {_value(item)}" for key, item in value.items()) + "}"
+ if isinstance(value, (list, tuple)):
+ return "[" + ", ".join(_value(item) for item in value) + "]"
+ return "未知" if value is None or value == "" else str(value)
+
+
+def render_detection(data: dict[str, Any]) -> str:
+ """从结构化推荐直接渲染可读结果,不从日志推导推荐或校准状态。"""
+ calibration = data["calibration"]
+ lines = [
+ f"推荐启动上限:{data['ceiling']}",
+ f"PDF/图片档位:{', '.join(data['pdf_image_tiers'])}",
+ f"请求默认档位:{data['default_request_tier']}",
+ f"推荐依据:{data['reason']}",
+ f"可用 CPU:{data['cpu_count']}",
+ f"小模型后端:{data['small_backend']}",
+ f"VLM 引擎:{data['vlm_engine']}",
+ f"实际设备:{data['device']}",
+ f"校准状态:{calibration['status']} ({calibration['reason']})",
+ ]
+ lines.extend(f"提示:{warning}" for warning in data.get("warnings", []))
+ return "\n".join(lines)
+
+
+def render_info(data: dict[str, Any]) -> str:
+ """使用与 JSON 相同的字段生成可复制的问题反馈文本。"""
+ cpu, memory = data["cpu"], data["memory"]
+ lines = [
+ f"系统:{data['system']['name']} {data['system']['release']} ({data['system']['architecture']})",
+ f"系统版本:{_value(data['system'].get('os_version'))}",
+ f"发行版:{_value(data['system']['distribution'])}",
+ f"Python:{data['python']['version']} ({data['python']['executable']})",
+ f"MinerU:{data['mineru']['version']} ({data['mineru']['module_path']})",
+ f"CPU:{_value(cpu['model'])}",
+ f"CPU 核数:物理 {_value(cpu['physical_cores'])},逻辑 {_value(cpu['logical_cores'])},"
+ f"进程可用 {_value(cpu['available_cores'])}",
+ f"CPU 频率 (MHz):基础 {_value(cpu['base_mhz'])},当前 {_value(cpu['current_mhz'])},最大 {_value(cpu['max_mhz'])}",
+ f"内存 (bytes):总量 {_value(memory['total_bytes'])},可用 {_value(memory['available_bytes'])}",
+ "系统显卡:",
+ ]
+ if not data["gpus"]:
+ lines.append(" 未发现;如有探测错误,请参见提示")
+ for gpu in data["gpus"]:
+ lines.extend(
+ [
+ f" {_value(gpu['name'])} [{gpu['kind']}],厂商 {_value(gpu['vendor'])},标识 {_value(gpu['device_id'])}",
+ f" 来源 {gpu['source']},驱动 {_value(gpu['driver'])},总线 {_value(gpu['bus_id'])}",
+ f" 独立显存 {_value(gpu['dedicated_memory_bytes'])} bytes,"
+ f"共享内存 {_value(gpu['shared_memory_bytes'])} bytes,统一内存 {_value(gpu['unified_memory'])}",
+ ]
+ )
+ lines.append("已安装软件:")
+ lines.extend(f" {package['name']} {package['version']} ({package['location']})" for package in data["packages"])
+ lines.append("当前进程运行时探测:")
+ for probe in data["runtimes"]:
+ lines.append(f" {probe['name']}: {probe['status']}")
+ if probe["error"]:
+ lines.append(f" {probe['error']}")
+ for key, value in probe["data"].items():
+ lines.append(f" {key}: {_value(value)}")
+ lines.append("有效配置:")
+ lines.extend(f" {key}: {_value(value)}" for key, value in data["effective_config"].items())
+ lines.append("OCR 校准记录:")
+ lines.extend(f" {key}: {_value(value)}" for key, value in data["calibration"].items())
+ lines.extend(f"提示:{warning}" for warning in data["warnings"])
+ return "\n".join(lines)
+
+
+def _info_data() -> dict[str, Any]:
+ """仅在执行 info 时惰性导入采集层,帮助入口保持无探测副作用。"""
+ from ...model.runtime.hardware import collect_hardware_info
+
+ return asdict(collect_hardware_info())
+
+
+def _detect_data() -> dict[str, Any]:
+ """仅在执行 detect 时调用共享推荐工作进程。"""
+ from ...model.runtime.hardware_probe import run_detection
+
+ return run_detection()
+
+
[email protected]("detect", help=t("Recommend the API tier ceiling using hardware and applicable OCR calibration."))
+def detect_cmd(json_mode: bool = typer.Option(False, "--json", help=t("JSON output"))) -> None:
+ """执行与 API 自动启动一致的后端感知推荐。"""
+ run_cli(CliContext(json_mode=json_mode), _detect_data, render=render_detection)
+
+
[email protected]("info", help=t("Read hardware, installed versions and runtime diagnostics without calibration."))
+def info_cmd(json_mode: bool = typer.Option(False, "--json", help=t("JSON output"))) -> None:
+ """只读输出可用于问题反馈的环境报告。"""
+ run_cli(CliContext(json_mode=json_mode), _info_data, render=render_info)
+
+
+__all__ = ["app", "detect_cmd", "info_cmd", "render_detection", "render_info"]
diff --git a/mineru/kit/main.py b/mineru/kit/main.py
index 48c59f4a..3ca3dfee 100644
--- a/mineru/kit/main.py
+++ b/mineru/kit/main.py
@@ -10,7 +10,7 @@ from ..cli.version_command import show_version, version_cmd
from ..utils.i18n import t
from ..utils.logger import configure_global_log_level
from ..utils.stdio import configure_standard_streams
-from .commands import api_server, file_parse_server, models, parse, router, vlm_server, webui
+from .commands import api_server, file_parse_server, hardware, models, parse, router, vlm_server, webui
TOP_LEVEL_COMMAND_ORDER = [
"parse",
@@ -20,6 +20,7 @@ TOP_LEVEL_COMMAND_ORDER = [
"vlm-server",
"router",
"models",
+ "hardware",
"version",
]
@@ -53,11 +54,10 @@ def root(
app.add_typer(models.app, name="models")
+app.add_typer(hardware.app, name="hardware")
app.command("parse", help=t("Parse files or directories into markdown, middle JSON, or zip outputs."))(parse.parse_cmd)
app.command("webui", help=t("Start the Gradio document parsing web UI backed by the MinerU V1 API."))(webui.webui_cmd)
-app.command("api-server", help=t("Start the self-hosted MinerU parsing API service."))(
- api_server.api_server_cmd
-)
+app.command("api-server", help=t("Start the self-hosted MinerU parsing API service."))(api_server.api_server_cmd)
app.command(
"vlm-server",
context_settings=vlm_server.FORWARD_CONTEXT_SETTINGS,
diff --git a/mineru/model/runtime/device.py b/mineru/model/runtime/device.py
index 7e8326a0..c3ae139d 100644
--- a/mineru/model/runtime/device.py
+++ b/mineru/model/runtime/device.py
@@ -4,6 +4,7 @@
from __future__ import annotations
import importlib.util
+from dataclasses import dataclass
import os
from typing import Literal
@@ -53,6 +54,51 @@ 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:
+ selected = get_device()
+ kind, _, index_text = selected.partition(":")
+ if kind == "cpu":
+ return TorchDeviceSelection(reason="configured_cpu" if os.getenv("MINERU_DEVICE_MODE") else "torch_cpu")
+ import torch
+
+ if kind == "mps":
+ available = torch.backends.mps.is_available() and (not index_text or int(index_text) == 0)
+ else:
+ if kind == "npu":
+ import torch_npu
+
+ api = torch_npu.npu
+ elif kind in {"cuda", *PROBE_TORCH_DEVICE_APIS}:
+ api = getattr(torch, kind, None)
+ else:
+ api = None
+ available = api is not None and api.is_available()
+ if available:
+ index = int(index_text) if index_text else 0
+ available = index >= 0 and index < api.device_count()
+ if available:
+ return TorchDeviceSelection(selected, "torch_accelerator")
+ return TorchDeviceSelection(reason="torch_device_unavailable", warning=f"Torch device {selected!r} is unavailable")
+ except Exception as error:
+ return TorchDeviceSelection(reason="torch_device_error", warning=f"Torch device check failed: {error}")
+
+
def module_available(name: str) -> bool:
"""只检查模块是否安装,避免自动选择时初始化无关的重依赖。"""
try:
@@ -77,4 +123,12 @@ def resolve_small_model_backend(backend: str | None = None) -> Literal["onnx", "
return "onnx"
-__all__ = ["PROBE_TORCH_DEVICE_APIS", "TORCH_REQUIRED_MODULES", "get_device", "module_available", "resolve_small_model_backend"]
+__all__ = [
+ "PROBE_TORCH_DEVICE_APIS",
+ "TORCH_REQUIRED_MODULES",
+ "TorchDeviceSelection",
+ "get_device",
+ "module_available",
+ "resolve_small_model_backend",
+ "resolve_torch_device",
+]
diff --git a/mineru/model/runtime/hardware.py b/mineru/model/runtime/hardware.py
new file mode 100644
index 00000000..950eb889
--- /dev/null
+++ b/mineru/model/runtime/hardware.py
@@ -0,0 +1,201 @@
+"""只读聚合问题反馈所需的环境信息;不调用模型加载或自动校准。"""
+
+from __future__ import annotations
+
+from importlib import metadata
+import os
+from pathlib import Path
+import platform
+import sys
+from typing import TYPE_CHECKING, Any
+
+from .hardware_probe import run_probe
+from .hardware_system import collect_system_hardware
+from .hardware_types import GpuInfo, HardwareInfo, PackageInfo, RuntimeProbe
+from .onnx_calibration_cache import inspect_calibration_record
+
+if TYPE_CHECKING:
+ from .webgpu import WebGPUDevice
+ from .windows_gpu import GpuAdapter
+
+PACKAGE_NAMES = (
+ "mineru",
+ "docvortex",
+ "mineru-llama-cpp",
+ "mineru-vl-utils",
+ "torch",
+ "transformers",
+ "onnxruntime",
+ "onnxruntime-gpu",
+ "onnxruntime-directml",
+ "onnxruntime-ep-webgpu",
+ "vllm",
+ "lmdeploy",
+ "mlx-vlm",
+ "pypdfium2",
+)
+DEVICE_ENVIRONMENT = (
+ "MINERU_DEVICE_MODE",
+ "MINERU_LLAMA_CPP_BACKEND",
+ "MINERU_CPU_NUM_THREADS",
+ "MINERU_INTRA_OP_NUM_THREADS",
+ "MINERU_INTER_OP_NUM_THREADS",
+ "OMP_NUM_THREADS",
+ "MKL_NUM_THREADS",
+ "CUDA_VISIBLE_DEVICES",
+ "HIP_VISIBLE_DEVICES",
+ "ROCR_VISIBLE_DEVICES",
+ "ZE_AFFINITY_MASK",
+ "ASCEND_RT_VISIBLE_DEVICES",
+ "GGML_VK_VISIBLE_DEVICES",
+ "VK_DRIVER_FILES",
+ "VK_ICD_FILENAMES",
+ "VK_LOADER_VENDOR_ID_FILTER",
+ "VK_LOADER_DEVICE_ID_FILTER",
+ "MESA_VK_DEVICE_SELECT",
+ "GGML_VK_SERIALIZE_SUBMISSIONS",
+)
+
+
+def installed_packages() -> list[PackageInfo]:
+ """仅列出明确清单内已安装的发行包,不为了获取版本而导入重依赖。"""
+ result = []
+ for name in PACKAGE_NAMES:
+ try:
+ distribution = metadata.distribution(name)
+ except metadata.PackageNotFoundError:
+ continue
+ result.append(PackageInfo(name, distribution.version, str(distribution.locate_file(""))))
+ return result
+
+
+def config_summary() -> dict[str, Any]:
+ """按白名单输出设备相关配置及来源,远程地址只暴露是否启用。"""
+ from ...config import get_config, get_config_file_path, get_config_source
+
+ config = get_config()
+ fields = {
+ "model.small_backend": config.model.small_backend,
+ "model.onnx_device": config.model.onnx_device,
+ "model.vlm.engine": config.model.vlm.engine,
+ }
+ return {
+ "config_file": get_config_file_path(),
+ "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},
+ }
+
+
+def merge_gpu_inventory(gpus: list[GpuInfo], probe: RuntimeProbe) -> None:
+ """按明确身份补充原生类型和显存;无法唯一匹配的多卡库存不猜测归属。"""
+ if probe.status != "ok":
+ return
+ vendors = {0x8086: "Intel", 0x10DE: "NVIDIA", 0x1002: "AMD"}
+ for row in probe.data.get("devices", []):
+ vendor, chip = row.get("vendor_id"), row.get("device_id")
+ if vendor is None or chip is None:
+ continue
+ identity = f"0x{vendor:04x}:0x{chip:04x}"
+ matches = [gpu for gpu in gpus if gpu.device_id == identity]
+ name = row.get("name")
+ if len(matches) > 1:
+ matches = [gpu for gpu in matches if gpu.name == name]
+ if len(matches) != 1:
+ continue
+ kind = row.get("kind") or {1: "integrated", 2: "discrete", 3: "virtual"}.get(row.get("device_type"), "unknown")
+ if matches:
+ target = matches[0]
+ target.name = target.name or name
+ target.kind = kind
+ else:
+ target = GpuInfo(
+ name=name, vendor=vendors.get(vendor, hex(vendor)), device_id=identity, kind=kind, source=probe.name
+ )
+ gpus.append(target)
+ for attribute in ("dedicated_memory_bytes", "shared_memory_bytes"):
+ if row.get(attribute) is not None:
+ setattr(target, attribute, row[attribute])
+
+
+def _calibration_adapters(probes: list[RuntimeProbe]) -> tuple[GpuAdapter | WebGPUDevice, ...] | None:
+ """从隔离探测结果重建纯数据描述,不在报告进程初始化 ORT 或驱动。"""
+ from .webgpu import WebGPUDevice
+ from .windows_gpu import GpuAdapter
+
+ onnx = next((probe for probe in probes if probe.name == "onnx"), None)
+ if onnx is None or onnx.status != "ok" or "adapters" not in onnx.data:
+ return None
+ rows = onnx.data["adapters"]
+ if "selected_adapter" in onnx.data:
+ rows = [onnx.data["selected_adapter"]] if onnx.data["selected_adapter"] is not None else []
+ if onnx.data.get("backend") == "dml":
+ return tuple(GpuAdapter(**row) for row in rows)
+ return tuple(WebGPUDevice(**row) for row in rows)
+
+
+def collect_hardware_info() -> HardwareInfo:
+ """汇总静态信息及有界运行时探测,单项失败保留其余诊断内容。"""
+ from ...version import __version__
+
+ native = collect_system_hardware()
+ packages = installed_packages()
+ names = {package.name for package in packages}
+ runtime_names = ["selection", "torch", "onnx"]
+ if "mineru-llama-cpp" in names:
+ runtime_names.append("llama-cpp")
+ runtime_names.extend(name for name in ("vllm", "lmdeploy", "mlx-vlm") if name in names)
+ if sys.platform in {"win32", "linux"}:
+ runtime_names.append("dxgi" if sys.platform == "win32" else "vulkan")
+ probes = [run_probe(name) for name in runtime_names]
+ for probe in probes:
+ if probe.name in {"vulkan", "dxgi"}:
+ merge_gpu_inventory(native.gpus, probe)
+ if probe.status in {"error", "timeout"}:
+ native.warnings.append(f"{probe.name}: {probe.error}")
+ if probe.data.get("adapter_error"):
+ native.warnings.append(f"ONNX adapter inventory is incomplete: {probe.data['adapter_error']}")
+ config = config_summary()
+ selection = next(probe for probe in probes if probe.name == "selection")
+ config["resolved"] = selection.data if selection.status == "ok" else None
+ calibration = inspect_calibration_record(_calibration_adapters(probes))
+ distribution = ""
+ if sys.platform == "linux":
+ try:
+ distribution = platform.freedesktop_os_release().get("PRETTY_NAME", "")
+ except OSError:
+ pass
+ return HardwareInfo(
+ system={
+ "name": platform.system(),
+ "release": platform.release(),
+ "version": platform.version(),
+ "os_version": platform.mac_ver()[0]
+ if sys.platform == "darwin"
+ else platform.win32_ver()[1]
+ if sys.platform == "win32"
+ else platform.release(),
+ "distribution": distribution,
+ "architecture": platform.machine(),
+ },
+ python={"version": platform.python_version(), "executable": sys.executable},
+ mineru={"version": __version__, "module_path": str(Path(__file__).resolve().parents[2] / "__init__.py")},
+ cpu=native.cpu,
+ memory=native.memory,
+ gpus=native.gpus,
+ packages=packages,
+ runtimes=probes,
+ effective_config=config,
+ calibration=calibration,
+ warnings=native.warnings,
+ )
+
+
+__all__ = [
+ "DEVICE_ENVIRONMENT",
+ "PACKAGE_NAMES",
+ "collect_hardware_info",
+ "config_summary",
+ "installed_packages",
+ "merge_gpu_inventory",
+]
diff --git a/mineru/model/runtime/hardware_probe.py b/mineru/model/runtime/hardware_probe.py
new file mode 100644
index 00000000..65daafc5
--- /dev/null
+++ b/mineru/model/runtime/hardware_probe.py
@@ -0,0 +1,222 @@
+"""隔离运行时导入和原生设备探测;不在模块导入时读取配置或初始化模型。"""
+
+from __future__ import annotations
+
+from contextlib import redirect_stdout
+from dataclasses import asdict
+import importlib
+import importlib.util
+import json
+import subprocess
+import sys
+from typing import Any
+
+from .hardware_types import RuntimeProbe
+
+PROBE_MARKER = "MINERU_HARDWARE_RESULT="
+PROBE_TIMEOUT_SECONDS = 15
+
+
+def _torch_probe() -> dict[str, Any]:
+ """只查询 Torch 版本、可用性和设备属性,不创建张量或模型。"""
+ import torch
+
+ from .device import PROBE_TORCH_DEVICE_APIS, resolve_torch_device
+
+ backends: dict[str, Any] = {}
+ for name in ("cuda", "mps", "npu", *PROBE_TORCH_DEVICE_APIS):
+ try:
+ if name == "mps":
+ available = torch.backends.mps.is_available()
+ backends[name] = {"available": available}
+ continue
+ if name == "npu":
+ if importlib.util.find_spec("torch_npu") is None:
+ continue
+ api = importlib.import_module("torch_npu").npu
+ else:
+ api = getattr(torch, name, None)
+ if api is None:
+ continue
+ available = bool(api.is_available())
+ devices: list[dict[str, Any]] = []
+ if available:
+ for index in range(api.device_count()):
+ entry: dict[str, Any] = {"index": index}
+ if hasattr(api, "get_device_name"):
+ entry["name"] = api.get_device_name(index)
+ if hasattr(api, "get_device_properties"):
+ properties = api.get_device_properties(index)
+ entry["total_memory_bytes"] = getattr(properties, "total_memory", None)
+ devices.append(entry)
+ backends[name] = {"available": available, "devices": devices}
+ except Exception as error:
+ backends[name] = {"available": None, "error": str(error)}
+ selected = resolve_torch_device()
+ return {
+ "version": torch.__version__,
+ "module_path": torch.__file__,
+ "cuda_build": torch.version.cuda,
+ "rocm_build": getattr(torch.version, "hip", None),
+ "backends": backends,
+ "selected_device": asdict(selected),
+ }
+
+
+def _onnx_probe() -> dict[str, Any]:
+ """检查 ORT provider 和适配器库存,不调用会触发校准的设备选择。"""
+ import onnxruntime as ort
+
+ result: dict[str, Any] = {
+ "version": ort.__version__,
+ "module_path": ort.__file__,
+ "providers": ort.get_available_providers(),
+ }
+ if sys.platform == "win32":
+ from .windows_gpu import discover_gpus, preferred_gpu
+
+ adapters = discover_gpus()
+ selected = preferred_gpu(adapters)
+ result["backend"] = "dml"
+ result["adapters"] = [asdict(adapter) for adapter in adapters]
+ result["selected_adapter"] = asdict(selected) if selected is not None else None
+ elif sys.platform == "linux":
+ from .webgpu import discover_webgpu_devices, select_webgpu_device
+
+ try:
+ adapters = discover_webgpu_devices()
+ selected = select_webgpu_device(adapters)
+ result.update(backend="webgpu", adapters=[asdict(adapter) for adapter in adapters])
+ result["selected_adapter"] = asdict(selected) if selected is not None else None
+ except Exception as error:
+ result["adapter_error"] = str(error)
+ return result
+
+
+def _selection_probe() -> dict[str, Any]:
+ """解析有效后端组合,只读配置而不进行推荐或模型选型。"""
+ from ...config import get_config
+ from ..vlm.selector import resolve_vlm_engine
+ from .device import resolve_small_model_backend
+
+ config = get_config()
+ return {
+ "small_backend": resolve_small_model_backend(),
+ "vlm_engine": "http-client" if config.model.vlm.server_url else resolve_vlm_engine(config.model.vlm.engine),
+ }
+
+
+def probe_runtime(name: str) -> RuntimeProbe:
+ """子进程内执行显式探测分支,将局部导入异常变成结构化结果。"""
+ modules = {"torch": "torch", "onnx": "onnxruntime", "vllm": "vllm", "lmdeploy": "lmdeploy", "mlx-vlm": "mlx_vlm"}
+ try:
+ if name in modules and importlib.util.find_spec(modules[name]) is None:
+ return RuntimeProbe(name, "not_installed")
+ if name == "torch":
+ data = _torch_probe()
+ elif name == "onnx":
+ data = _onnx_probe()
+ elif name == "selection":
+ data = _selection_probe()
+ elif name == "llama-cpp":
+ from .llama_probe import probe_devices
+
+ if importlib.util.find_spec("mineru_llama_cpp") is None:
+ return RuntimeProbe(name, "not_installed")
+ if sys.platform == "darwin":
+ module = importlib.import_module("mineru_llama_cpp")
+ data = {"module_path": module.__file__, "backend": "platform_native"}
+ else:
+ data = {"devices": [asdict(device) for device in probe_devices()]}
+ elif name == "vulkan":
+ from .vulkan import enumerate_vulkan_devices
+
+ data = {"devices": [asdict(device) for device in enumerate_vulkan_devices()]}
+ elif name == "dxgi":
+ from .windows_gpu import inspect_gpus
+
+ data = {"devices": inspect_gpus()}
+ elif name in modules:
+ module = importlib.import_module(modules[name])
+ data = {"module_path": module.__file__, "version": getattr(module, "__version__", None)}
+ else:
+ raise ValueError(f"Unknown hardware probe: {name}")
+ return RuntimeProbe(name, "ok", data)
+ except Exception as error:
+ return RuntimeProbe(name, "error", error=f"{type(error).__name__}: {error}")
+
+
+def _decode_result(output: str) -> dict[str, Any]:
+ """从原生库输出中读取独立的结果标记,拒绝缺失或畸形的协议数据。"""
+ line = next((line for line in reversed(output.splitlines()) if line.startswith(PROBE_MARKER)), None)
+ if line is None:
+ raise ValueError("Hardware probe did not return a result")
+ result = json.loads(line.removeprefix(PROBE_MARKER))
+ if not isinstance(result, dict):
+ raise ValueError("Hardware probe returned an invalid result")
+ return result
+
+
+def run_probe(name: str) -> RuntimeProbe:
+ """为每项运行时检查启动有超时保护的独立进程,失败不阻断其他信息采集。"""
+ try:
+ process = subprocess.run(
+ [sys.executable, "-m", "mineru.model.runtime.hardware_probe", name],
+ capture_output=True,
+ text=True,
+ encoding="utf-8",
+ errors="replace",
+ timeout=PROBE_TIMEOUT_SECONDS,
+ creationflags=subprocess.CREATE_NO_WINDOW if sys.platform == "win32" else 0,
+ )
+ if process.returncode:
+ return RuntimeProbe(name, "error", error=f"Probe exited {process.returncode}: {process.stderr[-1000:]}")
+ return RuntimeProbe(**_decode_result(process.stdout))
+ except subprocess.TimeoutExpired:
+ return RuntimeProbe(name, "timeout", error=f"Probe exceeded {PROBE_TIMEOUT_SECONDS} seconds")
+ except (OSError, ValueError, TypeError) as error:
+ return RuntimeProbe(name, "error", error=str(error))
+
+
+def run_detection() -> dict[str, Any]:
+ """隔离命令的推荐过程,原生日志与下载进度进入 stderr,stdout 只交付结果。"""
+ process = subprocess.run(
+ [sys.executable, "-m", "mineru.model.runtime.hardware_probe", "detect"],
+ stdout=subprocess.PIPE,
+ text=True,
+ encoding="utf-8",
+ errors="replace",
+ )
+ for line in process.stdout.splitlines():
+ if not line.startswith(PROBE_MARKER):
+ print(line, file=sys.stderr)
+ result = _decode_result(process.stdout)
+ if process.returncode or "error" in result:
+ raise ValueError(result.get("error", "Hardware detection failed"))
+ return result
+
+
+def main() -> None:
+ """私有工作进程入口,结果标记之外的 Python 输出全部重定向到 stderr。"""
+ name = sys.argv[1] if len(sys.argv) == 2 else ""
+ failed = False
+ with redirect_stdout(sys.stderr):
+ if name == "detect":
+ from .tier_recommendation import recommend_tiers
+
+ try:
+ result = asdict(recommend_tiers())
+ except Exception as error:
+ result = {"error": str(error)}
+ failed = True
+ else:
+ result = asdict(probe_runtime(name))
+ print(PROBE_MARKER + json.dumps(result, ensure_ascii=False), flush=True)
+ if failed:
+ raise SystemExit(1)
+
+
+__all__ = ["PROBE_TIMEOUT_SECONDS", "probe_runtime", "run_detection", "run_probe"]
+
+if __name__ == "__main__":
+ main()
diff --git a/mineru/model/runtime/hardware_system.py b/mineru/model/runtime/hardware_system.py
new file mode 100644
index 00000000..437120ed
--- /dev/null
+++ b/mineru/model/runtime/hardware_system.py
@@ -0,0 +1,307 @@
+"""标准库与平台原生工具实现的只读 CPU、内存和系统显卡库存采集。"""
+
+from __future__ import annotations
+
+import csv
+import io
+import json
+import os
+from pathlib import Path
+import platform
+import re
+import shlex
+import shutil
+import subprocess
+from typing import Any
+
+from .cpu_threads import effective_cpu_count
+from .hardware_types import GpuInfo, SystemHardware
+
+_VENDORS = {"0x8086": "Intel", "0x10de": "NVIDIA", "0x1002": "AMD"}
+
+
+def _read(path: Path) -> str | None:
+ """读取可选系统字段,缺失或无权限时保留未知而不填充伪造值。"""
+ try:
+ return path.read_text(encoding="utf-8").strip()
+ except OSError:
+ return None
+
+
+def _number(value: Any) -> float | None:
+ """解析平台报告的数值,空值、无效值和负数均保持未知。"""
+ try:
+ number = float(value)
+ return number if number >= 0 and number < float("inf") else None
+ except (ValueError, TypeError):
+ return None
+
+
+def _integer(value: Any) -> int | None:
+ """统一平台核数和字节值,避免对未知数值执行整型转换。"""
+ value = _number(value)
+ return int(value) if value is not None else None
+
+
+def _command(command: list[str], report: SystemHardware, *, partial: bool = False) -> str | None:
+ """有界运行只读平台工具,局部错误写入报告而不阻断后续采集。"""
+ try:
+ result = subprocess.run(command, capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=15)
+ if result.returncode:
+ report.warnings.append(f"{command[0]} exited {result.returncode}: {result.stderr.strip()[:300]}")
+ return result.stdout if partial else None
+ return result.stdout
+ except (OSError, subprocess.TimeoutExpired) as error:
+ report.warnings.append(f"{command[0]} unavailable: {error}")
+ return None
+
+
+def _memory_size(value: Any) -> int | None:
+ """解析平台给出的内存容量单位,不把未知或统一内存自动解释为独立显存。"""
+ match = re.search(r"([\d.]+)\s*(bytes|[KMGT]i?B)\b", str(value), re.IGNORECASE)
+ if not match:
+ return None
+ units = {"bytes": 1, "kb": 1024, "mb": 1024**2, "gb": 1024**3, "tb": 1024**4}
+ return int(float(match[1]) * units[match[2].lower().replace("ib", "b")])
+
+
+def _linux_cpu(report: SystemHardware, proc_root: Path, sys_root: Path) -> None:
+ """从 Linux 处理器拓扑、配额和频率节点读取事实,保留异构或受限环境的未知值。"""
+ content = _read(proc_root / "cpuinfo")
+ if content is None:
+ report.warnings.append("Cannot read /proc/cpuinfo; CPU identification is incomplete")
+ records: list[dict[str, str]] = []
+ for block in (content or "").split("\n\n"):
+ record = dict(line.split(":", 1) for line in block.splitlines() if ":" in line)
+ records.append({key.strip(): value.strip() for key, value in record.items()})
+ report.cpu.model = next(
+ (r.get("model name") or r.get("Hardware") for r in records if r.get("model name") or r.get("Hardware")), None
+ )
+ topology = {(r["physical id"], r["core id"]) for r in records if "physical id" in r and "core id" in r}
+ if topology:
+ report.cpu.physical_cores = len(topology)
+ frequencies = [_number(r.get("cpu MHz")) for r in records]
+ current = [value for value in frequencies if value is not None]
+ if current:
+ report.cpu.current_mhz = sum(current) / len(current)
+ for attribute, node in (("base_mhz", "base_frequency"), ("max_mhz", "cpuinfo_max_freq")):
+ values = [_number(_read(path)) for path in (sys_root / "devices/system/cpu").glob(f"cpu[0-9]*/cpufreq/{node}")]
+ known = [value for value in values if value is not None]
+ if known:
+ setattr(report.cpu, attribute, max(known) / 1000)
+ memory = {}
+ for line in (_read(proc_root / "meminfo") or "").splitlines():
+ key, _, raw = line.partition(":")
+ memory[key] = _memory_size(raw)
+ report.memory.total_bytes = memory.get("MemTotal")
+ report.memory.available_bytes = memory.get("MemAvailable")
+
+
+def _linux_gpus(report: SystemHardware, sys_root: Path) -> None:
+ """列出系统 PCI 显卡并补充驱动信息,不只保留运行时优先选择的显卡。"""
+ root = sys_root / "bus/pci/devices"
+ if not root.exists():
+ report.warnings.append("PCI inventory is unavailable; GPU inventory may be incomplete")
+ return
+ for path in sorted(root.iterdir()):
+ if not (_read(path / "class") or "").startswith("0x03"):
+ continue
+ vendor, chip = _read(path / "vendor"), _read(path / "device")
+ driver = path / "driver"
+ vram = _integer(_read(path / "mem_info_vram_total"))
+ report.gpus.append(
+ GpuInfo(
+ vendor=_VENDORS.get(vendor or "", vendor),
+ device_id=f"{vendor}:{chip}" if vendor and chip else None,
+ bus_id=path.name,
+ driver=driver.resolve().name if driver.exists() else None,
+ dedicated_memory_bytes=vram,
+ source="sysfs",
+ )
+ )
+ executable = shutil.which("lspci")
+ if executable:
+ output = _command([executable, "-D", "-mm"], report)
+ for line in (output or "").splitlines():
+ columns = shlex.split(line)
+ if len(columns) < 4:
+ continue
+ for gpu in report.gpus:
+ if gpu.bus_id == columns[0]:
+ gpu.name = f"{columns[2]} {columns[3]}"
+
+
+def parse_macos_displays(payload: dict[str, Any], report: SystemHardware, architecture: str) -> None:
+ """解析系统显示设备 JSON,只保留显卡属性,不包含显示器序列号等无关数据。"""
+ for row in payload.get("SPDisplaysDataType", []):
+ vendor = row.get("spdisplays_vendor", "").removeprefix("sppci_vendor_") or None
+ unified = vendor == "Apple" and architecture in {"arm64", "aarch64"}
+ integrated = unified or row.get("spdisplays_integrated") == "spdisplays_yes"
+ memory = _memory_size(row.get("spdisplays_vram") or row.get("spdisplays_vram_shared"))
+ report.gpus.append(
+ GpuInfo(
+ name=row.get("sppci_model") or row.get("_name"),
+ vendor=vendor,
+ device_id=row.get("spdisplays_device-id"),
+ kind="integrated" if integrated else "unknown",
+ bus_id=row.get("sppci_bus"),
+ driver=row.get("spdisplays_driver_version"),
+ dedicated_memory_bytes=None if unified or row.get("spdisplays_vram_shared") else memory,
+ shared_memory_bytes=report.memory.total_bytes
+ if unified
+ else memory
+ if row.get("spdisplays_vram_shared")
+ else None,
+ unified_memory=unified,
+ source="system_profiler",
+ )
+ )
+
+
+def _macos_hardware(report: SystemHardware) -> None:
+ """通过 sysctl、vm_stat 与 system_profiler 获取 macOS 原生报告。"""
+ keys = [
+ "machdep.cpu.brand_string",
+ "hw.physicalcpu",
+ "hw.logicalcpu",
+ "hw.cpufrequency",
+ "hw.cpufrequency_max",
+ "hw.memsize",
+ "hw.pagesize",
+ ]
+ output = _command(["sysctl", *keys], report, partial=True)
+ values = dict(line.split(": ", 1) for line in (output or "").splitlines() if ": " in line)
+ report.cpu.model = values.get("machdep.cpu.brand_string")
+ report.cpu.physical_cores = _integer(values.get("hw.physicalcpu"))
+ report.cpu.logical_cores = _integer(values.get("hw.logicalcpu")) or report.cpu.logical_cores
+ for attribute, key in (("base_mhz", "hw.cpufrequency"), ("max_mhz", "hw.cpufrequency_max")):
+ value = _number(values.get(key))
+ if value is not None:
+ setattr(report.cpu, attribute, value / 1_000_000)
+ report.memory.total_bytes = _integer(values.get("hw.memsize"))
+ vm = _command(["vm_stat"], report)
+ page_size = _integer(values.get("hw.pagesize"))
+ if vm and page_size:
+ pages = dict(re.findall(r"^(Pages (?:free|inactive|speculative)):\s+(\d+)", vm, re.MULTILINE))
+ if len(pages) == 3:
+ report.memory.available_bytes = sum(int(value) for value in pages.values()) * page_size
+ displays = _command(["system_profiler", "SPDisplaysDataType", "-json"], report)
+ if displays:
+ parse_macos_displays(json.loads(displays), report, platform.machine())
+
+
+def parse_windows_hardware(payload: dict[str, Any], report: SystemHardware) -> None:
+ """解析 CIM 结果,AdapterRAM 的 32 位限制不用于宣称独立显存容量。"""
+ cpus = payload.get("cpus") or []
+ if isinstance(cpus, dict):
+ cpus = [cpus]
+ if cpus:
+ report.cpu.model = "; ".join(dict.fromkeys(row.get("Name", "").strip() for row in cpus)) or None
+ for attribute, key in (("physical_cores", "NumberOfCores"), ("logical_cores", "NumberOfLogicalProcessors")):
+ counts = [_integer(row.get(key)) for row in cpus]
+ if all(value is not None for value in counts):
+ setattr(report.cpu, attribute, sum(counts))
+ for attribute, key in (("current_mhz", "CurrentClockSpeed"), ("max_mhz", "MaxClockSpeed")):
+ frequencies = [_number(row.get(key)) for row in cpus]
+ known = [value for value in frequencies if value is not None]
+ if known:
+ setattr(report.cpu, attribute, max(known))
+ memory = payload.get("memory") or {}
+ for attribute, key in (("total_bytes", "TotalVisibleMemorySize"), ("available_bytes", "FreePhysicalMemory")):
+ amount = _integer(memory.get(key))
+ if amount is not None:
+ setattr(report.memory, attribute, amount * 1024)
+ rows = payload.get("gpus") or []
+ if isinstance(rows, dict):
+ rows = [rows]
+ for row in rows:
+ identity = re.search(r"VEN_([0-9A-F]{4})&DEV_([0-9A-F]{4})", row.get("PNPDeviceID") or "", re.IGNORECASE)
+ report.gpus.append(
+ GpuInfo(
+ name=row.get("Name"),
+ vendor=row.get("AdapterCompatibility"),
+ device_id=f"0x{identity[1].lower()}:0x{identity[2].lower()}" if identity else None,
+ driver=row.get("DriverVersion"),
+ source="cim",
+ )
+ )
+
+
+def _windows_hardware(report: SystemHardware) -> None:
+ """仅使用系统自带 PowerShell/CIM 采集,不依赖额外 WMI Python 包。"""
+ queries = {
+ "cpus": "Win32_Processor | Select-Object Name,NumberOfCores,NumberOfLogicalProcessors,CurrentClockSpeed,MaxClockSpeed",
+ "memory": "Win32_OperatingSystem | Select-Object TotalVisibleMemorySize,FreePhysicalMemory",
+ "gpus": "Win32_VideoController | Select-Object Name,AdapterCompatibility,PNPDeviceID,DriverVersion",
+ }
+ payload: dict[str, Any] = {}
+ for key, query in queries.items():
+ script = (
+ "[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new(); $ErrorActionPreference = 'Stop'; "
+ f"Get-CimInstance {query} | ConvertTo-Json -Depth 4 -Compress"
+ )
+ output = _command(["powershell.exe", "-NoProfile", "-NonInteractive", "-Command", script], report)
+ if output:
+ try:
+ payload[key] = json.loads(output.lstrip("\ufeff"))
+ except ValueError as error:
+ report.warnings.append(f"CIM {key} returned invalid data: {error}")
+ parse_windows_hardware(payload, report)
+
+
+def _nvidia_details(report: SystemHardware) -> None:
+ """利用可选厂商工具补充名称、驱动和显存,按 PCI 地址匹配以免串卡。"""
+ executable = shutil.which("nvidia-smi")
+ if not executable:
+ return
+ output = _command(
+ [executable, "--query-gpu=pci.bus_id,name,driver_version,memory.total", "--format=csv,noheader,nounits"], report
+ )
+ for row in csv.reader(io.StringIO(output or "")):
+ if len(row) != 4:
+ continue
+ bus, name, driver, memory = (value.strip() for value in row)
+ matching = [gpu for gpu in report.gpus if gpu.bus_id and gpu.bus_id.lower()[-10:] == bus.lower()[-10:]]
+ if not matching:
+ matching = [gpu for gpu in report.gpus if gpu.bus_id is None and gpu.name == name]
+ if not matching:
+ gpu = GpuInfo(name=name, vendor="NVIDIA", bus_id=bus, source="nvidia-smi")
+ report.gpus.append(gpu)
+ matching = [gpu]
+ if len(matching) == 1:
+ gpu = matching[0]
+ gpu.name, gpu.driver, gpu.bus_id = name, driver, bus
+ amount = _number(memory)
+ if amount is not None:
+ gpu.dedicated_memory_bytes = int(amount * 1024**2)
+
+
+def collect_system_hardware() -> SystemHardware:
+ """分项采集本机只读硬件事实,未支持平台或局部失败不会伪造空库存。"""
+ report = SystemHardware()
+ report.cpu.logical_cores = os.cpu_count()
+ try:
+ report.cpu.available_cores = effective_cpu_count()
+ except OSError as error:
+ report.warnings.append(f"CPU availability check failed: {error}")
+ system = platform.system()
+ try:
+ if system == "Linux":
+ try:
+ _linux_cpu(report, Path("/proc"), Path("/sys"))
+ except (OSError, ValueError, TypeError) as error:
+ report.warnings.append(f"Linux CPU/memory information is incomplete: {error}")
+ _linux_gpus(report, Path("/sys"))
+ elif system == "Darwin":
+ _macos_hardware(report)
+ elif system == "Windows":
+ _windows_hardware(report)
+ else:
+ report.warnings.append(f"Native hardware inventory is unsupported on {system}")
+ except (OSError, ValueError, TypeError) as error:
+ report.warnings.append(f"Native hardware inventory is incomplete: {error}")
+ _nvidia_details(report)
+ return report
+
+
+__all__ = ["collect_system_hardware", "parse_macos_displays", "parse_windows_hardware"]
diff --git a/mineru/model/runtime/hardware_types.py b/mineru/model/runtime/hardware_types.py
new file mode 100644
index 00000000..de6af3a2
--- /dev/null
+++ b/mineru/model/runtime/hardware_types.py
@@ -0,0 +1,95 @@
+"""硬件诊断的可序列化报告类型,不导入推理运行时。"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from typing import Any
+
+from .onnx_calibration_cache import CalibrationInfo
+
+
+@dataclass
+class CpuInfo:
+ """区分机器核数、进程可用核数和不同来源的频率。"""
+
+ model: str | None = None
+ physical_cores: int | None = None
+ logical_cores: int | None = None
+ available_cores: int | None = None
+ base_mhz: float | None = None
+ current_mhz: float | None = None
+ max_mhz: float | None = None
+
+
+@dataclass
+class MemoryInfo:
+ """内存统一以字节表示,未知值不当作零。"""
+
+ total_bytes: int | None = None
+ available_bytes: int | None = None
+
+
+@dataclass
+class GpuInfo:
+ """系统发现的物理或虚拟显卡,不代表当前运行时一定可用。"""
+
+ name: str | None = None
+ vendor: str | None = None
+ device_id: str | None = None
+ kind: str = "unknown"
+ bus_id: str | None = None
+ driver: str | None = None
+ dedicated_memory_bytes: int | None = None
+ shared_memory_bytes: int | None = None
+ unified_memory: bool | None = None
+ source: str = "unknown"
+
+
+@dataclass
+class SystemHardware:
+ """平台原生只读采集结果和局部失败说明。"""
+
+ cpu: CpuInfo = field(default_factory=CpuInfo)
+ memory: MemoryInfo = field(default_factory=MemoryInfo)
+ gpus: list[GpuInfo] = field(default_factory=list)
+ warnings: list[str] = field(default_factory=list)
+
+
+@dataclass(frozen=True)
+class PackageInfo:
+ """已安装发行包的版本和安装位置,不以导入成功代替安装状态。"""
+
+ name: str
+ version: str
+ location: str
+
+
+@dataclass(frozen=True)
+class RuntimeProbe:
+ """隔离子进程的探测结果,保留未安装、超时及导入失败的区别。"""
+
+ name: str
+ status: str
+ data: dict[str, Any] = field(default_factory=dict)
+ error: str | None = None
+
+
+@dataclass(frozen=True)
+class HardwareInfo:
+ """供文本和 JSON 共用的完整问题反馈报告。"""
+
+ system: dict[str, str]
+ python: dict[str, str]
+ mineru: dict[str, str]
+ cpu: CpuInfo
+ memory: MemoryInfo
+ gpus: list[GpuInfo]
+ packages: list[PackageInfo]
+ runtimes: list[RuntimeProbe]
+ effective_config: dict[str, Any]
+ calibration: CalibrationInfo
+ warnings: list[str]
+ schema_version: int = 1
+
+
+__all__ = ["CpuInfo", "GpuInfo", "HardwareInfo", "MemoryInfo", "PackageInfo", "RuntimeProbe", "SystemHardware"]
diff --git a/mineru/model/runtime/llama_device.py b/mineru/model/runtime/llama_device.py
index 87a654d1..6552a6d1 100644
--- a/mineru/model/runtime/llama_device.py
+++ b/mineru/model/runtime/llama_device.py
@@ -122,7 +122,7 @@ def resolve_llama_device(
backend: str | None = None,
allow_download: bool = True,
) -> LlamaSelection:
- """自动模式只在没有原生可用独显时复用 ONNX;显式 CPU/GPU 设置优先。"""
+ """自动集显按小模型后端复用 Torch 可用性或 ONNX 选型;显式设备设置优先。"""
with _lock:
selection = _resolve(
n_gpu_layers=n_gpu_layers, device_names=device_names, backend=backend, allow_download=allow_download
@@ -162,17 +162,26 @@ def _resolve(
manual = requested != "auto" or n_gpu_layers is not None or device_names is not None
reason = "explicit_gpu" if manual else "discrete_gpu"
if not manual and not any(not d.integrated for d in inventory):
- from .onnx_device import resolve_onnx_device
-
- choice = resolve_onnx_device() if allow_download else resolve_onnx_device(allow_download=False)
- if choice.device != "gpu" or choice.adapter is None:
- return LlamaSelection("cpu", reason=f"onnx_{choice.reason}")
- matches = tuple(
- d for d in selected if (d.vendor_id, d.device_id) == (choice.adapter.vendor_id, choice.adapter.device_id)
- )
- if len(matches) != 1:
- return LlamaSelection("cpu", reason="onnx_gpu_identity_unconfirmed")
- selected, reason = matches, f"onnx_{choice.backend}_{choice.reason}"
+ from .device import resolve_small_model_backend, resolve_torch_device
+
+ if resolve_small_model_backend() == "torch":
+ torch_choice = resolve_torch_device()
+ if not torch_choice.accelerated:
+ return LlamaSelection("cpu", reason=torch_choice.reason)
+ # Torch 只提供加速可用性结论,物理设备仍由当前原生库存和绑定校验决定。
+ reason = "torch_accelerator"
+ else:
+ from .onnx_device import resolve_onnx_device
+
+ choice = resolve_onnx_device() if allow_download else resolve_onnx_device(allow_download=False)
+ if choice.device != "gpu" or choice.adapter is None:
+ return LlamaSelection("cpu", reason=f"onnx_{choice.reason}")
+ matches = tuple(
+ d for d in selected if (d.vendor_id, d.device_id) == (choice.adapter.vendor_id, choice.adapter.device_id)
+ )
+ if len(matches) != 1:
+ return LlamaSelection("cpu", reason="onnx_gpu_identity_unconfirmed")
+ selected, reason = matches, f"onnx_{choice.backend}_{choice.reason}"
serialized_devices = tuple(d for d in selected if needs_serialized_submissions(d))
if serialized_devices and len(serialized_devices) != len(selected):
if manual:
diff --git a/mineru/model/runtime/onnx_calibration_cache.py b/mineru/model/runtime/onnx_calibration_cache.py
index 28e91293..c47cb062 100644
--- a/mineru/model/runtime/onnx_calibration_cache.py
+++ b/mineru/model/runtime/onnx_calibration_cache.py
@@ -1,8 +1,8 @@
-"""保存可验证的 OCR 校准证据,供服务启动时只读推荐档位。"""
+"""保存可验证的 OCR 校准证据,供服务启动推荐和只读诊断复用。"""
from __future__ import annotations
-from dataclasses import asdict
+from dataclasses import asdict, dataclass
from importlib.metadata import PackageNotFoundError, version
import json
import os
@@ -34,6 +34,47 @@ class CalibrationRecord(BaseModel):
model_sha256: str
+@dataclass(frozen=True)
+class CalibrationInfo:
+ """只读校准摘要;未知环境匹配状态与明确不匹配分开表达。"""
+
+ path: str
+ status: str
+ matches_environment: bool | None = None
+ decision_valid: bool | None = None
+ outputs_match: bool | None = None
+ cpu_elapsed: float | None = None
+ gpu_elapsed: float | None = None
+ ratio: float | None = None
+ threshold: float | None = None
+ model_sha256: str | None = None
+ error: str | None = None
+
+
+def inspect_calibration_record(adapters: tuple[GpuAdapter | WebGPUDevice, ...] | None = None) -> CalibrationInfo:
+ """读取记录并与已探测的物理设备比较,不创建目录、不测速或修改文件。"""
+ path = calibration_record_path()
+ try:
+ record = CalibrationRecord.model_validate_json(path.read_text(encoding="utf-8"))
+ except FileNotFoundError:
+ return CalibrationInfo(str(path), "missing")
+ except (OSError, ValueError) as error:
+ return CalibrationInfo(str(path), "invalid", error=str(error))
+ matches = None if adapters is None else any(record.fingerprint == _fingerprint(adapter) for adapter in adapters)
+ return CalibrationInfo(
+ str(path),
+ "present",
+ matches,
+ record.decision_valid,
+ record.outputs_match,
+ record.cpu_elapsed,
+ record.gpu_elapsed,
+ record.gpu_elapsed / record.cpu_elapsed,
+ record.threshold,
+ record.model_sha256,
+ )
+
+
def calibration_record_path() -> Path:
"""记录随当前配置文件隔离,读取时不创建目录或锁文件。"""
from ...config import get_config_file_path
@@ -139,4 +180,11 @@ def calibrated_gpu_is_faster(adapter: GpuAdapter | WebGPUDevice, threshold: floa
return False
-__all__ = ["calibrated_gpu_is_faster", "calibration_record_path", "invalidate_calibration_record", "save_calibration_record"]
+__all__ = [
+ "CalibrationInfo",
+ "calibrated_gpu_is_faster",
+ "calibration_record_path",
+ "inspect_calibration_record",
+ "invalidate_calibration_record",
+ "save_calibration_record",
+]
diff --git a/mineru/model/runtime/onnx_device.py b/mineru/model/runtime/onnx_device.py
index add2c50b..1df944d4 100644
--- a/mineru/model/runtime/onnx_device.py
+++ b/mineru/model/runtime/onnx_device.py
@@ -40,6 +40,21 @@ _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)
@@ -127,7 +142,7 @@ 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:
- """Resolve at first model use; imports and diagnostic commands never call this function."""
+ """在首次模型使用或达到 Basic 的 API 自动推荐时选型;导入和诊断命令不调用。"""
from ...config import get_config, get_config_file_path, get_config_source
requested = get_config().model.onnx_device
@@ -184,6 +199,7 @@ __all__ = [
"ONNX_GPU_TIME_RATIO_THRESHOLDS",
"OnnxSelection",
"choose_gpu",
+ "cached_onnx_device",
"confirm_gpu_session",
"metacommands_enabled",
"resolve_onnx_device",
diff --git a/mineru/model/runtime/tier_recommendation.py b/mineru/model/runtime/tier_recommendation.py
index 6a50c8ff..874747ea 100644
--- a/mineru/model/runtime/tier_recommendation.py
+++ b/mineru/model/runtime/tier_recommendation.py
@@ -1,15 +1,47 @@
-"""通过静态设备事实与已有 OCR 校准,推荐 API 服务开放的档位集合。"""
+"""通过硬件初选与启动阶段的 OCR 设备校准,确定 API 服务开放档位。"""
from __future__ import annotations
from dataclasses import dataclass
import os
import sys
+from typing import TYPE_CHECKING
from loguru import logger
from ...types import TIERS, Tier
from .cpu_threads import effective_cpu_count
+from .device import resolve_small_model_backend, resolve_torch_device
+from .onnx_calibration_cache import CalibrationInfo, inspect_calibration_record
+
+if TYPE_CHECKING:
+ from ...config import VlmConfig
+
+
+@dataclass(frozen=True)
+class CalibrationDecision:
+ """描述本次推荐中的校准状态,避免把设备可用性当成实测胜出。"""
+
+ status: str
+ reason: str
+ evidence: CalibrationInfo | None = None
+
+
+@dataclass(frozen=True)
+class TierRecommendation:
+ """API 自动启动和硬件命令共同消费的推荐报告。"""
+
+ ceiling: Tier
+ pdf_image_tiers: tuple[Tier, ...]
+ default_request_tier: Tier
+ reason: str
+ cpu_count: int
+ small_backend: str
+ vlm_engine: str
+ device: str
+ calibration: CalibrationDecision
+ warnings: tuple[str, ...] = ()
+ schema_version: int = 1
@dataclass(frozen=True)
@@ -86,7 +118,7 @@ def _advanced_gpu_reason() -> str | None:
def detect_tier_hardware() -> TierHardware:
- """探测失败时保守使用 CPU 条件,推荐过程不下载模型或保存配置。"""
+ """只读探测当前硬件与校准证据;失败时使用 CPU 条件,不下载模型或保存配置。"""
try:
count = effective_cpu_count()
except OSError as error:
@@ -100,17 +132,93 @@ def detect_tier_hardware() -> TierHardware:
return TierHardware(count, bool(reason), reason or "cpu")
-def recommend_tiers() -> frozenset[Tier]:
- """每次调用读取当前硬件事实;API 服务只在启动阶段调用一次。"""
- hardware = detect_tier_hardware()
+def recommend_tiers(*, vlm_config: VlmConfig | None = None) -> TierRecommendation:
+ """先分流实际小模型后端;Torch 免测速,ONNX 初选达标后同步完成既有选型。"""
+ from ...config import get_config
+ from ..vlm.selector import resolve_vlm_engine
+
+ settings = vlm_config if vlm_config is not None else get_config().model.vlm
+ settings.validate_environment()
+ small_backend = resolve_small_model_backend()
+ vlm_engine = "http-client" if settings.server_url else resolve_vlm_engine(settings.engine)
+ warnings: list[str] = []
+ device = "cpu"
+ calibration = CalibrationDecision("skipped", "not_required")
+ if small_backend == "torch":
+ choice = resolve_torch_device()
+ try:
+ count = effective_cpu_count()
+ except OSError as error:
+ count = 1
+ warnings.append(f"CPU availability discovery failed: {error}")
+ hardware = TierHardware(count, choice.accelerated, choice.reason)
+ device = choice.device
+ calibration = CalibrationDecision("skipped", "torch_backend")
+ if choice.warning:
+ warnings.append(choice.warning)
+ else:
+ hardware = detect_tier_hardware()
tiers = tiers_for_hardware(hardware)
+ if small_backend == "onnx" and "basic" in tiers and sys.platform in {"win32", "linux"}:
+ logger.info("Automatic API tier selection is resolving the ONNX device before finalizing tiers")
+ try:
+ from .onnx_device import cached_onnx_device, resolve_onnx_device
+
+ # 复用模型运行时的配置、锁和缓存;显式设备选择及不兼容 GPU 不强制测速。
+ cached = cached_onnx_device()
+ onnx_choice = resolve_onnx_device()
+ device = f"{onnx_choice.backend}:gpu" if onnx_choice.device == "gpu" else "cpu"
+ evidence = inspect_calibration_record((onnx_choice.adapter,) if onnx_choice.adapter is not None else None)
+ 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 in {"configured_cpu", "configured_gpu"}:
+ status = "reused" if evidence.matches_environment and evidence.decision_valid else "skipped"
+ calibration = CalibrationDecision(status, onnx_choice.reason, evidence)
+ except Exception as error:
+ logger.warning("Startup ONNX selection unavailable; recommending tiers from current evidence: {}", error)
+ warnings.append(f"ONNX selection unavailable: {error}")
+ calibration = CalibrationDecision("failed", "selection_unavailable")
+ # 校准会写入新证据或撤销旧证据,必须在发布能力前重新计算,不能等到下次启动。
+ hardware = detect_tier_hardware()
+ tiers = tiers_for_hardware(hardware)
+ if hardware.reason == "gpu_discovery_unavailable":
+ warnings.append("GPU discovery unavailable; using CPU recommendation rules")
logger.info(
"Recommended API tiers: {} (available CPUs: {}, reason: {})",
",".join(tier for tier in TIERS if tier in tiers),
hardware.cpu_count,
hardware.reason,
)
- return tiers
+ ordered = tuple(tier for tier in TIERS if tier in tiers)
+ default = next(tier for tier in ("standard", "basic", "flash") if tier in tiers)
+ return TierRecommendation(
+ ordered[-1],
+ ordered,
+ default,
+ hardware.reason,
+ hardware.cpu_count,
+ small_backend,
+ vlm_engine,
+ device,
+ calibration,
+ tuple(warnings),
+ )
-__all__ = ["TierHardware", "detect_tier_hardware", "recommend_tiers", "tiers_for_hardware"]
+__all__ = [
+ "CalibrationDecision",
+ "TierHardware",
+ "TierRecommendation",
+ "detect_tier_hardware",
+ "recommend_tiers",
+ "tiers_for_hardware",
+]
diff --git a/mineru/model/runtime/windows_gpu.py b/mineru/model/runtime/windows_gpu.py
index 2db1b7db..ca803c5f 100644
--- a/mineru/model/runtime/windows_gpu.py
+++ b/mineru/model/runtime/windows_gpu.py
@@ -173,4 +173,51 @@ def preferred_gpu(adapters: tuple[GpuAdapter, ...]) -> GpuAdapter | None:
return min(adapters, key=lambda item: (item.uma is not False, item.preference, item.index), default=None)
-__all__ = ["GpuAdapter", "discover_gpus", "preferred_gpu"]
+def inspect_gpus() -> list[dict[str, Any]]:
+ """诊断库存保留不支持 D3D12 的硬件,并读取 DXGI 的 64 位显存容量。"""
+ if sys.platform != "win32":
+ return []
+ dxgi = C.WinDLL("dxgi", use_last_error=True)
+ d3d = C.WinDLL("d3d12", use_last_error=True)
+ create = dxgi.CreateDXGIFactory1
+ create.argtypes = [C.POINTER(_Guid), C.POINTER(C.c_void_p)]
+ create.restype = C.c_int32
+ create_device = d3d.D3D12CreateDevice
+ create_device.argtypes = [C.c_void_p, C.c_int32, C.POINTER(_Guid), C.POINTER(C.c_void_p)]
+ create_device.restype = C.c_int32
+ factory = C.c_void_p()
+ _check(create(C.byref(_guid("770aae78-f26f-4dba-a829-253c83d1b387")), C.byref(factory)))
+ result: list[dict[str, Any]] = []
+ try:
+ enum = _method(factory, 12, C.c_int32, C.c_uint32, C.POINTER(C.c_void_p))
+ for index in range(64):
+ adapter = C.c_void_p()
+ hr = enum(factory, index, C.byref(adapter))
+ if hr & 0xFFFFFFFF == 0x887A0002:
+ break
+ _check(hr)
+ try:
+ desc = _description(adapter)
+ if desc.flags & 2:
+ continue
+ supported, uma = _architecture(adapter, create_device)
+ result.append(
+ {
+ "name": desc.name,
+ "vendor_id": desc.vendor,
+ "device_id": desc.device,
+ "luid": _luid(desc),
+ "d3d12_available": supported,
+ "kind": "unknown" if uma is None else "integrated" if uma else "discrete",
+ "dedicated_memory_bytes": desc.video_memory,
+ "shared_memory_bytes": desc.shared_memory,
+ }
+ )
+ finally:
+ _release(adapter)
+ finally:
+ _release(factory)
+ return result
+
+
+__all__ = ["GpuAdapter", "discover_gpus", "inspect_gpus", "preferred_gpu"]
diff --git a/mineru/parser/api_server.py b/mineru/parser/api_server.py
index 9a87b762..9ccb6a92 100644
--- a/mineru/parser/api_server.py
+++ b/mineru/parser/api_server.py
@@ -1811,7 +1811,9 @@ def create_app(
Directory for uploaded files and parse artifacts.
tiers:
Exact non-empty set of PDF/image request tiers. ``None`` recommends
- a capability ceiling from hardware and existing OCR calibration evidence.
+ a capability ceiling from the effective small-model backend and hardware.
+ Torch validates acceleration without OCR calibration; ONNX may calibrate
+ before finalizing a preliminary ceiling of Basic or higher on Windows/Linux.
Native documents always use Flash independently of this set.
concurrency:
Maximum concurrent parse jobs (default 1).
@@ -1834,11 +1836,11 @@ def create_app(
"""
retention_seconds = resolve_retention_seconds(retention_seconds)
upload_dir = upload_dir or ""
- server_tiers = resolve_server_tiers(tiers)
+ vlm_config = (vlm_config if vlm_config is not None else get_config().model.vlm).model_copy(deep=True)
+ server_tiers = resolve_server_tiers(tiers, vlm_config=vlm_config)
model_tier = model_tier_for_server_tiers(server_tiers)
tier_runtime_options = _runtime_options_for_server_tiers(server_tiers)
default_tier = next((tier for tier in ("standard", "basic", "flash") if tier in server_tiers), None)
- vlm_config = (vlm_config if vlm_config is not None else get_config().model.vlm).model_copy(deep=True)
_preflight_tier_dependencies(model_tier, vlm_config)
_api_key: str | None = api_key or None
_upload_dir = pathlib.Path(upload_dir) if upload_dir else pathlib.Path(tempfile.mkdtemp(prefix="mineru_"))
diff --git a/mineru/parser/server_tiers.py b/mineru/parser/server_tiers.py
index acccb67b..e7a925df 100644
--- a/mineru/parser/server_tiers.py
+++ b/mineru/parser/server_tiers.py
@@ -3,9 +3,13 @@
from __future__ import annotations
from collections.abc import Collection
+from typing import TYPE_CHECKING
from ..types import TIERS, TIERS_BY_SERVER_TIER, DeploymentTier, Tier, validate_tier
+if TYPE_CHECKING:
+ from ..config import VlmConfig
+
def normalize_server_tiers(tiers: Collection[Tier]) -> tuple[Tier, ...]:
"""校验非空显式集合,去重并按公共档位顺序稳定输出。"""
@@ -24,12 +28,12 @@ def parse_server_tier(value: str) -> tuple[Tier, ...] | None:
return TIERS_BY_SERVER_TIER[validate_tier(value)]
-def resolve_server_tiers(tiers: Collection[Tier] | None) -> tuple[Tier, ...]:
- """显式列表完全跳过硬件推荐,自动模式只在调用时惰性探测。"""
+def resolve_server_tiers(tiers: Collection[Tier] | None, *, vlm_config: VlmConfig | None = None) -> tuple[Tier, ...]:
+ """显式列表跳过推荐与启动校准;自动模式按硬件初选并完成适用的 OCR 选型。"""
if tiers is None:
from ..model.runtime.tier_recommendation import recommend_tiers
- recommended = normalize_server_tiers(recommend_tiers())
+ recommended = normalize_server_tiers(recommend_tiers(vlm_config=vlm_config).pdf_image_tiers)
tiers = TIERS_BY_SERVER_TIER[recommended[-1]]
return normalize_server_tiers(tiers)
diff --git a/tests/unittest/test_hardware_info.py b/tests/unittest/test_hardware_info.py
new file mode 100644
index 00000000..8dac10b7
--- /dev/null
+++ b/tests/unittest/test_hardware_info.py
@@ -0,0 +1,324 @@
+"""只读诊断报告、三平台库存解析和隔离进程协议的回归。"""
+
+from __future__ import annotations
+
+from dataclasses import asdict
+from importlib import metadata
+import json
+from pathlib import Path
+import subprocess
+import sys
+from types import SimpleNamespace
+from unittest.mock import Mock
+
+import pytest
+from typer.testing import CliRunner
+
+from mineru.config import get_config
+from mineru.kit.commands import hardware as command
+from mineru.kit.main import app
+from mineru.model.runtime import hardware, hardware_probe, hardware_system, onnx_calibration_cache, onnx_device
+from mineru.model.runtime.hardware_types import (
+ CpuInfo,
+ GpuInfo,
+ HardwareInfo,
+ MemoryInfo,
+ PackageInfo,
+ RuntimeProbe,
+ SystemHardware,
+)
+
+
+def _report() -> HardwareInfo:
+ """构造最小有效报告,测试文本和 JSON 渲染使用相同语义数据。"""
+ return HardwareInfo(
+ system={"name": "Linux", "release": "6.0", "architecture": "x86_64", "distribution": "Test Linux", "version": "test"},
+ python={"version": "3.12", "executable": "/env/bin/python"},
+ mineru={"version": "4.0", "module_path": "/source/mineru/__init__.py"},
+ cpu=CpuInfo(model="test CPU", physical_cores=4, logical_cores=8, available_cores=2),
+ memory=MemoryInfo(16 * 1024**3, 8 * 1024**3),
+ gpus=[GpuInfo(name="integrated", kind="integrated"), GpuInfo(name="discrete", kind="discrete")],
+ packages=[PackageInfo("mineru", "4.0", "/source"), PackageInfo("torch", "2.0", "/env")],
+ runtimes=[RuntimeProbe("torch", "error", error="driver unavailable")],
+ effective_config={"resolved": {"small_backend": "torch"}},
+ calibration=onnx_calibration_cache.CalibrationInfo("/tmp/config.yaml.onnx-calibration.json", "missing"),
+ warnings=["partial GPU runtime inventory"],
+ )
+
+
[email protected]("json_mode", [False, True])
+def test_info_command_output(monkeypatch: pytest.MonkeyPatch, json_mode: bool) -> None:
+ """文本与 JSON 均包含诊断信息,局部失败保留可用报告并返回成功。"""
+ report = asdict(_report())
+ monkeypatch.setattr(command, "_info_data", lambda: report)
+ result = CliRunner().invoke(app, ["hardware", "info", *(["--json"] if json_mode else [])])
+ assert result.exit_code == 0, result.output
+ if json_mode:
+ assert json.loads(result.stdout) == report
+ else:
+ assert "test CPU" in result.stdout and "未知" in result.stdout
+ assert "driver unavailable" in result.stdout
+ assert "vllm" not in result.stdout
+
+
+ "arguments", [["hardware"], ["hardware", "--help"], ["hardware", "info", "--help"], ["hardware", "detect", "--help"]]
+)
+def test_hardware_help_never_probes(monkeypatch: pytest.MonkeyPatch, arguments: list[str]) -> None:
+ """无参数与帮助入口不执行诊断、下载或推荐。"""
+ forbidden = Mock(side_effect=AssertionError("help must not probe"))
+ monkeypatch.setattr(command, "_info_data", forbidden)
+ monkeypatch.setattr(command, "_detect_data", forbidden)
+ result = CliRunner().invoke(app, arguments)
+ assert "Usage:" in result.output
+ assert result.exit_code in {0, 2}
+ forbidden.assert_not_called()
+
+
[email protected]("arguments", [["hardware", "info", "--quiet"], ["hardware", "detect", "--quiet"], ["auto-tier"]])
+def test_no_quiet_or_auto_tier_alias(arguments: list[str]) -> None:
+ """只提供确定的两个入口,不保留未批准的参数或命令别名。"""
+ result = CliRunner().invoke(app, arguments)
+ assert result.exit_code != 0
+ assert "No such" in result.output
+
+
+def test_installed_package_allowlist_only(monkeypatch: pytest.MonkeyPatch) -> None:
+ """未安装的包不出现在版本列表中,也不会触发运行时导入。"""
+
+ def distribution(name: str) -> SimpleNamespace:
+ """仅模拟两项安装元数据,其他发行包按真实缺失异常处理。"""
+ if name not in {"mineru", "mineru-vl-utils"}:
+ raise metadata.PackageNotFoundError(name)
+ return SimpleNamespace(version="1.2.3", locate_file=lambda path: Path("/site-packages"))
+
+ monkeypatch.setattr(hardware.metadata, "distribution", distribution)
+ packages = hardware.installed_packages()
+ assert [package.name for package in packages] == ["mineru", "mineru-vl-utils"]
+ assert all(package.location == "/site-packages" for package in packages)
+
+
+def test_configuration_summary_excludes_secrets(monkeypatch: pytest.MonkeyPatch) -> None:
+ """配置白名单保留复现设备决策的信息,排除认证和完整远程地址。"""
+ monkeypatch.setattr(get_config().model.vlm, "api_key", "secret-api-token")
+ monkeypatch.setattr(get_config().model.vlm, "server_url", "http://private-user:secret@host")
+ monkeypatch.setenv("MINERU_VL_API_KEY", "other-secret")
+ monkeypatch.setenv("CUDA_VISIBLE_DEVICES", "1")
+ report = hardware.config_summary()
+ encoded = json.dumps(report)
+ assert report["remote_vlm"]["enabled"] is True
+ assert report["environment"]["CUDA_VISIBLE_DEVICES"] == "1"
+ for secret in ("secret-api-token", "private-user", "other-secret", "MINERU_VL_API_KEY"):
+ assert secret not in encoded
+
+
+def test_linux_cpu_quota_frequency_and_mixed_pci_inventory(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ """模拟 Linux 文件系统并保留全部独显/集显库存,频率和内存按明确单位转换。"""
+ proc, system = tmp_path / "proc", tmp_path / "sys"
+ proc.mkdir()
+ records = []
+ for core in (0, 0, 1, 1):
+ records.append(f"model name : Example CPU\nphysical id : 0\ncore id : {core}\ncpu MHz : 2400.0")
+ (proc / "cpuinfo").write_text("\n\n".join(records), encoding="utf-8")
+ (proc / "meminfo").write_text("MemTotal: 16384 kB\nMemAvailable: 8192 kB\n", encoding="utf-8")
+ frequency = system / "devices/system/cpu/cpu0/cpufreq"
+ frequency.mkdir(parents=True)
+ (frequency / "base_frequency").write_text("2000000")
+ (frequency / "cpuinfo_max_freq").write_text("4200000")
+ for bus, vendor, chip in (("0000:00:02.0", "0x8086", "0x7d51"), ("0000:01:00.0", "0x10de", "0x2489")):
+ pci = system / "bus/pci/devices" / bus
+ pci.mkdir(parents=True)
+ for name, value in (("class", "0x030000"), ("vendor", vendor), ("device", chip)):
+ (pci / name).write_text(value)
+ monkeypatch.setattr(hardware_system.shutil, "which", lambda name: None)
+ result = SystemHardware()
+ hardware_system._linux_cpu(result, proc, system)
+ hardware_system._linux_gpus(result, system)
+ assert result.cpu.model == "Example CPU" and result.cpu.physical_cores == 2
+ assert (result.cpu.base_mhz, result.cpu.current_mhz, result.cpu.max_mhz) == (2000, 2400, 4200)
+ assert result.memory == MemoryInfo(16384 * 1024, 8192 * 1024)
+ assert [gpu.vendor for gpu in result.gpus] == ["Intel", "NVIDIA"]
+ runtime = RuntimeProbe(
+ "vulkan", "ok", {"devices": [{"name": "Intel GPU", "vendor_id": 0x8086, "device_id": 0x7D51, "device_type": 1}]}
+ )
+ hardware.merge_gpu_inventory(result.gpus, runtime)
+ assert len(result.gpus) == 2 and result.gpus[0].kind == "integrated"
+ assert result.gpus[1].kind == "unknown"
+
+
+def test_macos_unified_memory_and_unknown_frequency() -> None:
+ """Apple GPU 报告统一内存,不伪造独立显存、主频或驱动版本。"""
+ result = SystemHardware(memory=MemoryInfo(16 * 1024**3))
+ hardware_system.parse_macos_displays(
+ {
+ "SPDisplaysDataType": [
+ {
+ "_name": "Apple M4",
+ "sppci_model": "Apple M4",
+ "spdisplays_vendor": "sppci_vendor_Apple",
+ "sppci_bus": "spdisplays_builtin",
+ "spdisplays_revision-id": "0x01",
+ "spdisplays_ndrvs": [{"serial-number": "do-not-report"}],
+ }
+ ]
+ },
+ result,
+ "arm64",
+ )
+ gpu = result.gpus[0]
+ assert gpu.kind == "integrated" and gpu.unified_memory is True
+ assert gpu.dedicated_memory_bytes is None and gpu.shared_memory_bytes == 16 * 1024**3
+ assert gpu.driver is None and result.cpu.base_mhz is None
+ assert "do-not-report" not in json.dumps(asdict(result))
+
+
+def test_windows_cim_and_dxgi_memory() -> None:
+ """CIM 提供型号/核数和全部 GPU,64 位 DXGI 显存覆盖不可靠的 AdapterRAM。"""
+ result = SystemHardware()
+ hardware_system.parse_windows_hardware(
+ {
+ "cpus": [
+ {
+ "Name": "Test CPU",
+ "NumberOfCores": 8,
+ "NumberOfLogicalProcessors": 16,
+ "CurrentClockSpeed": 2800,
+ "MaxClockSpeed": 4200,
+ }
+ ],
+ "memory": {"TotalVisibleMemorySize": 16 * 1024**2, "FreePhysicalMemory": 8 * 1024**2},
+ "gpus": [{"Name": "RTX", "PNPDeviceID": "PCI\\VEN_10DE&DEV_2489", "AdapterRAM": 1, "DriverVersion": "test"}],
+ },
+ result,
+ )
+ hardware.merge_gpu_inventory(
+ result.gpus,
+ RuntimeProbe(
+ "dxgi",
+ "ok",
+ {
+ "devices": [
+ {
+ "name": "RTX",
+ "vendor_id": 0x10DE,
+ "device_id": 0x2489,
+ "kind": "discrete",
+ "dedicated_memory_bytes": 8 * 1024**3,
+ "shared_memory_bytes": 8 * 1024**3,
+ }
+ ]
+ },
+ ),
+ )
+ assert (result.cpu.physical_cores, result.cpu.logical_cores) == (8, 16)
+ assert result.cpu.base_mhz is None and result.cpu.max_mhz == 4200
+ assert result.memory.total_bytes == 16 * 1024**3
+ assert len(result.gpus) == 1 and result.gpus[0].dedicated_memory_bytes == 8 * 1024**3
+
+
+def test_windows_cim_partial_failure_keeps_memory_and_gpu(monkeypatch: pytest.MonkeyPatch) -> None:
+ """一个 CIM 类不可用时,其余硬件查询仍独立运行并进入报告。"""
+ run = Mock(side_effect=[None, '{"TotalVisibleMemorySize": 1024}', '{"Name": "GPU"}'])
+ monkeypatch.setattr(hardware_system, "_command", run)
+ result = SystemHardware()
+ hardware_system._windows_hardware(result)
+ assert run.call_count == 3
+ assert result.cpu.model is None and result.memory.total_bytes == 1024**2
+ assert result.gpus[0].name == "GPU"
+
+
+def test_evidence_uses_eligible_visible_adapter(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ """证据匹配实际可选适配器,不能因 ORT 原始库存仍列出隐藏设备而误判。"""
+ from mineru.model.runtime.webgpu import WebGPUDevice
+
+ path = tmp_path / "record.json"
+ monkeypatch.setattr(onnx_calibration_cache, "calibration_record_path", lambda: path)
+ adapter = WebGPUDevice(0x8086, 0x7D51, (("driver", "v1"),), (0x8086, 0x7D51))
+ onnx_calibration_cache.save_calibration_record(
+ adapter,
+ {
+ "intra_threads": 4,
+ "inter_threads": 1,
+ "cpu_elapsed": 2.0,
+ "gpu_elapsed": 1.0,
+ "decision_threshold": 0.8,
+ "outputs_match": True,
+ "decision_valid": True,
+ "model_sha256": "test",
+ },
+ )
+ payload = {"backend": "webgpu", "adapters": [asdict(WebGPUDevice(0x8086, 0x7D51))], "selected_adapter": asdict(adapter)}
+ probes = [RuntimeProbe("onnx", "ok", payload)]
+ assert onnx_calibration_cache.inspect_calibration_record(hardware._calibration_adapters(probes)).matches_environment is True
+ payload["selected_adapter"] = None
+ assert (
+ onnx_calibration_cache.inspect_calibration_record(hardware._calibration_adapters(probes)).matches_environment is False
+ )
+
+
+def test_nvidia_tool_matches_existing_windows_inventory(monkeypatch: pytest.MonkeyPatch) -> None:
+ """厂商工具补充 CIM 同一设备,不因 CIM 缺少总线地址而重复列出显卡。"""
+ monkeypatch.setattr(hardware_system.shutil, "which", lambda name: "nvidia-smi")
+ monkeypatch.setattr(hardware_system, "_command", lambda command, report: "00000000:01:00.0, RTX, 999.0, 8192\n")
+ report = SystemHardware(gpus=[GpuInfo(name="RTX", vendor="NVIDIA", source="cim")])
+ hardware_system._nvidia_details(report)
+ assert len(report.gpus) == 1
+ assert report.gpus[0].driver == "999.0" and report.gpus[0].dedicated_memory_bytes == 8 * 1024**3
+
+
+def test_probe_timeout_and_native_noise(monkeypatch: pytest.MonkeyPatch) -> None:
+ """原生日志不污染结构化结果,每项运行时导入都有独立超时边界。"""
+ call = Mock(side_effect=subprocess.TimeoutExpired("probe", 15))
+ monkeypatch.setattr(hardware_probe.subprocess, "run", call)
+ assert hardware_probe.run_probe("torch").status == "timeout"
+ assert call.call_args.kwargs["timeout"] == 15
+ output = "native stdout\n" + hardware_probe.PROBE_MARKER + json.dumps(asdict(RuntimeProbe("torch", "ok"))) + "\n"
+ call.side_effect = None
+ call.return_value = SimpleNamespace(returncode=0, stdout=output, stderr="native stderr")
+ assert hardware_probe.run_probe("torch").status == "ok"
+ call.return_value.stdout = "no marker"
+ assert hardware_probe.run_probe("torch").status == "error"
+
+
+def test_detection_protocol_moves_native_noise_to_stderr(
+ monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
+) -> None:
+ """detect 只交付结果,原生 stdout 被保留到 stderr 便于诊断。"""
+ payload = {"schema_version": 1, "ceiling": "standard"}
+ process = SimpleNamespace(returncode=0, stdout="native output\n" + hardware_probe.PROBE_MARKER + json.dumps(payload))
+ monkeypatch.setattr(hardware_probe.subprocess, "run", Mock(return_value=process))
+ assert hardware_probe.run_detection() == payload
+ captured = capsys.readouterr()
+ assert not captured.out and "native output" in captured.err
+
+
+def test_info_partial_failure_is_read_only(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ """报告可在运行时探测失败时完成,并保留原有校准字节、无配置写入。"""
+ record = tmp_path / "config.yaml.onnx-calibration.json"
+ record.write_text("broken evidence", encoding="utf-8")
+ monkeypatch.setattr(onnx_calibration_cache, "calibration_record_path", lambda: record)
+ monkeypatch.setattr(
+ hardware, "collect_system_hardware", lambda: SystemHardware(cpu=CpuInfo(logical_cores=8, available_cores=2))
+ )
+ monkeypatch.setattr(hardware, "installed_packages", lambda: [PackageInfo("mineru", "4", "/env")])
+ monkeypatch.setattr(hardware, "run_probe", lambda name: RuntimeProbe(name, "error", error="probe failed"))
+ forbidden = Mock(side_effect=AssertionError("info must remain read only"))
+ monkeypatch.setattr(onnx_device, "resolve_onnx_device", forbidden)
+ monkeypatch.setattr(onnx_calibration_cache, "save_calibration_record", forbidden)
+ result = hardware.collect_hardware_info()
+ assert result.cpu.available_cores == 2 and result.calibration.status == "invalid"
+ assert result.warnings and result.effective_config["resolved"] is None
+ assert record.read_text(encoding="utf-8") == "broken evidence"
+ assert [package.name for package in result.packages] == ["mineru"]
+ forbidden.assert_not_called()
+
+
+def test_help_imports_no_heavy_runtime() -> None:
+ """在新进程验证帮助不会提前导入 Torch、ORT 或原生 llama 运行时。"""
+ script = (
+ "import sys; from typer.testing import CliRunner; from mineru.kit.main import app; "
+ "r=CliRunner().invoke(app,['hardware','--help']); assert r.exit_code == 0; "
+ "assert not {'torch','onnxruntime','mineru_llama_cpp'}.intersection(sys.modules)"
+ )
+ result = subprocess.run([sys.executable, "-c", script], capture_output=True, text=True, timeout=15)
+ assert result.returncode == 0, result.stderr
diff --git a/tests/unittest/test_hardware_recommendation.py b/tests/unittest/test_hardware_recommendation.py
new file mode 100644
index 00000000..a6c33620
--- /dev/null
+++ b/tests/unittest/test_hardware_recommendation.py
@@ -0,0 +1,157 @@
+"""验证 Torch 免校准、实际设备可用性及命令/API/llama.cpp 的统一决策。"""
+
+from __future__ import annotations
+
+from dataclasses import asdict
+import json
+import os
+from pathlib import Path
+import sys
+from types import SimpleNamespace
+from unittest.mock import Mock
+
+from fastapi.testclient import TestClient
+import pytest
+from typer.testing import CliRunner
+
+from mineru.config import VlmConfig, get_config
+from mineru.kit.commands import hardware as hardware_cmd
+from mineru.kit.main import app as kit_app
+from mineru.model.runtime import device, llama_device, onnx_calibration_cache, onnx_device, tier_recommendation
+from mineru.model.runtime.llama_probe import LlamaDevice
+from mineru.parser import api_server
+from mineru.types import TIERS
+
+
+def torch_environment(monkeypatch: pytest.MonkeyPatch) -> Mock:
+ """为 Torch 分支设置最小运行环境,并禁止任何 ONNX 选型或证据写入。"""
+ monkeypatch.setattr(get_config().model, "small_backend", "torch")
+ monkeypatch.setattr(get_config().model.vlm, "engine", "llama-cpp")
+ monkeypatch.setattr(get_config().model.vlm, "server_url", None)
+ monkeypatch.setattr(tier_recommendation, "effective_cpu_count", lambda: 8)
+ monkeypatch.setattr(device, "module_available", lambda name: True)
+ forbidden = Mock(side_effect=AssertionError("Torch must not calibrate or write ONNX settings"))
+ monkeypatch.setattr(onnx_device, "resolve_onnx_device", forbidden)
+ monkeypatch.setattr(onnx_calibration_cache, "save_calibration_record", forbidden)
+ monkeypatch.setattr(onnx_calibration_cache, "invalidate_calibration_record", forbidden)
+ monkeypatch.setattr(tier_recommendation, "_advanced_gpu_reason", forbidden)
+ return forbidden
+
+
+def _fake_torch(monkeypatch: pytest.MonkeyPatch, kind: str, available: bool, count: int = 1) -> None:
+ """只提供可用性 API,调用模型、张量或设备分配接口都会因缺失而失败。"""
+ api = SimpleNamespace(is_available=lambda: available, device_count=lambda: count)
+ unavailable = SimpleNamespace(is_available=lambda: False, device_count=lambda: 0)
+ fake = SimpleNamespace(
+ cuda=api if kind == "cuda" else unavailable,
+ xpu=api if kind == "xpu" else unavailable,
+ backends=SimpleNamespace(mps=api if kind == "mps" else unavailable),
+ )
+ monkeypatch.setitem(sys.modules, "torch", fake)
+ monkeypatch.setitem(sys.modules, "torch_npu", None)
+
+
[email protected]("backend", ["torch", "auto"])
[email protected]("accelerator", ["cuda", "mps", "xpu"])
[email protected]("engine", ["llama-cpp", "vllm", "lmdeploy"])
+def test_torch_accelerator_skips_onnx_for_every_engine(
+ torch_environment: Mock, monkeypatch: pytest.MonkeyPatch, backend: str, accelerator: str, engine: str
+) -> None:
+ """显式和自动 Torch 都直接使用有效加速设备,且不依赖 llama 库存。"""
+ monkeypatch.setattr(get_config().model, "small_backend", backend)
+ monkeypatch.delenv("MINERU_DEVICE_MODE", raising=False)
+ monkeypatch.setenv("MINERU_LLAMA_CPP_BACKEND", "cpu")
+ _fake_torch(monkeypatch, accelerator, True)
+ report = tier_recommendation.recommend_tiers(vlm_config=VlmConfig(engine=engine))
+ assert report.ceiling == "advanced" and report.pdf_image_tiers == TIERS
+ assert report.default_request_tier == "standard"
+ assert report.small_backend == "torch" and report.device == accelerator
+ assert report.vlm_engine == engine
+ assert report.calibration.status == "skipped" and report.calibration.reason == "torch_backend"
+ assert report.calibration.evidence is None and not report.warnings
+ torch_environment.assert_not_called()
+
+
+ ("requested", "available", "expected_warning"),
+ [("cpu", True, False), ("cuda", False, True), ("cuda:2", True, True), ("xpu:-1", True, True)],
+)
[email protected]("cores", [3, 4])
+def test_torch_cpu_and_invalid_explicit_device_are_conservative(
+ torch_environment: Mock,
+ monkeypatch: pytest.MonkeyPatch,
+ requested: str,
+ available: bool,
+ expected_warning: bool,
+ cores: int,
+) -> None:
+ """显式字符串不能伪造 GPU 可用性,CPU 边界按当前进程可用核数判断。"""
+ monkeypatch.setenv("MINERU_DEVICE_MODE", requested)
+ monkeypatch.setattr(tier_recommendation, "effective_cpu_count", lambda: cores)
+ _fake_torch(monkeypatch, requested.split(":")[0], available)
+ report = tier_recommendation.recommend_tiers()
+ assert report.device == "cpu" and report.ceiling == ("standard" if cores == 4 else "flash")
+ assert bool(report.warnings) == expected_warning
+ assert get_config().model.small_backend == "torch"
+ assert os.environ["MINERU_DEVICE_MODE"] == requested
+ torch_environment.assert_not_called()
+
+
+def test_torch_probe_exception_keeps_warning(torch_environment: Mock, monkeypatch: pytest.MonkeyPatch) -> None:
+ """运行时探测异常形成有解释的 CPU 推荐,而非伪造 GPU 或开始 OCR 测速。"""
+ monkeypatch.setattr(device, "get_device", Mock(side_effect=RuntimeError("driver error")))
+ report = tier_recommendation.recommend_tiers()
+ assert report.device == "cpu" and report.ceiling == "standard"
+ assert "driver error" in report.warnings[0]
+ torch_environment.assert_not_called()
+
+
+def test_remote_vlm_and_api_override_match_detect(
+ torch_environment: Mock, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ """API 显式 VLM 配置传入共享推荐,命令报告与首次服务能力保持一致。"""
+ _fake_torch(monkeypatch, "cuda", True)
+ monkeypatch.setenv("MINERU_DEVICE_MODE", "cuda")
+ settings = VlmConfig(engine="mlx", server_url="http://localhost:9999", api_key="not-for-report")
+ expected = tier_recommendation.recommend_tiers(vlm_config=settings)
+ monkeypatch.setattr(api_server, "ensure_tier_runtime_dependencies", Mock())
+ recommend = Mock(wraps=tier_recommendation.recommend_tiers)
+ monkeypatch.setattr(tier_recommendation, "recommend_tiers", recommend)
+ api = api_server.create_app(upload_dir=str(tmp_path), vlm_config=settings)
+ assert recommend.call_args.kwargs["vlm_config"] == settings
+ assert expected.vlm_engine == "http-client"
+ with TestClient(api) as client:
+ assert tuple(row["id"] for row in client.get("/v1/tiers").json()["data"]) == expected.pdf_image_tiers
+ assert api.state.default_tier == expected.default_request_tier
+ monkeypatch.setattr(hardware_cmd, "_detect_data", lambda: asdict(expected))
+ result = CliRunner().invoke(kit_app, ["hardware", "detect", "--json"])
+ assert result.exit_code == 0, result.output
+ assert json.loads(result.stdout)["ceiling"] == api.state.server_tiers[-1]
+ assert "not-for-report" not in result.stdout
+ torch_environment.assert_not_called()
+
+
[email protected]("accelerated", [True, False])
+def test_torch_llama_integrated_route_does_not_return_to_onnx(
+ torch_environment: Mock, monkeypatch: pytest.MonkeyPatch, accelerated: bool
+) -> None:
+ """llama 自动集显复用 Torch 可用性,后续绑定及 Intel 兼容策略继续执行。"""
+ monkeypatch.setattr(llama_device, "sys", SimpleNamespace(platform="linux"))
+ monkeypatch.delenv("MINERU_LLAMA_CPP_BACKEND", raising=False)
+ monkeypatch.delenv("GGML_VK_SERIALIZE_SUBMISSIONS", raising=False)
+ monkeypatch.setenv("MINERU_DEVICE_MODE", "xpu" if accelerated else "cpu")
+ _fake_torch(monkeypatch, "xpu", accelerated)
+ native = LlamaDevice("Vulkan0", "Arc", "vulkan", True, 0x8086, 0x7D51, 0)
+ monkeypatch.setattr(llama_device, "discover_llama_devices", lambda: (native,))
+ bind = Mock(side_effect=lambda selection: selection)
+ monkeypatch.setattr(llama_device, "_bind", bind)
+ result = llama_device.resolve_llama_device()
+ assert result.device == ("gpu" if accelerated else "cpu")
+ if accelerated:
+ assert result.devices == (native,)
+ assert dict(result.environment)["GGML_VK_SERIALIZE_SUBMISSIONS"] == "1"
+ bind.assert_called_once()
+ else:
+ bind.assert_not_called()
+ torch_environment.assert_not_called()
diff --git a/tests/unittest/test_kit_commands.py b/tests/unittest/test_kit_commands.py
index 64e40cc7..49333787 100644
--- a/tests/unittest/test_kit_commands.py
+++ b/tests/unittest/test_kit_commands.py
@@ -402,6 +402,7 @@ def test_kit_root_commands_keep_product_order() -> None:
"vlm-server",
"router",
"models",
+ "hardware",
"version",
]
diff --git a/tests/unittest/test_llama_device_policy.py b/tests/unittest/test_llama_device_policy.py
index d2bf4454..d2b6a703 100644
--- a/tests/unittest/test_llama_device_policy.py
+++ b/tests/unittest/test_llama_device_policy.py
@@ -30,6 +30,9 @@ def isolated(monkeypatch: pytest.MonkeyPatch) -> None:
"""单测不触发真实设备探测、模型加载或持久化校准。"""
monkeypatch.setattr(policy, "sys", SimpleNamespace(platform="linux", executable="python"))
monkeypatch.setattr(policy, "_runtime_environment", None)
+ from mineru.model.runtime import device
+
+ monkeypatch.setattr(device, "resolve_small_model_backend", lambda: "onnx")
for name in (*policy._BACKEND_ENV, "MINERU_LLAMA_CPP_BACKEND"):
monkeypatch.delenv(name, raising=False)
diff --git a/tests/unittest/test_parser_api_contract.py b/tests/unittest/test_parser_api_contract.py
index 38abb862..0cf3267b 100644
--- a/tests/unittest/test_parser_api_contract.py
+++ b/tests/unittest/test_parser_api_contract.py
@@ -7,6 +7,7 @@ import logging
import subprocess
import sys
from pathlib import Path
+from types import SimpleNamespace
from typing import Any
from unittest.mock import patch
@@ -67,7 +68,9 @@ _REMOVED_FORMULA_ENABLE_ENV = "MINERU_" + "FORMULA" + "_ENABLE"
@pytest.fixture(autouse=True)
def _stable_hardware_recommendation(monkeypatch: pytest.MonkeyPatch) -> None:
"""固定服务契约测试的硬件推荐,设备组合由独立测试覆盖。"""
- monkeypatch.setattr("mineru.model.runtime.tier_recommendation.recommend_tiers", lambda: frozenset(TIERS))
+ monkeypatch.setattr(
+ "mineru.model.runtime.tier_recommendation.recommend_tiers", lambda **kwargs: SimpleNamespace(pdf_image_tiers=TIERS)
+ )
def _stub_api_server_dependency_preflight(monkeypatch: pytest.MonkeyPatch) -> None:
@@ -774,8 +777,13 @@ def test_api_server_standard_no_flash_state_and_metadata(tmp_path: Path, monkeyp
@pytest.mark.parametrize(
("tiers", "default"),
- [(('flash', 'standard'), 'standard'), (('standard',), 'standard'),
- (('basic',), 'basic'), (('flash',), 'flash'), (('advanced',), None)],
+ [
+ (("flash", "standard"), "standard"),
+ (("standard",), "standard"),
+ (("basic",), "basic"),
+ (("flash",), "flash"),
+ (("advanced",), None),
+ ],
)
def test_api_server_explicit_capability_matrix(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, tiers: tuple[Tier, ...], default: Tier | None
@@ -977,7 +985,6 @@ def test_api_server_no_advanced_rejects_advanced_request(tmp_path: Path, monkeyp
app = create_app(
upload_dir=str(tmp_path / "api"),
tiers=("flash", "basic", "standard"),
-
)
with TestClient(app) as client:
@@ -1000,7 +1007,6 @@ def test_api_server_no_flash_rejects_flash_request(tmp_path: Path, monkeypatch:
app = create_app(
upload_dir=str(tmp_path / "api"),
tiers=("basic", "standard", "advanced"),
-
)
response = TestClient(app).post(
diff --git a/tests/unittest/test_server_tiers.py b/tests/unittest/test_server_tiers.py
index e553db0c..bb35deb2 100644
--- a/tests/unittest/test_server_tiers.py
+++ b/tests/unittest/test_server_tiers.py
@@ -4,6 +4,7 @@ from __future__ import annotations
from itertools import combinations
from pathlib import Path
+from types import SimpleNamespace
from typing import Any
from unittest.mock import Mock
@@ -55,14 +56,14 @@ def test_auto_recommendation_is_fixed_at_creation(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, preflight: Mock, tiers: tuple[Tier, ...]
) -> None:
"""自动推荐每个服务只计算一次,生命周期启动与能力查询不重新选择。"""
- recommend = Mock(return_value=frozenset(tiers))
+ recommend = Mock(return_value=SimpleNamespace(pdf_image_tiers=tiers))
monkeypatch.setattr(tier_recommendation, "recommend_tiers", recommend)
app = api_server.create_app(upload_dir=str(tmp_path))
- recommend.return_value = frozenset({"advanced"})
+ recommend.return_value = SimpleNamespace(pdf_image_tiers=("advanced",))
with TestClient(app) as client:
for _ in range(2):
assert tuple(row["id"] for row in client.get("/v1/tiers").json()["data"]) == TIERS_BY_SERVER_TIER[tiers[-1]]
- recommend.assert_called_once_with()
+ recommend.assert_called_once_with(vlm_config=app.state.vlm_config)
@pytest.mark.parametrize(
@@ -72,7 +73,7 @@ def test_auto_server_accepts_task_with_standard_default(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, preflight: Mock, options: dict[str, str | None], expected: str
) -> None:
"""硬件推荐四档后,经公共接单接口固定默认 standard 或调用方指定的 advanced。"""
- monkeypatch.setattr(tier_recommendation, "recommend_tiers", lambda: frozenset(TIERS))
+ monkeypatch.setattr(tier_recommendation, "recommend_tiers", lambda **kwargs: SimpleNamespace(pdf_image_tiers=TIERS))
app = api_server.create_app(upload_dir=str(tmp_path))
with TestClient(app) as client:
response = client.post("/v1/tasks", json={"files": [{"file_name": "test.pdf", "bytes": 1}], **options})
@@ -121,7 +122,7 @@ def test_old_python_options_removed(option: str) -> None:
def test_cli_entrypoints(monkeypatch: pytest.MonkeyPatch, preflight: Mock, entry: str, options: list[str]) -> None:
"""三个入口共享自动推荐与单档上限,不启动监听进程。"""
seen: list[tuple[Tier, ...]] = []
- monkeypatch.setattr(tier_recommendation, "recommend_tiers", lambda: frozenset(TIERS))
+ monkeypatch.setattr(tier_recommendation, "recommend_tiers", lambda **kwargs: SimpleNamespace(pdf_image_tiers=TIERS))
monkeypatch.setattr("uvicorn.Server.run", lambda server: seen.append(server.config.app.state.server_tiers))
if entry == "module":
result = CliRunner().invoke(api_server.main, options)
diff --git a/tests/unittest/test_tier_recommendation.py b/tests/unittest/test_tier_recommendation.py
index e4fdb1cd..82da1559 100644
--- a/tests/unittest/test_tier_recommendation.py
+++ b/tests/unittest/test_tier_recommendation.py
@@ -3,12 +3,14 @@
from __future__ import annotations
from dataclasses import replace
+import importlib
from pathlib import Path
from types import SimpleNamespace
from typing import Any
from unittest.mock import Mock
import pytest
+import yaml
from mineru.model.runtime import onnx_calibration_cache as cache
from mineru.model.runtime import tier_recommendation as recommendation
@@ -18,6 +20,12 @@ from mineru.model.runtime.windows_gpu import GpuAdapter
from mineru.types import TIERS
[email protected](autouse=True)
+def onnx_recommendation_backend(monkeypatch: pytest.MonkeyPatch) -> None:
+ """本文件验证 ONNX 既有推荐规则,隔离宿主可能自动选择的 Torch 后端。"""
+ monkeypatch.setattr(recommendation, "resolve_small_model_backend", lambda: "onnx")
+
+
@pytest.mark.parametrize(
("cores", "gpu", "expected"),
[
@@ -141,14 +149,17 @@ def test_unwritable_record_does_not_break_calibration(evidence_path: Path, monke
@pytest.mark.parametrize(("platform", "metal"), [("darwin", True), ("darwin", False), ("other", False)])
def test_apple_metal_recommendation(monkeypatch: pytest.MonkeyPatch, platform: str, metal: bool) -> None:
"""Apple Silicon 按 Metal 可用性推荐,不要求 Windows/Linux 校准记录。"""
- from mineru.model.runtime import llama_device
+ from mineru.model.runtime import llama_device, onnx_device
monkeypatch.delenv("MINERU_LLAMA_CPP_BACKEND", raising=False)
monkeypatch.setattr(recommendation, "sys", SimpleNamespace(platform=platform))
monkeypatch.setattr(recommendation, "effective_cpu_count", lambda: 4)
monkeypatch.setattr(recommendation, "_apple_metal_available", lambda: metal)
monkeypatch.setattr(llama_device, "discover_llama_devices", lambda: ())
- assert recommendation.recommend_tiers() == frozenset(TIERS if metal else TIERS[:-1])
+ selection = Mock(side_effect=AssertionError("unsupported platform must not select ONNX device"))
+ monkeypatch.setattr(onnx_device, "resolve_onnx_device", selection)
+ assert frozenset(recommendation.recommend_tiers().pdf_image_tiers) == frozenset(TIERS if metal else TIERS[:-1])
+ selection.assert_not_called()
@pytest.mark.parametrize("platform", ["win32", "linux"])
@@ -156,7 +167,7 @@ def test_apple_metal_recommendation(monkeypatch: pytest.MonkeyPatch, platform: s
def test_gpu_discovery_uses_only_existing_evidence(
evidence_path: Path, monkeypatch: pytest.MonkeyPatch, platform: str, kind: str
) -> None:
- """以真实证据读取验证跨平台 GPU 路由,并禁止推荐路径调用校准。"""
+ """硬件初选只读取真实证据,校准由达到门槛后的启动编排触发。"""
from mineru.model.runtime import llama_device, onnx_device, webgpu, windows_gpu
monkeypatch.delenv("MINERU_LLAMA_CPP_BACKEND", raising=False)
@@ -182,7 +193,8 @@ def test_gpu_discovery_uses_only_existing_evidence(
if kind != "unknown":
cache.save_calibration_record(adapter, _measurement(gpu_elapsed=3.0 if kind == "slow" else 1.0))
before = evidence_path.read_bytes() if evidence_path.exists() else None
- assert recommendation.recommend_tiers() == frozenset(TIERS if kind in {"discrete", "calibrated"} else TIERS[:-1])
+ hardware = recommendation.detect_tier_hardware()
+ assert recommendation.tiers_for_hardware(hardware) == frozenset(TIERS if kind in {"discrete", "calibrated"} else TIERS[:-1])
assert (evidence_path.read_bytes() if evidence_path.exists() else None) == before
onnx_device.resolve_onnx_device.assert_not_called()
@@ -191,4 +203,177 @@ def test_explicit_cpu_and_discovery_failure(monkeypatch: pytest.MonkeyPatch) ->
"""显式 CPU 禁止 GPU 推荐,CPU 探测失败时只推荐基础档位。"""
monkeypatch.setenv("MINERU_LLAMA_CPP_BACKEND", "cpu")
monkeypatch.setattr(recommendation, "effective_cpu_count", Mock(side_effect=OSError("affinity")))
- assert recommendation.recommend_tiers() == {"flash"}
+ assert recommendation.recommend_tiers().pdf_image_tiers == ("flash",)
+
+
[email protected](params=["win32", "linux"])
+def startup_calibration(
+ request: pytest.FixtureRequest, evidence_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> tuple[Path, Mock]:
+ """模拟双平台物理设备和测速 worker,保留真实选型、配置落盘及证据读取链路。"""
+ import onnxruntime
+
+ from mineru.model import registry
+ from mineru.model.runtime import llama_device, onnx_calibration, onnx_device, webgpu, windows_gpu
+
+ settings = importlib.import_module("mineru.config")
+ config_file = evidence_path.with_name("settings.yaml")
+ config_file.write_text("model:\n onnx_device: auto\n source: local\n", encoding="utf-8")
+ monkeypatch.setattr(settings.get_config().model, "onnx_device", "auto")
+ monkeypatch.setattr(settings, "get_config_file_path", lambda: str(config_file))
+ monkeypatch.setattr(settings, "get_config_source", lambda key: "file")
+ monkeypatch.delenv("MINERU_LLAMA_CPP_BACKEND", raising=False)
+ for module in (recommendation, onnx_device):
+ monkeypatch.setattr(module, "sys", SimpleNamespace(platform=request.param))
+ monkeypatch.setattr(recommendation, "effective_cpu_count", lambda: 8)
+ monkeypatch.setattr(onnx_device, "_selections", {})
+ monkeypatch.setattr(onnxruntime, "get_available_providers", lambda: ["DmlExecutionProvider", "CPUExecutionProvider"])
+ for module in (onnx_device, windows_gpu):
+ monkeypatch.setattr(module, "discover_gpus", lambda **kwargs: (_adapter(),))
+ for module in (onnx_device, webgpu):
+ monkeypatch.setattr(module, "discover_webgpu_devices", lambda: (WebGPUDevice(0x8086, 0x7D51),))
+ monkeypatch.setattr(
+ llama_device,
+ "discover_llama_devices",
+ lambda: (LlamaDevice("Vulkan0", "test", "vulkan", True, 0x8086, 0x7D51),),
+ )
+ monkeypatch.setattr(
+ registry, "MINERU_4_MODELS_ONNX", SimpleNamespace(ocr_rec=SimpleNamespace(ensure=Mock(return_value="rec.onnx")))
+ )
+ measurement = Mock(return_value=_measurement())
+
+ def run_calibration(
+ model_path: str,
+ adapter: GpuAdapter | WebGPUDevice,
+ *,
+ intra_op_num_threads: int,
+ inter_op_num_threads: int,
+ threshold: float,
+ ) -> dict[str, Any]:
+ """只替换实际硬件测量,按真实 worker 生命周期撤销并保存性能证据。"""
+ cache.invalidate_calibration_record()
+ result = measurement()
+ cache.save_calibration_record(adapter, result)
+ return result
+
+ monkeypatch.setattr(onnx_calibration, "run_calibration", run_calibration)
+ return config_file, measurement
+
+
[email protected]("outcome", ["fast", "slow", "unstable", "timeout", "output_error"])
+def test_auto_startup_calibrates_before_publishing(
+ startup_calibration: tuple[Path, Mock], monkeypatch: pytest.MonkeyPatch, outcome: str
+) -> None:
+ """真实服务工厂在发布能力前读取本次校准,失败保持标准上限且不伪造 CPU 胜出。"""
+ from fastapi.testclient import TestClient
+
+ from mineru.model.runtime import onnx_device
+ from mineru.parser import api_server
+
+ config_file, measurement = startup_calibration
+ if outcome == "slow":
+ measurement.return_value = _measurement(gpu_elapsed=2.0)
+ elif outcome == "unstable":
+ measurement.return_value = _measurement(decision_valid=False)
+ elif outcome in {"timeout", "output_error"}:
+ measurement.side_effect = TimeoutError("worker") if outcome == "timeout" else ValueError("outputs differ")
+ monkeypatch.setattr(api_server, "ensure_tier_runtime_dependencies", Mock())
+ preload = Mock(side_effect=AssertionError("startup calibration must not require model preload"))
+ monkeypatch.setattr(api_server, "_preload_server_models", preload)
+
+ app = api_server.create_app(upload_dir=str(config_file.parent / "uploads"))
+ expected = TIERS if outcome == "fast" else TIERS[:-1]
+ measurement.assert_called_once()
+ assert app.state.server_tiers == expected
+ assert app.state.default_tier == "standard"
+ with TestClient(app) as client:
+ assert tuple(row["id"] for row in client.get("/v1/tiers").json()["data"]) == expected
+ preload.assert_not_called()
+ # 随后的模型初始化复用本进程选择,不再开启第二次校准。
+ selected = onnx_device.resolve_onnx_device()
+ assert selected.device == ("gpu" if outcome == "fast" else "cpu")
+ measurement.assert_called_once()
+ saved = "gpu" if outcome == "fast" else "cpu" if outcome == "slow" else "auto"
+ assert yaml.safe_load(config_file.read_text(encoding="utf-8"))["model"] == {
+ "onnx_device": saved,
+ "source": "local",
+ }
+
+
+def test_flash_initial_recommendation_skips_calibration(
+ startup_calibration: tuple[Path, Mock], monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """可用 CPU 不足四且无已有 GPU 证据时,只开放 Flash 并跳过启动选型。"""
+ from mineru.model.runtime import onnx_device
+
+ monkeypatch.setattr(recommendation, "effective_cpu_count", lambda: 3)
+ assert recommendation.recommend_tiers().pdf_image_tiers == ("flash",)
+ startup_calibration[1].assert_not_called()
+ assert not onnx_device._selections
+
+
+def test_low_cpu_advanced_recommendation_still_selects_device(
+ startup_calibration: tuple[Path, Mock], monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """门槛按初选档位判断,低 CPU 配额的独显设备仍按平台规则提前选型。"""
+ from mineru.model.runtime import llama_device, onnx_device
+
+ monkeypatch.setattr(recommendation, "effective_cpu_count", lambda: 2)
+ monkeypatch.setattr(
+ llama_device,
+ "discover_llama_devices",
+ lambda: (LlamaDevice("Vulkan0", "test", "vulkan", False, 0x8086, 0x7D51),),
+ )
+ monkeypatch.setattr(onnx_device, "discover_gpus", lambda **kwargs: (replace(_adapter(), uma=False),))
+ assert frozenset(recommendation.recommend_tiers().pdf_image_tiers) == frozenset(TIERS)
+ assert onnx_device._selections
+ assert startup_calibration[1].call_count == (0 if onnx_device.sys.platform == "win32" else 1)
+
+
[email protected]("tier", TIERS)
+def test_explicit_ceiling_skips_startup_selection(startup_calibration: tuple[Path, Mock], tier: str) -> None:
+ """显式启动上限和 Python 精确集合均不进入自动推荐的设备选择。"""
+ from mineru.model.runtime import onnx_device
+ from mineru.parser.server_tiers import parse_server_tier, resolve_server_tiers
+
+ selected = parse_server_tier(tier)
+ assert resolve_server_tiers(selected) == selected
+ startup_calibration[1].assert_not_called()
+ assert not onnx_device._selections
+
+
[email protected]("requested", ["cpu", "gpu"])
+def test_startup_preserves_explicit_device_without_performance_evidence(
+ startup_calibration: tuple[Path, Mock], requested: str
+) -> None:
+ """已保存或手动的设备偏好不触发测速,也不代替集显的有效性能证据。"""
+ settings = importlib.import_module("mineru.config")
+ config_file, measurement = startup_calibration
+ settings.get_config().model.onnx_device = requested
+ config_file.write_text(f"model:\n onnx_device: {requested}\n", encoding="utf-8")
+ assert frozenset(recommendation.recommend_tiers().pdf_image_tiers) == frozenset(TIERS[:-1])
+ measurement.assert_not_called()
+ assert yaml.safe_load(config_file.read_text(encoding="utf-8"))["model"]["onnx_device"] == requested
+
+
+def test_next_startup_reuses_saved_device_and_evidence(startup_calibration: tuple[Path, Mock]) -> None:
+ """同次启动采用新证据,后续进程复用保存结果,不再次测速。"""
+ from mineru.model.runtime import onnx_device
+
+ assert frozenset(recommendation.recommend_tiers().pdf_image_tiers) == frozenset(TIERS)
+ onnx_device._selections.clear()
+ assert frozenset(recommendation.recommend_tiers().pdf_image_tiers) == frozenset(TIERS)
+ startup_calibration[1].assert_called_once()
+ assert onnx_device.resolve_onnx_device().reason == "configured_gpu"
+
+
+def test_failed_recalibration_revokes_previous_fast_evidence(startup_calibration: tuple[Path, Mock]) -> None:
+ """强制重新校准失败后,本次启动不能沿用已经撤销的旧 GPU 胜出证据。"""
+ from mineru.model.runtime import onnx_device
+
+ adapter = _adapter() if onnx_device.sys.platform == "win32" else WebGPUDevice(0x8086, 0x7D51)
+ cache.save_calibration_record(adapter, _measurement())
+ startup_calibration[1].side_effect = TimeoutError("worker")
+ assert frozenset(recommendation.recommend_tiers().pdf_image_tiers) == frozenset(TIERS[:-1])
+ startup_calibration[1].assert_called_once()
+ assert not cache.calibration_record_path().exists()