Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

install.sh: install XPU PyTorch on Linux when an Intel Arc / Data Center GPU is the only GPU (#13193)

Daniel Hane31a08032a54
diff --git a/install.sh b/install.sh
index 54a44958881..b4eb0bd5104 100755
--- a/install.sh
+++ b/install.sh
@@ -4823,6 +4823,52 @@ _nvidia_gpu_wins_over_amd() {
fi
return 0
}
+_pci_devices_root() { printf '%s' /sys/bus/pci/devices; }
+
+# First XPU-capable Intel display device id; same allowlist as hardware.py _INTEL_XPU_PCI_*.
+_intel_xpu_gpu_id() {
+ for _ix_vendor in "$(_pci_devices_root)"/*/vendor; do
+ [ -r "$_ix_vendor" ] || continue
+ read -r _ix_v < "$_ix_vendor" 2>/dev/null || continue
+ [ "$_ix_v" = "0x8086" ] || continue
+ _ix_dir="${_ix_vendor%vendor}"
+ read -r _ix_c < "${_ix_dir}class" 2>/dev/null || continue
+ case "$_ix_c" in 0x03*) ;; *) continue ;; esac
+ read -r _ix_d < "${_ix_dir}device" 2>/dev/null || continue
+ _ix_d=$(printf '%s' "$_ix_d" | tr '[:upper:]' '[:lower:]')
+ case "$_ix_d" in
+ 0x7d55|0x7d51|0x64a0|0xb080|0xb081|0xb082|0xb083|0xb084|0xb085|0xb086|0xb087) printf '%s' "$_ix_d"; return 0 ;;
+ # PVC (Data Center GPU Max) by exact id: 0x0BE0-0x0BE5 nearby is Cedar Trail (gma500).
+ 0x0bd0|0x0bd4|0x0bd5|0x0bd6|0x0bd7|0x0bd8|0x0bd9|0x0bda|0x0bdb|0x0b69|0x0b6e) printf '%s' "$_ix_d"; return 0 ;;
+ esac
+ _ix_n=$(printf '%d' "$_ix_d" 2>/dev/null) || continue
+ if { [ "$_ix_n" -ge 22160 ] && [ "$_ix_n" -le 22210 ]; } || # 0x5690-0x56C2
+ { [ "$_ix_n" -ge 57856 ] && [ "$_ix_n" -le 58111 ]; }; then # 0xE200-0xE2FF
+ printf '%s' "$_ix_d"; return 0
+ fi
+ done
+ return 1
+}
+
+# Declines beside any AMD silicon: the runtime-less AMD reroute owns a */cpu index there.
+_intel_xpu_auto_gpu_id() {
+ [ "${UNSLOTH_DISABLE_XPU_AUTO:-0}" = 1 ] && return 1
+ [ -n "${UNSLOTH_ROCM_GFX_ARCH:-}" ] && return 1
+ # Level Zero / SYCL device-filter indices need not follow PCI order, so any filter leaves the choice to a pin.
+ _ix_var=""
+ [ -n "${SYCL_DEVICE_FILTER+x}" ] && _ix_var=SYCL_DEVICE_FILTER
+ [ -n "${SYCL_DEVICE_ALLOWLIST+x}" ] && _ix_var=SYCL_DEVICE_ALLOWLIST
+ [ -n "${ONEAPI_DEVICE_SELECTOR+x}" ] && _ix_var=ONEAPI_DEVICE_SELECTOR
+ # Level Zero reads an empty or "default" mask as unset (compute-runtime isAffinityMaskSet).
+ case "${ZE_AFFINITY_MASK-default}" in ""|default) ;; *) _ix_var=ZE_AFFINITY_MASK ;; esac
+ if [ -n "$_ix_var" ]; then
+ echo "[INFO] $_ix_var is set -- skipping the Intel XPU auto route; set UNSLOTH_TORCH_INDEX_FAMILY=xpu to install XPU PyTorch." >&2
+ return 1
+ fi
+ _amd_hardware_corroborated && return 1
+ _intel_xpu_gpu_id
+}
+
# Returns 0 if an AMD display GPU is on the PCI bus even when ROCm cannot use it (a Strix Halo iGPU with no /dev/kfd). Only sharpens the "no GPU detected" hint. vendor 0x1002 = AMD/ATI; class 0x03* = display controller.
_amd_gpu_present_via_pci() {
[ -d /sys/bus/pci/devices ] || return 1
@@ -5771,6 +5817,10 @@ get_torch_index_url() {
*) echo "$_base/cpu"; return ;;
esac
if ! _has_amd_rocm_gpu; then
+ if _ix_gpu=$(_intel_xpu_auto_gpu_id); then
+ echo "[INFO] Intel GPU ($_ix_gpu) detected -- selecting XPU PyTorch (UNSLOTH_DISABLE_XPU_AUTO=1 to keep CPU)." >&2
+ echo "$_base/xpu"; return
+ fi
echo "$_base/cpu"; return
fi
# A generic rocm index is only safe when the gfx arch is readable: the Strix reroute (gfx1150/1151 to the arch-specific index) learns gfx from rocminfo/amd-smi, so if those are missing OR do not enumerate the GPU, an unknown-arch box might be Strix and would get the broken _grouped_mm wheels. Probe via the shared helper (override first, then rocminfo/amd-smi with visibility masks cleared); if the arch is unreadable, never guess a rocm index. A KFD-only host whose arch is still inferable from hardware IDs (PCI/cpuinfo/lspci) returns the cpu index and lets the runtime-less reroute below upgrade it to AMD per-arch wheels, and the reroute gate uses this same probe so the handoff cannot misfire. Only when inference fails too is CPU final, with the actionable warning.
@@ -6796,7 +6846,7 @@ fi
if [ "$SKIP_TORCH" = false ]; then
_warn_if_cuda_mask_hides_amd "$TORCH_INDEX_URL"
fi
-# Export the resolved torch backend ("cuda", "rocm" or "cpu") so setup.sh and install_python_stack.py know what was chosen here and can skip ROCm-specific repair steps. Classify on the FINAL path segment only: a custom UNSLOTH_PYTORCH_MIRROR whose base path happens to contain "rocm" or "gfx" must not mislabel a cu*/cpu index as ROCm (radeon repo URLs end in rocm-rel-X.Y/, Strix overrides in gfxNNNN/, so the trailing slash is stripped first). Lowercase the leaf so every gfx*/rocm*/cu* arm matches regardless of case (the canonical AMD RDNA4 leaf is gfx120X-all). CUDA is branded only on a real cu[0-9]* leaf, so a mirror leaf (/current) does NOT commit a CUDA backend; an unknown leaf leaves the var unset so the stack probes the GPU. Query and fragment are dropped first, then ALL trailing slashes, in lockstep with the shared _torch_index_url_leaf extractor.
+# Export the resolved torch backend ("cuda", "rocm", "xpu" or "cpu") so setup.sh and install_python_stack.py know what was chosen here and can skip ROCm-specific repair steps. Classify on the FINAL path segment only: a custom UNSLOTH_PYTORCH_MIRROR whose base path happens to contain "rocm" or "gfx" must not mislabel a cu*/cpu index as ROCm (radeon repo URLs end in rocm-rel-X.Y/, Strix overrides in gfxNNNN/, so the trailing slash is stripped first). Lowercase the leaf so every gfx*/rocm*/cu* arm matches regardless of case (the canonical AMD RDNA4 leaf is gfx120X-all). CUDA is branded only on a real cu[0-9]* leaf, so a mirror leaf (/current) does NOT commit a CUDA backend; an unknown leaf leaves the var unset so the stack probes the GPU. Query and fragment are dropped first, then ALL trailing slashes, in lockstep with the shared _torch_index_url_leaf extractor.
_torch_index_leaf="${TORCH_INDEX_URL%%\?*}"
_torch_index_leaf="${_torch_index_leaf%%#*}"
while [ -n "$_torch_index_leaf" ] && [ "${_torch_index_leaf%/}" != "$_torch_index_leaf" ]; do
@@ -6816,12 +6866,19 @@ case "$_torch_index_leaf" in
rocm*|gfx*) export UNSLOTH_TORCH_BACKEND="rocm" ;;
cpu) export UNSLOTH_TORCH_BACKEND="cpu" ;;
cu[0-9]*) export UNSLOTH_TORCH_BACKEND="cuda" ;;
+ xpu) export UNSLOTH_TORCH_BACKEND="xpu" ;;
# Unknown leaf: unset so a stale value cannot leak and the stack probes the GPU.
*) unset UNSLOTH_TORCH_BACKEND ;;
esac
# Derived from the index this script RESOLVED, which on a GPU-less machine is "cpu" whether or not anyone asked. Without the marker every ordinary Linux CPU install is recorded as a deliberate choice, and a machine that later gains a GPU is never offered the repair. Only when the stated family SURVIVED the resolution: the case above has already overwritten the variable, so a caller who said "cuda" on a machine with no visible GPU now carries the resolved "cpu", and treating that as stated would deny that host the repair for good if the GPU ever became visible.
-if [ -n "${UNSLOTH_TORCH_BACKEND:-}" ] &&
+# The XPU opt-out on a host the Intel route would otherwise take is a deliberate CPU choice.
+_xpu_opted_out=false
+if [ "${UNSLOTH_TORCH_BACKEND:-}" = cpu ] && [ "${UNSLOTH_DISABLE_XPU_AUTO:-0}" = 1 ] &&
+ _intel_xpu_gpu_id >/dev/null 2>&1 && ! _amd_hardware_corroborated; then
+ _xpu_opted_out=true
+fi
+if [ -n "${UNSLOTH_TORCH_BACKEND:-}" ] && [ "$_xpu_opted_out" != true ] &&
{ [ "$_torch_backend_was_stated" != true ] ||
[ "$_torch_backend_stated_value" != "$UNSLOTH_TORCH_BACKEND" ]; }; then
export UNSLOTH_TORCH_BACKEND_SOURCE="resolved"
@@ -6843,7 +6900,7 @@ case "$_torch_index_leaf" in
TORCHVISION_CONSTRAINT="torchvision>=0.26.0,<0.27.0"
TORCHAUDIO_CONSTRAINT="torchaudio>=2.11.0,<2.12.0"
;;
- # Floor 2.6, not the generic 2.4: unsloth/models/_utils.py raises at import for an XPU device below it, so a mirror serving an older +xpu wheel would install something that cannot run. Reached only through an explicit pin.
+ # Floor 2.6, not the generic 2.4: unsloth/models/_utils.py raises at import for an XPU device below it, so a mirror serving an older +xpu wheel would install something that cannot run. Reached through a pin or the Intel GPU auto route.
xpu)
TORCH_CONSTRAINT="torch>=2.6,<2.11.0"
TORCHVISION_CONSTRAINT="torchvision>=0.21,<0.26.0"
@@ -7386,6 +7443,12 @@ elif _has_amd_rocm_gpu; then
# AMD GPU visible to the kernel but the torch index stayed CPU: no usable ROCm userspace to pick a wheel. "none" would repeat the false diagnosis this installer used to give.
step "gpu" "AMD GPU (no usable ROCm -- CPU fallback)" "$C_WARN"
fi
+elif [ "$_torch_index_leaf" = xpu ]; then
+ if _ix_gpu=$(_intel_xpu_gpu_id); then
+ step "gpu" "Intel GPU ($_ix_gpu, XPU)"
+ else
+ step "gpu" "Intel XPU (torch index pinned)"
+ fi
else
step "gpu" "none (CPU-only)" "$C_WARN"
fi
diff --git a/studio/backend/tests/test_gpu_probe_robustness.py b/studio/backend/tests/test_gpu_probe_robustness.py
index ec73305d325..05ad9ad84ba 100644
--- a/studio/backend/tests/test_gpu_probe_robustness.py
+++ b/studio/backend/tests/test_gpu_probe_robustness.py
@@ -99,6 +99,12 @@ def test_the_winner_is_unchanged_when_every_probe_succeeds(monkeypatch):
("0x56a0", True), # Arc A770 (DG2)
("0x56c0", True), # Data Center GPU Flex 170 (ATS-M)
("0x0bd5", True), # Data Center GPU Max 1550 (PVC)
+ ("0x0bd0", True), # PVC
+ ("0x0b69", True), # Data Center GPU Max 1450 (PVC)
+ ("0x0b6e", True), # Data Center GPU Max 1100C (PVC)
+ ("0x0bdc", False), # between PVC and Cedar Trail, not a compute-runtime id
+ ("0x0be0", False), # Cedar Trail (gma500), next to PVC
+ ("0x0be5", False), # Cedar Trail (gma500)
("0xe20b", True), # Arc B580 (BMG)
("0x4905", False), # Iris Xe MAX (DG1): discrete, but no XPU wheel supports it
("0x46a6", False), # Alder Lake iGPU
diff --git a/studio/backend/utils/hardware/hardware.py b/studio/backend/utils/hardware/hardware.py
index 30c188ca1fd..5ffc5f57168 100644
--- a/studio/backend/utils/hardware/hardware.py
+++ b/studio/backend/utils/hardware/hardware.py
@@ -457,10 +457,15 @@ def _adapter_name_is_live(name: Optional[str], live_names: list[str]) -> bool:
)
-# XPU-capable Intel PCI IDs (pciids.h: DG2/ATS-M, PVC, BMG); an allowlist since DG1 Iris Xe MAX is discrete but unsupported.
-_INTEL_XPU_PCI_ID_RANGES = ((0x5690, 0x56C2), (0x0B69, 0x0BE5), (0xE200, 0xE2FF))
-# Core Ultra iGPUs with Arc Graphics, which PyTorch XPU lists: the ids Intel compute-runtime (devices_base.inl) names Arc (MTL-H, ARL-H, LNL, PTL).
-_INTEL_XPU_PCI_IDS = frozenset((0x7D55, 0x7D51, 0x64A0, 0xB080, 0xB081, 0xB082, 0xB083))
+# XPU-capable Intel PCI IDs (pciids.h: DG2/ATS-M, BMG); an allowlist since DG1 Iris Xe MAX is discrete but unsupported.
+_INTEL_XPU_PCI_ID_RANGES = ((0x5690, 0x56C2), (0xE200, 0xE2FF))
+# Core Ultra iGPUs with Arc Graphics, which PyTorch XPU lists: the ids Intel compute-runtime (devices_base.inl) names Arc (MTL-H, ARL-H, LNL, PTL), plus the PTL Arc Pro ids it lists unnamed.
+# Then PVC (Data Center GPU Max), by exact id: a 0x0B69-0x0BE5 range would also take Cedar Trail (0x0BE0-0x0BE5, gma500).
+_INTEL_XPU_PCI_IDS = frozenset((
+ 0x7D55, 0x7D51, 0x64A0, 0xB080, 0xB081, 0xB082, 0xB083, # Core Ultra Arc iGPUs
+ 0xB084, 0xB085, 0xB086, 0xB087, # PTL Arc Pro (Mesa iris_pci_ids.h)
+ 0x0BD0, 0x0BD4, 0x0BD5, 0x0BD6, 0x0BD7, 0x0BD8, 0x0BD9, 0x0BDA, 0x0BDB, 0x0B69, 0x0B6E, # PVC
+)) # fmt: skip
def _intel_pci_device_is_xpu_class(device_dir: str) -> Optional[bool]:
diff --git a/studio/install_python_stack.py b/studio/install_python_stack.py
index 4d672d672c5..d92185f1d4e 100644
--- a/studio/install_python_stack.py
+++ b/studio/install_python_stack.py
@@ -4393,7 +4393,7 @@ _XPU_TORCH_PKG_SPEC: tuple[str, str, str] = (
def _explicit_xpu_torch_index_url() -> "str | None":
"""The pinned wheel index URL when it names the XPU family (leaf == xpu), else None.
- Intel support is a pin, never autodetection, so the pin is the only signal there is.
+ Only the pin; install.sh's Intel GPU route reaches _ensure_xpu_torch through _TORCH_BACKEND.
"""
url = _explicit_torch_index_url()
if url is None:
@@ -4637,8 +4637,60 @@ def _ensure_cuda_torch(*, probe_only: bool = False) -> "bool | None":
)
-def _ensure_xpu_torch() -> "bool | None":
- """Install XPU torch when an explicit XPU pin is set but the venv has another build.
+# Same allowlist as studio/backend/utils/hardware/hardware.py and install.sh's _intel_xpu_gpu_id.
+_INTEL_XPU_PCI_ID_RANGES = ((0x5690, 0x56C2), (0xE200, 0xE2FF))
+_INTEL_XPU_PCI_IDS = frozenset((
+ 0x7D55, 0x7D51, 0x64A0, 0xB080, 0xB081, 0xB082, 0xB083, # Core Ultra Arc iGPUs
+ 0xB084, 0xB085, 0xB086, 0xB087, # PTL Arc Pro (Mesa iris_pci_ids.h)
+ 0x0BD0, 0x0BD4, 0x0BD5, 0x0BD6, 0x0BD7, 0x0BD8, 0x0BD9, 0x0BDA, 0x0BDB, 0x0B69, 0x0B6E, # PVC
+)) # fmt: skip
+_PCI_DEVICES_ROOT = "/sys/bus/pci/devices"
+_INTEL_DEVICE_FILTER_VARS = (
+ "ONEAPI_DEVICE_SELECTOR",
+ "SYCL_DEVICE_FILTER",
+ "SYCL_DEVICE_ALLOWLIST",
+)
+
+
+def _intel_xpu_auto_route_holds() -> bool:
+ """install.sh's Intel XPU auto route, re-asked now: opt-out, ZE_AFFINITY_MASK, AMD silicon, and
+ an allowlisted Intel display device on the PCI bus."""
+ if os.environ.get("UNSLOTH_DISABLE_XPU_AUTO", "0") == "1":
+ return False
+ # Level Zero reads an empty or "default" ZE_AFFINITY_MASK as unset (compute-runtime isAffinityMaskSet).
+ ze_mask_set = os.environ.get("ZE_AFFINITY_MASK", "default") not in ("", "default")
+ if (
+ ze_mask_set
+ or any(v in os.environ for v in _INTEL_DEVICE_FILTER_VARS)
+ or os.environ.get("UNSLOTH_ROCM_GFX_ARCH")
+ ):
+ return False
+ intel = False
+ try:
+ devices = sorted(Path(_PCI_DEVICES_ROOT).iterdir())
+ except OSError:
+ return False
+ for dev in devices:
+ try:
+ vendor = (dev / "vendor").read_text(encoding = "utf-8").strip().lower()
+ if not (dev / "class").read_text(encoding = "utf-8").strip().lower().startswith("0x03"):
+ continue
+ if vendor == "0x1002":
+ return False
+ if vendor != "0x8086":
+ continue
+ device_id = int((dev / "device").read_text(encoding = "utf-8").strip(), 16)
+ except (OSError, ValueError):
+ continue
+ if device_id in _INTEL_XPU_PCI_IDS or any(
+ lo <= device_id <= hi for lo, hi in _INTEL_XPU_PCI_ID_RANGES
+ ):
+ intel = True
+ return intel
+
+
+def _ensure_xpu_torch(probe_only: bool = False) -> "bool | None":
+ """Install XPU torch when an XPU pin, or install.sh's Intel GPU route, is not what the venv has.
Counterpart to _ensure_cpu_torch for Intel. `unsloth studio update` runs setup.sh, never
install.sh, so its XPU install path is unreachable there; and an xpu leaf names no family
@@ -4646,13 +4698,32 @@ def _ensure_xpu_torch() -> "bool | None":
Windows is excluded on purpose: setup.ps1 owns torch there and already installs the XPU
trio itself, so acting here would fight it. macOS has no XPU at all. False: a repair is
- required but the mirror cannot express the XPU index; the caller aborts.
+ required but the mirror cannot express the XPU index; the caller aborts. ``probe_only``
+ answers True where a repair (or that False) would happen, and installs nothing.
"""
if NO_TORCH or IS_MACOS or IS_WINDOWS:
return
pin = _explicit_xpu_torch_index_url()
+ _source = "an explicit XPU index is pinned"
if pin is None and _explicit_torch_index_family() != "xpu":
- return
+ # Unpinned: install.sh's route or the recorded flavor; any other stated backend or pin wins.
+ if (
+ _explicit_torch_index_family() is not None
+ or (_TORCH_BACKEND or _RECORDED_TORCH_TAG) != "xpu"
+ ):
+ return
+ # A stated backend is a preference; only install.sh's resolved answer or a record is re-asked.
+ stated = (
+ _TORCH_BACKEND == "xpu"
+ and os.environ.get("UNSLOTH_TORCH_BACKEND_SOURCE", "").strip().lower() != "resolved"
+ )
+ # A recorded XPU flavor yields to an NVIDIA or AMD GPU added since.
+ if not _TORCH_BACKEND and (_has_usable_nvidia_gpu() or _has_rocm_gpu()):
+ return
+ if not stated and not _intel_xpu_auto_route_holds():
+ return
+ pin = _pytorch_whl_leaf_url("xpu") # None: the mirror cannot express it; False below
+ _source = "this install selected XPU torch for its Intel GPU"
# Un-importable either way installs from the pin below. One shared probe bounds it.
_ran, _importable, _version, _hip, _cuda = _probe_torch_runtime()
@@ -4663,6 +4734,8 @@ def _ensure_xpu_torch() -> "bool | None":
# reinstalling never fixes a driver -- it would just re-download the trio twice per
# update, since this helper runs at two repair points.
if _xpu_wheel_supported_on_disk():
+ if probe_only:
+ return
_safe_print(
_red(
" torch did not respond in time; the installed XPU build is supported, "
@@ -4685,10 +4758,12 @@ def _ensure_xpu_torch() -> "bool | None":
else:
_why = "torch cannot import"
+ if probe_only:
+ return True
if pin is None:
return False
_safe_print(
- f" {_why} but an explicit XPU index is pinned -- reinstalling XPU torch from "
+ f" {_why} but {_source} -- reinstalling XPU torch from "
f"{_strip_index_url_credentials(pin)}"
)
_torch_pkg, _vision_pkg, _audio_pkg = _XPU_TORCH_PKG_SPEC
@@ -5848,6 +5923,18 @@ def _cuda_torch_needs_dependency_pass() -> bool:
return False
+def _xpu_torch_needs_dependency_pass() -> bool:
+ """True when only the dependency pass can put back the XPU torch this install chose.
+
+ Answered by _ensure_xpu_torch in probe mode, as _cuda_torch_needs_dependency_pass is.
+ Never installs, and fails closed.
+ """
+ try:
+ return bool(_ensure_xpu_torch(probe_only = True))
+ except Exception: # noqa: BLE001 - a probe that cannot answer keeps the fast path
+ return False
+
+
def _amd_torch_needs_dependency_pass() -> bool:
"""Return True when setup must run the dependency pass to repair non-ROCm torch.
@@ -12973,6 +13060,9 @@ if __name__ == "__main__":
if sys.argv[1:] == ["--cuda-torch-needs-dependency-pass"]:
# Exit 0 forces the dependency pass; exit 1 keeps the fast path.
sys.exit(0 if _cuda_torch_needs_dependency_pass() else 1)
+ if sys.argv[1:] == ["--xpu-torch-needs-dependency-pass"]:
+ # Exit 0 forces the dependency pass; exit 1 keeps the fast path.
+ sys.exit(0 if _xpu_torch_needs_dependency_pass() else 1)
if sys.argv[1:] == ["--missing-torch-needs-dependency-pass"]:
# Exit 0 forces the dependency pass; exit 1 keeps the fast path.
sys.exit(0 if _missing_torch_needs_dependency_pass() else 1)
diff --git a/studio/setup.sh b/studio/setup.sh
index 18a6332a91f..1a4332d43f0 100755
--- a/studio/setup.sh
+++ b/studio/setup.sh
@@ -3606,6 +3606,28 @@ if [ "$_SKIP_PYTHON_DEPS" = true ] && [ -x "$VENV_DIR/bin/python" ]; then
fi
fi
+# Same for an install that chose XPU torch for its Intel GPU (install.sh's auto route, recorded
+# in the manifest) but now holds another wheel: _ensure_xpu_torch runs only inside the pass.
+if [ "$_SKIP_PYTHON_DEPS" = true ] && [ -x "$VENV_DIR/bin/python" ]; then
+ _setup_xpu_torch_stale=false
+ if command -v timeout >/dev/null 2>&1; then
+ timeout -k 5 180 "$VENV_DIR/bin/python" \
+ "$SCRIPT_DIR/install_python_stack.py" --xpu-torch-needs-dependency-pass \
+ >/dev/null 2>&1 && _setup_xpu_torch_stale=true
+ elif "$VENV_DIR/bin/python" "$SCRIPT_DIR/install_python_stack.py" \
+ --xpu-torch-needs-dependency-pass >/dev/null 2>&1; then
+ _setup_xpu_torch_stale=true
+ fi
+ if [ "$_setup_xpu_torch_stale" = true ]; then
+ if [ "${_OFFLINE_FAST_PATH:-false}" = true ] || _uv_offline_requested; then
+ substep "installed PyTorch is not the XPU build this install chose but UV_OFFLINE is set -- left for the next online update"
+ else
+ substep "installed PyTorch is not the XPU build this install chose -- forcing dependency pass to repair..."
+ _SKIP_PYTHON_DEPS=false
+ fi
+ fi
+fi
+
if [ "$_SKIP_PYTHON_DEPS" = false ]; then
install_python_stack
_setup_rerun_if_replaced
diff --git a/tests/sh/test_install_intel_xpu_auto_route.sh b/tests/sh/test_install_intel_xpu_auto_route.sh
new file mode 100755
index 00000000000..090304d785e
--- /dev/null
+++ b/tests/sh/test_install_intel_xpu_auto_route.sh
@@ -0,0 +1,204 @@
+#!/bin/bash
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+# get_torch_index_url routes a Linux x86_64 host whose only GPU is an XPU-capable Intel part to
+# the xpu index, as install.ps1 does on Windows; every other host keeps its index.
+set -u
+
+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
+. "$SCRIPT_DIR/_harness.sh"
+ROOT="$SCRIPT_DIR/../.."
+INSTALL_SH="${INSTALL_SH:-$ROOT/install.sh}"
+HARDWARE_PY="$ROOT/studio/backend/utils/hardware/hardware.py"
+STACK_PY="$ROOT/studio/install_python_stack.py"
+
+_TMP=$(mktemp -d)
+trap 'rm -rf "${_TMP:?}"' EXIT
+_PCI="$_TMP/pci"
+_ABSENT="$_TMP/absent"
+_FUNC_FILE="$_TMP/funcs.sh"
+
+# get_torch_index_url and the helpers it reaches, as tests/sh/test_get_torch_index_url.sh lists
+# them, with the host paths the probes read redirected.
+_FUNCS="_run_bounded _cvd_hides_nvidia _has_amd_rocm_gpu _has_usable_nvidia_gpu
+ _rocm_torch_explicitly_requested _ensure_rocm_probe_env _probe_amd_gfx_arch
+ _amd_gpu_present_via_pci _infer_amd_gfx_arch_from_gpu_name _infer_linux_amd_gfx_arch
+ _amd_arch_index_family_for_gfx _amd_probe_arches _amd_agreed_index_family _amd_sole_index_arch
+ _trim_index_path_slashes _nvidia_library_inventory _nvidia_driver_cuda_version
+ _nvidia_cu126_verdict _cap_cuda_family_for_pre_turing _rocm_tag_from_amd_smi
+ _rocm_tag_from_version_file _rocm_tag_from_hipconfig _rocm_tag_from_dpkg _rocm_tag_from_rpm
+ _highest_rocm_tag _detect_rocm_version_tag _amd_hardware_corroborated _pci_devices_root
+ _intel_xpu_gpu_id _intel_xpu_auto_gpu_id get_torch_index_url"
+for _fn in $_FUNCS; do
+ awk -v fn="$_fn" '
+ !body && index($0, fn "()") == 1 { body = 1; print; if ($0 ~ /\}[[:space:]]*$/) body = 0; next }
+ body { print; if ($0 ~ /^\}/) body = 0 }
+ ' "$INSTALL_SH"
+ echo
+done | sed -e "s|/sys/bus/pci/devices|$_PCI|g" \
+ -e "s|/usr/bin/nvidia-smi|$_ABSENT/nvidia-smi|g" \
+ -e "s|/opt/rocm|$_ABSENT/rocm|g" \
+ -e "s|/proc/driver/nvidia|$_ABSENT/proc-nvidia|g" \
+ -e "s|/sys/class/kfd|$_ABSENT/kfd|g" \
+ -e "s|/dev/kfd|$_ABSENT/dev-kfd|g" \
+ -e "s|/dev/dxg|$_ABSENT/dxg|g" > "$_FUNC_FILE"
+
+_TOOLS="$_TMP/tools"
+mkdir -p "$_TOOLS"
+for _cmd in grep sed head sh bash cat awk printf tr; do
+ _real=$(command -v "$_cmd" 2>/dev/null || true)
+ [ -n "$_real" ] && ln -sf "$_real" "$_TOOLS/$_cmd"
+done
+
+# $1 = machine (x86_64 / aarch64).
+make_uname() {
+ cat > "$_TOOLS/uname" <<EOF
+#!/bin/sh
+case "\$1" in -m) echo $1 ;; *) echo Linux ;; esac
+EOF
+ chmod +x "$_TOOLS/uname"
+}
+
+# add_pci <slot> <vendor> <device> <class>
+add_pci() {
+ mkdir -p "$_PCI/$1"
+ echo "$2" > "$_PCI/$1/vendor"
+ echo "$3" > "$_PCI/$1/device"
+ echo "$4" > "$_PCI/$1/class"
+}
+
+_NV="$_TMP/nv"
+mkdir -p "$_NV"
+cat > "$_NV/nvidia-smi" <<'EOF'
+#!/bin/sh
+case "$1" in
+ -L) echo "GPU 0: NVIDIA GeForce RTX 3090 (UUID: GPU-fake)" ;;
+ --query-gpu=compute_cap) echo 8.6 ;;
+ *) echo "| NVIDIA-SMI 550.54.15 Driver Version: 550.54.15 CUDA Version: 12.8 |" ;;
+esac
+EOF
+chmod +x "$_NV/nvidia-smi"
+
+# run <extra PATH dir or ""> <env assignments...>
+run() {
+ _extra="$1"; shift
+ env -i HOME="$_TMP" PATH="${_extra:+$_extra:}$_TOOLS" "$@" \
+ bash -c ". '$_FUNC_FILE'; _ARCH=x86_64; get_torch_index_url" 2>/dev/null
+}
+
+cell() {
+ _label="$1"; _want="$2"; shift 2
+ assert_eq "$_label" "https://download.pytorch.org/whl/$_want" "$(run "$@")"
+}
+
+echo "=== test_install_intel_xpu_auto_route ==="
+make_uname x86_64
+
+rm -rf "$_PCI"; mkdir -p "$_PCI"
+cell "no GPU -> cpu" cpu ""
+
+for _id in 0x56a0 0xe20b 0x64a0 0x7d51 0xb084 0xb087 0x0bd5 0x0bd0 0x0b69 0x0b6e; do
+ rm -rf "$_PCI"; add_pci 0000:03:00.0 0x8086 "$_id" 0x030000
+ cell "Intel $_id -> xpu" xpu ""
+done
+
+rm -rf "$_PCI"; add_pci 0000:00:02.0 0x8086 0x46a6 0x030000
+cell "non-Arc Intel iGPU 0x46a6 -> cpu" cpu ""
+
+# Cedar Trail (gma500) sits next to PVC; the old 0x0B69-0x0BE5 range took it.
+for _id in 0x0be0 0x0be5; do
+ rm -rf "$_PCI"; add_pci 0000:00:02.0 0x8086 "$_id" 0x030000
+ cell "Cedar Trail $_id -> cpu" cpu ""
+done
+
+rm -rf "$_PCI"; add_pci 0000:00:1f.3 0x8086 0x56a0 0x040300
+cell "Intel id on a non-display function -> cpu" cpu ""
+
+rm -rf "$_PCI"; add_pci 0000:03:00.0 0x8086 0x56a0 0x030000; add_pci 0000:0b:00.0 0x1002 0x744c 0x030000
+cell "Arc beside AMD silicon -> cpu (AMD reroute owns it)" cpu ""
+
+rm -rf "$_PCI"; add_pci 0000:03:00.0 0x8086 0x56a0 0x030000
+cell "Arc + NVIDIA -> cu128" cu128 "$_NV"
+cell "Arc + family pin cpu -> cpu" cpu "" UNSLOTH_TORCH_INDEX_FAMILY=cpu
+cell "Arc + opt-out -> cpu" cpu "" UNSLOTH_DISABLE_XPU_AUTO=1
+cell "Arc + declared AMD arch -> cpu" cpu "" UNSLOTH_ROCM_GFX_ARCH=gfx1100
+cell "Arc + emptied ZE_AFFINITY_MASK -> xpu (Level Zero reads it as unset)" xpu "" ZE_AFFINITY_MASK=
+cell "Arc + ZE_AFFINITY_MASK=default -> xpu" xpu "" ZE_AFFINITY_MASK=default
+cell "Arc + ZE_AFFINITY_MASK=-1 -> cpu" cpu "" ZE_AFFINITY_MASK=-1
+cell "Arc + ZE_AFFINITY_MASK=0 -> cpu (indices need not follow PCI order)" cpu "" ZE_AFFINITY_MASK=0
+cell "Arc + ZE_AFFINITY_MASK=0 + xpu pin -> xpu" xpu "" ZE_AFFINITY_MASK=0 UNSLOTH_TORCH_INDEX_FAMILY=xpu
+_mask_info=$(env -i HOME="$_TMP" PATH="$_TOOLS" ZE_AFFINITY_MASK=0 bash -c ". '$_FUNC_FILE'; _ARCH=x86_64; get_torch_index_url" 2>&1 >/dev/null)
+assert_contains "a set mask names the pin to use" "$_mask_info" "UNSLOTH_TORCH_INDEX_FAMILY=xpu"
+cell "Arc + emptied mask + xpu pin -> xpu" xpu "" ZE_AFFINITY_MASK= UNSLOTH_TORCH_INDEX_FAMILY=xpu
+cell "Arc + ONEAPI_DEVICE_SELECTOR -> cpu" cpu "" ONEAPI_DEVICE_SELECTOR=level_zero:0
+cell "Arc + SYCL_DEVICE_FILTER -> cpu" cpu "" SYCL_DEVICE_FILTER=level_zero:gpu:0
+cell "Arc + SYCL_DEVICE_ALLOWLIST -> cpu" cpu "" SYCL_DEVICE_ALLOWLIST=DeviceType:cpu
+cell "Arc + ONEAPI_DEVICE_SELECTOR + xpu pin -> xpu" xpu "" ONEAPI_DEVICE_SELECTOR=level_zero:0 UNSLOTH_TORCH_INDEX_FAMILY=xpu
+_sel_info=$(env -i HOME="$_TMP" PATH="$_TOOLS" ONEAPI_DEVICE_SELECTOR=level_zero:0 bash -c ". '$_FUNC_FILE'; _ARCH=x86_64; get_torch_index_url" 2>&1 >/dev/null)
+assert_contains "a SYCL selector is named with the pin to use" "$_sel_info" "ONEAPI_DEVICE_SELECTOR is set -- skipping the Intel XPU auto route; set UNSLOTH_TORCH_INDEX_FAMILY=xpu"
+_info=$(env -i HOME="$_TMP" PATH="$_TOOLS" bash -c ". '$_FUNC_FILE'; _ARCH=x86_64; get_torch_index_url" 2>&1 >/dev/null)
+assert_contains "route prints the device and the opt-out" "$_info" "Intel GPU (0x56a0) detected"
+assert_contains "route names UNSLOTH_DISABLE_XPU_AUTO" "$_info" "UNSLOTH_DISABLE_XPU_AUTO=1"
+
+make_uname aarch64
+cell "Arc on aarch64 -> cpu" cpu ""
+make_uname x86_64
+
+# The opt-out on an Arc host records a deliberate CPU backend, not install.sh's resolved answer.
+_SRC_FILE="$_TMP/source.sh"
+awk '/^# Derived from the index this script RESOLVED/ { on = 1 } on { print } on && /^ unset UNSLOTH_TORCH_BACKEND_SOURCE/ { last = 1; next } last && /^fi/ { exit }' \
+ "$INSTALL_SH" > "$_SRC_FILE"
+# source_of <env assignments...>: UNSLOTH_TORCH_BACKEND_SOURCE after the block for a resolved cpu.
+source_of() {
+ env -i HOME="$_TMP" PATH="$_TOOLS" "$@" bash -c ". '$_FUNC_FILE'; _ARCH=x86_64
+ _torch_backend_was_stated=false; _torch_backend_stated_value=''; UNSLOTH_TORCH_BACKEND=cpu
+ . '$_SRC_FILE'; printf '%s' \"\${UNSLOTH_TORCH_BACKEND_SOURCE:-unset}\"" 2>/dev/null
+}
+rm -rf "$_PCI"; add_pci 0000:03:00.0 0x8086 0x56a0 0x030000
+assert_eq "Arc + opt-out records a deliberate cpu" "unset" "$(source_of UNSLOTH_DISABLE_XPU_AUTO=1)"
+assert_eq "Arc + opt-out + SYCL selector still records a deliberate cpu" "unset" "$(source_of UNSLOTH_DISABLE_XPU_AUTO=1 ONEAPI_DEVICE_SELECTOR=level_zero:0)"
+assert_eq "Arc without the opt-out keeps resolved" "resolved" "$(source_of)"
+rm -rf "$_PCI"; add_pci 0000:00:02.0 0x8086 0x46a6 0x030000
+assert_eq "opt-out without an XPU-capable GPU keeps resolved" "resolved" "$(source_of UNSLOTH_DISABLE_XPU_AUTO=1)"
+
+# One allowlist in three places: hardware.py, install_python_stack.py (update-time revalidation) and
+# the shell. The Python tables must be equal; the shell is probed on every id and bound neighbour.
+if command -v python3 >/dev/null 2>&1 && grep -q "^_intel_xpu_gpu_id()" "$_FUNC_FILE"; then
+ _pairs=$(python3 - "$HARDWARE_PY" "$STACK_PY" <<'PY'
+import ast, sys
+def tables(path):
+ out = {}
+ for node in ast.parse(open(path, encoding="utf-8").read()).body:
+ if isinstance(node, ast.Assign) and isinstance(node.targets[0], ast.Name):
+ if node.targets[0].id in ("_INTEL_XPU_PCI_ID_RANGES", "_INTEL_XPU_PCI_IDS"):
+ out[node.targets[0].id] = ast.literal_eval(node.value.args[0] if isinstance(node.value, ast.Call) else node.value)
+ return out
+vals = tables(sys.argv[1])
+stack = tables(sys.argv[2])
+if {k: set(v) for k, v in stack.items()} != {k: set(v) for k, v in vals.items()}:
+ print("STACK_DIFFERS")
+ids = set(vals["_INTEL_XPU_PCI_IDS"])
+for lo, hi in vals["_INTEL_XPU_PCI_ID_RANGES"]:
+ ids.update((lo, hi, (lo + hi) // 2))
+probe = {i: True for i in ids}
+for lo, hi in vals["_INTEL_XPU_PCI_ID_RANGES"]:
+ for edge in (lo - 1, hi + 1):
+ probe.setdefault(edge, any(a <= edge <= b for a, b in vals["_INTEL_XPU_PCI_ID_RANGES"]) or edge in vals["_INTEL_XPU_PCI_IDS"])
+for i in sorted(probe):
+ print(f"0x{i:04x} {'yes' if probe[i] else 'no'}")
+PY
+)
+ _mismatch=""
+ case "$_pairs" in *STACK_DIFFERS*) _mismatch=" install_python_stack.py" ;; esac
+ _pairs=$(printf '%s\n' "$_pairs" | grep -v STACK_DIFFERS)
+ while read -r _id _want; do
+ rm -rf "$_PCI"; add_pci 0000:03:00.0 0x8086 "$_id" 0x030000
+ _got=$(env -i PATH="$_TOOLS" bash -c ". '$_FUNC_FILE'; _intel_xpu_gpu_id >/dev/null && echo yes || echo no")
+ [ "$_got" = "$_want" ] || _mismatch="$_mismatch $_id"
+ done <<EOF
+$_pairs
+EOF
+ assert_eq "shell and install_python_stack.py allowlists match hardware.py ($(printf '%s\n' "$_pairs" | wc -l | tr -d ' ') ids)" "" "$_mismatch"
+fi
+
+summary
diff --git a/tests/studio/install/test_xpu_auto_route_update.py b/tests/studio/install/test_xpu_auto_route_update.py
new file mode 100644
index 00000000000..debf0d5fc75
--- /dev/null
+++ b/tests/studio/install/test_xpu_auto_route_update.py
@@ -0,0 +1,252 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+"""install.sh's Intel GPU route survives `unsloth studio update`: _ensure_xpu_torch acts on the
+resolved xpu backend, or the xpu flavor the install recorded, and on nothing else unpinned."""
+
+import importlib.util
+import re
+import sys
+from pathlib import Path
+from unittest.mock import patch
+
+import pytest
+
+ROOT = Path(__file__).resolve().parents[3]
+_SPEC = importlib.util.spec_from_file_location(
+ "studio_install_python_stack_xpu_auto", ROOT / "studio" / "install_python_stack.py"
+)
+stack = importlib.util.module_from_spec(_SPEC)
+sys.modules[_SPEC.name] = stack
+_SPEC.loader.exec_module(stack)
+
+
+def _pci(monkeypatch, tmp_path, *devices):
+ """A fake PCI tree of (vendor, device, class) functions."""
+ root = tmp_path / "pci"
+ root.mkdir(exist_ok = True)
+ for old in root.iterdir():
+ for f in old.iterdir():
+ f.unlink()
+ old.rmdir()
+ for i, (vendor, device, cls) in enumerate(devices):
+ d = root / f"0000_{i:02x}_00.0" # ":" is not legal in Windows paths
+ d.mkdir()
+ (d / "vendor").write_text(vendor + "\n")
+ (d / "device").write_text(device + "\n")
+ (d / "class").write_text(cls + "\n")
+ monkeypatch.setattr(stack, "_PCI_DEVICES_ROOT", str(root), raising = False)
+
+
[email protected](autouse = True)
+def _linux(monkeypatch, tmp_path):
+ monkeypatch.setattr(stack, "NO_TORCH", False)
+ monkeypatch.setattr(stack, "IS_MACOS", False)
+ monkeypatch.setattr(stack, "IS_WINDOWS", False)
+ for var in ("UNSLOTH_TORCH_INDEX_URL", "UNSLOTH_TORCH_INDEX_FAMILY"):
+ monkeypatch.delenv(var, raising = False)
+ monkeypatch.setattr(stack, "_has_usable_nvidia_gpu", lambda: False)
+ monkeypatch.setattr(stack, "_has_rocm_gpu", lambda: False)
+ for var in (
+ "ZE_AFFINITY_MASK",
+ "ONEAPI_DEVICE_SELECTOR",
+ "SYCL_DEVICE_FILTER",
+ "SYCL_DEVICE_ALLOWLIST",
+ "UNSLOTH_DISABLE_XPU_AUTO",
+ "UNSLOTH_ROCM_GFX_ARCH",
+ ):
+ monkeypatch.delenv(var, raising = False)
+ # install.sh exports this beside the backend it resolved.
+ monkeypatch.setenv("UNSLOTH_TORCH_BACKEND_SOURCE", "resolved")
+ _pci(monkeypatch, tmp_path, ("0x8086", "0x56a0", "0x030000"))
+ stack._invalidate_torch_runtime_probe()
+ yield
+ stack._invalidate_torch_runtime_probe()
+
+
+def _run(
+ backend,
+ recorded,
+ version = "2.11.0+cpu",
+ probe_only = False,
+):
+ with (
+ patch.object(stack, "_TORCH_BACKEND", backend),
+ patch.object(stack, "_RECORDED_TORCH_TAG", recorded),
+ patch.object(stack, "_probe_torch_runtime", return_value = (True, True, version, None, None)),
+ patch.object(stack, "pip_install") as pip,
+ ):
+ pip.result = (
+ stack._ensure_xpu_torch(probe_only = probe_only)
+ if probe_only
+ else stack._ensure_xpu_torch()
+ )
+ return pip
+
+
+ ("backend", "recorded"),
+ [("xpu", None), ("", "xpu")],
+ ids = ["install.sh route", "standalone update, recorded xpu"],
+)
+def test_the_auto_route_repairs_a_cpu_wheel_from_the_xpu_index(backend, recorded):
+ pip = _run(backend, recorded)
+ assert pip.called
+ assert pip.call_args.args[-2:] == ("--index-url", "https://download.pytorch.org/whl/xpu")
+
+
+ ("backend", "recorded"),
+ [("", None), ("", "cpu"), ("cpu", "xpu"), ("cuda", None), ("rocm", "xpu")],
+)
+def test_no_xpu_signal_or_another_stated_backend_leaves_torch_alone(backend, recorded):
+ assert not _run(backend, recorded).called
+
+
+def test_another_family_pin_wins_over_a_recorded_xpu(monkeypatch):
+ monkeypatch.setenv("UNSLOTH_TORCH_INDEX_FAMILY", "cpu")
+ assert not _run("", "xpu").called
+
+
+def test_a_supported_xpu_wheel_is_left_alone():
+ assert not _run("xpu", None, version = "2.9.1+xpu").called
+
+
+def test_install_sh_exports_the_xpu_backend():
+ source = (ROOT / "install.sh").read_text(encoding = "utf-8")
+ assert re.search(r'^\s*xpu\)\s*export UNSLOTH_TORCH_BACKEND="xpu"', source, re.M)
+
+
[email protected]("vendor", ["_has_usable_nvidia_gpu", "_has_rocm_gpu"])
+def test_a_recorded_xpu_flavor_yields_to_a_gpu_added_since(monkeypatch, vendor):
+ monkeypatch.setattr(stack, vendor, lambda: True)
+ assert not _run("", "xpu").called
+
+
+def test_install_sh_route_still_acts_beside_another_vendor_probe(monkeypatch):
+ monkeypatch.setattr(stack, "_has_usable_nvidia_gpu", lambda: True)
+ assert _run("xpu", None).called
+
+
[email protected](("backend", "recorded"), [("xpu", None), ("", "xpu")])
+def test_an_unexpressible_repair_is_reported(monkeypatch, backend, recorded):
+ monkeypatch.setattr(stack, "_pytorch_whl_leaf_url", lambda leaf: None)
+ pip = _run(backend, recorded)
+ assert pip.result is False and not pip.called
+ assert _run(backend, recorded, version = "2.9.1+xpu").result is None
+
+
+ ("backend", "recorded", "version", "needs"),
+ [
+ ("", "xpu", "2.11.0+cpu", True),
+ ("", "xpu", "2.9.1+xpu", False),
+ ("", "cpu", "2.11.0+cpu", False),
+ ("", None, "2.11.0+cpu", False),
+ ],
+)
+def test_the_fast_path_probe_matches_the_repair(backend, recorded, version, needs):
+ pip = _run(backend, recorded, version = version, probe_only = True)
+ assert bool(pip.result) is needs and not pip.called
+
+
+def test_setup_sh_forces_the_pass_on_a_stale_xpu_wheel():
+ setup = (ROOT / "studio" / "setup.sh").read_text(encoding = "utf-8")
+ stack_src = (ROOT / "studio" / "install_python_stack.py").read_text(encoding = "utf-8")
+ assert setup.count("--xpu-torch-needs-dependency-pass") == 2
+ assert 'sys.argv[1:] == ["--xpu-torch-needs-dependency-pass"]' in stack_src
+
+
[email protected]("backend, recorded", [("xpu", None), ("", "xpu")])
+ "case",
+ [
+ "intel gone",
+ "non-Arc iGPU only",
+ "Cedar Trail 0x0be0",
+ "Cedar Trail 0x0be5",
+ "AMD beside Arc",
+ "mask set",
+ "oneAPI selector",
+ "SYCL filter",
+ "SYCL allowlist",
+ "opt-out",
+ ],
+)
+def test_the_unpinned_route_is_revalidated(monkeypatch, tmp_path, backend, recorded, case):
+ if case == "intel gone":
+ _pci(monkeypatch, tmp_path)
+ elif case == "non-Arc iGPU only":
+ _pci(monkeypatch, tmp_path, ("0x8086", "0x46a6", "0x030000"))
+ elif case.startswith("Cedar Trail"):
+ _pci(monkeypatch, tmp_path, ("0x8086", case.split()[-1], "0x030000"))
+ elif case == "oneAPI selector":
+ monkeypatch.setenv("ONEAPI_DEVICE_SELECTOR", "level_zero:0")
+ elif case == "SYCL filter":
+ monkeypatch.setenv("SYCL_DEVICE_FILTER", "level_zero:gpu:0")
+ elif case == "SYCL allowlist":
+ monkeypatch.setenv("SYCL_DEVICE_ALLOWLIST", "DeviceType:cpu")
+ elif case == "AMD beside Arc":
+ _pci(
+ monkeypatch,
+ tmp_path,
+ ("0x8086", "0x56a0", "0x030000"),
+ ("0x1002", "0x744c", "0x030000"),
+ )
+ elif case == "mask set":
+ monkeypatch.setenv("ZE_AFFINITY_MASK", "0")
+ else:
+ monkeypatch.setenv("UNSLOTH_DISABLE_XPU_AUTO", "1")
+ assert not _run(backend, recorded).called
+
+
+def test_a_stated_xpu_backend_is_not_revalidated(monkeypatch, tmp_path):
+ # Not install.sh's resolved answer: the user asked for XPU, so a hidden Arc does not undo it.
+ _pci(monkeypatch, tmp_path)
+ monkeypatch.delenv("UNSLOTH_TORCH_BACKEND_SOURCE")
+ assert _run("xpu", None).called
+ assert not _run("", "xpu").called
+
+
+def test_an_explicit_pin_stays_authoritative(monkeypatch, tmp_path):
+ _pci(monkeypatch, tmp_path)
+ monkeypatch.setenv("ZE_AFFINITY_MASK", "0")
+ monkeypatch.setenv("UNSLOTH_TORCH_INDEX_FAMILY", "xpu")
+ assert _run("", None).called
+
+
+def test_the_allowlist_matches_hardware_py():
+ import ast
+
+ def tables(path):
+ out = {}
+ for node in ast.parse(path.read_text(encoding = "utf-8")).body:
+ if isinstance(node, ast.Assign) and isinstance(node.targets[0], ast.Name):
+ name = node.targets[0].id
+ if name in ("_INTEL_XPU_PCI_ID_RANGES", "_INTEL_XPU_PCI_IDS"):
+ value = node.value.args[0] if isinstance(node.value, ast.Call) else node.value
+ out[name] = set(ast.literal_eval(value))
+ return out
+
+ hardware = tables(ROOT / "studio" / "backend" / "utils" / "hardware" / "hardware.py")
+ assert tables(ROOT / "studio" / "install_python_stack.py") == hardware
+ assert len(hardware) == 2
+
+
[email protected]("device", ["0x0bd0", "0x0bd5", "0x0b69", "0x0b6e", "0xb084", "0xb087"])
+def test_pvc_and_ptl_arc_pro_ids_route(monkeypatch, tmp_path, device):
+ _pci(monkeypatch, tmp_path, ("0x8086", device, "0x030000"))
+ assert stack._intel_xpu_auto_route_holds()
+
+
[email protected]("mask", ["", "default"])
+def test_an_unset_equivalent_mask_keeps_the_route(monkeypatch, tmp_path, mask):
+ # Level Zero reads these as no mask, so every Intel GPU stays visible.
+ _pci(monkeypatch, tmp_path, ("0x8086", "0x56a0", "0x030000"))
+ monkeypatch.setenv("ZE_AFFINITY_MASK", mask)
+ assert stack._intel_xpu_auto_route_holds()
+
+
+def test_an_explicit_pin_wins_over_a_sycl_selector(monkeypatch, tmp_path):
+ monkeypatch.setenv("ONEAPI_DEVICE_SELECTOR", "level_zero:0")
+ monkeypatch.setenv("UNSLOTH_TORCH_INDEX_FAMILY", "xpu")
+ assert _run("", None).called
diff --git a/tests/studio/test_xpu_triton_swap.py b/tests/studio/test_xpu_triton_swap.py
index c5a3c52f1c8..aeef0cbf1f2 100644
--- a/tests/studio/test_xpu_triton_swap.py
+++ b/tests/studio/test_xpu_triton_swap.py
@@ -523,7 +523,7 @@ class TestADeadDriverIsNotAFlavourMismatch:
# Asserted on the source because _ensure_xpu_torch sits above the extracted slice: the early return must come
# BEFORE the repair reason is set, or the repair runs anyway.
src = STACK.read_text(encoding = "utf-8")
- start = src.index('def _ensure_xpu_torch() -> "bool | None":')
+ start = src.index("def _ensure_xpu_torch(")
body = src[start : src.index("def _installed_torch_version_label", start)]
guard = body.index("_xpu_wheel_supported_on_disk()")
armed = body.index('_why = "torch could not be probed"')