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
feat(studio): add UNSLOTH_LLAMA_CPP_BACKEND env var to force CPU fallback #7213 (#7228)
Naitik Palcf912cbd8811
diff --git a/studio/backend/tests/test_install_resolve_prebuilt.py b/studio/backend/tests/test_install_resolve_prebuilt.pyindex e97ca47717e..3ebad861ad9 100644--- a/studio/backend/tests/test_install_resolve_prebuilt.py+++ b/studio/backend/tests/test_install_resolve_prebuilt.py@@ -445,6 +445,101 @@ def test_route_to_vulkan_prebuilt_cpu_fallback_wins():assert routed is host[email protected]("cpu_flag", ["--cpu-fallback", "--force-cpu"])+def test_resolve_prebuilt_cpu_fallback_overrides_intel_vulkan(monkeypatch, capsys, cpu_flag):+ """Either CPU flag via CLI must suppress Vulkan even on an Intel GPU host: both+ drop GPU detection (--force-cpu additionally persists, on the install path)."""+ monkeypatch.setattr(+ ilp,+ "detect_host",+ lambda: _host(is_linux = True, is_x86_64 = True, has_intel_gpu = True),+ )+ seen = {}++ def _resolver(tag, host, repo, published_release_tag):+ seen["host"] = host+ seen["repo"] = repo+ raise ilp.PrebuiltFallback("no asset")++ monkeypatch.setattr(ilp, "resolve_simple_install_release_plans", _resolver)+ monkeypatch.setattr(+ sys,+ "argv",+ [+ "install_llama_prebuilt.py",+ "--resolve-prebuilt",+ "latest",+ cpu_flag,+ "--output-format",+ "json",+ ],+ )+ assert ilp.main() == ilp.EXIT_SUCCESS+ # The CPU flag must suppress Intel GPU, route to fork (not upstream Vulkan)+ assert seen["host"].has_intel_gpu is False+ assert seen["repo"] == FORK+++ "flags, expect_force, expect_persist",+ [+ ([], False, False),+ # Automatic/transient last resort (arm64 GPU-build recovery): drops GPU but+ # does NOT persist, so a later update heals to a GPU bundle (#6097).+ (["--cpu-fallback"], True, False),+ # Deliberate CPU-only (UNSLOTH_LLAMA_CPP_BACKEND=cpu): drops GPU AND persists so+ # the updater re-asserts it and never revives the Intel iGPU crash (#7213).+ (["--force-cpu"], True, True),+ (["--cpu-fallback", "--force-cpu"], True, True),+ ],+)+def test_cli_cpu_flags_thread_force_and_persist(+ monkeypatch, tmp_path, flags, expect_force, expect_persist+):+ captured = {}+ monkeypatch.setattr(ilp, "install_prebuilt", lambda **kw: captured.update(kw))+ monkeypatch.setattr(+ sys,+ "argv",+ ["install_llama_prebuilt.py", "--install-dir", str(tmp_path / "llama.cpp"), *flags],+ )+ assert ilp.main() == ilp.EXIT_SUCCESS+ assert captured["force_cpu"] is expect_force+ assert captured["persist_force_cpu"] is expect_persist+++ "existing, requested, expected",+ [+ # A deliberate --force-cpu on top of a naturally-installed CPU bundle (same+ # asset, install skipped) must still flip the marker to true (#7213).+ (False, True, True),+ (None, True, True),+ # No spurious writes when already in sync, and a released force syncs down.+ (True, True, True),+ (False, False, False),+ (True, False, False),+ ],+)+def test_sync_marker_force_cpu(tmp_path, existing, requested, expected):+ marker = {"tag": "b9585", "asset": "llama-b9585-bin-ubuntu-x64.tar.gz"}+ if existing is not None:+ marker["force_cpu"] = existing+ marker_path = tmp_path / "UNSLOTH_PREBUILT_INFO.json"+ marker_path.write_text(json.dumps(marker))+ ilp.sync_marker_force_cpu(tmp_path, requested)+ written = json.loads(marker_path.read_text())+ assert written["force_cpu"] is expected+ # Unrelated fields are preserved.+ assert written["asset"] == "llama-b9585-bin-ubuntu-x64.tar.gz"+++def test_sync_marker_force_cpu_missing_marker_is_noop(tmp_path):+ # No marker (or unreadable) must not crash the reuse path.+ ilp.sync_marker_force_cpu(tmp_path, True)+ assert not (tmp_path / "UNSLOTH_PREBUILT_INFO.json").exists()++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, ordiff --git a/studio/backend/tests/test_llama_cpp_update.py b/studio/backend/tests/test_llama_cpp_update.pyindex 83ea07a0662..f12384231f4 100644--- a/studio/backend/tests/test_llama_cpp_update.py+++ b/studio/backend/tests/test_llama_cpp_update.py@@ -83,6 +83,7 @@ def _write_install(repo: str = "unslothai/llama.cpp",asset: str | None = None,release_tag: str | None = None,+ force_cpu: bool | None = None,) -> str:"""Create a fake prebuilt install and return the llama-server path."""bin_dir = dir_ / "build" / "bin"@@ -99,6 +100,8 @@ def _write_install(}if asset is not None:marker["asset"] = asset+ if force_cpu is not None:+ marker["force_cpu"] = force_cpu(dir_ / MARKER).write_text(json.dumps(marker))return str(binary)@@ -493,6 +496,47 @@ def test_start_update_preserves_vulkan_via_env(monkeypatch, tmp_path):assert popen_kwargs["env"]["UNSLOTH_FORCE_VULKAN"] == "1"+ "force_cpu, expect_flag",+ [+ # A deliberate CPU install (marker force_cpu=True) re-asserts --force-cpu on+ # update so detect_host on a GPU host cannot re-route and revive the crash+ # (#7213); --force-cpu also re-persists the flag for the next update.+ (True, True),+ # A transient fallback (or a legacy marker without the flag) stays free to+ # heal to a GPU bundle (#6097).+ (False, False),+ (None, False),+ ],+)+def test_start_update_cpu_fallback_preserved_by_flag(monkeypatch, tmp_path, force_cpu, expect_flag):+ asset = "llama-b9493-bin-ubuntu-x64.tar.gz"+ install_dir = tmp_path / "llama.cpp"+ binary = _write_install(install_dir, "b9493", asset = asset, force_cpu = force_cpu)+ 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")++ captured: dict = {}++ def _on_start(cmd):+ captured["cmd"] = cmd+ _write_install(install_dir, "b9518", asset = asset, force_cpu = force_cpu)++ _patch_installer_popen(monkeypatch, lines = ["installed\n"], on_start = _on_start)++ 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 ("--force-cpu" in captured["cmd"]) is expect_flag+ assert "--cpu-fallback" not in captured["cmd"]++def test_start_update_reports_full_release_tag(monkeypatch, tmp_path):install_dir = tmp_path / "llama.cpp"binary = _write_install(install_dir, "b9595")@@ -676,7 +720,7 @@ def test_install_cmd_rocm_marker_forwards_gfx(monkeypatch, tmp_path):assert "--rocm-gfx" in cmdassert cmd[cmd.index("--rocm-gfx") + 1] == "gfx110x"assert "--has-rocm" not in cmd- assert "--cpu-fallback" not in cmd+ assert "--force-cpu" not in cmdassert "--simple-policy" not in cmdassert "--published-repo" in cmd and "unslothai/llama.cpp" in cmd@@ -690,17 +734,17 @@ def test_install_cmd_fork_rocm_marker_forwards_has_rocm(monkeypatch, tmp_path):def test_install_cmd_ggml_cpu_marker_has_no_cpu_fallback(monkeypatch, tmp_path):- # Legacy CPU installs recorded a ggml-org marker (new installs use the fork).- # Re-running into the same install-dir/repo reproduces the same CPU bundle;- # --cpu-fallback (which force-drops GPU detection) is reserved for setup.sh's- # arm64 rescue and must not appear here.+ # Legacy CPU installs recorded a ggml-org marker (new installs use the fork) with+ # no force_cpu field. Re-running into the same install-dir/repo reproduces the same+ # CPU bundle; --force-cpu (the persisted-CPU re-assert) must not appear for a marker+ # that never recorded a deliberate CPU choice, so it can still heal to GPU (#6097).cmd = _capture_install_cmd(monkeypatch,tmp_path,repo = "ggml-org/llama.cpp",asset = "llama-b9334-bin-ubuntu-x64.tar.gz",)- assert "--cpu-fallback" not in cmd+ assert "--force-cpu" not in cmdassert "--rocm-gfx" not in cmdassert "--has-rocm" not in cmdassert "--simple-policy" not in cmd@@ -714,7 +758,7 @@ def test_install_cmd_cuda_marker_minimal_and_backward_compatible(monkeypatch, tmassert "--simple-policy" not in cmdassert "--rocm-gfx" not in cmdassert "--has-rocm" not in cmd- assert "--cpu-fallback" not in cmd+ assert "--force-cpu" not in cmddef test_install_cmd_pins_offered_release_tag(monkeypatch, tmp_path):diff --git a/studio/backend/tests/test_setup_llama_cpp_backend.py b/studio/backend/tests/test_setup_llama_cpp_backend.pynew file mode 100644index 00000000000..36928c680c5--- /dev/null+++ b/studio/backend/tests/test_setup_llama_cpp_backend.py@@ -0,0 +1,154 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""setup.sh and setup.ps1 must map UNSLOTH_LLAMA_CPP_BACKEND=cpu to+install_llama_prebuilt.py's --force-cpu so users can force the CPU-only prebuilt+on GPU hosts (#7213). The match is case-insensitive and whitespace-trimmed, an+unrecognized value warns instead of silently falling back, and macOS warns (no+CPU-only bundle). Runs the real block extracted from each script so the tests+track the shipped logic.+"""++import os+import re+import shutil+import subprocess+from pathlib import Path++import pytest++_STUDIO = Path(__file__).resolve().parents[2]+_SETUP_SH = _STUDIO / "setup.sh"+_SETUP_PS1 = _STUDIO / "setup.ps1"+_SKIP_NO_BASH = pytest.mark.skipif(shutil.which("bash") is None, reason = "bash unavailable")+_SKIP_NO_PWSH = pytest.mark.skipif(shutil.which("pwsh") is None, reason = "pwsh unavailable")+++def _backend_block() -> str:+ text = _SETUP_SH.read_text(encoding = "utf-8")+ m = re.search(r"_llama_backend=.*?esac", text, re.DOTALL)+ assert m, "UNSLOTH_LLAMA_CPP_BACKEND block not found in setup.sh"+ return m.group(0)+++def _run(value: str | None, system: str = "Linux") -> tuple[list[str], str]:+ # Pass the value through env (not the script text) so whitespace survives, and+ # stub the setup.sh logging helpers the unknown-value branch calls. system sets+ # _HOST_SYSTEM so the macOS (Darwin) no-op branch can be exercised.+ env = {k: v for k, v in os.environ.items() if k != "UNSLOTH_LLAMA_CPP_BACKEND"}+ if value is not None:+ env["UNSLOTH_LLAMA_CPP_BACKEND"] = value+ harness = (+ f'_PREBUILT_CMD=()\nC_WARN=""\n_HOST_SYSTEM="{system}"\n'+ 'step() { printf "STEP: %s\\n" "$*" >&2; }\n'+ f"{_backend_block()}\n"+ 'printf "%s\\n" "${_PREBUILT_CMD[@]}"'+ )+ out = subprocess.run(+ ["bash", "-c", harness], capture_output = True, text = True, env = env, check = True+ )+ return out.stdout.split(), out.stderr+++@_SKIP_NO_BASH[email protected]("value", ["cpu", "CPU", "Cpu", " cpu ", "CPU\t"])+def test_backend_cpu_appends_flag(value):+ # A deliberate CPU choice persists, so it uses --force-cpu (not the transient+ # --cpu-fallback the arm64 GPU-build recovery uses).+ args, stderr = _run(value)+ assert "--force-cpu" in args+ assert "--cpu-fallback" not in args+ assert "Ignoring" not in stderr+++@_SKIP_NO_BASH[email protected]("value", ["cpu", "CPU", " cpu "])+def test_backend_cpu_macos_warns_no_flag(value):+ # macOS has no CPU-only bundle (the universal build already runs on CPU), so the+ # override warns instead of writing a misleading forced-CPU marker.+ args, stderr = _run(value, system = "Darwin")+ assert "--force-cpu" not in args+ assert "--cpu-fallback" not in args+ assert "macOS" in stderr+++@_SKIP_NO_BASH[email protected]("value", [None, "", "auto", "AUTO", " "])+def test_backend_auto_no_flag_no_warn(value):+ args, stderr = _run(value)+ assert "--force-cpu" not in args+ assert "Ignoring" not in stderr+++@_SKIP_NO_BASH[email protected]("value", ["vulkan", "gpu", "cuda"])+def test_backend_unknown_warns_and_no_flag(value):+ args, stderr = _run(value)+ assert "--force-cpu" not in args+ assert "Ignoring" in stderr+++@_SKIP_NO_BASH+def test_arm64_recovery_uses_transient_cpu_fallback():+ # The arm64 Linux GPU-build recovery must stay transient (--cpu-fallback), never+ # the persisted --force-cpu, so a later update can still heal to a GPU bundle (#6097).+ text = _SETUP_SH.read_text(encoding = "utf-8")+ m = re.search(r"_ARM64_CPU_CMD=\((.*?)\)", text, re.DOTALL)+ assert m, "arm64 CPU recovery command not found in setup.sh"+ block = m.group(1)+ assert "--cpu-fallback" in block+ assert "--force-cpu" not in block+++def _ps1_search(pattern: str, flags = 0) -> str:+ m = re.search(pattern, _SETUP_PS1.read_text(encoding = "utf-8"), flags)+ assert m, f"setup.ps1 block not found: {pattern}"+ return m.group(0)+++def _run_ps1(value: str | None) -> str:+ # The override is normalized (assign + warn) at the top of the prebuilt block and+ # applied to $prebuiltArgs lower down; compose both real snippets.+ normalize = _ps1_search(+ r'\$llamaBackend = "\$\(\$env:UNSLOTH_LLAMA_CPP_BACKEND\)".*?Write-Host.*?\n\s*\}',+ re.DOTALL,+ )+ apply_flag = _ps1_search(+ r'if \(\$llamaBackend -eq "cpu"\) \{\s*\$prebuiltArgs \+= "--force-cpu"\s*\}'+ )+ env = {k: v for k, v in os.environ.items() if k != "UNSLOTH_LLAMA_CPP_BACKEND"}+ if value is not None:+ env["UNSLOTH_LLAMA_CPP_BACKEND"] = value+ harness = f'$prebuiltArgs = @()\n{normalize}\n{apply_flag}\n"ARGS:" + ($prebuiltArgs -join ",")'+ out = subprocess.run(+ ["pwsh", "-NoProfile", "-Command", harness],+ capture_output = True,+ text = True,+ env = env,+ check = True,+ )+ return out.stdout+++@_SKIP_NO_PWSH[email protected]("value", ["cpu", "CPU", "Cpu", " cpu ", "CPU\t"])+def test_ps1_backend_cpu_appends_flag(value):+ out = _run_ps1(value)+ assert "--force-cpu" in out+ assert "Ignoring" not in out+++@_SKIP_NO_PWSH[email protected]("value", [None, "", "auto", "AUTO", " "])+def test_ps1_backend_auto_no_flag_no_warn(value):+ out = _run_ps1(value)+ assert "--force-cpu" not in out+ assert "Ignoring" not in out+++@_SKIP_NO_PWSH[email protected]("value", ["vulkan", "gpu", "cuda"])+def test_ps1_backend_unknown_warns_and_no_flag(value):+ out = _run_ps1(value)+ assert "--force-cpu" not in out+ assert "Ignoring" in outdiff --git a/studio/backend/utils/llama_cpp_update.py b/studio/backend/utils/llama_cpp_update.pyindex 31dbda63eae..67733bde35e 100644--- a/studio/backend/utils/llama_cpp_update.py+++ b/studio/backend/utils/llama_cpp_update.py@@ -479,6 +479,7 @@ def _run_update(asset: Optional[str],script: Path,pin_release_tag: Optional[str] = None,+ force_cpu: bool = False,) -> None:"""Worker: put the backend into a maintenance state, run the installer forthe latest prebuilt, then refresh caches so the next load uses the new build.@@ -522,6 +523,12 @@ def _run_update(if pin_release_tag:cmd.extend(["--published-release-tag", pin_release_tag])cmd.extend(_rocm_install_args(asset))+ # Re-assert a deliberate CPU install (--force-cpu) so detect_host on a GPU host+ # does not re-route to a GPU/Vulkan bundle and revive the crash (#7213). --force-cpu+ # (not --cpu-fallback) also re-persists force_cpu, keeping the choice across future+ # updates. A natural fallback (or a legacy marker without the flag) heals to GPU (#6097).+ if force_cpu:+ cmd.append("--force-cpu")logger.info("llama update: installing", cmd = " ".join(cmd))# Stream progress lines into job["progress"].env = dict(os.environ, UNSLOTH_PROGRESS_PERCENT_STEP = "5")@@ -671,6 +678,7 @@ def start_update() -> dict:repo = marker.get("published_repo") or DEFAULT_PUBLISHED_REPOfrom_tag = marker.get("tag") or marker.get("release_tag")asset = marker.get("asset")+ force_cpu = bool(marker.get("force_cpu"))# Install exactly the release the banner offered: the installer's own# "latest" is commit-date ordered and can lag the published_at pick# above, reinstalling the current build in a loop (the #6219 class).@@ -705,6 +713,8 @@ def start_update() -> dict:repo = (res or {}).get("repo") or DEFAULT_PUBLISHED_REPOfrom_tag = Noneasset = (res or {}).get("asset")+ # Source builds carry no forced-CPU marker, so nothing to preserve here.+ force_cpu = False# No pin: source-build detection resolves via --resolve-prebuilt latest,# the same resolver the unpinned apply uses, so the two already agree.pin_release_tag = None@@ -735,7 +745,7 @@ def start_update() -> dict:thread = threading.Thread(target = _run_update,- args = (install_dir, repo, asset, script, pin_release_tag),+ args = (install_dir, repo, asset, script, pin_release_tag, force_cpu),name = "llama-cpp-update",daemon = True,)diff --git a/studio/install_llama_prebuilt.py b/studio/install_llama_prebuilt.pyindex 9bbd0cb8be3..b8182a534bd 100644--- a/studio/install_llama_prebuilt.py+++ b/studio/install_llama_prebuilt.py@@ -6450,6 +6450,7 @@ def write_prebuilt_metadata(choice: AssetChoice,approved_checksums: ApprovedReleaseChecksums,prebuilt_fallback_used: bool,+ force_cpu: bool = False,) -> None:source_asset_name, source_sha256 = selected_source_archive_metadata(approved_checksums,@@ -6474,6 +6475,10 @@ def write_prebuilt_metadata("release_tag": release_tag,"published_repo": approved_checksums.repo,"asset": choice.name,+ # True only for a deliberate CPU choice (--force-cpu). The updater re-asserts it+ # so a forced CPU install is not re-routed to a GPU bundle (#7213). An automatic+ # --cpu-fallback (e.g. arm64 GPU-build recovery) stays False so it can heal to GPU.+ "force_cpu": force_cpu,"asset_sha256": choice.expected_sha256,"source": choice.source_label,# Binary-side repo/tag for non-fork sources (e.g. the ggml-org upstream@@ -6501,6 +6506,24 @@ def write_prebuilt_metadata((install_dir / "UNSLOTH_PREBUILT_INFO.json").write_text(json.dumps(metadata, indent = 2) + "\n")+def sync_marker_force_cpu(install_dir: Path, persist_force_cpu: bool) -> None:+ """Sync only the force_cpu flag of an existing marker when the resolved bundle is+ unchanged, so the install is skipped without a full metadata rewrite. A deliberate+ --force-cpu on top of a naturally installed CPU bundle (same asset) must still be+ recorded, else the updater will not re-assert it and can re-route the install to a+ GPU/Vulkan bundle that revives the crash (#7213)."""+ marker_path = install_dir / "UNSLOTH_PREBUILT_INFO.json"+ try:+ marker = json.loads(marker_path.read_text())+ except (OSError, ValueError):+ return+ if not isinstance(marker, dict) or bool(marker.get("force_cpu")) == persist_force_cpu:+ return+ marker["force_cpu"] = persist_force_cpu+ marker_path.write_text(json.dumps(marker, indent = 2) + "\n")+ log(f"existing install reused; recorded force_cpu={persist_force_cpu} from this run")++def expected_install_fingerprint(*,llama_tag: str,@@ -6746,6 +6769,7 @@ def validate_prebuilt_choice(approved_checksums: ApprovedReleaseChecksums,prebuilt_fallback_used: bool,quantized_path: Path,+ force_cpu: bool = False,) -> tuple[Path, Path]:source_repo, source_ref, source_archive, exact_source = preferred_source_archive(approved_checksums, llama_tag@@ -6786,6 +6810,7 @@ def validate_prebuilt_choice(choice = choice,approved_checksums = approved_checksums,prebuilt_fallback_used = prebuilt_fallback_used,+ force_cpu = force_cpu,)# Hashless external prebuilts are not in the approved-sha256# manifest and rely on the functional smoke test as their only integrity gate,@@ -6828,6 +6853,7 @@ def validate_prebuilt_attempts(approved_checksums: ApprovedReleaseChecksums,initial_fallback_used: bool = False,existing_install_dir: Path | None = None,+ force_cpu: bool = False,) -> tuple[AssetChoice, Path, bool]:attempt_list = list(attempts)if not attempt_list:@@ -6880,6 +6906,7 @@ def validate_prebuilt_attempts(approved_checksums = approved_checksums,prebuilt_fallback_used = tried_fallback,quantized_path = quantized_path,+ force_cpu = force_cpu,)except Exception as exc:remove_tree(staging_dir)@@ -6939,8 +6966,8 @@ def _route_to_vulkan_prebuilt("""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):+ from UPSTREAM_REPO. Two triggers route here, both suppressed when a CPU flag+ (--cpu-fallback or --force-cpu, folded into force_cpu) wins:* UNSLOTH_FORCE_VULKAN forces Vulkan over the detected CUDA/ROCm backend;* an auto-detected Intel GPU with NO physical NVIDIA/ROCm -- the purposeof the has_intel_gpu probe, since the fork manifest ships no Vulkan asset.@@ -7020,8 +7047,11 @@ def install_prebuilt(override_has_rocm: bool = False,override_rocm_gfx: str | None = None,force_cpu: bool = False,+ persist_force_cpu: bool = False,instruction_cleanup_root: Path | None = None,) -> None:+ # force_cpu drops GPU detection (mechanism, both --cpu-fallback and --force-cpu);+ # persist_force_cpu records the deliberate choice so the updater re-asserts it.host = detect_host()host = _apply_host_overrides(host,@@ -7072,6 +7102,9 @@ def install_prebuilt("existing llama.cpp install already matches selected release "f"{current.release_tag} upstream_tag={current.llama_tag}; skipping download and install")+ # Reused bundle is unchanged, but a fresh --force-cpu still must be+ # recorded so the updater re-asserts it (#7213).+ sync_marker_force_cpu(install_dir, persist_force_cpu)returnwith tempfile.TemporaryDirectory(prefix = "unsloth-llama-prebuilt-") as tmp:work_dir = Path(tmp)@@ -7092,6 +7125,7 @@ def install_prebuilt("existing llama.cpp install already matches fallback release "f"{plan.release_tag} upstream_tag={plan.llama_tag}; skipping reinstall")+ sync_marker_force_cpu(install_dir, persist_force_cpu)returnlog("selected "@@ -7112,6 +7146,8 @@ def install_prebuilt(initial_fallback_used = release_index > 0,# Skip is gated per-attempt inside, so pass the dir always.existing_install_dir = install_dir,+ # Persist only the deliberate choice, not a transient fallback.+ force_cpu = persist_force_cpu,)except ExistingInstallSatisfied:return@@ -7209,8 +7245,21 @@ def parse_args() -> argparse.Namespace:default = False,help = ("Select the CPU prebuilt for this OS/arch even when a GPU is present. "- "setup.sh uses this as a last resort for arm64 Linux GPU hosts whose "- "source build failed (no arm64 CUDA prebuilt exists anywhere)."+ "Automatic/transient: setup.sh uses this as a last resort for arm64 Linux "+ "GPU hosts whose source build failed. Does NOT persist, so a later update "+ "heals back to a GPU bundle once one is available (#6097). Use --force-cpu "+ "for a deliberate CPU-only choice that survives updates."+ ),+ )+ parser.add_argument(+ "--force-cpu",+ action = "store_true",+ default = False,+ help = (+ "Deliberate CPU-only install (UNSLOTH_LLAMA_CPP_BACKEND=cpu). Drops GPU "+ "detection like --cpu-fallback but also records force_cpu in the marker, so "+ "the in-app updater re-asserts CPU and never re-routes to a GPU/Vulkan "+ "bundle that would revive the Intel iGPU crash (#7213)."),)resolve_group = parser.add_mutually_exclusive_group()@@ -7333,16 +7382,19 @@ def main() -> int:# Host-aware "is a prebuilt available" probe, no download. Every host now# plans against the fork (args.published_repo defaults to it); an explicit# --published-repo overrides. PrebuiltFallback == source build.+ # Both flags drop GPU detection; --force-cpu additionally persists (install+ # path only). The probe only needs the mechanism, so OR them.+ _cpu_mechanism = args.cpu_fallback or args.force_cpuhost = _apply_host_overrides(detect_host(),override_has_rocm = args.has_rocm,override_rocm_gfx = args.rocm_gfx,- force_cpu = args.cpu_fallback,+ force_cpu = _cpu_mechanism,)# 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+ host, args.published_repo, args.published_release_tag or "", force_cpu = _cpu_mechanism)try:_requested, plans = resolve_simple_install_release_plans(@@ -7380,7 +7432,10 @@ def main() -> int:published_release_tag = args.published_release_tag or "",override_has_rocm = args.has_rocm,override_rocm_gfx = args.rocm_gfx,- force_cpu = args.cpu_fallback,+ # Both drop GPU detection; only --force-cpu (deliberate) is recorded so the+ # updater re-asserts it. --cpu-fallback stays transient and heals to GPU.+ force_cpu = args.cpu_fallback or args.force_cpu,+ persist_force_cpu = args.force_cpu,instruction_cleanup_root = install_arg.absolute(),)return EXIT_SUCCESSdiff --git a/studio/setup.ps1 b/studio/setup.ps1index 98e801cd3c5..f7d33a11423 100644--- a/studio/setup.ps1+++ b/studio/setup.ps1@@ -32,6 +32,10 @@ $PackageDir = Split-Path -Parent $ScriptDir# (no matching GitHub release), forces a source build, and causes HTTP 422# errors. Only use "master" temporarily when the latest release is missing# support for a new model architecture.+#+# UNSLOTH_LLAMA_CPP_BACKEND : "auto" (default) or "cpu". When "cpu", forces+# the CPU-only prebuilt bundle on GPU hosts. Fixes Intel iGPU Vulkan+# crashes (#7213).$DefaultLlamaPrForce = ""$DefaultLlamaSource = "https://github.com/ggml-org/llama.cpp"$DefaultLlamaTag = "latest"@@ -3367,6 +3371,15 @@ if ($LocalLlamaCppLinked) {if ($env:UNSLOTH_LLAMA_RELEASE_TAG) {$prebuiltArgs += @("--published-release-tag", $env:UNSLOTH_LLAMA_RELEASE_TAG)}+ # UNSLOTH_LLAMA_CPP_BACKEND=cpu (case-insensitive, whitespace-trimmed) forces the+ # CPU-only prebuilt via --force-cpu (persisted so updates keep it). Fixes Intel+ # iGPU Vulkan crash (#7213).+ $llamaBackend = "$($env:UNSLOTH_LLAMA_CPP_BACKEND)".Trim().ToLowerInvariant()+ if ($llamaBackend -eq "cpu") {+ $prebuiltArgs += "--force-cpu"+ } elseif ($llamaBackend -and $llamaBackend -ne "auto") {+ Write-Host "[WARN] Ignoring UNSLOTH_LLAMA_CPP_BACKEND='$($env:UNSLOTH_LLAMA_CPP_BACKEND)' (expected 'auto' or 'cpu')" -ForegroundColor Yellow+ }$prevEAPPrebuilt = $ErrorActionPreference$ErrorActionPreference = "Continue"$previousNativeErrorPreference = $nulldiff --git a/studio/setup.sh b/studio/setup.shindex 8d47eecfda0..df7178c662a 100755--- a/studio/setup.sh+++ b/studio/setup.sh@@ -36,6 +36,10 @@ fi# forces a source build, and causes HTTP 422 errors.# Only use "master" temporarily when the latest release# is missing support for a new model architecture.+#+# UNSLOTH_LLAMA_CPP_BACKEND : "auto" (default) or "cpu". When "cpu", forces+# the CPU-only prebuilt bundle on GPU hosts.+# Fixes Intel iGPU Vulkan crashes (#7213).# ──────────────────────────────────────────────────────────────────────────_DEFAULT_LLAMA_PR_FORCE=""_DEFAULT_LLAMA_SOURCE="https://github.com/ggml-org/llama.cpp"@@ -1359,6 +1363,22 @@ else# present so it can still attempt a prebuilt. Mirrors setup.ps1 behaviour._PREBUILT_CMD+=(--has-rocm)fi+ # UNSLOTH_LLAMA_CPP_BACKEND=cpu (case-insensitive, trimmed) forces the CPU-only+ # prebuilt via --force-cpu, bypassing Vulkan/CUDA/ROCm. Fixes Intel iGPU crash (#7213).+ # No effect on macOS: the universal bundle already runs on CPU (Metal is a runtime+ # -ngl choice), so warn instead of writing a misleading forced-CPU marker.+ _llama_backend="$(printf '%s' "${UNSLOTH_LLAMA_CPP_BACKEND:-auto}" | awk '{$1=$1; print tolower($0)}')"+ case "$_llama_backend" in+ cpu)+ if [ "$_HOST_SYSTEM" = "Darwin" ]; then+ step "llama.cpp" "UNSLOTH_LLAMA_CPP_BACKEND=cpu has no effect on macOS (universal build; use -ngl 0 at runtime for CPU-only)" "$C_WARN" >&2+ else+ _PREBUILT_CMD+=(--force-cpu)+ fi+ ;;+ ""|auto) ;;+ *) step "llama.cpp" "Ignoring UNSLOTH_LLAMA_CPP_BACKEND='$UNSLOTH_LLAMA_CPP_BACKEND' (expected 'auto' or 'cpu')" "$C_WARN" >&2 ;;+ esac_PREBUILT_LOG="$(mktemp)"set +eif _is_verbose; thendiff --git a/tests/studio/install/test_install_llama_prebuilt_logic.py b/tests/studio/install/test_install_llama_prebuilt_logic.pyindex e995e5033ec..9a094ddc0e8 100644--- a/tests/studio/install/test_install_llama_prebuilt_logic.py+++ b/tests/studio/install/test_install_llama_prebuilt_logic.py@@ -1348,6 +1348,7 @@ def test_install_prebuilt_falls_back_to_older_release_plan(approved_checksums,initial_fallback_used = False,existing_install_dir = None,+ force_cpu = False,):call_log.append((llama_tag, initial_fallback_used))if llama_tag == "b9002":@@ -2551,6 +2552,7 @@ def test_install_prebuilt_skips_when_older_release_fallback_matches_existing_insapproved_checksums,initial_fallback_used = False,existing_install_dir = None,+ force_cpu = False,):call_log.append(llama_tag)raise PrebuiltFallback("validation failed for latest release")@@ -2698,6 +2700,7 @@ def test_install_prebuilt_skips_same_release_fallback_attempt_when_installed(approved_checksums,prebuilt_fallback_used,quantized_path,+ force_cpu = False,):attempted_names.append(choice.name)if choice.name == first_choice.name:@@ -2824,6 +2827,7 @@ def test_install_prebuilt_same_tag_upstream_failure_uses_older_unsloth_release_papproved_checksums,initial_fallback_used = False,existing_install_dir = None,+ force_cpu = False,):attempted.append((llama_tag, release_tag, attempts[0].source_label))if llama_tag == "b9002":