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
Enhance device compatibility: add support for Intel XPU and update device detection logic
myhloli0334e313567a
diff --git a/docs/en/usage/quick_usage.md b/docs/en/usage/quick_usage.mdindex 30407c0e..267e2410 100644--- a/docs/en/usage/quick_usage.md+++ b/docs/en/usage/quick_usage.md@@ -22,8 +22,9 @@ mineru parse <input_path> --pages all -o <output_path>> [!NOTE]> Runtime acceleration is selected separately for the two model components, based on installed dependencies and detected devices:>-> - Small models use the Torch backend only when `torch`, `torchvision`, `transformers`, `accelerate`, and `safetensors` are **all** installed and a non-CPU device (CUDA/MPS/...) is detected; otherwise they run ONNX on CPU. Installing Torch alone is not enough.+> - Small models use the Torch backend only when `torch`, `torchvision`, `transformers`, `accelerate`, and `safetensors` are **all** installed and a non-CPU device (CUDA/XPU/MPS/...) is detected; otherwise they run ONNX on CPU. Installing Torch alone is not enough.> - The local VLM engine is chosen independently: macOS always uses llama.cpp; on an accelerator device Linux prefers vLLM, then an installed LMDeploy, and Windows uses LMDeploy; otherwise llama.cpp.+> - XPU is excluded from automatic LMDeploy selection: Linux uses an installed XPU-compatible vLLM, otherwise llama.cpp; Windows uses llama.cpp.> - Windows users who need CUDA acceleration should first visit the [PyTorch website](https://pytorch.org/get-started/locally/) and install accelerator-enabled `torch` and `torchvision` matching their CUDA version, then install the `mineru[full]` extras.After installation, confirm the runtimes actually in effect in your environment:diff --git a/docs/en/usage/tiers.md b/docs/en/usage/tiers.mdindex f003c7b0..709be4f0 100644--- a/docs/en/usage/tiers.md+++ b/docs/en/usage/tiers.md@@ -30,6 +30,8 @@ PDF and images support all four tiers. Office, OpenDocument, RTF, EPUB, OFD, HTMAutomatic selection uses installed dependencies and available devices. An explicit choice with missing dependencies fails instead of silently selecting another backend. ONNX small models run on CPU; VLM device selection is independent.+Intel XPU is excluded from automatic LMDeploy selection. Linux prefers an installed XPU-compatible vLLM and otherwise falls back to llama.cpp; Windows uses llama.cpp.+```yamlmodel:small_backend: autodiff --git a/docs/zh/usage/quick_usage.md b/docs/zh/usage/quick_usage.mdindex 6477396a..65b3c95a 100644--- a/docs/zh/usage/quick_usage.md+++ b/docs/zh/usage/quick_usage.md@@ -22,8 +22,9 @@ mineru parse <input_path> --pages all -o <output_path>> [!NOTE]> 运行时加速按两个模型组件分别选择,依据是已安装的依赖和检测到的设备:>-> - 小模型仅在 `torch`、`torchvision`、`transformers`、`accelerate`、`safetensors` **全部安装**且检测到非 CPU 设备(CUDA/MPS 等)时使用 Torch 后端,否则使用 ONNX(CPU)。只安装 Torch 并不足以启用。+> - 小模型仅在 `torch`、`torchvision`、`transformers`、`accelerate`、`safetensors` **全部安装**且检测到非 CPU 设备(CUDA/XPU/MPS 等)时使用 Torch 后端,否则使用 ONNX(CPU)。只安装 Torch 并不足以启用。> - 本地 VLM 引擎独立选择:macOS 固定使用 llama.cpp;加速卡设备上 Linux 优先 vLLM、其次已安装的 LMDeploy,Windows 使用 LMDeploy;否则使用 llama.cpp。+> - XPU 不会自动选择 LMDeploy:Linux 上安装了支持 XPU 的 vLLM 时使用 vLLM,否则使用 llama.cpp;Windows 上使用 llama.cpp。> - Windows 用户如需 CUDA 加速,请先前往 [PyTorch 官网](https://pytorch.org/get-started/locally/) 选择与 CUDA 版本匹配的命令安装支持加速的 `torch` 和 `torchvision`,再安装 `mineru[full]`。安装完成后,确认当前环境实际生效的运行时:diff --git a/docs/zh/usage/tiers.md b/docs/zh/usage/tiers.mdindex 4b4a4fae..d8fd5d95 100644--- a/docs/zh/usage/tiers.md+++ b/docs/zh/usage/tiers.md@@ -30,6 +30,8 @@ PDF 和图片可选四档。Office、OpenDocument、RTF、EPUB、OFD、HTML、CS自动选择依据已安装依赖和可用设备;显式指定的后端缺依赖时会报错,不会静默改用另一种。ONNX 小模型在 CPU 上执行,VLM 的设备选择独立。+Intel XPU 不会自动选择 LMDeploy。Linux 上安装了支持 XPU 的 vLLM 时优先使用 vLLM,否则回退 llama.cpp;Windows 上使用 llama.cpp。+```yamlmodel:small_backend: autodiff --git a/mineru/kit/router/workers.py b/mineru/kit/router/workers.pyindex 48960023..0af0e060 100644--- a/mineru/kit/router/workers.py+++ b/mineru/kit/router/workers.py@@ -95,31 +95,33 @@ def parse_local_gpus(value: str) -> list[str | None]:raise ValueError("--local-gpus must be auto, none, or a non-empty CSV")return devices- for env_name in ("CUDA_VISIBLE_DEVICES", "ASCEND_RT_VISIBLE_DEVICES"):- configured = os.getenv(env_name)- if configured:- normalized_config = configured.strip().lower()- if normalized_config == "all":- break- devices = [- item.strip()- for item in configured.split(",")- if item.strip() and item.strip().lower() not in {"-1", "none", "void"}- ]- if devices:- return devices- return [None]-device = get_device().split(":", 1)[0]if device in {"cpu", "mps"}:return [None]+ # 只继承当前设备族的掩码,避免把 CUDA/NPU 的编号写成 XPU 的可见设备限制。+ configured = os.getenv(visible_device_env_name(device))+ if configured and configured.strip().lower() != "all":+ devices = [+ item.strip()+ for item in configured.split(",")+ if item.strip() and item.strip().lower() not in {"-1", "none", "void"}+ ]+ return devices or [None]device_count = accelerator_device_count(device)return [str(index) for index in range(device_count)] if device_count > 0 else ["0"]-def visible_device_env_name() -> str:+# 非默认 CUDA 语义的设备族对应的可见设备环境变量;XPU 用 Level Zero 的 ZE_AFFINITY_MASK(索引 CSV 同构)。+_VISIBLE_DEVICE_ENV_NAMES: dict[str, str] = {+ "npu": "ASCEND_RT_VISIBLE_DEVICES",+ "xpu": "ZE_AFFINITY_MASK",+}+++def visible_device_env_name(device: str | None = None) -> str:"""根据当前设备族返回本地 worker 的可见设备环境变量名。"""- return "ASCEND_RT_VISIBLE_DEVICES" if get_device().split(":", 1)[0] == "npu" else "CUDA_VISIBLE_DEVICES"+ device_type = (get_device() if device is None else device).split(":", 1)[0]+ return _VISIBLE_DEVICE_ENV_NAMES.get(device_type, "CUDA_VISIBLE_DEVICES")@dataclass(frozen=True)diff --git a/mineru/model/layout/pp_doclayoutv2.py b/mineru/model/layout/pp_doclayoutv2.pyindex d05835fe..697d7a2f 100644--- a/mineru/model/layout/pp_doclayoutv2.py+++ b/mineru/model/layout/pp_doclayoutv2.py@@ -48,7 +48,7 @@ class _CpuSinePositionEmbedding(nn.Module):device: torch.device | None = None,dtype: torch.dtype = torch.float32,) -> torch.Tensor:- """避开 MPS 不支持的 float64 运算,复用官方 CPU 位置编码缓存。"""+ """避开 MPS 和部分 XPU 不支持的 float64 运算,复用官方 CPU 位置编码缓存。"""return self.embedding(width=width, height=height, device=torch.device("cpu"), dtype=dtype).to(device=device)@@ -81,8 +81,8 @@ class PPDocLayoutV2LayoutModel(PPDocLayoutV2PostProcessor):dtype=torch.float32,attn_implementation="eager" if torch.device(self.device).type == "mps" else None,)- if torch.device(self.device).type == "mps":- # 官方正弦编码内部使用 float64;只适配这个无参数模块,不切换整个模型的设备。+ if torch.device(self.device).type in {"mps", "xpu"}:+ # 官方正弦编码内部使用 float64,Arc 等 XPU 不支持;统一在 CPU 缓存这个无参数模块的结果。for layer in self.model.model.encoder.aifi:layer.position_embedding = _CpuSinePositionEmbedding(layer.position_embedding)# 同步加载器生成的非持久化 buffer;已经位于目标设备的参数不会再次复制。diff --git a/mineru/model/mfr/pp_formulanet/predict_formula.py b/mineru/model/mfr/pp_formulanet/predict_formula.pyindex 46f8000a..0ea2ce68 100644--- a/mineru/model/mfr/pp_formulanet/predict_formula.py+++ b/mineru/model/mfr/pp_formulanet/predict_formula.py@@ -77,7 +77,7 @@ class FormulaRecognizer(BaseOCRV20):if model_name == "PP-FormulaNet_plus-M" and self.device.type == "cpu":# CPU 仅使用增量缓存,attention 仍保持原有 eager 算子。self.net.head.use_growing_cache = True- if model_name == "PP-FormulaNet_plus-M" and self.device.type in {"mps", "cuda"}:+ if model_name == "PP-FormulaNet_plus-M" and self.device.type in {"mps", "cuda", "xpu"}:# 仅为经过适配的公式解码器启用快速 attention;CPU 和其他模型保持原路径。self.net.head.set_fast_attention()logger.info(diff --git a/mineru/model/runtime/device.py b/mineru/model/runtime/device.pyindex cbcac9ea..7e980a39 100644--- a/mineru/model/runtime/device.py+++ b/mineru/model/runtime/device.py@@ -8,6 +8,10 @@ import osfrom typing import Literal+# 通过 getattr(torch, name) 探测可用性的附加加速后端,按优先级排列;xpu 为 Intel GPU 原生后端。+PROBE_TORCH_DEVICE_APIS: tuple[str, ...] = ("xpu", "gcu", "musa", "mlu", "sdaa")++def get_device() -> str:"""返回显式配置或当前环境中可用的首选模型设备。"""configured_device = os.getenv("MINERU_DEVICE_MODE")@@ -36,7 +40,7 @@ def get_device() -> str:return "npu"except Exception:pass- for device_name in ("gcu", "musa", "mlu", "sdaa"):+ for device_name in PROBE_TORCH_DEVICE_APIS:try:device_api = getattr(torch, device_name)if device_api.is_available():@@ -73,4 +77,4 @@ def resolve_small_model_backend(backend: str | None = None) -> Literal["onnx", "return "onnx"-__all__ = ["TORCH_REQUIRED_MODULES", "get_device", "module_available", "resolve_small_model_backend"]+__all__ = ["PROBE_TORCH_DEVICE_APIS", "TORCH_REQUIRED_MODULES", "get_device", "module_available", "resolve_small_model_backend"]diff --git a/mineru/model/runtime/memory.py b/mineru/model/runtime/memory.pyindex 339222be..06736bb8 100644--- a/mineru/model/runtime/memory.py+++ b/mineru/model/runtime/memory.py@@ -12,6 +12,8 @@ from typing import Anyfrom loguru import logger+from .device import PROBE_TORCH_DEVICE_APIS+@lru_cache(maxsize=1)def _get_malloc_trim() -> Callable[[int], int] | None:@@ -72,7 +74,7 @@ def clean_memory(device: str = "cuda") -> None:elif device_name.startswith("mps"):torch.mps.empty_cache()else:- for accelerator_name in ("gcu", "musa", "mlu", "sdaa"):+ for accelerator_name in PROBE_TORCH_DEVICE_APIS:if not device_name.startswith(accelerator_name):continueaccelerator = getattr(torch, accelerator_name, None)@@ -109,7 +111,7 @@ def get_vram(device: str) -> int:return round(torch.cuda.get_device_properties(device).total_memory / (1024**3))if device_name.startswith("npu") and torch_npu is not None and torch_npu.npu.is_available():return round(torch_npu.npu.get_device_properties(device).total_memory / (1024**3))- for accelerator_name in ("gcu", "musa", "mlu", "sdaa"):+ for accelerator_name in PROBE_TORCH_DEVICE_APIS:if not device_name.startswith(accelerator_name):continueaccelerator = getattr(torch, accelerator_name, None)diff --git a/mineru/model/vlm/selector.py b/mineru/model/vlm/selector.pyindex c71cf9cb..35f67148 100644--- a/mineru/model/vlm/selector.py+++ b/mineru/model/vlm/selector.py@@ -43,11 +43,13 @@ def resolve_vlm_engine(engine: str | None = None) -> VlmEngineName:# macOS 和未知平台固定优先 llama;不探测或自动导入 MLX。if not (is_linux_environment() or is_windows_environment()):return "llama-cpp"- if get_device().split(":")[0] == "cpu":+ device_type = get_device().split(":", 1)[0]+ if device_type == "cpu":return "llama-cpp"if is_linux_environment() and module_available("vllm"):return "vllm"- if module_available("lmdeploy"):+ # 当前 LMDeploy 接入不支持 Intel XPU;保留 Linux 的 vLLM 优先级,其余 XPU 回退 llama。+ if device_type != "xpu" and module_available("lmdeploy"):return "lmdeploy"return "llama-cpp"diff --git a/tests/unittest/test_model_backend_selection.py b/tests/unittest/test_model_backend_selection.pyindex 55fb797c..13cfeee6 100644--- a/tests/unittest/test_model_backend_selection.py+++ b/tests/unittest/test_model_backend_selection.py@@ -40,6 +40,12 @@ except ModuleNotFoundError:("linux", "cpu", {"torch", "vllm"}, "onnx", "llama-cpp"),("win32", "cpu", {"torch", "lmdeploy"}, "onnx", "llama-cpp"),("other", "npu", {"torch"}, "torch", "llama-cpp"),+ ("linux", "xpu", {"torch"}, "torch", "llama-cpp"),+ ("linux", "xpu", {"torch", "vllm"}, "torch", "vllm"),+ ("linux", "xpu", {"torch", "lmdeploy"}, "torch", "llama-cpp"),+ ("linux", "xpu:1", {"torch", "vllm", "lmdeploy"}, "torch", "vllm"),+ ("win32", "xpu", {"torch", "lmdeploy"}, "torch", "llama-cpp"),+ ("win32", "xpu:1", {"torch", "vllm", "lmdeploy"}, "torch", "llama-cpp"),],)def test_automatic_platform_combinations(diff --git a/tests/unittest/test_runtime_device.py b/tests/unittest/test_runtime_device.pynew file mode 100644index 00000000..5052a68b--- /dev/null+++ b/tests/unittest/test_runtime_device.py@@ -0,0 +1,79 @@+"""验证设备探测顺序与 XPU 的缓存释放、显存探测分支。"""++from __future__ import annotations++import sys+from types import SimpleNamespace+from unittest.mock import Mock++import pytest++from mineru.model.runtime.device import get_device+from mineru.model.runtime.memory import clean_memory, get_vram+++def _accelerator_api(available: bool) -> SimpleNamespace:+ """构造只包含设备可用性查询的加速器 API 替身。"""+ return SimpleNamespace(is_available=lambda: available)+++def _fake_torch(xpu_available: bool = True, generic_available: bool = True) -> SimpleNamespace:+ """构造只暴露探测与缓存释放所需 API 的 torch 替身。"""+ return SimpleNamespace(+ cuda=_accelerator_api(False),+ backends=SimpleNamespace(mps=_accelerator_api(False)),+ xpu=_accelerator_api(xpu_available),+ gcu=_accelerator_api(generic_available),+ musa=_accelerator_api(generic_available),+ mlu=_accelerator_api(generic_available),+ sdaa=_accelerator_api(generic_available),+ )+++def _install_fake_torch(monkeypatch: pytest.MonkeyPatch, fake_torch: SimpleNamespace) -> None:+ """隔离设备环境变量与可选 NPU 扩展,安装测试用 torch 替身。"""+ monkeypatch.delenv("MINERU_DEVICE_MODE", raising=False)+ monkeypatch.delenv("MINERU_VIRTUAL_VRAM_SIZE", raising=False)+ monkeypatch.setitem(sys.modules, "torch", fake_torch)+ # sys.modules 中置 None 使 import torch_npu 直接抛 ImportError,避免宿主环境干扰探测顺序。+ monkeypatch.setitem(sys.modules, "torch_npu", None)+++def test_get_device_probes_xpu_before_generic_accelerators(monkeypatch: pytest.MonkeyPatch) -> None:+ """xpu 可用时优先于国产加速后端命中。"""+ _install_fake_torch(monkeypatch, _fake_torch())+ assert get_device() == "xpu"+++def test_get_device_falls_back_to_cpu_without_accelerators(monkeypatch: pytest.MonkeyPatch) -> None:+ """xpu 与国产后端都不可用时回退 CPU。"""+ _install_fake_torch(monkeypatch, _fake_torch(xpu_available=False, generic_available=False))+ assert get_device() == "cpu"+++def test_configured_device_overrides_autodetect(monkeypatch: pytest.MonkeyPatch) -> None:+ """MINERU_DEVICE_MODE 显式配置优先于任何探测结果。"""+ _install_fake_torch(monkeypatch, _fake_torch())+ monkeypatch.setenv("MINERU_DEVICE_MODE", "cpu")+ assert get_device() == "cpu"+++def test_clean_memory_releases_xpu_cache(monkeypatch: pytest.MonkeyPatch) -> None:+ """xpu 设备调用 torch.xpu.empty_cache 释放框架缓存。"""+ empty_cache = Mock()+ fake_torch = _fake_torch()+ fake_torch.xpu = SimpleNamespace(is_available=lambda: True, empty_cache=empty_cache)+ _install_fake_torch(monkeypatch, fake_torch)+ clean_memory("xpu")+ empty_cache.assert_called_once_with()+++def test_get_vram_reads_xpu_total_memory(monkeypatch: pytest.MonkeyPatch) -> None:+ """xpu 显存按 get_device_properties().total_memory 换算为整数 GB。"""+ fake_torch = _fake_torch()+ fake_torch.xpu = SimpleNamespace(+ is_available=lambda: True,+ get_device_properties=lambda device: SimpleNamespace(total_memory=12 * 1024**3 + 200 * 1024**2),+ )+ _install_fake_torch(monkeypatch, fake_torch)+ assert get_vram("xpu") == 12diff --git a/tests/unittest/test_transformers5_models.py b/tests/unittest/test_transformers5_models.pyindex 2cde6c6f..966d7497 100644--- a/tests/unittest/test_transformers5_models.py+++ b/tests/unittest/test_transformers5_models.py@@ -213,21 +213,65 @@ def test_layout_configuration_constructs_the_inference_graph() -> None:assert any(True for _ in model.parameters())[email protected](not torch.backends.mps.is_available(), reason="requires Apple Silicon MPS")-def test_layout_position_embedding_preserves_native_math_on_mps() -> None:- """MPS 路径仍使用官方位置编码数值,并且没有新增或改名的模型权重。"""[email protected]("device", ["cpu", "mps", "xpu"])+def test_layout_position_embedding_preserves_native_math(device: str) -> None:+ """CPU/MPS/XPU 包装保持官方位置编码数值,且没有新增或改名的模型权重。"""from transformers.models.pp_doclayout_v2.modeling_pp_doclayout_v2 import PPDocLayoutV2SinePositionEmbeddingfrom mineru.model.layout.pp_doclayoutv2 import _CpuSinePositionEmbedding+ if device == "mps" and not torch.backends.mps.is_available():+ pytest.skip("requires Apple Silicon MPS")+ if device == "xpu" and not torch.xpu.is_available():+ pytest.skip("requires Intel XPU")native = PPDocLayoutV2SinePositionEmbedding(embed_dim=16)adapter = _CpuSinePositionEmbedding(native)- actual = adapter(width=3, height=2, device=torch.device("mps"))+ actual = adapter(width=3, height=2, device=torch.device(device))expected = native(width=3, height=2, device=torch.device("cpu"), dtype=torch.float32)- assert actual.device.type == "mps"+ assert actual.device.type == devicetorch.testing.assert_close(actual.cpu(), expected, rtol=0, atol=0)assert not adapter.state_dict()[email protected]("device", ["cpu", "cuda", "cuda:1", "mps", "xpu", "xpu:1"])+def test_layout_loader_adapts_position_embeddings_for_mps_and_xpu(+ monkeypatch: pytest.MonkeyPatch, device: str+) -> None:+ """覆盖真实加载入口的设备分支,验证 XPU 编号设备也采用 CPU 正弦编码。"""+ from types import SimpleNamespace+ from unittest.mock import Mock++ from transformers.models.pp_doclayout_v2.modeling_pp_doclayout_v2 import PPDocLayoutV2SinePositionEmbedding+ from mineru.model.layout import pp_doclayoutv2 as layout++ native = PPDocLayoutV2SinePositionEmbedding(embed_dim=16)+ layer = SimpleNamespace(position_embedding=native)+ model = Mock()+ model.model.encoder.aifi = [layer]+ config = Mock()+ load = Mock(return_value=model)+ monkeypatch.setattr(layout, "load_preprocess_config", lambda _path: {})+ monkeypatch.setattr(layout.PPDocLayoutV2Config, "from_pretrained", Mock(return_value=config))+ monkeypatch.setattr(layout.PPDocLayoutV2ForObjectDetection, "from_pretrained", load)++ layout.PPDocLayoutV2LayoutModel("local-checkpoint", device=device)++ assert load.call_args.kwargs["device_map"] == {"": device}+ model.to.assert_called_once_with(device)+ model.eval.assert_called_once_with()+ if torch.device(device).type in {"mps", "xpu"}:+ assert isinstance(layer.position_embedding, layout._CpuSinePositionEmbedding)+ # 使用 meta 作为无硬件目标,真实 CPU 算子计算后只将结果送到目标设备。+ embedding_forward = Mock(wraps=native.forward)+ monkeypatch.setattr(native, "forward", embedding_forward)+ result = layer.position_embedding(width=7, height=5, device=torch.device("meta"), dtype=torch.float16)+ assert result.device.type == "meta"+ assert result.dtype == torch.float16+ assert result.shape == (1, 35, 16)+ embedding_forward.assert_called_once_with(width=7, height=5, device=torch.device("cpu"), dtype=torch.float16)+ else:+ assert layer.position_embedding is native++@pytest.mark.parametrize("device", ["cpu", "mps", "cuda"])def test_unimernet_stages_only_mps_weights_on_cpu(monkeypatch: pytest.MonkeyPatch, device: str) -> None:"""MPS 在目标精度下经 CPU 物化后串行搬运,CPU/CUDA 保持直接加载。"""diff --git a/tests/unittest/test_v1_router.py b/tests/unittest/test_v1_router.pyindex e410e67d..f8c9a503 100644--- a/tests/unittest/test_v1_router.py+++ b/tests/unittest/test_v1_router.py@@ -903,6 +903,66 @@ def test_auto_local_gpus_expands_visible_accelerator_count(monkeypatch: pytest.Massert parse_local_gpus("auto") == ["0", "1", "2"]+def test_xpu_local_gpus_use_level_zero_affinity_mask(monkeypatch: pytest.MonkeyPatch) -> None:+ """验证 XPU worker 通过 ZE_AFFINITY_MASK 继承与隔离可见设备。"""+ import mineru.kit.router.workers as workers++ monkeypatch.delenv("CUDA_VISIBLE_DEVICES", raising=False)+ monkeypatch.delenv("ASCEND_RT_VISIBLE_DEVICES", raising=False)+ monkeypatch.delenv("ZE_AFFINITY_MASK", raising=False)+ monkeypatch.setattr(workers, "get_device", lambda: "xpu")+ assert workers.visible_device_env_name() == "ZE_AFFINITY_MASK"++ monkeypatch.setattr(workers, "accelerator_device_count", lambda _device: 2)+ assert parse_local_gpus("auto") == ["0", "1"]++ monkeypatch.setenv("ZE_AFFINITY_MASK", "1")+ assert parse_local_gpus("auto") == ["1"]+++ ("device", "expected", "env_name"),+ [+ ("cuda", ["3"], "CUDA_VISIBLE_DEVICES"),+ ("npu", ["2"], "ASCEND_RT_VISIBLE_DEVICES"),+ ("xpu", ["0", "1"], "ZE_AFFINITY_MASK"),+ ("xpu:1", ["0", "1"], "ZE_AFFINITY_MASK"),+ ("cpu", [None], "CUDA_VISIBLE_DEVICES"),+ ("mps", [None], "CUDA_VISIBLE_DEVICES"),+ ],+)+def test_auto_local_gpus_ignores_other_device_family_masks(+ monkeypatch: pytest.MonkeyPatch, device: str, expected: list[str | None], env_name: str+) -> None:+ """多个设备族掩码共存时只继承当前设备族,CPU/MPS 不据此创建 GPU worker。"""+ import mineru.kit.router.workers as workers++ monkeypatch.setenv("CUDA_VISIBLE_DEVICES", "3")+ monkeypatch.setenv("ASCEND_RT_VISIBLE_DEVICES", "2")+ monkeypatch.setenv("ZE_AFFINITY_MASK", "0,1")+ monkeypatch.setattr(workers, "get_device", lambda: device)+ assert parse_local_gpus("auto") == expected+ assert workers.visible_device_env_name() == env_name++[email protected]("mask", [None, "all", "-1", "none", "void", "0.1, 1.0"])+def test_xpu_local_gpus_mask_fallbacks(monkeypatch: pytest.MonkeyPatch, mask: str | None) -> None:+ """XPU 无掩码时枚举自身设备,禁用标记与子设备编号不受其他设备族影响。"""+ import mineru.kit.router.workers as workers++ monkeypatch.setenv("CUDA_VISIBLE_DEVICES", "3")+ monkeypatch.setenv("ASCEND_RT_VISIBLE_DEVICES", "2")+ monkeypatch.delenv("ZE_AFFINITY_MASK", raising=False)+ if mask is not None:+ monkeypatch.setenv("ZE_AFFINITY_MASK", mask)+ monkeypatch.setattr(workers, "get_device", lambda: "xpu:1")+ monkeypatch.setattr(workers, "accelerator_device_count", lambda _device: 2)+ expected = ["0", "1"] if mask in {None, "all"} else (["0.1", "1.0"] if mask == "0.1, 1.0" else [None])+ assert parse_local_gpus("auto") == expected+ assert parse_local_gpus("4,5") == ["4", "5"]+ assert parse_local_gpus("none") == []++def test_compose_router_healthcheck_uses_v1_path() -> None:"""验证 Router Compose profile 只探测正式 `/v1/health`。"""repo_root = Path(__file__).resolve().parents[2]