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(gpu): enhance GPU classification and identity matching for improved hardware detection
myhloli129d9452077d
diff --git a/docs/next/cli/mineru-kit-api-server.md b/docs/next/cli/mineru-kit-api-server.mdindex 064797ba..4e079cd9 100644--- a/docs/next/cli/mineru-kit-api-server.md+++ b/docs/next/cli/mineru-kit-api-server.md@@ -64,11 +64,13 @@ Tasks 的请求 `tier` 仍可选,只对 PDF/图片生效。省略或 JSON `nulCPU 数按逻辑 CPU 计算,并考虑进程亲和性和 Linux cgroup 配额。集显沿用有效 OCR 校准的 GPU 时间不高于 CPU 时间 0.8 倍的判定。探测失败或设备身份不明确时按 CPU 条件推荐。显式上限可以覆盖推荐,随后仍执行正常依赖预检。+GPU 类型与 OCR、llama.cpp 和硬件诊断使用共享分类;只有目标运行后端可见且原生身份确认的独显,才凭类型开放 Advanced。ggml 的通用 GPU 标志、未知类型及虚拟 GPU 均不直接视为独显;同型号多卡无法唯一关联时保持保守结果。各后端可以选择不同 GPU,共用分类和优先级,不强制跨后端同卡。+自动推荐先解析有效小模型后端。Torch(包括 auto 最终选择 Torch)只验证实际设备可用性:可用 CUDA/MPS/XPU 等加速设备推荐 advanced;显式 CPU 或设备不可用时按 CPU 条件推荐,不下载 ONNX 校准模型或改写其配置/记录。Torch 推荐不依赖 llama.cpp 库存。ONNX 分支先探测硬件并读取已有校准记录。如果初选达到 Basic 或更高档位,Windows/Linux 会在发布服务能力前同步执行现有 ONNX 设备选择流程,再根据最新证据确定最终上限。初选只有 Flash、macOS 及其他平台跳过这一步;显式 `--tier` 和 Python 精确集合也不触发这项启动校准。-启动选型继续遵守 `model.onnx_device`:`auto` 才按既有设备策略决定是否测速,显式或已保存的 `cpu/gpu` 不强制重新校准;Windows 独显、无可用 GPU、兼容策略排除的 GPU 等仍沿用原规则。需要测速时会按正常模型生命周期准备或下载 OCR rec 权重,并复用已有进程缓存、文件锁、采样阈值及失败回退。下载和模型准备不计入 15 秒校准子进程超时。校准失败或结果不稳定不会阻止后续推荐,但不作为 GPU 胜出证据。+启动选型继续遵守 `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` 在服务生命周期内固定。diff --git a/docs/next/cli/mineru-kit-hardware.md b/docs/next/cli/mineru-kit-hardware.mdindex f22d6849..12e82794 100644--- a/docs/next/cli/mineru-kit-hardware.md+++ b/docs/next/cli/mineru-kit-hardware.md@@ -25,10 +25,12 @@ mineru-kit hardware info --json > hardware-info.json`small_backend=auto` 最终选择 Torch 时同样免校准。显式设备字符串必须经过实际可用性检查;检查失败会给出保守结果及原因,不修改设备配置。Torch 推荐不依赖 llama.cpp 库存,不下载 ONNX 校准权重,也不写入 `model.onnx_device` 或 OCR 校准记录。-ONNX 分支保留既有兼容策略、0.8 阈值、进程缓存和配置保存规则。首次实际测速可能下载 OCR rec 模型;下载和派生图准备不计入 15 秒校准 worker 超时。显式或已保存的 CPU/GPU 选择不强制重测。校准失败、超时或不稳定时保守推荐,并携带警告。+ONNX 分支保留既有兼容策略、0.8 阈值和进程缓存。Windows 确认的独显,以及 Linux 通过兼容检查、由 Vulkan 唯一识别并配置物理绑定的独显,均免 OCR 校准,报告 `status=skipped, reason=discrete_gpu`;首次真实 GPU 会话成功后才保存 `gpu`,硬件推荐本身不生成校准记录。集显或类型无法确认的候选继续测速,首次可能下载 OCR rec 模型;下载和派生图准备不计入 15 秒校准 worker 超时。显式或已保存的 CPU/GPU 选择不强制重测。校准失败、超时或不稳定时保守推荐,并携带警告。llama.cpp 自动集显路径同样按有效小模型后端分流:Torch 使用加速可用性结果,不再绕回 OCR 校准;ONNX 保留原有性能结果和设备身份匹配。原生独显优先、显式 CPU/GPU 参数、物理绑定和兼容处理保持不变。+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`,不将可用性结论标成性能实测通过。开放 Advanced 后,请求省略 tier 仍默认 Standard。推荐不代表模型已准备好,API 服务继续执行依赖预检;显式启动上限和 Python 精确集合不进入自动推荐。API 工厂的 VLM 配置覆盖参与共享推荐,远程 VLM 显示为 `http-client`,不自动扩大本机上限。@@ -40,6 +42,7 @@ JSON 报告 `schema_version=1`,包含 `ceiling`、`pdf_image_tiers`、`default- 系统、Python 版本与解释器路径,MinerU 版本与实际模块路径。- CPU 型号、物理/逻辑/进程可用核数,基础/当前/最大频率(MHz);内存总量及可用量(bytes)。- 系统可探测到的全部独显、集显和虚拟 GPU,以及当前进程运行时可用设备。保留名称、身份、驱动及可获得的显存/共享内存信息。+- GPU 的 `kind` 与选型共用同一套分类;`kind_source` 标识分类来源,`source` 保留硬件资料的采集来源,`unified_memory` 单独记录已知的统一内存属性。- 已安装的软件包版本与位置:MinerU、DocVortex、mineru-llama-cpp、mineru-vl-utils、torch、transformers、ONNX Runtime及EP、vLLM、LMDeploy、mlx-vlm、pypdfium2。未安装的包不列入软件版本列表。- Torch 导入、编译使用的 CUDA/ROCm 版本和后端可用性;ORT provider 与相关引擎的探测结果。- 后端、设备、线程及可见设备限制的有效配置与来源;OCR 校准记录的存在状态、环境匹配、稳定性、耗时和阈值。diff --git a/docs/next/onnx-device.md b/docs/next/onnx-device.mdindex 3ac1f030..d6c73347 100644--- a/docs/next/onnx-device.md+++ b/docs/next/onnx-device.md@@ -11,11 +11,26 @@ model:环境变量 `MINERU_MODEL_ONNX_DEVICE` 高于文件配置。`small_backend=auto` 仍按原有规则选择Torch 或 ONNX;此选项不强制切换模型栈,也不改变 Torch / VLM 的设备。+### 共享 GPU 分类与选型++OCR、llama.cpp、auto tier 和硬件诊断共用 `discrete / integrated / virtual / unknown` 分类。+Windows 的分类依据为 D3D12 UMA,Linux 为 Vulkan 原生设备类型,macOS 复用现有系统显示设备信息。+统一内存属性单独保存,不将 Apple Silicon 的集显分类解释为低性能设备。++各后端先应用显式配置、设备可见性及兼容限制,再按“确认独显 → 确认集显 → 虚拟 GPU → 类型未知”排序;+同类设备保留 Windows 高性能排序、Vulkan 原生顺序或 llama.cpp 的单后端多设备分组规则。+OCR 与 llama.cpp 可以因支持范围不同选择不同显卡;不在目标后端候选中的独显不影响当前设备的校准或推荐。++ggml 的 GPU/IGPU 枚举仅用于确定 llama.cpp 可见的 GPU 库存,分类来自与平台原生设备的唯一关联。+身份匹配优先使用双方已有的 LUID、PCI 地址,再使用双方唯一的厂商/设备型号;名称只用于原生库存的唯一关联,+不用于猜测类型。重复库存、同型号多卡无法唯一关联或原生查询失败时保留未知,不凭此开放 Advanced 或免校准。+本实现不增加 UUID、PCI 地址等身份采集。Torch 的加速可用性推荐和 Apple Silicon/MPS 特例保持不变。+| 值 | Windows DML | Linux WebGPU ||---|---|---|| `cpu` | 全部使用 CPU,不枚举显卡、不测速 | 全部使用 CPU,不加载插件、不探测 GPU || `gpu` | 首次使用时发现 GPU,独显优先,不测速 | 通过 Intel 架构检查后使用 GPU,不测速;旧 Intel 回退 CPU |-| `auto` | 独显直接使用;集显执行 rec 测速 | 通过架构检查的集显、独显均执行自适应 rec 测速 |+| `auto` | 独显直接使用;集显或类型未知执行 rec 测速 | 通过架构检查且唯一确认的独显直接使用;集显或类型未知执行自适应 rec 测速 |Windows 使用 DXGI 高性能顺序、D3D12 UMA 属性和 LUID 匹配;适配器编号不写入配置。已保存的 `gpu` 使用 Windows 高性能排序及无设备创建的 D3D12 能力检查,避免逐张创建设备查询 UMA;@@ -28,6 +43,9 @@ Linux 使用原生 `onnxruntime-ep-webgpu`,通过 Dawn/Vulkan 执行。WebGPU 0.4 的 ORT 设备枚举项用于注册 EP,并不绑定 Dawn 的物理显卡。通常仍使用`powerPreference=high-performance`;参数固定为 `preferredLayout=NHWC`、`enableGraphCapture=0`、`dawnBackendType=Vulkan`,其他计算参数沿用运行时默认值。+独显/集显分类读取 Vulkan 的 `VkPhysicalDeviceProperties.deviceType`,不依据厂商名称、显存大小或 ORT 元数据猜测。+只有 ORT 描述与 Vulkan 可见设备唯一匹配、类型为 `DISCRETE_GPU` 且会话采用物理设备约束时,才跳过自动校准。+同型号多卡、重复 EP 描述或无法确认类型时保留校准;虚拟 GPU 不视为独显。### Linux Intel 架构策略@@ -39,14 +57,14 @@ WebGPU 0.4 的 ORT 设备枚举项用于注册 EP,并不绑定 Dawn 的物理|---|---|| 01、04、0a、0c、0d、0f、16、22、19、31、3e、5a、59、87、9b、8a、45、4e、98 | 旧架构,CPU || 46、4c、49、9a、a7 | Xe-LP,CPU(包含 DG1 独显) |-| 4f、56 | Xe-HPG,继续自适应校准 |-| 7d、b6 | Xe-LPG 系,继续自适应校准 |-| 64、e2 | Xe2-LPG / Xe2-HPG,继续自适应校准 |-| b0、fd | Xe3-LPG / Xe3-LPG XS,继续自适应校准 |+| 4f、56 | Xe-HPG,允许 GPU;按 Vulkan 类型决定是否校准 |+| 7d、b6 | Xe-LPG 系,允许 GPU;按 Vulkan 类型决定是否校准 |+| 64、e2 | Xe2-LPG / Xe2-HPG,允许 GPU;按 Vulkan 类型决定是否校准 |+| b0、fd | Xe3-LPG / Xe3-LPG XS,允许 GPU;按 Vulkan 类型决定是否校准 || 未识别的 Intel PCI ID 家族 | 保守使用 CPU,补充显式映射后才启用 |例如 `8086:4680`、`8086:a780`、`8086:9a49` 直接走 CPU;`8086:7d51`、`8086:7d55`、-`8086:56a0`、`8086:64a0`、`8086:e20b`、`8086:b080` 继续原有校准。+`8086:56a0`、`8086:64a0`、`8086:e20b`、`8086:b080` 进入 GPU 选型,其中确认的独显免校准。AMD/NVIDIA 不参与 Intel 分类;Windows DML 的设备规则和 metacommands 保持原样。这是 MinerU 的产品支持策略,不是宣称旧 Intel 硬件不支持 WebGPU。@@ -56,16 +74,16 @@ AMD/NVIDIA 不参与 Intel 分类;Windows DML 的设备规则和 metacommands### 混合显卡的物理设备约束-只有 ORT 库存同时包含被限制的 Intel 和其他候选 GPU 时,才查询 Vulkan 实际可见设备,尊重用户的 ICD/驱动筛选。+Linux GPU 选型查询 Vulkan 实际可见设备,尊重用户的 ICD/驱动筛选;全部架构受支持的机器同样执行此查询。该查询仅创建实例、枚举属性,不创建 logical device、不编译 shader、不进行 GPU 推理。从实际可见且架构允许的设备中优先选择独显,避免“发现一张 UHD 就禁用整个 WebGPU”。例如 UHD 770+3060 Ti 仍选择独显;若用户通过 `VK_DRIVER_FILES` 仅开放 Intel ICD,则直接走 CPU,不会把 ORT 中仍然存在的 NVIDIA 枚举项误当成可用物理独显。-混合场景在每次 WebGPU 会话创建期间临时设置 Vulkan 厂商/设备 ID 过滤,并在创建 Dawn 前重新枚举,+确认的独显及多卡场景在每次 WebGPU 会话创建期间临时设置 Vulkan 厂商/设备 ID 过滤,并在创建 Dawn 前重新枚举,确认只剩目标设备才继续。优先使用 Vulkan-Loader 1.4.326 起支持的 `VK_LOADER_VENDOR_ID_FILTER` /`VK_LOADER_DEVICE_ID_FILTER`;旧 loader 尝试 Mesa device-select 的 `vendor:device!`,同样必须验证结果。-若两种约束都不可用或被忽略,则记录原因、回退 CPU,不进行可能落到旧 Intel 的模型推理。+若两种约束都不可用或被忽略,则记录原因、回退 CPU,不保存独显 GPU 偏好,也不进行可能落到其他卡的模型推理。此时需升级 Vulkan loader 或安装/启用 Mesa device-select;不依赖 `vulkaninfo` 命令或新增 Python 包。过滤值随设备描述传入校准子进程;临时环境变量在成功和异常退出时均恢复。@@ -74,7 +92,8 @@ MinerU 的 WebGPU 运行时锁覆盖过滤与会话初始化,后续每次会这些环境变量是进程级的,宿主若另有独立 Vulkan 消费者,应避免在同一进程同时初始化它们。宿主也不应在 MinerU 之前自行初始化同一插件的默认 Dawn context;已有外部 WebGPU 会话时需使用新进程,本策略无法重新绑定外部提前创建的原生 context。-纯 AMD/NVIDIA 或全部为已支持架构的机器不额外查询 Vulkan、不设置过滤,保留原来的默认选择。+单张集显保持默认物理选择。若原生类型查询失败且 ORT 库存中的架构均受支持,则保留默认候选并继续校准,+不会据此授予独显免校准资格;存在受限 Intel 架构时,查询失败直接回退 CPU。本机双卡及仅 Intel ICD 的验证见 [Intel 架构过滤报告](onnx-intel-architecture-policy-validation.md)。@@ -82,8 +101,12 @@ MinerU 的 WebGPU 运行时锁覆盖过滤与会话初始化,后续每次会`mineru-kit hardware detect` 与 API 自动启动共享推荐逻辑;`hardware info` 只读报告环境与校准记录,不测速。界面启动本身、导入 SDK、查询配置和模型列表不会运行测速;界面托管的 API 服务仍遵循其启动参数。自动决策成功后原子更新有效配置文件中的 `model.onnx_device`,保留其余键;进程间通过文件锁协调。+校准证据显式保存设备、运行时与线程指纹;分类来源等诊断字段不进入指纹,原有有效记录可继续复用。+实际设备或物理绑定改变后,旧记录不再作为当前设备的性能证据。+Windows/Linux 免校准独显都只在首次真实 GPU 会话成功后保存 `gpu`;仅运行硬件推荐时仍保留 `auto`,+不下载校准权重、不生成性能校准记录。初始化错误或静默回退 CPU 不保存 GPU 偏好。环境变量覆盖不写入文件;只读配置保留本进程选择。测速失败不保存为 CPU 性能优胜,同进程不重复尝试。-Linux 插件缺失、Vulkan/设备发现失败(包括未发现可用硬件设备)、校准超时或输出不一致时保留 `auto`。+Linux 插件缺失、没有可用设备、物理绑定失败、校准超时或输出不一致时保留 `auto`。通过环境变量强制 `auto` 时,每个新进程重新选择,并使用选择锁避免同时测速。显式或已保存的 `cpu` 不会因后来接入独显而改变。@@ -214,7 +237,7 @@ Linux 标签可自定义,独立验证必须显式提供 `--expect cpu|gpu`;`WebGPU 推导新阈值需要至少三台不同标签机器的完整五进程报告,同时有 CPU/GPU 优胜组,各组通过 `--expect` 按独立性能证据标记。不能混合 DML/WebGPU、EP 版本或 WebGPU 参数来推导阈值。报告 schema v2 增加 backend/EP 字段;推导工具仍接受历史 v1 DML 报告。-WebGPU 阈值为 `None` 时,所有 auto GPU 路径保留 `auto` 并临时使用 CPU,显式 `gpu` 不受此限制。+WebGPU 阈值为 `None` 时,需要校准的 auto 路径保留 `auto` 并临时使用 CPU;显式 `gpu` 和确认的独显不受此限制。## 安装diff --git a/mineru/model/runtime/gpu.py b/mineru/model/runtime/gpu.pynew file mode 100644index 00000000..efad7b41--- /dev/null+++ b/mineru/model/runtime/gpu.py@@ -0,0 +1,132 @@+"""共享 GPU 分类、已有身份匹配和候选优先级;不导入或初始化推理运行时。"""++from __future__ import annotations++from collections.abc import Sequence+from dataclasses import dataclass, replace+from typing import Literal, TypeVar++GpuKind = Literal["discrete", "integrated", "virtual", "unknown"]+GPU_KIND_ORDER: tuple[GpuKind, ...] = ("discrete", "integrated", "virtual", "unknown")+_KIND_PRIORITY: dict[GpuKind, int] = {"discrete": 0, "integrated": 1, "virtual": 2, "unknown": 3}+++@dataclass(frozen=True, kw_only=True)+class GpuClassification:+ """各后端共用的分类事实,统一内存属性与 GPU 类型分别保存。"""++ kind: GpuKind = "unknown"+ kind_source: str = "unknown"+ unified_memory: bool | None = None+++@dataclass(frozen=True)+class GpuIdentity:+ """只使用已有设备身份;名称仅可用于原生库存之间的唯一关联。"""++ vendor_id: int | None = None+ device_id: int | None = None+ luid: str | None = None+ bus_id: str | None = None+ name: str | None = None+++_Gpu = TypeVar("_Gpu", bound=GpuClassification)+++def with_gpu_classification(device: _Gpu, classification: GpuClassification) -> _Gpu:+ """替换统一分类字段,保留后端的设备索引、注册描述和绑定约束。"""+ return replace(+ device,+ kind=classification.kind,+ kind_source=classification.kind_source,+ unified_memory=classification.unified_memory,+ )+++def gpu_kind_rank(kind: GpuKind) -> int:+ """返回统一优先级;同类型的性能排序或分组仍由各后端维护。"""+ return _KIND_PRIORITY[kind]+++def is_discrete_gpu(device: GpuClassification) -> bool:+ """只有已确认的独显分类才允许进入独显策略,未知或虚拟类型均不算。"""+ return device.kind == "discrete"+++def classify_d3d12_gpu(uma: bool | None) -> GpuClassification:+ """在 Windows 适配边界将 UMA 查询结果转换为统一分类,失败保留未知。"""+ kind: GpuKind = "unknown" if uma is None else "integrated" if uma else "discrete"+ return GpuClassification(kind=kind, kind_source="d3d12", unified_memory=uma)+++def classify_vulkan_gpu(device_type: int | None) -> GpuClassification:+ """仅在原生适配边界解释 Vulkan 类型,不据此推断未查询的统一内存属性。"""+ kinds: dict[int, GpuKind] = {1: "integrated", 2: "discrete", 3: "virtual"}+ if device_type is None:+ return GpuClassification()+ return GpuClassification(kind=kinds.get(device_type, "unknown"), kind_source="vulkan")+++def classify_macos_gpu(vendor: str | None, architecture: str, *, integrated: bool) -> GpuClassification:+ """转换现有 macOS 系统事实,Apple Silicon 的统一内存不等同于性能较弱。"""+ unified = vendor == "Apple" and architecture in {"arm64", "aarch64"}+ return GpuClassification(+ kind="integrated" if unified or integrated else "unknown",+ kind_source="system_profiler",+ unified_memory=True if unified else None,+ )+++def _normalized_bus_id(value: str) -> str:+ """统一已采集 PCI 地址的十六进制宽度,不额外读取系统或扩展身份信息。"""+ try:+ domain, bus, address = value.split(":")+ slot, function = address.split(".")+ return f"{int(domain, 16):04x}:{int(bus, 16):02x}:{int(slot, 16):02x}.{int(function, 16):x}"+ except ValueError:+ return value.lower()+++def gpu_identities_match(left: GpuIdentity, right: GpuIdentity, *, allow_name: bool = False) -> bool:+ """优先比较双方共有的强身份,存在冲突时不得退回型号或名称匹配。"""+ for first, second in ((left.vendor_id, right.vendor_id), (left.device_id, right.device_id)):+ if first is not None and second is not None and first != second:+ return False+ if left.luid and right.luid:+ return left.luid.lower() == right.luid.lower()+ if left.bus_id and right.bus_id:+ return _normalized_bus_id(left.bus_id) == _normalized_bus_id(right.bus_id)+ if all(value is not None for value in (left.vendor_id, left.device_id, right.vendor_id, right.device_id)):+ return (left.vendor_id, left.device_id) == (right.vendor_id, right.device_id)+ return bool(allow_name and left.name and left.name == right.name)+++def match_gpu_identities(+ sources: Sequence[GpuIdentity], targets: Sequence[GpuIdentity], *, allow_name: bool = False+) -> tuple[int | None, ...]:+ """只有两侧均唯一对应时返回目标索引,同型号多卡和重复库存均不猜测归属。"""+ candidates = [+ [index for index, target in enumerate(targets) if gpu_identities_match(source, target, allow_name=allow_name)]+ for source in sources+ ]+ return tuple(+ matches[0] if len(matches) == 1 and sum(matches[0] in other for other in candidates) == 1 else None+ for matches in candidates+ )+++__all__ = [+ "GPU_KIND_ORDER",+ "GpuClassification",+ "GpuIdentity",+ "GpuKind",+ "classify_d3d12_gpu",+ "classify_macos_gpu",+ "classify_vulkan_gpu",+ "gpu_identities_match",+ "gpu_kind_rank",+ "is_discrete_gpu",+ "match_gpu_identities",+ "with_gpu_classification",+]diff --git a/mineru/model/runtime/hardware.py b/mineru/model/runtime/hardware.pyindex 950eb889..dcd64c82 100644--- a/mineru/model/runtime/hardware.py+++ b/mineru/model/runtime/hardware.py@@ -13,6 +13,7 @@ from .hardware_probe import run_probefrom .hardware_system import collect_system_hardwarefrom .hardware_types import GpuInfo, HardwareInfo, PackageInfo, RuntimeProbefrom .onnx_calibration_cache import inspect_calibration_record+from .gpu import GPU_KIND_ORDER, GpuIdentity, gpu_identities_match, match_gpu_identitiesif TYPE_CHECKING:from .webgpu import WebGPUDevice@@ -92,27 +93,38 @@ def merge_gpu_inventory(gpus: list[GpuInfo], probe: RuntimeProbe) -> None:if probe.status != "ok":returnvendors = {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]+ rows = [+ row for row in probe.data.get("devices", []) if row.get("vendor_id") is not None and row.get("device_id") is not None+ ]+ identities = [+ GpuIdentity(row["vendor_id"], row["device_id"], luid=row.get("luid"), bus_id=row.get("bus_id"), name=row.get("name"))+ for row in rows+ ]+ targets = [gpu.identity for gpu in gpus]+ matches = match_gpu_identities(identities, targets)+ native_matches = match_gpu_identities(identities, identities)+ for index, (row, matched) in enumerate(zip(rows, matches)):+ vendor, chip = row["vendor_id"], row["device_id"]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]+ kind = row.get("kind", "unknown")+ if kind not in GPU_KIND_ORDER or native_matches[index] is None:+ kind = "unknown"+ if matched is not None:+ target = gpus[matched]target.name = target.name or name- target.kind = kindelse:+ if any(gpu_identities_match(identities[index], identity) for identity in targets):+ continue # 存在同型号候选但不能唯一关联,保留系统报告中的未知类型。target = GpuInfo(- name=name, vendor=vendors.get(vendor, hex(vendor)), device_id=identity, kind=kind, source=probe.name+ name=name,+ vendor=vendors.get(vendor, hex(vendor)),+ device_id=f"0x{vendor:04x}:0x{chip:04x}",+ source=probe.name,)gpus.append(target)+ target.kind = kind+ target.kind_source = row.get("kind_source", "unknown")+ target.unified_memory = row.get("unified_memory")for attribute in ("dedicated_memory_bytes", "shared_memory_bytes"):if row.get(attribute) is not None:setattr(target, attribute, row[attribute])diff --git a/mineru/model/runtime/hardware_system.py b/mineru/model/runtime/hardware_system.pyindex 437120ed..1bde7863 100644--- a/mineru/model/runtime/hardware_system.py+++ b/mineru/model/runtime/hardware_system.py@@ -16,6 +16,7 @@ from typing import Anyfrom .cpu_threads import effective_cpu_countfrom .hardware_types import GpuInfo, SystemHardware+from .gpu import GpuIdentity, classify_macos_gpu, gpu_identities_match, match_gpu_identities_VENDORS = {"0x8086": "Intel", "0x10de": "NVIDIA", "0x1002": "AMD"}@@ -135,15 +136,18 @@ def parse_macos_displays(payload: dict[str, Any], report: SystemHardware, archit"""解析系统显示设备 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"+ classification = classify_macos_gpu(+ vendor, architecture, integrated=row.get("spdisplays_integrated") == "spdisplays_yes"+ )+ unified = classification.unified_memorymemory = _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",+ kind=classification.kind,+ kind_source=classification.kind_source,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,@@ -257,23 +261,22 @@ def _nvidia_details(report: SystemHardware) -> None: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:+ rows = [tuple(value.strip() for value in row) for row in csv.reader(io.StringIO(output or "")) if len(row) == 4]+ identities = [GpuIdentity(bus_id=row[0], name=row[1]) for row in rows]+ targets = [gpu.identity for gpu in report.gpus]+ matches = match_gpu_identities(identities, targets, allow_name=True)+ for index, ((bus, name, driver, memory), matched) in enumerate(zip(rows, matches)):+ if matched is None:+ if any(gpu_identities_match(identities[index], target, allow_name=True) for target in targets):+ continuegpu = 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)+ else:+ gpu = report.gpus[matched]+ 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:diff --git a/mineru/model/runtime/hardware_types.py b/mineru/model/runtime/hardware_types.pyindex de6af3a2..9775bb72 100644--- a/mineru/model/runtime/hardware_types.py+++ b/mineru/model/runtime/hardware_types.py@@ -6,6 +6,7 @@ from dataclasses import dataclass, fieldfrom typing import Anyfrom .onnx_calibration_cache import CalibrationInfo+from .gpu import GpuIdentity, GpuKind@dataclass@@ -36,7 +37,8 @@ class GpuInfo:name: str | None = Nonevendor: str | None = Nonedevice_id: str | None = None- kind: str = "unknown"+ kind: GpuKind = "unknown"+ kind_source: str = "unknown"bus_id: str | None = Nonedriver: str | None = Nonededicated_memory_bytes: int | None = None@@ -44,6 +46,18 @@ class GpuInfo:unified_memory: bool | None = Nonesource: str = "unknown"+ @property+ def identity(self) -> GpuIdentity:+ """将报告已有的 PCI 型号和地址转换为共享身份,不从名称猜测厂商或类型。"""+ vendor, chip = None, None+ if self.device_id:+ try:+ vendor_text, chip_text = self.device_id.split(":")+ vendor, chip = int(vendor_text, 16), int(chip_text, 16)+ except ValueError:+ pass+ return GpuIdentity(vendor, chip, bus_id=self.bus_id, name=self.name)+@dataclassclass SystemHardware:diff --git a/mineru/model/runtime/llama_device.py b/mineru/model/runtime/llama_device.pyindex 6552a6d1..d7ef8eef 100644--- a/mineru/model/runtime/llama_device.py+++ b/mineru/model/runtime/llama_device.py@@ -16,6 +16,7 @@ from typing import Literalfrom loguru import loggerfrom .intel_gpu import INTEL_VENDOR_ID, intel_architecture+from .gpu import GPU_KIND_ORDER, is_discrete_gpu, match_gpu_identitiesfrom .llama_probe import LlamaDevice, PROBE_MARKERfrom .vulkan import vulkan_environment_lock@@ -79,19 +80,19 @@ def needs_serialized_submissions(device: LlamaDevice) -> bool:def _preferred(devices: tuple[LlamaDevice, ...], backend: str) -> tuple[LlamaDevice, ...]:"""与包内 Engine 的独显优先、单后端多设备规则保持一致。"""- for integrated in (False, True):+ for kind in GPU_KIND_ORDER:for name in ("metal", "vulkan"):if backend not in ("auto", name):continue- group = tuple(d for d in devices if d.integrated == integrated and d.backend == name)+ group = tuple(d for d in devices if d.kind == kind and d.backend == name)if group:return groupreturn ()-def _identity(device: LlamaDevice) -> tuple[str, bool, int | None, int | None]:+def _identity(device: LlamaDevice) -> tuple[str, str, int | None, int | None, str]:"""不使用可能因可见设备过滤而变化的 VulkanN 名称作为物理身份。"""- return device.description, device.integrated, device.vendor_id, device.device_id+ return device.description, device.kind, device.vendor_id, device.device_id, device.luid or ""def _bind(selection: LlamaSelection) -> LlamaSelection:@@ -161,7 +162,7 @@ def _resolve(return LlamaSelection("cpu", reason="no_gpu")manual = requested != "auto" or n_gpu_layers is not None or device_names is not Nonereason = "explicit_gpu" if manual else "discrete_gpu"- if not manual and not any(not d.integrated for d in inventory):+ if not manual and not any(is_discrete_gpu(d) for d in selected):from .device import resolve_small_model_backend, resolve_torch_deviceif resolve_small_model_backend() == "torch":@@ -176,12 +177,10 @@ def _resolve(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:+ matched = match_gpu_identities((choice.adapter.identity,), [d.identity for d in selected])[0]+ if matched is None:return LlamaSelection("cpu", reason="onnx_gpu_identity_unconfirmed")- selected, reason = matches, f"onnx_{choice.backend}_{choice.reason}"+ selected, reason = (selected[matched],), 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/llama_probe.py b/mineru/model/runtime/llama_probe.pyindex 6bde6337..31508b84 100644--- a/mineru/model/runtime/llama_probe.py+++ b/mineru/model/runtime/llama_probe.py@@ -5,29 +5,70 @@ from __future__ import annotationsimport ctypes as ctfrom contextlib import ExitStack-from dataclasses import asdict, dataclass+from dataclasses import asdict, dataclass, replaceimport importlib.utilimport jsonimport osfrom pathlib import Pathimport sys-from .vulkan import enumerate_vulkan_devices+from .gpu import GpuClassification, GpuIdentity, match_gpu_identities, with_gpu_classification+from .vulkan import VulkanDevice, enumerate_vulkan_devicesPROBE_MARKER = "MINERU_LLAMA_DEVICES="@dataclass(frozen=True)-class LlamaDevice:+class LlamaDevice(GpuClassification):"""ggml 注册设备名称和经过唯一匹配的 Vulkan PCI 身份。"""name: strdescription: strbackend: str- integrated: boolvendor_id: int | None = Nonedevice_id: int | None = Nonevulkan_index: int | None = None+ luid: str | None = None++ @property+ def identity(self) -> GpuIdentity:+ """提供原生唯一匹配得到的物理身份,不使用可变的 VulkanN 注册名称。"""+ return GpuIdentity(self.vendor_id, self.device_id, luid=self.luid, name=self.description)+++def _classify_devices(devices: tuple[LlamaDevice, ...], physical: tuple[VulkanDevice, ...]) -> tuple[LlamaDevice, ...]:+ """ggml 只确认可见性,分类来自 Linux Vulkan 或 Windows D3D12 的唯一原生匹配。"""+ vulkan_indices = [index for index, device in enumerate(devices) if device.backend == "vulkan"]+ matches = match_gpu_identities(+ [devices[index].identity for index in vulkan_indices], [device.identity for device in physical], allow_name=True+ )+ result = list(devices)+ for index, matched in zip(vulkan_indices, matches):+ if matched is None:+ continue+ native = physical[matched]+ result[index] = replace(+ result[index], vendor_id=native.vendor_id, device_id=native.device_id, vulkan_index=native.index+ )+ if sys.platform == "linux":+ result[index] = with_gpu_classification(result[index], native)+ if sys.platform == "win32":+ from .windows_gpu import discover_gpus++ try:+ adapters = discover_gpus()+ except (OSError, RuntimeError):+ adapters = ()+ matches = match_gpu_identities(+ [result[index].identity for index in vulkan_indices], [adapter.identity for adapter in adapters], allow_name=True+ )+ for index, matched in zip(vulkan_indices, matches):+ if matched is not None:+ adapter = adapters[matched]+ result[index] = with_gpu_classification(+ replace(result[index], vendor_id=adapter.vendor_id, device_id=adapter.device_id, luid=adapter.luid), adapter+ )+ return tuple(result)def probe_devices() -> tuple[LlamaDevice, ...]:@@ -80,20 +121,14 @@ def _probe_library(root: Path) -> tuple[LlamaDevice, ...]:continuelabel = description(device).decode()backend_name = backend(registry(device)).decode().lower()- matches = [p for p in physical if p.name == label] if backend_name == "vulkan" else []- identities = {(p.vendor_id, p.device_id) for p in matches}- identity = next(iter(identities)) if len(identities) == 1 else (None, None)result.append(LlamaDevice(name(device).decode(),label,"metal" if backend_name == "mtl" else backend_name,- device_type == 2,- *identity,- matches[0].index if len(matches) == 1 else None,))- return tuple(result)+ return _classify_devices(tuple(result), physical)def main() -> None:diff --git a/mineru/model/runtime/onnx_calibration_cache.py b/mineru/model/runtime/onnx_calibration_cache.pyindex c47cb062..849c07d5 100644--- a/mineru/model/runtime/onnx_calibration_cache.py+++ b/mineru/model/runtime/onnx_calibration_cache.py@@ -2,7 +2,7 @@from __future__ import annotations-from dataclasses import asdict, dataclass+from dataclasses import dataclassfrom importlib.metadata import PackageNotFoundError, versionimport jsonimport os@@ -105,9 +105,12 @@ def _fingerprint(adapter: GpuAdapter | WebGPUDevice, intra_op_num_threads: int = 0, inter_op_num_threads: int = 0) -> dict[str, Any]:"""绑定物理设备、后端版本及 CPU 配置;忽略进程内设备序号和排序。"""- identity = asdict(adapter)- identity.pop("index", None)- identity.pop("preference", None)+ # 显式保持既有证据格式,分类来源等新增诊断字段不参与性能证据的身份指纹。+ identity: dict[str, Any] = {"vendor_id": adapter.vendor_id, "device_id": adapter.device_id}+ if isinstance(adapter, GpuAdapter):+ identity.update(luid=adapter.luid, name=adapter.name, uma=adapter.unified_memory)+ else:+ identity.update(metadata=adapter.metadata, vulkan_device=adapter.vulkan_device)backend = "webgpu" if isinstance(adapter, WebGPUDevice) else "dml"# JSON 往返统一 metadata 等元组,确保读写指纹完全一致。return json.loads(diff --git a/mineru/model/runtime/onnx_device.py b/mineru/model/runtime/onnx_device.pyindex 1df944d4..45be04bb 100644--- a/mineru/model/runtime/onnx_device.py+++ b/mineru/model/runtime/onnx_device.py@@ -15,6 +15,7 @@ from loguru import loggerfrom .windows_gpu import GpuAdapter, discover_gpus, preferred_gpufrom .webgpu import WebGPUDevice, discover_webgpu_devices, select_webgpu_device+from .gpu import is_discrete_gpu# Require at least 20% lower GPU inference time; simplified to 0.8 at the user's request.# Evidence: docs/next/onnx-selection-validation.md. Each backend can be calibrated independently.@@ -85,7 +86,7 @@ def _select(devices = discover_webgpu_devices()adapter = select_webgpu_device(devices)if devices and adapter is None:- logger.info("Linux WebGPU Intel architecture policy selected CPU; no eligible visible GPU")+ logger.info("Linux WebGPU device policy selected CPU; no eligible visible GPU")return OnnxSelection(reason="webgpu_architecture_policy", backend=backend), Falseelse:import onnxruntime as ort@@ -97,7 +98,11 @@ def _select(if adapter is None:# A plugin can expose no devices after a driver discovery failure. Do not persist that as a CPU win.return OnnxSelection(reason="no_hardware_gpu"), requested == "auto" and backend == "dml"- if requested == "gpu" or (isinstance(adapter, GpuAdapter) and adapter.uma is False):+ # Linux 只有唯一确认的 Vulkan 独显且会话带物理约束,才与 DML 独显一样免校准。+ discrete = is_discrete_gpu(adapter) and (+ not isinstance(adapter, WebGPUDevice) or adapter.vulkan_device == (adapter.vendor_id, adapter.device_id)+ )+ if requested == "gpu" or discrete:return OnnxSelection("gpu", adapter, "configured_gpu" if requested == "gpu" else "discrete_gpu", backend), Falsethreshold = ONNX_GPU_TIME_RATIO_THRESHOLDS[backend]if threshold is None:@@ -182,7 +187,7 @@ def resolve_onnx_device(def confirm_gpu_session(selection: OnnxSelection) -> None:- """Persist a discrete-GPU auto choice only after an actual DML session succeeded."""+ """独显自动选型仅在真实 DML/WebGPU 会话成功后保存,初始化回退不写入 GPU 偏好。"""if selection.reason != "discrete_gpu":returnfrom ...config import get_config, get_config_source, update_config_filediff --git a/mineru/model/runtime/tier_recommendation.py b/mineru/model/runtime/tier_recommendation.pyindex 874747ea..fc450a09 100644--- a/mineru/model/runtime/tier_recommendation.py+++ b/mineru/model/runtime/tier_recommendation.py@@ -12,6 +12,7 @@ from loguru import loggerfrom ...types import TIERS, Tierfrom .cpu_threads import effective_cpu_countfrom .device import resolve_small_model_backend, resolve_torch_device+from .gpu import is_discrete_gpu, match_gpu_identitiesfrom .onnx_calibration_cache import CalibrationInfo, inspect_calibration_recordif TYPE_CHECKING:@@ -87,7 +88,7 @@ def _advanced_gpu_reason() -> str | None:from .llama_device import discover_llama_devicesdevices = tuple(d for d in discover_llama_devices() if backend == "auto" or d.backend == backend)- if any(not device.integrated for device in devices):+ if any(is_discrete_gpu(device) for device in devices):return "discrete_gpu"if not devices:return None@@ -107,8 +108,8 @@ def _advanced_gpu_reason() -> str | None:threshold = ONNX_GPU_TIME_RATIO_THRESHOLDS["webgpu"]if adapter is None or threshold is None:return None- matches = [d for d in devices if (d.vendor_id, d.device_id) == (adapter.vendor_id, adapter.device_id)]- if len(matches) != 1:+ 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 Noneif calibrated_gpu_is_faster(adapter, threshold):diff --git a/mineru/model/runtime/vulkan.py b/mineru/model/runtime/vulkan.pyindex f11dd3b9..0a5b9e89 100644--- a/mineru/model/runtime/vulkan.py+++ b/mineru/model/runtime/vulkan.py@@ -13,6 +13,8 @@ import osimport sysimport threading+from .gpu import GpuClassification, GpuIdentity, classify_vulkan_gpu, with_gpu_classification+_environment_lock = threading.RLock()@@ -22,13 +24,17 @@ def vulkan_environment_lock() -> threading.RLock:@dataclass(frozen=True)-class VulkanDevice:+class VulkanDevice(GpuClassification):vendor_id: intdevice_id: int- device_type: intname: strindex: int = -1+ @property+ def identity(self) -> GpuIdentity:+ """返回现有 PCI 型号和原生名称,不把枚举序号当作跨后端身份。"""+ return GpuIdentity(self.vendor_id, self.device_id, name=self.name)+class _ApplicationInfo(ct.Structure):_fields_ = [@@ -111,14 +117,16 @@ def enumerate_vulkan_devices() -> tuple[VulkanDevice, ...]:storage = _PropertiesStorage()properties(handle, ct.byref(storage))value = storage.prefix- if value.deviceType in (1, 2, 3): # integrated, discrete, virtual GPU; exclude software CPU+ if value.deviceType in (0, 1, 2, 3): # 保留未知原生类型,由运行后端过滤可用性;排除软件 CPU。result.append(- VulkanDevice(- value.vendorID,- value.deviceID,- value.deviceType,- value.deviceName.decode("utf-8", errors="replace"),- index,+ with_gpu_classification(+ VulkanDevice(+ value.vendorID,+ value.deviceID,+ value.deviceName.decode("utf-8", errors="replace"),+ index,+ ),+ classify_vulkan_gpu(value.deviceType),))return tuple(result)diff --git a/mineru/model/runtime/webgpu.py b/mineru/model/runtime/webgpu.pyindex c968fc5f..cef688f8 100644--- a/mineru/model/runtime/webgpu.py+++ b/mineru/model/runtime/webgpu.py@@ -12,6 +12,15 @@ import threadingfrom typing import TYPE_CHECKINGfrom .intel_gpu import supports_webgpu_architecture+from .gpu import (+ GpuClassification,+ GpuIdentity,+ gpu_identities_match,+ gpu_kind_rank,+ is_discrete_gpu,+ match_gpu_identities,+ with_gpu_classification,+)if TYPE_CHECKING:import onnxruntime as ort@@ -26,15 +35,20 @@ WEBGPU_OPTIONS: dict[str, str] = {@dataclass(frozen=True)-class WebGPUDevice:+class WebGPUDevice(GpuClassification):"""Serializable EP registration identity, NOT a Dawn physical-adapter selector."""vendor_id: intdevice_id: intmetadata: tuple[tuple[str, str], ...] = ()- # Only needed when old Intel and eligible GPUs coexist. No native handles.+ # 物理设备约束用于多卡选型及独显免校准;只传递身份,不保存原生句柄。vulkan_device: tuple[int, int] | None = None+ @property+ def identity(self) -> GpuIdentity:+ """复用 EP 已提供的身份元数据,不额外查询 UUID 或 PCI 地址。"""+ return GpuIdentity(self.vendor_id, self.device_id, bus_id=dict(self.metadata).get("pci_bus_id"))+_lock = threading.RLock()_registered_pid: int | None = None@@ -75,7 +89,7 @@ def discover_webgpu_devices() -> tuple[WebGPUDevice, ...]:def select_webgpu_device(devices: tuple[WebGPUDevice, ...]) -> WebGPUDevice | None:- """Apply the Linux Intel policy without treating an EP handle as a GPU binding."""+ """按 Vulkan 可见类型优先选择独显,并为免校准和多卡会话绑定实际设备。"""if not devices:return Noneif sys.platform != "linux":@@ -83,20 +97,31 @@ def select_webgpu_device(devices: tuple[WebGPUDevice, ...]) -> WebGPUDevice | Noallowed = tuple(d for d in devices if supports_webgpu_architecture(d.vendor_id, d.device_id))if not allowed:return None- if len(allowed) == len(devices):- return devices[0] # Preserve ordinary AMD/NVIDIA/modern-Intel selection.- from .vulkan import enumerate_vulkan_devices-- # ORT enumerates OS devices, even those hidden by VK_DRIVER_FILES. Query- # the loader before deciding which physical GPUs can actually be used.- with execution_lock():- visible = enumerate_vulkan_devices()- rank = {2: 0, 1: 1, 3: 2} # Dawn high-performance: discrete before integrated.- for physical in sorted(visible, key=lambda d: rank[d.device_type]):- descriptor = next((d for d in allowed if (d.vendor_id, d.device_id) == (physical.vendor_id, physical.device_id)), None)- if descriptor is not None:- return replace(descriptor, vulkan_device=(physical.vendor_id, physical.device_id))- return None+ from .vulkan import enumerate_vulkan_devices, vulkan_environment_lock++ # ORT 库存可能包含 ICD 已隐藏的设备;分类必须来自 Vulkan 实际可见的物理设备。+ try:+ with execution_lock(), vulkan_environment_lock():+ visible = enumerate_vulkan_devices()+ except (OSError, RuntimeError):+ if len(allowed) != len(devices):+ raise # 有受限架构时无法确认物理绑定,不允许继续默认选卡。+ return with_gpu_classification(devices[0], GpuClassification())+ matches = match_gpu_identities([d.identity for d in allowed], [d.identity for d in visible])+ candidates: list[tuple[int, WebGPUDevice]] = []+ for descriptor, matched in zip(allowed, matches):+ physical_indices = [+ i for i, physical in enumerate(visible) if gpu_identities_match(descriptor.identity, physical.identity)+ ]+ if not physical_indices:+ continue+ # 物理型号存在但无法双向唯一关联时,仍可校准,不允许继承某张卡的独显分类。+ candidate = with_gpu_classification(descriptor, visible[matched] if matched is not None else GpuClassification())+ bind = is_discrete_gpu(candidate) or len(visible) > 1 or len(allowed) != len(devices)+ identity = (candidate.vendor_id, candidate.device_id)+ candidates.append((physical_indices[0], replace(candidate, vulkan_device=identity if bind else None)))+ candidates.sort(key=lambda item: (gpu_kind_rank(item[1].kind), item[0]))+ return candidates[0][1] if candidates else None@contextmanager@@ -130,12 +155,11 @@ def webgpu_session_scope(device: WebGPUDevice) -> Iterator[None]:def attach_webgpu_provider(options: ort.SessionOptions, device: WebGPUDevice) -> None:"""Resolve a fresh native handle and attach the production provider parameters."""with execution_lock():- identity = replace(device, vulkan_device=None)+ identity = with_gpu_classification(replace(device, vulkan_device=None), GpuClassification())ep = next((ep for ep in _devices() if _describe(ep) == identity), None)if ep is None:raise RuntimeError("WebGPU hardware registration device is no longer available")- # The caller's webgpu_session_scope restricts mixed-architecture systems.- # This registration handle itself still does not bind a physical adapter.+ # 物理约束由调用方 webgpu_session_scope 验证;EP 注册句柄本身不绑定显卡。options.add_provider_for_devices([ep], WEBGPU_OPTIONS)diff --git a/mineru/model/runtime/windows_gpu.py b/mineru/model/runtime/windows_gpu.pyindex ca803c5f..32c875b4 100644--- a/mineru/model/runtime/windows_gpu.py+++ b/mineru/model/runtime/windows_gpu.py@@ -4,14 +4,16 @@from __future__ import annotationsimport ctypes as C-from dataclasses import dataclass+from dataclasses import asdict, dataclassimport sysfrom typing import Anyimport uuid+from .gpu import GpuClassification, GpuIdentity, classify_d3d12_gpu, gpu_kind_rank, with_gpu_classification+@dataclass(frozen=True)-class GpuAdapter:+class GpuAdapter(GpuClassification):"""One hardware adapter, with its ordinary DXGI index and preference rank."""index: int@@ -19,9 +21,13 @@ class GpuAdapter:name: strvendor_id: intdevice_id: int- uma: bool | Nonepreference: int+ @property+ def identity(self) -> GpuIdentity:+ """提供已有 LUID 与 PCI 型号,设备序号不参与物理身份匹配。"""+ return GpuIdentity(self.vendor_id, self.device_id, luid=self.luid, name=self.name)+@propertydef vendor(self) -> str:return {0x8086: "intel", 0x1002: "amd", 0x10DE: "nvidia"}.get(self.vendor_id, "unknown")@@ -160,17 +166,22 @@ def discover_gpus(*, classify: bool = True) -> tuple[GpuAdapter, ...]:supported, uma = _architecture(adapter, create_device, classify=classify or not modern)if supported:luid = _luid(desc)- rows.append(GpuAdapter(index, luid, desc.name, desc.vendor, desc.device, uma, ranks.get(luid, index)))+ rows.append(+ with_gpu_classification(+ GpuAdapter(index, luid, desc.name, desc.vendor, desc.device, ranks.get(luid, index)),+ classify_d3d12_gpu(uma),+ )+ )finally:_release(adapter)- return tuple(sorted(rows, key=lambda item: (item.uma is not False, item.preference, item.index)))+ return tuple(sorted(rows, key=lambda item: (gpu_kind_rank(item.kind), item.preference, item.index)))finally:_release(factory)def preferred_gpu(adapters: tuple[GpuAdapter, ...]) -> GpuAdapter | None:"""Prefer a confirmed discrete GPU, then Windows performance preference."""- return min(adapters, key=lambda item: (item.uma is not False, item.preference, item.index), default=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]]:@@ -208,7 +219,7 @@ def inspect_gpus() -> list[dict[str, Any]]:"device_id": desc.device,"luid": _luid(desc),"d3d12_available": supported,- "kind": "unknown" if uma is None else "integrated" if uma else "discrete",+ **asdict(classify_d3d12_gpu(uma)),"dedicated_memory_bytes": desc.video_memory,"shared_memory_bytes": desc.shared_memory,}diff --git a/scripts/benchmark_onnx_selection.py b/scripts/benchmark_onnx_selection.pyindex e4f652ac..eb571f98 100644--- a/scripts/benchmark_onnx_selection.py+++ b/scripts/benchmark_onnx_selection.py@@ -139,7 +139,7 @@ def run(args: argparse.Namespace) -> None:adapter = next((gpu for gpu in adapters if gpu.luid == args.luid), None) if args.luid else preferred_gpu(adapters)if adapter is None:raise ValueError("Requested hardware GPU was not found")- if backend == "dml" and adapter.uma is not True:+ if backend == "dml" and adapter.kind != "integrated":raise ValueError("Threshold calibration must explicitly target a confirmed integrated GPU")if args.model is None:from mineru.model.registry import MINERU_4_MODELS_ONNXdiff --git a/tests/unittest/test_directml_runtime.py b/tests/unittest/test_directml_runtime.pyindex a755afc0..90e6ef33 100644--- a/tests/unittest/test_directml_runtime.py+++ b/tests/unittest/test_directml_runtime.py@@ -11,6 +11,7 @@ from unittest.mock import Mockimport numpy as npimport pytest+from mineru.model.runtime.gpu import classify_d3d12_gpu, with_gpu_classificationfrom mineru.model.runtime import onnxfrom mineru.model.runtime.onnx_device import OnnxSelectionfrom mineru.model.runtime.windows_gpu import GpuAdapter@@ -26,7 +27,7 @@ from mineru.model.runtime.windows_gpu import GpuAdapter],)def test_vendor_presets_and_actual_index(monkeypatch: pytest.MonkeyPatch, vendor: int, enabled: list[bool | None]) -> None:- adapter = GpuAdapter(7, "luid", "gpu", vendor, 1, True, 0)+ adapter = with_gpu_classification(GpuAdapter(7, "luid", "gpu", vendor, 1, 0), classify_d3d12_gpu(True))monkeypatch.setattr(onnx.ort, "get_available_providers", lambda: ["DmlExecutionProvider", "CPUExecutionProvider"])native = SimpleNamespace(get_providers=lambda: ["DmlExecutionProvider", "CPUExecutionProvider"], disable_fallback=Mock())factory = Mock(return_value=native)@@ -58,7 +59,7 @@ def test_cpu_models_do_not_select_gpu(monkeypatch: pytest.MonkeyPatch) -> None:@pytest.mark.parametrize("failure", ["unavailable", "exception", "silent"])@pytest.mark.parametrize("kind", ["layout", "unet"])def test_production_fallback_does_not_save_gpu(monkeypatch: pytest.MonkeyPatch, failure: str, kind: str) -> None:- adapter = GpuAdapter(1, "id", "gpu", 0x8086, 1, False, 0)+ adapter = with_gpu_classification(GpuAdapter(1, "id", "gpu", 0x8086, 1, 0), classify_d3d12_gpu(False))cpu = SimpleNamespace(get_providers=lambda: ["CPUExecutionProvider"])monkeypatch.setattr(onnx.ort, "get_available_providers", lambda: [] if failure == "unavailable" else ["DmlExecutionProvider"]@@ -94,7 +95,9 @@ def test_calibration_factory_fails_instead_of_falling_back(monkeypatch: pytest.Monnx.ort, "InferenceSession", Mock(return_value=SimpleNamespace(get_providers=lambda: ["CPUExecutionProvider"])))with pytest.raises(RuntimeError, match="fell back"):- onnx.create_ort_session("test.onnx", adapter=GpuAdapter(0, "id", "gpu", 1, 1, True, 0))+ onnx.create_ort_session(+ "test.onnx", adapter=with_gpu_classification(GpuAdapter(0, "id", "gpu", 1, 1, 0), classify_d3d12_gpu(True))+ )def test_run_is_serialized_per_session() -> None:diff --git a/tests/unittest/test_gpu_policy.py b/tests/unittest/test_gpu_policy.pynew file mode 100644index 00000000..59e7191d--- /dev/null+++ b/tests/unittest/test_gpu_policy.py@@ -0,0 +1,205 @@+"""共享 GPU 类型、身份关联及各运行入口的一致性回归。"""++from __future__ import annotations++from dataclasses import asdict, replace+import itertools+from pathlib import Path+import subprocess+import sys+from types import SimpleNamespace+from unittest.mock import Mock++import pytest++from mineru.model.runtime import hardware, llama_device, llama_probe, tier_recommendation, vulkan, webgpu, windows_gpu+from mineru.model.runtime.gpu import (+ GPU_KIND_ORDER,+ GpuClassification,+ GpuIdentity,+ GpuKind,+ classify_d3d12_gpu,+ classify_macos_gpu,+ classify_vulkan_gpu,+ gpu_identities_match,+ match_gpu_identities,+ with_gpu_classification,+)+from mineru.model.runtime.hardware_types import GpuInfo, RuntimeProbe+++ ("platform", "classification"),+ [+ ("linux", classify_vulkan_gpu(1)),+ ("linux", classify_vulkan_gpu(2)),+ ("linux", classify_vulkan_gpu(3)),+ ("linux", classify_vulkan_gpu(0)),+ ("win32", classify_d3d12_gpu(True)),+ ("win32", classify_d3d12_gpu(False)),+ ("win32", classify_d3d12_gpu(None)),+ ],+)+def test_native_classification_agrees_across_runtime_and_report(+ monkeypatch: pytest.MonkeyPatch, platform: str, classification: GpuClassification+) -> None:+ """同一卡的 OCR、ggml 可见设备、档位推荐和硬件报告必须采用同一个分类来源。"""+ from mineru.model.runtime import onnx_calibration_cache++ for module in (llama_probe, webgpu, tier_recommendation):+ monkeypatch.setattr(module, "sys", SimpleNamespace(platform=platform))+ monkeypatch.delenv("MINERU_LLAMA_CPP_BACKEND", raising=False)+ monkeypatch.setattr(tier_recommendation, "effective_cpu_count", lambda: 4)+ monkeypatch.setattr(onnx_calibration_cache, "calibrated_gpu_is_faster", lambda *args: False)+ native = vulkan.VulkanDevice(0x1002, 1, "GPU", 0)+ # Windows 故意提供相反的 Vulkan 类型,确认分类权威仍是 D3D12。+ native = with_gpu_classification(+ native, classification if platform == "linux" else classify_vulkan_gpu(2 if classification.kind != "discrete" else 1)+ )+ monkeypatch.setattr(vulkan, "enumerate_vulkan_devices", lambda: (native,))+ windows = with_gpu_classification(windows_gpu.GpuAdapter(0, "physical", "GPU", 0x1002, 1, 0), classification)+ monkeypatch.setattr(windows_gpu, "discover_gpus", lambda: (windows,))+ monkeypatch.setattr(webgpu, "discover_webgpu_devices", lambda: (webgpu.WebGPUDevice(0x1002, 1),))+ actual = llama_probe._classify_devices((llama_probe.LlamaDevice("Vulkan0", "GPU", "vulkan"),), (native,))+ monkeypatch.setattr(llama_device, "discover_llama_devices", lambda: actual)+ ocr = (+ windows_gpu.preferred_gpu((windows,))+ if platform == "win32"+ else webgpu.select_webgpu_device(webgpu.discover_webgpu_devices())+ )+ assert ocr is not None+ report = [GpuInfo(name="GPU", device_id="0x1002:0x0001")]+ hardware.merge_gpu_inventory(+ report,+ RuntimeProbe(+ "dxgi" if platform == "win32" else "vulkan", "ok", {"devices": [asdict(windows if platform == "win32" else native)]}+ ),+ )+ for device in (ocr, actual[0], report[0]):+ assert device.kind == classification.kind+ assert device.kind_source == classification.kind_source+ assert device.unified_memory == classification.unified_memory+ assert tier_recommendation.detect_tier_hardware().advanced_gpu is (classification.kind == "discrete")++[email protected]("order", list(itertools.permutations(GPU_KIND_ORDER)))+def test_backends_share_kind_order_with_native_tiebreakers(order: tuple[GpuKind, ...]) -> None:+ """Windows 性能排序和 llama 后端分组都只能在统一类型优先级之后生效。"""+ windows = tuple(+ windows_gpu.GpuAdapter(index, str(index), kind, 0x1002, index, index, kind=kind) for index, kind in enumerate(order)+ )+ llama = tuple(+ llama_probe.LlamaDevice(f"Vulkan{index}", kind, "vulkan", 0x1002, index, index, kind=kind)+ for index, kind in enumerate(order)+ )+ for expected in GPU_KIND_ORDER:+ selected = windows_gpu.preferred_gpu(windows)+ assert selected is not None and selected.kind == expected+ assert llama_device._preferred(llama, "auto")[0].kind == expected+ windows = tuple(device for device in windows if device.kind != expected)+ llama = tuple(device for device in llama if device.kind != expected)+++def test_identity_matching_requires_mutual_uniqueness() -> None:+ """不能仅凭同型号或重复名称把多个设备合并,已有强身份相异时也不得降级匹配。"""+ card = GpuIdentity(0x10DE, 1, name="GPU")+ assert match_gpu_identities((card,), (card,)) == (0,)+ assert match_gpu_identities((card, card), (card,)) == (None, None)+ assert match_gpu_identities((card,), (card, card)) == (None,)+ assert match_gpu_identities((GpuIdentity(name="GPU"),), (card,)) == (None,)+ assert match_gpu_identities((GpuIdentity(name="GPU"),), (card,), allow_name=True) == (0,)+ assert not gpu_identities_match(replace(card, luid="a"), replace(card, luid="b"))+ assert not gpu_identities_match(replace(card, bus_id="0000:01:00.0"), replace(card, bus_id="0000:02:00.0"))+ assert not gpu_identities_match(card, replace(card, device_id=2), allow_name=True)+ first, second = replace(card, luid="a"), replace(card, luid="b")+ assert match_gpu_identities((first, second), (second, first)) == (1, 0)+ assert gpu_identities_match(GpuIdentity(bus_id="00000000:01:00.0"), GpuIdentity(bus_id="0000:01:00.0"))++[email protected]("platform", ["linux", "win32"])+def test_ambiguous_native_mapping_remains_unknown_everywhere(monkeypatch: pytest.MonkeyPatch, platform: str) -> None:+ """同型号多卡无法关联到运行时和报告时,不能被标为确定独显。"""+ monkeypatch.setattr(llama_probe, "sys", SimpleNamespace(platform=platform))+ monkeypatch.setattr(webgpu, "sys", SimpleNamespace(platform="linux"))+ physical = tuple(vulkan.VulkanDevice(0x10DE, 1, "GPU", index, kind="discrete", kind_source="vulkan") for index in range(2))+ raw = tuple(llama_probe.LlamaDevice(f"Vulkan{index}", "GPU", "vulkan") for index in range(2))+ monkeypatch.setattr(vulkan, "enumerate_vulkan_devices", lambda: physical)+ monkeypatch.setattr(+ windows_gpu,+ "discover_gpus",+ lambda: tuple(+ windows_gpu.GpuAdapter(index, str(index), "GPU", 0x10DE, 1, index, kind="discrete", kind_source="d3d12")+ for index in range(2)+ ),+ )+ result = llama_probe._classify_devices(raw, physical)+ assert all(device.kind == "unknown" for device in result)+ ocr = webgpu.select_webgpu_device((webgpu.WebGPUDevice(0x10DE, 1),))+ assert ocr is not None and ocr.kind == "unknown"+ report = [GpuInfo(name="GPU", device_id="0x10de:0x0001") for _ in range(2)]+ hardware.merge_gpu_inventory(report, RuntimeProbe("vulkan", "ok", {"devices": [asdict(device) for device in physical]}))+ assert len(report) == 2 and all(device.kind == "unknown" for device in report)+++def test_windows_native_query_failure_does_not_use_ggml_or_vulkan_type(monkeypatch: pytest.MonkeyPatch) -> None:+ """Windows 的分类查询失败时保留未知,不把 ggml/Vulkan 的 GPU 标签升级为独显。"""+ monkeypatch.setattr(llama_probe, "sys", SimpleNamespace(platform="win32"))+ monkeypatch.setattr(windows_gpu, "discover_gpus", Mock(side_effect=OSError("D3D12 unavailable")))+ result = llama_probe._classify_devices(+ (llama_probe.LlamaDevice("Vulkan0", "GPU", "vulkan"),),+ (vulkan.VulkanDevice(0x10DE, 1, "GPU", 0, kind="discrete", kind_source="vulkan"),),+ )+ assert result[0].kind == "unknown" and result[0].vulkan_index == 0++[email protected]("native_type", [1, 3])+def test_ggml_gpu_enum_only_controls_inventory(monkeypatch: pytest.MonkeyPatch, tmp_path: Path, native_type: int) -> None:+ """实际 ctypes 探测即使收到 ggml GPU 枚举,也必须采用原生集显或虚拟 GPU 分类。"""+ library_path = tmp_path / "lib" / "libggml.so"+ library_path.parent.mkdir()+ library_path.touch()+ library = SimpleNamespace(+ ggml_backend_load_all_from_path=Mock(),+ ggml_backend_dev_count=Mock(return_value=1),+ ggml_backend_dev_get=Mock(return_value=1),+ ggml_backend_dev_type=Mock(return_value=1),+ ggml_backend_dev_name=Mock(return_value=b"Vulkan0"),+ ggml_backend_dev_description=Mock(return_value=b"GPU"),+ ggml_backend_dev_backend_reg=Mock(return_value=1),+ ggml_backend_reg_name=Mock(return_value=b"Vulkan"),+ )+ physical = with_gpu_classification(vulkan.VulkanDevice(0x1002, 1, "GPU", 0), classify_vulkan_gpu(native_type))+ monkeypatch.setattr(llama_probe, "sys", SimpleNamespace(platform="linux"))+ monkeypatch.setattr(llama_probe.ct, "CDLL", lambda path: library)+ monkeypatch.setattr(llama_probe, "enumerate_vulkan_devices", lambda: (physical,))+ result = llama_probe._probe_library(tmp_path)+ assert result[0].kind == physical.kind and result[0].kind_source == "vulkan"+ assert not hasattr(result[0], "integrated")+ with pytest.raises(TypeError, match="integrated"):+ llama_probe.LlamaDevice("Vulkan0", "GPU", "vulkan", integrated=True)+++def test_apple_classification_preserves_unified_memory() -> None:+ """Apple Silicon 的集显分类保留统一内存事实,不改变 MPS 的可用性推荐。"""+ apple = classify_macos_gpu("Apple", "arm64", integrated=False)+ assert apple.kind == "integrated" and apple.unified_memory is True+ unknown = classify_macos_gpu("AMD", "x86_64", integrated=False)+ assert unknown.kind == "unknown" and unknown.unified_memory is None+++def test_shared_policy_imports_without_inference_dependencies() -> None:+ """共享事实和排序层的导入不得触发 Torch、ORT 或 llama 原生运行时。"""+ code = """+import importlib.abc+import sys+class BlockRuntime(importlib.abc.MetaPathFinder):+ def find_spec(self, fullname, path=None, target=None):+ # 阻止测试进程意外导入推理依赖。+ if fullname.split(".")[0] in {"torch", "onnxruntime", "mineru_llama_cpp"}:+ raise AssertionError(fullname)+sys.meta_path.insert(0, BlockRuntime())+from mineru.model.runtime.gpu import GPU_KIND_ORDER, GpuIdentity, match_gpu_identities+assert GPU_KIND_ORDER[0] == "discrete"+assert match_gpu_identities((GpuIdentity(1, 2),), (GpuIdentity(1, 2),)) == (0,)+"""+ subprocess.run([sys.executable, "-c", code], check=True, capture_output=True, text=True, timeout=15)diff --git a/tests/unittest/test_hardware_info.py b/tests/unittest/test_hardware_info.pyindex 8dac10b7..3ec91c5f 100644--- a/tests/unittest/test_hardware_info.py+++ b/tests/unittest/test_hardware_info.py@@ -139,7 +139,13 @@ def test_linux_cpu_quota_frequency_and_mixed_pci_inventory(tmp_path: Path, monkeassert 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}]}+ "vulkan",+ "ok",+ {+ "devices": [+ {"name": "Intel GPU", "vendor_id": 0x8086, "device_id": 0x7D51, "kind": "integrated", "kind_source": "vulkan"}+ ]+ },)hardware.merge_gpu_inventory(result.gpus, runtime)assert len(result.gpus) == 2 and result.gpus[0].kind == "integrated"diff --git a/tests/unittest/test_hardware_recommendation.py b/tests/unittest/test_hardware_recommendation.pyindex a6c33620..7aa4ca70 100644--- a/tests/unittest/test_hardware_recommendation.py+++ b/tests/unittest/test_hardware_recommendation.py@@ -142,7 +142,7 @@ def test_torch_llama_integrated_route_does_not_return_to_onnx(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)+ native = LlamaDevice("Vulkan0", "Arc", "vulkan", 0x8086, 0x7D51, 0, kind="integrated", kind_source="vulkan")monkeypatch.setattr(llama_device, "discover_llama_devices", lambda: (native,))bind = Mock(side_effect=lambda selection: selection)monkeypatch.setattr(llama_device, "_bind", bind)diff --git a/tests/unittest/test_llama_device_policy.py b/tests/unittest/test_llama_device_policy.pyindex d2b6a703..44789a4a 100644--- a/tests/unittest/test_llama_device_policy.py+++ b/tests/unittest/test_llama_device_policy.py@@ -13,6 +13,7 @@ from unittest.mock import Mockimport pytest+from mineru.model.runtime.gpu import classify_d3d12_gpu, with_gpu_classificationfrom mineru.model.runtime import llama_device as policyfrom mineru.model.runtime.llama_probe import LlamaDevice, PROBE_MARKERfrom mineru.model.runtime.onnx_device import OnnxSelection@@ -22,7 +23,16 @@ from mineru.model.runtime.windows_gpu import GpuAdapterdef gpu(vendor: int, chip: int, *, integrated: bool = True, index: int = 0) -> LlamaDevice:"""构造有稳定物理索引的原生设备。"""- return LlamaDevice(f"Vulkan{index}", f"GPU {vendor:04x}:{chip:04x}", "vulkan", integrated, vendor, chip, index)+ return LlamaDevice(+ f"Vulkan{index}",+ f"GPU {vendor:04x}:{chip:04x}",+ "vulkan",+ vendor,+ chip,+ index,+ kind="integrated" if integrated else "discrete",+ kind_source="vulkan",+ )@pytest.fixture(autouse=True)@@ -128,7 +138,11 @@ def test_integrated_only_reuses_platform_decision(monkeypatch.setattr(policy.sys, "platform", platform)device = gpu(0x8086, 0x7D51)inventory(monkeypatch, (device,))- adapter = WebGPUDevice(0x8086, 0x7D51) if backend == "webgpu" else GpuAdapter(0, "luid", "Arc", 0x8086, 0x7D51, True, 0)+ adapter = (+ WebGPUDevice(0x8086, 0x7D51)+ if backend == "webgpu"+ else with_gpu_classification(GpuAdapter(0, "luid", "Arc", 0x8086, 0x7D51, 0), classify_d3d12_gpu(True))+ )calibrate = onnx(monkeypatch, OnnxSelection(decision, adapter if decision == "gpu" else None, "rec_calibration", backend))result = policy.resolve_llama_device()assert result.device == decision@@ -154,6 +168,17 @@ def test_failed_or_mismatched_calibration_cannot_select_gpu(monkeypatch: pytest.assert policy.resolve_llama_device().reason == "onnx_gpu_identity_unconfirmed"+def test_unselected_backend_discrete_does_not_exempt_integrated(monkeypatch: pytest.MonkeyPatch) -> None:+ """其他后端的独显不在自动候选中时,实际选中的 Vulkan 集显仍需复用校准决策。"""+ unavailable = replace(gpu(0x10DE, 1, integrated=False), backend="other")+ integrated = gpu(0x1002, 0x150E, index=1)+ inventory(monkeypatch, (unavailable, integrated))+ calibrate = onnx(monkeypatch, OnnxSelection(reason="configured_cpu"))+ result = policy.resolve_llama_device()+ assert result.device == "cpu" and result.reason == "onnx_configured_cpu"+ calibrate.assert_called_once()++def test_no_gpu_and_explicit_cpu_do_not_calibrate(monkeypatch: pytest.MonkeyPatch) -> None:discover = inventory(monkeypatch, ())calibrate = onnx(monkeypatch, OnnxSelection())@@ -248,7 +273,8 @@ def test_probe_protocol_uses_native_inventory_without_parsing_log_names(monkeypa"name": "Vulkan0","description": "device","backend": "vulkan",- "integrated": True,+ "kind": "integrated",+ "kind_source": "vulkan","vendor_id": 0x8086,"device_id": 0x4680,"vulkan_index": 1,diff --git a/tests/unittest/test_llama_server_device_policy.py b/tests/unittest/test_llama_server_device_policy.pyindex 1af15188..bcded302 100644--- a/tests/unittest/test_llama_server_device_policy.py+++ b/tests/unittest/test_llama_server_device_policy.py@@ -19,7 +19,7 @@ def plan() -> LlamaSelection:"""显式选择原来的 Vulkan1 后,隔离原生设备索引会变为 Vulkan0。"""return LlamaSelection("gpu",- (LlamaDevice("Vulkan0", "Intel", "vulkan", True, 0x8086, 0x4680, 1),),+ (LlamaDevice("Vulkan0", "Intel", "vulkan", 0x8086, 0x4680, 1, kind="integrated", kind_source="vulkan"),),"explicit_gpu",((SERIALIZE_ENV, "1"), ("GGML_VK_VISIBLE_DEVICES", "1")),(("Vulkan1", "Vulkan0"),),@@ -166,7 +166,9 @@ def test_actual_device_policy_reaches_server_environment():monkeypatch.delenv(name, raising=False)monkeypatch.setattr(policy, "sys", SimpleNamespace(platform=platform))- device = LlamaDevice("Vulkan0", "Intel", "vulkan", chip != 0x56A0, 0x8086, chip, 0)+ device = LlamaDevice(+ "Vulkan0", "Intel", "vulkan", 0x8086, chip, 0, kind="integrated" if chip != 0x56A0 else "discrete", kind_source="vulkan"+ )monkeypatch.setattr(policy, "discover_llama_devices", Mock(return_value=(device,)))args = ["-ngl", "0", "--mmproj-device", "Vulkan0", "--mmproj-offload"] if projector_only else ["--device", "Vulkan0"]selected = server._device_policy(args)diff --git a/tests/unittest/test_onnx_calibration.py b/tests/unittest/test_onnx_calibration.pyindex 3d73bdef..b5d40390 100644--- a/tests/unittest/test_onnx_calibration.py+++ b/tests/unittest/test_onnx_calibration.py@@ -12,6 +12,7 @@ from unittest.mock import Mockimport numpy as npimport pytest+from mineru.model.runtime.gpu import classify_d3d12_gpu, with_gpu_classificationfrom mineru.model.runtime import onnx_calibration as calibrationfrom mineru.model.runtime.windows_gpu import GpuAdapterfrom mineru.model.runtime.webgpu import WEBGPU_PROVIDER, WebGPUDevice@@ -20,7 +21,7 @@ from scripts.benchmark_onnx_selection import derive_thresholddef gpu() -> GpuAdapter:- return GpuAdapter(2, "id", "test", 0x8086, 1, True, 0)+ return with_gpu_classification(GpuAdapter(2, "id", "test", 0x8086, 1, 0), classify_d3d12_gpu(True))@pytest.fixture(autouse=True)diff --git a/tests/unittest/test_onnx_device_selection.py b/tests/unittest/test_onnx_device_selection.pyindex 56d676fd..8cd2c45e 100644--- a/tests/unittest/test_onnx_device_selection.py+++ b/tests/unittest/test_onnx_device_selection.py@@ -3,6 +3,7 @@from __future__ import annotationsimport importlib+from dataclasses import replacefrom pathlib import Pathfrom types import SimpleNamespacefrom unittest.mock import Mock@@ -11,6 +12,7 @@ import pytestimport yamlfrom pydantic import ValidationError+from mineru.model.runtime.gpu import classify_d3d12_gpu, classify_vulkan_gpu, with_gpu_classificationfrom mineru.config import Configfrom mineru.model.runtime import onnx_device as policyfrom mineru.model.runtime.windows_gpu import GpuAdapter, preferred_gpu@@ -20,7 +22,7 @@ settings = importlib.import_module("mineru.config")def adapter(*, index: int = 0, uma: bool | None = True, vendor: int = 0x8086, rank: int = 0) -> GpuAdapter:- return GpuAdapter(index, f"luid-{index}", "test GPU", vendor, 1, uma, rank)+ return with_gpu_classification(GpuAdapter(index, f"luid-{index}", "test GPU", vendor, 1, rank), classify_d3d12_gpu(uma))@pytest.fixture@@ -296,16 +298,28 @@ def test_unet_first_model_shares_selection_and_persistence(@pytest.fixturedef linux_config(config_file: Path, monkeypatch: pytest.MonkeyPatch) -> Path:+ """为 Linux 选型提供可见集显,避免读取测试宿主的 Vulkan 设备。"""+ from mineru.model.runtime import vulkan, webgpu+monkeypatch.setattr(policy, "sys", SimpleNamespace(platform="linux"))+ monkeypatch.setattr(webgpu, "sys", SimpleNamespace(platform="linux"))+ monkeypatch.setattr(webgpu, "_runtime_pid", None)+ monkeypatch.setattr(webgpu, "_runtime_device", None)+ monkeypatch.setattr(+ vulkan,+ "enumerate_vulkan_devices",+ lambda: (with_gpu_classification(vulkan.VulkanDevice(0x1002, 1, "integrated"), classify_vulkan_gpu(1)),),+ )monkeypatch.setattr(policy, "discover_webgpu_devices", Mock(return_value=(WebGPUDevice(0x1002, 1),)))return config_file@pytest.mark.parametrize(("gpu_time", "expected"), [(1.5, "gpu"), (1.6, "gpu"), (1.601, "cpu")])@pytest.mark.parametrize("hardware", ["integrated", "discrete"])-def test_linux_calibrates_both_gpu_types_and_uses_own_threshold(+def test_linux_calibration_uses_vulkan_type_instead_of_ep_metadata(linux_config: Path, monkeypatch: pytest.MonkeyPatch, gpu_time: float, expected: str, hardware: str) -> None:+ """EP 元数据即使声称独显,Vulkan 确认的集显仍按 0.8 阈值校准。"""from mineru.model.runtime import onnx_calibrationdescriptor = WebGPUDevice(0x1002, 1, (("type", hardware),))@@ -315,10 +329,122 @@ def test_linux_calibrates_both_gpu_types_and_uses_own_threshold(selection = policy.resolve_onnx_device()assert selection.device == expected and selection.backend == "webgpu"assert policy.resolve_onnx_device() is selection- measure.assert_called_once_with("rec.onnx", descriptor, intra_op_num_threads=0, inter_op_num_threads=0, threshold=0.8)+ measure.assert_called_once_with(+ "rec.onnx",+ with_gpu_classification(descriptor, classify_vulkan_gpu(1)),+ intra_op_num_threads=0,+ inter_op_num_threads=0,+ threshold=0.8,+ )assert yaml.safe_load(linux_config.read_text())["model"] == {"onnx_device": expected, "source": "local"}[email protected]("identity", [(0x10DE, 0x2489), (0x1002, 0x73DF), (0x8086, 0x56A0)])[email protected]("source", ["file", "env"])+def test_linux_discrete_skips_calibration_and_saves_after_actual_session(+ linux_config: Path, monkeypatch: pytest.MonkeyPatch, identity: tuple[int, int], source: str+) -> None:+ """三家独显均免下载和校准,只在 WebGPU 会话确认成功后按配置来源保存。"""+ from mineru.model import registry+ from mineru.model.runtime import onnx, onnx_calibration, vulkan, webgpu++ descriptor = WebGPUDevice(*identity)+ monkeypatch.setattr(policy, "discover_webgpu_devices", lambda: (descriptor,))+ monkeypatch.setattr(+ vulkan,+ "enumerate_vulkan_devices",+ lambda: (with_gpu_classification(vulkan.VulkanDevice(*identity, "GPU"), classify_vulkan_gpu(2)),),+ )+ monkeypatch.setattr(settings, "get_config_source", lambda key: source)+ monkeypatch.setitem(policy.ONNX_GPU_TIME_RATIO_THRESHOLDS, "webgpu", None)+ download = Mock(side_effect=AssertionError("discrete GPU must not prepare calibration weights"))+ monkeypatch.setattr(registry, "MINERU_4_MODELS_ONNX", SimpleNamespace(ocr_rec=SimpleNamespace(ensure=download)))+ selected = policy.resolve_onnx_device(allow_download=False)+ assert selected == policy.OnnxSelection(+ "gpu",+ with_gpu_classification(replace(descriptor, vulkan_device=identity), classify_vulkan_gpu(2)),+ "discrete_gpu",+ "webgpu",+ )+ assert yaml.safe_load(linux_config.read_text(encoding="utf-8"))["model"]["onnx_device"] == "auto"++ native = SimpleNamespace(get_providers=lambda: [webgpu.WEBGPU_PROVIDER], disable_fallback=Mock())+ monkeypatch.setattr(onnx.ort, "InferenceSession", Mock(return_value=native))+ monkeypatch.setattr(onnx, "attach_webgpu_provider", Mock())+ session = onnx.ort_session("layout.onnx", model_kind="layout", selection=selected)+ assert session.get_providers() == [webgpu.WEBGPU_PROVIDER]+ native.disable_fallback.assert_called_once()+ assert yaml.safe_load(linux_config.read_text(encoding="utf-8"))["model"]["onnx_device"] == (+ "gpu" if source == "file" else "auto"+ )+ assert not Path(f"{linux_config}.onnx-calibration.json").exists()+ policy._selections.clear()+ assert policy.resolve_onnx_device().reason == ("configured_gpu" if source == "file" else "discrete_gpu")+ download.assert_not_called()+ onnx_calibration.run_calibration.assert_not_called()++[email protected]("failure", ["binding", "initialization", "silent_cpu"])+def test_linux_discrete_session_failure_preserves_auto(+ linux_config: Path, monkeypatch: pytest.MonkeyPatch, failure: str+) -> None:+ """免校准独显发生绑定失败、初始化错误或静默 CPU 回退时,不保存 GPU 偏好。"""+ from mineru.model.runtime import onnx, onnx_calibration, vulkan++ descriptor = WebGPUDevice(0x10DE, 0x2489)+ integrated = with_gpu_classification(vulkan.VulkanDevice(0x1002, 1, "integrated"), classify_vulkan_gpu(1))+ discrete = with_gpu_classification(vulkan.VulkanDevice(0x10DE, 0x2489, "discrete"), classify_vulkan_gpu(2))+ monkeypatch.setattr(policy, "discover_webgpu_devices", lambda: (descriptor,))+ monkeypatch.setattr(+ vulkan, "enumerate_vulkan_devices", lambda: (integrated, discrete) if failure == "binding" else (discrete,)+ )+ selected = policy.resolve_onnx_device()+ assert selected.reason == "discrete_gpu"+ cpu = SimpleNamespace(get_providers=lambda: ["CPUExecutionProvider"])+ factory = Mock(side_effect=[RuntimeError("GPU failed"), cpu] if failure == "initialization" else None, return_value=cpu)+ monkeypatch.setattr(onnx.ort, "InferenceSession", factory)+ monkeypatch.setattr(onnx, "attach_webgpu_provider", Mock())+ assert onnx.ort_session("layout.onnx", model_kind="layout", selection=selected) is cpu+ assert factory.call_count == (1 if failure == "binding" else 2)+ assert yaml.safe_load(linux_config.read_text(encoding="utf-8"))["model"]["onnx_device"] == "auto"+ onnx_calibration.run_calibration.assert_not_called()++[email protected]("state", ["unavailable", "duplicate", "virtual"])+def test_linux_unconfirmed_discrete_still_calibrates(linux_config: Path, monkeypatch: pytest.MonkeyPatch, state: str) -> None:+ """类型未知、同型号多卡及虚拟 GPU 均不能获得独显免校准资格。"""+ from mineru.model.runtime import onnx_calibration, vulkan++ descriptor = WebGPUDevice(0x10DE, 0x2489, (("type", "discrete"),))+ physical = with_gpu_classification(+ vulkan.VulkanDevice(0x10DE, 0x2489, "GPU"), classify_vulkan_gpu(3 if state == "virtual" else 2)+ )+ monkeypatch.setattr(policy, "discover_webgpu_devices", lambda: (descriptor,))+ monkeypatch.setattr(+ vulkan,+ "enumerate_vulkan_devices",+ Mock(+ side_effect=OSError("query failed") if state == "unavailable" else None,+ return_value=(physical, physical) if state == "duplicate" else (physical,),+ ),+ )+ assert policy.resolve_onnx_device().reason == "rec_calibration"+ onnx_calibration.run_calibration.assert_called_once()+++def test_linux_hidden_discrete_does_not_exempt_visible_integrated(linux_config: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ """ORT 中仍可见但被 ICD 隐藏的独显,不能让实际可见的集显免校准。"""+ from mineru.model.runtime import onnx_calibration++ integrated = WebGPUDevice(0x1002, 1)+ monkeypatch.setattr(policy, "discover_webgpu_devices", lambda: (WebGPUDevice(0x10DE, 0x2489), integrated))+ selected = policy.resolve_onnx_device()+ assert selected.reason == "rec_calibration" and selected.adapter == with_gpu_classification(+ integrated, classify_vulkan_gpu(1)+ )+ onnx_calibration.run_calibration.assert_called_once()++@pytest.mark.parametrize("requested", ["cpu", "gpu"])def test_linux_explicit_modes_do_not_calibrate(linux_config: Path, monkeypatch: pytest.MonkeyPatch, requested: str) -> None:from mineru.model.runtime import onnx_calibration@@ -380,9 +506,15 @@ def test_linux_waiting_process_rechecks_saved_choice(linux_config: Path, monkeyp@pytest.mark.parametrize("platform", ["linux", "win32"])def test_unstable_calibration_keeps_auto(config_file: Path, monkeypatch: pytest.MonkeyPatch, platform: str) -> None:- from mineru.model.runtime import onnx_calibration+ from mineru.model.runtime import onnx_calibration, vulkan, webgpumonkeypatch.setattr(policy, "sys", SimpleNamespace(platform=platform))+ monkeypatch.setattr(webgpu, "sys", SimpleNamespace(platform=platform))+ monkeypatch.setattr(+ vulkan,+ "enumerate_vulkan_devices",+ lambda: (with_gpu_classification(vulkan.VulkanDevice(0x8086, 0x7D51, "integrated"), classify_vulkan_gpu(1)),),+ )monkeypatch.setattr(policy, "discover_webgpu_devices", lambda: (WebGPUDevice(0x8086, 0x7D51),))measure = Mock(return_value={"decision_valid": False, "cpu_elapsed": 2.0, "gpu_elapsed": 1.0})monkeypatch.setattr(onnx_calibration, "run_calibration", measure)diff --git a/tests/unittest/test_table_onnx_runtime.py b/tests/unittest/test_table_onnx_runtime.pyindex f403639f..a7f25677 100644--- a/tests/unittest/test_table_onnx_runtime.py+++ b/tests/unittest/test_table_onnx_runtime.py@@ -6,6 +6,7 @@ from pathlib import Pathimport pytest+from mineru.model.runtime.gpu import classify_d3d12_gpu, with_gpu_classificationfrom mineru.model.runtime import onnx@@ -227,7 +228,11 @@ def test_onnx_unet_preserves_options_profile_and_dml_lock(monkeypatch: pytest.Momonkeypatch.setenv("MINERU_TABLE_DEVICE", "cpu")monkeypatch.setenv("MINERU_ONNX_PROFILE_DIR", str(tmp_path / "profiles"))monkeypatch.setenv("MINERU_INTRA_OP_NUM_THREADS", "8")- select = Mock(return_value=OnnxSelection("gpu", GpuAdapter(7, "id", "intel", 0x8086, 1, True, 0), backend="dml"))+ select = Mock(+ return_value=OnnxSelection(+ "gpu", with_gpu_classification(GpuAdapter(7, "id", "intel", 0x8086, 1, 0), classify_d3d12_gpu(True)), backend="dml"+ )+ )monkeypatch.setattr(onnx, "resolve_onnx_device", select)monkeypatch.setattr(onnx.ort, "get_available_providers", lambda: ["DmlExecutionProvider", "CPUExecutionProvider"])native = SimpleNamespace(get_providers=lambda: ["DmlExecutionProvider", "CPUExecutionProvider"], disable_fallback=Mock())diff --git a/tests/unittest/test_tier_recommendation.py b/tests/unittest/test_tier_recommendation.pyindex 82da1559..7a86c74d 100644--- a/tests/unittest/test_tier_recommendation.py+++ b/tests/unittest/test_tier_recommendation.py@@ -12,6 +12,7 @@ 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 recommendationfrom mineru.model.runtime.llama_probe import LlamaDevice@@ -74,7 +75,7 @@ def evidence_path(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:def _adapter() -> GpuAdapter:"""构造具有稳定物理身份的集显。"""- return GpuAdapter(0, "physical-id", "integrated", 0x8086, 0x7D51, True, 0)+ return with_gpu_classification(GpuAdapter(0, "physical-id", "integrated", 0x8086, 0x7D51, 0), classify_d3d12_gpu(True))def _measurement(**overrides: Any) -> dict[str, Any]:@@ -174,7 +175,15 @@ def test_gpu_discovery_uses_only_existing_evidence(monkeypatch.setattr(recommendation, "sys", SimpleNamespace(platform=platform))monkeypatch.setattr(recommendation, "effective_cpu_count", lambda: 4)monkeypatch.setattr(onnx_device, "resolve_onnx_device", Mock(side_effect=AssertionError("must not calibrate")))- descriptor = LlamaDevice("Vulkan0", "test", "vulkan", kind != "discrete", 0x8086, 0x7D51)+ descriptor = LlamaDevice(+ "Vulkan0",+ "test",+ "vulkan",+ 0x8086,+ 0x7D51,+ kind="integrated" if kind != "discrete" else "discrete",+ kind_source="vulkan",+ )if kind == "mismatch":descriptor = replace(descriptor, device_id=1)inventory = () if kind == "hidden" else (descriptor,)@@ -213,8 +222,8 @@ def startup_calibration("""模拟双平台物理设备和测速 worker,保留真实选型、配置落盘及证据读取链路。"""import onnxruntime- from mineru.model import registry- from mineru.model.runtime import llama_device, onnx_calibration, onnx_device, webgpu, windows_gpu+ from mineru.model.download import ModelPath+ from mineru.model.runtime import llama_device, onnx_calibration, onnx_device, vulkan, webgpu, windows_gpusettings = importlib.import_module("mineru.config")config_file = evidence_path.with_name("settings.yaml")@@ -223,8 +232,13 @@ def startup_calibration(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):+ for module in (recommendation, onnx_device, webgpu):monkeypatch.setattr(module, "sys", SimpleNamespace(platform=request.param))+ monkeypatch.setattr(+ vulkan,+ "enumerate_vulkan_devices",+ lambda: (with_gpu_classification(vulkan.VulkanDevice(0x8086, 0x7D51, "test"), classify_vulkan_gpu(1)),),+ )monkeypatch.setattr(recommendation, "effective_cpu_count", lambda: 8)monkeypatch.setattr(onnx_device, "_selections", {})monkeypatch.setattr(onnxruntime, "get_available_providers", lambda: ["DmlExecutionProvider", "CPUExecutionProvider"])@@ -235,11 +249,10 @@ def startup_calibration(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")))+ lambda: (LlamaDevice("Vulkan0", "test", "vulkan", 0x8086, 0x7D51, kind="integrated", kind_source="vulkan"),),)+ # 只替换权重准备,避免服务惰性导入的模块永久持有伪造的仓库对象。+ monkeypatch.setattr(ModelPath, "ensure", Mock(return_value=Path("rec.onnx")))measurement = Mock(return_value=_measurement())def run_calibration(@@ -316,18 +329,31 @@ 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+ from mineru.model.runtime import llama_device, onnx_device, vulkanmonkeypatch.setattr(recommendation, "effective_cpu_count", lambda: 2)monkeypatch.setattr(llama_device,"discover_llama_devices",- lambda: (LlamaDevice("Vulkan0", "test", "vulkan", False, 0x8086, 0x7D51),),+ lambda: (LlamaDevice("Vulkan0", "test", "vulkan", 0x8086, 0x7D51, kind="discrete", kind_source="vulkan"),),)- monkeypatch.setattr(onnx_device, "discover_gpus", lambda **kwargs: (replace(_adapter(), uma=False),))- assert frozenset(recommendation.recommend_tiers().pdf_image_tiers) == frozenset(TIERS)+ monkeypatch.setattr(+ onnx_device, "discover_gpus", lambda **kwargs: (with_gpu_classification(_adapter(), classify_d3d12_gpu(False)),)+ )+ monkeypatch.setattr(+ vulkan,+ "enumerate_vulkan_devices",+ lambda: (with_gpu_classification(vulkan.VulkanDevice(0x8086, 0x7D51, "test"), classify_vulkan_gpu(2)),),+ )+ report = recommendation.recommend_tiers()+ assert frozenset(report.pdf_image_tiers) == frozenset(TIERS)+ assert report.calibration.status == "skipped" and report.calibration.reason == "discrete_gpu"+ assert report.default_request_tier == "standard"assert onnx_device._selections- assert startup_calibration[1].call_count == (0 if onnx_device.sys.platform == "win32" else 1)+ startup_calibration[1].assert_not_called()+ config_file = startup_calibration[0]+ assert yaml.safe_load(config_file.read_text(encoding="utf-8"))["model"]["onnx_device"] == "auto"+ assert not cache.calibration_record_path().exists()@pytest.mark.parametrize("tier", TIERS)@@ -377,3 +403,22 @@ def test_failed_recalibration_revokes_previous_fast_evidence(startup_calibrationassert frozenset(recommendation.recommend_tiers().pdf_image_tiers) == frozenset(TIERS[:-1])startup_calibration[1].assert_called_once()assert not cache.calibration_record_path().exists()++[email protected]("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"]+ assert set(identity) == (+ {"vendor_id", "device_id", "name", "luid", "uma"}+ if backend == "dml"+ else {"vendor_id", "device_id", "metadata", "vulkan_device"}+ )+ assert cache.calibrated_gpu_is_faster(replace(adapter, kind="unknown", kind_source="new_probe"), 0.8)+ assert not cache.calibrated_gpu_is_faster(replace(adapter, device_id=1), 0.8)+ if backend == "webgpu":+ assert not cache.calibrated_gpu_is_faster(replace(adapter, vulkan_device=(0x8086, 0x7D51)), 0.8)diff --git a/tests/unittest/test_webgpu_architecture.py b/tests/unittest/test_webgpu_architecture.pyindex 34833ad5..3ed5349c 100644--- a/tests/unittest/test_webgpu_architecture.py+++ b/tests/unittest/test_webgpu_architecture.py@@ -3,7 +3,7 @@from __future__ import annotationsimport ctypes as ct-from dataclasses import asdict+from dataclasses import asdict, replaceimport importlibimport jsonimport os@@ -13,11 +13,13 @@ from unittest.mock import Mockimport pytest+from mineru.model.runtime.gpu import classify_d3d12_gpu, classify_vulkan_gpu, with_gpu_classificationfrom mineru.model.runtime import intel_gpu, onnx, onnx_device, vulkan, webgpu@pytest.fixture(autouse=True)def fresh_runtime(monkeypatch: pytest.MonkeyPatch) -> None:+ """隔离运行时和宿主 Vulkan 驱动,让各用例显式声明可见设备。"""monkeypatch.setattr(webgpu, "_runtime_pid", None)monkeypatch.setattr(webgpu, "_runtime_device", None)monkeypatch.setattr(webgpu, "sys", SimpleNamespace(platform="linux"))@@ -83,10 +85,15 @@ def test_unknown_intel_is_not_guessed_from_numeric_age(device_id: int) -> None:@pytest.mark.parametrize("vendor", [0x1002, 0x10DE])def test_amd_nvidia_ids_never_use_intel_mapping(vendor: int, monkeypatch: pytest.MonkeyPatch) -> None:+ """AMD/NVIDIA 即使使用相同设备号,也按 Vulkan 类型而非 Intel 架构表分类。"""descriptor = webgpu.WebGPUDevice(vendor, 0x4680)- monkeypatch.setattr(vulkan, "enumerate_vulkan_devices", Mock(side_effect=AssertionError("unnecessary Vulkan probe")))+ monkeypatch.setattr(+ vulkan,+ "enumerate_vulkan_devices",+ lambda: (with_gpu_classification(vulkan.VulkanDevice(vendor, 0x4680, "GPU"), classify_vulkan_gpu(1)),),+ )assert intel_gpu.supports_webgpu_architecture(vendor, descriptor.device_id)- assert webgpu.select_webgpu_device((descriptor,)) is descriptor+ assert webgpu.select_webgpu_device((descriptor,)) == with_gpu_classification(descriptor, classify_vulkan_gpu(1))@pytest.mark.parametrize("requested", ["auto", "gpu"])@@ -131,22 +138,30 @@ def test_mixed_host_selects_and_binds_eligible_gpu(vulkan,"enumerate_vulkan_devices",lambda: (- vulkan.VulkanDevice(old.vendor_id, old.device_id, 1, "old"),- vulkan.VulkanDevice(*eligible, 2, "discrete"),+ with_gpu_classification(vulkan.VulkanDevice(old.vendor_id, old.device_id, "old"), classify_vulkan_gpu(1)),+ with_gpu_classification(vulkan.VulkanDevice(*eligible, "discrete"), classify_vulkan_gpu(2)),),)selected = webgpu.select_webgpu_device(devices)- assert selected == webgpu.WebGPUDevice(*eligible, vulkan_device=eligible)+ assert selected == with_gpu_classification(webgpu.WebGPUDevice(*eligible, vulkan_device=eligible), classify_vulkan_gpu(2))-def test_icd_exclusion_cannot_be_bypassed_by_ort_inventory(monkeypatch: pytest.MonkeyPatch) -> None:[email protected]("include_old", [False, True])+def test_icd_exclusion_cannot_be_bypassed_by_ort_inventory(monkeypatch: pytest.MonkeyPatch, include_old: bool) -> None:+ """即使 ORT 只报告独显,也不能绕过 Vulkan ICD 对该设备的隐藏。"""old = webgpu.WebGPUDevice(0x8086, 0x4680)good = webgpu.WebGPUDevice(0x10DE, 0x2489)- monkeypatch.setattr(vulkan, "enumerate_vulkan_devices", lambda: (vulkan.VulkanDevice(0x8086, 0x4680, 1, "Intel-only ICD"),))- assert webgpu.select_webgpu_device((good, old)) is None+ monkeypatch.setattr(+ vulkan,+ "enumerate_vulkan_devices",+ lambda: (with_gpu_classification(vulkan.VulkanDevice(0x8086, 0x4680, "Intel-only ICD"), classify_vulkan_gpu(1)),),+ )+ assert webgpu.select_webgpu_device((good, old) if include_old else (good,)) is None-def test_multiple_good_candidates_prefer_discrete_gpu(monkeypatch: pytest.MonkeyPatch) -> None:[email protected]("include_old", [False, True])+def test_multiple_good_candidates_prefer_discrete_gpu(monkeypatch: pytest.MonkeyPatch, include_old: bool) -> None:+ """全部架构受支持的多卡机器也应独显优先,不依赖 ORT 的枚举顺序。"""old, integrated, discrete = (webgpu.WebGPUDevice(0x8086, 0x4680),webgpu.WebGPUDevice(0x1002, 0x150E),@@ -156,13 +171,35 @@ def test_multiple_good_candidates_prefer_discrete_gpu(monkeypatch: pytest.Monkeyvulkan,"enumerate_vulkan_devices",lambda: (- vulkan.VulkanDevice(0x1002, 0x150E, 1, "AMD integrated"),- vulkan.VulkanDevice(0x10DE, 0x2489, 2, "NVIDIA"),- vulkan.VulkanDevice(0x8086, 0x4680, 1, "old Intel"),+ with_gpu_classification(vulkan.VulkanDevice(0x1002, 0x150E, "AMD integrated"), classify_vulkan_gpu(1)),+ with_gpu_classification(vulkan.VulkanDevice(0x10DE, 0x2489, "NVIDIA"), classify_vulkan_gpu(2)),+ with_gpu_classification(vulkan.VulkanDevice(0x8086, 0x4680, "old Intel"), classify_vulkan_gpu(1)),),)- selected = webgpu.select_webgpu_device((old, integrated, discrete))- assert selected is not None and selected.vulkan_device == (0x10DE, 0x2489)+ selected = webgpu.select_webgpu_device((old, integrated, discrete) if include_old else (integrated, discrete))+ assert selected == with_gpu_classification(replace(discrete, vulkan_device=(0x10DE, 0x2489)), classify_vulkan_gpu(2))++[email protected]("duplicate", ["vulkan", "ort"])+def test_ambiguous_device_identity_does_not_confirm_discrete(monkeypatch: pytest.MonkeyPatch, duplicate: str) -> None:+ """同型号多卡或重复 EP 注册无法唯一对应时,不授予独显免校准资格。"""+ descriptor = webgpu.WebGPUDevice(0x10DE, 0x2489)+ physical = with_gpu_classification(vulkan.VulkanDevice(0x10DE, 0x2489, "GPU"), classify_vulkan_gpu(2))+ monkeypatch.setattr(+ vulkan, "enumerate_vulkan_devices", lambda: (physical, physical) if duplicate == "vulkan" else (physical,)+ )+ selected = webgpu.select_webgpu_device((descriptor, descriptor) if duplicate == "ort" else (descriptor,))+ assert selected is not None and selected.kind == "unknown"++[email protected]("failure", [OSError("loader unavailable"), RuntimeError("enumeration failed")])+def test_unknown_vulkan_type_keeps_calibration_eligible(monkeypatch: pytest.MonkeyPatch, failure: Exception) -> None:+ """没有受限架构时,原生类型查询失败只撤销免校准资格,不猜测独显。"""+ descriptor = webgpu.WebGPUDevice(0x10DE, 0x2489, (("type", "discrete"),))+ monkeypatch.setattr(vulkan, "enumerate_vulkan_devices", Mock(side_effect=failure))+ assert webgpu.select_webgpu_device((descriptor,)) == descriptor+ with pytest.raises(type(failure)):+ webgpu.select_webgpu_device((descriptor, webgpu.WebGPUDevice(0x8086, 0x4680)))def test_windows_dml_does_not_apply_linux_policy(monkeypatch: pytest.MonkeyPatch) -> None:@@ -172,7 +209,11 @@ def test_windows_dml_does_not_apply_linux_policy(monkeypatch: pytest.MonkeyPatchmonkeypatch.setattr(onnx_device, "sys", SimpleNamespace(platform="win32"))monkeypatch.setattr(onnx.ort, "get_available_providers", lambda: ["DmlExecutionProvider"])- monkeypatch.setattr(onnx_device, "discover_gpus", lambda **_: (GpuAdapter(0, "id", "UHD770", 0x8086, 0x4680, True, 0),))+ monkeypatch.setattr(+ onnx_device,+ "discover_gpus",+ lambda **_: (with_gpu_classification(GpuAdapter(0, "id", "UHD770", 0x8086, 0x4680, 0), classify_d3d12_gpu(True)),),+ )monkeypatch.setattr(onnx_device, "select_webgpu_device", Mock(side_effect=AssertionError("Linux policy")))monkeypatch.setattr(registry, "MINERU_4_MODELS_ONNX", SimpleNamespace(ocr_rec=SimpleNamespace(ensure=lambda: "rec.onnx")))measure = Mock(return_value={"decision_valid": True, "cpu_elapsed": 1, "gpu_elapsed": 0.5})@@ -183,24 +224,54 @@ def test_windows_dml_does_not_apply_linux_policy(monkeypatch: pytest.MonkeyPatch@pytest.mark.parametrize("device_id", [0x7D51, 0x7D55, 0x56A0, 0x64A0, 0xE20B, 0xB080])-def test_modern_intel_auto_still_runs_adaptive_calibration(monkeypatch: pytest.MonkeyPatch, device_id: int) -> None:[email protected]("device_type", [1, 2, None])+def test_modern_intel_auto_calibrates_according_to_vulkan_type(+ monkeypatch: pytest.MonkeyPatch, device_id: int, device_type: int | None+) -> None:+ """架构白名单只决定兼容性,是否免校准由实际 Vulkan 类型独立决定。"""from mineru.model.runtime import onnx_calibrationfrom mineru.model import registrydescriptor = webgpu.WebGPUDevice(0x8086, device_id)monkeypatch.setattr(onnx_device, "sys", SimpleNamespace(platform="linux"))monkeypatch.setattr(onnx_device, "discover_webgpu_devices", lambda: (descriptor,))+ monkeypatch.setattr(+ vulkan,+ "enumerate_vulkan_devices",+ Mock(+ return_value=(+ with_gpu_classification(+ vulkan.VulkanDevice(0x8086, device_id, "Intel GPU"), classify_vulkan_gpu(device_type or 1)+ ),+ ),+ side_effect=OSError("type unavailable") if device_type is None else None,+ ),+ )monkeypatch.setattr(registry, "MINERU_4_MODELS_ONNX", SimpleNamespace(ocr_rec=SimpleNamespace(ensure=lambda: "rec.onnx")))measure = Mock(return_value={"decision_valid": True, "cpu_elapsed": 1, "gpu_elapsed": 0.5})monkeypatch.setattr(onnx_calibration, "run_calibration", measure)selected, completed = onnx_device._select("auto", 4, 1)- assert selected.device == "gpu" and selected.reason == "rec_calibration" and completed- measure.assert_called_once_with("rec.onnx", descriptor, intra_op_num_threads=4, inter_op_num_threads=1, threshold=0.8)+ assert selected.device == "gpu"+ if device_type == 2:+ assert selected.reason == "discrete_gpu" and not completed+ measure.assert_not_called()+ else:+ assert selected.reason == "rec_calibration" and completed+ measure.assert_called_once_with(+ "rec.onnx",+ with_gpu_classification(descriptor, classify_vulkan_gpu(device_type)),+ intra_op_num_threads=4,+ inter_op_num_threads=1,+ threshold=0.8,+ )@pytest.mark.parametrize("fail", [False, True])def test_loader_restriction_is_verified_and_restores_environment(monkeypatch: pytest.MonkeyPatch, fail: bool) -> None:- old, good = vulkan.VulkanDevice(0x8086, 0x4680, 1, "Intel"), vulkan.VulkanDevice(0x10DE, 0x2489, 2, "NVIDIA")+ old, good = (+ with_gpu_classification(vulkan.VulkanDevice(0x8086, 0x4680, "Intel"), classify_vulkan_gpu(1)),+ with_gpu_classification(vulkan.VulkanDevice(0x10DE, 0x2489, "NVIDIA"), classify_vulkan_gpu(2)),+ )monkeypatch.setenv("VK_LOADER_VENDOR_ID_FILTER", "0x8086,0x10de")monkeypatch.setenv("VK_LOADER_DEVICE_ID_FILTER", "0:65535")snapshot = dict(os.environ)@@ -220,7 +291,10 @@ def test_loader_restriction_is_verified_and_restores_environment(monkeypatch: pydef test_older_loader_uses_verified_mesa_fallback(monkeypatch: pytest.MonkeyPatch) -> None:- old, good = vulkan.VulkanDevice(0x8086, 0x4680, 1, "Intel"), vulkan.VulkanDevice(0x8086, 0x56A0, 2, "Arc")+ old, good = (+ with_gpu_classification(vulkan.VulkanDevice(0x8086, 0x4680, "Intel"), classify_vulkan_gpu(1)),+ with_gpu_classification(vulkan.VulkanDevice(0x8086, 0x56A0, "Arc"), classify_vulkan_gpu(2)),+ )snapshot = dict(os.environ)def visible() -> tuple[vulkan.VulkanDevice, ...]:@@ -233,7 +307,10 @@ def test_older_loader_uses_verified_mesa_fallback(monkeypatch: pytest.MonkeyPatcdef test_ignored_filters_fail_before_creating_a_gpu_session(monkeypatch: pytest.MonkeyPatch) -> None:- old, good = vulkan.VulkanDevice(0x8086, 0x4680, 1, "Intel"), vulkan.VulkanDevice(0x10DE, 0x2489, 2, "NVIDIA")+ old, good = (+ with_gpu_classification(vulkan.VulkanDevice(0x8086, 0x4680, "Intel"), classify_vulkan_gpu(1)),+ with_gpu_classification(vulkan.VulkanDevice(0x10DE, 0x2489, "NVIDIA"), classify_vulkan_gpu(2)),+ )monkeypatch.setattr(vulkan, "enumerate_vulkan_devices", lambda: (old, good))factory = Mock(side_effect=AssertionError("unsafe native session"))monkeypatch.setattr(onnx.ort, "InferenceSession", factory)@@ -252,7 +329,7 @@ def test_forbidden_intel_cannot_bypass_policy_through_low_level_factory(monkeypadef test_scope_covers_provider_attachment_and_native_session_initialization(monkeypatch: pytest.MonkeyPatch) -> None:- good = vulkan.VulkanDevice(0x10DE, 0x2489, 2, "NVIDIA")+ good = with_gpu_classification(vulkan.VulkanDevice(0x10DE, 0x2489, "NVIDIA"), classify_vulkan_gpu(2))monkeypatch.setattr(vulkan, "enumerate_vulkan_devices", lambda: (good,))snapshot = dict(os.environ)@@ -277,7 +354,9 @@ def test_bound_descriptor_roundtrips_through_worker_json(monkeypatch: pytest.Monimport iofrom mineru.model.runtime import onnx_calibration- descriptor = webgpu.WebGPUDevice(0x10DE, 0x2489, (("pci_bus_id", "0000:01:00.0"),), (0x10DE, 0x2489))+ descriptor = with_gpu_classification(+ webgpu.WebGPUDevice(0x10DE, 0x2489, (("pci_bus_id", "0000:01:00.0"),), (0x10DE, 0x2489)), classify_vulkan_gpu(2)+ )stream = io.StringIO(json.dumps({"backend": "webgpu", "adapter": asdict(descriptor), "model_path": "rec.onnx"}))monkeypatch.setattr(onnx_calibration.sys, "stdin", stream)measure = Mock(return_value={"ok": True})@@ -288,9 +367,12 @@ def test_bound_descriptor_roundtrips_through_worker_json(monkeypatch: pytest.Mon@pytest.mark.parametrize("error", [False, True])[email protected]("native_type", [0, 1, 2, 3])def test_vulkan_query_reads_pci_identity_without_creating_logical_device_and_cleans_up(- monkeypatch: pytest.MonkeyPatch, error: bool+ monkeypatch: pytest.MonkeyPatch, error: bool, native_type: int) -> None:+ """原生类型在适配边界统一转换,未知硬件仍保留,而软件 CPU 不进入 GPU 库存。"""+def create(info: object, allocator: object, instance: object) -> int:instance._obj.value = 123return 0@@ -306,7 +388,7 @@ def test_vulkan_query_reads_pci_identity_without_creating_logical_device_and_cledef properties(handle: object, storage: object) -> None:p = storage._obj.prefixp.vendorID, p.deviceID, p.deviceType, p.deviceName = (- (0x10DE, 0x2489, 2, b"NVIDIA") if handle == 100 else (0x10005, 0, 4, b"llvmpipe")+ (0x10DE, 0x2489, native_type, b"NVIDIA") if handle == 100 else (0x10005, 0, 4, b"llvmpipe"))lib = SimpleNamespace(@@ -320,6 +402,8 @@ def test_vulkan_query_reads_pci_identity_without_creating_logical_device_and_clewith pytest.raises(RuntimeError, match="count devices"):vulkan.enumerate_vulkan_devices()else:- assert vulkan.enumerate_vulkan_devices() == (vulkan.VulkanDevice(0x10DE, 0x2489, 2, "NVIDIA", 0),)+ assert vulkan.enumerate_vulkan_devices() == (+ with_gpu_classification(vulkan.VulkanDevice(0x10DE, 0x2489, "NVIDIA", 0), classify_vulkan_gpu(native_type)),+ )lib.vkDestroyInstance.assert_called_once()assert ct.sizeof(vulkan._PropertiesStorage) >= 824diff --git a/tests/unittest/test_webgpu_runtime.py b/tests/unittest/test_webgpu_runtime.pyindex d03e8d66..4b3c672e 100644--- a/tests/unittest/test_webgpu_runtime.py+++ b/tests/unittest/test_webgpu_runtime.py@@ -1,7 +1,7 @@"""Linux plugin lifecycle, real-provider checks, model routing and shared locking."""from concurrent.futures import ThreadPoolExecutor-from dataclasses import asdict+from dataclasses import asdict, replaceimport jsonfrom pathlib import Pathimport sys@@ -12,6 +12,7 @@ from unittest.mock import Mockimport pytest+from mineru.model.runtime.gpu import classify_vulkan_gpu, with_gpu_classificationfrom mineru.model.runtime import onnx, webgpufrom mineru.model.runtime.onnx_device import OnnxSelection@@ -52,7 +53,9 @@ def test_production_options_resolve_native_handles_locally(monkeypatch: pytest.Mep = SimpleNamespace(device=SimpleNamespace(vendor_id=0x1002, device_id=1, metadata=dict(device().metadata)))monkeypatch.setattr(webgpu, "_devices", lambda: [ep])options = SimpleNamespace(add_provider_for_devices=Mock())- webgpu.attach_webgpu_provider(options, device())+ webgpu.attach_webgpu_provider(+ options, with_gpu_classification(replace(device(), vulkan_device=(0x1002, 1)), classify_vulkan_gpu(2))+ )options.add_provider_for_devices.assert_called_once_with([ep], webgpu.WEBGPU_OPTIONS)descriptor = json.loads(json.dumps(asdict(device())))assert descriptor == {@@ -60,6 +63,9 @@ def test_production_options_resolve_native_handles_locally(monkeypatch: pytest.M"device_id": 1,"metadata": [["pci_bus_id", "0000:00:01.0"]],"vulkan_device": None,+ "kind": "unknown",+ "kind_source": "unknown",+ "unified_memory": None,}with pytest.raises(RuntimeError, match="no longer available"):webgpu.attach_webgpu_provider(options, webgpu.WebGPUDevice(1, 2))