Transforms complex documents like PDFs and Office docs into LLM-ready markdown/JSON for your Agentic workflows.
Python ai4sciencedocument-analysisdocxextract-datalayout-analysisocrparserpdfpdf-converterpdf-extractor-llmpdf-extractor-pretrainpdf-extractor-ragpdf-parserpptxpythonxlsx
fix(onnx): gate automatic discrete GPU selection on total memory
myhloli32bfd789196d
diff --git a/docs/en/usage/tiers.md b/docs/en/usage/tiers.mdindex b760dd27..3a46f7cc 100644--- a/docs/en/usage/tiers.md+++ b/docs/en/usage/tiers.md@@ -66,7 +66,7 @@ mineru-kit hardware info --jsondetect shares API startup recommendations and may perform applicable ONNX calibration. info reads hardware, installed runtimes, effective configuration, and calibration records without benchmarking, downloading weights, or writing configuration.-Automatic API/WebUI tiers use the small-model backend’s device decision: GPU enables all four tiers; CPU with at least 12 available logical cores enables up to Standard, 4–11 cores up to Basic, and fewer than 4 cores only Flash. Recommendations do not query GPU memory capacity. Standard is the default request tier when available; CPU does not automatically enable Advanced. An explicit startup ceiling bypasses automatic recommendation.+Automatic API/WebUI tiers use the small-model backend’s device decision: GPU enables all four tiers; CPU with at least 12 available logical cores enables up to Standard, 4–11 cores up to Basic, and fewer than 4 cores only Flash. Recommendations add no separate memory probe. On Windows/Linux, ONNX auto selection uses a discrete GPU only when its total memory rounds to at least 6 GB (`1024³` bytes per GB); insufficient or unavailable capacity selects CPU without calibration. Multiple cards of the same model use the smallest capacity. Configured `cpu/gpu` preferences and Torch selection retain their existing behavior. Standard is the default request tier when available; CPU does not automatically enable Advanced. An explicit startup ceiling bypasses automatic recommendation.## Resources and platform boundariesdiff --git a/docs/next/cli/mineru-kit-api-server.md b/docs/next/cli/mineru-kit-api-server.mdindex d6da43d9..56f4c697 100644--- a/docs/next/cli/mineru-kit-api-server.md+++ b/docs/next/cli/mineru-kit-api-server.md@@ -67,11 +67,11 @@ CPU 数沿用进程可用逻辑核数,考虑亲和性和 Linux cgroup 配额自动推荐先解析有效小模型后端。Torch(包括 auto 最终选择 Torch)使用经过可用性验证的 CUDA/ROCm、MPS、XPU 等加速设备,开放全部四档;显式 CPU、设备不可用或探测失败时按 CPU 核数推荐。该分支不调用 ONNX 选型、不下载校准模型或改写其配置/记录。-ONNX 分支直接调用现有设备选择入口,不再进行显卡库存初选或显存检查。无论 CPU 核数多少,均在发布服务能力前完成适用选型:GPU 开放全部四档,CPU 按表中核数规则推荐。不受支持平台的 CPU 回退由 ONNX 入口处理,不额外探测 Apple Metal。显式 `--tier` 和 Python 精确集合跳过自动推荐。+ONNX 分支直接调用现有设备选择入口,不再进行独立的显卡库存初选或显存检查;ONNX auto 的独显容量检查在设备选型内部完成。无论 CPU 核数多少,均在发布服务能力前完成适用选型:GPU 开放全部四档,CPU 按表中核数规则推荐。不受支持平台的 CPU 回退由 ONNX 入口处理,不额外探测 Apple Metal。显式 `--tier` 和 Python 精确集合跳过自动推荐。-推荐、llama.cpp 自动模式和默认模型加载统一复用 `resolve_runtime_device()` 的不可变进程快照,不读取 llama 专用参数,也不增加显卡匹配或独立测速。显存容量未知、偏小或查询失败均不参与推荐;`hardware detect --json` 为兼容保留 `gpu_memory: null`。+推荐、llama.cpp 自动模式和默认模型加载统一复用 `resolve_runtime_device()` 的不可变进程快照,不读取 llama 专用参数,也不增加显卡匹配或独立测速。推荐自身不增加显存检查;ONNX auto 的独显容量不足或未知会先选择 CPU,再按 CPU 规则推荐;`hardware detect --json` 为兼容保留 `gpu_memory: null`。-启动选型继续遵守 `model.onnx_device`:`auto` 才按设备策略决定是否测速,显式或已保存的 `cpu/gpu` 不强制重新校准。Windows 确认的独显,以及 Linux 通过兼容检查、由 Vulkan 唯一识别并配置物理绑定的独显,均跳过 OCR 校准;首次真实 GPU 会话成功后才保存设备偏好。集显或类型无法确认的候选继续按 0.8 阈值测速。需要测速时会按正常模型生命周期准备或下载 OCR rec 权重,并复用已有进程缓存、文件锁、采样阈值及失败回退。下载和模型准备不计入 15 秒校准子进程超时。校准失败或结果不稳定不会阻止后续推荐,但不作为 GPU 胜出证据。+启动选型继续遵守 `model.onnx_device`:`auto` 才按设备策略决定是否测速,显式或已保存的 `cpu/gpu` 不强制重新校准。Windows 确认的独显,以及 Linux 通过兼容检查、由 Vulkan 确认并限制到相同型号的独显,在 auto 下总显存四舍五入后至少 6 GB 才跳过 OCR 校准;不足或未知直接使用 CPU,不再尝试集显或校准。首次真实 GPU 会话成功后才保存 GPU 偏好,容量回退不写回配置。集显或类型无法确认的候选继续按 0.8 阈值测速。需要测速时会按正常模型生命周期准备或下载 OCR rec 权重,并复用已有进程缓存、文件锁、采样阈值及失败回退。下载和模型准备不计入 15 秒校准子进程超时。校准失败或结果不稳定不会阻止后续推荐,但不作为 GPU 胜出证据。实际 OCR 校准把证据保存在 `<配置文件路径>.onnx-calibration.json`。自动推荐直接采用本次设备结论,历史记录只供诊断,不额外要求有效性能证据。显式或已保存的 `gpu` 只要实际选型为 GPU 就开放全部四档;本次 CPU 或失败结果不会被静态库存覆盖。之后 `/v1/tiers` 和默认设备决策在进程生命周期内固定;配置写回不会改变当前模型缓存。diff --git a/docs/next/cli/mineru-kit-hardware.md b/docs/next/cli/mineru-kit-hardware.mdindex c8f4885d..0afbfdae 100644--- a/docs/next/cli/mineru-kit-hardware.md+++ b/docs/next/cli/mineru-kit-hardware.md@@ -15,7 +15,7 @@ mineru-kit hardware info --json > hardware-info.json## 自动推荐-命令与 API、WebUI 的自动启动共享结构化推荐结果。先解析有效小模型后端,再直接采用其 GPU/CPU 设备结论,不查询显存容量:+命令与 API、WebUI 的自动启动共享结构化推荐结果。先解析有效小模型后端,再直接采用其 GPU/CPU 设备结论,不增加独立显存查询:| 设备结论 | 进程可用逻辑核数 | PDF/图片开放档位 | 请求默认档位 ||----------|------------------|------------------|--------------|@@ -28,7 +28,7 @@ CPU 计数沿用进程亲和性和 Linux cgroup 配额限制。读取失败回Torch(包括 `small_backend=auto` 最终选择 Torch)使用经过可用性验证的加速设备结论,包括 CUDA/ROCm、MPS、XPU 等。显式 CPU、设备不可用或探测失败时按 CPU 规则推荐,并保留原因与警告。该分支不调用 ONNX 选型、不下载 OCR 校准权重,也不修改 ONNX 配置或校准记录。-统一 `resolve_runtime_device()` 在 ONNX 分支的所有 CPU 核数下完成选型,复用进程快照、兼容策略、显式配置和校准。Windows 确认的独显,以及 Linux 通过兼容检查、由 Vulkan 唯一识别并配置物理绑定的独显,保留免 OCR 校准路径。`onnx_device=auto` 下需要测速的候选沿用 0.8 阈值;首次可能准备或下载 OCR rec 模型。下载和派生图准备不计入 15 秒校准 worker 超时。校准失败、超时或不稳定时使用本次 CPU 结果推荐。+统一 `resolve_runtime_device()` 在 ONNX 分支的所有 CPU 核数下完成选型,复用进程快照、兼容策略、显式配置和校准。Windows 确认的独显,以及 Linux 通过兼容检查、由 Vulkan 确认并限制到相同型号的独显,在 auto 下总显存四舍五入后至少 6 GB 才保留免 OCR 校准路径;不足或未知直接 CPU,不下载校准模型、不尝试集显或校准,且不写回配置。同型号多张独显采用最小总容量,GB 按 `1024**3` 字节换算。显式或已保存的 `gpu` 不增加容量检查。`onnx_device=auto` 下需要测速的候选沿用 0.8 阈值;首次可能准备或下载 OCR rec 模型。下载和派生图准备不计入 15 秒校准 worker 超时。校准失败、超时或不稳定时使用本次 CPU 结果推荐。`onnx_device=gpu` 无论来自用户配置还是先前自动选型,都不强制测速。实际选中 GPU 就开放全部四档;校准记录缺失、损坏、过期或记录 GPU 较慢均不额外阻止开放。此时推荐原因是 `configured_gpu`,校准状态为 `status=skipped, reason=configured_gpu`。记录摘要仅供诊断,读取失败附带警告,不改变设备和档位结论。`onnx_device=cpu` 及不受支持平台的 ONNX CPU 回退均遵循 CPU 规则;ONNX 分支不额外探测 Apple Metal。@@ -64,7 +64,7 @@ Windows DXGI 和 Linux Vulkan 的原生库存用于补充“System GPUs”,不未知值为 JSON `null`,文本显示“unknown”。例如 Apple Silicon 通常不报告可可靠读取的 CPU 主频,统一内存也不作为独立显存。系统或容器限制导致库存不完整时保留错误说明;不从型号名称猜测设备类型或频率。-独立显存采集能力和 Windows PCI 身份修复继续保留,其结果不参与自动 tier。Windows 原生查询不依赖 Torch:DXGI 库存通过 `D3DKMTOpenAdapterFromLuid` / `D3DKMTQueryAdapterInfo(KMTQAITYPE_ADAPTERADDRESS)` 补充物理 PCI 位置,内存仍由对应适配器的 DXGI 接口读取。身份匹配优先使用 LUID 和已知 PCI 坐标,不猜测缺失字段;查询失败或多个同等匹配保留未知。读取预算成功不代表模型推理已验证。+独立显存采集能力和 Windows PCI 诊断身份继续保留。自动 tier 不独立查询显存;ONNX auto 的独显容量检查在设备发现和选型时完成。Windows 原生查询不依赖 Torch:DXGI 库存通过 `D3DKMTOpenAdapterFromLuid` / `D3DKMTQueryAdapterInfo(KMTQAITYPE_ADAPTERADDRESS)` 补充物理 PCI 位置,内存仍由对应适配器的 DXGI 接口读取。身份匹配优先使用 LUID 和已知 PCI 坐标,不猜测缺失字段;查询失败或多个同等匹配保留未知。总容量或型号分组通过检查不代表模型推理已验证。配置报告使用明确白名单,不输出认证信息、完整远程服务地址或整个环境变量集合。文本隐藏解释器、模块和软件安装路径,保留配置文件及校准记录路径;JSON 中的完整本地路径仍可用于确认解释器和实际加载位置。diff --git a/docs/next/onnx-device.md b/docs/next/onnx-device.mdindex 64cd1d49..3d343458 100644--- a/docs/next/onnx-device.md+++ b/docs/next/onnx-device.md@@ -19,9 +19,9 @@ Windows 的分类依据为 D3D12 UMA,Linux 为 Vulkan 原生设备类型,mac统一内存属性单独保存,不将 Apple Silicon 的集显分类解释为低性能设备。ONNX 先应用显式配置、设备可见性及兼容限制,再按“确认独显 → 确认集显 → 虚拟 GPU → 类型未知”排序;-同类设备保留 Windows 高性能排序或 Vulkan 原生顺序。自动 tier 不再查询显存容量。+同类设备保留 Windows 高性能排序或 Vulkan 原生顺序。自动 tier 直接复用选型结果,不独立查询显存。身份匹配优先使用 LUID、PCI 地址,再使用双方唯一的厂商/设备型号;名称只用于原生库存的唯一关联。-重复库存或原生查询失败时保留未知类型,不据此授予独显免校准资格。+通用身份关联遇到重复库存时仍保留未知;ONNX auto 可将同型号且全部为独显的可见设备按组确认,并取最小总容量。原生查询失败直接使用 CPU。llama.cpp 的 CPU/GPU 自动决策直接复用小模型后端,具体显卡交给原生引擎。MinerU 不在启动推荐或模型构造时枚举 ggml、匹配 ONNX/llama 显卡、绑定 Vulkan 编号或重映射设备名。@@ -32,7 +32,11 @@ MinerU 不在启动推荐或模型构造时枚举 ggml、匹配 ONNX/llama 显|---|---|---|| `cpu` | 全部使用 CPU,不枚举显卡、不测速 | 全部使用 CPU,不加载插件、不探测 GPU || `gpu` | 首次使用时发现 GPU,独显优先,不测速 | 通过 Intel 架构检查后使用 GPU,不测速;旧 Intel 回退 CPU |-| `auto` | 独显直接使用;集显或类型未知执行 rec 测速 | 通过架构检查且唯一确认的独显直接使用;集显或类型未知执行自适应 rec 测速 |+| `auto` | 独显总显存四舍五入后至少 6 GB 才直接使用;不足或未知直接 CPU;集显或类型未知执行 rec 测速 | 通过架构检查的独显按相同总显存门槛选型;集显或类型未知执行自适应 rec 测速 |++仅 `model.onnx_device=auto` 对确认的独显检查总显存,GB 按 `1024**3` 字节换算并四舍五入到整数,结果至少为 6 才返回 GPU;例如 5.49 GB 返回 CPU,5.50 GB 返回 GPU。Windows 在已有 DXGI 枚举中读取 `DedicatedVideoMemory`,Linux 在已有 Vulkan 枚举中读取独显 device-local 堆总量,每个堆只计一次。不计算剩余预算、不加载 Torch 或额外 Python 绑定。同型号多张独显采用最小总容量,不因无法区分物理卡而退为未知。++独显容量不足、为零或读取失败时直接返回 CPU,不下载校准模型、不执行集显/CPU OCR 测速,也不继续尝试集显;CPU 结果只缓存于当前进程,不写回配置。显式或历史保存的 `cpu/gpu` 不增加显存门槛。Torch 及 macOS 的既有设备选择保持不变。Windows 使用 DXGI 高性能顺序、D3D12 UMA 属性和 LUID 匹配;适配器编号不写入配置。已保存的 `gpu` 使用 Windows 高性能排序及无设备创建的 D3D12 能力检查,避免逐张创建设备查询 UMA;@@ -46,8 +50,7 @@ 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 不视为独显。+自动模式按 ORT 已有厂商/设备型号关联 Vulkan 可见库存;同型号候选全部为 `DISCRETE_GPU` 且会话限制到该型号时,按组检查最小总显存并决定是否免校准。重复 EP 描述或多张同型号独显不再要求逐卡唯一匹配;无法确认类型时保留校准,虚拟 GPU 不视为独显。### Linux Intel 架构策略@@ -105,9 +108,9 @@ MinerU 的 WebGPU 运行时锁覆盖过滤与会话初始化,后续每次会自动决策成功后原子更新有效配置文件中的 `model.onnx_device`,保留其余键;进程间通过文件锁协调。校准证据显式保存设备、运行时与线程指纹;分类来源等诊断字段不进入指纹,原有有效记录可继续复用。实际设备或物理绑定改变后,诊断报告会显示旧记录不再匹配;这不会覆盖配置中的设备偏好,也不会单独限制已选 GPU 的档位。-Windows/Linux 免校准独显都只在首次真实 GPU 会话成功后保存 `gpu`;仅运行硬件推荐时仍保留 `auto`,+Windows/Linux 自动模式下容量达标的免校准独显,只在首次真实 GPU 会话成功后保存 `gpu`;仅运行硬件推荐时仍保留 `auto`,不下载校准权重、不生成性能校准记录。初始化错误或静默回退 CPU 不保存 GPU 偏好。-环境变量覆盖不写入文件;只读配置保留本进程选择。测速失败不保存为 CPU 性能优胜,同进程不重复尝试。设备偏好和自动 tier 均不设置显存容量门槛。+环境变量覆盖不写入文件;只读配置保留本进程选择。测速失败不保存为 CPU 性能优胜,同进程不重复尝试。已配置的设备偏好不受新增门槛限制;显存门槛只位于 ONNX 自动选型的独显分支,自动 tier 继续消费最终设备结论。Linux 插件缺失、没有可用设备、物理绑定失败、校准超时或输出不一致时保留 `auto`。通过环境变量强制 `auto` 时,每个新进程重新选择,并使用选择锁避免同时测速。显式或已保存的 `cpu` 不会因后来接入独显而改变。diff --git a/docs/zh/usage/tiers.md b/docs/zh/usage/tiers.mdindex 85c51ed3..a72a2372 100644--- a/docs/zh/usage/tiers.md+++ b/docs/zh/usage/tiers.md@@ -66,7 +66,7 @@ mineru-kit hardware info --jsondetect 与 API 自动启动共用推荐逻辑,可能执行适用的 ONNX 校准;info 只读采集硬件、已安装运行时、有效配置和校准记录,不测速、不下载权重、不写配置。-API/WebUI 的自动 tier 采用小模型后端的设备结论:GPU 开放全部四档;CPU 可用逻辑核至少 12 时开放到 Standard,4–11 核开放到 Basic,不足 4 核只开放 Flash。自动推荐不查询显存容量。开放 Standard 时默认请求 Standard,CPU 不自动开放 Advanced。显式启动上限跳过自动推荐。+API/WebUI 的自动 tier 采用小模型后端的设备结论:GPU 开放全部四档;CPU 可用逻辑核至少 12 时开放到 Standard,4–11 核开放到 Basic,不足 4 核只开放 Flash。自动推荐不增加独立显存检查;Windows/Linux 的 ONNX 自动选型仅在独显总显存四舍五入后至少为 6 GB 时直接选择 GPU,不足或读取失败直接选择 CPU。同型号多卡取最小容量,GB 按 `1024³` 字节换算;已配置的 `cpu/gpu` 和 Torch 选型保持原有行为。开放 Standard 时默认请求 Standard,CPU 不自动开放 Advanced。显式启动上限跳过自动推荐。## 资源与平台边界diff --git a/mineru/kit/commands/hardware.py b/mineru/kit/commands/hardware.pyindex c813fd08..80859925 100644--- a/mineru/kit/commands/hardware.py+++ b/mineru/kit/commands/hardware.py@@ -167,6 +167,8 @@ def _render_device_selection(data: dict[str, Any]) -> list[str]:"configured_cpu": "CPU selected by configuration","configured_gpu": "GPU selected by configuration; automatic benchmarking skipped","discrete_gpu": "The confirmed discrete GPU candidate meets the rules for skipping calibration",+ "discrete_gpu_memory_insufficient": "Discrete GPU total memory rounds to less than 6 GB; using CPU without calibration",+ "discrete_gpu_memory_unavailable": "Discrete GPU total memory is unavailable; using CPU without calibration","unsupported_platform": "ONNX GPU execution is unsupported on this platform; using CPU","directml_unavailable": "DirectML provider is unavailable; using CPU","no_hardware_gpu": "No usable ONNX GPU found; using CPU",diff --git a/mineru/model/runtime/gpu.py b/mineru/model/runtime/gpu.pyindex 181d8415..3226087d 100644--- a/mineru/model/runtime/gpu.py+++ b/mineru/model/runtime/gpu.py@@ -53,6 +53,12 @@ class GpuIdentity:_Gpu = TypeVar("_Gpu", bound=GpuClassification)+def minimum_gpu_memory_bytes(capacities: Sequence[int | None]) -> int | None:+ """同型号多卡采用最小有效总容量;实际读取失败时保留未知,不累加显存。"""+ valid = [value for value in capacities if type(value) is int and value > 0]+ return min(valid) if valid and len(valid) == len(capacities) else None++def with_gpu_classification(device: _Gpu, classification: GpuClassification) -> _Gpu:"""替换统一分类字段,保留后端的设备索引、注册描述和绑定约束。"""return replace(@@ -178,5 +184,6 @@ __all__ = ["gpu_kind_rank","is_discrete_gpu","match_gpu_identities",+ "minimum_gpu_memory_bytes","with_gpu_classification",]diff --git a/mineru/model/runtime/gpu_memory.py b/mineru/model/runtime/gpu_memory.pydeleted file mode 100644index 1a5b756b..00000000--- a/mineru/model/runtime/gpu_memory.py+++ /dev/null@@ -1,142 +0,0 @@-# Copyright (c) Opendatalab. All rights reserved.-"""为自动档位提供选定设备的精确内存证据,不使用虚拟显存或系统内存替代预算。"""--from __future__ import annotations--from dataclasses import dataclass, replace-import sys-from typing import Literal--from .gpu import GpuIdentity, PciAddress, match_gpu_identities--MIN_GPU_MEMORY_BYTES = 11 * 1024**3 // 2 # 5.5 GiB,始终使用整数字节比较。---@dataclass(frozen=True)-class GpuMemory:- """一次设备查询的容量、口径和来源;未知容量保留为空并携带原因。"""-- device: str- identity: GpuIdentity- memory_bytes: int | None = None- kind: Literal["dedicated", "budget", "unknown"] = "unknown"- source: str = "unknown"- warning: str | None = None-- @property- def sufficient(self) -> bool:- """按原始字节判断 5.5 GiB 边界,不四舍五入、不累加不同显卡。"""- return self.memory_bytes is not None and self.memory_bytes >= MIN_GPU_MEMORY_BYTES---def _validated(memory: GpuMemory) -> GpuMemory:- """未知或非法容量统一降为未知,保留探测来源和具体错误。"""- if type(memory.memory_bytes) is int and memory.memory_bytes > 0:- return memory- return replace(memory, memory_bytes=None, warning=memory.warning or "GPU memory capacity or budget is unavailable")---def native_gpu_memory(identity: GpuIdentity, *, device: str) -> GpuMemory:- """通过双向唯一身份关联查询选中 GPU,不能关联时禁止借用其他设备的容量。"""- result = GpuMemory(device, identity)- try:- if sys.platform == "win32":- from .windows_gpu import inspect_gpus-- rows = inspect_gpus(include_memory_budget=True)- identities = [- GpuIdentity(- row["vendor_id"],- row["device_id"],- luid=row["luid"],- name=row["name"],- pci_address=PciAddress(**row["pci_address"]) if row.get("pci_address") is not None else None,- )- for row in rows- ]- matched = match_gpu_identities((identity,), identities, allow_name=True)[0]- if matched is not None:- row = rows[matched]- dedicated = row["kind"] == "discrete"- result = GpuMemory(- device,- identities[matched],- row.get("dedicated_memory_bytes") if dedicated else row.get("memory_budget_bytes"),- "dedicated" if dedicated else "budget",- "dxgi.dedicated_video_memory" if dedicated else "dxgi.local_budget",- row.get("memory_error"),- )- elif sys.platform == "linux":- from .vulkan import enumerate_vulkan_devices, vulkan_environment_lock-- with vulkan_environment_lock():- devices = enumerate_vulkan_devices(include_memory=True)- matched = match_gpu_identities((identity,), [item.identity for item in devices], allow_name=True)[0]- if matched is not None:- item = devices[matched]- dedicated = item.kind == "discrete"- result = GpuMemory(- device,- item.identity,- item.dedicated_memory_bytes if dedicated else item.memory_budget_bytes,- "dedicated" if dedicated else "budget",- "vulkan.device_local_heap" if dedicated else "vulkan.heap_budget",- item.memory_error,- )- if result.source == "unknown":- result = replace(result, warning="GPU memory device identity could not be uniquely matched")- except Exception as error:- result = replace(result, warning=f"GPU memory discovery failed: {error}")- return _validated(result)---def torch_gpu_memory(device: str) -> GpuMemory:- """惰性读取 Torch 选定设备的容量;MPS 与集显使用运行时预算且不创建模型。"""- result = GpuMemory(device, GpuIdentity(name=device))- try:- import torch-- kind, _, index_text = device.partition(":")- if kind == "mps":- return _validated(- GpuMemory(- device, result.identity, torch.mps.recommended_max_memory(), "budget", "metal.recommended_working_set"- )- )- if kind == "npu":- import torch_npu-- api = torch_npu.npu- else:- api = getattr(torch, kind)- index = int(index_text) if index_text else api.current_device()- properties = api.get_device_properties(index)- selected = f"{kind}:{index}"- bus = getattr(properties, "pci_bus_id", None)- slot = getattr(properties, "pci_device_id", None)- pci_address = None- if type(bus) is int and type(slot) is int:- # ROCm 给出整数 bus/device/domain,没有 function;不能把 bus 编号当完整 BDF 字符串。- try:- pci_address = PciAddress(bus, slot, domain=getattr(properties, "pci_domain_id", None))- except ValueError:- pass # 可选身份字段不可用,不影响独显直接读取容量;原生匹配仍需唯一。- identity = GpuIdentity(- vendor_id=0x8086 if kind == "xpu" else None,- device_id=getattr(properties, "device_id", None),- bus_id=bus if isinstance(bus, str) else None,- name=getattr(properties, "name", None),- pci_address=pci_address,- )- integrated = getattr(properties, "is_integrated_gpu", getattr(properties, "is_integrated", None))- if integrated or (kind == "xpu" and integrated is None):- return native_gpu_memory(identity, device=selected)- result = GpuMemory(- selected, identity, getattr(properties, "total_memory", None), "dedicated", f"torch.{kind}.total_memory"- )- except Exception as error:- result = replace(result, warning=f"GPU memory discovery failed: {error}")- return _validated(result)---__all__ = ["GpuMemory", "MIN_GPU_MEMORY_BYTES", "native_gpu_memory", "torch_gpu_memory"]diff --git a/mineru/model/runtime/hardware_probe.py b/mineru/model/runtime/hardware_probe.pyindex b9999a25..6d02dabe 100644--- a/mineru/model/runtime/hardware_probe.py+++ b/mineru/model/runtime/hardware_probe.py@@ -97,7 +97,9 @@ def _onnx_probe() -> dict[str, Any]:try:adapters = discover_webgpu_devices()has_devices = bool(adapters)- selected = select_webgpu_device(adapters)+ selected = (+ select_webgpu_device(adapters, check_memory=True) if requested == "auto" else select_webgpu_device(adapters)+ )result.update(backend="webgpu", adapters=[asdict(adapter) for adapter in adapters])result["selected_adapter"] = asdict(selected) if selected is not None else Noneexcept Exception as error:@@ -161,7 +163,7 @@ def probe_runtime(name: str) -> RuntimeProbe:elif name == "vulkan":from .vulkan import enumerate_vulkan_devices- data = {"devices": [asdict(device) for device in enumerate_vulkan_devices()]}+ data = {"devices": [asdict(device) for device in enumerate_vulkan_devices(include_memory=True)]}elif name == "dxgi":from .windows_gpu import inspect_gpusdiff --git a/mineru/model/runtime/onnx_device.py b/mineru/model/runtime/onnx_device.pyindex 7224c74b..59178ce0 100644--- a/mineru/model/runtime/onnx_device.py+++ b/mineru/model/runtime/onnx_device.py@@ -60,12 +60,21 @@ def inspect_onnx_candidate(return OnnxSelection(reason="webgpu_architecture_policy", backend=backend)if adapter is None:return OnnxSelection(reason="no_hardware_gpu")- # Linux 只有唯一确认的 Vulkan 独显且会话带物理约束,才与 DML 独显一样免校准。+ # Linux 需由 Vulkan 确认独显并约束到相同型号,容量达标后才免校准。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)+ if requested == "gpu":+ return OnnxSelection("gpu", adapter, "configured_gpu", backend)+ if discrete:+ memory = adapter.dedicated_memory_bytes+ if type(memory) is not int or memory <= 0:+ return OnnxSelection(reason="discrete_gpu_memory_unavailable", backend=backend)+ # GB 沿用 1024**3 字节口径,使用整数运算实现四舍五入。+ rounded_gb = (memory + 1024**3 // 2) // 1024**3+ if rounded_gb < 6:+ return OnnxSelection(reason="discrete_gpu_memory_insufficient", backend=backend)+ return OnnxSelection("gpu", adapter, "discrete_gpu", backend)if ONNX_GPU_TIME_RATIO_THRESHOLDS[backend] is None:return OnnxSelection(reason="calibration_pending")return OnnxSelection(reason="calibration_required", backend=backend)@@ -86,7 +95,7 @@ def _select(if backend == "webgpu":devices = discover_webgpu_devices()has_devices = bool(devices)- adapter = select_webgpu_device(devices)+ adapter = select_webgpu_device(devices, check_memory=True) if requested == "auto" else select_webgpu_device(devices)if devices and adapter is None:logger.info("Linux WebGPU device policy selected CPU; no eligible visible GPU")else:@@ -97,6 +106,14 @@ def _select(return inspect_onnx_candidate(requested, backend=backend, provider_available=False), Falseadapter = preferred_gpu(discover_gpus(classify=requested == "auto"))selection = inspect_onnx_candidate(requested, backend=backend, adapter=adapter, has_devices=has_devices)+ if selection.reason in {"discrete_gpu_memory_unavailable", "discrete_gpu_memory_insufficient"}:+ logger.warning(+ "ONNX {} discrete GPU total memory {} bytes does not meet the rounded 6 GB requirement; "+ "using CPU without calibration ({})",+ backend,+ adapter.dedicated_memory_bytes,+ selection.reason,+ )if selection.reason != "calibration_required":if selection.reason == "calibration_pending":logger.warning("ONNX {} threshold has not completed calibration; using CPU without saving", backend)diff --git a/mineru/model/runtime/vulkan.py b/mineru/model/runtime/vulkan.pyindex 4feeaee4..52cb20bc 100644--- a/mineru/model/runtime/vulkan.py+++ b/mineru/model/runtime/vulkan.py@@ -1,7 +1,7 @@# Copyright (c) Opendatalab. All rights reserved."""No-compute Vulkan enumeration and scoped physical-device restrictions for Dawn.-Uses Vulkan 1.0 properties and Vulkan 1.1 identity/budget queries.+Uses Vulkan 1.0 memory properties and Vulkan 1.1 identity queries.No logical device, shader or GPU work is created.Callers must serialize scopes with the WebGPU runtime lock."""@@ -32,7 +32,6 @@ class VulkanDevice(GpuClassification):name: strindex: int = -1dedicated_memory_bytes: int | None = None- memory_budget_bytes: int | None = Nonememory_error: str | None = Noneluid: str | None = None@@ -131,52 +130,14 @@ class _MemoryProperties(ct.Structure):]-class _MemoryProperties2(ct.Structure):- _fields_ = [("sType", ct.c_uint32), ("pNext", ct.c_void_p), ("memory", _MemoryProperties)]---class _MemoryBudget(ct.Structure):- _fields_ = [- ("sType", ct.c_uint32),- ("pNext", ct.c_void_p),- ("budget", ct.c_uint64 * 16),- ("usage", ct.c_uint64 * 16),- ]---class _ExtensionProperties(ct.Structure):- _fields_ = [("name", ct.c_char * 256), ("version", ct.c_uint32)]---def _device_memory(library: Any, handle: ct.c_void_p, *, discrete: bool) -> tuple[int | None, int | None]:- """按唯一设备的本地堆读取容量和预算;共享内存无预算扩展时保持未知。"""+def _device_memory(library: Any, handle: ct.c_void_p) -> int | None:+ """读取独显本地堆总容量,每个物理堆只计一次,不查询预算或共享内存。"""properties = library.vkGetPhysicalDeviceMemoryPropertiesproperties.argtypes, properties.restype = [ct.c_void_p, ct.POINTER(_MemoryProperties)], Nonememory = _MemoryProperties()properties(handle, ct.byref(memory))local = [index for index in range(min(memory.heap_count, 16)) if memory.heaps[index].flags & 1]- total = sum(memory.heaps[index].size for index in local) or None- if discrete:- return total, None- extensions = library.vkEnumerateDeviceExtensionProperties- extensions.argtypes = [ct.c_void_p, ct.c_char_p, ct.POINTER(ct.c_uint32), ct.POINTER(_ExtensionProperties)]- extensions.restype = ct.c_int32- count = ct.c_uint32()- _check(extensions(handle, None, ct.byref(count), None), "count memory extensions")- rows = (_ExtensionProperties * count.value)()- _check(extensions(handle, None, ct.byref(count), rows), "read memory extensions")- if not any(row.name == b"VK_EXT_memory_budget" for row in rows):- return None, None- budget = _MemoryBudget(sType=1000237000)- info = _MemoryProperties2(sType=1000059006, pNext=ct.cast(ct.pointer(budget), ct.c_void_p))- properties2 = library.vkGetPhysicalDeviceMemoryProperties2- properties2.argtypes, properties2.restype = [ct.c_void_p, ct.POINTER(_MemoryProperties2)], None- properties2(handle, ct.byref(info))- # 预算为进程可用上限,不减去当前用量;每个物理堆只计一次。- local = [index for index in range(min(info.memory.heap_count, 16)) if info.memory.heaps[index].flags & 1]- if not local or any(budget.budget[index] == 0 for index in local):- return None, None- return None, sum(min(budget.budget[index], info.memory.heaps[index].size) for index in local)+ return sum(memory.heaps[index].size for index in local) or Nonedef _check(result: int, operation: str) -> None:@@ -185,7 +146,7 @@ def _check(result: int, operation: str) -> None:def enumerate_vulkan_devices(*, include_memory: bool = False) -> tuple[VulkanDevice, ...]:- """遵守 ICD 和设备过滤枚举 GPU;仅推荐容量时额外读取本地堆或共享预算。"""+ """遵守 ICD 和设备过滤枚举 GPU;按需只为独显读取本地堆总容量。"""library = ct.WinDLL("vulkan-1.dll") if sys.platform == "win32" else ct.CDLL("libvulkan.so.1")create = library.vkCreateInstancecreate.argtypes = [ct.POINTER(_InstanceCreateInfo), ct.c_void_p, ct.POINTER(ct.c_void_p)]@@ -218,10 +179,10 @@ def enumerate_vulkan_devices(*, include_memory: bool = False) -> tuple[VulkanDevproperties(handle, ct.byref(storage))value = storage.prefixif value.deviceType in (0, 1, 2, 3): # 保留未知原生类型,由运行后端过滤可用性;排除软件 CPU。- total, budget, memory_error = None, None, None- if include_memory:+ total, memory_error = None, None+ if include_memory and value.deviceType == 2:try:- total, budget = _device_memory(library, handle, discrete=value.deviceType == 2)+ total = _device_memory(library, handle)except Exception as error:memory_error = str(error)result.append(@@ -232,7 +193,6 @@ def enumerate_vulkan_devices(*, include_memory: bool = False) -> tuple[VulkanDevvalue.deviceName.decode("utf-8", errors="replace"),index,total,- budget,memory_error,luid=_device_luid(library, handle) if sys.platform == "win32" else None,),diff --git a/mineru/model/runtime/webgpu.py b/mineru/model/runtime/webgpu.pyindex cef688f8..5a5036a2 100644--- a/mineru/model/runtime/webgpu.py+++ b/mineru/model/runtime/webgpu.py@@ -5,7 +5,7 @@ from __future__ import annotationsfrom collections.abc import Iteratorfrom contextlib import contextmanager-from dataclasses import dataclass, replace+from dataclasses import dataclass, field, replaceimport osimport sysimport threading@@ -19,6 +19,7 @@ from .gpu import (gpu_kind_rank,is_discrete_gpu,match_gpu_identities,+ minimum_gpu_memory_bytes,with_gpu_classification,)@@ -43,6 +44,8 @@ class WebGPUDevice(GpuClassification):metadata: tuple[tuple[str, str], ...] = ()# 物理设备约束用于多卡选型及独显免校准;只传递身份,不保存原生句柄。vulkan_device: tuple[int, int] | None = None+ # 容量属于选型证据,不参与 EP 注册句柄的身份比较。+ dedicated_memory_bytes: int | None = field(default=None, compare=False)@propertydef identity(self) -> GpuIdentity:@@ -88,8 +91,8 @@ def discover_webgpu_devices() -> tuple[WebGPUDevice, ...]:return tuple(_describe(ep) for ep in _devices())-def select_webgpu_device(devices: tuple[WebGPUDevice, ...]) -> WebGPUDevice | None:- """按 Vulkan 可见类型优先选择独显,并为免校准和多卡会话绑定实际设备。"""+def select_webgpu_device(devices: tuple[WebGPUDevice, ...], *, check_memory: bool = False) -> WebGPUDevice | None:+ """优先选择可见独显;自动模式读取同型号最小容量,显式模式沿用既有选型。"""if not devices:return Noneif sys.platform != "linux":@@ -102,9 +105,9 @@ def select_webgpu_device(devices: tuple[WebGPUDevice, ...]) -> WebGPUDevice | No# ORT 库存可能包含 ICD 已隐藏的设备;分类必须来自 Vulkan 实际可见的物理设备。try:with execution_lock(), vulkan_environment_lock():- visible = enumerate_vulkan_devices()+ visible = enumerate_vulkan_devices(include_memory=True) if check_memory else enumerate_vulkan_devices()except (OSError, RuntimeError):- if len(allowed) != len(devices):+ if check_memory or 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])@@ -115,8 +118,14 @@ def select_webgpu_device(devices: tuple[WebGPUDevice, ...]) -> WebGPUDevice | No]if not physical_indices:continue- # 物理型号存在但无法双向唯一关联时,仍可校准,不允许继承某张卡的独显分类。candidate = with_gpu_classification(descriptor, visible[matched] if matched is not None else GpuClassification())+ if check_memory and all(is_discrete_gpu(visible[i]) for i in physical_indices):+ # 同型号均为独显即可按组确认;运行时允许在这一组内选择,不必定位某一张卡。+ candidate = with_gpu_classification(descriptor, visible[physical_indices[0]])+ candidate = replace(+ candidate,+ dedicated_memory_bytes=minimum_gpu_memory_bytes([visible[i].dedicated_memory_bytes for i in physical_indices]),+ )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)))diff --git a/mineru/model/runtime/windows_gpu.py b/mineru/model/runtime/windows_gpu.pyindex 3bcc4d1c..13678253 100644--- a/mineru/model/runtime/windows_gpu.py+++ b/mineru/model/runtime/windows_gpu.py@@ -4,12 +4,21 @@from __future__ import annotationsimport ctypes as C-from dataclasses import asdict, dataclass+from dataclasses import asdict, dataclass, field, replaceimport sysfrom typing import Anyimport uuid-from .gpu import GpuClassification, GpuIdentity, PciAddress, classify_d3d12_gpu, gpu_kind_rank, with_gpu_classification+from .gpu import (+ GpuClassification,+ GpuIdentity,+ PciAddress,+ classify_d3d12_gpu,+ gpu_kind_rank,+ is_discrete_gpu,+ minimum_gpu_memory_bytes,+ with_gpu_classification,+)@dataclass(frozen=True)@@ -22,6 +31,8 @@ class GpuAdapter(GpuClassification):vendor_id: intdevice_id: intpreference: int+ # 容量只参与自动选型,不改变设备身份、排序或校准证据。+ dedicated_memory_bytes: int | None = field(default=None, compare=False)@propertydef identity(self) -> GpuIdentity:@@ -108,29 +119,6 @@ class _Architecture(C.Structure):]-class _VideoMemoryInfo(C.Structure):- _fields_ = [- ("budget", C.c_uint64),- ("usage", C.c_uint64),- ("available_for_reservation", C.c_uint64),- ("reservation", C.c_uint64),- ]---def _memory_budget(adapter: C.c_void_p) -> int:- """读取同一 UMA 适配器的本地内存预算,查询接口始终成对释放。"""- adapter3 = C.c_void_p()- query = _method(adapter, 0, C.c_int32, C.POINTER(_Guid), C.POINTER(C.c_void_p))- _check(query(adapter, C.byref(_guid("645967a4-1392-4310-a798-8053ce3e93fd")), C.byref(adapter3)))- try:- memory = _VideoMemoryInfo()- read = _method(adapter3, 14, C.c_int32, C.c_uint32, C.c_int32, C.POINTER(_VideoMemoryInfo))- _check(read(adapter3, 0, 0, C.byref(memory)))- return memory.budget- finally:- _release(adapter3)--def _guid(value: str) -> _Guid:return _Guid.from_buffer_copy(uuid.UUID(value).bytes_le)@@ -233,7 +221,15 @@ def discover_gpus(*, classify: bool = True) -> tuple[GpuAdapter, ...]:luid = _luid(desc)rows.append(with_gpu_classification(- GpuAdapter(index, luid, desc.name, desc.vendor, desc.device, ranks.get(luid, index)),+ GpuAdapter(+ index,+ luid,+ desc.name,+ desc.vendor,+ desc.device,+ ranks.get(luid, index),+ dedicated_memory_bytes=desc.video_memory,+ ),classify_d3d12_gpu(uma),))@@ -245,11 +241,19 @@ def discover_gpus(*, classify: bool = True) -> tuple[GpuAdapter, ...]:def preferred_gpu(adapters: tuple[GpuAdapter, ...]) -> GpuAdapter | None:- """Prefer a confirmed discrete GPU, then Windows performance preference."""- return min(adapters, key=lambda item: (gpu_kind_rank(item.kind), item.preference, item.index), default=None)+ """优先独显及系统性能排序;同型号独显取最小总容量,无需逐卡身份关联。"""+ selected = min(adapters, key=lambda item: (gpu_kind_rank(item.kind), item.preference, item.index), default=None)+ if selected is None or not is_discrete_gpu(selected):+ return selected+ capacities = [+ item.dedicated_memory_bytes+ for item in adapters+ if is_discrete_gpu(item) and (item.vendor_id, item.device_id) == (selected.vendor_id, selected.device_id)+ ]+ return replace(selected, dedicated_memory_bytes=minimum_gpu_memory_bytes(capacities))-def inspect_gpus(*, include_memory_budget: bool = False) -> list[dict[str, Any]]:+def inspect_gpus() -> list[dict[str, Any]]:"""诊断库存保留不支持 D3D12 的硬件,并读取 DXGI 的 64 位显存容量。"""if sys.platform != "win32":return []@@ -282,12 +286,6 @@ def inspect_gpus(*, include_memory_budget: bool = False) -> list[dict[str, Any]]pci_address = _pci_address(desc.luid)except Exception as error:pci_error = str(error)- budget, memory_error = None, None- if include_memory_budget and uma is True:- try:- budget = _memory_budget(adapter)- except Exception as error:- memory_error = str(error)result.append({"name": desc.name,@@ -300,8 +298,6 @@ def inspect_gpus(*, include_memory_budget: bool = False) -> list[dict[str, Any]]**asdict(classify_d3d12_gpu(uma)),"dedicated_memory_bytes": desc.video_memory,"shared_memory_bytes": desc.shared_memory,- "memory_budget_bytes": budget,- "memory_error": memory_error,})finally:diff --git a/tests/unittest/test_gpu_memory.py b/tests/unittest/test_gpu_memory.pyindex 95b3c3e6..f3b4fc82 100644--- a/tests/unittest/test_gpu_memory.py+++ b/tests/unittest/test_gpu_memory.py@@ -1,150 +1,16 @@-"""选中设备容量、共享预算与原生 ABI 的回归,避免依赖宿主显卡。"""+"""原生独显容量与保留的硬件诊断 ABI 回归。"""from __future__ import annotationsimport ctypes as ct-from dataclasses import replace-import sysfrom types import SimpleNamespacefrom typing import Anyfrom unittest.mock import Mockimport pytest-from mineru.model.runtime import gpu_memory, vulkan, windows_gpu-from mineru.model.runtime.gpu import GpuIdentity, PciAddress--[email protected]("device", ["cuda:1", "cuda"])-def test_torch_reads_exact_selected_device_bytes(monkeypatch: pytest.MonkeyPatch, device: str) -> None:- """显式序号和默认当前设备都不借用零号大卡,虚拟显存和四舍五入不参与。"""- values = (24 * 1024**3, 5_905_580_032 - 1)- properties = Mock(side_effect=lambda index: SimpleNamespace(name=f"GPU {index}", total_memory=values[index]))- monkeypatch.setitem(- sys.modules, "torch", SimpleNamespace(cuda=SimpleNamespace(current_device=lambda: 1, get_device_properties=properties))- )- monkeypatch.setenv("MINERU_VIRTUAL_VRAM_SIZE", "128")- result = gpu_memory.torch_gpu_memory(device)- assert result.device == "cuda:1" and result.memory_bytes == values[1] and not result.sufficient- assert result.kind == "dedicated" and result.source == "torch.cuda.total_memory"- properties.assert_called_once_with(1)--[email protected]("amount", [None, 0, 5_905_580_032 - 1, 5_905_580_032, 6 * 1024**3 - 1, 8 * 1024**3])-def test_metal_uses_recommended_budget(monkeypatch: pytest.MonkeyPatch, amount: int | None) -> None:- """Metal 只读推荐工作集,不拿系统总内存或当前空闲内存替代。"""- monkeypatch.setitem(sys.modules, "torch", SimpleNamespace(mps=SimpleNamespace(recommended_max_memory=lambda: amount)))- result = gpu_memory.torch_gpu_memory("mps")- assert result.memory_bytes == (amount or None)- assert result.sufficient is (amount is not None and amount >= 5_905_580_032)- assert result.kind == "budget" and result.source == "metal.recommended_working_set"- assert bool(result.warning) is (not amount)--[email protected]("platform", ["linux", "win32"])[email protected]("integrated", [False, True])[email protected]("amount", [None, 5_905_580_032 - 1, 5_905_580_032, 6 * 1024**3 - 1])-def test_native_capacity_belongs_to_selected_gpu(- monkeypatch: pytest.MonkeyPatch, platform: str, integrated: bool, amount: int | None-) -> None:- """库存中的其他大卡不授予能力;集显的大共享上限不能替代预算。"""- monkeypatch.setattr(gpu_memory, "sys", SimpleNamespace(platform=platform))- identity = GpuIdentity(0x8086, 1, luid="selected" if platform == "win32" else None)- kind = "integrated" if integrated else "discrete"- if platform == "win32":- rows = [- {- "vendor_id": 0x8086,- "device_id": 2,- "name": "other",- "luid": "other",- "kind": "discrete",- "dedicated_memory_bytes": 24 * 1024**3,- },- {- "vendor_id": 0x8086,- "device_id": 1,- "name": "selected",- "luid": "selected",- "kind": kind,- "dedicated_memory_bytes": 512 * 1024**2 if integrated else amount,- "memory_budget_bytes": amount if integrated else None,- "shared_memory_bytes": 128 * 1024**3,- },- ]- monkeypatch.setattr(windows_gpu, "inspect_gpus", lambda **kwargs: rows)- else:- devices = (- vulkan.VulkanDevice(0x8086, 2, "other", kind="discrete", dedicated_memory_bytes=24 * 1024**3),- vulkan.VulkanDevice(- 0x8086,- 1,- "selected",- kind=kind,- dedicated_memory_bytes=None if integrated else amount,- memory_budget_bytes=amount if integrated else None,- ),- )- monkeypatch.setattr(vulkan, "enumerate_vulkan_devices", lambda **kwargs: devices)- result = gpu_memory.native_gpu_memory(identity, device="selected")- assert result.memory_bytes == amount- assert result.kind == ("budget" if integrated else "dedicated")- assert result.sufficient is (amount is not None and amount >= 5_905_580_032)---def test_ambiguous_native_gpu_does_not_borrow_capacity(monkeypatch: pytest.MonkeyPatch) -> None:- """同型号多卡缺少强身份时,即使某卡容量达标也不能猜测归属。"""- monkeypatch.setattr(gpu_memory, "sys", SimpleNamespace(platform="linux"))- first = vulkan.VulkanDevice(0x8086, 1, "GPU", kind="discrete", dedicated_memory_bytes=4 * 1024**3)- monkeypatch.setattr(- vulkan, "enumerate_vulkan_devices", lambda **kwargs: (first, replace(first, dedicated_memory_bytes=24 * 1024**3))- )- result = gpu_memory.native_gpu_memory(first.identity, device="selected")- assert result.memory_bytes is None and not result.sufficient and "uniquely matched" in result.warning---def test_xpu_integrated_uses_native_budget(monkeypatch: pytest.MonkeyPatch) -> None:- """Torch 集显的全局内存不能替代原生预算,型号用于唯一关联原生设备。"""- props = SimpleNamespace(name="Intel GPU", device_id=1, is_integrated_gpu=True, total_memory=64 * 1024**3)- monkeypatch.setitem(sys.modules, "torch", SimpleNamespace(xpu=SimpleNamespace(get_device_properties=lambda index: props)))- query = Mock(return_value=gpu_memory.GpuMemory("xpu:1", GpuIdentity(0x8086, 1), 4 * 1024**3, "budget", "native"))- monkeypatch.setattr(gpu_memory, "native_gpu_memory", query)- result = gpu_memory.torch_gpu_memory("xpu:1")- assert result.memory_bytes == 4 * 1024**3 and not result.sufficient- query.assert_called_once_with(GpuIdentity(0x8086, 1, name="Intel GPU"), device="xpu:1")--[email protected]("device", ["cuda:1", "cuda"])[email protected]("amount", [None, 5_905_580_032 - 1, 5_905_580_032])-def test_rocm_integrated_reads_matching_dxgi_budget(monkeypatch: pytest.MonkeyPatch, device: str, amount: int | None) -> None:- """整数 PCI 字段定位真实 DXGI 适配器,重复条目或 Torch 大容量都不替代其预算。"""- monkeypatch.setattr(gpu_memory, "sys", SimpleNamespace(platform="win32"))- properties = Mock(- return_value=SimpleNamespace(- name="8060S", is_integrated=1, pci_bus_id=195, pci_device_id=0, pci_domain_id=0, total_memory=96 * 1024**3- )- )- monkeypatch.setitem(- sys.modules, "torch", SimpleNamespace(cuda=SimpleNamespace(current_device=lambda: 1, get_device_properties=properties))- )- physical = {- "vendor_id": 0x1002,- "device_id": 5510,- "name": "8060S",- "luid": "physical",- "pci_address": {"bus": 195, "device": 0, "domain": None, "function": 0},- "kind": "integrated",- "dedicated_memory_bytes": 32 * 1024**3,- "shared_memory_bytes": 128 * 1024**3,- "memory_budget_bytes": amount,- }- duplicate = {**physical, "luid": "duplicate", "pci_address": None, "memory_budget_bytes": 128 * 1024**3}- monkeypatch.setattr(windows_gpu, "inspect_gpus", lambda **kwargs: [duplicate, physical])- result = gpu_memory.torch_gpu_memory(device)- assert result.memory_bytes == amount and result.sufficient is (amount == 5_905_580_032)- assert result.device == "cuda:1" and result.identity.luid == "physical"- assert result.source == "dxgi.local_budget" and result.kind == "budget"- properties.assert_called_once_with(1)+from mineru.model.runtime import vulkan, windows_gpu+from mineru.model.runtime.gpu import PciAddress@pytest.mark.parametrize("stage", ["success", "open", "query", "invalid", "close"])@@ -183,89 +49,89 @@ def test_windows_pci_query_abi_and_handle_lifetime(monkeypatch: pytest.MonkeyPatassert windows_gpu._QueryAdapterInfo.data.offset == 8[email protected]("native", [False, True])-def test_memory_probe_errors_are_reported(monkeypatch: pytest.MonkeyPatch, native: bool) -> None:- """驱动异常输出未知容量和警告,不伪造零容量或吞掉原因。"""- failure = Mock(side_effect=RuntimeError("driver unavailable"))- monkeypatch.setattr(gpu_memory, "sys", SimpleNamespace(platform="linux"))- monkeypatch.setattr(vulkan, "enumerate_vulkan_devices", failure)- monkeypatch.setitem(sys.modules, "torch", SimpleNamespace(mps=SimpleNamespace(recommended_max_memory=failure)))- result = gpu_memory.native_gpu_memory(GpuIdentity(1, 2), device="gpu") if native else gpu_memory.torch_gpu_memory("mps")- assert result.memory_bytes is None and not result.sufficient and "driver unavailable" in result.warning[email protected]("vendor", [0x10DE, 0x1002, 0x8086])+def test_windows_discovery_carries_native_64bit_memory(monkeypatch: pytest.MonkeyPatch, vendor: int) -> None:+ """模拟系统 DXGI 调用,验证三家独显均保留超过 32 位的总容量。"""+ monkeypatch.setattr(windows_gpu, "sys", SimpleNamespace(platform="win32"))+ def create(iid: Any, output: Any) -> int:+ """使用旧版工厂路径,避免测试依赖宿主 Windows 接口。"""+ output._obj.value = 1+ return -1 if factory.call_count == 1 else 0[email protected]("discrete", [False, True])[email protected]("extension", [False, True])-def test_vulkan_memory_abi_uses_local_heaps_once(discrete: bool, extension: bool) -> None:- """模拟原生填充结构体,验证共享预算扩展、字节宽度及本地堆去重。"""+ def enumerate_adapter(pointer: Any, index: int, output: Any) -> int:+ """枚举一张独显后正常结束。"""+ output._obj.value = 2+ return 0 if index == 0 else 0x887A0002- def fill_memory(memory: Any) -> None:- """两个类型指向同一个 GPU 堆,另一个大堆是主机内存。"""- memory.type_count, memory.heap_count = 2, 2- memory.types[0].heap_index = memory.types[1].heap_index = 0- memory.heaps[0].flags, memory.heaps[0].size = 1, 8 * 1024**3- memory.heaps[1].flags, memory.heaps[1].size = 0, 128 * 1024**3-- def properties(handle: Any, output: Any) -> None:- """按 Vulkan 1.0 ABI 回填显存堆。"""- fill_memory(output._obj)-- def extensions(handle: Any, layer: Any, count: Any, rows: Any) -> int:- """分别模拟支持和不支持预算扩展的运行时。"""- count._obj.value = int(extension)- if rows is not None and extension:- rows[0].name = b"VK_EXT_memory_budget"- return 0-- def properties2(handle: Any, output: Any) -> None:- """预算显著低于总容量且有用量,查询应保留预算上限。"""- assert output._obj.sType == 1000059006- fill_memory(output._obj.memory)- budget = ct.cast(output._obj.pNext, ct.POINTER(vulkan._MemoryBudget)).contents- assert budget.sType == 1000237000- budget.budget[0], budget.usage[0] = 6 * 1024**3, 2 * 1024**3- budget.budget[1] = 100 * 1024**3-- lib = SimpleNamespace(- vkGetPhysicalDeviceMemoryProperties=Mock(side_effect=properties),- vkEnumerateDeviceExtensionProperties=Mock(side_effect=extensions),- vkGetPhysicalDeviceMemoryProperties2=Mock(side_effect=properties2),- )- assert vulkan._device_memory(lib, ct.c_void_p(1), discrete=discrete) == (- (8 * 1024**3, None) if discrete else (None, 6 * 1024**3 if extension else None)- )- if discrete or not extension:- lib.vkGetPhysicalDeviceMemoryProperties2.assert_not_called()- assert ct.sizeof(vulkan._MemoryProperties) == 520- assert vulkan._MemoryProperties.heaps.offset == 264+ factory = Mock(side_effect=create)+ library = SimpleNamespace(CreateDXGIFactory1=factory, D3D12CreateDevice=Mock())+ monkeypatch.setattr(windows_gpu.C, "WinDLL", lambda *args, **kwargs: library, raising=False)+ monkeypatch.setattr(windows_gpu, "_method", lambda *args: enumerate_adapter)+ monkeypatch.setattr(windows_gpu, "_architecture", Mock(return_value=(True, False)))+ description = windows_gpu._Description()+ description.name, description.vendor, description.device = "GPU", vendor, 1+ description.video_memory = 8 * 1024**3+ monkeypatch.setattr(windows_gpu, "_description", Mock(return_value=description))+ release = Mock()+ monkeypatch.setattr(windows_gpu, "_release", release)+ selected = windows_gpu.preferred_gpu(windows_gpu.discover_gpus())+ assert selected.kind == "discrete" and selected.vendor_id == vendor+ assert selected.dedicated_memory_bytes == 8 * 1024**3+ assert release.call_count == 2[email protected]("include_memory", [False, True])@pytest.mark.parametrize("failed", [False, True])-def test_dxgi_budget_queries_same_adapter_and_releases(monkeypatch: pytest.MonkeyPatch, failed: bool) -> None:- """模拟 COM 查询与释放,预算失败仍释放接口且不使用共享容量替代。"""+def test_vulkan_discovery_only_reads_discrete_local_heaps(+ monkeypatch: pytest.MonkeyPatch, include_memory: bool, failed: bool+) -> None:+ """完整枚举夹具验证仅查询独显、本地堆不重复计数、失败保留原因且释放实例。"""+ monkeypatch.setattr(vulkan, "sys", SimpleNamespace(platform="linux"))- def query(pointer: Any, iid: Any, output: Any) -> int:- """返回同一适配器的 IDXGIAdapter3 接口。"""- assert pointer.value == 123- output._obj.value = 456+ def create(info: Any, allocator: Any, output: Any) -> int:+ """创建测试实例,不创建逻辑设备或分配显存。"""+ output._obj.value = 1return 0- def read(pointer: Any, node: int, segment: int, output: Any) -> int:- """查询本地段预算,不减去用量或加入非本地内存。"""- assert (pointer.value, node, segment) == (456, 0, 0)- output._obj.budget, output._obj.usage = 6 * 1024**3, 2 * 1024**3- return -1 if failed else 0+ def enumerate_devices(instance: Any, count: Any, handles: Any) -> int:+ """返回一张独显和一张集显。"""+ count._obj.value = 2+ if handles is not None:+ handles[0], handles[1] = 2, 3+ return 0- def method(pointer: Any, slot: int, *args: Any) -> Any:- """只允许 QueryInterface 和 QueryVideoMemoryInfo 两个方法。"""- return {0: query, 14: read}[slot]+ def properties(handle: int, output: Any) -> None:+ """独显和集显使用不同的原生类型。"""+ output._obj.prefix.vendorID = 0x1002+ output._obj.prefix.deviceID = handle+ output._obj.prefix.deviceType = 2 if handle == 2 else 1+ output._obj.prefix.deviceName = b"GPU"++ def memory(handle: int, output: Any) -> None:+ """两个内存类型指向同一个堆,另一个大堆属于主机内存。"""+ assert handle == 2+ if failed:+ raise OSError("memory properties unavailable")+ value = output._obj+ value.type_count, value.heap_count = 2, 3+ value.types[0].heap_index = value.types[1].heap_index = 0+ value.heaps[0].flags, value.heaps[0].size = 1, 8 * 1024**3+ value.heaps[1].flags, value.heaps[1].size = 1, 2 * 1024**3+ value.heaps[2].flags, value.heaps[2].size = 0, 128 * 1024**3- monkeypatch.setattr(windows_gpu, "_method", method)- release = Mock()- monkeypatch.setattr(windows_gpu, "_release", release)- if failed:- with pytest.raises(OSError, match="HRESULT"):- windows_gpu._memory_budget(ct.c_void_p(123))- else:- assert windows_gpu._memory_budget(ct.c_void_p(123)) == 6 * 1024**3- assert release.call_count == 1 and release.call_args.args[0].value == 456+ library = SimpleNamespace(+ vkCreateInstance=Mock(side_effect=create),+ vkDestroyInstance=Mock(),+ vkEnumeratePhysicalDevices=Mock(side_effect=enumerate_devices),+ vkGetPhysicalDeviceProperties=Mock(side_effect=properties),+ vkGetPhysicalDeviceMemoryProperties=Mock(side_effect=memory),+ )+ monkeypatch.setattr(vulkan.ct, "CDLL", lambda *args: library)+ discrete, integrated = vulkan.enumerate_vulkan_devices(include_memory=include_memory)+ assert discrete.kind == "discrete" and integrated.kind == "integrated"+ assert discrete.dedicated_memory_bytes == (10 * 1024**3 if include_memory and not failed else None)+ assert bool(discrete.memory_error) is (include_memory and failed)+ assert integrated.dedicated_memory_bytes is None and integrated.memory_error is None+ assert library.vkGetPhysicalDeviceMemoryProperties.call_count == int(include_memory)+ library.vkDestroyInstance.assert_called_once()diff --git a/tests/unittest/test_gpu_policy.py b/tests/unittest/test_gpu_policy.pyindex c1233674..a39812cc 100644--- a/tests/unittest/test_gpu_policy.py+++ b/tests/unittest/test_gpu_policy.py@@ -53,7 +53,7 @@ def test_native_classification_agrees_across_runtime_and_report(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,))+ 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),))@@ -135,7 +135,7 @@ def test_ambiguous_native_mapping_remains_unknown_everywhere(monkeypatch: pytestmonkeypatch.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(vulkan, "enumerate_vulkan_devices", lambda **_: physical)monkeypatch.setattr(windows_gpu,"discover_gpus",@@ -205,7 +205,7 @@ def test_ggml_gpu_enum_only_controls_inventory(monkeypatch: pytest.MonkeyPatch,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,))+ 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")@@ -239,7 +239,7 @@ def test_windows_probe_loads_device_accessors_from_base_dll(libraries = {str(registry_path): registry_library, str(base_path): base_library}monkeypatch.setattr(llama_probe, "sys", SimpleNamespace(platform="win32"))monkeypatch.setattr(llama_probe.ct, "CDLL", libraries.__getitem__)- monkeypatch.setattr(llama_probe, "enumerate_vulkan_devices", lambda: ())+ monkeypatch.setattr(llama_probe, "enumerate_vulkan_devices", lambda **_: ())monkeypatch.setattr(windows_gpu, "discover_gpus", lambda: ())assert llama_probe._probe_library(tmp_path) == (llama_probe.LlamaDevice("Vulkan0", "GPU", "vulkan"),)@@ -271,29 +271,20 @@ 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)-def test_windows_memory_query_without_torch_or_other_inference_dependencies() -> None:- """基础安装的 Windows 原生查询和 LUID 匹配无需导入任何推理后端。"""- code = """-import importlib.abc+def test_native_memory_modules_only_require_standard_library() -> None:+ """关闭 site-packages 后独立导入原生探测模块,确保不需要任何第三方 Python 包。"""+ root = Path(windows_gpu.__file__).parent+ code = f"""import sys-from types import SimpleNamespace-class BlockRuntime(importlib.abc.MetaPathFinder):- def find_spec(self, fullname, path=None, target=None):- if fullname.split('.')[0] in {'torch', 'torchvision', 'onnxruntime', 'mineru_llama_cpp'}:- raise AssertionError(fullname)-sys.meta_path.insert(0, BlockRuntime())-from mineru.model.runtime import gpu_memory, windows_gpu-from mineru.model.runtime.gpu import GpuIdentity-gpu_memory.sys = SimpleNamespace(platform='win32')-rows = [- {'vendor_id': 4098, 'device_id': 5510, 'name': '8060S', 'luid': luid,- 'kind': 'integrated', 'memory_budget_bytes': budget, 'pci_address': None}- for luid, budget in [('other', 128 * 1024**3), ('selected', 8 * 1024**3)]-]-windows_gpu.inspect_gpus = lambda **kwargs: rows-memory = gpu_memory.native_gpu_memory(GpuIdentity(luid='selected'), device='dml:gpu')-assert memory.memory_bytes == 8 * 1024**3-assert memory.source == 'dxgi.local_budget' and memory.identity.luid == 'selected'-assert 'torch' not in sys.modules and 'onnxruntime' not in sys.modules+from types import ModuleType, SimpleNamespace+package = ModuleType("native_probe")+package.__path__ = [{str(root)!r}]+sys.modules[package.__name__] = package+from native_probe import gpu, windows_gpu, vulkan+assert gpu.minimum_gpu_memory_bytes([8 * 1024**3, 16 * 1024**3]) == 8 * 1024**3+assert gpu.minimum_gpu_memory_bytes([None, 16 * 1024**3]) is None+adapter = windows_gpu.GpuAdapter(0, "id", "GPU", 0x10de, 1, 0, dedicated_memory_bytes=8 * 1024**3)+assert adapter.dedicated_memory_bytes == 8 * 1024**3+assert "torch" not in sys.modules and "onnxruntime" not in sys.modules and "loguru" not in sys.modules"""- subprocess.run([sys.executable, "-c", code], check=True, capture_output=True, text=True, timeout=15)+ subprocess.run([sys.executable, "-S", "-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 b005bc3a..e2b0a7bf 100644--- a/tests/unittest/test_hardware_info.py+++ b/tests/unittest/test_hardware_info.py@@ -636,7 +636,7 @@ def test_onnx_info_probe_reuses_policy_without_calibrating(get_available_providers=lambda: ["DmlExecutionProvider"] if provider else ["CPUExecutionProvider"],),)- gpu = windows_gpu.GpuAdapter(0, "luid-0", "test", 0x10DE, 1, 0, kind=kind)+ gpu = windows_gpu.GpuAdapter(0, "luid-0", "test", 0x10DE, 1, 0, kind=kind, dedicated_memory_bytes=8 * 1024**3)discovery = Mock(return_value=(gpu,))monkeypatch.setattr(windows_gpu, "discover_gpus", discovery)forbidden = Mock(side_effect=AssertionError("info cannot calibrate, download or save"))diff --git a/tests/unittest/test_hardware_recommendation.py b/tests/unittest/test_hardware_recommendation.pyindex 6aa8e789..12ed875e 100644--- a/tests/unittest/test_hardware_recommendation.py+++ b/tests/unittest/test_hardware_recommendation.py@@ -17,7 +17,7 @@ from typer.testing import CliRunnerfrom mineru.config import VlmConfig, get_configfrom mineru.kit.commands import hardware as hardware_cmdfrom mineru.kit.main import app as kit_app-from mineru.model.runtime import device, gpu_memory, llama_device, onnx_calibration_cache, onnx_device, tier_recommendation+from mineru.model.runtime import device, llama_device, onnx_calibration_cache, onnx_device, tier_recommendationfrom mineru.parser import api_serverfrom mineru.types import TIERS@@ -34,8 +34,6 @@ def torch_environment(monkeypatch: pytest.MonkeyPatch) -> Mock:monkeypatch.setattr(onnx_device, "resolve_onnx_device", forbidden)monkeypatch.setattr(onnx_calibration_cache, "save_calibration_record", forbidden)monkeypatch.setattr(onnx_calibration_cache, "invalidate_calibration_record", forbidden)- monkeypatch.setattr(gpu_memory, "native_gpu_memory", forbidden)- monkeypatch.setattr(gpu_memory, "torch_gpu_memory", forbidden)return forbiddendiff --git a/tests/unittest/test_onnx_device_selection.py b/tests/unittest/test_onnx_device_selection.pyindex 67f8425c..826bc1b9 100644--- a/tests/unittest/test_onnx_device_selection.py+++ b/tests/unittest/test_onnx_device_selection.py@@ -22,8 +22,13 @@ from mineru.model.runtime.webgpu import WebGPUDevicesettings = importlib.import_module("mineru.config")-def adapter(*, index: int = 0, uma: bool | None = True, vendor: int = 0x8086, rank: int = 0) -> GpuAdapter:- return with_gpu_classification(GpuAdapter(index, f"luid-{index}", "test GPU", vendor, 1, rank), classify_d3d12_gpu(uma))+def adapter(+ *, index: int = 0, uma: bool | None = True, vendor: int = 0x8086, rank: int = 0, memory: int | None = 8 * 1024**3+) -> GpuAdapter:+ """提供可配置容量的原生适配器,默认独显满足自动门槛。"""+ return with_gpu_classification(+ GpuAdapter(index, f"luid-{index}", "test GPU", vendor, 1, rank, dedicated_memory_bytes=memory), classify_d3d12_gpu(uma)+ )@pytest.fixture@@ -310,7 +315,11 @@ def linux_config(config_file: Path, monkeypatch: pytest.MonkeyPatch) -> Path:monkeypatch.setattr(vulkan,"enumerate_vulkan_devices",- lambda: (with_gpu_classification(vulkan.VulkanDevice(0x1002, 1, "integrated"), classify_vulkan_gpu(1)),),+ lambda **_: (+ with_gpu_classification(+ vulkan.VulkanDevice(0x1002, 1, "integrated", dedicated_memory_bytes=8 * 1024**3), classify_vulkan_gpu(1)+ ),+ ),)monkeypatch.setattr(policy, "discover_webgpu_devices", Mock(return_value=(WebGPUDevice(0x1002, 1),)))return config_file@@ -355,7 +364,11 @@ def test_linux_discrete_skips_calibration_and_saves_after_actual_session(monkeypatch.setattr(vulkan,"enumerate_vulkan_devices",- lambda: (with_gpu_classification(vulkan.VulkanDevice(*identity, "GPU"), classify_vulkan_gpu(2)),),+ lambda **_: (+ with_gpu_classification(+ vulkan.VulkanDevice(*identity, "GPU", dedicated_memory_bytes=8 * 1024**3), classify_vulkan_gpu(2)+ ),+ ),)monkeypatch.setattr(settings, "get_config_source", lambda key: source)monkeypatch.setitem(policy.ONNX_GPU_TIME_RATIO_THRESHOLDS, "webgpu", None)@@ -394,11 +407,15 @@ def test_linux_discrete_session_failure_preserves_auto(from mineru.model.runtime import onnx, onnx_calibration, vulkandescriptor = 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))+ integrated = with_gpu_classification(+ vulkan.VulkanDevice(0x1002, 1, "integrated", dedicated_memory_bytes=8 * 1024**3), classify_vulkan_gpu(1)+ )+ discrete = with_gpu_classification(+ vulkan.VulkanDevice(0x10DE, 0x2489, "discrete", dedicated_memory_bytes=8 * 1024**3), 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,)+ vulkan, "enumerate_vulkan_devices", lambda **_: (integrated, discrete) if failure == "binding" else (discrete,))selected = device_state.resolve_runtime_device().selectionassert selected.reason == "discrete_gpu"@@ -412,14 +429,15 @@ def test_linux_discrete_session_failure_preserves_auto(onnx_calibration.run_calibration.assert_not_called()[email protected]("state", ["unavailable", "duplicate", "virtual"])[email protected]("state", ["virtual"])def test_linux_unconfirmed_discrete_still_calibrates(linux_config: Path, monkeypatch: pytest.MonkeyPatch, state: str) -> None:- """类型未知、同型号多卡及虚拟 GPU 均不能获得独显免校准资格。"""+ """虚拟 GPU 不因 EP 元数据声称独显而获得免校准资格。"""from mineru.model.runtime import onnx_calibration, vulkandescriptor = WebGPUDevice(0x10DE, 0x2489, (("type", "discrete"),))physical = with_gpu_classification(- vulkan.VulkanDevice(0x10DE, 0x2489, "GPU"), classify_vulkan_gpu(3 if state == "virtual" else 2)+ vulkan.VulkanDevice(0x10DE, 0x2489, "GPU", dedicated_memory_bytes=8 * 1024**3),+ classify_vulkan_gpu(3 if state == "virtual" else 2),)monkeypatch.setattr(policy, "discover_webgpu_devices", lambda: (descriptor,))monkeypatch.setattr(@@ -515,7 +533,11 @@ def test_unstable_calibration_keeps_auto(config_file: Path, monkeypatch: pytest.monkeypatch.setattr(vulkan,"enumerate_vulkan_devices",- lambda: (with_gpu_classification(vulkan.VulkanDevice(0x8086, 0x7D51, "integrated"), classify_vulkan_gpu(1)),),+ lambda **_: (+ with_gpu_classification(+ vulkan.VulkanDevice(0x8086, 0x7D51, "integrated", dedicated_memory_bytes=8 * 1024**3), 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})@@ -530,7 +552,9 @@ def test_unstable_calibration_keeps_auto(config_file: Path, monkeypatch: pytest.@pytest.mark.parametrize("binding", [None, (0x8086, 1), (0x8086, 2)])def test_readonly_discrete_policy_requires_matching_webgpu_binding(binding: tuple[int, int] | None) -> None:"""只读诊断与运行时共享独显判断,缺少或错误物理绑定时仍需要校准。"""- descriptor = with_gpu_classification(WebGPUDevice(0x8086, 1, vulkan_device=binding), classify_vulkan_gpu(2))+ descriptor = with_gpu_classification(+ WebGPUDevice(0x8086, 1, vulkan_device=binding, dedicated_memory_bytes=8 * 1024**3), classify_vulkan_gpu(2)+ )selection = policy.inspect_onnx_candidate("auto", backend="webgpu", adapter=descriptor, has_devices=True)assert selection.reason == ("discrete_gpu" if binding == (0x8086, 1) else "calibration_required")assert selection.device == ("gpu" if binding == (0x8086, 1) else "cpu")@@ -549,3 +573,174 @@ def test_readonly_policy_explains_missing_candidate(backend: str | None, has_dev"""平台不支持、无设备和有库存但无合格候选保持不同原因。"""selection = policy.inspect_onnx_candidate("auto", backend=backend, has_devices=has_devices)assert selection.device == "cpu" and selection.reason == reason++[email protected]("platform", ["win32", "linux"])[email protected]("vendor", [0x10DE, 0x1002, 0x8086])+ "memory",+ [+ None,+ 0,+ -1,+ 2 * 1024**3,+ 4 * 1024**3,+ 11 * 1024**3 // 2 - 1,+ 11 * 1024**3 // 2,+ 6 * 1024**3 - 1,+ 6 * 1024**3,+ 8 * 1024**3,+ ],+)+def test_auto_discrete_memory_gate_skips_all_calibration(+ config_file: Path, monkeypatch: pytest.MonkeyPatch, platform: str, vendor: int, memory: int | None+) -> None:+ """三家独显统一按整数 GB 四舍五入;不足或未知时直接 CPU,不下载或校准。"""+ from mineru.model import registry+ from mineru.model.runtime import onnx_calibration, vulkan, webgpu++ monkeypatch.setattr(policy, "sys", SimpleNamespace(platform=platform))+ monkeypatch.setattr(webgpu, "sys", SimpleNamespace(platform=platform))+ chip = 0x56A0 if vendor == 0x8086 else 1+ integrated = adapter(index=0, uma=True, memory=128 * 1024**3)+ discrete = adapter(index=1, uma=False, vendor=vendor, memory=memory)+ monkeypatch.setattr(policy, "discover_gpus", Mock(return_value=(integrated, discrete)))+ monkeypatch.setattr(policy, "discover_webgpu_devices", Mock(return_value=(WebGPUDevice(vendor, chip),)))+ inventory = Mock(+ return_value=(+ vulkan.VulkanDevice(0x1002, 2, "integrated", kind="integrated", dedicated_memory_bytes=128 * 1024**3),+ vulkan.VulkanDevice(vendor, chip, "discrete", kind="discrete", dedicated_memory_bytes=memory),+ )+ )+ monkeypatch.setattr(vulkan, "enumerate_vulkan_devices", inventory)+ forbidden = Mock(side_effect=AssertionError("独显选型不应准备或执行 OCR 校准"))+ monkeypatch.setattr(registry, "MINERU_4_MODELS_ONNX", SimpleNamespace(ocr_rec=SimpleNamespace(ensure=forbidden)))+ monkeypatch.setattr(onnx_calibration, "run_calibration", forbidden)+ monkeypatch.setenv("MINERU_VIRTUAL_VRAM_SIZE", "128")+ selected = device_state.resolve_runtime_device().selection+ expected = "gpu" if memory is not None and memory >= 11 * 1024**3 // 2 else "cpu"+ assert selected.device == expected+ if expected == "cpu":+ assert selected.reason == (+ "discrete_gpu_memory_unavailable" if memory is None or memory <= 0 else "discrete_gpu_memory_insufficient"+ )+ assert device_state.resolve_runtime_device().selection is selected+ assert yaml.safe_load(config_file.read_text())["model"]["onnx_device"] == "auto"+ forbidden.assert_not_called()+ if platform == "linux":+ inventory.assert_called_once_with(include_memory=True)++[email protected]("platform", ["win32", "linux"])[email protected]("requested", ["cpu", "gpu"])[email protected]("memory", [None, 0, 2 * 1024**3])+def test_configured_device_bypasses_new_memory_gate(+ config_file: Path, monkeypatch: pytest.MonkeyPatch, platform: str, requested: str, memory: int | None+) -> None:+ """显式及历史保存的 CPU/GPU 偏好不增加显存门槛,Linux 不额外读取容量。"""+ from mineru.model.runtime import onnx_calibration, vulkan, webgpu++ config_file.write_text(f"model:\n onnx_device: {requested}\n", encoding="utf-8")+ monkeypatch.setattr(settings.get_config().model, "onnx_device", requested)+ monkeypatch.setattr(policy, "sys", SimpleNamespace(platform=platform))+ monkeypatch.setattr(webgpu, "sys", SimpleNamespace(platform=platform))+ discover = Mock(return_value=(adapter(uma=False, memory=memory),))+ monkeypatch.setattr(policy, "discover_gpus", discover)+ monkeypatch.setattr(policy, "discover_webgpu_devices", Mock(return_value=(WebGPUDevice(0x8086, 0x56A0),)))+ inventory = Mock(return_value=(vulkan.VulkanDevice(0x8086, 0x56A0, "GPU", kind="discrete"),))+ monkeypatch.setattr(vulkan, "enumerate_vulkan_devices", inventory)+ selected = device_state.resolve_runtime_device().selection+ assert selected.device == requested+ onnx_calibration.run_calibration.assert_not_called()+ assert yaml.safe_load(config_file.read_text())["model"]["onnx_device"] == requested+ if requested == "cpu":+ discover.assert_not_called()+ inventory.assert_not_called()+ elif platform == "win32":+ discover.assert_called_once_with(classify=False)+ else:+ inventory.assert_called_once_with()++[email protected]("platform", ["win32", "linux"])[email protected]("duplicate_ep", [False, True])+ "capacities, expected",+ [+ ((8 * 1024**3, 8 * 1024**3), "gpu"),+ ((8 * 1024**3, 16 * 1024**3), "gpu"),+ ((4 * 1024**3, 8 * 1024**3), "cpu"),+ ((None, 8 * 1024**3), "cpu"),+ ],+)+def test_same_model_discrete_group_uses_minimum_memory(+ config_file: Path,+ monkeypatch: pytest.MonkeyPatch,+ platform: str,+ duplicate_ep: bool,+ capacities: tuple[int | None, int | None],+ expected: str,+) -> None:+ """同型号多卡可按组确认独显,取最小容量;其他型号大卡不能替代。"""+ from mineru.model.runtime import onnx_calibration, vulkan, webgpu++ monkeypatch.setattr(policy, "sys", SimpleNamespace(platform=platform))+ monkeypatch.setattr(webgpu, "sys", SimpleNamespace(platform=platform))+ monkeypatch.setattr(+ policy,+ "discover_gpus",+ Mock(+ return_value=(+ adapter(index=0, uma=False, memory=capacities[0]),+ adapter(index=1, uma=False, memory=capacities[1]),+ adapter(index=2, uma=False, vendor=0x10DE, memory=24 * 1024**3, rank=2),+ )+ ),+ )+ descriptor = WebGPUDevice(0x8086, 0x56A0)+ monkeypatch.setattr(policy, "discover_webgpu_devices", Mock(return_value=(descriptor,) * (2 if duplicate_ep else 1)))+ monkeypatch.setattr(+ vulkan,+ "enumerate_vulkan_devices",+ Mock(+ return_value=(+ vulkan.VulkanDevice(0x8086, 0x56A0, "GPU", kind="discrete", dedicated_memory_bytes=capacities[0]),+ vulkan.VulkanDevice(0x8086, 0x56A0, "GPU", kind="discrete", dedicated_memory_bytes=capacities[1]),+ vulkan.VulkanDevice(0x10DE, 2, "other", kind="discrete", dedicated_memory_bytes=24 * 1024**3),+ )+ ),+ )+ selected = device_state.resolve_runtime_device().selection+ assert selected.device == expected+ if expected == "gpu":+ assert selected.reason == "discrete_gpu"+ assert selected.adapter.dedicated_memory_bytes == min(capacities)+ onnx_calibration.run_calibration.assert_not_called()+++def test_linux_native_discovery_error_returns_cpu_without_calibration(+ linux_config: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """自动模式原生探测失败直接选 CPU,不把失败当作待校准候选。"""+ from mineru.model.runtime import onnx_calibration, vulkan++ monkeypatch.setattr(vulkan, "enumerate_vulkan_devices", Mock(side_effect=OSError("driver unavailable")))+ assert device_state.resolve_runtime_device().selection.reason == "selection_failed"+ onnx_calibration.run_calibration.assert_not_called()+++def test_low_memory_cpu_is_shared_with_llama_and_tiers(config_file: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ """低显存独显的 CPU 结论由进程缓存共享,llama 和档位不重新选择 GPU。"""+ from mineru.model.runtime import llama_device, onnx_calibration, tier_recommendation++ monkeypatch.setattr(policy, "discover_gpus", Mock(return_value=(adapter(uma=False, memory=2 * 1024**3),)))+ monkeypatch.setattr(llama_device, "sys", SimpleNamespace(platform="win32"))+ monkeypatch.delenv("MINERU_LLAMA_CPP_BACKEND", raising=False)+ monkeypatch.setattr(settings.get_config().model.vlm, "engine", "llama-cpp")+ monkeypatch.setattr(tier_recommendation, "effective_cpu_count", lambda: 8)+ selected = device_state.resolve_runtime_device()+ assert selected.is_cpu+ assert llama_device.resolve_llama_device().device == "cpu"+ assert tier_recommendation.recommend_tiers().pdf_image_tiers == ("flash", "basic")+ policy.discover_gpus.assert_called_once()+ onnx_calibration.run_calibration.assert_not_called()diff --git a/tests/unittest/test_tier_recommendation.py b/tests/unittest/test_tier_recommendation.pyindex 6b6bc72b..c082edf2 100644--- a/tests/unittest/test_tier_recommendation.py+++ b/tests/unittest/test_tier_recommendation.py@@ -27,7 +27,7 @@ from mineru.types import TIERS@pytest.fixture(autouse=True)def onnx_recommendation_backend(monkeypatch: pytest.MonkeyPatch) -> Iterator[None]:"""本文件验证 ONNX 既有推荐规则,隔离宿主可能自动选择的 Torch 后端。"""- from mineru.model.runtime import gpu_memory, llama_probe+ from mineru.model.runtime import llama_probeimport subprocessforbidden = Mock(side_effect=AssertionError("recommendation must not probe llama devices"))@@ -46,11 +46,7 @@ def onnx_recommendation_backend(monkeypatch: pytest.MonkeyPatch) -> Iterator[Nonmonkeypatch.setattr(get_config().model, "onnx_device", "auto")monkeypatch.setattr(get_config().model.vlm, "engine", "llama-cpp")monkeypatch.setattr(device_state, "_states", {})- memory_probe = Mock(side_effect=AssertionError("recommendation must not query GPU memory"))- monkeypatch.setattr(gpu_memory, "native_gpu_memory", memory_probe)- monkeypatch.setattr(gpu_memory, "torch_gpu_memory", memory_probe)yield- memory_probe.assert_not_called()forbidden.assert_not_called()@@ -110,7 +106,10 @@ def evidence_path(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:def _adapter() -> GpuAdapter:"""构造具有稳定物理身份的集显。"""- return with_gpu_classification(GpuAdapter(0, "physical-id", "integrated", 0x8086, 0x7D51, 0), classify_d3d12_gpu(True))+ return with_gpu_classification(+ GpuAdapter(0, "physical-id", "integrated", 0x8086, 0x7D51, 0, dedicated_memory_bytes=8 * 1024**3),+ classify_d3d12_gpu(True),+ )def _measurement(**overrides: Any) -> dict[str, Any]:@@ -230,7 +229,7 @@ def startup_calibration(monkeypatch.setattr(vulkan,"enumerate_vulkan_devices",- lambda: (with_gpu_classification(vulkan.VulkanDevice(0x8086, 0x7D51, "test"), classify_vulkan_gpu(1)),),+ lambda **_: (with_gpu_classification(vulkan.VulkanDevice(0x8086, 0x7D51, "test"), classify_vulkan_gpu(1)),),)monkeypatch.setattr(recommendation, "effective_cpu_count", lambda: 8)monkeypatch.setattr(device_state, "_states", {})@@ -350,7 +349,11 @@ def test_low_cpu_advanced_recommendation_still_selects_device(monkeypatch.setattr(vulkan,"enumerate_vulkan_devices",- lambda: (with_gpu_classification(vulkan.VulkanDevice(0x8086, 0x7D51, "test"), classify_vulkan_gpu(2)),),+ lambda **_: (+ with_gpu_classification(+ vulkan.VulkanDevice(0x8086, 0x7D51, "test", dedicated_memory_bytes=8 * 1024**3), classify_vulkan_gpu(2)+ ),+ ),)report = recommendation.recommend_tiers()assert frozenset(report.pdf_image_tiers) == frozenset(TIERS)@@ -564,26 +567,22 @@ def test_cpu_count_failure_does_not_disable_selected_gpu(configured_gpu[1].assert_not_called()[email protected]("amount", [None, 1024**3, "error"])-def test_onnx_recommendation_without_torch_or_memory_queries(- configured_gpu: tuple[Path, Mock], monkeypatch: pytest.MonkeyPatch, amount: int | str | None+def test_onnx_configured_gpu_recommendation_without_torch(+ configured_gpu: tuple[Path, Mock], monkeypatch: pytest.MonkeyPatch) -> None:- """未安装 Torch 时自动选择 ONNX,显存偏小、未知或查询异常均不参与推荐。"""+ """未安装 Torch 时采用已配置的 ONNX GPU,不增加第二次设备探测。"""from mineru.config import get_config- from mineru.model.runtime import device, gpu_memory+ from mineru.model.runtime import devicemonkeypatch.setattr(get_config().model, "small_backend", "auto")monkeypatch.setitem(sys.modules, "torch", None)monkeypatch.setitem(sys.modules, "torchvision", None)torch_probe = Mock(side_effect=AssertionError("ONNX recommendation must not probe Torch"))monkeypatch.setattr(device, "resolve_torch_device", torch_probe)- memory = Mock(return_value=amount, side_effect=RuntimeError("memory unavailable") if amount == "error" else None)- monkeypatch.setattr(gpu_memory, "native_gpu_memory", memory)report = recommendation.recommend_tiers()assert report.small_backend == "onnx" and report.device.endswith(":gpu")assert report.pdf_image_tiers == TIERS and report.gpu_memory is Noneassert not report.warnings- memory.assert_not_called()torch_probe.assert_not_called()configured_gpu[1].assert_not_called()@@ -600,6 +599,7 @@ def test_shared_classification_preserves_existing_calibration_fingerprint(evidenelse {"vendor_id", "device_id", "metadata", "vulkan_device"})assert cache.calibrated_gpu_is_faster(replace(adapter, kind="unknown", kind_source="new_probe"), 0.8)+ assert cache.calibrated_gpu_is_faster(replace(adapter, dedicated_memory_bytes=4 * 1024**3), 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 84ff8bee..3d013e2c 100644--- a/tests/unittest/test_webgpu_architecture.py+++ b/tests/unittest/test_webgpu_architecture.py@@ -91,7 +91,7 @@ def test_amd_nvidia_ids_never_use_intel_mapping(vendor: int, monkeypatch: pytestmonkeypatch.setattr(vulkan,"enumerate_vulkan_devices",- lambda: (with_gpu_classification(vulkan.VulkanDevice(vendor, 0x4680, "GPU"), classify_vulkan_gpu(1)),),+ 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,)) == with_gpu_classification(descriptor, classify_vulkan_gpu(1))@@ -139,7 +139,7 @@ def test_mixed_host_selects_and_binds_eligible_gpu(monkeypatch.setattr(vulkan,"enumerate_vulkan_devices",- lambda: (+ lambda **_: (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)),),@@ -156,7 +156,7 @@ def test_icd_exclusion_cannot_be_bypassed_by_ort_inventory(monkeypatch: pytest.Mmonkeypatch.setattr(vulkan,"enumerate_vulkan_devices",- lambda: (with_gpu_classification(vulkan.VulkanDevice(0x8086, 0x4680, "Intel-only ICD"), classify_vulkan_gpu(1)),),+ 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@@ -172,7 +172,7 @@ def test_multiple_good_candidates_prefer_discrete_gpu(monkeypatch: pytest.Monkeymonkeypatch.setattr(vulkan,"enumerate_vulkan_devices",- lambda: (+ lambda **_: (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)),@@ -188,7 +188,7 @@ def test_ambiguous_device_identity_does_not_confirm_discrete(monkeypatch: pytestdescriptor = 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,)+ 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"@@ -227,10 +227,10 @@ def test_windows_dml_does_not_apply_linux_policy(monkeypatch: pytest.MonkeyPatch@pytest.mark.parametrize("device_id", [0x7D51, 0x7D55, 0x56A0, 0x64A0, 0xE20B, 0xB080])@pytest.mark.parametrize("device_type", [1, 2, None])-def test_modern_intel_auto_calibrates_according_to_vulkan_type(+def test_modern_intel_auto_respects_vulkan_type_and_probe_failure(monkeypatch: pytest.MonkeyPatch, device_id: int, device_type: int | None) -> None:- """架构白名单只决定兼容性,是否免校准由实际 Vulkan 类型独立决定。"""+ """架构兼容后仍按类型和总容量选型,原生枚举失败则交由上层直接回退 CPU。"""from mineru.model.runtime import onnx_calibrationfrom mineru.model import registry@@ -243,7 +243,8 @@ def test_modern_intel_auto_calibrates_according_to_vulkan_type(Mock(return_value=(with_gpu_classification(- vulkan.VulkanDevice(0x8086, device_id, "Intel GPU"), classify_vulkan_gpu(device_type or 1)+ vulkan.VulkanDevice(0x8086, device_id, "Intel GPU", dedicated_memory_bytes=8 * 1024**3),+ classify_vulkan_gpu(device_type or 1),),),side_effect=OSError("type unavailable") if device_type is None else None,@@ -252,6 +253,11 @@ def test_modern_intel_auto_calibrates_according_to_vulkan_type(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)+ if device_type is None:+ with pytest.raises(OSError, match="type unavailable"):+ onnx_device._select("auto", 4, 1)+ measure.assert_not_called()+ returnselected, completed = onnx_device._select("auto", 4, 1)assert selected.device == "gpu"if device_type == 2:@@ -313,7 +319,7 @@ def test_ignored_filters_fail_before_creating_a_gpu_session(monkeypatch: pytest.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))+ monkeypatch.setattr(vulkan, "enumerate_vulkan_devices", lambda **_: (old, good))factory = Mock(side_effect=AssertionError("unsafe native session"))monkeypatch.setattr(onnx.ort, "InferenceSession", factory)with pytest.raises(RuntimeError, match="Cannot restrict"):@@ -332,7 +338,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 = with_gpu_classification(vulkan.VulkanDevice(0x10DE, 0x2489, "NVIDIA"), classify_vulkan_gpu(2))- monkeypatch.setattr(vulkan, "enumerate_vulkan_devices", lambda: (good,))+ monkeypatch.setattr(vulkan, "enumerate_vulkan_devices", lambda **_: (good,))snapshot = dict(os.environ)def attached(*_: object) -> None:diff --git a/tests/unittest/test_webgpu_runtime.py b/tests/unittest/test_webgpu_runtime.pyindex 0d6fe35e..1dad8d7c 100644--- a/tests/unittest/test_webgpu_runtime.py+++ b/tests/unittest/test_webgpu_runtime.py@@ -53,11 +53,15 @@ def test_registration_is_lazy_once_per_process_and_filters_virtual_devices(monkedef test_production_options_resolve_native_handles_locally(monkeypatch: pytest.MonkeyPatch) -> None:+ """容量证据不影响运行时匹配原生句柄,且可随描述符序列化。"""ep = 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, with_gpu_classification(replace(device(), vulkan_device=(0x1002, 1)), classify_vulkan_gpu(2))+ options,+ with_gpu_classification(+ replace(device(), vulkan_device=(0x1002, 1), dedicated_memory_bytes=8 * 1024**3), classify_vulkan_gpu(2)+ ),)options.add_provider_for_devices.assert_called_once_with([ep], webgpu.WEBGPU_OPTIONS)descriptor = json.loads(json.dumps(asdict(device())))@@ -66,6 +70,7 @@ 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,+ "dedicated_memory_bytes": None,"kind": "unknown","kind_source": "unknown","unified_memory": None,