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
fix(runtime): use selected GPU memory for automatic tiers
Xiaomeng Zhao57c8e4d88278
diff --git a/docs/next/cli/mineru-kit-hardware.md b/docs/next/cli/mineru-kit-hardware.mdindex 486f4f3f..4b50b723 100644--- a/docs/next/cli/mineru-kit-hardware.md+++ b/docs/next/cli/mineru-kit-hardware.md@@ -21,7 +21,7 @@ mineru-kit hardware info --json > hardware-info.json|----------|------|| Torch + 可用 CUDA/MPS/XPU 等加速设备 | 跳过 OCR 测速;选定设备的显存/预算至少 5.5 GiB 时推荐 advanced,否则按 CPU 条件推荐 || Torch + 显式 CPU 或加速设备不可用 | 跳过测速,进程可用逻辑 CPU 至少 4 时推荐 basic,否则 flash |-| ONNX | CPU 至少 4 核或存在内存达标的兼容 GPU 候选时,在 Windows/Linux 同步完成适用的 OCR 选型,再确定最终上限 |+| ONNX | CPU 至少 4 核或存在内存达标的兼容 GPU 候选时,在 Windows/Linux 同步完成现有设备选型;实际选中 GPU 且内存达标时开放全部四档,不再额外检查性能证据 |自动推荐的 CPU 条件只开放 Basic:进程可用逻辑核数至少 4 时开放 `flash,basic`,默认请求 Basic,否则只开放 Flash。计数遵守进程亲和性和容器 CPU 配额。GPU 经现有选型确认可用且显存/预算至少 `5_905_580_032` 字节时,独立于 CPU 核数开放全部四档;默认请求仍为 Standard,Advanced 必须显式请求。@@ -29,7 +29,9 @@ mineru-kit hardware info --json > hardware-info.json`small_backend=auto` 最终选择 Torch 时同样免校准。显式设备字符串必须经过实际可用性检查;检查失败会给出保守结果及原因,不修改设备配置。Torch 推荐不依赖 llama.cpp 库存,不下载 ONNX 校准权重,也不写入 `model.onnx_device` 或 OCR 校准记录。-ONNX 分支保留既有兼容策略、0.8 阈值和进程缓存。Windows 确认的独显,以及 Linux 通过兼容检查、由 Vulkan 唯一识别并配置物理绑定的独显,均免 OCR 校准,报告 `status=skipped, reason=discrete_gpu`;首次真实 GPU 会话成功后才保存 `gpu`,硬件推荐本身不生成校准记录。集显或类型无法确认的候选继续测速,首次可能下载 OCR rec 模型;下载和派生图准备不计入 15 秒校准 worker 超时。显式或已保存的 CPU/GPU 选择不强制重测。校准失败、超时或不稳定时保守推荐,并携带警告。+ONNX 分支保留既有兼容策略、0.8 阈值和进程缓存。Windows 确认的独显,以及 Linux 通过兼容检查、由 Vulkan 唯一识别并配置物理绑定的独显,均免 OCR 校准,报告 `status=skipped, reason=discrete_gpu`;首次真实 GPU 会话成功后才保存 `gpu`,硬件推荐本身不生成校准记录。`onnx_device=auto` 时,集显或类型无法确认的候选继续沿用现有设备选型测速,首次可能下载 OCR rec 模型;下载和派生图准备不计入 15 秒校准 worker 超时。校准失败、超时或不稳定导致本次设备选型回退 CPU 时,按 CPU 条件推荐,并携带警告。++`onnx_device=gpu` 无论来自用户配置还是之前的自动选型,都不触发测速;实际选中兼容 GPU 后,仅检查该设备的显存/预算是否达到 5.5 GiB。校准记录缺失、损坏、过期或记录 GPU 较慢,均不阻止内存达标的 GPU 开放 Standard/Advanced。此时推荐原因是 `configured_gpu`,校准状态为 `status=skipped, reason=configured_gpu`。内存不足或未知时报告相应内存原因。记录摘要只供诊断,读取失败会附带警告,不改变设备和档位结论。`onnx_device=cpu` 仍遵循 CPU 规则。llama.cpp 自动集显路径同样按有效小模型后端分流:Torch 使用加速可用性结果,不再绕回 OCR 校准;ONNX 保留原有性能结果和设备身份匹配。原生独显优先、显式 CPU/GPU 参数、物理绑定和兼容处理保持不变。@@ -37,7 +39,7 @@ OCR、llama.cpp、档位推荐与诊断共用 GPU 分类和双向唯一身份匹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 校准指纹,既有有效测速记录可以继续复用。每个服务在启动阶段形成一次最终开放集合,运行过程中不动态升降档位。+本次实际选型落在 CPU 或选型失败时,不会凭静态显卡库存重新开放高档位。性能判断归属 ONNX 自动设备选型,auto tier 不增加独立测速或历史性能证据门槛。设备容量信息不进入 OCR 校准指纹,每次启动读取当前选定设备的内存容量。每个服务在启动阶段形成一次最终开放集合,运行过程中不动态升降档位。开放 Advanced 后,请求省略 tier 仍默认 Standard。推荐不代表模型已准备好,API 服务继续执行依赖预检;显式启动上限和 Python 精确集合不进入自动推荐。API 工厂的 VLM 配置覆盖参与共享推荐,远程 VLM 显示为 `http-client`,不自动扩大本机上限。diff --git a/docs/next/onnx-device.md b/docs/next/onnx-device.mdindex 894f68ae..50847621 100644--- a/docs/next/onnx-device.md+++ b/docs/next/onnx-device.md@@ -97,15 +97,15 @@ MinerU 的 WebGPU 运行时锁覆盖过滤与会话初始化,后续每次会本机双卡及仅 Intel ICD 的验证见 [Intel 架构过滤报告](onnx-intel-architecture-policy-validation.md)。-通常在首次实际使用 ONNX 模型时选型。API 使用 `--tier auto`(或省略),有效小模型后端为 ONNX,且可用逻辑 CPU 至少 4 核或存在显存/预算达到 5.5 GiB 的兼容 GPU 候选时,Windows/Linux 会提前同步调用相同的设备选择流程,校准证据在本次最终档位推荐中生效,不依赖 `--preload-models`。CPU 不足 4 核且无内存达标 GPU 候选、显式启动档位或 macOS 不增加这项启动选型。有效小模型后端为 Torch 时采用实际设备可用性和内存证据并跳过 OCR 校准,不修改 ONNX 设备偏好或证据;llama.cpp 自动集显路径也遵循这处分流。+通常在首次实际使用 ONNX 模型时选型。API 使用 `--tier auto`(或省略),有效小模型后端为 ONNX,且可用逻辑 CPU 至少 4 核或存在显存/预算达到 5.5 GiB 的兼容 GPU 候选时,Windows/Linux 会提前同步调用相同的设备选择流程,并直接采用本次设备选型结果,不依赖 `--preload-models`。实际选中 GPU 且内存达标时开放 Standard/Advanced;auto tier 不增加独立测速,也不额外检查历史校准是否胜出。`onnx_device=gpu` 无论来自用户偏好还是自动选型写入,均免测速,校准记录缺失、损坏、过期或 GPU 较慢不阻止内存达标的已选 GPU 开放高级档位。CPU 不足 4 核且无内存达标 GPU 候选、显式启动档位或 macOS 不增加这项启动选型。有效小模型后端为 Torch 时采用实际设备可用性和内存证据并跳过 OCR 校准,不修改 ONNX 设备偏好或证据;llama.cpp 自动集显路径也遵循这处分流。`mineru-kit hardware detect` 与 API 自动启动共享推荐逻辑;`hardware info` 只读报告环境与校准记录,不测速。界面启动本身、导入 SDK、查询配置和模型列表不会运行测速;界面托管的 API 服务仍遵循其启动参数。自动决策成功后原子更新有效配置文件中的 `model.onnx_device`,保留其余键;进程间通过文件锁协调。校准证据显式保存设备、运行时与线程指纹;分类来源等诊断字段不进入指纹,原有有效记录可继续复用。-实际设备或物理绑定改变后,旧记录不再作为当前设备的性能证据。+实际设备或物理绑定改变后,诊断报告会显示旧记录不再匹配;这不会覆盖配置中的设备偏好,也不会单独限制已选 GPU 的档位。Windows/Linux 免校准独显都只在首次真实 GPU 会话成功后保存 `gpu`;仅运行硬件推荐时仍保留 `auto`,不下载校准权重、不生成性能校准记录。初始化错误或静默回退 CPU 不保存 GPU 偏好。-环境变量覆盖不写入文件;只读配置保留本进程选择。测速失败不保存为 CPU 性能优胜,同进程不重复尝试。+环境变量覆盖不写入文件;只读配置保留本进程选择。测速失败不保存为 CPU 性能优胜,同进程不重复尝试。写入 `onnx_device=gpu` 不要求达到 5.5 GiB,该内存门槛只用于 auto tier 开放 Standard/Advanced;较小的 GPU 仍可用于 ONNX 加速。Linux 插件缺失、没有可用设备、物理绑定失败、校准超时或输出不一致时保留 `auto`。通过环境变量强制 `auto` 时,每个新进程重新选择,并使用选择锁避免同时测速。显式或已保存的 `cpu` 不会因后来接入独显而改变。diff --git a/docs/next/tiers.md b/docs/next/tiers.mdindex 89319867..047a2d04 100644--- a/docs/next/tiers.md+++ b/docs/next/tiers.md@@ -102,7 +102,7 @@ advanced 只接受显式选择:只有 advanced 时没有默认档位,返回`--tier auto` 或省略启动参数时,进程可用逻辑 CPU 至少 4 核默认开放 flash、basic,否则只开放 flash;计数遵守亲和性和容器配额。只有实际 GPU 已经确认可用,并且选中设备的专用显存总量或 GPU 内存预算至少 5.5 GiB,才开放 standard、advanced。GPU 达标不要求 CPU 同时达到 4 核;开放全部四档时请求默认仍为 standard。-自动推荐先解析有效小模型后端。Torch(包括 auto 最终选择 Torch)、Apple Metal 和符合既有确认与绑定规则的独显保留免 OCR 测速路径;其他 ONNX GPU 继续要求有效校准胜出。CPU 至少 4 核或存在内存达标的兼容 GPU 候选时,Windows/Linux 在本次启动内完成适用的 ONNX 选型。最终选中 CPU、校准失败、设备身份不明确或内存未知时按 CPU 条件推荐,静态 GPU 库存不能覆盖最终结果。+自动推荐先解析有效小模型后端。Torch(包括 auto 最终选择 Torch)、Apple Metal 和符合既有确认与绑定规则的独显保留免 OCR 测速路径。CPU 至少 4 核或存在内存达标的兼容 GPU 候选时,Windows/Linux 在本次启动内完成现有 ONNX 设备选型:`onnx_device=auto` 保留适用的性能校准,`onnx_device=gpu` 无论来自手动配置还是先前自动选型都不测速。auto tier 直接采用实际选型结果,GPU 内存达标即开放全部四档,不再额外要求独显类型或校准胜出记录;历史记录缺失、损坏、过期或 GPU 较慢均不影响已选 GPU 的档位判断。最终选中 CPU、选型失败、设备身份不明确或内存未知时按 CPU 条件推荐,静态 GPU 库存不能覆盖最终结果。显存按原始字节比较,不取整、不累加多卡,不使用虚拟显存覆盖。统一/共享内存使用 Metal 推荐工作集、DXGI 本地预算或 Vulkan `heapBudget`,不以系统总内存替代。最终集合在启动时固定;`mineru-kit hardware detect` 共享推荐与内存证据,`hardware info` 只读收集环境信息。diff --git a/mineru/model/runtime/tier_recommendation.py b/mineru/model/runtime/tier_recommendation.pyindex 3246e605..cef6dc49 100644--- a/mineru/model/runtime/tier_recommendation.py+++ b/mineru/model/runtime/tier_recommendation.py@@ -1,11 +1,11 @@# Copyright (c) Opendatalab. All rights reserved.-"""通过硬件初选与启动阶段的 OCR 设备校准,确定 API 服务开放档位。"""+"""通过现有设备选型与选定 GPU 的内存预算,确定 API 服务开放档位。"""from __future__ import annotations-from dataclasses import dataclass, replaceimport osimport sys+from dataclasses import dataclass, replacefrom typing import TYPE_CHECKINGfrom loguru import logger@@ -80,7 +80,7 @@ def _apple_metal_available() -> bool: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)@@ -110,34 +110,41 @@ def _onnx_gpu_hardware(count: int, choice: OnnxSelection | None = None) -> TierHif not devices:return TierHardware(count, reason="no_visible_gpu")- from .onnx_calibration_cache import calibrated_gpu_is_faster- from .onnx_device import ONNX_GPU_TIME_RATIO_THRESHOLDS-- 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())- threshold = ONNX_GPU_TIME_RATIO_THRESHOLDS["dml"]else:from .webgpu import discover_webgpu_devices, select_webgpu_deviceadapter = select_webgpu_device(discover_webgpu_devices())- threshold = ONNX_GPU_TIME_RATIO_THRESHOLDS["webgpu"]- if adapter is None or threshold is None:+ if adapter is 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:return TierHardware(count, reason="gpu_identity_unconfirmed")memory = native_gpu_memory(adapter.identity, device=f"{choice.backend if choice else 'onnx'}:gpu")+ if choice is not None:+ # 性能判断属于 ONNX 自动选型;已选 GPU 仅需满足内存门槛,不再要求历史校准证据。+ reason = "ocr_calibrated_gpu" if choice.reason == "rec_calibration" else choice.reason+ return _gpu_hardware(count, True, reason, memory)+ if get_config().model.onnx_device == "gpu":+ # 初选保留内存候选,让低 CPU 配额也能进入实际设备选型,配置本身不确认设备可用。+ return TierHardware(count, reason="configured_gpu", gpu_memory=memory)++ from .onnx_calibration_cache import calibrated_gpu_is_faster+ from .onnx_device import ONNX_GPU_TIME_RATIO_THRESHOLDS+ from .webgpu import WebGPUDevice++ threshold = ONNX_GPU_TIME_RATIO_THRESHOLDS["webgpu" if sys.platform == "linux" else "dml"]+ if threshold is None:+ return TierHardware(count, reason="no_eligible_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)+ calibrated = 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)@@ -200,7 +207,12 @@ def recommend_tiers(*, vlm_config: VlmConfig | None = None) -> TierRecommendatiocached = 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)+ hardware = _onnx_gpu_hardware(hardware.cpu_count, onnx_choice)+ try:+ evidence = inspect_calibration_record((onnx_choice.adapter,) if onnx_choice.adapter is not None else None)+ except Exception as error:+ evidence = None+ warnings.append(f"ONNX calibration diagnostics unavailable: {error}")status = "skipped"if onnx_choice.reason == "rec_calibration":status = "reused" if cached is not None else "completed"@@ -212,10 +224,9 @@ def recommend_tiers(*, vlm_config: VlmConfig | None = None) -> TierRecommendatio}:status = "failed"warnings.append(f"ONNX selection used CPU: {onnx_choice.reason}")- elif onnx_choice.reason in {"configured_cpu", "configured_gpu"}:+ elif onnx_choice.reason == "configured_cpu" and evidence is not None:status = "reused" if evidence.matches_environment and evidence.decision_valid else "skipped"calibration = CalibrationDecision(status, onnx_choice.reason, evidence)- hardware = _onnx_gpu_hardware(hardware.cpu_count, onnx_choice)except Exception as error:logger.warning("Startup ONNX selection unavailable; using CPU recommendation rules: {}", error)warnings.append(f"ONNX selection unavailable: {error}")diff --git a/tests/unittest/test_tier_recommendation.py b/tests/unittest/test_tier_recommendation.pyindex 822c0243..68a66cbd 100644--- a/tests/unittest/test_tier_recommendation.py+++ b/tests/unittest/test_tier_recommendation.py@@ -2,8 +2,9 @@from __future__ import annotations-from dataclasses import replaceimport importlib+import json+from dataclasses import asdict, replacefrom pathlib import Pathfrom types import SimpleNamespacefrom typing import Any@@ -12,10 +13,9 @@ from unittest.mock import Mockimport pytestimport yaml-from 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 import GpuIdentity, classify_d3d12_gpu, classify_vulkan_gpu, with_gpu_classificationfrom mineru.model.runtime.gpu_memory import GpuMemoryfrom mineru.model.runtime.llama_probe import LlamaDevicefrom mineru.model.runtime.webgpu import WebGPUDevice@@ -291,6 +291,17 @@ def startup_calibration(return config_file, measurement+def configured_gpu(startup_calibration: tuple[Path, Mock]) -> tuple[Path, Mock]:+ """复用双平台选型环境,仅将用户设备偏好设置为 GPU。"""+ from mineru.config import get_config++ config_file, measurement = startup_calibration+ get_config().model.onnx_device = "gpu"+ config_file.write_text("model:\n onnx_device: gpu\n source: local\n", encoding="utf-8")+ return config_file, measurement++@pytest.mark.parametrize("outcome", ["fast", "slow", "unstable", "timeout", "output_error"])def test_auto_startup_calibrates_before_publishing(startup_calibration: tuple[Path, Mock], monkeypatch: pytest.MonkeyPatch, outcome: str@@ -391,27 +402,173 @@ def test_explicit_ceiling_skips_startup_selection(startup_calibration: tuple[Patdef test_startup_preserves_explicit_device_without_performance_evidence(startup_calibration: tuple[Path, Mock], requested: str) -> None:- """已保存或手动的设备偏好不触发测速,也不代替集显的有效性能证据。"""+ """显式设备不触发测速,实际选中的达标 GPU 无需校准证据即可开放四档。"""settings = importlib.import_module("mineru.config")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[:2])+ report = recommendation.recommend_tiers()+ assert report.pdf_image_tiers == (TIERS if requested == "gpu" else TIERS[:2])+ assert report.reason == f"configured_{requested}"+ assert report.calibration.status == "skipped"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:- """同次启动采用新证据,后续进程复用保存结果,不再次测速。"""[email protected]("remove_evidence", [False, True])+def test_next_startup_reuses_saved_device(startup_calibration: tuple[Path, Mock], remove_evidence: bool) -> None:+ """自动校准保存 GPU 后,即使记录丢失也直接采用 GPU 与当前内存预算。"""from mineru.model.runtime import onnx_deviceassert frozenset(recommendation.recommend_tiers().pdf_image_tiers) == frozenset(TIERS)onnx_device._selections.clear()- assert frozenset(recommendation.recommend_tiers().pdf_image_tiers) == frozenset(TIERS)+ if remove_evidence:+ cache.calibration_record_path().unlink()+ report = recommendation.recommend_tiers()+ assert report.pdf_image_tiers == TIERS+ assert report.reason == "configured_gpu"+ assert report.calibration.status == "skipped" and report.calibration.reason == "configured_gpu"startup_calibration[1].assert_called_once()assert onnx_device.resolve_onnx_device().reason == "configured_gpu"[email protected]("record", ["missing", "invalid", "stale", "slow", "unstable", "valid", "read_error"])+def test_configured_gpu_does_not_require_performance_evidence(+ configured_gpu: tuple[Path, Mock], monkeypatch: pytest.MonkeyPatch, record: str+) -> None:+ """历史测速只供诊断,不能限制已选 GPU、触发补测或改写配置。"""+ from mineru.model.runtime import onnx_device++ settings = importlib.import_module("mineru.config")+ config_file, measurement = configured_gpu+ path = cache.calibration_record_path()+ if record == "invalid":+ path.write_text("broken", encoding="utf-8")+ elif record not in {"missing", "read_error"}:+ adapter = _adapter() if onnx_device.sys.platform == "win32" else WebGPUDevice(0x8086, 0x7D51)+ if record == "stale":+ adapter = replace(adapter, device_id=1)+ cache.save_calibration_record(+ adapter, _measurement(gpu_elapsed=3.0 if record == "slow" else 1.0, decision_valid=record != "unstable")+ )+ if record == "read_error":+ monkeypatch.setattr(recommendation, "inspect_calibration_record", Mock(side_effect=OSError("record unavailable")))+ evidence_before = path.read_bytes() if path.exists() else None+ config_before = config_file.read_bytes()+ writes = Mock(side_effect=AssertionError("configured GPU must not write configuration"))+ performance = Mock(side_effect=AssertionError("configured GPU must not require performance evidence"))+ monkeypatch.setattr(settings, "update_config_file", writes)+ monkeypatch.setattr(cache, "calibrated_gpu_is_faster", performance)+ monkeypatch.setattr(recommendation, "effective_cpu_count", lambda: 3)++ report = recommendation.recommend_tiers()++ assert report.pdf_image_tiers == TIERS and report.default_request_tier == "standard"+ assert report.reason == "configured_gpu" and report.device.endswith(":gpu")+ assert report.calibration.status == "skipped" and report.calibration.reason == "configured_gpu"+ if record == "read_error":+ assert report.calibration.evidence is None+ assert any("record unavailable" in warning for warning in report.warnings)+ else:+ assert report.calibration.evidence is not None+ assert config_file.read_bytes() == config_before+ assert (path.read_bytes() if path.exists() else None) == evidence_before+ measurement.assert_not_called()+ performance.assert_not_called()+ writes.assert_not_called()++[email protected]("cores", [3, 4])[email protected]("amount", [None, 5_905_580_032 - 1, 5_905_580_032, 6 * 1024**3 - 1])+def test_configured_gpu_memory_threshold(+ configured_gpu: tuple[Path, Mock], monkeypatch: pytest.MonkeyPatch, cores: int, amount: int | None+) -> None:+ """配置 GPU 仍遵守精确内存门槛,内存不足时按 CPU 核数降级且不测速。"""+ config_file, measurement = configured_gpu+ before = config_file.read_bytes()+ monkeypatch.setattr(recommendation, "effective_cpu_count", lambda: cores)+ monkeypatch.setattr(+ recommendation, "native_gpu_memory", lambda identity, *, device: GpuMemory(device, identity, amount, "budget", "test")+ )++ report = recommendation.recommend_tiers()++ enough = amount is not None and amount >= 5_905_580_032+ expected = TIERS if enough else TIERS[:2] if cores >= 4 else ("flash",)+ assert report.pdf_image_tiers == expected+ assert report.default_request_tier == ("standard" if enough else expected[-1])+ assert report.gpu_memory.memory_bytes == amount+ if cores >= 4 or enough:+ assert report.device.endswith(":gpu")+ assert report.calibration.status == "skipped" and report.calibration.reason == "configured_gpu"+ assert report.reason == (+ "configured_gpu" if enough else "gpu_memory_unknown" if amount is None else "gpu_memory_insufficient"+ )+ measurement.assert_not_called()+ assert config_file.read_bytes() == before+ assert not cache.calibration_record_path().exists()+++def test_configured_gpu_does_not_require_calibration_threshold(+ configured_gpu: tuple[Path, Mock], monkeypatch: pytest.MonkeyPatch+) -> None:+ """性能阈值仅约束自动测速,不能阻断已选 GPU 的内存判定。"""+ from mineru.model.runtime import onnx_device++ monkeypatch.setitem(onnx_device.ONNX_GPU_TIME_RATIO_THRESHOLDS, "dml", None)+ monkeypatch.setitem(onnx_device.ONNX_GPU_TIME_RATIO_THRESHOLDS, "webgpu", None)+ monkeypatch.setattr(recommendation, "effective_cpu_count", lambda: 3)+ assert recommendation.recommend_tiers().pdf_image_tiers == TIERS+ configured_gpu[1].assert_not_called()++[email protected]("inventory", ["hidden", "mismatch", "ambiguous"])+def test_configured_gpu_still_requires_visible_matching_device(+ configured_gpu: tuple[Path, Mock], monkeypatch: pytest.MonkeyPatch, inventory: str+) -> None:+ """配置 GPU 不能借用不可见、另一张卡或身份不唯一的显存来开放高级档位。"""+ from mineru.model.runtime import llama_device++ device = LlamaDevice("Vulkan0", "test", "vulkan", 0x8086, 1 if inventory == "mismatch" else 0x7D51)+ devices = () if inventory == "hidden" else (device, device) if inventory == "ambiguous" else (device,)+ monkeypatch.setattr(llama_device, "discover_llama_devices", lambda: devices)+ report = recommendation.recommend_tiers()+ assert report.device.endswith(":gpu") and report.pdf_image_tiers == TIERS[:2]+ assert report.reason == ("no_visible_gpu" if inventory == "hidden" else "gpu_identity_unconfirmed")+ configured_gpu[1].assert_not_called()+++def test_configured_gpu_cli_and_api_agree(configured_gpu: tuple[Path, Mock], monkeypatch: pytest.MonkeyPatch) -> None:+ """真实推荐同时驱动 CLI 报告和 API 能力,缺少校准记录仍默认 Standard。"""+ from fastapi.testclient import TestClient+ from typer.testing import CliRunner++ from mineru.kit.commands import hardware+ from mineru.kit.main import app as kit_app+ from mineru.parser import api_server++ monkeypatch.setattr(hardware, "_detect_data", lambda: asdict(recommendation.recommend_tiers()))+ monkeypatch.setattr(api_server, "ensure_tier_runtime_dependencies", Mock())+ output = CliRunner().invoke(kit_app, ["hardware", "detect", "--json"])+ assert output.exit_code == 0, output.output+ data = json.loads(output.stdout)+ assert data["ceiling"] == "advanced" and data["default_request_tier"] == "standard"+ assert data["reason"] == "configured_gpu" and data["calibration"]["status"] == "skipped"+ assert data["calibration"]["reason"] == "configured_gpu" and data["calibration"]["evidence"]["status"] == "missing"+ assert "推荐启动上限:advanced" in hardware.render_detection(data)+ app = api_server.create_app(upload_dir=str(configured_gpu[0].parent / "uploads"))+ assert app.state.server_tiers == tuple(data["pdf_image_tiers"]) == TIERS+ assert app.state.default_tier == data["default_request_tier"]+ with TestClient(app) as client:+ assert tuple(row["id"] for row in client.get("/v1/tiers").json()["data"]) == TIERS+ for options in ({}, {"tier": "standard"}, {"tier": "advanced"}):+ 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 == options.get("tier", "standard")+ configured_gpu[1].assert_not_called()+ assert not cache.calibration_record_path().exists()++def test_failed_recalibration_revokes_previous_fast_evidence(startup_calibration: tuple[Path, Mock]) -> None:"""强制重新校准失败后,本次启动不能沿用已经撤销的旧 GPU 胜出证据。"""from mineru.model.runtime import onnx_device@@ -446,7 +603,9 @@ def test_startup_gpu_memory_threshold_and_low_cpu_calibration(assert report.reason == ("gpu_memory_unknown" if amount is None else "gpu_memory_insufficient")[email protected]("failure", ["configured_cpu", "selection_failed", "raise"])+ "failure", ["configured_cpu", "selection_failed", "no_hardware_gpu", "webgpu_architecture_policy", "raise"]+)def test_final_cpu_result_cannot_be_upgraded_by_discrete_inventory(startup_calibration: tuple[Path, Mock], monkeypatch: pytest.MonkeyPatch, failure: str) -> None:@@ -483,8 +642,6 @@ def test_apple_onnx_path_also_requires_budget(monkeypatch: pytest.MonkeyPatch, a@pytest.mark.parametrize("backend", ["dml", "webgpu"])def test_shared_classification_preserves_existing_calibration_fingerprint(evidence_path: Path, backend: str) -> None:"""分类和诊断字段变化不废弃旧校准格式,真实设备或绑定变化仍使证据失效。"""- import json-adapter = _adapter() if backend == "dml" else WebGPUDevice(0x8086, 0x7D51)cache.save_calibration_record(adapter, _measurement())identity = json.loads(evidence_path.read_text(encoding="utf-8"))["fingerprint"]["adapter"]