Transforms complex documents like PDFs and Office docs into LLM-ready markdown/JSON for your Agentic workflows.
Python ai4sciencedocument-analysisdocxextract-datalayout-analysisocrparserpdfpdf-converterpdf-extractor-llmpdf-extractor-pretrainpdf-extractor-ragpdf-parserpptxpythonxlsx
feat(runtime): gate automatic tiers on GPU memory capacity
myhloli40841e03b964
diff --git a/docs/next/api/changes.md b/docs/next/api/changes.mdindex e44aac17..90f8b9d4 100644--- a/docs/next/api/changes.md+++ b/docs/next/api/changes.md@@ -8,7 +8,7 @@ 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、显式启动档位以及已保存的设备选择不强制测速;模型预加载与请求默认档位保持原规则。+`--tier auto`(包括省略参数)按有效小模型后端分流。CPU 可用逻辑核至少 4 时默认开放到 Basic;GPU 经既有选型确认可用且对应显存/预算至少 5.5 GiB 时,才开放 Standard/Advanced,且不额外要求 4 核。Torch、Apple Metal 及符合既有绑定规则的独显免测速,其他 ONNX 候选仍要求有效校准胜出。Windows/Linux 在 CPU 达标或存在内存达标的兼容 GPU 候选时同步完成适用 ONNX 选型,最终 CPU 或失败结果不能凭静态库存重新升级。无需启用 `--preload-models`,首次校准可能准备或下载 OCR rec 模型。显式启动档位以及已保存的设备选择不强制测速;模型预加载与请求默认选档顺序保持原规则。新增 `mineru-kit hardware detect [--json]` 和 `hardware info [--json]`,分别用于同源推荐与只读问题反馈诊断。软件版本只展示指定清单内已安装的包;没有 `--quiet` 或 `auto-tier` 别名。diff --git a/docs/next/cli/mineru-kit-api-server.md b/docs/next/cli/mineru-kit-api-server.mdindex 4e079cd9..ddb1e61f 100644--- a/docs/next/cli/mineru-kit-api-server.md+++ b/docs/next/cli/mineru-kit-api-server.md@@ -59,22 +59,24 @@ Tasks 的请求 `tier` 仍可选,只对 PDF/图片生效。省略或 JSON `nul| 硬件条件 | 启动上限 | PDF/图片公开集合 ||----------|----------|------------------|| 进程可用 CPU 数不足 4,且无达标 GPU | flash | `flash` |-| 进程可用 CPU 数至少 4,且无达标 GPU | standard | `flash,basic,standard` |-| 有可用独显、OCR 校准达标的集显,或 Metal 可用的 Apple Silicon | advanced | 全部四档 |+| 进程可用 CPU 数至少 4,且无达标 GPU | basic | `flash,basic` |+| GPU 已确认可用,且选定设备显存/预算至少 5.5 GiB(CPU 核数不限) | advanced | 全部四档 |CPU 数按逻辑 CPU 计算,并考虑进程亲和性和 Linux cgroup 配额。集显沿用有效 OCR 校准的 GPU 时间不高于 CPU 时间 0.8 倍的判定。探测失败或设备身份不明确时按 CPU 条件推荐。显式上限可以覆盖推荐,随后仍执行正常依赖预检。-GPU 类型与 OCR、llama.cpp 和硬件诊断使用共享分类;只有目标运行后端可见且原生身份确认的独显,才凭类型开放 Advanced。ggml 的通用 GPU 标志、未知类型及虚拟 GPU 均不直接视为独显;同型号多卡无法唯一关联时保持保守结果。各后端可以选择不同 GPU,共用分类和优先级,不强制跨后端同卡。+5.5 GiB 按 `5_905_580_032` 字节比较,不四舍五入、不累加多卡,也不使用 `MINERU_VIRTUAL_VRAM_SIZE`。独显读取专用显存总量;Apple 统一内存使用 Metal 推荐工作集,Windows/Linux 集显分别使用 DXGI 本地预算与 Vulkan `heapBudget`。预算比较使用上限,不减去当前用量;未知预算不以系统总内存替代。容量证据可通过 `mineru-kit hardware detect --json` 的 `gpu_memory` 查看。-自动推荐先解析有效小模型后端。Torch(包括 auto 最终选择 Torch)只验证实际设备可用性:可用 CUDA/MPS/XPU 等加速设备推荐 advanced;显式 CPU 或设备不可用时按 CPU 条件推荐,不下载 ONNX 校准模型或改写其配置/记录。Torch 推荐不依赖 llama.cpp 库存。+GPU 类型与 OCR、llama.cpp 和硬件诊断使用共享分类;目标运行后端可见且原生身份确认的独显可以免测速,但仍须满足 5.5 GiB 内存门槛才能开放 Standard/Advanced。ggml 的通用 GPU 标志、未知类型及虚拟 GPU 均不直接视为独显;同型号多卡无法唯一关联时保持保守结果。各后端可以选择不同 GPU,共用分类和优先级,不强制跨后端同卡。-ONNX 分支先探测硬件并读取已有校准记录。如果初选达到 Basic 或更高档位,Windows/Linux 会在发布服务能力前同步执行现有 ONNX 设备选择流程,再根据最新证据确定最终上限。初选只有 Flash、macOS 及其他平台跳过这一步;显式 `--tier` 和 Python 精确集合也不触发这项启动校准。+自动推荐先解析有效小模型后端。Torch(包括 auto 最终选择 Torch)验证实际设备可用性及容量:选中 CUDA/MPS/XPU 等设备的显存/预算至少 5.5 GiB 时推荐 advanced;显式 CPU 或设备不可用时按 CPU 条件推荐,不下载 ONNX 校准模型或改写其配置/记录。Torch 推荐不依赖 llama.cpp 库存。++ONNX 分支先探测硬件并读取已有校准记录。如果 CPU 至少 4 核或存在内存达标的兼容 GPU 候选,Windows/Linux 会在发布服务能力前同步执行现有 ONNX 设备选择流程,再根据实际选择和容量确定最终上限。CPU 不足 4 核且无内存达标候选、macOS 及其他平台跳过这一步;显式 `--tier` 和 Python 精确集合也不触发这项启动校准。启动选型继续遵守 `model.onnx_device`:`auto` 才按设备策略决定是否测速,显式或已保存的 `cpu/gpu` 不强制重新校准。Windows 确认的独显,以及 Linux 通过兼容检查、由 Vulkan 唯一识别并配置物理绑定的独显,均跳过 OCR 校准;首次真实 GPU 会话成功后才保存设备偏好。集显或类型无法确认的候选继续按 0.8 阈值测速。需要测速时会按正常模型生命周期准备或下载 OCR rec 权重,并复用已有进程缓存、文件锁、采样阈值及失败回退。下载和模型准备不计入 15 秒校准子进程超时。校准失败或结果不稳定不会阻止后续推荐,但不作为 GPU 胜出证据。实际 OCR 校准把证据保存在 `<配置文件路径>.onnx-calibration.json`,仅复用设备、运行时版本与 CPU 配置匹配的有效结果;旧 cpu/gpu 偏好及手动 GPU 设置不视为校准证据。启动阶段产生的新证据在本次最终推荐中生效,之后 `/v1/tiers` 在服务生命周期内固定。-远程 VLM 配置不自动扩大推荐上限,也不增加 VLM 性能测试或内存分级门槛。上述 OCR 选型不要求 `--preload-models`;该参数仍另外控制完整模型或 VLM 客户端的提前初始化。+远程 VLM 配置不自动扩大推荐上限或放宽本机内存门槛,也不增加 VLM 性能测试。上述 OCR 选型不要求 `--preload-models`;该参数仍另外控制完整模型或 VLM 客户端的提前初始化。`mineru-kit hardware detect` 使用同一结构化推荐流程;`hardware info` 只读输出诊断报告,详见 [hardware 命令](mineru-kit-hardware.md)。API 工厂的 VLM 配置覆盖也参与推荐,避免与实际运行配置不一致。diff --git a/docs/next/cli/mineru-kit-hardware.md b/docs/next/cli/mineru-kit-hardware.mdindex 12e82794..486f4f3f 100644--- a/docs/next/cli/mineru-kit-hardware.md+++ b/docs/next/cli/mineru-kit-hardware.md@@ -19,9 +19,13 @@ mineru-kit hardware info --json > hardware-info.json| 有效后端 | 行为 ||----------|------|-| Torch + 可用 CUDA/MPS/XPU 等加速设备 | 跳过 OCR 测速,推荐 advanced |-| Torch + 显式 CPU 或加速设备不可用 | 跳过测速,进程可用 CPU 至少 4 时推荐 standard,否则 flash |-| ONNX | 沿用既有硬件初选;初选至少 Basic 时在 Windows/Linux 同步完成适用的 OCR 选型,再确定最终上限 |+| Torch + 可用 CUDA/MPS/XPU 等加速设备 | 跳过 OCR 测速;选定设备的显存/预算至少 5.5 GiB 时推荐 advanced,否则按 CPU 条件推荐 |+| Torch + 显式 CPU 或加速设备不可用 | 跳过测速,进程可用逻辑 CPU 至少 4 时推荐 basic,否则 flash |+| ONNX | CPU 至少 4 核或存在内存达标的兼容 GPU 候选时,在 Windows/Linux 同步完成适用的 OCR 选型,再确定最终上限 |++自动推荐的 CPU 条件只开放 Basic:进程可用逻辑核数至少 4 时开放 `flash,basic`,默认请求 Basic,否则只开放 Flash。计数遵守进程亲和性和容器 CPU 配额。GPU 经现有选型确认可用且显存/预算至少 `5_905_580_032` 字节时,独立于 CPU 核数开放全部四档;默认请求仍为 Standard,Advanced 必须显式请求。++内存检查只使用确认设备的原始字节值,不四舍五入、不累加多卡,也不读取 `MINERU_VIRTUAL_VRAM_SIZE`。独显按专用显存总量判断;Apple Metal 按推荐工作集预算,Windows 集显按 DXGI 本地预算,Linux 集显按 Vulkan `heapBudget` 判断。预算比较使用上限,不减去当前用量。不能唯一关联设备、容量未知、预算扩展不可用或查询失败时按 CPU 条件推荐;系统总内存和共享内存理论上限不能替代 GPU 预算。`small_backend=auto` 最终选择 Torch 时同样免校准。显式设备字符串必须经过实际可用性检查;检查失败会给出保守结果及原因,不修改设备配置。Torch 推荐不依赖 llama.cpp 库存,不下载 ONNX 校准权重,也不写入 `model.onnx_device` 或 OCR 校准记录。@@ -31,7 +35,9 @@ llama.cpp 自动集显路径同样按有效小模型后端分流:Torch 使用OCR、llama.cpp、档位推荐与诊断共用 GPU 分类和双向唯一身份匹配。先按各后端的实际可见性和兼容性过滤,再按独显、集显、虚拟 GPU、未知类型排序;后端之间无需选择同一张卡。ggml 的 GPU/IGPU 标志不再直接作为独显判据,Windows 使用 D3D12 UMA、Linux 使用 Vulkan 原生分类。无法唯一关联的设备保留未知类型,不授予独显免校准或仅凭类型开放 Advanced。-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`,不将可用性结论标成性能实测通过。+JSON 报告保留 `schema_version=1`,包含 `ceiling`、`pdf_image_tiers`、`default_request_tier`、`reason`、`cpu_count`、`small_backend`、`vlm_engine`、`device`、`calibration` 和 `warnings`,并增补 `gpu_memory`。内存证据包含 `device`、`identity`、`memory_bytes`、`kind`(`dedicated`/`budget`/`unknown`)、`source`、`warning`;没有候选设备时为 `null`。校准状态来自执行结果;Torch 使用 `status=skipped, reason=torch_backend`,不将可用性结论标成性能实测通过。++本次实际选型落在 CPU、校准失败或证据失效时,不会凭静态显卡库存重新开放高档位。设备容量信息不进入 OCR 校准指纹,既有有效测速记录可以继续复用。每个服务在启动阶段形成一次最终开放集合,运行过程中不动态升降档位。开放 Advanced 后,请求省略 tier 仍默认 Standard。推荐不代表模型已准备好,API 服务继续执行依赖预检;显式启动上限和 Python 精确集合不进入自动推荐。API 工厂的 VLM 配置覆盖参与共享推荐,远程 VLM 显示为 `http-client`,不自动扩大本机上限。diff --git a/docs/next/decisions/0017-mineru-kit-api-server-command.md b/docs/next/decisions/0017-mineru-kit-api-server-command.mdindex 4ffa22fa..d34e9c2c 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` 均直接移除。-自动推荐先按有效小模型后端分流。Torch 使用实际加速设备可用性,GPU 路径开放 Advanced,CPU 路径按可用核数推荐,不执行 OCR 校准或写入 ONNX 配置。ONNX 沿用现有 CPU、独显、有效 OCR 校准和 Apple Silicon Metal 规则;初选达到 Basic 时,Windows/Linux 同步完成适用选型,再按最新证据确定本次上限。初选仅 Flash 或显式指定上限不增加启动校准。不引入新的采样阈值、VLM 实测或内存门槛。依赖预检与可选预加载仍执行,Advanced 复用 Standard 模型配置。`hardware detect` 与服务使用相同结构化推荐。+自动推荐先按有效小模型后端分流:CPU 可用逻辑核至少 4 时开放到 Basic,否则只开放 Flash。GPU 经既有选型确认可用且选定设备显存/预算至少 5.5 GiB 时,独立于 CPU 核数开放全部四档。Torch、Apple Metal 和符合既有绑定规则的独显保留免测速路径;其他 ONNX GPU 仍须校准胜出。CPU 至少 4 核或存在内存达标的兼容 GPU 候选时,Windows/Linux 在本次启动内完成适用选型;最终 CPU 回退不能被静态库存覆盖。显式启动上限跳过推荐。不引入新的采样阈值或 VLM 实测,依赖预检与可选预加载仍执行。Advanced 复用 Standard 模型配置,请求默认仍优先 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.mdindex d6c73347..894f68ae 100644--- a/docs/next/onnx-device.md+++ b/docs/next/onnx-device.md@@ -97,7 +97,7 @@ MinerU 的 WebGPU 运行时锁覆盖过滤与会话初始化,后续每次会本机双卡及仅 Intel ICD 的验证见 [Intel 架构过滤报告](onnx-intel-architecture-policy-validation.md)。-通常在首次实际使用 ONNX 模型时选型。API 使用 `--tier auto`(或省略),有效小模型后端为 ONNX 且硬件初选达到 Basic 时,Windows/Linux 会提前同步调用相同的设备选择流程,校准证据在本次最终档位推荐中生效,不依赖 `--preload-models`。初选仅 Flash、显式启动档位或 macOS 不增加这项启动选型。有效小模型后端为 Torch 时采用实际设备可用性结果并跳过 OCR 校准,不修改 ONNX 设备偏好或证据;llama.cpp 自动集显路径也遵循这处分流。+通常在首次实际使用 ONNX 模型时选型。API 使用 `--tier auto`(或省略),有效小模型后端为 ONNX,且可用逻辑 CPU 至少 4 核或存在显存/预算达到 5.5 GiB 的兼容 GPU 候选时,Windows/Linux 会提前同步调用相同的设备选择流程,校准证据在本次最终档位推荐中生效,不依赖 `--preload-models`。CPU 不足 4 核且无内存达标 GPU 候选、显式启动档位或 macOS 不增加这项启动选型。有效小模型后端为 Torch 时采用实际设备可用性和内存证据并跳过 OCR 校准,不修改 ONNX 设备偏好或证据;llama.cpp 自动集显路径也遵循这处分流。`mineru-kit hardware detect` 与 API 自动启动共享推荐逻辑;`hardware info` 只读报告环境与校准记录,不测速。界面启动本身、导入 SDK、查询配置和模型列表不会运行测速;界面托管的 API 服务仍遵循其启动参数。自动决策成功后原子更新有效配置文件中的 `model.onnx_device`,保留其余键;进程间通过文件锁协调。diff --git a/docs/next/open-questions.md b/docs/next/open-questions.mdindex e444348d..0c22d1df 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,Torch 按实际设备可用性免校准,ONNX 初选达到 basic 时在适用平台同步完成 OCR 选型,HTTP 请求默认仍优先 standard;`hardware detect` 共享推荐逻辑。 |+| api-server tier | `mineru-kit api-server --tier` 配置最高开放档位;省略等价于 auto,CPU 至少 4 核默认开放 basic,GPU 确认可用且显存/预算至少 5.5 GiB 才开放更高档位;Torch 免校准,ONNX 在 CPU 或 GPU 候选达标时同步完成适用选型,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.mdindex e584914b..89319867 100644--- a/docs/next/tiers.md+++ b/docs/next/tiers.md@@ -100,9 +100,11 @@ advanced 只接受显式选择:只有 advanced 时没有默认档位,返回### 3.4 API 服务启动推荐-`--tier auto` 或省略启动参数时,先解析有效小模型后端。Torch 有经核验可用的 CUDA/MPS/XPU 等加速设备时开放全部四档,跳过 OCR 校准;显式 CPU 或设备不可用时,进程可用逻辑 CPU 至少 4 开放 flash、basic、standard,否则只开放 flash。此规则也适用于 auto 最终选择 Torch,不改写 ONNX 配置或校准记录。+`--tier auto` 或省略启动参数时,进程可用逻辑 CPU 至少 4 核默认开放 flash、basic,否则只开放 flash;计数遵守亲和性和容器配额。只有实际 GPU 已经确认可用,并且选中设备的专用显存总量或 GPU 内存预算至少 5.5 GiB,才开放 standard、advanced。GPU 达标不要求 CPU 同时达到 4 核;开放全部四档时请求默认仍为 standard。-ONNX 保留既有规则:CPU 不足 4 且没有达标 GPU 时只开放 flash;CPU 至少 4 时开放到 standard;可用独显、有效 OCR 校准达标的集显或 Metal 可用的 Apple Silicon 开放全部四档。初选达到 basic 后,Windows/Linux 同步完成现有 ONNX 选型和适用校准,再确定本次上限。最终集合在启动时固定,不增加 VLM 性能测试或额外内存分级。`mineru-kit hardware detect` 共享这套推荐;`hardware info` 只读收集环境信息。+自动推荐先解析有效小模型后端。Torch(包括 auto 最终选择 Torch)、Apple Metal 和符合既有确认与绑定规则的独显保留免 OCR 测速路径;其他 ONNX GPU 继续要求有效校准胜出。CPU 至少 4 核或存在内存达标的兼容 GPU 候选时,Windows/Linux 在本次启动内完成适用的 ONNX 选型。最终选中 CPU、校准失败、设备身份不明确或内存未知时按 CPU 条件推荐,静态 GPU 库存不能覆盖最终结果。++显存按原始字节比较,不取整、不累加多卡,不使用虚拟显存覆盖。统一/共享内存使用 Metal 推荐工作集、DXGI 本地预算或 Vulkan `heapBudget`,不以系统总内存替代。最终集合在启动时固定;`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/hardware.py b/mineru/kit/commands/hardware.pyindex 40eb1032..fb4a05ca 100644--- a/mineru/kit/commands/hardware.py+++ b/mineru/kit/commands/hardware.py@@ -37,6 +37,15 @@ def render_detection(data: dict[str, Any]) -> str:f"实际设备:{data['device']}",f"校准状态:{calibration['status']} ({calibration['reason']})",]+ memory = data.get("gpu_memory")+ if memory is not None:+ lines.extend(+ [+ f"GPU 内存设备:{memory['device']},身份:{_value(memory['identity'])}",+ f"GPU 内存:{_value(memory['memory_bytes'])} bytes,口径:{memory['kind']},来源:{memory['source']}",+ "Standard/Advanced 内存门槛:5.5 GiB (5905580032 bytes)",+ ]+ )lines.extend(f"提示:{warning}" for warning in data.get("warnings", []))return "\n".join(lines)diff --git a/mineru/model/runtime/gpu_memory.py b/mineru/model/runtime/gpu_memory.pynew file mode 100644index 00000000..2c731b86--- /dev/null+++ b/mineru/model/runtime/gpu_memory.py@@ -0,0 +1,123 @@+# Copyright (c) Opendatalab. All rights reserved.+"""为自动档位提供选定设备的精确内存证据,不使用虚拟显存或系统内存替代预算。"""++from __future__ import annotations++from dataclasses import dataclass, replace+import sys+from typing import Literal++from .gpu import GpuIdentity, match_gpu_identities++MIN_GPU_MEMORY_BYTES = 11 * 1024**3 // 2 # 5.5 GiB,始终使用整数字节比较。+++@dataclass(frozen=True)+class GpuMemory:+ """一次设备查询的容量、口径和来源;未知容量保留为空并携带原因。"""++ device: str+ identity: GpuIdentity+ memory_bytes: int | None = None+ kind: Literal["dedicated", "budget", "unknown"] = "unknown"+ source: str = "unknown"+ warning: str | None = None++ @property+ def sufficient(self) -> bool:+ """按原始字节判断 5.5 GiB 边界,不四舍五入、不累加不同显卡。"""+ return self.memory_bytes is not None and self.memory_bytes >= MIN_GPU_MEMORY_BYTES+++def _validated(memory: GpuMemory) -> GpuMemory:+ """未知或非法容量统一降为未知,保留探测来源和具体错误。"""+ if type(memory.memory_bytes) is int and memory.memory_bytes > 0:+ return memory+ return replace(memory, memory_bytes=None, warning=memory.warning or "GPU memory capacity or budget is unavailable")+++def native_gpu_memory(identity: GpuIdentity, *, device: str) -> GpuMemory:+ """通过双向唯一身份关联查询选中 GPU,不能关联时禁止借用其他设备的容量。"""+ result = GpuMemory(device, identity)+ try:+ if sys.platform == "win32":+ from .windows_gpu import inspect_gpus++ rows = inspect_gpus(include_memory_budget=True)+ identities = [GpuIdentity(row["vendor_id"], row["device_id"], luid=row["luid"], name=row["name"]) for row in rows]+ matched = match_gpu_identities((identity,), identities, allow_name=True)[0]+ if matched is not None:+ row = rows[matched]+ dedicated = row["kind"] == "discrete"+ result = GpuMemory(+ device,+ identities[matched],+ row.get("dedicated_memory_bytes") if dedicated else row.get("memory_budget_bytes"),+ "dedicated" if dedicated else "budget",+ "dxgi.dedicated_video_memory" if dedicated else "dxgi.local_budget",+ row.get("memory_error"),+ )+ elif sys.platform == "linux":+ from .vulkan import enumerate_vulkan_devices, vulkan_environment_lock++ with vulkan_environment_lock():+ devices = enumerate_vulkan_devices(include_memory=True)+ matched = match_gpu_identities((identity,), [item.identity for item in devices], allow_name=True)[0]+ if matched is not None:+ item = devices[matched]+ dedicated = item.kind == "discrete"+ result = GpuMemory(+ device,+ item.identity,+ item.dedicated_memory_bytes if dedicated else item.memory_budget_bytes,+ "dedicated" if dedicated else "budget",+ "vulkan.device_local_heap" if dedicated else "vulkan.heap_budget",+ item.memory_error,+ )+ if result.source == "unknown":+ result = replace(result, warning="GPU memory device identity could not be uniquely matched")+ except Exception as error:+ result = replace(result, warning=f"GPU memory discovery failed: {error}")+ return _validated(result)+++def torch_gpu_memory(device: str) -> GpuMemory:+ """惰性读取 Torch 选定设备的容量;MPS 与集显使用运行时预算且不创建模型。"""+ result = GpuMemory(device, GpuIdentity(name=device))+ try:+ import torch++ kind, _, index_text = device.partition(":")+ if kind == "mps":+ return _validated(+ GpuMemory(+ device, result.identity, torch.mps.recommended_max_memory(), "budget", "metal.recommended_working_set"+ )+ )+ if kind == "npu":+ import torch_npu++ api = torch_npu.npu+ else:+ api = getattr(torch, kind)+ index = int(index_text) if index_text else api.current_device()+ properties = api.get_device_properties(index)+ selected = f"{kind}:{index}"+ identity = GpuIdentity(+ vendor_id=0x8086 if kind == "xpu" else None,+ device_id=getattr(properties, "device_id", None),+ bus_id=getattr(properties, "pci_bus_id", None),+ name=getattr(properties, "name", None),+ )+ integrated = getattr(properties, "is_integrated_gpu", getattr(properties, "is_integrated", None))+ if integrated or (kind == "xpu" and integrated is None):+ return native_gpu_memory(identity, device=selected)+ result = GpuMemory(+ selected, identity, getattr(properties, "total_memory", None), "dedicated", f"torch.{kind}.total_memory"+ )+ except Exception as error:+ result = replace(result, warning=f"GPU memory discovery failed: {error}")+ return _validated(result)+++__all__ = ["GpuMemory", "MIN_GPU_MEMORY_BYTES", "native_gpu_memory", "torch_gpu_memory"]diff --git a/mineru/model/runtime/onnx_device.py b/mineru/model/runtime/onnx_device.pyindex 45be04bb..aa2e0c7a 100644--- a/mineru/model/runtime/onnx_device.py+++ b/mineru/model/runtime/onnx_device.py@@ -147,7 +147,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:- """在首次模型使用或达到 Basic 的 API 自动推荐时选型;导入和诊断命令不调用。"""+ """在首次模型使用或 CPU/GPU 候选达标的 API 自动推荐时选型;导入和只读诊断不调用。"""from ...config import get_config, get_config_file_path, get_config_sourcerequested = get_config().model.onnx_devicediff --git a/mineru/model/runtime/tier_recommendation.py b/mineru/model/runtime/tier_recommendation.pyindex d69ed42c..3246e605 100644--- a/mineru/model/runtime/tier_recommendation.py+++ b/mineru/model/runtime/tier_recommendation.py@@ -3,7 +3,7 @@from __future__ import annotations-from dataclasses import dataclass+from dataclasses import dataclass, replaceimport osimport sysfrom typing import TYPE_CHECKING@@ -14,10 +14,12 @@ from ...types import TIERS, Tierfrom .cpu_threads import effective_cpu_countfrom .device import resolve_small_model_backend, resolve_torch_devicefrom .gpu import is_discrete_gpu, match_gpu_identities+from .gpu_memory import GpuMemory, native_gpu_memory, torch_gpu_memoryfrom .onnx_calibration_cache import CalibrationInfo, inspect_calibration_recordif TYPE_CHECKING:from ...config import VlmConfig+ from .onnx_device import OnnxSelection@dataclass(frozen=True)@@ -44,6 +46,7 @@ class TierRecommendation:calibration: CalibrationDecisionwarnings: tuple[str, ...] = ()schema_version: int = 1+ gpu_memory: GpuMemory | None = None@dataclass(frozen=True)@@ -53,14 +56,15 @@ class TierHardware:cpu_count: intadvanced_gpu: bool = Falsereason: str = "cpu"+ gpu_memory: GpuMemory | None = Nonedef tiers_for_hardware(hardware: TierHardware) -> frozenset[Tier]:"""按已确定的工程阈值计算集合,达标 GPU 同时开放所有较低档位。"""- if hardware.advanced_gpu:+ if hardware.advanced_gpu and hardware.gpu_memory is not None and hardware.gpu_memory.sufficient:return frozenset(TIERS)if hardware.cpu_count >= 4:- return frozenset(("flash", "basic", "standard"))+ return frozenset(("flash", "basic"))return frozenset(("flash",))@@ -75,29 +79,46 @@ def _apple_metal_available() -> bool:return torch.backends.mps.is_available()-def _advanced_gpu_reason() -> str | None:- """复用可见设备及兼容策略,集显只读取证据而不触发自动校准。"""+def _gpu_hardware(count: int, confirmed: bool, reason: str, memory: GpuMemory) -> TierHardware:+ """把设备确认和容量阈值合并为一次可解释的推荐,不把配置偏好当成性能证据。"""+ if confirmed and not memory.sufficient:+ reason = "gpu_memory_unknown" if memory.memory_bytes is None else "gpu_memory_insufficient"+ return TierHardware(count, confirmed and memory.sufficient, reason, memory)+++def _onnx_gpu_hardware(count: int, choice: OnnxSelection | None = None) -> TierHardware:+ """初选只读候选和旧证据;最终推荐严格采用本次选型,CPU 或失败不能被库存升级。"""+ from ...config import get_config++ if choice is not None and (choice.device != "gpu" or choice.adapter is None):+ return TierHardware(count, reason=choice.reason)backend = os.getenv("MINERU_LLAMA_CPP_BACKEND", "auto")if backend == "cpu":- return None+ return TierHardware(count, reason="configured_cpu")if sys.platform == "darwin":- # ggml 的 Metal GPU 类型不能区分独显与集显,只采用已确认的 Apple Silicon 规则。- return "apple_silicon_metal" if backend in {"auto", "metal"} and _apple_metal_available() else None+ if backend in {"auto", "metal"} and _apple_metal_available():+ return _gpu_hardware(count, True, "apple_silicon_metal", torch_gpu_memory("mps"))+ return TierHardware(count)if sys.platform not in {"linux", "win32"}:- return None+ return TierHardware(count)+ if choice is None and get_config().model.onnx_device == "cpu":+ return TierHardware(count, reason="configured_cpu")from .llama_device import discover_llama_devicesdevices = tuple(d for d in discover_llama_devices() if backend == "auto" or d.backend == backend)- if any(is_discrete_gpu(device) for device in devices):- return "discrete_gpu"if not devices:- return None+ return TierHardware(count, reason="no_visible_gpu")from .onnx_calibration_cache import calibrated_gpu_is_fasterfrom .onnx_device import ONNX_GPU_TIME_RATIO_THRESHOLDS- if sys.platform == "win32":+ from .webgpu import WebGPUDevice++ if choice is not None:+ adapter = choice.adapter+ threshold = ONNX_GPU_TIME_RATIO_THRESHOLDS.get(choice.backend)+ elif sys.platform == "win32":from .windows_gpu import discover_gpus, preferred_gpuadapter = preferred_gpu(discover_gpus())@@ -108,15 +129,17 @@ def _advanced_gpu_reason() -> str | None:adapter = select_webgpu_device(discover_webgpu_devices())threshold = ONNX_GPU_TIME_RATIO_THRESHOLDS["webgpu"]if adapter is None or threshold is None:- return None+ return TierHardware(count, reason="no_eligible_gpu")matched = match_gpu_identities((adapter.identity,), [device.identity for device in devices])[0]if matched is None:- logger.info("GPU tier recommendation uses CPU rules: OCR adapter identity is not uniquely matched")- return None- if calibrated_gpu_is_faster(adapter, threshold):- return "ocr_calibrated_gpu"- logger.info("GPU tier recommendation uses CPU rules: no matching valid OCR evidence of a faster GPU")- return None+ return TierHardware(count, reason="gpu_identity_unconfirmed")+ memory = native_gpu_memory(adapter.identity, device=f"{choice.backend if choice else 'onnx'}:gpu")+ discrete = (is_discrete_gpu(adapter) or is_discrete_gpu(devices[matched])) and (+ not isinstance(adapter, WebGPUDevice) or adapter.vulkan_device == (adapter.vendor_id, adapter.device_id)+ )+ calibrated = (choice is not None and choice.reason == "rec_calibration") or calibrated_gpu_is_faster(adapter, threshold)+ reason = "discrete_gpu" if discrete else "ocr_calibrated_gpu" if calibrated else "gpu_calibration_required"+ return _gpu_hardware(count, discrete or calibrated, reason, memory)def detect_tier_hardware() -> TierHardware:@@ -127,11 +150,10 @@ def detect_tier_hardware() -> TierHardware:logger.warning("CPU availability discovery failed: {}", error)count = 1try:- reason = _advanced_gpu_reason()+ return _onnx_gpu_hardware(count)except Exception as error:logger.warning("GPU tier recommendation unavailable; using CPU rules: {}", error)return TierHardware(count, reason="gpu_discovery_unavailable")- return TierHardware(count, bool(reason), reason or "cpu")def recommend_tiers(*, vlm_config: VlmConfig | None = None) -> TierRecommendation:@@ -153,15 +175,23 @@ def recommend_tiers(*, vlm_config: VlmConfig | None = None) -> TierRecommendatioexcept OSError as error:count = 1warnings.append(f"CPU availability discovery failed: {error}")- hardware = TierHardware(count, choice.accelerated, choice.reason)+ hardware = (+ _gpu_hardware(count, True, choice.reason, torch_gpu_memory(choice.device))+ if choice.accelerated+ else TierHardware(count, reason=choice.reason)+ )device = choice.devicecalibration = CalibrationDecision("skipped", "torch_backend")if choice.warning:warnings.append(choice.warning)else:hardware = detect_tier_hardware()+ if hardware.gpu_memory is not None and hardware.gpu_memory.device == "mps":+ device = "mps"+ calibration = CalibrationDecision("skipped", "apple_silicon_metal")tiers = tiers_for_hardware(hardware)- if small_backend == "onnx" and "basic" in tiers and sys.platform in {"win32", "linux"}:+ gpu_candidate = hardware.gpu_memory is not None and hardware.gpu_memory.sufficient+ if small_backend == "onnx" and ("basic" in tiers or gpu_candidate) 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@@ -185,15 +215,20 @@ def recommend_tiers(*, vlm_config: VlmConfig | None = None) -> TierRecommendatioelif 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)+ hardware = _onnx_gpu_hardware(hardware.cpu_count, onnx_choice)except Exception as error:- logger.warning("Startup ONNX selection unavailable; recommending tiers from current evidence: {}", error)+ logger.warning("Startup ONNX selection unavailable; using CPU recommendation rules: {}", error)warnings.append(f"ONNX selection unavailable: {error}")calibration = CalibrationDecision("failed", "selection_unavailable")- # 校准会写入新证据或撤销旧证据,必须在发布能力前重新计算,不能等到下次启动。- hardware = detect_tier_hardware()+ hardware = replace(hardware, advanced_gpu=False, reason="selection_unavailable")+ # 以实际选择形成最终结果,不能重新扫描库存覆盖本次 CPU 回退。tiers = tiers_for_hardware(hardware)if hardware.reason == "gpu_discovery_unavailable":warnings.append("GPU discovery unavailable; using CPU recommendation rules")+ if hardware.gpu_memory is not None and hardware.gpu_memory.warning:+ warnings.append(hardware.gpu_memory.warning)+ if hardware.reason == "gpu_identity_unconfirmed":+ warnings.append("GPU device identity could not be uniquely matched; using CPU recommendation rules")logger.info("Recommended API tiers: {} (available CPUs: {}, reason: {})",",".join(tier for tier in TIERS if tier in tiers),@@ -213,6 +248,7 @@ def recommend_tiers(*, vlm_config: VlmConfig | None = None) -> TierRecommendatiodevice,calibration,tuple(warnings),+ gpu_memory=hardware.gpu_memory,)diff --git a/mineru/model/runtime/vulkan.py b/mineru/model/runtime/vulkan.pyindex 0a5b9e89..d57795e3 100644--- a/mineru/model/runtime/vulkan.py+++ b/mineru/model/runtime/vulkan.py@@ -12,6 +12,7 @@ from dataclasses import dataclassimport osimport sysimport threading+from typing import Anyfrom .gpu import GpuClassification, GpuIdentity, classify_vulkan_gpu, with_gpu_classification@@ -29,6 +30,9 @@ class VulkanDevice(GpuClassification):device_id: intname: strindex: int = -1+ dedicated_memory_bytes: int | None = None+ memory_budget_bytes: int | None = None+ memory_error: str | None = None@propertydef identity(self) -> GpuIdentity:@@ -79,13 +83,78 @@ class _PropertiesStorage(ct.Union):_fields_ = [("prefix", _PropertiesPrefix), ("storage", ct.c_uint64 * 128)]+class _MemoryType(ct.Structure):+ _fields_ = [("flags", ct.c_uint32), ("heap_index", ct.c_uint32)]+++class _MemoryHeap(ct.Structure):+ _fields_ = [("size", ct.c_uint64), ("flags", ct.c_uint32)]+++class _MemoryProperties(ct.Structure):+ _fields_ = [+ ("type_count", ct.c_uint32),+ ("types", _MemoryType * 32),+ ("heap_count", ct.c_uint32),+ ("heaps", _MemoryHeap * 16),+ ]+++class _MemoryProperties2(ct.Structure):+ _fields_ = [("sType", ct.c_uint32), ("pNext", ct.c_void_p), ("memory", _MemoryProperties)]+++class _MemoryBudget(ct.Structure):+ _fields_ = [+ ("sType", ct.c_uint32),+ ("pNext", ct.c_void_p),+ ("budget", ct.c_uint64 * 16),+ ("usage", ct.c_uint64 * 16),+ ]+++class _ExtensionProperties(ct.Structure):+ _fields_ = [("name", ct.c_char * 256), ("version", ct.c_uint32)]+++def _device_memory(library: Any, handle: ct.c_void_p, *, discrete: bool) -> tuple[int | None, int | None]:+ """按唯一设备的本地堆读取容量和预算;共享内存无预算扩展时保持未知。"""+ properties = library.vkGetPhysicalDeviceMemoryProperties+ properties.argtypes, properties.restype = [ct.c_void_p, ct.POINTER(_MemoryProperties)], None+ memory = _MemoryProperties()+ properties(handle, ct.byref(memory))+ local = [index for index in range(min(memory.heap_count, 16)) if memory.heaps[index].flags & 1]+ total = sum(memory.heaps[index].size for index in local) or None+ if discrete:+ return total, None+ extensions = library.vkEnumerateDeviceExtensionProperties+ extensions.argtypes = [ct.c_void_p, ct.c_char_p, ct.POINTER(ct.c_uint32), ct.POINTER(_ExtensionProperties)]+ extensions.restype = ct.c_int32+ count = ct.c_uint32()+ _check(extensions(handle, None, ct.byref(count), None), "count memory extensions")+ rows = (_ExtensionProperties * count.value)()+ _check(extensions(handle, None, ct.byref(count), rows), "read memory extensions")+ if not any(row.name == b"VK_EXT_memory_budget" for row in rows):+ return None, None+ budget = _MemoryBudget(sType=1000237000)+ info = _MemoryProperties2(sType=1000059006, pNext=ct.cast(ct.pointer(budget), ct.c_void_p))+ properties2 = library.vkGetPhysicalDeviceMemoryProperties2+ properties2.argtypes, properties2.restype = [ct.c_void_p, ct.POINTER(_MemoryProperties2)], None+ properties2(handle, ct.byref(info))+ # 预算为进程可用上限,不减去当前用量;每个物理堆只计一次。+ local = [index for index in range(min(info.memory.heap_count, 16)) if info.memory.heaps[index].flags & 1]+ if not local or any(budget.budget[index] == 0 for index in local):+ return None, None+ return None, sum(min(budget.budget[index], info.memory.heaps[index].size) for index in local)++def _check(result: int, operation: str) -> None:if result != 0:raise RuntimeError(f"Vulkan {operation} failed ({result})")-def enumerate_vulkan_devices() -> tuple[VulkanDevice, ...]:- """Enumerate GPUs visible to the loader, honoring the user's ICD/layer filters."""+def enumerate_vulkan_devices(*, include_memory: bool = False) -> tuple[VulkanDevice, ...]:+ """遵守 ICD 和设备过滤枚举 GPU;仅推荐容量时额外读取本地堆或共享预算。"""library = ct.WinDLL("vulkan-1.dll") if sys.platform == "win32" else ct.CDLL("libvulkan.so.1")create = library.vkCreateInstancecreate.argtypes = [ct.POINTER(_InstanceCreateInfo), ct.c_void_p, ct.POINTER(ct.c_void_p)]@@ -118,6 +187,12 @@ def enumerate_vulkan_devices() -> tuple[VulkanDevice, ...]:properties(handle, ct.byref(storage))value = storage.prefixif value.deviceType in (0, 1, 2, 3): # 保留未知原生类型,由运行后端过滤可用性;排除软件 CPU。+ total, budget, memory_error = None, None, None+ if include_memory:+ try:+ total, budget = _device_memory(library, handle, discrete=value.deviceType == 2)+ except Exception as error:+ memory_error = str(error)result.append(with_gpu_classification(VulkanDevice(@@ -125,6 +200,9 @@ def enumerate_vulkan_devices() -> tuple[VulkanDevice, ...]:value.deviceID,value.deviceName.decode("utf-8", errors="replace"),index,+ total,+ budget,+ memory_error,),classify_vulkan_gpu(value.deviceType),)diff --git a/mineru/model/runtime/windows_gpu.py b/mineru/model/runtime/windows_gpu.pyindex 32c875b4..4680b509 100644--- a/mineru/model/runtime/windows_gpu.py+++ b/mineru/model/runtime/windows_gpu.py@@ -66,6 +66,29 @@ class _Architecture(C.Structure):]+class _VideoMemoryInfo(C.Structure):+ _fields_ = [+ ("budget", C.c_uint64),+ ("usage", C.c_uint64),+ ("available_for_reservation", C.c_uint64),+ ("reservation", C.c_uint64),+ ]+++def _memory_budget(adapter: C.c_void_p) -> int:+ """读取同一 UMA 适配器的本地内存预算,查询接口始终成对释放。"""+ adapter3 = C.c_void_p()+ query = _method(adapter, 0, C.c_int32, C.POINTER(_Guid), C.POINTER(C.c_void_p))+ _check(query(adapter, C.byref(_guid("645967a4-1392-4310-a798-8053ce3e93fd")), C.byref(adapter3)))+ try:+ memory = _VideoMemoryInfo()+ read = _method(adapter3, 14, C.c_int32, C.c_uint32, C.c_int32, C.POINTER(_VideoMemoryInfo))+ _check(read(adapter3, 0, 0, C.byref(memory)))+ return memory.budget+ finally:+ _release(adapter3)++def _guid(value: str) -> _Guid:return _Guid.from_buffer_copy(uuid.UUID(value).bytes_le)@@ -184,7 +207,7 @@ def preferred_gpu(adapters: tuple[GpuAdapter, ...]) -> GpuAdapter | None:return min(adapters, key=lambda item: (gpu_kind_rank(item.kind), item.preference, item.index), default=None)-def inspect_gpus() -> list[dict[str, Any]]:+def inspect_gpus(*, include_memory_budget: bool = False) -> list[dict[str, Any]]:"""诊断库存保留不支持 D3D12 的硬件,并读取 DXGI 的 64 位显存容量。"""if sys.platform != "win32":return []@@ -212,6 +235,12 @@ def inspect_gpus() -> list[dict[str, Any]]:if desc.flags & 2:continuesupported, uma = _architecture(adapter, create_device)+ budget, memory_error = None, None+ if include_memory_budget and uma is True:+ try:+ budget = _memory_budget(adapter)+ except Exception as error:+ memory_error = str(error)result.append({"name": desc.name,@@ -222,6 +251,8 @@ def inspect_gpus() -> list[dict[str, Any]]:**asdict(classify_d3d12_gpu(uma)),"dedicated_memory_bytes": desc.video_memory,"shared_memory_bytes": desc.shared_memory,+ "memory_budget_bytes": budget,+ "memory_error": memory_error,})finally:diff --git a/tests/unittest/test_gpu_memory.py b/tests/unittest/test_gpu_memory.pynew file mode 100644index 00000000..94e713fb--- /dev/null+++ b/tests/unittest/test_gpu_memory.py@@ -0,0 +1,202 @@+"""选中设备容量、共享预算与原生 ABI 的回归,避免依赖宿主显卡。"""++from __future__ import annotations++import ctypes as ct+from dataclasses import replace+import sys+from types import SimpleNamespace+from typing import Any+from unittest.mock import Mock++import pytest++from mineru.model.runtime import gpu_memory, vulkan, windows_gpu+from mineru.model.runtime.gpu import GpuIdentity++[email protected]("device", ["cuda:1", "cuda"])+def test_torch_reads_exact_selected_device_bytes(monkeypatch: pytest.MonkeyPatch, device: str) -> None:+ """显式序号和默认当前设备都不借用零号大卡,虚拟显存和四舍五入不参与。"""+ values = (24 * 1024**3, 5_905_580_032 - 1)+ properties = Mock(side_effect=lambda index: SimpleNamespace(name=f"GPU {index}", total_memory=values[index]))+ monkeypatch.setitem(+ sys.modules, "torch", SimpleNamespace(cuda=SimpleNamespace(current_device=lambda: 1, get_device_properties=properties))+ )+ monkeypatch.setenv("MINERU_VIRTUAL_VRAM_SIZE", "128")+ result = gpu_memory.torch_gpu_memory(device)+ assert result.device == "cuda:1" and result.memory_bytes == values[1] and not result.sufficient+ assert result.kind == "dedicated" and result.source == "torch.cuda.total_memory"+ properties.assert_called_once_with(1)++[email protected]("amount", [None, 0, 5_905_580_032 - 1, 5_905_580_032, 6 * 1024**3 - 1, 8 * 1024**3])+def test_metal_uses_recommended_budget(monkeypatch: pytest.MonkeyPatch, amount: int | None) -> None:+ """Metal 只读推荐工作集,不拿系统总内存或当前空闲内存替代。"""+ monkeypatch.setitem(sys.modules, "torch", SimpleNamespace(mps=SimpleNamespace(recommended_max_memory=lambda: amount)))+ result = gpu_memory.torch_gpu_memory("mps")+ assert result.memory_bytes == (amount or None)+ assert result.sufficient is (amount is not None and amount >= 5_905_580_032)+ assert result.kind == "budget" and result.source == "metal.recommended_working_set"+ assert bool(result.warning) is (not amount)++[email protected]("platform", ["linux", "win32"])[email protected]("integrated", [False, True])[email protected]("amount", [None, 5_905_580_032 - 1, 5_905_580_032, 6 * 1024**3 - 1])+def test_native_capacity_belongs_to_selected_gpu(+ monkeypatch: pytest.MonkeyPatch, platform: str, integrated: bool, amount: int | None+) -> None:+ """库存中的其他大卡不授予能力;集显的大共享上限不能替代预算。"""+ monkeypatch.setattr(gpu_memory, "sys", SimpleNamespace(platform=platform))+ identity = GpuIdentity(0x8086, 1, luid="selected" if platform == "win32" else None)+ kind = "integrated" if integrated else "discrete"+ if platform == "win32":+ rows = [+ {+ "vendor_id": 0x8086,+ "device_id": 2,+ "name": "other",+ "luid": "other",+ "kind": "discrete",+ "dedicated_memory_bytes": 24 * 1024**3,+ },+ {+ "vendor_id": 0x8086,+ "device_id": 1,+ "name": "selected",+ "luid": "selected",+ "kind": kind,+ "dedicated_memory_bytes": 512 * 1024**2 if integrated else amount,+ "memory_budget_bytes": amount if integrated else None,+ "shared_memory_bytes": 128 * 1024**3,+ },+ ]+ monkeypatch.setattr(windows_gpu, "inspect_gpus", lambda **kwargs: rows)+ else:+ devices = (+ vulkan.VulkanDevice(0x8086, 2, "other", kind="discrete", dedicated_memory_bytes=24 * 1024**3),+ vulkan.VulkanDevice(+ 0x8086,+ 1,+ "selected",+ kind=kind,+ dedicated_memory_bytes=None if integrated else amount,+ memory_budget_bytes=amount if integrated else None,+ ),+ )+ monkeypatch.setattr(vulkan, "enumerate_vulkan_devices", lambda **kwargs: devices)+ result = gpu_memory.native_gpu_memory(identity, device="selected")+ assert result.memory_bytes == amount+ assert result.kind == ("budget" if integrated else "dedicated")+ assert result.sufficient is (amount is not None and amount >= 5_905_580_032)+++def test_ambiguous_native_gpu_does_not_borrow_capacity(monkeypatch: pytest.MonkeyPatch) -> None:+ """同型号多卡缺少强身份时,即使某卡容量达标也不能猜测归属。"""+ monkeypatch.setattr(gpu_memory, "sys", SimpleNamespace(platform="linux"))+ first = vulkan.VulkanDevice(0x8086, 1, "GPU", kind="discrete", dedicated_memory_bytes=4 * 1024**3)+ monkeypatch.setattr(+ vulkan, "enumerate_vulkan_devices", lambda **kwargs: (first, replace(first, dedicated_memory_bytes=24 * 1024**3))+ )+ result = gpu_memory.native_gpu_memory(first.identity, device="selected")+ assert result.memory_bytes is None and not result.sufficient and "uniquely matched" in result.warning+++def test_xpu_integrated_uses_native_budget(monkeypatch: pytest.MonkeyPatch) -> None:+ """Torch 集显的全局内存不能替代原生预算,型号用于唯一关联原生设备。"""+ props = SimpleNamespace(name="Intel GPU", device_id=1, is_integrated_gpu=True, total_memory=64 * 1024**3)+ monkeypatch.setitem(sys.modules, "torch", SimpleNamespace(xpu=SimpleNamespace(get_device_properties=lambda index: props)))+ query = Mock(return_value=gpu_memory.GpuMemory("xpu:1", GpuIdentity(0x8086, 1), 4 * 1024**3, "budget", "native"))+ monkeypatch.setattr(gpu_memory, "native_gpu_memory", query)+ result = gpu_memory.torch_gpu_memory("xpu:1")+ assert result.memory_bytes == 4 * 1024**3 and not result.sufficient+ query.assert_called_once_with(GpuIdentity(0x8086, 1, name="Intel GPU"), device="xpu:1")++[email protected]("native", [False, True])+def test_memory_probe_errors_are_reported(monkeypatch: pytest.MonkeyPatch, native: bool) -> None:+ """驱动异常输出未知容量和警告,不伪造零容量或吞掉原因。"""+ failure = Mock(side_effect=RuntimeError("driver unavailable"))+ monkeypatch.setattr(gpu_memory, "sys", SimpleNamespace(platform="linux"))+ monkeypatch.setattr(vulkan, "enumerate_vulkan_devices", failure)+ monkeypatch.setitem(sys.modules, "torch", SimpleNamespace(mps=SimpleNamespace(recommended_max_memory=failure)))+ result = gpu_memory.native_gpu_memory(GpuIdentity(1, 2), device="gpu") if native else gpu_memory.torch_gpu_memory("mps")+ assert result.memory_bytes is None and not result.sufficient and "driver unavailable" in result.warning++[email protected]("discrete", [False, True])[email protected]("extension", [False, True])+def test_vulkan_memory_abi_uses_local_heaps_once(discrete: bool, extension: bool) -> None:+ """模拟原生填充结构体,验证共享预算扩展、字节宽度及本地堆去重。"""++ def fill_memory(memory: Any) -> None:+ """两个类型指向同一个 GPU 堆,另一个大堆是主机内存。"""+ memory.type_count, memory.heap_count = 2, 2+ memory.types[0].heap_index = memory.types[1].heap_index = 0+ memory.heaps[0].flags, memory.heaps[0].size = 1, 8 * 1024**3+ memory.heaps[1].flags, memory.heaps[1].size = 0, 128 * 1024**3++ def properties(handle: Any, output: Any) -> None:+ """按 Vulkan 1.0 ABI 回填显存堆。"""+ fill_memory(output._obj)++ def extensions(handle: Any, layer: Any, count: Any, rows: Any) -> int:+ """分别模拟支持和不支持预算扩展的运行时。"""+ count._obj.value = int(extension)+ if rows is not None and extension:+ rows[0].name = b"VK_EXT_memory_budget"+ return 0++ def properties2(handle: Any, output: Any) -> None:+ """预算显著低于总容量且有用量,查询应保留预算上限。"""+ assert output._obj.sType == 1000059006+ fill_memory(output._obj.memory)+ budget = ct.cast(output._obj.pNext, ct.POINTER(vulkan._MemoryBudget)).contents+ assert budget.sType == 1000237000+ budget.budget[0], budget.usage[0] = 6 * 1024**3, 2 * 1024**3+ budget.budget[1] = 100 * 1024**3++ lib = SimpleNamespace(+ vkGetPhysicalDeviceMemoryProperties=Mock(side_effect=properties),+ vkEnumerateDeviceExtensionProperties=Mock(side_effect=extensions),+ vkGetPhysicalDeviceMemoryProperties2=Mock(side_effect=properties2),+ )+ assert vulkan._device_memory(lib, ct.c_void_p(1), discrete=discrete) == (+ (8 * 1024**3, None) if discrete else (None, 6 * 1024**3 if extension else None)+ )+ if discrete or not extension:+ lib.vkGetPhysicalDeviceMemoryProperties2.assert_not_called()+ assert ct.sizeof(vulkan._MemoryProperties) == 520+ assert vulkan._MemoryProperties.heaps.offset == 264++[email protected]("failed", [False, True])+def test_dxgi_budget_queries_same_adapter_and_releases(monkeypatch: pytest.MonkeyPatch, failed: bool) -> None:+ """模拟 COM 查询与释放,预算失败仍释放接口且不使用共享容量替代。"""++ def query(pointer: Any, iid: Any, output: Any) -> int:+ """返回同一适配器的 IDXGIAdapter3 接口。"""+ assert pointer.value == 123+ output._obj.value = 456+ return 0++ def read(pointer: Any, node: int, segment: int, output: Any) -> int:+ """查询本地段预算,不减去用量或加入非本地内存。"""+ assert (pointer.value, node, segment) == (456, 0, 0)+ output._obj.budget, output._obj.usage = 6 * 1024**3, 2 * 1024**3+ return -1 if failed else 0++ def method(pointer: Any, slot: int, *args: Any) -> Any:+ """只允许 QueryInterface 和 QueryVideoMemoryInfo 两个方法。"""+ return {0: query, 14: read}[slot]++ monkeypatch.setattr(windows_gpu, "_method", method)+ release = Mock()+ monkeypatch.setattr(windows_gpu, "_release", release)+ if failed:+ with pytest.raises(OSError, match="HRESULT"):+ windows_gpu._memory_budget(ct.c_void_p(123))+ else:+ assert windows_gpu._memory_budget(ct.c_void_p(123)) == 6 * 1024**3+ assert release.call_count == 1 and release.call_args.args[0].value == 456diff --git a/tests/unittest/test_gpu_policy.py b/tests/unittest/test_gpu_policy.pyindex 59e7191d..0abb123d 100644--- a/tests/unittest/test_gpu_policy.py+++ b/tests/unittest/test_gpu_policy.py@@ -13,6 +13,7 @@ from unittest.mock import Mockimport pytestfrom mineru.model.runtime import hardware, llama_device, llama_probe, tier_recommendation, vulkan, webgpu, windows_gpu+from mineru.model.runtime.gpu_memory import GpuMemoryfrom mineru.model.runtime.gpu import (GPU_KIND_ORDER,GpuClassification,@@ -50,6 +51,12 @@ def test_native_classification_agrees_across_runtime_and_report(monkeypatch.setattr(module, "sys", SimpleNamespace(platform=platform))monkeypatch.delenv("MINERU_LLAMA_CPP_BACKEND", raising=False)monkeypatch.setattr(tier_recommendation, "effective_cpu_count", lambda: 4)+ from mineru.config import get_config++ monkeypatch.setattr(get_config().model, "onnx_device", "auto")+ monkeypatch.setattr(+ tier_recommendation, "native_gpu_memory", lambda identity, *, device: GpuMemory(device, identity, 8 * 1024**3)+ )monkeypatch.setattr(onnx_calibration_cache, "calibrated_gpu_is_faster", lambda *args: False)native = vulkan.VulkanDevice(0x1002, 1, "GPU", 0)# Windows 故意提供相反的 Vulkan 类型,确认分类权威仍是 D3D12。diff --git a/tests/unittest/test_hardware_recommendation.py b/tests/unittest/test_hardware_recommendation.pyindex 7aa4ca70..10a17f60 100644--- a/tests/unittest/test_hardware_recommendation.py+++ b/tests/unittest/test_hardware_recommendation.py@@ -35,15 +35,21 @@ def torch_environment(monkeypatch: pytest.MonkeyPatch) -> Mock: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)+ monkeypatch.setattr(tier_recommendation, "_onnx_gpu_hardware", forbidden)return forbiddendef _fake_torch(monkeypatch: pytest.MonkeyPatch, kind: str, available: bool, count: int = 1) -> None:"""只提供可用性 API,调用模型、张量或设备分配接口都会因缺失而失败。"""- api = SimpleNamespace(is_available=lambda: available, device_count=lambda: count)+ api = SimpleNamespace(+ is_available=lambda: available,+ device_count=lambda: count,+ current_device=lambda: 0,+ get_device_properties=lambda index: SimpleNamespace(total_memory=8 * 1024**3, is_integrated_gpu=False),+ )unavailable = SimpleNamespace(is_available=lambda: False, device_count=lambda: 0)fake = SimpleNamespace(+ mps=SimpleNamespace(recommended_max_memory=lambda: 8 * 1024**3),cuda=api if kind == "cuda" else unavailable,xpu=api if kind == "xpu" else unavailable,backends=SimpleNamespace(mps=api if kind == "mps" else unavailable),@@ -91,7 +97,7 @@ def test_torch_cpu_and_invalid_explicit_device_are_conservative(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 report.device == "cpu" and report.ceiling == ("basic" if cores == 4 else "flash")assert bool(report.warnings) == expected_warningassert get_config().model.small_backend == "torch"assert os.environ["MINERU_DEVICE_MODE"] == requested@@ -102,11 +108,65 @@ def test_torch_probe_exception_keeps_warning(torch_environment: Mock, monkeypatc"""运行时探测异常形成有解释的 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 report.device == "cpu" and report.ceiling == "basic"assert "driver error" in report.warnings[0]torch_environment.assert_not_called()[email protected]("cores", [3, 4])[email protected]("accelerator", ["cuda", "mps", "xpu"])[email protected]("amount", [None, 5_905_580_032 - 1, 5_905_580_032, 6 * 1024**3 - 1])+def test_torch_memory_gate_preserves_onnx_isolation(+ torch_environment: Mock, monkeypatch: pytest.MonkeyPatch, cores: int, accelerator: str, amount: int | None+) -> None:+ """真实推荐链路检查精确容量边界,内存不足和未知均不触发 ONNX。"""+ monkeypatch.setattr(tier_recommendation, "effective_cpu_count", lambda: cores)+ monkeypatch.setenv("MINERU_DEVICE_MODE", accelerator)+ _fake_torch(monkeypatch, accelerator, True)+ fake = sys.modules["torch"]+ if accelerator == "mps":+ fake.mps.recommended_max_memory = lambda: amount+ else:+ getattr(fake, accelerator).get_device_properties = lambda index: SimpleNamespace(+ total_memory=amount, is_integrated_gpu=False+ )+ report = tier_recommendation.recommend_tiers()+ expected = TIERS if amount is not None and amount >= 5_905_580_032 else TIERS[:2] if cores >= 4 else ("flash",)+ assert report.pdf_image_tiers == expected+ assert report.gpu_memory.memory_bytes == amount and report.calibration.reason == "torch_backend"+ assert bool(report.warnings) is (amount is None)+ torch_environment.assert_not_called()+++def test_auto_basic_api_defaults_and_rejects_higher_tiers(+ torch_environment: Mock, monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ """经过真实推荐形成 Basic 服务,文本/JSON、能力列表和接单错误保持一致。"""+ monkeypatch.setenv("MINERU_DEVICE_MODE", "cuda")+ _fake_torch(monkeypatch, "cuda", True)+ sys.modules["torch"].cuda.get_device_properties = lambda index: SimpleNamespace(total_memory=5_905_580_032 - 1)+ monkeypatch.setattr(api_server, "ensure_tier_runtime_dependencies", Mock())+ report = tier_recommendation.recommend_tiers()+ monkeypatch.setattr(hardware_cmd, "_detect_data", lambda: asdict(report))+ output = CliRunner().invoke(kit_app, ["hardware", "detect", "--json"])+ data = json.loads(output.stdout)+ assert data["schema_version"] == 1 and data["gpu_memory"]["memory_bytes"] == 5_905_580_032 - 1+ rendered = hardware_cmd.render_detection(data)+ assert "gpu_memory_insufficient" in rendered and "5905580031 bytes" in rendered and "torch.cuda.total_memory" in rendered+ app = api_server.create_app(upload_dir=str(tmp_path))+ with TestClient(app) as client:+ assert tuple(row["id"] for row in client.get("/v1/tiers").json()["data"]) == ("flash", "basic")+ for options in ({}, {"tier": None}):+ response = client.post("/v1/tasks", json={"files": [{"file_name": "test.pdf", "bytes": 1}], **options})+ assert response.status_code == 202+ assert app.state.task_store._records[response.json()["task_id"]].options.tier == "basic"+ for tier in ("standard", "advanced"):+ response = client.post("/v1/tasks", json={"files": [{"file_name": "test.pdf", "bytes": 1}], "tier": tier})+ assert response.status_code == 400 and response.json()["error"]["code"] == "invalid_request"+ assert response.json()["error"]["param"] == "tier"+ torch_environment.assert_not_called()++def test_remote_vlm_and_api_override_match_detect(torch_environment: Mock, monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:diff --git a/tests/unittest/test_tier_recommendation.py b/tests/unittest/test_tier_recommendation.pyindex 7a86c74d..822c0243 100644--- a/tests/unittest/test_tier_recommendation.py+++ b/tests/unittest/test_tier_recommendation.py@@ -15,6 +15,8 @@ import yamlfrom mineru.model.runtime.gpu import classify_d3d12_gpu, classify_vulkan_gpu, with_gpu_classificationfrom mineru.model.runtime import onnx_calibration_cache as cachefrom mineru.model.runtime import tier_recommendation as recommendation+from mineru.model.runtime.gpu import GpuIdentity+from mineru.model.runtime.gpu_memory import GpuMemoryfrom mineru.model.runtime.llama_probe import LlamaDevicefrom mineru.model.runtime.webgpu import WebGPUDevicefrom mineru.model.runtime.windows_gpu import GpuAdapter@@ -25,6 +27,14 @@ from mineru.types import TIERSdef onnx_recommendation_backend(monkeypatch: pytest.MonkeyPatch) -> None:"""本文件验证 ONNX 既有推荐规则,隔离宿主可能自动选择的 Torch 后端。"""monkeypatch.setattr(recommendation, "resolve_small_model_backend", lambda: "onnx")+ from mineru.config import get_config++ monkeypatch.setattr(get_config().model, "onnx_device", "auto")+ monkeypatch.setattr(+ recommendation,+ "native_gpu_memory",+ lambda identity, *, device: GpuMemory(device, identity, 8 * 1024**3, "budget", "test"),+ )@pytest.mark.parametrize(@@ -32,15 +42,20 @@ def onnx_recommendation_backend(monkeypatch: pytest.MonkeyPatch) -> None:[(1, False, {"flash"}),(3, False, {"flash"}),- (4, False, set(TIERS[:-1])),- (32, False, set(TIERS[:-1])),+ (4, False, set(TIERS[:2])),+ (32, False, set(TIERS[:2])),(1, True, set(TIERS)),(4, True, set(TIERS)),],)def test_recommendation_matrix(cores: int, gpu: bool, expected: set[str]) -> None:"""验证 CPU 边界及 GPU 对全部档位的开放规则。"""- assert recommendation.tiers_for_hardware(recommendation.TierHardware(cores, gpu)) == expected+ assert (+ recommendation.tiers_for_hardware(+ recommendation.TierHardware(cores, gpu, gpu_memory=GpuMemory("gpu", GpuIdentity(), 8 * 1024**3))+ )+ == expected+ )@pytest.mark.parametrize(@@ -55,10 +70,10 @@ def test_recommendation_respects_affinity_and_quota(monkeypatch.setattr(cpu_threads.os, "cpu_count", lambda: 16)monkeypatch.setattr(cpu_threads.os, "sched_getaffinity", lambda pid: set(range(affinity)), raising=False)monkeypatch.setattr(cpu_threads.Path, "read_text", lambda path: quota if path.name == "cpu.max" else "-1")- monkeypatch.setattr(recommendation, "_advanced_gpu_reason", lambda: None)+ monkeypatch.setattr(recommendation, "_onnx_gpu_hardware", lambda count: recommendation.TierHardware(count))hardware = recommendation.detect_tier_hardware()assert hardware.cpu_count == expected- assert recommendation.tiers_for_hardware(hardware) == frozenset(TIERS[:-1] if expected >= 4 else ("flash",))+ assert recommendation.tiers_for_hardware(hardware) == frozenset(TIERS[:2] if expected >= 4 else ("flash",))@pytest.fixture@@ -156,10 +171,13 @@ def test_apple_metal_recommendation(monkeypatch: pytest.MonkeyPatch, platform: smonkeypatch.setattr(recommendation, "sys", SimpleNamespace(platform=platform))monkeypatch.setattr(recommendation, "effective_cpu_count", lambda: 4)monkeypatch.setattr(recommendation, "_apple_metal_available", lambda: metal)+ monkeypatch.setattr(+ recommendation, "torch_gpu_memory", lambda device: GpuMemory(device, GpuIdentity(), 8 * 1024**3, "budget", "test")+ )monkeypatch.setattr(llama_device, "discover_llama_devices", lambda: ())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])+ assert frozenset(recommendation.recommend_tiers().pdf_image_tiers) == frozenset(TIERS if metal else TIERS[:2])selection.assert_not_called()@@ -195,7 +213,7 @@ def test_gpu_discovery_uses_only_existing_evidence(side_effect=RuntimeError("driver") if kind == "failure" else None,),)- adapter = _adapter() if platform == "win32" else WebGPUDevice(0x8086, 0x7D51)+ adapter = _adapter() if platform == "win32" else WebGPUDevice(0x8086, 0x7D51, vulkan_device=(0x8086, 0x7D51))monkeypatch.setattr(windows_gpu, "discover_gpus", lambda: (adapter,))monkeypatch.setattr(webgpu, "discover_webgpu_devices", lambda: (adapter,))monkeypatch.setattr(webgpu, "select_webgpu_device", lambda devices: devices[0])@@ -203,7 +221,7 @@ def test_gpu_discovery_uses_only_existing_evidence(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 Nonehardware = recommendation.detect_tier_hardware()- assert recommendation.tiers_for_hardware(hardware) == frozenset(TIERS if kind in {"discrete", "calibrated"} else TIERS[:-1])+ assert recommendation.tiers_for_hardware(hardware) == frozenset(TIERS if kind in {"discrete", "calibrated"} else TIERS[:2])assert (evidence_path.read_bytes() if evidence_path.exists() else None) == beforeonnx_device.resolve_onnx_device.assert_not_called()@@ -277,7 +295,7 @@ def startup_calibration(def test_auto_startup_calibrates_before_publishing(startup_calibration: tuple[Path, Mock], monkeypatch: pytest.MonkeyPatch, outcome: str) -> None:- """真实服务工厂在发布能力前读取本次校准,失败保持标准上限且不伪造 CPU 胜出。"""+ """真实服务工厂在发布能力前读取本次校准,失败保持 Basic 上限且不伪造 CPU 胜出。"""from fastapi.testclient import TestClientfrom mineru.model.runtime import onnx_device@@ -295,10 +313,10 @@ def test_auto_startup_calibrates_before_publishing(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]+ expected = TIERS if outcome == "fast" else TIERS[:2]measurement.assert_called_once()assert app.state.server_tiers == expected- assert app.state.default_tier == "standard"+ assert app.state.default_tier == ("standard" if outcome == "fast" else "basic")with TestClient(app) as client:assert tuple(row["id"] for row in client.get("/v1/tiers").json()["data"]) == expectedpreload.assert_not_called()@@ -313,13 +331,14 @@ def test_auto_startup_calibrates_before_publishing(}-def test_flash_initial_recommendation_skips_calibration(+def test_flash_without_sufficient_gpu_skips_calibration(startup_calibration: tuple[Path, Mock], monkeypatch: pytest.MonkeyPatch) -> None:"""可用 CPU 不足四且无已有 GPU 证据时,只开放 Flash 并跳过启动选型。"""from mineru.model.runtime import onnx_devicemonkeypatch.setattr(recommendation, "effective_cpu_count", lambda: 3)+ monkeypatch.setattr(recommendation, "native_gpu_memory", lambda identity, *, device: GpuMemory(device, identity))assert recommendation.recommend_tiers().pdf_image_tiers == ("flash",)startup_calibration[1].assert_not_called()assert not onnx_device._selections@@ -377,7 +396,7 @@ def test_startup_preserves_explicit_device_without_performance_evidence(config_file, measurement = startup_calibrationsettings.get_config().model.onnx_device = requestedconfig_file.write_text(f"model:\n onnx_device: {requested}\n", encoding="utf-8")- assert frozenset(recommendation.recommend_tiers().pdf_image_tiers) == frozenset(TIERS[:-1])+ assert frozenset(recommendation.recommend_tiers().pdf_image_tiers) == frozenset(TIERS[:2])measurement.assert_not_called()assert yaml.safe_load(config_file.read_text(encoding="utf-8"))["model"]["onnx_device"] == requested@@ -400,11 +419,67 @@ def test_failed_recalibration_revokes_previous_fast_evidence(startup_calibrationadapter = _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])+ assert frozenset(recommendation.recommend_tiers().pdf_image_tiers) == frozenset(TIERS[:2])startup_calibration[1].assert_called_once()assert not cache.calibration_record_path().exists()[email protected]("cores", [3, 4])[email protected]("amount", [None, 5_905_580_032 - 1, 5_905_580_032, 6 * 1024**3 - 1, 8 * 1024**3])+def test_startup_gpu_memory_threshold_and_low_cpu_calibration(+ startup_calibration: tuple[Path, Mock], monkeypatch: pytest.MonkeyPatch, cores: int, amount: int | None+) -> None:+ """低核数的达标 GPU 仍能完成首次校准;四核小显存 GPU 只加速 Basic。"""+ monkeypatch.setattr(recommendation, "effective_cpu_count", lambda: cores)+ monkeypatch.setattr(+ recommendation, "native_gpu_memory", lambda identity, *, device: GpuMemory(device, identity, amount, "budget", "test")+ )+ enough = amount is not None and amount >= 5_905_580_032+ expected = TIERS if enough else ("flash", "basic") if cores >= 4 else ("flash",)+ report = recommendation.recommend_tiers()+ assert report.pdf_image_tiers == expected+ assert report.default_request_tier == ("standard" if enough else expected[-1])+ assert startup_calibration[1].call_count == int(cores >= 4 or enough)+ assert report.gpu_memory.memory_bytes == amount+ if cores >= 4 and not enough:+ assert report.device.endswith(":gpu") and report.calibration.status == "completed"+ assert report.reason == ("gpu_memory_unknown" if amount is None else "gpu_memory_insufficient")++[email protected]("failure", ["configured_cpu", "selection_failed", "raise"])+def test_final_cpu_result_cannot_be_upgraded_by_discrete_inventory(+ startup_calibration: tuple[Path, Mock], monkeypatch: pytest.MonkeyPatch, failure: str+) -> None:+ """即使初选发现达标独显,最终 CPU 或选型异常也必须撤销高级能力。"""+ from mineru.model.runtime import onnx_device++ candidate = recommendation.TierHardware(4, True, "discrete_gpu", GpuMemory("gpu", GpuIdentity(), 24 * 1024**3))+ monkeypatch.setattr(recommendation, "detect_tier_hardware", lambda: candidate)+ selection = Mock(+ return_value=onnx_device.OnnxSelection(reason=failure),+ side_effect=RuntimeError("driver") if failure == "raise" else None,+ )+ monkeypatch.setattr(onnx_device, "resolve_onnx_device", selection)+ report = recommendation.recommend_tiers()+ assert report.pdf_image_tiers == ("flash", "basic") and report.default_request_tier == "basic"+ selection.assert_called_once()++[email protected]("amount", [None, 5_905_580_032 - 1, 5_905_580_032, 6 * 1024**3 - 1])+def test_apple_onnx_path_also_requires_budget(monkeypatch: pytest.MonkeyPatch, amount: int | None) -> None:+ """ONNX 小模型配合 Apple Metal 的旧免测速路径同样受预算门槛约束。"""+ monkeypatch.delenv("MINERU_LLAMA_CPP_BACKEND", raising=False)+ monkeypatch.setattr(recommendation, "sys", SimpleNamespace(platform="darwin"))+ monkeypatch.setattr(recommendation, "effective_cpu_count", lambda: 4)+ monkeypatch.setattr(recommendation, "_apple_metal_available", lambda: True)+ monkeypatch.setattr(+ recommendation, "torch_gpu_memory", lambda device: GpuMemory(device, GpuIdentity(), amount, "budget", "metal")+ )+ report = recommendation.recommend_tiers()+ assert report.pdf_image_tiers == (TIERS if amount is not None and amount >= 5_905_580_032 else TIERS[:2])+ assert report.device == "mps" and report.calibration.reason == "apple_silicon_metal"++@pytest.mark.parametrize("backend", ["dml", "webgpu"])def test_shared_classification_preserves_existing_calibration_fingerprint(evidence_path: Path, backend: str) -> None:"""分类和诊断字段变化不废弃旧校准格式,真实设备或绑定变化仍使证据失效。"""