Transforms complex documents like PDFs and Office docs into LLM-ready markdown/JSON for your Agentic workflows.
Python ai4sciencedocument-analysisdocxextract-datalayout-analysisocrparserpdfpdf-converterpdf-extractor-llmpdf-extractor-pretrainpdf-extractor-ragpdf-parserpptxpythonxlsx
fix(runtime): match Windows GPU memory by physical PCI identity
myhloli250212946d77
diff --git a/docs/next/cli/mineru-kit-hardware.md b/docs/next/cli/mineru-kit-hardware.mdindex 36ca0a66..32f772c4 100644--- a/docs/next/cli/mineru-kit-hardware.md+++ b/docs/next/cli/mineru-kit-hardware.md@@ -27,6 +27,8 @@ mineru-kit hardware info --json > hardware-info.json内存检查只使用确认设备的原始字节值,不四舍五入、不累加多卡,也不读取 `MINERU_VIRTUAL_VRAM_SIZE`。独显按专用显存总量判断;Apple Metal 按推荐工作集预算,Windows 集显按 DXGI 本地预算,Linux 集显按 Vulkan `heapBudget` 判断。预算比较使用上限,不减去当前用量。不能唯一关联设备、容量未知、预算扩展不可用或查询失败时按 CPU 条件推荐;系统总内存和共享内存理论上限不能替代 GPU 预算。+Windows 原生查询不依赖 Torch。DXGI 库存通过系统 `D3DKMTOpenAdapterFromLuid` / `D3DKMTQueryAdapterInfo(KMTQAITYPE_ADAPTERADDRESS)` 补充物理 PCI 位置,内存仍来自该适配器的 DXGI 查询。ONNX 已选设备按 LUID 关联;可选 Torch/ROCm 后端的整数 PCI 字段作为部分坐标参与关联,不把 bus 编号当作完整 BDF,不猜测缺失的 domain/function。匹配优先采用 LUID 和已知 PCI 坐标,最后才使用唯一型号或名称;同名但无物理地址的条目不能覆盖明确的 PCI 匹配。无效地址、查询失败或多个同等匹配继续保留未知,不按容量大小或枚举顺序猜测。可用性和实际推理验证仍由各后端负责,读取预算成功不代表模型推理已验证。+`small_backend=auto` 最终选择 Torch 时同样免校准。显式设备字符串必须经过实际可用性检查;检查失败会给出保守结果及原因,不修改设备配置。Torch 推荐不依赖 llama.cpp 库存,不下载 ONNX 校准权重,也不写入 `model.onnx_device` 或 OCR 校准记录。ONNX 分支保留既有兼容策略、0.8 阈值和进程缓存。Windows 确认的独显,以及 Linux 通过兼容检查、由 Vulkan 唯一识别并配置物理绑定的独显,均免 OCR 校准,报告 `status=skipped, reason=discrete_gpu`;首次真实 GPU 会话成功后才保存 `gpu`,硬件推荐本身不生成校准记录。`onnx_device=auto` 时,集显或类型无法确认的候选继续沿用现有设备选型测速,首次可能下载 OCR rec 模型;下载和派生图准备不计入 15 秒校准 worker 超时。校准失败、超时或不稳定导致本次设备选型回退 CPU 时,按 CPU 条件推荐,并携带警告。diff --git a/mineru/model/runtime/gpu.py b/mineru/model/runtime/gpu.pyindex a138f44c..181d8415 100644--- a/mineru/model/runtime/gpu.py+++ b/mineru/model/runtime/gpu.py@@ -21,6 +21,23 @@ class GpuClassification:unified_memory: bool | None = None+@dataclass(frozen=True)+class PciAddress:+ """PCI 物理位置;未提供的 domain/function 保留未知,不猜测为零。"""++ bus: int+ device: int+ domain: int | None = None+ function: int | None = None++ def __post_init__(self) -> None:+ if self.bus is None or self.device is None:+ raise ValueError("PCI bus and device are required")+ for value, maximum in ((self.bus, 255), (self.device, 31), (self.domain, 65535), (self.function, 7)):+ if value is not None and (type(value) is not int or not 0 <= value <= maximum):+ raise ValueError("Invalid PCI address")++@dataclass(frozen=True)class GpuIdentity:"""只使用已有设备身份;名称仅可用于原生库存之间的唯一关联。"""@@ -30,6 +47,7 @@ class GpuIdentity:luid: str | None = Nonebus_id: str | None = Nonename: str | None = None+ pci_address: PciAddress | None = None_Gpu = TypeVar("_Gpu", bound=GpuClassification)@@ -89,28 +107,58 @@ def _normalized_bus_id(value: str) -> str:return value.lower()-def gpu_identities_match(left: GpuIdentity, right: GpuIdentity, *, allow_name: bool = False) -> bool:- """优先比较双方共有的强身份,存在冲突时不得退回型号或名称匹配。"""+def _pci_address(identity: GpuIdentity) -> PciAddress | None:+ """兼容既有完整 BDF 字符串与运行时只提供部分坐标的 PCI 地址。"""+ if identity.pci_address is not None:+ return identity.pci_address+ if isinstance(identity.bus_id, str):+ try:+ domain, bus, address = identity.bus_id.split(":")+ device, function = address.split(".")+ return PciAddress(int(bus, 16), int(device, 16), int(domain, 16), int(function, 16))+ except ValueError:+ pass+ return None+++def _identity_match_strength(left: GpuIdentity, right: GpuIdentity, *, allow_name: bool) -> int:+ """LUID、PCI 地址、型号、名称依次降级;共有身份冲突时禁止弱匹配。"""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+ return -1if left.luid and right.luid:- return left.luid.lower() == right.luid.lower()+ return 5 if left.luid.lower() == right.luid.lower() else -1+ left_pci, right_pci = _pci_address(left), _pci_address(right)+ if left_pci is not None and right_pci is not None:+ coordinates = (+ (left_pci.bus, right_pci.bus),+ (left_pci.device, right_pci.device),+ (left_pci.domain, right_pci.domain),+ (left_pci.function, right_pci.function),+ )+ shared = [(first, second) for first, second in coordinates if first is not None and second is not None]+ return len(shared) if all(first == second for first, second in shared) else -1if left.bus_id and right.bus_id:- return _normalized_bus_id(left.bus_id) == _normalized_bus_id(right.bus_id)+ return 4 if _normalized_bus_id(left.bus_id) == _normalized_bus_id(right.bus_id) else -1if 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)+ return 1+ return 0 if allow_name and left.name and left.name == right.name else -1+++def gpu_identities_match(left: GpuIdentity, right: GpuIdentity, *, allow_name: bool = False) -> bool:+ """优先比较双方共有的强身份,存在冲突时不得退回型号或名称匹配。"""+ return _identity_match_strength(left, right, allow_name=allow_name) >= 0def 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- ]+ candidates: list[list[int]] = []+ for source in sources:+ strengths = [_identity_match_strength(source, target, allow_name=allow_name) for target in targets]+ strongest = max(strengths, default=-1)+ candidates.append([index for index, strength in enumerate(strengths) if strength >= 0 and strength == strongest])return tuple(matches[0] if len(matches) == 1 and sum(matches[0] in other for other in candidates) == 1 else Nonefor matches in candidates@@ -122,6 +170,7 @@ __all__ = ["GpuClassification","GpuIdentity","GpuKind",+ "PciAddress","classify_d3d12_gpu","classify_macos_gpu","classify_vulkan_gpu",diff --git a/mineru/model/runtime/gpu_memory.py b/mineru/model/runtime/gpu_memory.pyindex 2c731b86..1a5b756b 100644--- a/mineru/model/runtime/gpu_memory.py+++ b/mineru/model/runtime/gpu_memory.py@@ -7,7 +7,7 @@ from dataclasses import dataclass, replaceimport sysfrom typing import Literal-from .gpu import GpuIdentity, match_gpu_identities+from .gpu import GpuIdentity, PciAddress, match_gpu_identitiesMIN_GPU_MEMORY_BYTES = 11 * 1024**3 // 2 # 5.5 GiB,始终使用整数字节比较。@@ -44,7 +44,16 @@ def native_gpu_memory(identity: GpuIdentity, *, device: str) -> GpuMemory:from .windows_gpu import inspect_gpusrows = inspect_gpus(include_memory_budget=True)- identities = [GpuIdentity(row["vendor_id"], row["device_id"], luid=row["luid"], name=row["name"]) for row in rows]+ 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]@@ -103,11 +112,21 @@ def torch_gpu_memory(device: str) -> GpuMemory: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=getattr(properties, "pci_bus_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):diff --git a/mineru/model/runtime/windows_gpu.py b/mineru/model/runtime/windows_gpu.pyindex 4680b509..3bcc4d1c 100644--- a/mineru/model/runtime/windows_gpu.py+++ b/mineru/model/runtime/windows_gpu.py@@ -9,7 +9,7 @@ import sysfrom typing import Anyimport uuid-from .gpu import GpuClassification, GpuIdentity, classify_d3d12_gpu, gpu_kind_rank, with_gpu_classification+from .gpu import GpuClassification, GpuIdentity, PciAddress, classify_d3d12_gpu, gpu_kind_rank, with_gpu_classification@dataclass(frozen=True)@@ -41,6 +41,48 @@ class _Luid(C.Structure):_fields_ = [("low", C.c_uint32), ("high", C.c_int32)]+class _OpenAdapterFromLuid(C.Structure):+ _fields_ = [("luid", _Luid), ("handle", C.c_uint32)]+++class _QueryAdapterInfo(C.Structure):+ _fields_ = [("handle", C.c_uint32), ("type", C.c_int32), ("data", C.c_void_p), ("size", C.c_uint32)]+++class _AdapterAddress(C.Structure):+ _fields_ = [("bus", C.c_uint32), ("device", C.c_uint32), ("function", C.c_uint32)]+++class _CloseAdapter(C.Structure):+ _fields_ = [("handle", C.c_uint32)]+++def _pci_address(luid: _Luid) -> PciAddress:+ """以 DXGI LUID 查询同一适配器的物理 PCI 地址,不加载任何推理后端。"""+ library = C.WinDLL("gdi32", use_last_error=True)+ open_adapter = library.D3DKMTOpenAdapterFromLuid+ open_adapter.argtypes, open_adapter.restype = [C.POINTER(_OpenAdapterFromLuid)], C.c_int32+ query_adapter = library.D3DKMTQueryAdapterInfo+ query_adapter.argtypes, query_adapter.restype = [C.POINTER(_QueryAdapterInfo)], C.c_int32+ close_adapter = library.D3DKMTCloseAdapter+ close_adapter.argtypes, close_adapter.restype = [C.POINTER(_CloseAdapter)], C.c_int32++ def check_status(status: int) -> None:+ if status < 0:+ raise OSError(f"Windows GPU PCI query failed: NTSTATUS=0x{status & 0xFFFFFFFF:08x}")++ opened = _OpenAdapterFromLuid(luid, 0)+ check_status(open_adapter(C.byref(opened)))+ try:+ address = _AdapterAddress()+ # KMTQAITYPE_ADAPTERADDRESS = 6; Windows 不提供 PCI domain,不能自行补零。+ query = _QueryAdapterInfo(opened.handle, 6, C.addressof(address), C.sizeof(address))+ check_status(query_adapter(C.byref(query)))+ return PciAddress(address.bus, address.device, function=address.function)+ finally:+ check_status(close_adapter(C.byref(_CloseAdapter(opened.handle))))++class _Description(C.Structure):_fields_ = [("name", C.c_wchar * 128),@@ -235,6 +277,11 @@ def inspect_gpus(*, include_memory_budget: bool = False) -> list[dict[str, Any]]if desc.flags & 2:continuesupported, uma = _architecture(adapter, create_device)+ pci_address, pci_error = None, None+ try:+ pci_address = _pci_address(desc.luid)+ except Exception as error:+ pci_error = str(error)budget, memory_error = None, Noneif include_memory_budget and uma is True:try:@@ -247,6 +294,8 @@ def inspect_gpus(*, include_memory_budget: bool = False) -> list[dict[str, Any]]"vendor_id": desc.vendor,"device_id": desc.device,"luid": _luid(desc),+ "pci_address": asdict(pci_address) if pci_address is not None else None,+ "pci_error": pci_error,"d3d12_available": supported,**asdict(classify_d3d12_gpu(uma)),"dedicated_memory_bytes": desc.video_memory,diff --git a/tests/unittest/test_gpu_memory.py b/tests/unittest/test_gpu_memory.pyindex 94e713fb..95b3c3e6 100644--- a/tests/unittest/test_gpu_memory.py+++ b/tests/unittest/test_gpu_memory.py@@ -12,7 +12,7 @@ from unittest.mock import Mockimport pytestfrom mineru.model.runtime import gpu_memory, vulkan, windows_gpu-from mineru.model.runtime.gpu import GpuIdentity+from mineru.model.runtime.gpu import GpuIdentity, PciAddress@pytest.mark.parametrize("device", ["cuda:1", "cuda"])@@ -114,6 +114,75 @@ def test_xpu_integrated_uses_native_budget(monkeypatch: pytest.MonkeyPatch) -> Nquery.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)++[email protected]("stage", ["success", "open", "query", "invalid", "close"])+def test_windows_pci_query_abi_and_handle_lifetime(monkeypatch: pytest.MonkeyPatch, stage: str) -> None:+ """验证系统接口结构布局,失败/无效地址均不伪造坐标,已打开句柄始终关闭。"""++ def open_adapter(output: Any) -> int:+ assert output._obj.luid.low == 0x1709C and output._obj.luid.high == 1+ output._obj.handle = 123+ return -1 if stage == "open" else 0++ def query_adapter(output: Any) -> int:+ query = output._obj+ assert query.handle == 123 and query.type == 6 and query.size == 12+ address = ct.cast(query.data, ct.POINTER(windows_gpu._AdapterAddress)).contents+ address.bus, address.device, address.function = (0xFFFFFFFF, 0xFFFF, 0xFFFF) if stage == "invalid" else (195, 0, 1)+ return -1 if stage == "query" else 0++ def close_adapter(output: Any) -> int:+ assert output._obj.handle == 123+ return -1 if stage == "close" else 0++ library = SimpleNamespace(+ D3DKMTOpenAdapterFromLuid=Mock(side_effect=open_adapter),+ D3DKMTQueryAdapterInfo=Mock(side_effect=query_adapter),+ D3DKMTCloseAdapter=Mock(side_effect=close_adapter),+ )+ monkeypatch.setattr(windows_gpu.C, "WinDLL", lambda *args, **kwargs: library, raising=False)+ if stage == "success":+ assert windows_gpu._pci_address(windows_gpu._Luid(0x1709C, 1)) == PciAddress(195, 0, function=1)+ else:+ with pytest.raises(ValueError if stage == "invalid" else OSError):+ windows_gpu._pci_address(windows_gpu._Luid(0x1709C, 1))+ assert library.D3DKMTCloseAdapter.call_count == int(stage != "open")+ assert ct.sizeof(windows_gpu._OpenAdapterFromLuid) == 12+ assert windows_gpu._QueryAdapterInfo.data.offset == 8++@pytest.mark.parametrize("native", [False, True])def test_memory_probe_errors_are_reported(monkeypatch: pytest.MonkeyPatch, native: bool) -> None:"""驱动异常输出未知容量和警告,不伪造零容量或吞掉原因。"""diff --git a/tests/unittest/test_gpu_policy.py b/tests/unittest/test_gpu_policy.pyindex e8910768..56166ae9 100644--- a/tests/unittest/test_gpu_policy.py+++ b/tests/unittest/test_gpu_policy.py@@ -19,6 +19,7 @@ from mineru.model.runtime.gpu import (GpuClassification,GpuIdentity,GpuKind,+ PciAddress,classify_d3d12_gpu,classify_macos_gpu,classify_vulkan_gpu,@@ -116,6 +117,29 @@ def test_identity_matching_requires_mutual_uniqueness() -> None:assert gpu_identities_match(GpuIdentity(bus_id="00000000:01:00.0"), GpuIdentity(bus_id="0000:01:00.0"))[email protected]("reverse", [False, True])+def test_physical_pci_match_beats_duplicate_name(reverse: bool) -> None:+ """有效 PCI 坐标优先于同名无物理地址的 DXGI 条目,不依赖枚举顺序。"""+ selected = GpuIdentity(name="8060S", pci_address=PciAddress(195, 0, domain=0))+ physical = GpuIdentity(0x1002, 5510, luid="physical", name="8060S", pci_address=PciAddress(195, 0, function=0))+ duplicate = replace(physical, luid="duplicate", pci_address=None)+ targets = (physical, duplicate) if not reverse else (duplicate, physical)+ assert match_gpu_identities((selected,), targets, allow_name=True) == (int(reverse),)+ assert match_gpu_identities((selected, selected), targets, allow_name=True) == (None, None)+++def test_partial_pci_address_does_not_guess_domain_or_function() -> None:+ """Torch 不提供 function、Windows 不提供 domain 时,只比较已知坐标并保留多解。"""+ selected = GpuIdentity(name="GPU", pci_address=PciAddress(195, 0, domain=0))+ function_zero = GpuIdentity(name="GPU", bus_id="0000:c3:00.0")+ function_one = replace(function_zero, bus_id="0000:c3:00.1")+ assert match_gpu_identities((selected,), (function_one,), allow_name=True) == (0,)+ assert match_gpu_identities((selected,), (function_zero, function_one), allow_name=True) == (None,)+ for conflict in ("0001:c3:00.0", "0000:c4:00.0", "0000:c3:01.0"):+ assert not gpu_identities_match(selected, replace(function_zero, bus_id=conflict), allow_name=True)+ assert not gpu_identities_match(replace(selected, luid="one"), replace(function_zero, luid="two"), allow_name=True)++@pytest.mark.parametrize("platform", ["linux", "win32"])def test_ambiguous_native_mapping_remains_unknown_everywhere(monkeypatch: pytest.MonkeyPatch, platform: str) -> None:"""同型号多卡无法关联到运行时和报告时,不能被标为确定独显。"""@@ -257,3 +281,31 @@ 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)+++def test_windows_memory_query_without_torch_or_other_inference_dependencies() -> None:+ """基础安装的 Windows 原生查询和 LUID 匹配无需导入任何推理后端。"""+ code = """+import importlib.abc+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+"""+ subprocess.run([sys.executable, "-c", code], check=True, capture_output=True, text=True, timeout=15)