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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: add Vulkan llama.cpp support (#5819)
oobabooga350233512092
diff --git a/studio/backend/core/inference/_vulkan_probe.py b/studio/backend/core/inference/_vulkan_probe.pynew file mode 100644index 00000000000..706346daadd--- /dev/null+++ b/studio/backend/core/inference/_vulkan_probe.py@@ -0,0 +1,110 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Standalone free-VRAM probe for the bundled ggml Vulkan backend.++Run in a short-lived subprocess (``python _vulkan_probe.py <bindir>``) so the+Vulkan instance never lives in the long-running backend process. Loads the+bundled ggml Vulkan backend from ``<bindir>`` and prints one+``<idx>\\t<free_bytes>\\t<is_igpu>\\t<total_bytes>`` line per device to stdout.+Indices are ggml's own Vulkan device ordinals, which need not match nvidia-smi+order. ``is_igpu`` (from ggml's device type) is ``1`` for an integrated GPU+sharing system RAM. ``total_bytes`` is the device-local heap; the reader uses+it to reserve absolute headroom on a discrete card (parity with the CUDA/ROCm+fit) and ignores it for an iGPU, whose "VRAM" is shared system RAM.++Uses only the standard library so it stays runnable as a bare script.+"""++import ctypes+import os+import sys++# ggml_backend_dev_type enum (ggml-backend.h): CPU=0, GPU=1, IGPU=2, ...+_GGML_BACKEND_DEVICE_TYPE_IGPU = 2+++def _igpu_flags(base, lib, count: int) -> list[bool]:+ """Per-device integrated-GPU flags via ggml's backend registry.++ The Vulkan reg enumerates devices in the same order as+ ``ggml_backend_vk_get_device_memory`` (each context uses ``ctx->device =+ i``), so reg index == device ordinal. Returns all-False on any failure so+ the reader never over-caps a discrete card.+ """+ flags = [False] * count+ try:+ lib.ggml_backend_vk_reg.restype = ctypes.c_void_p+ lib.ggml_backend_vk_reg.argtypes = []+ base.ggml_backend_reg_dev_count.restype = ctypes.c_size_t+ base.ggml_backend_reg_dev_count.argtypes = [ctypes.c_void_p]+ base.ggml_backend_reg_dev_get.restype = ctypes.c_void_p+ base.ggml_backend_reg_dev_get.argtypes = [ctypes.c_void_p, ctypes.c_size_t]+ base.ggml_backend_dev_type.restype = ctypes.c_int+ base.ggml_backend_dev_type.argtypes = [ctypes.c_void_p]++ reg = lib.ggml_backend_vk_reg()+ if not reg:+ return flags+ dev_count = base.ggml_backend_reg_dev_count(reg)+ for i in range(min(count, dev_count)):+ dev = base.ggml_backend_reg_dev_get(reg, i)+ if dev:+ flags[i] = base.ggml_backend_dev_type(dev) == _GGML_BACKEND_DEVICE_TYPE_IGPU+ except Exception:+ # Best-effort: any failure degrades to "discrete" so the memory+ # readings still get through instead of crashing the probe.+ pass+ return flags+++def main() -> int:+ if len(sys.argv) < 2:+ return 0+ bindir = sys.argv[1]++ # Hold add_dll_directory's handle for the rest of main() (the documented+ # idiom) so bindir stays on the search path while the sibling ggml DLLs+ # resolve below.+ _dll_dir = None+ if sys.platform == "win32":+ base_name, vk_name = "ggml-base.dll", "ggml-vulkan.dll"+ try:+ _dll_dir = os.add_dll_directory(bindir)+ except Exception:+ pass+ else:+ base_name, vk_name = "libggml-base.so", "libggml-vulkan.so"++ # RTLD_GLOBAL exposes ggml-base's symbols to ggml-vulkan on POSIX. getattr+ # falls back to 0 where the flag doesn't exist (Windows CDLL ignores mode).+ _rtld_global = getattr(ctypes, "RTLD_GLOBAL", 0)+ try:+ base = ctypes.CDLL(os.path.join(bindir, base_name), mode = _rtld_global)+ lib = ctypes.CDLL(os.path.join(bindir, vk_name), mode = _rtld_global)+ except OSError as e:+ print(f"ggml-vulkan load failed: {e}", file = sys.stderr)+ return 1++ lib.ggml_backend_vk_get_device_count.restype = ctypes.c_int+ lib.ggml_backend_vk_get_device_count.argtypes = []+ lib.ggml_backend_vk_get_device_memory.restype = None+ lib.ggml_backend_vk_get_device_memory.argtypes = [+ ctypes.c_int,+ ctypes.POINTER(ctypes.c_size_t),+ ctypes.POINTER(ctypes.c_size_t),+ ]++ count = lib.ggml_backend_vk_get_device_count()+ igpu = _igpu_flags(base, lib, count)+ rows = []+ for i in range(count):+ free, total = ctypes.c_size_t(0), ctypes.c_size_t(0)+ lib.ggml_backend_vk_get_device_memory(i, ctypes.byref(free), ctypes.byref(total))+ rows.append("%d\t%d\t%d\t%d" % (i, free.value, int(igpu[i]), total.value))+ sys.stdout.write("\n".join(rows))+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.pyindex f61402aa5c7..3ba9eff8574 100644--- a/studio/backend/core/inference/llama_cpp.py+++ b/studio/backend/core/inference/llama_cpp.py@@ -1436,6 +1436,50 @@ def _backfill_usage_from_timings(usage, timings):return out+def _vulkan_lib_filename() -> str:+ return "ggml-vulkan.dll" if sys.platform == "win32" else "libggml-vulkan.so"+++# Host RAM to leave free on an integrated GPU, matching llama.cpp's own --fit+# margin (default 1024 MiB per device). ggml reports an iGPU's "VRAM" as shared+# system RAM, so hold back the same margin rather than inventing a larger one.+_IGPU_HOST_RESERVE_MIB = 1024+++def _apply_igpu_host_reserve_mib(free_mib: int, is_igpu: bool) -> int:+ """Reserve host headroom on an integrated (shared-memory) Vulkan GPU.++ An iGPU's reported free "VRAM" is really free system RAM, so sizing+ context/offload against all of it would push the host into swap or the OOM+ killer. Leave the same margin llama.cpp's --fit uses. ``is_igpu`` comes from+ ggml's device type, so a discrete card is never touched; only ever reduces.+ """+ if not is_igpu:+ return free_mib+ return max(0, free_mib - _IGPU_HOST_RESERVE_MIB)+++def _llama_lib_dir(binary: str) -> Path:+ # The installer exposes llama-server as a top-level entrypoint into build/bin/,+ # where the ggml backend libs live, so callers looking for sibling libs (Vulkan+ # detection, LD_LIBRARY_PATH, probe bindir) need the real dir. It is normally a+ # symlink (resolve() reaches build/bin), but create_exec_entrypoint falls back to+ # a shell wrapper (exec "$(dirname "$0")/build/bin/llama-server" "$@") when it+ # cannot symlink, and resolve() stops at the wrapper file. Follow the wrapper's+ # exec target too, so a wrapper-based install still finds build/bin.+ resolved = Path(binary).resolve()+ try:+ with open(resolved, "rb") as _f:+ _head = _f.read(256)+ if _head.startswith(b"#!"):+ _m = re.search(r'exec "\$\(dirname "\$0"\)/([^"]+)"', _head.decode("utf-8", "ignore"))+ if _m:+ return (resolved.parent / _m.group(1)).resolve().parent+ except OSError:+ pass+ return resolved.parent++def _is_external_link(path: Path) -> bool:"""True when ``path`` is a --with-llama-cpp-dir local link: a POSIX symlinkor a Windows directory junction / reparse point. Such a link resolves into@@ -2278,6 +2322,30 @@ class LlamaCppBackend:return total+ @staticmethod+ def _is_vulkan_backend(binary: Optional[str] = None) -> bool:+ """True if the installed llama.cpp build is Vulkan-only.++ The official prebuilts are single-backend, so the Vulkan ggml lib next+ to llama-server identifies a Vulkan build. Keeps the free-memory probe+ and GPU pin in ggml's Vulkan device-index space. For a custom+ multi-backend build with a CUDA or HIP ggml lib alongside Vulkan, defer+ to that backend (torch-usable, better-understood probe/pin).+ """+ binary = binary or LlamaCppBackend._find_llama_server_binary()+ if not binary:+ return False+ lib_dir = _llama_lib_dir(binary)+ if not (lib_dir / _vulkan_lib_filename()).is_file():+ return False+ for _backend in ("cuda", "hip"):+ sibling = (+ f"ggml-{_backend}.dll" if sys.platform == "win32" else f"libggml-{_backend}.so"+ )+ if (lib_dir / sibling).is_file():+ return False+ return True+@staticmethoddef _resolve_visible_physical_ids() -> Optional[list[int]]:"""Physical GPU ids behind the active visibility mask (HIP/ROCR/CUDA on@@ -2440,11 +2508,42 @@ class LlamaCppBackend:return True@staticmethod- def _get_gpu_free_memory() -> list[tuple[int, int]]:+ def _visible_devices_mask(env_name: str) -> Optional[set[int]]:+ """Physical indices a ``*_VISIBLE_DEVICES`` mask permits, or None if unset.++ ``if x.strip()`` filters trailing-comma masks ("0,1,"); an empty mask+ ("") yields an empty set (all devices hidden), distinct from an unset+ var (None, no mask). Used by the nvidia-smi probe.+ """+ raw = os.environ.get(env_name)+ if raw is None:+ return None+ try:+ return set(int(x.strip()) for x in raw.split(",") if x.strip())+ except ValueError:+ return None++ @staticmethod+ def _vulkan_pin_args(gpu_indices: Optional[Iterable[int]]) -> list[str]:+ """``--device Vulkan<i>,...`` to pin a Vulkan launch to selected GPUs.++ The indices are ggml's compact Vulkan ordinals (as _get_gpu_free_memory+ reports and the registry names ``Vulkan<i>``). Pin by that name, NOT via+ GGML_VK_VISIBLE_DEVICES: ggml parses that env var in the raw+ vkEnumeratePhysicalDevices space (before dropping CPU/llvmpipe devices+ and deduplicating ICDs), so a compact ordinal there could select a+ different physical device or the CPU rasterizer.+ """+ if not gpu_indices:+ return []+ return ["--device", ",".join(f"Vulkan{i}" for i in gpu_indices)]++ @staticmethod+ def _get_gpu_free_memory(binary: Optional[str] = None) -> list[tuple[int, int]]:"""Query free memory per GPU. Returns ``(gpu_index, free_mib)`` sorted byindex; empty if no supported GPU is reachable. Thin wrapper over``_get_gpu_memory`` for callers that only need free VRAM."""- return [(idx, free) for idx, free, _total in LlamaCppBackend._get_gpu_memory()]+ return [(idx, free) for idx, free, _total in LlamaCppBackend._get_gpu_memory(binary)]@staticmethoddef _apple_metal_memory_budget_bytes() -> int:@@ -2475,7 +2574,7 @@ class LlamaCppBackend:return int(rec_bytes * _APPLE_UNIFIED_MEMORY_FRACTION)@staticmethod- def _get_gpu_memory() -> list[tuple[int, int, int]]:+ def _get_gpu_memory(binary: Optional[str] = None) -> list[tuple[int, int, int]]:"""Query free AND total memory per GPU.Order:@@ -2487,9 +2586,18 @@ class LlamaCppBackend:probe returned [] on AMD) and NVIDIA hosts missing``nvidia-smi`` from PATH.+ On a Vulkan build the ggml Vulkan probe is authoritative, so the indices+ are ggml's compact Vulkan ordinals (the space the pin selects via+ ``--device Vulkan<i>``). It reports ``total`` for discrete cards and 0+ for an iGPU (shared RAM) so the fit falls back to free*frac there.+ Otherwise nvidia-smi / torch cover NVIDIA + AMD ROCm.+Returns (gpu_index, free_mib, total_mib) sorted by index; empty if no- supported GPU is reachable. ``total`` lets the fit reserve absolute headroom.+ supported GPU is reachable."""+ binary = binary or LlamaCppBackend._find_llama_server_binary()+ if LlamaCppBackend._is_vulkan_backend(binary):+ return LlamaCppBackend._get_gpu_free_memory_vulkan(binary)# ── NVIDIA via nvidia-smi ────────────────────────────────────try:result = subprocess.run(@@ -2505,16 +2613,7 @@ class LlamaCppBackend:**_windows_hidden_subprocess_kwargs(),)if result.returncode == 0:- allowed: Optional[set[int]] = None- cvd = os.environ.get("CUDA_VISIBLE_DEVICES")- if cvd is not None:- try:- # `if x.strip()` filters trailing-comma masks ("0,1,").- # Empty mask (CVD="") yields an empty set -> all GPUs- # filtered out, per codebase convention.- allowed = set(int(x.strip()) for x in cvd.split(",") if x.strip())- except ValueError:- pass+ allowed = LlamaCppBackend._visible_devices_mask("CUDA_VISIBLE_DEVICES")gpus: list[tuple[int, int, int]] = []for line in result.stdout.strip().splitlines():parts = [p.strip() for p in line.split(",")]@@ -2579,6 +2678,91 @@ class LlamaCppBackend:logger.debug(f"torch GPU probe failed: {e}")return []+ @staticmethod+ def _get_gpu_free_memory_vulkan(binary: Optional[str] = None) -> list[tuple[int, int, int]]:+ """Query free (and total) VRAM per device via the bundled ggml Vulkan backend.++ Loads ``libggml-vulkan`` in a short-lived subprocess (no Vulkan instance+ in this process) and returns (device_index, free_mib, total_mib) sorted+ by index. The index is ggml's compact Vulkan ordinal -- the one the+ registry names ``Vulkan<index>`` and load_model pins with ``--device``,+ NOT the raw ``GGML_VK_VISIBLE_DEVICES`` space. A user-set+ ``GGML_VK_VISIBLE_DEVICES`` is honored by ggml (passed through), so the+ list already reflects it. iGPUs leave a host-RAM margin (see+ ``_apply_igpu_host_reserve_mib``) and report total 0; discrete cards pass+ their real total through. [] when no Vulkan build or device is reachable.+ """+ binary = binary or LlamaCppBackend._find_llama_server_binary()+ if not binary:+ return []+ binary_dir = _llama_lib_dir(binary)+ if not (binary_dir / _vulkan_lib_filename()).is_file():+ return []++ env = child_env_without_native_path_secret()+ # Pass any inherited GGML_VK_VISIBLE_DEVICES through to ggml unchanged so+ # the probe enumerates the same device list the launch will, named+ # Vulkan0..N in the compact order reported here and pinned by that name+ # via --device -- probe, mask, and pin stay in one index space. Do NOT+ # filter the mask in Python: ggml parses the env var in raw+ # vkEnumeratePhysicalDevices space while this probe reports the compact+ # post-filter ordinal, so a Python filter would compare mismatched spaces.+ if sys.platform != "win32":+ # Let the loader resolve sibling ggml libs next to the binary.+ existing_ld = env.get("LD_LIBRARY_PATH", "")+ env["LD_LIBRARY_PATH"] = (+ f"{binary_dir}:{existing_ld}" if existing_ld else str(binary_dir)+ )+ probe_script = Path(__file__).with_name("_vulkan_probe.py")+ try:+ result = subprocess.run(+ [sys.executable, str(probe_script), str(binary_dir)],+ capture_output = True,+ text = True,+ timeout = 15,+ env = env,+ **_windows_hidden_subprocess_kwargs(),+ )+ if result.returncode != 0:+ logger.debug(+ f"vulkan GPU probe exited {result.returncode}: {result.stderr.strip()}"+ )+ return []+ except Exception as e:+ logger.debug(f"vulkan GPU probe failed: {e}")+ return []++ gpus: list[tuple[int, int, int]] = []+ for line in result.stdout.strip().splitlines():+ parts = line.split("\t")+ if len(parts) != 4:+ continue+ try:+ idx = int(parts[0])+ free_mib = int(parts[1]) // (1024 * 1024)+ is_igpu = parts[2] == "1"+ # iGPU "total" is shared RAM, not a VRAM budget -> keep 0 so the+ # fit stays on free*frac (the host reserve below is its+ # headroom); a discrete card passes its real total through.+ total_mib = 0 if is_igpu else int(parts[3]) // (1024 * 1024)+ except ValueError:+ continue+ capped = _apply_igpu_host_reserve_mib(free_mib, is_igpu)+ if capped < free_mib:+ logger.info(+ f"Vulkan device VK{idx} is an integrated GPU sharing system "+ f"RAM; reserving {free_mib - capped}MiB host headroom "+ f"({free_mib}->{capped}MiB usable)"+ )+ gpus.append((idx, capped, total_mib))+ gpus.sort(key = lambda g: g[0])+ if gpus:+ logger.info(+ "Vulkan GPU memory detected: "+ + ", ".join(f"VK{idx}={free}MiB" for idx, free, _total in gpus)+ )+ return gpus+@staticmethoddef _available_system_memory_mib() -> Optional[int]:"""Available system RAM in MiB (psutil, then /proc/meminfo), or None if@@ -2807,7 +2991,8 @@ class LlamaCppBackend:def _llama_server_env_for_binary(binary: str) -> dict[str, str]:"""Build a subprocess env that lets llama-server resolve native libs."""env = child_env_without_native_path_secret()- binary_dir = str(Path(binary).parent)+ # _llama_lib_dir resolves the llama-server symlink to the real build/bin.+ binary_dir = str(_llama_lib_dir(binary))if sys.platform == "win32":# Ordering: see _build_windows_path_dirs. #5106.@@ -5210,6 +5395,7 @@ class LlamaCppBackend:# Resolve llama-server now but defer a not-found error: a block-diffusion# GGUF uses the diffusion runner, and its arch is only known after the header.binary = self._find_llama_server_binary()+ is_vulkan_backend = self._is_vulkan_backend(binary)# ── Phase 2: download (NO lock held, so cancel can proceed) ──# mtp_draft_path arrives set for local Gemma loads (detected@@ -5449,7 +5635,8 @@ class LlamaCppBackend:model_size = gguf_size + mmproj_size# 2-tuple gpus for existing logic + a total map for the absolute# per-GPU headroom (correct when the GPU is already partly used).- _gpu_mem = self._get_gpu_memory()+ # Pass binary so a Vulkan build probes ggml's Vulkan ordinals.+ _gpu_mem = self._get_gpu_memory(binary)gpus = [(idx, free) for idx, free, _t in _gpu_mem]total_by_idx = {idx: total for idx, _f, total in _gpu_mem}@@ -6222,7 +6409,12 @@ class LlamaCppBackend:# cap, not the ROCm-reported VRAM, is the real ceiling); refuse an# oversize load the OS would otherwise kill mid-flight. Base model# only: an optional MTP drafter is dropped by the MTP-drop fallback.- if model_size is not None and self._amd_apu_wants_unified_memory(gpu_indices):+ # CUDA/ROCm ids only; a Vulkan build's gpu_indices are ggml ordinals.+ if (+ model_size is not None+ and not is_vulkan_backend+ and self._amd_apu_wants_unified_memory(gpu_indices)+ ):_ram_msg = self._apu_ram_shortfall_message(model_size, self._available_system_memory_mib())@@ -6485,6 +6677,12 @@ class LlamaCppBackend:", ".join(unsupported_cache_flags),)+ # Vulkan pins via --device (a cmd arg, unlike the env-based+ # CUDA/ROCm pin below), emitted BEFORE user extras so llama.cpp's+ # last-wins parsing lets a user --device override Studio's pick.+ if is_vulkan_backend and gpu_indices is not None:+ cmd += LlamaCppBackend._vulkan_pin_args(gpu_indices)+# User pass-through args go last so llama.cpp's last-wins parsing# lets the user override Studio's auto-set flags. Already# validated by the route via validate_extra_args().@@ -6536,23 +6734,25 @@ class LlamaCppBackend:env.setdefault("OMP_NUM_THREADS", "2")# AMD unified-memory APUs (gfx1150/gfx1151): let llama.cpp use- # shared system RAM. setdefault so a user value wins.- if self._amd_apu_wants_unified_memory(gpu_indices):+ # shared system RAM. setdefault so a user value wins. Not on Vulkan+ # (nor DC below): gpu_indices are ggml ordinals, not CUDA/ROCm ids.+ if not is_vulkan_backend and self._amd_apu_wants_unified_memory(gpu_indices):env.setdefault("GGML_CUDA_ENABLE_UNIFIED_MEMORY", "1")logger.info("AMD unified-memory APU: set GGML_CUDA_ENABLE_UNIFIED_MEMORY=1")# DC NVIDIA GPUs: FP32 accum (+ P2P / launch queues for multi-GPU).# See _apply_datacenter_env; opt out with UNSLOTH_DISABLE_DC_TUNING=1.- if self._apply_datacenter_env(env, gpu_indices):+ if not is_vulkan_backend and self._apply_datacenter_env(env, gpu_indices):multi_gpu = self._effective_gpu_count(gpu_indices) > 1logger.info(f"Data-center GPU detected: applied DC llama.cpp env tuning (multi_gpu={multi_gpu})")# Pin to selected GPU(s). On ROCm, narrowing only- # CUDA_VISIBLE_DEVICES leaves an AMD child seeing the full- # set, so set HIP_VISIBLE_DEVICES too.- if gpu_indices is not None:+ # CUDA_VISIBLE_DEVICES leaves an AMD child seeing the full set, so+ # set HIP_VISIBLE_DEVICES too. Vulkan is pinned via --device+ # (above), not here.+ if gpu_indices is not None and not is_vulkan_backend:pinned = ",".join(str(i) for i in gpu_indices)env["CUDA_VISIBLE_DEVICES"] = pinnedtry:diff --git a/studio/backend/tests/test_install_resolve_prebuilt.py b/studio/backend/tests/test_install_resolve_prebuilt.pyindex b825172a63a..090d2932ea9 100644--- a/studio/backend/tests/test_install_resolve_prebuilt.py+++ b/studio/backend/tests/test_install_resolve_prebuilt.py@@ -55,6 +55,27 @@ def _host(**kw):return ilp.HostInfo(**base)+def test_force_cpu_clears_all_gpu_attributes_including_intel():+ # --cpu-fallback is the "select the CPU prebuilt even when a GPU is present"+ # escape hatch. It must drop EVERY GPU attribute, including has_intel_gpu, or+ # the planner still prepends the Vulkan asset on an Intel-GPU host.+ host = _host(+ is_linux = True,+ is_x86_64 = True,+ has_usable_nvidia = True,+ has_physical_nvidia = True,+ has_rocm = True,+ rocm_gfx_target = "gfx1100",+ has_intel_gpu = True,+ )+ forced = ilp._apply_host_overrides(host, force_cpu = True)+ assert forced.has_usable_nvidia is False+ assert forced.has_physical_nvidia is False+ assert forced.has_rocm is False+ assert forced.rocm_gfx_target is None+ assert forced.has_intel_gpu is False++def test_macos_upstream_pin_only_for_explicit_pre26_upstream():pre26 = _host(system = "Darwin",@@ -313,3 +334,152 @@ def test_sm103_host_drops_cuda128_windows_build():)kept_b200 = ilp._drop_blackwell_incapable_windows_cuda(b200, [cuda128, cuda129])assert [a.name for a in kept_b200] == [cuda128.name, cuda129.name]+++def _upstream_release(tag, asset_names):+ return {+ "tag_name": tag,+ "assets": [+ {"name": n, "browser_download_url": f"https://example/{n}"} for n in asset_names+ ],+ }+++def test_direct_upstream_arm64_intel_prefers_vulkan():+ # Auto-detected Intel GPU on Linux arm64 -> Vulkan prebuilt first, CPU+ # second (mirrors the x86_64 branch; ggml-org ships the arm64 Vulkan asset).+ host = _host(is_linux = True, is_arm64 = True, machine = "aarch64", has_intel_gpu = True)+ rel = _upstream_release(+ "b9925",+ ["llama-b9925-bin-ubuntu-vulkan-arm64.tar.gz", "llama-b9925-bin-ubuntu-arm64.tar.gz"],+ )+ plan = ilp.direct_upstream_release_plan(rel, host, UPSTREAM, "latest")+ kinds = [a.install_kind for a in plan.attempts]+ assert kinds[0] == "linux-vulkan", kinds+ assert "linux-arm64" in kinds+ assert plan.attempts[0].name == "llama-b9925-bin-ubuntu-vulkan-arm64.tar.gz"+++def test_direct_upstream_intel_with_hidden_nvidia_is_cpu_only():+ # A host with a physical NVIDIA hidden via CUDA_VISIBLE_DEVICES (physical+ # True, usable False) + an Intel iGPU must NOT get the Vulkan archive even+ # when planning directly against upstream: Vulkan ignores CUDA_VISIBLE_DEVICES+ # and could grab the reserved card. It falls through to the CPU asset.+ host = _host(+ is_linux = True,+ is_x86_64 = True,+ has_intel_gpu = True,+ has_physical_nvidia = True,+ has_usable_nvidia = False,+ )+ rel = _upstream_release(+ "b9925",+ ["llama-b9925-bin-ubuntu-vulkan-x64.tar.gz", "llama-b9925-bin-ubuntu-x64.tar.gz"],+ )+ plan = ilp.direct_upstream_release_plan(rel, host, UPSTREAM, "latest")+ assert [a.install_kind for a in plan.attempts] == ["linux-cpu"]+++def test_direct_upstream_arm64_without_intel_is_cpu_only():+ host = _host(is_linux = True, is_arm64 = True, machine = "aarch64")+ rel = _upstream_release(+ "b9925",+ ["llama-b9925-bin-ubuntu-vulkan-arm64.tar.gz", "llama-b9925-bin-ubuntu-arm64.tar.gz"],+ )+ plan = ilp.direct_upstream_release_plan(rel, host, UPSTREAM, "latest")+ assert [a.install_kind for a in plan.attempts] == ["linux-arm64"]+++def test_direct_upstream_x86_intel_prefers_vulkan():+ host = _host(is_linux = True, is_x86_64 = True, has_intel_gpu = True)+ rel = _upstream_release(+ "b9925",+ ["llama-b9925-bin-ubuntu-vulkan-x64.tar.gz", "llama-b9925-bin-ubuntu-x64.tar.gz"],+ )+ plan = ilp.direct_upstream_release_plan(rel, host, UPSTREAM, "latest")+ kinds = [a.install_kind for a in plan.attempts]+ assert kinds[0] == "linux-vulkan", kinds+ assert "linux-cpu" in kinds+++def test_linux_vulkan_health_glob_matches_bare_cpu_lib():+ # The widened glob must cover both arch-suffixed (x64) and bare (arm64) CPU+ # libs so a valid Vulkan install is not re-flagged unhealthy every check.+ choice = ilp.AssetChoice(+ repo = UPSTREAM,+ tag = "b9925",+ name = "llama-b9925-bin-ubuntu-vulkan-arm64.tar.gz",+ url = "https://example/x",+ source_label = "upstream",+ install_kind = "linux-vulkan",+ )+ groups = ilp.runtime_payload_health_groups(choice)+ assert ["libggml-cpu*.so*"] in groups+ assert ["libggml-cpu-*.so*"] not in groups+++def test_route_to_vulkan_prebuilt_auto_intel_goes_upstream_and_drops_fork_pin():+ # Routing fork -> upstream also drops the fork release pin, which is in a+ # different tag namespace and would make the upstream resolver miss.+ host = _host(is_linux = True, is_x86_64 = True, has_intel_gpu = True)+ routed, repo, tag = ilp._route_to_vulkan_prebuilt(host, FORK, "b9596-mix-abc", force_cpu = False)+ assert repo == UPSTREAM+ assert tag == ""+ assert routed.has_intel_gpu is True+++def test_route_to_vulkan_prebuilt_preserves_explicit_upstream_pin():+ # A pin set WITH an explicit upstream repo is already on upstream -> kept.+ host = _host(is_linux = True, is_x86_64 = True, has_intel_gpu = True)+ _routed, repo, tag = ilp._route_to_vulkan_prebuilt(host, UPSTREAM, "b9596", force_cpu = False)+ assert repo == UPSTREAM+ assert tag == "b9596"+++def test_route_to_vulkan_prebuilt_cpu_fallback_wins():+ # --cpu-fallback suppresses Vulkan routing even for an Intel host.+ host = _host(is_linux = True, is_x86_64 = True, has_intel_gpu = True)+ routed, repo, tag = ilp._route_to_vulkan_prebuilt(host, FORK, "b9596-mix-abc", force_cpu = True)+ assert repo == FORK+ assert tag == "b9596-mix-abc"+ assert routed is host+++def test_route_to_vulkan_prebuilt_hidden_nvidia_not_rerouted():+ # A mixed NVIDIA+Intel host that hid NVIDIA (CUDA_VISIBLE_DEVICES=""/-1):+ # physical NVIDIA present but not usable. Must NOT auto-route to Vulkan, or+ # Vulkan (which ignores CUDA_VISIBLE_DEVICES) could grab the reserved GPU.+ host = _host(+ is_linux = True,+ is_x86_64 = True,+ has_intel_gpu = True,+ has_physical_nvidia = True,+ has_usable_nvidia = False,+ )+ _routed, repo, _tag = ilp._route_to_vulkan_prebuilt(host, FORK, "", force_cpu = False)+ assert repo == FORK+++def test_route_to_vulkan_prebuilt_rocm_host_not_rerouted():+ # An Intel iGPU alongside a usable ROCm GPU stays on its ROCm/fork path.+ host = _host(is_linux = True, is_x86_64 = True, has_intel_gpu = True, has_rocm = True)+ _routed, repo, _tag = ilp._route_to_vulkan_prebuilt(host, FORK, "", force_cpu = False)+ assert repo == FORK+++def test_route_to_vulkan_prebuilt_non_intel_unchanged():+ host = _host(is_linux = True, is_x86_64 = True)+ routed, repo, _tag = ilp._route_to_vulkan_prebuilt(host, FORK, "", force_cpu = False)+ assert repo == FORK+ assert routed is host+++def test_resolve_prebuilt_intel_host_routes_to_upstream(monkeypatch, capsys):+ # The --resolve-prebuilt probe must agree with the install path: an+ # auto-detected Intel host resolves against upstream (Vulkan), not the fork.+ monkeypatch.setattr(+ ilp, "detect_host", lambda: _host(is_linux = True, is_x86_64 = True, has_intel_gpu = True)+ )+ seen, out = _run_resolve_capture_host(monkeypatch, capsys)+ assert seen["repo"] == UPSTREAM+ assert out["repo"] == UPSTREAMdiff --git a/studio/backend/tests/test_llama_cpp_update.py b/studio/backend/tests/test_llama_cpp_update.pyindex 5138e904710..f405ebcbd1e 100644--- a/studio/backend/tests/test_llama_cpp_update.py+++ b/studio/backend/tests/test_llama_cpp_update.py@@ -448,6 +448,48 @@ def test_start_update_happy_path(monkeypatch, tmp_path):assert popen_kwargs["env"]["UNSLOTH_PROGRESS_PERCENT_STEP"] == "5"+def test_start_update_preserves_vulkan_via_env(monkeypatch, tmp_path):+ # A Vulkan install (marker asset carries 'vulkan') must re-assert+ # UNSLOTH_FORCE_VULKAN on update, or detect_host on a GPU box re-routes to+ # CUDA/ROCm and silently replaces the Vulkan build.+ install_dir = tmp_path / "llama.cpp"+ binary = _write_install(+ install_dir,+ "b9493",+ repo = "ggml-org/llama.cpp",+ asset = "llama-b9493-bin-ubuntu-vulkan-x64.tar.gz",+ )+ monkeypatch.setattr(upd, "_find_binary", lambda: binary)+ monkeypatch.setattr(upd, "_installer_script", lambda: tmp_path / "install_llama_prebuilt.py")+ monkeypatch.setattr(freshness, "_fetch_latest_release_tag", lambda repo, timeout = 5.0: "b9518")++ def _on_start(cmd):+ _write_install(+ install_dir,+ "b9518",+ repo = "ggml-org/llama.cpp",+ asset = "llama-b9518-bin-ubuntu-vulkan-x64.tar.gz",+ )++ popen_kwargs: dict = {}+ _patch_installer_popen(+ monkeypatch,+ lines = ["installed\n"],+ on_start = _on_start,+ captured_kwargs = popen_kwargs,+ )++ assert upd.start_update()["started"] is True+ deadline = time.time() + 10+ while time.time() < deadline:+ job = upd.get_update_status()["job"]+ if job["state"] in ("success", "error"):+ break+ time.sleep(0.05)+ assert job["state"] == "success", job+ assert popen_kwargs["env"]["UNSLOTH_FORCE_VULKAN"] == "1"++def test_start_update_reports_full_release_tag(monkeypatch, tmp_path):install_dir = tmp_path / "llama.cpp"binary = _write_install(install_dir, "b9595")diff --git a/studio/backend/tests/test_llama_cpp_vulkan_probe.py b/studio/backend/tests/test_llama_cpp_vulkan_probe.pynew file mode 100644index 00000000000..92aaab4873c--- /dev/null+++ b/studio/backend/tests/test_llama_cpp_vulkan_probe.py@@ -0,0 +1,193 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Vulkan free-VRAM reader regression tests on a synthetic probe output.++Covers the post-probe handling in+``LlamaCppBackend._get_gpu_free_memory_vulkan``:++ * integrated GPUs (probe reports is_igpu=1) leave a flat per-device host+ margin matching llama.cpp's --fit-target, so context auto-sizing can't+ over-commit shared RAM, and report total 0 (shared RAM is not a budget),+ * discrete GPUs (is_igpu=0) keep their free untouched and pass their real+ total through so the fit can reserve absolute headroom,+ * an inherited ``GGML_VK_VISIBLE_DEVICES`` is passed through to ggml unchanged+ (ggml applies it), not stripped or filtered in Python -- the probe reports+ ggml's compact ordinal, which load_model pins with ``--device Vulkan<i>``.++The ggml Vulkan library is never loaded: subprocess.run is mocked to emit+the tab-separated lines the real ``_vulkan_probe.py`` would print.+"""++from __future__ import annotations++import subprocess+import sys+import types as _types+from pathlib import Path+from unittest import mock++import pytest++_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)+if _BACKEND_DIR not in sys.path:+ sys.path.insert(0, _BACKEND_DIR)++import importlib as _importlib # noqa: E402+++def _maybe_stub(name: str, builder):+ try:+ _importlib.import_module(name)+ except ImportError:+ sys.modules[name] = builder()+++def _build_loggers_stub():+ m = _types.ModuleType("loggers")+ m.get_logger = lambda name: __import__("logging").getLogger(name)+ return m+++_maybe_stub("loggers", _build_loggers_stub)+_maybe_stub("structlog", lambda: _types.ModuleType("structlog"))++from core.inference import llama_cpp as _llama_mod # noqa: E402+from core.inference.llama_cpp import ( # noqa: E402+ LlamaCppBackend,+ _llama_lib_dir,+ _vulkan_lib_filename,+)++MIB = 1024 * 1024+GIB = 1024 * MIB+++def _make_vulkan_install(tmp_path: Path) -> str:+ """A binary whose sibling dir holds the Vulkan ggml lib, so the+ reader's ``is_vulkan_backend`` sibling-file check passes."""+ bindir = tmp_path / "build" / "bin"+ bindir.mkdir(parents = True)+ binary = bindir / ("llama-server.exe" if sys.platform == "win32" else "llama-server")+ binary.write_bytes(b"stub")+ (bindir / _vulkan_lib_filename()).write_bytes(b"stub")+ return str(binary)+++def _mock_probe(rows: list[str], captured_env: dict | None = None):+ """Patch subprocess.run so the _vulkan_probe.py call returns ``rows``+ (already tab-formatted), recording the env it was launched with."""+ real_run = subprocess.run++ def fake_run(cmd, *args, **kwargs):+ if isinstance(cmd, list) and any("_vulkan_probe" in str(c) for c in cmd):+ if captured_env is not None:+ captured_env.clear()+ captured_env.update(kwargs.get("env") or {})+ return subprocess.CompletedProcess(+ args = cmd, returncode = 0, stdout = "\n".join(rows), stderr = ""+ )+ return real_run(cmd, *args, **kwargs)++ return mock.patch("subprocess.run", side_effect = fake_run)+++def _row(+ idx: int,+ free_bytes: int,+ is_igpu: int,+ total_bytes: int = 0,+) -> str:+ return f"{idx}\t{free_bytes}\t{is_igpu}\t{total_bytes}"+++def test_integrated_gpu_leaves_host_margin(tmp_path):+ binary = _make_vulkan_install(tmp_path)+ # iGPU with 30 GiB free; reserve a flat 1024 MiB (llama.cpp --fit-target).+ # total stays 0: shared system RAM is not a VRAM budget for the fit.+ rows = [_row(0, 30 * GIB, is_igpu = 1, total_bytes = 32 * GIB)]+ with _mock_probe(rows):+ gpus = LlamaCppBackend._get_gpu_free_memory_vulkan(binary)+ assert gpus == [(0, 30 * 1024 - 1024, 0)], gpus+++def test_discrete_gpu_free_is_untouched_and_total_passed_through(tmp_path):+ binary = _make_vulkan_install(tmp_path)+ # 6 GiB free on a partially occupied 24 GiB card: free is untouched and the+ # real total flows through so the fit reserves absolute headroom (CUDA/ROCm+ # parity) instead of the looser free*frac budget.+ rows = [_row(0, 6 * GIB, is_igpu = 0, total_bytes = 24 * GIB)]+ with _mock_probe(rows):+ gpus = LlamaCppBackend._get_gpu_free_memory_vulkan(binary)+ assert gpus == [(0, 6 * 1024, 24 * 1024)], gpus+++def test_large_discrete_gpu_is_untouched(tmp_path):+ binary = _make_vulkan_install(tmp_path)+ # A 48 GiB discrete card stays untouched regardless of size; only the+ # iGPU flag triggers the host margin, never a VRAM/RAM ratio.+ rows = [_row(0, 47 * GIB, is_igpu = 0, total_bytes = 48 * GIB)]+ with _mock_probe(rows):+ gpus = LlamaCppBackend._get_gpu_free_memory_vulkan(binary)+ assert gpus == [(0, 47 * 1024, 48 * 1024)], gpus+++def test_inherited_visible_devices_mask_is_passed_through_to_probe(tmp_path, monkeypatch):+ # The mask is NOT stripped or filtered in Python: ggml parses it in raw+ # physical-device space while this probe reports the compact post-filter+ # ordinal, so mixing spaces would be wrong. It is passed through unchanged+ # so ggml applies it to the same device list the launch will enumerate.+ binary = _make_vulkan_install(tmp_path)+ monkeypatch.setenv("GGML_VK_VISIBLE_DEVICES", "1")+ captured: dict = {}+ rows = [_row(0, 23 * GIB, is_igpu = 0, total_bytes = 24 * GIB)]+ with _mock_probe(rows, captured_env = captured):+ LlamaCppBackend._get_gpu_free_memory_vulkan(binary)+ assert captured.get("GGML_VK_VISIBLE_DEVICES") == "1", captured+++def test_vulkan_pin_args_uses_device_names_not_env_mask():+ # Pin by compact device name via --device (the space the probe reports and+ # the registry names), never by writing a compact ordinal into the raw+ # GGML_VK_VISIBLE_DEVICES index space.+ assert LlamaCppBackend._vulkan_pin_args([0]) == ["--device", "Vulkan0"]+ assert LlamaCppBackend._vulkan_pin_args([1, 2]) == ["--device", "Vulkan1,Vulkan2"]+ assert LlamaCppBackend._vulkan_pin_args(None) == []+ assert LlamaCppBackend._vulkan_pin_args([]) == []+++def test_vulkan_only_build_is_detected(tmp_path):+ binary = _make_vulkan_install(tmp_path)+ assert LlamaCppBackend._is_vulkan_backend(binary) is True+++def test_multi_backend_build_is_not_vulkan_only(tmp_path):+ # A custom build that ships CUDA (or HIP) alongside Vulkan must NOT be+ # treated as Vulkan-only, or its CUDA GPU would be probed/pinned as a Vulkan+ # device; defer to the CUDA/HIP path instead.+ binary = _make_vulkan_install(tmp_path)+ cuda = "ggml-cuda.dll" if sys.platform == "win32" else "libggml-cuda.so"+ (_llama_lib_dir(binary) / cuda).write_bytes(b"stub")+ assert LlamaCppBackend._is_vulkan_backend(binary) is False++[email protected](sys.platform == "win32", reason = "shell wrapper fallback is POSIX")+def test_shell_wrapper_entrypoint_resolves_to_real_lib_dir(tmp_path):+ # create_exec_entrypoint falls back to a #!/bin/sh wrapper at the install root+ # when it cannot symlink; _find_llama_server_binary returns that root entrypoint,+ # so _llama_lib_dir must follow the wrapper's exec target to build/bin -- else+ # _is_vulkan_backend misses libggml-vulkan.so and the Vulkan probe/pin silently+ # never engage on a valid Vulkan install.+ import os++ binary = _make_vulkan_install(tmp_path) # tmp_path/build/bin/llama-server + vulkan lib+ bindir = Path(binary).parent+ wrapper = tmp_path / "llama-server"+ wrapper.write_text('#!/bin/sh\nexec "$(dirname "$0")/build/bin/llama-server" "$@"\n')+ os.chmod(wrapper, 0o755)+ assert _llama_lib_dir(str(wrapper)) == bindir+ assert LlamaCppBackend._is_vulkan_backend(str(wrapper)) is True+++if __name__ == "__main__":+ raise SystemExit(pytest.main([__file__, "-v"]))diff --git a/studio/backend/utils/llama_cpp_update.py b/studio/backend/utils/llama_cpp_update.pyindex c16ae91467e..1bcbfbf95a8 100644--- a/studio/backend/utils/llama_cpp_update.py+++ b/studio/backend/utils/llama_cpp_update.py@@ -514,6 +514,12 @@ def _run_update(install_dir: Path, repo: str, asset: Optional[str], script: Pathlogger.info("llama update: installing", cmd = " ".join(cmd))# Stream progress lines into job["progress"].env = dict(os.environ, UNSLOTH_PROGRESS_PERCENT_STEP = "5")+ # Preserve a Vulkan install across updates: detect_host on a CUDA/ROCm+ # box would otherwise re-route and silently replace the Vulkan build.+ # Re-assert it via the same env flag setup uses (mirrors+ # _rocm_install_args).+ if asset and "vulkan" in asset.lower():+ env["UNSLOTH_FORCE_VULKAN"] = "1"proc = subprocess.Popen(cmd,stdout = subprocess.PIPE,diff --git a/studio/install_llama_prebuilt.py b/studio/install_llama_prebuilt.pyindex 6c75e6c394a..856ba714787 100644--- a/studio/install_llama_prebuilt.py+++ b/studio/install_llama_prebuilt.py@@ -10,6 +10,7 @@ import argparseimport atexitimport errnoimport fnmatch+import globimport hashlibimport jsonimport os@@ -265,6 +266,7 @@ class HostInfo:has_physical_nvidia: boolhas_usable_nvidia: boolhas_rocm: bool = False+ has_intel_gpu: bool = Falserocm_gfx_target: str | None = None# (major, minor) from platform.mac_ver(); None off macOS or if unparseable.# Skips a macos prebuilt whose minimum-OS exceeds this host.@@ -1482,6 +1484,24 @@ def direct_upstream_release_plan(install_kind = "windows-hip",))+ # Intel (or other non-NVIDIA/non-AMD) GPU: use the Vulkan prebuilt. Gate+ # on no PHYSICAL NVIDIA (not just no usable one): a host that hid NVIDIA+ # via CUDA_VISIBLE_DEVICES must not reach Vulkan, which ignores that mask+ # and could enumerate the reserved card. Falls through to CPU below.+ elif host.has_intel_gpu and not host.has_physical_nvidia:+ vulkan_asset = f"llama-{release_tag}-bin-win-vulkan-x64.zip"+ vulkan_url = assets.get(vulkan_asset)+ if vulkan_url:+ attempts.append(+ AssetChoice(+ repo = repo,+ tag = release_tag,+ name = vulkan_asset,+ url = vulkan_url,+ source_label = "upstream",+ install_kind = "windows-vulkan",+ )+ )cpu_asset = f"llama-{release_tag}-bin-win-cpu-x64.zip"cpu_url = assets.get(cpu_asset)if cpu_url:@@ -1545,6 +1565,23 @@ def direct_upstream_release_plan(# ROCm hosts are excluded: this ggml-org path ships no per-gfx ROCm# asset, so they fall through to the empty-attempts raise (HIP source# build) rather than silently getting a CPU binary on a GPU host.+ # Intel (or other non-NVIDIA/non-AMD) GPU: use the Vulkan prebuilt. The+ # elif already excludes usable NVIDIA and ROCm; also require no PHYSICAL+ # NVIDIA so a CUDA-hidden card isn't reached through Vulkan (CPU below).+ if host.has_intel_gpu and not host.has_physical_nvidia:+ vulkan_asset = f"llama-{release_tag}-bin-ubuntu-vulkan-x64.tar.gz"+ vulkan_url = assets.get(vulkan_asset)+ if vulkan_url:+ attempts.append(+ AssetChoice(+ repo = repo,+ tag = release_tag,+ name = vulkan_asset,+ url = vulkan_url,+ source_label = "upstream",+ install_kind = "linux-vulkan",+ )+ )asset_name = f"llama-{release_tag}-bin-ubuntu-x64.tar.gz"asset_url = assets.get(asset_name)if asset_url:@@ -1564,6 +1601,23 @@ def direct_upstream_release_plan(# selector returned 0 attempts and the installer fell back to a# source build on every Linux ARM64 host (DGX Spark, Ampere# Altra, GitHub-hosted ubuntu-24.04-arm runners, etc.).+ # Intel (or other non-NVIDIA/non-AMD) GPU: prefer the Vulkan prebuilt,+ # mirroring the x86_64 branch. Upstream ships bin-ubuntu-vulkan-arm64.+ # No physical NVIDIA: don't reach a CUDA-hidden card through Vulkan.+ if host.has_intel_gpu and not host.has_physical_nvidia and not host.has_rocm:+ vulkan_asset = f"llama-{release_tag}-bin-ubuntu-vulkan-arm64.tar.gz"+ vulkan_url = assets.get(vulkan_asset)+ if vulkan_url:+ attempts.append(+ AssetChoice(+ repo = repo,+ tag = release_tag,+ name = vulkan_asset,+ url = vulkan_url,+ source_label = "upstream",+ install_kind = "linux-vulkan",+ )+ )asset_name = f"llama-{release_tag}-bin-ubuntu-arm64.tar.gz"asset_url = assets.get(asset_name)if asset_url:@@ -3075,6 +3129,40 @@ def detect_host() -> HostInfo:# Note: amdhip64.dll presence alone is NOT treated as GPU evidence# since the HIP SDK can be installed without an AMD GPU.+ # Detect an Intel GPU; gates the Vulkan prebuilt. Linux reads the DRM sysfs+ # vendor id (0x8086); Windows queries the WMI video controller list. Only+ # probed with no usable NVIDIA and no ROCm (matching the Vulkan branches),+ # keeping the probe (notably the Windows powershell call) off that path.+ has_intel_gpu = False+ if not has_usable_nvidia and not has_rocm:+ if is_linux:+ for _vendor_file in glob.glob("/sys/class/drm/card*/device/vendor"):+ try:+ with open(_vendor_file) as _vf:+ if _vf.read().strip().lower() == "0x8086":+ has_intel_gpu = True+ break+ except OSError:+ continue+ elif is_windows:+ _ps = shutil.which("powershell") or shutil.which("pwsh")+ if _ps:+ try:+ _result = run_capture(+ [+ _ps,+ "-NoProfile",+ "-Command",+ "Get-CimInstance Win32_VideoController | "+ "Select-Object -ExpandProperty Name",+ ],+ timeout = 15,+ )+ if _result.returncode == 0 and "intel" in _result.stdout.lower():+ has_intel_gpu = True+ except Exception:+ pass+return HostInfo(system = system,machine = machine,@@ -3090,6 +3178,7 @@ def detect_host() -> HostInfo:has_physical_nvidia = has_physical_nvidia,has_usable_nvidia = has_usable_nvidia,has_rocm = has_rocm,+ has_intel_gpu = has_intel_gpu,rocm_gfx_target = rocm_gfx_target,macos_version = macos_version,)@@ -3126,6 +3215,7 @@ def _apply_host_overrides(has_physical_nvidia = False,has_rocm = False,rocm_gfx_target = None,+ has_intel_gpu = False,)gfx = _normalize_forwarded_gfx(override_rocm_gfx)if gfx:@@ -3866,6 +3956,23 @@ def resolve_upstream_asset_choice(host: HostInfo, llama_tag: str) -> AssetChoice"falling back to source build with HIP support")+ # Intel (or other non-NVIDIA/non-AMD) GPU: use the Vulkan prebuilt. No+ # physical NVIDIA (not just no usable one): a CUDA-hidden card must not+ # be reached through Vulkan, which ignores CUDA_VISIBLE_DEVICES.+ if host.has_intel_gpu and not host.has_physical_nvidia and not host.has_rocm:+ vulkan_name = f"llama-{llama_tag}-bin-ubuntu-vulkan-x64.tar.gz"+ if vulkan_name in upstream_assets:+ log(f"Intel GPU detected -- using upstream Vulkan prebuilt {vulkan_name}")+ return AssetChoice(+ repo = UPSTREAM_REPO,+ tag = llama_tag,+ name = vulkan_name,+ url = upstream_assets[vulkan_name],+ source_label = "upstream",+ install_kind = "linux-vulkan",+ )+ log("Intel GPU detected but no Vulkan prebuilt found -- falling back to CPU")+upstream_name = f"llama-{llama_tag}-bin-ubuntu-x64.tar.gz"if upstream_name not in upstream_assets:raise PrebuiltFallback("upstream Linux CPU asset was not found")@@ -3908,6 +4015,24 @@ def resolve_upstream_asset_choice(host: HostInfo, llama_tag: str) -> AssetChoice)log("AMD ROCm detected on Windows but no HIP prebuilt found -- falling back to CPU")+ # Intel (or other non-NVIDIA/non-AMD) GPU on Windows: use Vulkan. No+ # physical NVIDIA so a CUDA-hidden card isn't reached through Vulkan.+ if host.has_intel_gpu and not host.has_physical_nvidia and not host.has_rocm:+ vulkan_name = f"llama-{llama_tag}-bin-win-vulkan-x64.zip"+ if vulkan_name in upstream_assets:+ log(+ f"Intel GPU detected on Windows -- using upstream Vulkan prebuilt {vulkan_name}"+ )+ return AssetChoice(+ repo = UPSTREAM_REPO,+ tag = llama_tag,+ name = vulkan_name,+ url = upstream_assets[vulkan_name],+ source_label = "upstream",+ install_kind = "windows-vulkan",+ )+ log("Intel GPU detected on Windows but no Vulkan prebuilt found -- falling back to CPU")+upstream_name = f"llama-{llama_tag}-bin-win-cpu-x64.zip"if upstream_name not in upstream_assets:raise PrebuiltFallback("upstream Windows CPU asset was not found")@@ -4503,6 +4628,7 @@ def runtime_patterns_for_choice(choice: AssetChoice) -> list[str]:"linux-arm64-cuda","linux-rocm","linux-arm64",+ "linux-vulkan",}:return ["llama-server", "llama-quantize", "llama-diffusion-gemma-visual-server", "lib*.so*"]if choice.install_kind in {"macos-arm64", "macos-x64"}:@@ -4516,6 +4642,7 @@ def runtime_patterns_for_choice(choice: AssetChoice) -> list[str]:"windows-cpu","windows-cuda","windows-hip",+ "windows-vulkan","windows-rocm","windows-arm64",}:@@ -5731,8 +5858,10 @@ def validate_server("linux-cuda","linux-arm64-cuda","linux-rocm",+ "linux-vulkan","windows-cuda","windows-hip",+ "windows-vulkan","windows-rocm","macos-arm64",}@@ -6354,6 +6483,20 @@ def runtime_payload_health_groups(choice: AssetChoice) -> list[list[str]]:["libmtmd.so*"],["libggml-hip.so*"],]+ if choice.install_kind == "linux-vulkan":+ return [+ ["libllama-common.so*"],+ ["libllama.so*"],+ ["libggml.so*"],+ ["libggml-base.so*"],+ # Match the sibling globs (linux-cuda/-rocm): x64 bundles ship+ # arch-suffixed libggml-cpu-<variant>.so, arm64 may ship a bare+ # libggml-cpu.so; the '-' form missed the latter and re-flagged+ # the install unhealthy on every check.+ ["libggml-cpu*.so*"],+ ["libmtmd.so*"],+ ["libggml-vulkan.so*"],+ ]if choice.install_kind in {"windows-cpu", "windows-arm64"}:return [["llama.dll"]]if choice.install_kind == "windows-cuda":@@ -6373,6 +6516,8 @@ def runtime_payload_health_groups(choice: AssetChoice) -> list[list[str]]:return groupsif choice.install_kind in {"windows-hip", "windows-rocm"}:return [["llama.dll"], ["*hip*.dll"]]+ if choice.install_kind == "windows-vulkan":+ return [["llama.dll"], ["ggml-vulkan.dll"]]return []@@ -6654,6 +6799,89 @@ def validate_prebuilt_attempts(raise PrebuiltFallback("no prebuilt bundle passed validation")+def force_vulkan_requested() -> bool:+ """Whether UNSLOTH_FORCE_VULKAN opts this host into the Vulkan llama.cpp+ prebuilt instead of its detected CUDA/ROCm backend (e.g. so an AMD user can+ run the Vulkan build for inference). Scoped to the llama.cpp backend; the+ torch/training stack installs separately and still sees the real GPU.+ """+ return os.environ.get("UNSLOTH_FORCE_VULKAN", "").strip().lower() in (+ "1",+ "true",+ "yes",+ )+++def _vulkan_only_host(host: HostInfo) -> HostInfo:+ """Rewrite ``host`` so the asset selectors take their Vulkan branch.++ That branch fires on ``has_intel_gpu and not nvidia and not rocm``, so clear+ the CUDA/ROCm flags and raise the integrated-GPU flag. The synthetic flag+ never leaves install planning -- it only routes the llama.cpp prebuilt+ choice, not the torch/training stack.+ """+ return dataclasses_replace(+ host,+ has_usable_nvidia = False,+ has_physical_nvidia = False,+ has_rocm = False,+ has_intel_gpu = True,+ )+++def _route_to_vulkan_prebuilt(+ host: HostInfo, published_repo: str, published_release_tag: str, *, force_cpu: bool+) -> tuple[HostInfo, str, str]:+ """Point a Vulkan-capable host at the upstream ggml-org Vulkan prebuilt.++ The unsloth published repo ships only CUDA/ROCm/CPU assets, so Vulkan comes+ from UPSTREAM_REPO. Two triggers route here, both suppressed under+ --cpu-fallback (the explicit "give me CPU" last resort wins):+ * UNSLOTH_FORCE_VULKAN forces Vulkan over the detected CUDA/ROCm backend;+ * an auto-detected Intel GPU with NO physical NVIDIA/ROCm -- the purpose+ of the has_intel_gpu probe, since the fork manifest ships no Vulkan asset.+ Applied by BOTH the install path and the --resolve-prebuilt probe so the+ "is a prebuilt available" answer matches what actually gets installed.++ Returns the (possibly rewritten) host, repo, and release tag.+ """+ forced = force_vulkan_requested()+ # Gate auto-routing on no PHYSICAL NVIDIA, not merely no usable one: a mixed+ # NVIDIA+Intel host that hides NVIDIA with CUDA_VISIBLE_DEVICES=""/-1 keeps+ # has_physical_nvidia=True while has_usable_nvidia goes False. Vulkan ignores+ # CUDA_VISIBLE_DEVICES, so auto-routing such a host would let it grab the+ # reserved NVIDIA GPU. An explicit UNSLOTH_FORCE_VULKAN still overrides.+ auto_intel = host.has_intel_gpu and not host.has_physical_nvidia and not host.has_rocm+ if force_cpu or not (forced or auto_intel):+ return host, published_repo, published_release_tag+ if host.is_macos:+ if forced:+ log(+ "UNSLOTH_FORCE_VULKAN is set but ignored on macOS "+ "(Metal is used; there is no Vulkan prebuilt)"+ )+ return host, published_repo, published_release_tag+ if forced:+ log(+ "UNSLOTH_FORCE_VULKAN is set; installing the upstream Vulkan "+ "llama.cpp prebuilt instead of the detected GPU backend"+ )+ # Forcing may override a detected NVIDIA/ROCm host, so normalize it to+ # Vulkan-only; an auto-detected Intel host already is.+ host = _vulkan_only_host(host)+ else:+ log("Intel GPU detected; installing the upstream Vulkan llama.cpp prebuilt")+ # Swapping the fork for upstream invalidates a fork release pin: the two use+ # different tag namespaces (fork b9596-mix-<sha> vs upstream b9596), so a+ # pinned fork tag would make the upstream resolver query a nonexistent+ # release and fall back to source. Drop it and let the upstream resolver+ # pick by the requested llama tag. A pin already on an explicit upstream repo+ # (repo unchanged here) is preserved.+ if published_repo != UPSTREAM_REPO:+ published_release_tag = ""+ return host, UPSTREAM_REPO, published_release_tag++def diffusion_visual_server_backfill_needed(install_dir: Path, host: HostInfo, choice: AssetChoice) -> bool:@@ -6696,6 +6924,9 @@ def install_prebuilt(override_rocm_gfx = override_rocm_gfx,force_cpu = force_cpu,)+ host, published_repo, published_release_tag = _route_to_vulkan_prebuilt(+ host, published_repo, published_release_tag, force_cpu = force_cpu+ )choice: AssetChoice | None = Nonetry:with install_lock(install_lock_path(install_dir)):@@ -6708,7 +6939,9 @@ def install_prebuilt(f"no existing llama.cpp install detected at {install_dir}; performing fresh prebuilt install")# Single resolver: every fork host selects from the release manifest;- # an explicit ggml-org override selects by asset filename instead.+ # an explicit ggml-org override selects by asset filename instead. A+ # forced-Vulkan host already has published_repo pointed at+ # UPSTREAM_REPO above, so the resolver takes the Vulkan asset branch.requested_tag, release_plans = resolve_simple_install_release_plans(llama_tag,host,@@ -6994,10 +7227,14 @@ def main() -> int:override_rocm_gfx = args.rocm_gfx,force_cpu = args.cpu_fallback,)- repo = args.published_repo+ # Same Vulkan routing the install path applies, so the probe's answer+ # matches what would install (an Intel/forced-Vulkan host -> upstream).+ host, repo, release_tag = _route_to_vulkan_prebuilt(+ host, args.published_repo, args.published_release_tag or "", force_cpu = args.cpu_fallback+ )try:_requested, plans = resolve_simple_install_release_plans(- args.resolve_prebuilt, host, repo, args.published_release_tag or ""+ args.resolve_prebuilt, host, repo, release_tag)choice = plans[0].attempts[0] if plans and plans[0].attempts else Noneif choice is None: