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: switch llama.cpp backends from the UI (#8520)
oobabooga5426a78c3965
diff --git a/README.md b/README.mdindex 828859851f7..ca78f126b68 100644--- a/README.md+++ b/README.md@@ -160,10 +160,12 @@ curl -fsSL https://unsloth.ai/install.sh | sh```Use the same command to update.-To force the Vulkan llama.cpp backend, set `UNSLOTH_FORCE_VULKAN=1` **before installing or updating**. The setting selects the llama.cpp binary bundle, so setting it only when launching Studio cannot replace an existing CPU bundle:+The GGUF inference backend can be changed from **Settings > System > GGUF inference engine** once Studio is running: pick CPU, CUDA, ROCm or Vulkan (only the ones with a build for your machine are listed) and Apply. The choice is recorded with the install, so updates keep it, and Automatic returns to hardware detection.++To pick it before the first launch instead, set `UNSLOTH_LLAMA_CPP_BACKEND` **before installing or updating**. It selects the llama.cpp binary bundle, so setting it only when launching Studio cannot replace an existing one, and it overrides whatever was chosen in Settings:```bash-export UNSLOTH_FORCE_VULKAN=1+export UNSLOTH_LLAMA_CPP_BACKEND=vulkan # or cpu, cuda, rocm, autocurl -fsSL https://unsloth.ai/install.sh | sh```@@ -173,14 +175,14 @@ irm https://unsloth.ai/install.ps1 | iex```Use the same command to update.-To force the Vulkan llama.cpp backend, set the environment variable before running the installer or updater:+To pick the GGUF inference backend before the first launch, set the environment variable before running the installer or updater (or change it later in **Settings > System > GGUF inference engine**):```powershell-$env:UNSLOTH_FORCE_VULKAN=1+$env:UNSLOTH_LLAMA_CPP_BACKEND="vulkan" # or cpu, cuda, rocm, autoirm https://unsloth.ai/install.ps1 | iex```-Re-running the current installer replaces a previously selected CPU bundle when the backend differs. A separate Vulkan SDK is not required; the GPU driver must provide a working Vulkan runtime.+Re-running the current installer replaces a previously selected bundle when the backend differs. A separate Vulkan SDK is not required; the GPU driver must provide a working Vulkan runtime.#### Launch```bashdiff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.pyindex b7f35ccb62d..e9bfded9f56 100644--- a/studio/backend/core/inference/llama_cpp.py+++ b/studio/backend/core/inference/llama_cpp.py@@ -10080,30 +10080,33 @@ class LlamaCppBackend:@staticmethoddef _vulkan_prebuilt_was_auto_selected(binary: Optional[str]) -> bool:- """Whether setup chose this managed Vulkan bundle without an override.+ """Whether this managed Vulkan bundle was detected rather than chosen.- Explicit selections set an override or marker. The managed marker also- excludes custom and PATH binaries.+ Only an automatic Vulkan install may be quietly replaced with CPU placement+ on a crash: someone who picked Vulkan in Settings > System (or exported+ the variable) picked it over a GPU backend that presumably crashed too, and+ silently undoing that would be the same bug in the other direction. The+ managed marker also excludes custom and PATH binaries."""if not binary:return False- if os.environ.get("UNSLOTH_FORCE_VULKAN", "").strip().lower() in {- "1",- "true",- "yes",- "on",- }:- return False- if (os.environ.get("UNSLOTH_LLAMA_CPP_BACKEND") or "").strip().lower() in {- "cpu",- "vulkan",- "hip",- "rocm",- }:+ from utils.llama_cpp_update import _llama_install_root+ from utils.prebuilt.llama_backend import (+ environment_backend_override,+ marker_backend_was_chosen,+ )++ # The same precedence the installer applied when it chose this bundle, so+ # a stale UNSLOTH_FORCE_VULKAN cannot mark an install explicit that+ # UNSLOTH_LLAMA_CPP_BACKEND=auto had setup detect. Only a concrete+ # override is a choice; "auto" still has to pass the marker check below.+ override = environment_backend_override(+ os.environ.get("UNSLOTH_LLAMA_CPP_BACKEND"),+ os.environ.get("UNSLOTH_FORCE_VULKAN"),+ )+ if override is not None and override != "auto":return Falsetry:- from utils.llama_cpp_update import _llama_install_root-install_root = _llama_install_root(binary)if install_root is None:return False@@ -10112,11 +10115,8 @@ class LlamaCppBackend:)except (OSError, ValueError, TypeError):return False- return (- isinstance(marker, dict)- and not bool(marker.get("force_cpu"))- and marker.get("llama_backend") in (None, "", "auto")- )+ # Reads new and pre-#7188 markers alike, including the force_cpu-only ones.+ return isinstance(marker, dict) and not marker_backend_was_chosen(marker)@staticmethoddef _strip_cpu_fallback_main_placement(args: Iterable[str]) -> list[str]:diff --git a/studio/backend/routes/llama.py b/studio/backend/routes/llama.pyindex 84b89ad7d5f..e956cc7cae9 100644--- a/studio/backend/routes/llama.py+++ b/studio/backend/routes/llama.py@@ -28,7 +28,12 @@ from pydantic import BaseModel, Fieldfrom auth.authentication import get_current_subjectfrom loggers import get_logger-from utils.llama_cpp_update import get_update_status, start_update+from utils.llama_cpp_update import (+ get_backend_status,+ get_update_status,+ start_backend_switch,+ start_update,+)logger = get_logger(__name__)router = APIRouter()@@ -36,6 +41,8 @@ router = APIRouter()class LlamaUpdateJob(BaseModel):state: str = Field("idle", description = "idle | running | success | error")+ operation: Optional[Literal["update", "switch"]] = None+ requested_backend: Optional[Literal["auto", "cpu", "cuda", "rocm", "vulkan"]] = Nonemessage: str = ""from_tag: Optional[str] = Noneto_tag: Optional[str] = None@@ -158,3 +165,89 @@ async def llama_update() -> LlamaUpdateActionResponse:action = await asyncio.to_thread(start_update)return LlamaUpdateActionResponse(**action)+++class LlamaBackendOption(BaseModel):+ backend: str = Field(..., description = "auto | cpu | cuda | rocm | vulkan")+ available: bool = Field(+ False, description = "True when a prebuilt for this backend installs on this host."+ )+ unavailable_reason: Optional[str] = Field(+ None, description = "unavailable | no_prebuilt | error, when available is false."+ )+ resolved_backend: Optional[str] = Field(+ None, description = "For 'auto', the backend hardware detection picks right now."+ )+ release_tag: Optional[str] = None+ download_size_bytes: Optional[int] = None+++class LlamaBackendStatusResponse(BaseModel):+ supported: bool = Field(+ False, description = "True when this install's backend can be switched from here."+ )+ reason: Optional[str] = Field(+ None,+ description = (+ "Why it cannot: not_installed | local_link | source_build | no_install_dir "+ "| unresolved (the backend list could not be resolved, e.g. offline)."+ ),+ )+ env_backend: Optional[str] = Field(+ None,+ description = (+ "Backend pinned by UNSLOTH_LLAMA_CPP_BACKEND / UNSLOTH_FORCE_VULKAN. It "+ "overrides a stored choice, so the picker shows it as read-only."+ ),+ )+ backend: Optional[str] = Field(None, description = "What the install runs on now.")+ backend_request: str = Field(+ "auto",+ description = (+ "The recorded choice; 'auto' means hardware detection. A name this "+ "build does not know was written by a newer Studio and is read-only."+ ),+ )+ selection_applied: bool = Field(+ True,+ description = (+ "False when the recorded choice is 'auto' and detection would now "+ "resolve to a different backend than the installed one."+ ),+ )+ installed_tag: Optional[str] = None+ options: list[LlamaBackendOption] = Field(default_factory = list)+ job: LlamaUpdateJob = Field(default_factory = LlamaUpdateJob)+++class LlamaBackendRequest(BaseModel):+ backend: Literal["auto", "cpu", "cuda", "rocm", "vulkan"] = Field(+ ..., description = "Backend to install. 'auto' restores hardware detection."+ )++[email protected]("/backend", response_model = LlamaBackendStatusResponse)+async def llama_backend_status(+ force_refresh: bool = Query(+ False, description = "Bypass the 24h resolver cache for an explicit re-check."+ ),+ current_subject: str = Depends(get_current_subject),+) -> LlamaBackendStatusResponse:+ # Off the event loop: resolving the options runs the installer's probe.+ status = await asyncio.to_thread(get_backend_status, force_refresh = force_refresh)+ return LlamaBackendStatusResponse(**status)++[email protected]("/backend", response_model = LlamaUpdateActionResponse)+async def llama_backend_switch(+ request: LlamaBackendRequest, current_subject: str = Depends(get_current_subject)+) -> LlamaUpdateActionResponse:+ """Install the llama.cpp build for another backend and record the choice.++ Shares the update job, so it answers already_running rather than starting a+ second writer against the same install; callers poll /update-status for+ progress exactly as they do for an update.+ """+ logger.info("llama_backend_switch_requested", backend = request.backend)+ action = await asyncio.to_thread(start_backend_switch, request.backend)+ return LlamaUpdateActionResponse(**action)diff --git a/studio/backend/tests/test_gpu_init_crash_message.py b/studio/backend/tests/test_gpu_init_crash_message.pyindex 79ea1229a00..2e04412dcc5 100644--- a/studio/backend/tests/test_gpu_init_crash_message.py+++ b/studio/backend/tests/test_gpu_init_crash_message.py@@ -411,6 +411,22 @@ class TestAutoVulkanCpuFallbackGate:{},)+ def test_auto_suppresses_a_stale_legacy_vulkan_flag(self, monkeypatch, tmp_path):+ # UNSLOTH_LLAMA_CPP_BACKEND=auto outranks UNSLOTH_FORCE_VULKAN everywhere+ # else, so setup detected this bundle rather than being told to install it.+ # Reading the legacy flag as a choice here would leave a crashing Vulkan+ # install with no automatic CPU replay.+ self._managed_marker(monkeypatch, tmp_path, llama_backend = "auto")+ monkeypatch.setattr(+ LlamaCppBackend, "_is_vulkan_backend", staticmethod(lambda _binary = None: True)+ )+ monkeypatch.setenv("UNSLOTH_LLAMA_CPP_BACKEND", "auto")+ monkeypatch.setenv("UNSLOTH_FORCE_VULKAN", "1")++ assert LlamaCppBackend._auto_vulkan_cpu_fallback_eligible(+ "/managed/llama-server", GgufLoadIntent(model_identifier = "m"), None, {}+ )+@pytest.mark.parametrize("name,value",[@@ -537,6 +553,19 @@ class TestAutoVulkanCpuFallbackGate:"/custom/llama-server", GgufLoadIntent(model_identifier = "m"), None)+ def test_auto_environment_override_does_not_make_a_custom_binary_managed(self, monkeypatch):+ import utils.llama_cpp_update as update++ monkeypatch.setenv("UNSLOTH_LLAMA_CPP_BACKEND", "auto")+ monkeypatch.setattr(update, "_llama_install_root", lambda _binary: None)+ monkeypatch.setattr(+ LlamaCppBackend, "_is_vulkan_backend", staticmethod(lambda _binary = None: True)+ )++ assert not LlamaCppBackend._auto_vulkan_cpu_fallback_eligible(+ "/custom/llama-server", GgufLoadIntent(model_identifier = "m"), None+ )+class TestCpuIsolatedReplay:@pytest.mark.parametrize("name", ["LLAMA_ARG_MMPROJ", "LLAMA_ARG_MMPROJ_URL"])diff --git a/studio/backend/tests/test_install_resolve_prebuilt.py b/studio/backend/tests/test_install_resolve_prebuilt.pyindex 41126a1f8ec..619d6c56597 100644--- a/studio/backend/tests/test_install_resolve_prebuilt.py+++ b/studio/backend/tests/test_install_resolve_prebuilt.py@@ -558,15 +558,16 @@ def test_linux_vulkan_health_glob_matches_bare_cpu_lib():(None, None, None, False),("vulkan", None, "vulkan", True),(" VULKAN ", None, "vulkan", True),- ("auto", "1", None, True),+ ("auto", "1", "auto", False),(None, "true", None, True),(None, "on", None, True),- ("auto", None, None, False),+ ("auto", None, "auto", False),("cpu", "0", "cpu", False),- ("hip", "1", "hip", False),- ("rocm", "on", "hip", False),- (" HIP ", "1", "hip", False),- (" ROCM ", "1", "hip", False),+ ("cuda", "1", "cuda", False),+ ("hip", "1", "rocm", False),+ ("rocm", "on", "rocm", False),+ (" HIP ", "1", "rocm", False),+ (" ROCM ", "1", "rocm", False),],)def test_force_vulkan_requested_accepts_public_selector_and_legacy_alias(@@ -574,7 +575,8 @@ def test_force_vulkan_requested_accepts_public_selector_and_legacy_alias():# UNSLOTH_LLAMA_CPP_BACKEND is the public selector; a recognized non-vulkan# value is authoritative, so it opts out even against a stale legacy alias.- # auto/unset/unknown leave the backend unpinned so selection stays automatic.+ # "auto" clears a choice and outranks the legacy Vulkan alias.+ # hip and rocm share one canonical marker value.for name, value in (("UNSLOTH_LLAMA_CPP_BACKEND", backend),("UNSLOTH_FORCE_VULKAN", legacy),@@ -604,7 +606,8 @@ def test_forced_vulkan_filters_cpu_fallback_before_validation():source_label = "upstream",install_kind = "linux-cpu",)- assert ilp._vulkan_only_attempts([vulkan, cpu]) == [vulkan]+ assert ilp._backend_only_attempts([vulkan, cpu], "vulkan") == [vulkan]+ assert ilp._backend_only_attempts([vulkan, cpu], "cpu") == [cpu]def test_forced_vulkan_skips_cpu_only_release_plans():@@ -629,7 +632,7 @@ def test_forced_vulkan_skips_cpu_only_release_plans():ilp.InstallReleasePlan("latest", "b9924", "b9924", [vulkan], SimpleNamespace()),]- filtered = ilp._vulkan_only_release_plans(plans)+ filtered = ilp._backend_only_release_plans(plans, "vulkan")assert [plan.release_tag for plan in filtered] == ["b9924"]assert filtered[0].attempts == [vulkan]@@ -706,7 +709,7 @@ def test_forced_vulkan_linux_arm64_still_resolves_a_vulkan_bundle():["llama-b9925-bin-ubuntu-vulkan-arm64.tar.gz", "llama-b9925-bin-ubuntu-arm64.tar.gz"],)plan = ilp.direct_upstream_release_plan(release, routed, repo, "latest")- filtered = ilp._vulkan_only_release_plans([plan])+ filtered = ilp._backend_only_release_plans([plan], "vulkan")assert [attempt.name for attempt in filtered[0].attempts] == ["llama-b9925-bin-ubuntu-vulkan-arm64.tar.gz"@@ -860,20 +863,21 @@ def test_cpu_backend_env_forces_cpu_in_direct_install(monkeypatch, tmp_path):@pytest.mark.parametrize(- "flags, expect_force, expect_persist",+ "flags, expect_force, expect_backend",[- ([], 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),+ ([], False, None),+ # Transient CPU recovery does not persist (#6097).+ (["--cpu-fallback"], True, None),+ # Deliberate CPU selection persists (#7213).+ (["--force-cpu"], False, "cpu"),+ (["--cpu-fallback", "--force-cpu"], True, "cpu"),+ (["--llama-backend", "vulkan"], False, "vulkan"),+ # An explicit request outranks the legacy flag spelling of another one.+ (["--llama-backend", "cuda", "--force-cpu"], False, "cuda"),],)-def test_cli_cpu_flags_thread_force_and_persist(- monkeypatch, tmp_path, flags, expect_force, expect_persist+def test_cli_cpu_flags_thread_force_and_backend(+ monkeypatch, tmp_path, flags, expect_force, expect_backend):captured = {}monkeypatch.setattr(ilp, "install_prebuilt", lambda **kw: captured.update(kw))@@ -884,13 +888,13 @@ def test_cli_cpu_flags_thread_force_and_persist()assert ilp.main() == ilp.EXIT_SUCCESSassert captured["force_cpu"] is expect_force- assert captured["persist_force_cpu"] is expect_persist+ assert captured["llama_backend"] == expect_backend@pytest.mark.parametrize("existing, requested, expected",[- # A deliberate --force-cpu on top of a naturally-installed CPU bundle (same+ # A deliberate CPU choice 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),@@ -900,22 +904,54 @@ def test_cli_cpu_flags_thread_force_and_persist((True, False, False),],)-def test_sync_marker_force_cpu(tmp_path, existing, requested, expected):+def test_sync_marker_selection_records_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"] = existingmarker_path = tmp_path / "UNSLOTH_PREBUILT_INFO.json"marker_path.write_text(json.dumps(marker))- ilp.sync_marker_force_cpu(tmp_path, requested)+ ilp.sync_marker_selection(+ tmp_path,+ choice = _choice("linux-cpu", "llama-b9585-bin-ubuntu-x64.tar.gz"),+ backend_request = "cpu" if requested else "auto",+ persist_force_cpu = 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):+def test_sync_marker_selection_records_the_backend_of_a_reused_bundle(tmp_path):+ """A switch can resolve to the bundle already installed -- CPU-forcing a host+ whose detected pick was already CPU. The bundle is right, but the recorded+ choice is not, and only that stops the next update re-detecting it away."""+ marker_path = tmp_path / "UNSLOTH_PREBUILT_INFO.json"+ marker_path.write_text(+ json.dumps({"tag": "b9585", "asset": "cpu.tar.gz", "backend_request": "auto"})+ )++ ilp.sync_marker_selection(+ tmp_path,+ choice = _choice("linux-cpu", "cpu.tar.gz"),+ backend_request = "cpu",+ persist_force_cpu = True,+ )++ written = json.loads(marker_path.read_text())+ assert written["backend_request"] == "cpu"+ assert written["backend"] == "cpu"+ assert written["force_cpu"] is True+++def test_sync_marker_selection_missing_marker_is_noop(tmp_path):# No marker (or unreadable) must not crash the reuse path.- ilp.sync_marker_force_cpu(tmp_path, True)+ ilp.sync_marker_selection(+ tmp_path,+ choice = _choice("linux-cpu", "cpu.tar.gz"),+ backend_request = "cpu",+ persist_force_cpu = True,+ )assert not (tmp_path / "UNSLOTH_PREBUILT_INFO.json").exists()@@ -1972,16 +2008,27 @@ def test_a_remembered_arch_never_outranks_a_live_probe(monkeypatch):assert ilp._active_rocm_gfx_target(ilp._apply_host_overrides(probed)) == "gfx1100"+def _sync_gfx(install_dir, legacy_backend, rocm_gfx):+ """sync_marker_selection with only the routing arch in play."""+ ilp.sync_marker_selection(+ install_dir,+ choice = _choice("windows-vulkan", "win-vulkan.zip"),+ backend_request = "auto",+ persist_llama_backend = legacy_backend,+ rocm_gfx = rocm_gfx,+ )++def test_reusing_an_install_still_records_the_routing_gfx(tmp_path):"""The reuse paths skip write_prebuilt_metadata, so they must sync it too."""marker_path = tmp_path / "UNSLOTH_PREBUILT_INFO.json"marker_path.write_text(json.dumps({"llama_backend": "auto", "asset": "win-vulkan.zip"}))- ilp.sync_marker_rocm_gfx(tmp_path, "gfx1034")+ _sync_gfx(tmp_path, "auto", "gfx1034")assert json.loads(marker_path.read_text())["rocm_gfx"] == "gfx1034"# Nothing to record leaves the marker untouched.- ilp.sync_marker_rocm_gfx(tmp_path, None)+ _sync_gfx(tmp_path, "auto", None)assert json.loads(marker_path.read_text())["rocm_gfx"] == "gfx1034"@@ -1992,7 +2039,7 @@ def test_only_the_automatic_route_records_a_routing_gfx(tmp_path, backend):marker_path = tmp_path / "UNSLOTH_PREBUILT_INFO.json"marker_path.write_text(json.dumps({"llama_backend": backend, "asset": "win-hip.zip"}))- ilp.sync_marker_rocm_gfx(tmp_path, "gfx1034")+ _sync_gfx(tmp_path, backend, "gfx1034")assert "rocm_gfx" not in json.loads(marker_path.read_text())diff --git a/studio/backend/tests/test_llama_backend_marker.py b/studio/backend/tests/test_llama_backend_marker.pynew file mode 100644index 00000000000..506e7b19f0d--- /dev/null+++ b/studio/backend/tests/test_llama_backend_marker.py@@ -0,0 +1,136 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""utils.prebuilt.llama_backend agrees with install_llama_prebuilt.py.++The installer owns backend selection and writes the marker; the backend reads that+marker directly on paths where spawning the installer is not an option (the+model-load recovery gate runs per load, the status endpoints per poll). Two+implementations of one contract drift, so this compares them on the same inputs+rather than trusting a comment.+"""++from __future__ import annotations++import importlib+import json+import sys+from pathlib import Path++import pytest++_BACKEND = Path(__file__).resolve().parent.parent+_STUDIO = _BACKEND.parent+for _path in (str(_BACKEND), str(_STUDIO)):+ if _path not in sys.path:+ sys.path.insert(0, _path)++ilp = importlib.import_module("install_llama_prebuilt")+from utils.prebuilt import llama_backend as backend_marker # noqa: E402++# Marker shapes shared by the installer and backend reader.+MARKERS = [+ {},+ {"asset": "app-b1-linux-x64-cuda12-older.tar.gz"},+ {"asset": "app-b1-linux-x64-cpu.tar.gz", "force_cpu": True},+ {"asset": "app-b1-linux-x64-cpu.tar.gz", "force_cpu": False},+ {"asset": "llama-b1-bin-ubuntu-vulkan-x64.tar.gz"},+ {"asset": "llama-b1-bin-ubuntu-vulkan-x64.tar.gz", "llama_backend": None},+ {"asset": "app-b1-win-vulkan.zip", "llama_backend": "auto"},+ {"asset": "app-b1-win-vulkan.zip", "llama_backend": "vulkan"},+ {"asset": "app-b1-win-vulkan.zip", "llama_backend": ""},+ {"asset": "x.tar.gz", "llama_backend": "sycl"},+ {"asset": "x.tar.gz", "llama_backend": 7},+ {"backend": "cuda", "backend_request": "auto"},+ {"backend": "cpu", "backend_request": "cpu", "force_cpu": True},+ {"backend": "vulkan", "backend_request": "vulkan"},+ {"backend": "rocm", "backend_request": "hip"},+ {"backend": "sycl", "backend_request": "sycl"},+]++[email protected](autouse = True)+def _no_ambient_backend_env(monkeypatch):+ for name in ("UNSLOTH_LLAMA_CPP_BACKEND", "UNSLOTH_FORCE_VULKAN"):+ monkeypatch.delenv(name, raising = False)++[email protected]("marker", MARKERS, ids = range(len(MARKERS)))+def test_both_read_the_same_choice_from_a_marker(tmp_path, marker):+ (tmp_path / "UNSLOTH_PREBUILT_INFO.json").write_text(+ json.dumps({"release_tag": "b1", **marker}), encoding = "utf-8"+ )+ assert backend_marker.marker_backend_request(marker) == ilp.persisted_backend_request(tmp_path)+++def test_the_install_kind_maps_are_identical():+ assert backend_marker.INSTALL_KIND_BACKENDS == ilp.INSTALL_KIND_BACKENDS+++def test_the_requestable_backends_are_identical():+ assert backend_marker.REQUESTABLE_BACKENDS == ilp.REQUESTABLE_BACKENDS+++ "primary,legacy,expected",+ [+ (None, None, None),+ (None, "on", "vulkan"),+ ("auto", "on", "auto"),+ ("cpu", "on", "cpu"),+ ("hip", None, "rocm"),+ ("metal", "on", "vulkan"),+ ("unknown", "true", "vulkan"),+ ],+)+def test_public_backend_selector_outranks_the_legacy_flag(primary, legacy, expected):+ assert backend_marker.environment_backend_override(primary, legacy) == expected+++def test_the_api_offers_exactly_the_requestable_backends():+ """The route's Literal is what FastAPI validates and documents, so a backend+ added to the installer must reach the picker rather than 422 on the way in."""+ from typing import get_args++ from routes.llama import LlamaBackendRequest++ field = LlamaBackendRequest.model_fields["backend"]+ assert set(get_args(field.annotation)) == set(ilp.REQUESTABLE_BACKENDS)+++def test_the_api_reports_an_unreadable_newer_backend_request_verbatim():+ """A choice written by a newer Studio survives the response model.++ Coercing it to "auto" would tell the picker this install is detecting when it+ is not, and the picker would then happily overwrite the newer choice.+ """+ from routes.llama import LlamaBackendStatusResponse++ response = LlamaBackendStatusResponse(backend_request = "sycl")++ assert response.backend_request == "sycl"+++ "marker, chosen",+ [+ # Detected, so crash recovery may still fall back to CPU placement.+ ({}, False),+ ({"llama_backend": None}, False),+ ({"llama_backend": ""}, False),+ ({"llama_backend": "auto"}, False),+ ({"backend_request": "auto"}, False),+ # Legacy Vulkan stays eligible for automatic recovery.+ ({"asset": "llama-b1-bin-ubuntu-vulkan-x64.tar.gz"}, False),+ # Chosen.+ ({"llama_backend": "vulkan"}, True),+ ({"force_cpu": True}, True),+ ({"backend_request": "vulkan"}, True),+ ({"backend_request": "cpu"}, True),+ # Unreadable is chosen: undoing a choice we cannot name is the wrong guess.+ ({"llama_backend": "sycl"}, True),+ ({"backend_request": "sycl"}, True),+ ],+)+def test_was_chosen_separates_a_pinned_install_from_a_detected_one(marker, chosen):+ assert backend_marker.marker_backend_was_chosen(marker) is chosendiff --git a/studio/backend/tests/test_llama_backend_selection.py b/studio/backend/tests/test_llama_backend_selection.pynew file mode 100644index 00000000000..9ef3df280d5--- /dev/null+++ b/studio/backend/tests/test_llama_backend_selection.py@@ -0,0 +1,616 @@+# 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_llama_prebuilt.py: naming a llama.cpp backend, and keeping that choice.++The picker in Settings > System, `UNSLOTH_LLAMA_CPP_BACKEND`, and+`--llama-backend` are three spellings of one thing: a backend request, resolved+here and recorded in the install marker so every later entry point -- setup.sh,+`unsloth studio update`, the desktop updater -- installs the same backend without+being told again.++Network and host detection are stubbed; no GPU or internet needed.+"""++from __future__ import annotations++import importlib+import json+import re+import sys+from pathlib import Path+from types import SimpleNamespace++import pytest++_studio = Path(__file__).resolve().parent.parent.parent+if str(_studio) not in sys.path:+ sys.path.insert(0, str(_studio))++ilp = importlib.import_module("install_llama_prebuilt")++FORK = ilp.DEFAULT_PUBLISHED_REPO++[email protected](autouse = True)+def _no_ambient_backend_env(monkeypatch):+ """A backend exported in the developer's shell would override every case here."""+ for name in ("UNSLOTH_LLAMA_CPP_BACKEND", "UNSLOTH_FORCE_VULKAN"):+ monkeypatch.delenv(name, raising = False)+++def _marker(tmp_path: Path, **fields) -> Path:+ (tmp_path / "UNSLOTH_PREBUILT_INFO.json").write_text(+ json.dumps({"release_tag": "b9925", **fields}), encoding = "utf-8"+ )+ return tmp_path+++def _choice(install_kind: str, name: str = "bundle.tar.gz") -> ilp.AssetChoice:+ return ilp.AssetChoice(+ repo = FORK,+ tag = "b9925",+ name = name,+ url = "https://example/bundle",+ source_label = "published",+ install_kind = install_kind,+ )+++# ── The vocabulary ──+++def test_every_install_kind_the_installer_can_select_names_a_backend():+ """The marker describes each install by backend, so a bundle kind with no+ mapping would install as an unknown one the picker cannot show or re-assert.++ Reads the kinds out of the module source rather than a hand-kept list, so+ adding a bundle family without extending INSTALL_KIND_BACKENDS fails here+ instead of silently shipping an undescribed install.+ """+ source = Path(ilp.__file__).read_text(encoding = "utf-8")+ selected = set(re.findall(r'install_kind = "([a-z0-9-]+)"', source))+ # The validate-install CLI documents kinds in help text; only assignments count.+ assert selected, "no install_kind assignments found -- has the pattern changed?"+ unmapped = sorted(selected - set(ilp.INSTALL_KIND_BACKENDS))+ assert unmapped == [], f"install kinds with no backend mapping: {unmapped}"+++ "kind, backend",+ [+ ("linux-cuda", "cuda"),+ ("linux-arm64-cuda", "cuda"),+ ("windows-cuda", "cuda"),+ ("linux-rocm", "rocm"),+ ("windows-hip", "rocm"),+ ("windows-rocm", "rocm"),+ ("linux-vulkan", "vulkan"),+ ("windows-vulkan", "vulkan"),+ ("linux-cpu", "cpu"),+ ("linux-arm64", "cpu"),+ ("windows-arm64", "cpu"),+ ("macos-arm64", "metal"),+ ("sycl-someday", None),+ ],+)+def test_install_kind_maps_to_its_accelerator(kind, backend):+ assert ilp.backend_for_install_kind(kind) == backend+++def test_install_kinds_for_backend_is_the_inverse():+ assert ilp.install_kinds_for_backend("vulkan") == ilp.VULKAN_INSTALL_KINDS+ assert "linux-cuda" in ilp.install_kinds_for_backend("cuda")+ assert ilp.install_kinds_for_backend(None) == frozenset()+++def test_windows_rocm_bundle_satisfies_a_rocm_request():+ choice = _choice("windows-rocm", "llama-b9925-windows-rocm-gfx1100.zip")+ plan = ilp.InstallReleasePlan("latest", "b9925", "b9925", [choice], SimpleNamespace())++ filtered = ilp._backend_only_release_plans([plan], "rocm")++ assert filtered[0].attempts == [choice]+++# ── Reading a choice back off an install ──+++ "marker, expected",+ [+ # Nothing recorded: an ordinary detected install, which must keep detecting.+ ({"asset": "app-b1-linux-x64-cuda12.tar.gz", "force_cpu": False}, "auto"),+ # The two overrides older installers could record.+ ({"asset": "app-b1-linux-x64-cpu.tar.gz", "force_cpu": True}, "cpu"),+ ({"asset": "vulkan.tar.gz", "llama_backend": "vulkan"}, "vulkan"),+ # Automatic Windows-AMD Vulkan routing: detected, not chosen.+ ({"asset": "win-vulkan.zip", "llama_backend": "auto"}, "auto"),+ # Pre-#7188: no llama_backend key at all, so the asset is the only evidence.+ ({"asset": "llama-b1-bin-ubuntu-vulkan-x64.tar.gz"}, "vulkan"),+ # Written by this build.+ ({"backend": "rocm", "backend_request": "rocm"}, "rocm"),+ ({"backend": "cuda", "backend_request": "auto"}, "auto"),+ # A choice from a newer Studio is returned verbatim, never as "auto":+ # "auto" would license this build to re-detect over it.+ ({"backend": "sycl", "backend_request": "sycl"}, "sycl"),+ ({"asset": "x.tar.gz", "llama_backend": "sycl"}, "sycl"),+ # A non-string records no readable choice at all, so detection applies.+ ({"backend": "cuda", "backend_request": 7}, "auto"),+ ({"asset": "x.tar.gz", "llama_backend": 7}, "auto"),+ ],+)+def test_persisted_backend_request_reads_old_and_new_markers(tmp_path, marker, expected):+ assert ilp.persisted_backend_request(_marker(tmp_path, **marker)) == expected+++def test_persisted_backend_request_without_an_install(tmp_path):+ # No marker records no choice, which is detection, not an unreadable one.+ assert ilp.persisted_backend_request(None) == "auto"+ assert ilp.persisted_backend_request(tmp_path) == "auto"+++# ── Precedence ──+++def test_the_flag_outranks_the_environment_and_the_install(monkeypatch, tmp_path):+ monkeypatch.setenv("UNSLOTH_LLAMA_CPP_BACKEND", "cuda")+ install = _marker(tmp_path, backend_request = "cpu")+ assert ilp.effective_backend_request("vulkan", install_dir = install) == ("vulkan", True)+++def test_the_environment_outranks_the_install(monkeypatch, tmp_path):+ monkeypatch.setenv("UNSLOTH_LLAMA_CPP_BACKEND", "cuda")+ install = _marker(tmp_path, backend_request = "cpu")+ assert ilp.effective_backend_request(None, install_dir = install) == ("cuda", True)+++def test_an_explicit_auto_clears_a_recorded_choice(monkeypatch, tmp_path):+ # How the picker's "Automatic" entry gets back to detection.+ monkeypatch.setenv("UNSLOTH_LLAMA_CPP_BACKEND", "auto")+ install = _marker(tmp_path, backend_request = "vulkan")+ assert ilp.effective_backend_request(None, install_dir = install) == ("auto", True)+++def test_an_explicit_auto_suppresses_the_legacy_vulkan_flag(monkeypatch, tmp_path):+ monkeypatch.setenv("UNSLOTH_LLAMA_CPP_BACKEND", "auto")+ monkeypatch.setenv("UNSLOTH_FORCE_VULKAN", "1")+ install = _marker(tmp_path, backend_request = "vulkan")+ assert ilp.effective_backend_request(None, install_dir = install) == ("auto", True)+++def test_legacy_force_vulkan_still_outranks_a_recorded_choice(monkeypatch, tmp_path):+ # The legacy environment override outranks the stored choice.+ monkeypatch.setenv("UNSLOTH_FORCE_VULKAN", "1")+ install = _marker(tmp_path, backend_request = "cpu")+ assert ilp.effective_backend_request(None, install_dir = install) == ("vulkan", True)+++def test_a_recorded_choice_applies_when_nobody_names_one(tmp_path):+ # The whole point: no env, no flag, and the install still comes back Vulkan.+ install = _marker(tmp_path, backend_request = "vulkan")+ assert ilp.effective_backend_request(None, install_dir = install) == ("vulkan", False)+++def test_an_unknown_environment_value_falls_through_to_the_install(monkeypatch, tmp_path):+ monkeypatch.setenv("UNSLOTH_LLAMA_CPP_BACKEND", "banana")+ install = _marker(tmp_path, backend_request = "vulkan")+ assert ilp.effective_backend_request(None, install_dir = install) == ("vulkan", False)+++# ── What gets recorded ──+++ "request_backend, kind, expected",+ [+ ("vulkan", "linux-vulkan", "vulkan"),+ ("cpu", "linux-cpu", "cpu"),+ ("auto", "linux-cuda", "auto"),+ (None, "linux-cuda", "auto"),+ # macOS cannot persist requests that all resolve to its universal Metal build.+ ("cpu", "macos-arm64", "auto"),+ ("vulkan", "linux-cpu", "auto"),+ ],+)+def test_only_a_request_the_install_honours_is_recorded(request_backend, kind, expected):+ assert ilp.persisted_marker_backend_request(request_backend, _choice(kind)) == expected+++def test_macos_backend_resolver_only_offers_automatic_metal(monkeypatch):+ host = ilp.HostInfo(+ system = "Darwin",+ machine = "arm64",+ is_windows = False,+ is_linux = False,+ is_macos = True,+ is_x86_64 = False,+ is_arm64 = True,+ nvidia_smi = None,+ driver_cuda_version = None,+ compute_caps = [],+ visible_cuda_devices = None,+ has_physical_nvidia = False,+ has_usable_nvidia = False,+ has_rocm = False,+ rocm_gfx_target = None,+ macos_version = (15, 5),+ )+ seen = []+ monkeypatch.setattr(ilp, "detect_host", lambda: host)+ monkeypatch.setattr(ilp, "load_prebuilt_metadata", lambda install_dir: None)++ def _select(**kwargs):+ seen.append(kwargs["backend"])+ return ilp.BackendSelection(+ backend = "auto",+ host = host,+ published_repo = FORK,+ published_release_tag = "",+ requested_tag = "latest",+ release_plans = [+ ilp.InstallReleasePlan(+ "latest",+ "b9925",+ "b9925",+ [_choice("macos-arm64")],+ SimpleNamespace(),+ )+ ],+ persist_llama_backend = None,+ persist_rocm_gfx = None,+ )++ monkeypatch.setattr(ilp, "select_backend_install", _select)+ args = SimpleNamespace(+ published_repo = FORK,+ published_release_tag = "",+ has_rocm = False,+ rocm_gfx = None,+ )++ payload = ilp.resolve_backends_payload("latest", args = args)++ assert seen == ["auto"]+ assert [entry["backend"] for entry in payload["backends"]] == ["auto"]+ assert payload["backends"][0]["resolved_backend"] == "metal"+++def test_selection_payload_reports_the_backend_a_plan_would_install():+ primary = _choice("linux-cuda", "cuda13.tar.gz")+ fallback = _choice("linux-cuda", "cuda12.tar.gz")+ selection = SimpleNamespace(+ choice = primary,+ published_repo = FORK,+ release_plans = [+ SimpleNamespace(+ release_tag = "b9925",+ llama_tag = "b9925",+ attempts = [primary, fallback],+ )+ ],+ )++ payload = ilp._selection_payload(selection)++ assert payload["asset"] == "cuda13.tar.gz"+ assert payload["backend"] == "cuda"+++def test_explicit_rocm_reprobes_and_suppresses_cuda_on_a_mixed_host(monkeypatch):+ automatic_host = ilp.HostInfo(+ system = "Linux",+ machine = "x86_64",+ is_windows = False,+ is_linux = True,+ is_macos = False,+ is_x86_64 = True,+ is_arm64 = False,+ nvidia_smi = "/usr/bin/nvidia-smi",+ driver_cuda_version = (13, 0),+ compute_caps = ["120"],+ visible_cuda_devices = None,+ has_physical_nvidia = True,+ has_usable_nvidia = True,+ )+ mixed_host = ilp.dataclasses_replace(+ automatic_host,+ has_rocm = True,+ rocm_gfx_target = "gfx1100",+ rocm_gfx_targets = ["gfx1100"],+ )+ probes = []++ def _detect_host(*, probe_rocm_with_nvidia = False):+ probes.append(probe_rocm_with_nvidia)+ return mixed_host if probe_rocm_with_nvidia else automatic_host++ monkeypatch.setattr(ilp, "detect_host", _detect_host)++ route = ilp.route_backend_request(+ backend = "rocm",+ published_repo = FORK,+ published_release_tag = "",+ host = automatic_host,+ )++ assert probes == [True]+ assert route.host.has_usable_nvidia is False+ assert route.host.has_physical_nvidia is False+ assert route.host.has_rocm is True+ assert route.host.rocm_gfx_target == "gfx1100"+++def test_backend_resolver_does_not_turn_a_switch_into_a_version_update(monkeypatch):+ monkeypatch.setattr(+ ilp,+ "detect_host",+ lambda: SimpleNamespace(is_macos = False, system = "Linux", machine = "x86_64"),+ )+ monkeypatch.setattr(+ ilp, "load_prebuilt_metadata", lambda install_dir: {"release_tag": "b9900-mix-old"}+ )+ seen_pins = []++ def _unavailable(**kwargs):+ seen_pins.append(kwargs["published_release_tag"])+ raise ilp.BackendUnavailable("release no longer publishes this backend")++ monkeypatch.setattr(ilp, "select_backend_install", _unavailable)+ args = SimpleNamespace(+ published_repo = FORK,+ published_release_tag = "",+ has_rocm = False,+ rocm_gfx = None,+ )++ payload = ilp.resolve_backends_payload("latest", args = args, install_dir = Path("unused"))++ assert payload["pinned_release_tag"] == "b9900-mix-old"+ assert seen_pins == ["b9900-mix-old"] * len(ilp.REQUESTABLE_BACKENDS)+ assert not any(entry["available"] for entry in payload["backends"])+++def test_backend_resolver_rejects_cross_repository_switches(monkeypatch):+ host = SimpleNamespace(is_macos = False, system = "Linux", machine = "aarch64")+ monkeypatch.setattr(ilp, "detect_host", lambda: host)+ monkeypatch.setattr(+ ilp,+ "load_prebuilt_metadata",+ lambda install_dir: {"release_tag": "b9900-mix-old", "published_repo": FORK},+ )++ def _upstream_selection(**kwargs):+ choice = ilp.AssetChoice(+ repo = ilp.UPSTREAM_REPO,+ tag = "b9999",+ name = "llama-b9999-bin-ubuntu-vulkan-arm64.tar.gz",+ url = "https://example/upstream-vulkan",+ source_label = "upstream",+ install_kind = "linux-vulkan",+ )+ plan = ilp.InstallReleasePlan("latest", "b9999", "b9999", [choice], SimpleNamespace())+ return ilp.BackendSelection(+ backend = kwargs["backend"],+ host = host,+ published_repo = ilp.UPSTREAM_REPO,+ published_release_tag = "",+ requested_tag = "latest",+ release_plans = [plan],+ persist_llama_backend = "vulkan",+ persist_rocm_gfx = None,+ )++ monkeypatch.setattr(ilp, "select_backend_install", _upstream_selection)+ args = SimpleNamespace(+ published_repo = FORK,+ published_release_tag = "",+ has_rocm = False,+ rocm_gfx = None,+ )++ payload = ilp.resolve_backends_payload("latest", args = args, install_dir = Path("unused"))++ assert not any(entry["available"] for entry in payload["backends"])+ assert all(entry["reason"] == "no_prebuilt" for entry in payload["backends"])+++def test_backend_resolver_fails_when_every_option_hits_an_unexpected_error(monkeypatch):+ monkeypatch.setattr(+ ilp,+ "detect_host",+ lambda: SimpleNamespace(is_macos = False, system = "Linux", machine = "x86_64"),+ )+ monkeypatch.setattr(ilp, "load_prebuilt_metadata", lambda install_dir: None)++ def _offline(**kwargs):+ raise ConnectionError("offline")++ monkeypatch.setattr(ilp, "select_backend_install", _offline)+ args = SimpleNamespace(+ published_repo = FORK,+ published_release_tag = "",+ has_rocm = False,+ rocm_gfx = None,+ )++ with pytest.raises(RuntimeError, match = "could not resolve any"):+ ilp.resolve_backends_payload("latest", args = args)+++def test_metadata_records_both_the_backend_and_the_choice(tmp_path):+ checksums = ilp.ApprovedReleaseChecksums(+ repo = FORK,+ release_tag = "b9925",+ upstream_tag = "b9925",+ source_repo = FORK,+ source_repo_url = f"https://github.com/{FORK}",+ )+ ilp.write_prebuilt_metadata(+ tmp_path,+ requested_tag = "latest",+ llama_tag = "b9925",+ release_tag = "b9925",+ choice = _choice("linux-vulkan", "app-b9925-linux-x64-vulkan.tar.gz"),+ approved_checksums = checksums,+ prebuilt_fallback_used = False,+ llama_backend = "vulkan",+ backend_request = "vulkan",+ )+ marker = json.loads((tmp_path / "UNSLOTH_PREBUILT_INFO.json").read_text())+ assert marker["backend"] == "vulkan"+ assert marker["backend_request"] == "vulkan"+ # The superseded field stays, so an older Studio keeps re-asserting Vulkan.+ assert marker["llama_backend"] == "vulkan"+++def test_a_detected_install_records_its_backend_but_no_choice(tmp_path):+ checksums = ilp.ApprovedReleaseChecksums(+ repo = FORK,+ release_tag = "b9925",+ upstream_tag = "b9925",+ source_repo = FORK,+ source_repo_url = f"https://github.com/{FORK}",+ )+ ilp.write_prebuilt_metadata(+ tmp_path,+ requested_tag = "latest",+ llama_tag = "b9925",+ release_tag = "b9925",+ choice = _choice("linux-cuda", "app-b9925-linux-x64-cuda12.tar.gz"),+ approved_checksums = checksums,+ prebuilt_fallback_used = False,+ )+ marker = json.loads((tmp_path / "UNSLOTH_PREBUILT_INFO.json").read_text())+ # Describes the install for the picker...+ assert marker["backend"] == "cuda"+ # ...without pinning it, so the next update re-detects as it always has.+ assert marker["backend_request"] == "auto"+++# ── Applying a request to an install ──+++def _stub_selection(+ monkeypatch,+ *,+ available,+ install_kind = "linux-cuda",+):+ """Record which backend the install path asked for, and answer for it."""+ seen = []+ # Avoid the unrelated DiffusionGemma backfill download.+ monkeypatch.setattr(ilp, "diffusion_visual_server_backfill_needed", lambda *a, **k: False)++ def _select(+ *,+ backend,+ llama_tag,+ published_repo,+ published_release_tag,+ route = None,+ **_,+ ):+ seen.append(backend)+ if backend in available:+ plan = ilp.InstallReleasePlan(+ "latest",+ "b9925",+ "b9925",+ [_choice(install_kind)],+ SimpleNamespace(ggml_tree = None, repo = FORK),+ )+ return ilp.BackendSelection(+ backend = backend,+ host = route.host if route is not None else ilp.detect_host(),+ published_repo = published_repo,+ published_release_tag = published_release_tag,+ requested_tag = "latest",+ release_plans = [plan],+ persist_llama_backend = None,+ persist_rocm_gfx = None,+ )+ raise ilp.BackendUnavailable(f"no {backend} prebuilt bundle attempts were available")++ monkeypatch.setattr(ilp, "select_backend_install", _select)+ return seen+++def test_an_install_applies_the_choice_its_marker_recorded(monkeypatch, tmp_path):+ seen = _stub_selection(monkeypatch, available = {"vulkan"}, install_kind = "linux-vulkan")+ monkeypatch.setattr(ilp, "existing_install_matches_plan", lambda *a, **k: True)+ _marker(tmp_path, backend = "vulkan", backend_request = "vulkan")++ ilp.install_prebuilt(tmp_path, "latest", FORK, "")++ assert seen == ["vulkan"]+++def test_an_update_refuses_to_replace_an_unknown_recorded_choice(monkeypatch, tmp_path):+ seen = _stub_selection(monkeypatch, available = {"auto"})+ marker_path = _marker(tmp_path, backend = "sycl", backend_request = "sycl")++ with pytest.raises(SystemExit) as raised:+ ilp.install_prebuilt(tmp_path, "latest", FORK, "")++ # EXIT_ERROR, not the source fallback: a source build would pick its own+ # backend, which is the outcome refusing this update exists to prevent.+ assert raised.value.code == ilp.EXIT_ERROR+ assert seen == []+ marker = json.loads((marker_path / "UNSLOTH_PREBUILT_INFO.json").read_text())+ assert marker["backend_request"] == "sycl"+++def test_a_recorded_choice_this_host_cannot_serve_falls_back_to_detection(monkeypatch, tmp_path):+ # Re-detect after hardware invalidates a stored choice.+ seen = _stub_selection(monkeypatch, available = {"auto"})+ monkeypatch.setattr(ilp, "existing_install_matches_plan", lambda *a, **k: True)+ _marker(tmp_path, backend = "rocm", backend_request = "rocm")++ ilp.install_prebuilt(tmp_path, "latest", FORK, "")++ assert seen == ["rocm", "auto"]+ marker = json.loads((tmp_path / "UNSLOTH_PREBUILT_INFO.json").read_text())+ assert marker["backend_request"] == "auto"+++def test_a_named_backend_this_host_cannot_serve_fails_instead(monkeypatch, tmp_path):+ # An explicit request must not silently install another backend.+ seen = _stub_selection(monkeypatch, available = {"auto"})+ _marker(tmp_path, backend = "cuda", backend_request = "auto")++ with pytest.raises(SystemExit) as raised:+ ilp.install_prebuilt(tmp_path, "latest", FORK, "", llama_backend = "vulkan")++ # Both the UI and setup need a specific fail-closed result.+ assert raised.value.code == ilp.EXIT_BACKEND_UNAVAILABLE+ assert seen == ["vulkan"]+++ "backend_request,expected_exit",+ [("cpu", ilp.EXIT_BACKEND_UNAVAILABLE), ("auto", ilp.EXIT_FALLBACK)],+)+def test_only_automatic_selection_can_source_fallback_after_candidate_failure(+ monkeypatch, tmp_path, backend_request, expected_exit+):+ _stub_selection(monkeypatch, available = {backend_request}, install_kind = "linux-cpu")+ _marker(tmp_path, backend = "cpu", backend_request = backend_request)+ monkeypatch.setattr(ilp, "existing_install_matches_plan", lambda *a, **k: False)+ monkeypatch.setattr(ilp, "diffusion_visual_server_backfill_needed", lambda *a, **k: False)+ monkeypatch.setattr(ilp, "resolve_validation_model", lambda probe: probe)+ monkeypatch.setattr(+ ilp,+ "validate_prebuilt_attempts",+ lambda *a, **k: (_ for _ in ()).throw(ilp.PrebuiltFallback("candidate failed")),+ )+ monkeypatch.setattr(ilp, "collect_system_report", lambda *a, **k: "report")++ with pytest.raises(SystemExit) as raised:+ ilp.install_prebuilt(tmp_path, "latest", FORK, "")++ assert raised.value.code == expected_exit+++def test_backend_unavailable_uses_the_prebuilt_rollback_path():+ assert issubclass(ilp.BackendUnavailable, ilp.PrebuiltFallback)diff --git a/studio/backend/tests/test_llama_backend_switch.py b/studio/backend/tests/test_llama_backend_switch.pynew file mode 100644index 00000000000..3181d39d5fb--- /dev/null+++ b/studio/backend/tests/test_llama_backend_switch.py@@ -0,0 +1,791 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Switching the llama.cpp backend from the app.++The picker in Settings > System reads utils.llama_cpp_update.get_backend_status+and applies with start_backend_switch. Both run on the update job, so a switch and+an update can never write to the same install at once.++The installer subprocess is stubbed; no download or GPU needed.+"""++from __future__ import annotations++import json+import sys+import threading+import time+from pathlib import Path++import pytest++_BACKEND = Path(__file__).resolve().parent.parent+if str(_BACKEND) not in sys.path:+ sys.path.insert(0, str(_BACKEND))++import utils.llama_cpp_freshness as freshness # noqa: E402+import utils.llama_cpp_update as upd # noqa: E402+import utils.whisper_cpp_update as whisper_upd # noqa: E402++MARKER = "UNSLOTH_PREBUILT_INFO.json"++# Captured before the autouse fixture stubs it out on the module.+_whisper_phase_plan = upd._whisper_phase_plan+++class _FakeInstallerPopen:+ def __init__(+ self,+ cmd,+ *,+ on_start = None,+ returncode = 0,+ lines = None,+ **kwargs,+ ):+ if on_start is not None:+ on_start(list(cmd), kwargs)+ self.pid = 424242+ self.returncode = returncode+ self.stdout = iter(lines or ["installed\n"])++ def poll(self):+ return self.returncode++ def wait(self):+ return self.returncode++ def kill(self):+ pass+++def _patch_installer(+ monkeypatch,+ *,+ on_start = None,+ returncode = 0,+):+ monkeypatch.setattr(+ upd.subprocess,+ "Popen",+ lambda cmd, **kw: _FakeInstallerPopen(cmd, on_start = on_start, returncode = returncode, **kw),+ )+++def _write_install(dir_: Path, **marker_fields) -> str:+ bin_dir = dir_ / "build" / "bin"+ bin_dir.mkdir(parents = True, exist_ok = True)+ binary = bin_dir / "llama-server"+ binary.write_text("#!/bin/sh\necho stub\n")+ marker = {+ "tag": "b9596",+ "release_tag": "b9596-mix-abc",+ "published_repo": "unslothai/llama.cpp",+ "installed_at_utc": "2020-01-01T00:00:00Z",+ "asset": "app-b9596-mix-abc-linux-x64-cuda12.tar.gz",+ "install_kind": "linux-cuda",+ "backend": "cuda",+ "backend_request": "auto",+ }+ marker.update(marker_fields)+ (dir_ / MARKER).write_text(json.dumps(marker))+ return str(binary)++[email protected](autouse = True)+def _clean_state(monkeypatch, tmp_path):+ freshness.reset_caches()+ upd._reset_job_for_tests()+ upd._resolve_memo.clear()+ upd._backends_memo.clear()+ monkeypatch.setattr(freshness, "_cache_dir", lambda: tmp_path / ".freshness_cache")+ for name in ("UNSLOTH_LLAMA_CPP_BACKEND", "UNSLOTH_FORCE_VULKAN"):+ monkeypatch.delenv(name, raising = False)+ # Nothing in this suite may touch the network or the real whisper install.+ monkeypatch.setattr(freshness, "_fetch_latest_release_tag", lambda repo, timeout = 5.0: None)+ monkeypatch.setattr(upd, "_whisper_phase_plan", lambda *a, **k: {})+ monkeypatch.setattr(+ upd,+ "_resolve_backends_for_host",+ lambda install_dir, **kwargs: {+ "backends": [+ {+ "backend": backend,+ "available": True,+ "resolved_backend": "cuda" if backend == "auto" else backend,+ "asset": (+ "app-b9596-mix-abc-linux-x64-cuda12.tar.gz"+ if backend in ("auto", "cuda")+ else f"app-b9596-mix-abc-linux-x64-{backend}.tar.gz"+ ),+ }+ for backend in ("auto", "cpu", "cuda", "rocm", "vulkan")+ ]+ },+ )+++def _install(monkeypatch, tmp_path, **marker_fields) -> Path:+ install_dir = tmp_path / "llama.cpp"+ binary = _write_install(install_dir, **marker_fields)+ monkeypatch.setattr(upd, "_find_binary", lambda: binary)+ monkeypatch.setattr(upd, "_installer_script", lambda: tmp_path / "install_llama_prebuilt.py")+ return install_dir+++def _await_job(state = ("success", "error")) -> dict:+ deadline = time.time() + 10+ while time.time() < deadline:+ job = upd.get_update_status()["job"]+ if job["state"] in state:+ return job+ time.sleep(0.05)+ raise AssertionError(f"job never reached {state}: {upd.get_update_status()['job']}")+++# ── Applying ──+++def test_a_switch_names_the_backend_and_keeps_the_installed_release(monkeypatch, tmp_path):+ """A switch changes the backend and nothing else.++ Pinned to the release already installed rather than the latest: bundling an+ update into it would also break the paired whisper.cpp install, whose slim+ bundle names the exact llama.cpp release it borrows ggml modules from.+ """+ install_dir = _install(monkeypatch, tmp_path)+ seen: dict = {}++ def _on_start(cmd, kwargs):+ seen["cmd"] = cmd+ seen["env"] = kwargs.get("env") or {}+ _write_install(+ install_dir,+ asset = "app-b9596-mix-abc-linux-x64-vulkan.tar.gz",+ install_kind = "linux-vulkan",+ backend = "vulkan",+ backend_request = "vulkan",+ )++ _patch_installer(monkeypatch, on_start = _on_start)++ assert upd.start_backend_switch("vulkan")["started"] is True+ job = _await_job()++ assert job["state"] == "success", job+ assert job["operation"] == "switch"+ assert job["requested_backend"] == "vulkan"+ assert seen["cmd"][seen["cmd"].index("--llama-backend") + 1] == "vulkan"+ assert seen["cmd"][seen["cmd"].index("--published-release-tag") + 1] == "b9596-mix-abc"+ assert seen["env"]["UNSLOTH_LLAMA_CPP_BACKEND"] == "vulkan"+ assert job["message"] == "llama.cpp is now running on vulkan."+++ "name,value,expected",+ [+ ("UNSLOTH_LLAMA_CPP_BACKEND", "cpu", "cpu"),+ ("UNSLOTH_LLAMA_CPP_BACKEND", "auto", "auto"),+ ("UNSLOTH_FORCE_VULKAN", "1", "vulkan"),+ ],+)+def test_environment_override_refuses_a_switch(monkeypatch, tmp_path, name, value, expected):+ _install(monkeypatch, tmp_path)+ monkeypatch.setenv(name, value)++ action = upd.start_backend_switch("vulkan")++ assert action["started"] is False+ assert action["reason"] == "environment_override"+ assert expected in action["message"]+++def test_a_backend_with_no_build_here_is_reported_by_name(monkeypatch, tmp_path):+ # Hardware or published bundles can change after option resolution.+ _install(monkeypatch, tmp_path)+ _patch_installer(monkeypatch, returncode = upd._EXIT_BACKEND_UNAVAILABLE)++ assert upd.start_backend_switch("rocm")["started"] is True+ job = _await_job()++ assert job["state"] == "error"+ assert "Could not install the rocm llama.cpp build on this machine" in job["error"]+++ "name,value,expected",+ [+ ("UNSLOTH_LLAMA_CPP_BACKEND", "cpu", "cpu"),+ ("UNSLOTH_FORCE_VULKAN", "1", "vulkan"),+ ],+)+def test_update_failure_names_the_environment_pinned_backend(+ monkeypatch, tmp_path, name, value, expected+):+ install_dir = _install(monkeypatch, tmp_path)+ monkeypatch.setenv(name, value)+ monkeypatch.setattr(+ upd,+ "_plan_llama_phase",+ lambda backend_request = None: {+ "spec": {+ "install_dir": install_dir,+ "repo": "unslothai/llama.cpp",+ "asset": None,+ "script": tmp_path / "install_llama_prebuilt.py",+ "pin_release_tag": "b9597-mix-new",+ "from_tag": "b9596-mix-abc",+ "llama_backend": "auto",+ "rocm_gfx": None,+ "backend_request": None,+ }+ },+ )+ _patch_installer(monkeypatch, returncode = upd._EXIT_BACKEND_UNAVAILABLE)++ assert upd.start_update()["started"] is True+ job = _await_job()++ assert job["state"] == "error"+ assert f"Could not install the {expected} llama.cpp build on this machine" in job["error"]+++def test_a_switch_rejects_a_cross_repository_result(monkeypatch, tmp_path):+ install_dir = _install(monkeypatch, tmp_path)++ def _on_start(cmd, kwargs):+ _write_install(+ install_dir,+ release_tag = "b9596",+ published_repo = "ggml-org/llama.cpp",+ asset = "llama-b9596-bin-ubuntu-vulkan-arm64.tar.gz",+ install_kind = "linux-vulkan",+ backend = "vulkan",+ backend_request = "vulkan",+ )++ _patch_installer(monkeypatch, on_start = _on_start)++ assert upd.start_backend_switch("vulkan")["started"] is True+ job = _await_job()++ assert job["state"] == "error"+ assert "backend switch must preserve" in job["error"]+++# ── Refusing ──+++def test_switching_to_the_recorded_choice_is_refused(monkeypatch, tmp_path):+ _install(+ monkeypatch,+ tmp_path,+ asset = "app-b9596-mix-abc-linux-x64-vulkan.tar.gz",+ backend = "vulkan",+ backend_request = "vulkan",+ )++ action = upd.start_backend_switch("vulkan")++ assert action["started"] is False+ assert action["reason"] == "already_selected"+++def test_a_failed_whisper_repair_can_be_retried_from_the_same_selection(monkeypatch):+ """The one already-selected request that must still start a job.++ The llama phase runs first and records the new backend, so a retryable whisper+ failure (a dropped download, an install that was busy) ends with llama switched and+ dictation still hardlinked to the old runtime. Retrying is then "already selected",+ and refusing it leaves the reported failure unfixable except by switching llama.cpp+ away and back.+ """+ monkeypatch.setattr(whisper_upd, "slim_pairing_is_stale", lambda: True)+ monkeypatch.setattr(whisper_upd, "repair_pairing_plan", lambda: {"phase": {"repair": True}})++ plan = _whisper_phase_plan("cuda", llama_will_run = False, llama_skip_reason = "already_selected")++ assert plan["phase"]["repair"] is True+++def test_an_already_selected_request_with_a_healthy_pairing_stays_refused(monkeypatch):+ """Staleness is what separates an owed repair from an ordinary no-op.++ Without it every already-selected request would start a whisper job that finds+ nothing to do and reports success, replacing a clear refusal with a false one.+ """+ planned = []+ monkeypatch.setattr(+ whisper_upd, "repair_pairing_plan", lambda: planned.append(1) or {"phase": {"repair": True}}+ )++ monkeypatch.setattr(whisper_upd, "slim_pairing_is_stale", lambda: False)+ assert (+ _whisper_phase_plan("cuda", llama_will_run = False, llama_skip_reason = "already_selected")+ == {}+ )++ # Every other refusal stays refused whatever the pairing looks like.+ monkeypatch.setattr(whisper_upd, "slim_pairing_is_stale", lambda: True)+ assert _whisper_phase_plan("cuda", llama_will_run = False, llama_skip_reason = "local_link") == {}+ assert planned == []+++def test_re_selecting_a_backend_is_refused_even_when_its_asset_moved(monkeypatch, tmp_path):+ """The picker chooses a backend, not a bundle.++ A newer per-architecture asset for the backend already selected is an update,+ which the update flow offers on its own schedule. Making Apply mean "reinstall+ too" would hand the same install to two jobs with two different triggers.+ """+ _install(+ monkeypatch,+ tmp_path,+ asset = "app-b9596-mix-abc-linux-x64-cuda12-old.tar.gz",+ backend = "cuda",+ backend_request = "cuda",+ )+ monkeypatch.setattr(+ upd,+ "_resolve_backends_for_host",+ lambda install_dir, **kwargs: {+ "backends": [+ {+ "backend": "cuda",+ "available": True,+ "resolved_backend": "cuda",+ "asset": "app-b9596-mix-abc-linux-x64-cuda13.tar.gz",+ }+ ]+ },+ )++ action = upd.start_backend_switch("cuda")++ assert action["started"] is False+ assert action["reason"] == "already_selected"+++def test_auto_reapplies_when_hardware_detection_changes(monkeypatch, tmp_path):+ install_dir = _install(monkeypatch, tmp_path, backend = "cpu", backend_request = "auto")+ _patch_installer(+ monkeypatch,+ on_start = lambda cmd, kwargs: _write_install(+ install_dir, backend = "cuda", backend_request = "auto"+ ),+ )++ assert upd.start_backend_switch("auto")["started"] is True+ assert _await_job()["state"] == "success"+++def test_pinning_a_detected_install_to_its_own_backend_is_a_real_change(monkeypatch, tmp_path):+ """auto -> cuda on a CUDA box installs the same bundle, and still matters: it+ stops the next update from re-detecting the machine onto something else."""+ install_dir = _install(monkeypatch, tmp_path, backend = "cuda", backend_request = "auto")+ _patch_installer(+ monkeypatch,+ on_start = lambda cmd, kwargs: _write_install(+ install_dir, backend = "cuda", backend_request = "cuda"+ ),+ )++ assert upd.start_backend_switch("cuda")["started"] is True+ assert _await_job()["state"] == "success"+++def test_unavailable_backend_is_refused_before_the_runtime_is_unloaded(monkeypatch, tmp_path):+ _install(monkeypatch, tmp_path)+ monkeypatch.setattr(+ upd,+ "_resolve_backends_for_host",+ lambda install_dir, **kwargs: {+ "backends": [{"backend": "vulkan", "available": False, "resolved_backend": None}]+ },+ )+ installer_started = False++ def _unexpected_installer(cmd, kwargs):+ nonlocal installer_started+ installer_started = True++ _patch_installer(monkeypatch, on_start = _unexpected_installer)++ action = upd.start_backend_switch("vulkan")++ assert action["started"] is False+ assert action["reason"] == "backend_unavailable"+ assert installer_started is False+++def test_switch_preflight_uses_the_install_recorded_repository(monkeypatch, tmp_path):+ _install(monkeypatch, tmp_path, published_repo = "owner/custom-llama")+ seen = {}++ def _resolve(install_dir, **kwargs):+ seen.update(kwargs)+ return {"backends": [{"backend": "cpu", "available": False, "resolved_backend": None}]}++ monkeypatch.setattr(upd, "_resolve_backends_for_host", _resolve)++ action = upd.start_backend_switch("cpu")++ assert action["started"] is False+ assert seen["published_repo"] == "owner/custom-llama"+++def test_switch_fails_if_the_installer_does_not_record_the_requested_backend(monkeypatch, tmp_path):+ _install(monkeypatch, tmp_path, backend = "cuda", backend_request = "auto")+ _patch_installer(monkeypatch)++ assert upd.start_backend_switch("cpu")["started"] is True+ job = _await_job()++ assert job["state"] == "error"+ assert "requested cpu" in job["error"]+++def test_an_unknown_backend_is_refused_without_starting_a_job(monkeypatch, tmp_path):+ _install(monkeypatch, tmp_path)++ action = upd.start_backend_switch("sycl")++ assert action["started"] is False+ assert action["reason"] == "unknown_backend"+ assert action["job"]["state"] == "idle"+++def test_a_source_build_has_no_backend_to_switch(monkeypatch, tmp_path):+ install_dir = tmp_path / "llama.cpp"+ (install_dir / "build" / "bin").mkdir(parents = True)+ binary = install_dir / "build" / "bin" / "llama-server"+ binary.write_text("#!/bin/sh\n")+ monkeypatch.setattr(upd, "_find_binary", lambda: str(binary))+ monkeypatch.setattr(upd, "_installer_script", lambda: tmp_path / "install.py")++ action = upd.start_backend_switch("cpu")++ assert action["started"] is False+ assert action["reason"] == "not_prebuilt"+++def test_a_switch_and_an_update_cannot_run_at_once(monkeypatch, tmp_path):+ # The shared job prevents concurrent installers.+ _install(monkeypatch, tmp_path)+ with upd._job_lock:+ upd._job.update(state = upd._JOB_RUNNING, message = "busy")+ try:+ switch = upd.start_backend_switch("cpu")+ update = upd.start_update()+ assert switch["reason"] == "already_running"+ assert update["reason"] == "already_running"+ assert switch["message"] == "Another llama.cpp install is already running."+ assert update["message"] == "Another llama.cpp install is already running."+ finally:+ upd._reset_job_for_tests()+++def test_backend_resolution_is_part_of_the_serialized_operation(monkeypatch, tmp_path):+ _install(monkeypatch, tmp_path)+ with upd._job_lock:+ upd._job.update(+ state = upd._JOB_SUCCESS,+ message = "old completed job",+ finished_at = "2020-01-01T00:00:00Z",+ )+ entered = threading.Event()+ release = threading.Event()++ def _resolve(*args, **kwargs):+ entered.set()+ assert release.wait(timeout = 5)+ return {"backends": [{"backend": "rocm", "available": False, "resolved_backend": None}]}++ monkeypatch.setattr(upd, "_resolve_backends_for_host", _resolve)+ first: dict = {}+ thread = threading.Thread(+ target = lambda: first.update(upd.start_backend_switch("rocm")), daemon = True+ )+ thread.start()+ assert entered.wait(timeout = 5)++ second = upd.start_update()+ assert second["reason"] == "already_running"+ assert second["job"]["state"] == "running"+ assert second["job"]["operation"] == "switch"+ assert second["job"]["requested_backend"] == "rocm"+ assert second["job"]["finished_at"] is None+ release.set()+ thread.join(timeout = 5)++ assert first["reason"] == "backend_unavailable"+ assert first["job"]["state"] == "error"+ assert not upd._operation_lock.locked()+++# ── Status ──+++def test_status_reports_the_install_and_the_options(monkeypatch, tmp_path):+ _install(monkeypatch, tmp_path)+ monkeypatch.setattr(+ upd,+ "_resolve_backends_for_host",+ lambda install_dir, **kwargs: {+ "backends": [+ {+ "backend": "auto",+ "available": True,+ "resolved_backend": "cuda",+ "release_tag": "b9596-mix-abc",+ "asset": "app-b9596-mix-abc-linux-x64-cuda12.tar.gz",+ },+ {"backend": "rocm", "available": False, "reason": "unavailable"},+ # Older pickers ignore backends they cannot label.+ {"backend": "sycl", "available": True},+ ]+ },+ )+ monkeypatch.setattr(+ # Bound into the update module at import, so the freshness module's copy+ # is not the one it calls.+ upd,+ "latest_release_assets",+ lambda repo, force_refresh = False: {"app-b9596-mix-abc-linux-x64-cuda12.tar.gz": 1234},+ )++ status = upd.get_backend_status()++ assert status["supported"] is True+ assert status["backend"] == "cuda"+ assert status["backend_request"] == "auto"+ assert status["selection_applied"] is True+ assert status["installed_tag"] == "b9596-mix-abc"+ by_backend = {option["backend"]: option for option in status["options"]}+ assert by_backend["auto"]["resolved_backend"] == "cuda"+ assert by_backend["auto"]["download_size_bytes"] == 1234+ assert by_backend["rocm"]["available"] is False+ assert "sycl" not in by_backend+++def test_status_reports_when_auto_now_resolves_to_another_backend(monkeypatch, tmp_path):+ _install(monkeypatch, tmp_path, backend = "cpu", backend_request = "auto")++ status = upd.get_backend_status()++ assert status["backend"] == "cpu"+ assert status["backend_request"] == "auto"+ assert status["selection_applied"] is False+++def test_status_keeps_a_concrete_choice_applied_when_its_asset_moves(monkeypatch, tmp_path):+ # The recorded name and the installed backend agree, which is all a concrete+ # choice claims. A newer asset for it is an update, not an unapplied selection.+ _install(+ monkeypatch,+ tmp_path,+ asset = "app-b9596-mix-abc-linux-x64-cuda12-old.tar.gz",+ backend = "cuda",+ backend_request = "cuda",+ )++ status = upd.get_backend_status()++ assert status["backend"] == "cuda"+ assert status["backend_request"] == "cuda"+ assert status["selection_applied"] is True+++def test_a_switch_that_installs_nothing_plans_no_whisper_phase(monkeypatch):+ # Whisper only re-pairs because llama's ggml is being replaced. Without a llama+ # phase there is nothing to re-pair, so a refusal stays a refusal instead of+ # turning into a whisper-only job that reports a switch nobody performed.+ planned = []+ monkeypatch.setattr(+ whisper_upd, "repair_pairing_plan", lambda: planned.append(1) or {"phase": {"repair": True}}+ )++ assert _whisper_phase_plan("cuda", llama_will_run = False) == {}+ assert planned == []+ assert _whisper_phase_plan("cuda", llama_will_run = True)["phase"]["repair"] is True+++def _slim_whisper(+ monkeypatch,+ tmp_path,+ install_kind = "slim",+) -> str:+ whisper_dir = tmp_path / f"whisper.cpp-{install_kind}"+ binary = _write_install(whisper_dir, install_kind = install_kind)+ (whisper_dir / MARKER).rename(whisper_dir / whisper_upd._INSTALL_MARKER_NAME)+ monkeypatch.setattr(whisper_upd, "_find_binary", lambda: binary)+ monkeypatch.setattr(+ whisper_upd, "_installer_script", lambda: tmp_path / "install_whisper_prebuilt.py"+ )+ return binary+++def test_only_a_slim_whisper_install_is_re_paired(monkeypatch, tmp_path):+ _slim_whisper(monkeypatch, tmp_path)+ assert whisper_upd.repair_pairing_plan()["phase"]["repair"] is True++ _slim_whisper(monkeypatch, tmp_path, install_kind = "fat")+ # A fat bundle ships its own ggml, so llama's backend is not its backend.+ assert whisper_upd.repair_pairing_plan()["skip_reason"] == "self_contained"+++def test_whisper_repair_installs_the_backend_llama_landed_on(monkeypatch, tmp_path):+ _slim_whisper(monkeypatch, tmp_path) # marker backend "cuda"+ monkeypatch.setattr(+ whisper_upd,+ "_installed_llama_bundle",+ lambda: ("rocm", "app-b9596-linux-x64-rocm-gfx1100.tar.gz"),+ )+ calls = []+ monkeypatch.setattr(+ whisper_upd,+ "_install_latest",+ lambda *args, **kwargs: calls.append(args) or {},+ )++ result = whisper_upd.run_repair_phase(+ {"install_dir": tmp_path, "repo": "unslothai/whisper.cpp", "script": tmp_path / "i.py"},+ lambda progress: None,+ )++ # The llama asset carries the AMD arch the new bundle was built for.+ assert calls[0][2] == "app-b9596-linux-x64-rocm-gfx1100.tar.gz"+ assert calls[0][3] == "rocm"+ assert "rocm backend" in result["message"]+++def test_whisper_repair_skips_a_backend_it_is_already_built_against(monkeypatch, tmp_path):+ # Detection can land back where it was; the release is preserved either way,+ # so the hardlinks still point at the same build.+ _slim_whisper(monkeypatch, tmp_path) # marker backend "cuda"+ monkeypatch.setattr(whisper_upd, "_installed_llama_bundle", lambda: ("cuda", "asset.tar.gz"))+ monkeypatch.setattr(+ whisper_upd, "_install_latest", lambda *a, **k: pytest.fail("reinstalled needlessly")+ )++ assert whisper_upd.run_repair_phase({}, lambda progress: None) == {}+++def test_whisper_repair_treats_only_incompatibility_as_unavailable(monkeypatch, tmp_path):+ _slim_whisper(monkeypatch, tmp_path) # marker backend "cuda"+ monkeypatch.setattr(whisper_upd, "_installed_llama_bundle", lambda: ("vulkan", "asset.tar.gz"))+ monkeypatch.setattr(+ whisper_upd,+ "_install_latest",+ lambda *a, **k: (_ for _ in ()).throw(whisper_upd._flow.InstallerExit(2, "incompatible")),+ )++ result = whisper_upd.run_repair_phase(+ {"install_dir": tmp_path, "repo": "r", "script": tmp_path / "i.py"}, lambda p: None+ )++ assert "no whisper.cpp build is published" in result["message"]++[email protected]("returncode", [1, 3])+def test_whisper_repair_surfaces_retryable_installer_failures(monkeypatch, tmp_path, returncode):+ _slim_whisper(monkeypatch, tmp_path) # marker backend "cuda"+ monkeypatch.setattr(whisper_upd, "_installed_llama_bundle", lambda: ("vulkan", "asset.tar.gz"))+ monkeypatch.setattr(+ whisper_upd,+ "_install_latest",+ lambda *a, **k: (_ for _ in ()).throw(+ whisper_upd._flow.InstallerExit(returncode, "retryable")+ ),+ )++ with pytest.raises(whisper_upd._flow.InstallerExit) as raised:+ whisper_upd.run_repair_phase(+ {"install_dir": tmp_path, "repo": "r", "script": tmp_path / "i.py"}, lambda p: None+ )++ assert raised.value.returncode == returncode+++def test_status_surfaces_an_environment_pin(monkeypatch, tmp_path):+ # Surface environment overrides instead of accepting an ineffective choice.+ monkeypatch.setenv("UNSLOTH_LLAMA_CPP_BACKEND", "vulkan")+ _install(monkeypatch, tmp_path)+ monkeypatch.setattr(upd, "_resolve_backends_for_host", lambda install_dir, **kwargs: {})++ status = upd.get_backend_status()++ assert status["env_backend"] == "vulkan"+++def test_status_says_why_an_unmanaged_install_cannot_be_switched(monkeypatch, tmp_path):+ monkeypatch.setattr(upd, "_find_binary", lambda: None)++ status = upd.get_backend_status()++ assert status["supported"] is False+ assert status["reason"] == "not_installed"+ assert status["options"] == []+++def test_status_degrades_when_the_options_cannot_be_resolved(monkeypatch, tmp_path):+ # Offline status keeps the installed backend without guessing alternatives.+ _install(monkeypatch, tmp_path)+ monkeypatch.setattr(upd, "_resolve_backends_for_host", lambda install_dir, **kwargs: None)++ status = upd.get_backend_status()++ assert status["reason"] == "unresolved"+ assert status["supported"] is False+ assert status["backend"] == "cuda"+ assert status["options"] == []+++def test_backend_resolution_failures_are_not_cached(monkeypatch, tmp_path):+ memo = {}+ responses = [+ (1, ""),+ (+ 0,+ json.dumps(+ {"backends": [{"backend": "auto", "available": True, "resolved_backend": "cuda"}]}+ ),+ ),+ ]++ def _run(cmd, **kwargs):+ returncode, stdout = responses.pop(0)+ return type("Result", (), {"returncode": returncode, "stdout": stdout})()++ monkeypatch.setattr(upd.subprocess, "run", _run)++ kwargs = {+ "force_refresh": False,+ "memo": memo,+ "installer_script": lambda: tmp_path / "install.py",+ "log_message": "test resolver failed",+ "mode": ("--resolve-backends", "latest"),+ }+ assert upd._flow.resolve_prebuilt_for_host(**kwargs) is None+ resolved = upd._flow.resolve_prebuilt_for_host(**kwargs)+ assert resolved["backends"][0]["available"] is True+ assert responses == []+++def test_running_job_status_does_not_resolve_options_again(monkeypatch, tmp_path):+ _install(monkeypatch, tmp_path)++ def _unexpected_resolver(*args, **kwargs):+ raise AssertionError("resolver raced the running installer")++ monkeypatch.setattr(upd, "_resolve_backends_for_host", _unexpected_resolver)+ with upd._job_lock:+ upd._job.update(state = upd._JOB_RUNNING, operation = "update")+ try:+ status = upd.get_backend_status()+ finally:+ upd._reset_job_for_tests()++ assert status["job"]["state"] == "running"+ assert status["options"] == []diff --git a/studio/backend/tests/test_llama_cpp_freshness.py b/studio/backend/tests/test_llama_cpp_freshness.pyindex 0624d6e9e5b..9f9be4c3ee5 100644--- a/studio/backend/tests/test_llama_cpp_freshness.py+++ b/studio/backend/tests/test_llama_cpp_freshness.py@@ -161,6 +161,26 @@ def test_read_install_marker_handles_invalid_json(tmp_path):assert fr.read_install_marker(str(bin_path)) is None+ "payload",+ ["[]", '["cpu"]', '"cuda"', "123", "true", "null"],+ ids = ["empty-list", "list", "string", "int", "bool", "null"],+)+def test_read_install_marker_rejects_non_object_json(tmp_path, payload):+ """JSON that parses but is not an object must read as "no marker".++ Every caller treats a non-None return as a mapping -- the update planner, the+ backend picker and crash recovery all reach straight for ``.get`` -- so a marker+ holding ``["cpu"]`` used to raise AttributeError out of a plain status read+ instead of degrading to the source-build path a corrupt file deserves.+ """+ install_dir = tmp_path / "llama.cpp"+ install_dir.mkdir(parents = True)+ (install_dir / "UNSLOTH_PREBUILT_INFO.json").write_text(payload)+ bin_path = _fake_binary(install_dir, layout = "root")+ assert fr.read_install_marker(str(bin_path)) is None++def test_read_install_marker_handles_none_path():assert fr.read_install_marker(None) is Nonediff --git a/studio/backend/tests/test_llama_cpp_update.py b/studio/backend/tests/test_llama_cpp_update.pyindex 3d625fc5fc5..be01d8eb54a 100644--- a/studio/backend/tests/test_llama_cpp_update.py+++ b/studio/backend/tests/test_llama_cpp_update.py@@ -466,47 +466,64 @@ def test_start_update_happy_path(monkeypatch, tmp_path):@pytest.mark.parametrize(- "llama_backend,include_llama_backend,expect_forced",+ "marker_fields, expected_choice",[- (None, False, True),- (None, True, False),- ("vulkan", True, True),- ("auto", True, False),+ # A legacy markerless Vulkan asset was an explicit selection, so the bundle+ # is kept rather than re-detected.+ ({"asset": "llama-b9493-bin-ubuntu-vulkan-x64.tar.gz"}, "vulkan"),+ # New automatic Intel / Windows AMD installs carry llama_backend (None or+ # "auto") and rerun hardware detection, staying eligible for CPU recovery.+ (+ {+ "asset": "llama-b9493-bin-ubuntu-vulkan-x64.tar.gz",+ "llama_backend": None,+ "include_llama_backend": True,+ },+ "auto",+ ),+ (+ {"asset": "llama-b9493-bin-ubuntu-vulkan-x64.tar.gz", "llama_backend": "auto"},+ "auto",+ ),+ (+ {"asset": "llama-b9493-bin-ubuntu-vulkan-x64.tar.gz", "llama_backend": "vulkan"},+ "vulkan",+ ),+ # A deliberate CPU install must not be re-routed onto a GPU bundle (#7213);+ # a transient fallback (or a legacy marker without the flag) heals (#6097).+ ({"asset": "llama-b9493-bin-ubuntu-x64.tar.gz", "force_cpu": True}, "cpu"),+ ({"asset": "llama-b9493-bin-ubuntu-x64.tar.gz", "force_cpu": False}, "auto"),+ ({"asset": "llama-b9493-bin-ubuntu-x64.tar.gz"}, "auto"),],)-def test_start_update_preserves_vulkan_selection(- monkeypatch, tmp_path, llama_backend, include_llama_backend, expect_forced+def test_update_leaves_the_recorded_choice_to_the_installer(+ monkeypatch, tmp_path, marker_fields, expected_choice):- # A legacy markerless Vulkan asset was an explicit selection. New automatic Intel- # and Windows AMD installs carry llama_backend (None or "auto") and rerun hardware- # detection so they stay eligible for CPU crash recovery.+ """An update names no backend: install_llama_prebuilt.py reads the choice back+ out of the marker it wrote.++ That is what makes the choice survive every other entry point too (setup.sh,+ `unsloth studio update`, the desktop updater), none of which could forward an+ env var they were never given. Both halves are asserted here -- the command+ carries no override, and the installer resolves the marker to the choice -- so+ the handoff cannot silently break on one side.+ """monkeypatch.delenv("UNSLOTH_FORCE_VULKAN", raising = False)monkeypatch.delenv("UNSLOTH_LLAMA_CPP_BACKEND", raising = False)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",- llama_backend = llama_backend,- include_llama_backend = include_llama_backend,- )+ fields = dict(marker_fields)+ binary = _write_install(install_dir, "b9493", repo = "ggml-org/llama.cpp", **fields)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 = {}+ popen_kwargs: dict = {}+def _on_start(cmd):captured["cmd"] = cmd- _write_install(- install_dir,- "b9518",- repo = "ggml-org/llama.cpp",- asset = "llama-b9518-bin-ubuntu-vulkan-x64.tar.gz",- llama_backend = llama_backend,- )+ _write_install(install_dir, "b9518", repo = "ggml-org/llama.cpp", **fields)- captured: dict = {}- popen_kwargs: dict = {}_patch_installer_popen(monkeypatch,lines = ["installed\n"],@@ -522,55 +539,22 @@ def test_start_update_preserves_vulkan_selection(breaktime.sleep(0.05)assert job["state"] == "success", job- if expect_forced:- assert popen_kwargs["env"]["UNSLOTH_FORCE_VULKAN"] == "1"- assert popen_kwargs["env"]["UNSLOTH_LLAMA_CPP_BACKEND"] == "vulkan"- assert "--llama-backend" in captured["cmd"] and "vulkan" in captured["cmd"]- else:- assert "UNSLOTH_FORCE_VULKAN" not in popen_kwargs["env"]- assert "UNSLOTH_LLAMA_CPP_BACKEND" not in popen_kwargs["env"]- assert "--llama-backend" not in captured["cmd"]-- "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)+ assert "--llama-backend" not in captured["cmd"]+ assert "--force-cpu" not in captured["cmd"]+ assert "--cpu-fallback" not in captured["cmd"]+ assert "UNSLOTH_LLAMA_CPP_BACKEND" not in popen_kwargs["env"]+ assert "UNSLOTH_FORCE_VULKAN" not in popen_kwargs["env"]- _patch_installer_popen(monkeypatch, lines = ["installed\n"], on_start = _on_start)+ _studio = _BACKEND.parent+ if str(_studio) not in sys.path:+ sys.path.insert(0, str(_studio))+ import install_llama_prebuilt as ilp- 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"]+ assert ilp.effective_backend_request(None, install_dir = install_dir) == (+ expected_choice,+ False,+ )def test_start_update_reports_full_release_tag(monkeypatch, tmp_path):@@ -836,6 +820,7 @@ def test_start_update_already_running_refuses(monkeypatch, tmp_path):res = upd.start_update()assert res["started"] is Falseassert res["reason"] == "already_running"+ assert res["message"] == "Another llama.cpp install is already running."def test_start_update_installer_missing_refuses(monkeypatch, tmp_path):@@ -923,6 +908,7 @@ def test_update_clears_maintenance_flag_on_installer_failure(monkeypatch, tmp_pabreaktime.sleep(0.05)assert upd.get_update_status()["job"]["state"] == "error"+ assert upd.get_update_status()["job"]["reload_required"] is Trueassert backend._llama_update_in_progress is Falsediff --git a/studio/backend/tests/test_llama_route.py b/studio/backend/tests/test_llama_route.pyindex cc450d55cc0..9ca66531436 100644--- a/studio/backend/tests/test_llama_route.py+++ b/studio/backend/tests/test_llama_route.py@@ -115,6 +115,12 @@ def test_status_response_exposes_update_component():assert model.model_dump()["update_component"] == "whisper"+def test_backend_status_response_exposes_selection_applied():+ model = rl.LlamaBackendStatusResponse(selection_applied = False)++ assert model.model_dump()["selection_applied"] is False++def test_status_handler_runs_off_event_loop(monkeypatch):seen = {}diff --git a/studio/backend/tests/test_setup_llama_cpp_backend.py b/studio/backend/tests/test_setup_llama_cpp_backend.pyindex 29d6e8b3b8a..b7ccb3cbb0e 100644--- a/studio/backend/tests/test_setup_llama_cpp_backend.py+++ b/studio/backend/tests/test_setup_llama_cpp_backend.py@@ -3,10 +3,11 @@"""Backend selector coverage for setup.sh and setup.ps1.-cpu maps to install_llama_prebuilt.py's persisted --force-cpu option. vulkan is-accepted and passed through in the environment for the installer to consume.-The match is case-insensitive and whitespace-trimmed, unknown values warn, and-macOS warns for the CPU-only choice.+The scripts do not act on UNSLOTH_LLAMA_CPP_BACKEND: install_llama_prebuilt.py+reads it directly, and it is also the only side that can see a choice recorded in+the install marker. What is left here is reporting -- the match is+case-insensitive and whitespace-trimmed, unknown values warn, and macOS says so+for the two choices its universal Metal build cannot honour."""import os@@ -26,7 +27,7 @@ _SKIP_NO_PWSH = pytest.mark.skipif(shutil.which("pwsh") is None, reason = "pwshdef _backend_block() -> str:text = _SETUP_SH.read_text(encoding = "utf-8")- m = re.search(r"_llama_backend=.*?esac", text, re.DOTALL)+ m = re.search(r"# Reporting only:.*?esac", text, re.DOTALL)assert m, "UNSLOTH_LLAMA_CPP_BACKEND block not found in setup.sh"return m.group(0)@@ -44,10 +45,11 @@ def _run(value: str | None, system: str = "Linux") -> tuple[list[str], str]:env["UNSLOTH_LLAMA_CPP_BACKEND"] = valueharness = (f'set -u\n_PREBUILT_CMD=()\nC_WARN=""\nC_OK=""\n_HOST_SYSTEM="{system}"\n'- '_source_backend_choice="$(printf \'%s\' "${UNSLOTH_LLAMA_CPP_BACKEND:-auto}" '+ '_source_backend_choice="$(printf \'%s\' "${UNSLOTH_LLAMA_CPP_BACKEND:-}" '"| awk '{$1=$1; print tolower($0)}')\"\n"'_source_legacy_force_vulkan="$(printf \'%s\' "${UNSLOTH_FORCE_VULKAN:-}" '"| awk '{$1=$1; print tolower($0)}')\"\n"+ '_explicit_llama_source_backend=""\n''step() { printf "STEP: %s\\n" "$*" >&2; }\n'f"{_backend_block()}\n"'printf "%s\\n" "${_PREBUILT_CMD[@]}"'@@ -58,59 +60,68 @@ def _run(value: str | None, system: str = "Linux") -> tuple[list[str], str]:return out.stdout.split(), out.stderr+def test_backend_block_forwards_nothing_to_the_installer():+ # One owner for the selection. install_llama_prebuilt.py reads the variable+ # itself and is the only side that can also read the marker's recorded choice,+ # so a second copy assembled here could only ever contradict it.+ assert "_PREBUILT_CMD" not in _backend_block()++@_SKIP_NO_BASH@pytest.mark.parametrize("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).+def test_backend_cpu_is_accepted(value):args, stderr = _run(value)- assert "--force-cpu" in args- assert "--cpu-fallback" not in args+ assert args == []assert "Ignoring" not in stderr@_SKIP_NO_BASH@pytest.mark.parametrize("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.+def test_backend_cpu_macos_warns(value):+ # macOS has no CPU-only bundle: the universal build already runs on CPU.args, stderr = _run(value, system = "Darwin")- assert "--force-cpu" not in args- assert "--cpu-fallback" not in args+ assert args == []assert "macOS" in stderr@_SKIP_NO_BASH@pytest.mark.parametrize("value", [None, "", "auto", "AUTO", " "])-def test_backend_auto_no_flag_no_warn(value):+def test_backend_auto_is_silent(value):args, stderr = _run(value)- assert "--force-cpu" not in args- assert "Ignoring" not in stderr+ assert args == []+ assert stderr == ""@_SKIP_NO_BASH@pytest.mark.parametrize("value", ["vulkan", "VULKAN", " vulkan "])-def test_backend_vulkan_is_accepted(value):+def test_backend_vulkan_is_reported(value):args, stderr = _run(value)- assert "--force-cpu" not in args- assert args[-2:] == ["--llama-backend", "vulkan"]+ assert args == []+ assert "Vulkan selected for GGUF inference" in stderrassert "Ignoring" not in stderr@_SKIP_NO_BASH[email protected]("value", ["hip", "HIP", "rocm", " ROCM "])-def test_backend_hip_opt_out_is_accepted(value):[email protected]("value", ["vulkan", "VULKAN"])+def test_backend_vulkan_macos_warns(value):+ args, stderr = _run(value, system = "Darwin")+ assert args == []+ assert "Metal" in stderr+++@_SKIP_NO_BASH[email protected]("value", ["hip", "HIP", "rocm", " ROCM ", "cuda", " CUDA "])+def test_backend_gpu_opt_out_is_accepted(value):args, stderr = _run(value)- assert "--force-cpu" not in args- assert "--llama-backend" not in args+ assert args == []assert "Ignoring" not in stderr@_SKIP_NO_BASH[email protected]("value", ["gpu", "cuda"])-def test_backend_unknown_warns_and_no_flag(value):[email protected]("value", ["gpu", "sycl"])+def test_backend_unknown_warns(value):args, stderr = _run(value)- assert "--force-cpu" not in args+ assert args == []assert "Ignoring" in stderr@@ -126,37 +137,51 @@ def test_arm64_recovery_uses_transient_cpu_fallback():assert "--force-cpu" not in block-def test_explicit_vulkan_prebuilt_failure_does_not_change_backend():+def test_ordinary_prebuilt_failure_does_not_re_derive_the_backend():+ # Exit 2 is reached only when no concrete backend was in play: a request the+ # installer could not honour -- named in the environment or recorded in the+ # marker the scripts cannot read -- arrives as exit 5 and fails closed there.+ # Re-deriving it here from the environment alone would miss the marker case+ # and disagree with the installer on the rest.sh = _SETUP_SH.read_text(encoding = "utf-8")failure = sh.index('step "llama.cpp" "prebuilt install failed"')- source_build = sh.index("_NEED_LLAMA_SOURCE_BUILD=true", failure)- guard = sh.index('if [ "$_explicit_vulkan_backend" = true ]', failure)- assert guard < source_build- guarded = sh[guard:source_build]- assert "will not substitute a ROCm or CPU source build" in guarded- # Aborts through the helper, which exits AND emits [TAURI:ERROR] in desktop mode.- assert "setup_fail 1" in guarded+ branch = sh[failure : sh.index("_NEED_LLAMA_SOURCE_BUILD=true", failure)]+ assert "_explicit_llama" not in branchps1 = _SETUP_PS1.read_text(encoding = "utf-8")failure = ps1.index('step "llama.cpp" "prebuilt install failed"')- source_build = ps1.index("$NeedLlamaSourceBuild = $true", failure)- guard = ps1.index("if ($explicitVulkanBackend)", failure)- assert guard < source_build- guarded = ps1[guard:source_build]- assert "will not substitute a CUDA, ROCm, or CPU source build" in guarded+ branch = ps1[failure : ps1.index("$NeedLlamaSourceBuild = $true", failure)]+ assert "explicitLlama" not in branch+++def test_unavailable_named_backend_never_falls_through_to_source():+ sh = _SETUP_SH.read_text(encoding = "utf-8")+ unavailable = sh.index('elif [ "$_PREBUILT_STATUS" -eq 5 ]; then')+ ordinary_fallback = sh.index('elif [ "$_PREBUILT_STATUS" -eq 2 ]; then', unavailable)+ guarded = sh[unavailable:ordinary_fallback]+ assert "will not substitute a different source backend" in guarded+ assert "_NEED_LLAMA_SOURCE_BUILD=true" not in guarded+ assert "setup_fail 1" in guarded++ ps1 = _SETUP_PS1.read_text(encoding = "utf-8")+ unavailable = ps1.index("} elseif ($prebuiltExit -eq 5) {")+ ordinary_fallback = ps1.index("} elseif ($prebuiltExit -eq 2) {", unavailable)+ guarded = ps1[unavailable:ordinary_fallback]+ assert "will not substitute a different source backend" in guarded+ assert "$NeedLlamaSourceBuild = $true" not in guardedassert "Exit-SetupFailure" in guarded-def test_explicit_vulkan_source_build_fails_closed():+def test_explicit_backend_source_build_fails_closed():sh = _SETUP_SH.read_text(encoding = "utf-8")local_branch = sh.index('if [ "$_LOCAL_LLAMA_CPP_LINKED" = true ]; then')prebuilt_branch = sh.index('elif [ "$_LLAMA_FORCE_COMPILE" = "1" ]; then', local_branch)guarded = sh[local_branch:prebuilt_branch]assert (- 'elif [ "$_explicit_vulkan_source_build" = true ] && '+ 'elif [ -n "$_explicit_llama_source_backend" ] && ''[ "$_NEED_LLAMA_SOURCE_BUILD" = true ]; then') in guarded- assert "Vulkan source builds are not supported" in guarded+ assert "Explicit backend selection requires a matching prebuilt bundle" in guardedassert "setup_fail 1" in guardedps1 = _SETUP_PS1.read_text(encoding = "utf-8")@@ -165,46 +190,43 @@ def test_explicit_vulkan_source_build_fails_closed():'} elseif ($env:UNSLOTH_LLAMA_FORCE_COMPILE -eq "1") {', local_branch)guarded = ps1[local_branch:prebuilt_branch]- assert "} elseif ($explicitVulkanSourceBuild -and $NeedLlamaSourceBuild) {" in guarded- assert "Vulkan source builds are not supported" in guarded+ assert "} elseif ($explicitLlamaSourceBackend -and $NeedLlamaSourceBuild) {" in guarded+ assert "Explicit backend selection requires a matching prebuilt bundle" in guardedassert "Exit-SetupFailure" in guarded-def test_force_compile_sets_need_source_build_before_vulkan_guard():- # UNSLOTH_LLAMA_FORCE_COMPILE=1 combined with an explicit Vulkan backend must- # hit the "Vulkan source builds are not supported" rejection, not silently- # fall through to a CUDA/ROCm/CPU source build. That only holds if- # _NEED_LLAMA_SOURCE_BUILD/$NeedLlamaSourceBuild is already true by the time- # the explicit-Vulkan elif guard runs, i.e. set earlier in the script.+def test_force_compile_sets_need_source_build_before_backend_guard():+ # A forced source build combined with any concrete backend must reach the+ # explicit-backend rejection. The source-build state must therefore be set+ # before the guard runs.sh = _SETUP_SH.read_text(encoding = "utf-8")force_compile_set = sh.index('if [ "$_LLAMA_FORCE_COMPILE" = "1" ]; then\n _NEED_LLAMA_SOURCE_BUILD=true')- vulkan_guard = sh.index('elif [ "$_explicit_vulkan_source_build" = true ] && ')- assert force_compile_set < vulkan_guard+ backend_guard = sh.index('elif [ -n "$_explicit_llama_source_backend" ] && ')+ assert force_compile_set < backend_guardps1 = _SETUP_PS1.read_text(encoding = "utf-8")force_compile_set = ps1.index('if ($env:UNSLOTH_LLAMA_FORCE_COMPILE -eq "1") {\n $NeedLlamaSourceBuild = $true')- vulkan_guard = ps1.index("} elseif ($explicitVulkanSourceBuild -and $NeedLlamaSourceBuild) {")- assert force_compile_set < vulkan_guard+ backend_guard = ps1.index("} elseif ($explicitLlamaSourceBackend -and $NeedLlamaSourceBuild) {")+ assert force_compile_set < backend_guarddef test_legacy_force_vulkan_gets_the_same_strict_fallback():sh = _SETUP_SH.read_text(encoding = "utf-8")- assert "_legacy_force_vulkan=" in sh- assert "1|true|yes|on) _explicit_vulkan_backend=true" in sh+ assert '1|true|yes|on) _explicit_llama_source_backend="vulkan"' in shps1 = _SETUP_PS1.read_text(encoding = "utf-8")- assert "$legacyForceVulkan = $sourceLegacyForceVulkan" in ps1- assert '$legacyForceVulkan -in @("1", "true", "yes", "on")' in ps1+ assert '$sourceLegacyForceVulkan -in @("1", "true", "yes", "on")' in ps1+ assert '$explicitLlamaSourceBackend = "vulkan"' in ps1def _source_backend_choice_block() -> str:text = _SETUP_SH.read_text(encoding = "utf-8")m = re.search(- r'_source_backend_choice="\$\(printf.*?\n.*?_explicit_vulkan_source_build=false\n'+ r'_source_backend_choice="\$\(printf.*?\n.*?_explicit_llama_source_backend=""\n'r".*?\nfi\n",text,re.DOTALL,@@ -217,13 +239,15 @@ def _source_backend_choice_block() -> str:@pytest.mark.parametrize("backend, force_vulkan, expected_backend, expected_explicit",[- (None, None, "auto", "false"),- ("vulkan", None, "vulkan", "true"),- ("auto", "on", "auto", "true"),- ("banana", "1", "banana", "true"),- ("cpu", "1", "cpu", "false"),- ("hip", "1", "hip", "false"),- ("rocm", "1", "rocm", "false"),+ (None, None, "", ""),+ (None, "on", "", "vulkan"),+ ("vulkan", None, "vulkan", "vulkan"),+ ("auto", "on", "auto", ""),+ ("banana", "1", "banana", "vulkan"),+ ("cpu", "1", "cpu", "cpu"),+ ("cuda", "1", "cuda", "cuda"),+ ("hip", "1", "hip", "rocm"),+ ("rocm", "1", "rocm", "rocm"),],)def test_llama_backend_source_choice_in_setup_sh(@@ -241,7 +265,7 @@ def test_llama_backend_source_choice_in_setup_sh(harness = ("set -u\n_HOST_SYSTEM=Linux\n"f"{_source_backend_choice_block()}\n"- 'printf "%s:%s" "$_source_backend_choice" "$_explicit_vulkan_source_build"'+ 'printf "%s:%s" "$_source_backend_choice" "$_explicit_llama_source_backend"')out = subprocess.run(["bash", "-c", harness], capture_output = True, text = True, env = env, check = True@@ -259,18 +283,20 @@ def _ps1_search(pattern: str, flags = 0) -> str:@pytest.mark.parametrize("backend, force_vulkan, expected_explicit",[- (None, None, "False"),- ("vulkan", None, "True"),- ("auto", "on", "True"),- ("cpu", "1", "False"),- ("hip", "1", "False"),- ("rocm", "1", "False"),+ (None, None, ""),+ (None, "on", "vulkan"),+ ("vulkan", None, "vulkan"),+ ("auto", "on", ""),+ ("cpu", "1", "cpu"),+ ("cuda", "1", "cuda"),+ ("hip", "1", "rocm"),+ ("rocm", "1", "rocm"),],)def test_llama_backend_source_choice_in_setup_ps1(backend, force_vulkan, expected_explicit):normalize = _ps1_search(r'\$sourceLlamaBackend = "\$\(\$env:UNSLOTH_LLAMA_CPP_BACKEND\)".*?'- r"\$explicitVulkanSourceBuild = \(.*?\n\)\n",+ r"\$explicitLlamaSourceBackend = \$null.*?\n\}",re.DOTALL,)env = {@@ -289,7 +315,7 @@ def test_llama_backend_source_choice_in_setup_ps1(backend, force_vulkan, expecte"-Command",# Brace the name: PowerShell reads "$var:" as a scope qualifier and# fails to parse, so the probe never ran on a host that has pwsh.- f'{normalize}\n"RESULT:${{sourceLlamaBackend}}:$explicitVulkanSourceBuild"',+ f'{normalize}\n"RESULT:${{sourceLlamaBackend}}:$explicitLlamaSourceBackend"',],capture_output = True,text = True,@@ -301,15 +327,12 @@ def test_llama_backend_source_choice_in_setup_ps1(backend, force_vulkan, expectedef _run_ps1(value: str | None) -> str:- # One snippet, not two: NORMALIZE already spans the whole if/elseif chain up to- # and including the "Ignoring UNSLOTH_LLAMA_CPP_BACKEND" warn, so the --force-cpu- # append is inside it. Composing the apply snippet on top of it made the harness- # emit the flag twice while setup.ps1 appends it once.normalize = _ps1_search(r"\$llamaBackend = \$sourceLlamaBackend.*?Ignoring UNSLOTH_LLAMA_CPP_BACKEND.*?\n\s*\}",re.DOTALL,)- assert normalize.count('$prebuiltArgs += "--force-cpu"') == 1, normalize+ # The mirror of test_backend_block_forwards_nothing_to_the_installer.+ assert "$prebuiltArgs" not in normalize, normalizeenv = {k: vfor k, v in os.environ.items()@@ -327,6 +350,7 @@ def _run_ps1(value: str | None) -> str:"$prebuiltArgs = @()\n"'$sourceLlamaBackend = "$($env:UNSLOTH_LLAMA_CPP_BACKEND)".Trim().ToLowerInvariant()\n''$sourceLegacyForceVulkan = "$($env:UNSLOTH_FORCE_VULKAN)".Trim().ToLowerInvariant()\n'+ "$explicitLlamaSourceBackend = $null\n"f'{normalize}\n"ARGS:" + ($prebuiltArgs -join ",")')out = subprocess.run(@@ -340,56 +364,42 @@ def _run_ps1(value: str | None) -> str:@_SKIP_NO_PWSH[email protected]("value", ["cpu", "CPU", "Cpu", " cpu ", "CPU\t"])-def test_ps1_backend_cpu_appends_flag(value):- out = _run_ps1(value)- # The whole argv, not a substring: an `in` check passed while the harness was- # emitting --force-cpu twice. setup.ps1 appends it exactly once, and nothing- # else, for a cpu override.- assert out.strip() == "ARGS:--force-cpu"---@_SKIP_NO_PWSH[email protected]("value", [None, "", "auto", "AUTO", " "])-def test_ps1_backend_auto_no_flag_no_warn(value):+ "value", ["cpu", "CPU", "Cpu", " cpu ", "CPU\t", None, "", "auto", "AUTO", " "]+)+def test_ps1_backend_forwards_no_arguments(value):out = _run_ps1(value)- assert "--force-cpu" not in out- assert "Ignoring" not in out+ assert out.strip() == "ARGS:"@_SKIP_NO_PWSH@pytest.mark.parametrize("value", ["vulkan", "VULKAN", " vulkan "])-def test_ps1_backend_vulkan_is_accepted(value):+def test_ps1_backend_vulkan_is_reported(value):out = _run_ps1(value)- assert "--force-cpu" not in out- assert "--llama-backend,vulkan" in out+ assert "Vulkan selected for GGUF inference" in outassert "Ignoring" not in out@_SKIP_NO_PWSH[email protected]("value", ["hip", "HIP", "rocm", " ROCM "])-def test_ps1_backend_hip_opt_out_is_accepted(value):[email protected]("value", ["cuda", " CUDA ", "hip", "HIP", "rocm", " ROCM "])+def test_ps1_backend_gpu_opt_out_is_accepted(value):out = _run_ps1(value)- assert "--force-cpu" not in out- assert "--llama-backend" not in out- assert "Ignoring" not in out+ assert out.strip() == "ARGS:"def test_ps1_forced_vulkan_fails_closed_on_windows_arm64():ps1 = _SETUP_PS1.read_text(encoding = "utf-8")- arm64_guard = ps1.index("elseif ($windowsArm64)")- vulkan_flag = ps1.index(- '$prebuiltArgs += @("--llama-backend", "vulkan")',- arm64_guard,+ branch = ps1.index(+ 'if ($llamaBackend -eq "vulkan" -or $explicitLlamaSourceBackend -eq "vulkan")')- assert arm64_guard < vulkan_flag- assert "no Windows ARM64 Vulkan bundle is published" in ps1- assert "Unset UNSLOTH_FORCE_VULKAN" in ps1+ guarded = ps1[branch : ps1.index("Vulkan selected for GGUF inference", branch)]+ assert "elseif ($windowsArm64)" in guarded+ assert "no Windows ARM64 Vulkan bundle is published" in guarded+ assert "UNSLOTH_FORCE_VULKAN" in guarded@_SKIP_NO_PWSH[email protected]("value", ["gpu", "cuda"])-def test_ps1_backend_unknown_warns_and_no_flag(value):[email protected]("value", ["gpu", "sycl"])+def test_ps1_backend_unknown_warns(value):out = _run_ps1(value)- assert "--force-cpu" not in outassert "Ignoring" in outdiff --git a/studio/backend/utils/llama_cpp_update.py b/studio/backend/utils/llama_cpp_update.pyindex 9d363924803..c6c31eba0cd 100644--- a/studio/backend/utils/llama_cpp_update.py+++ b/studio/backend/utils/llama_cpp_update.py@@ -50,6 +50,13 @@ from utils.llama_cpp_freshness import (update_download_size_bytes,)from utils.prebuilt import update_flow as _flow+from utils.prebuilt.llama_backend import (+ REQUESTABLE_BACKENDS,+ environment_backend_override,+ marker_backend,+ marker_backend_request,+ normalize_backend,+)logger = structlog.get_logger(__name__)@@ -57,6 +64,17 @@ DEFAULT_PUBLISHED_REPO = "unslothai/llama.cpp"_INSTALL_TIMEOUT_SECONDS = 1800 # 30 min ceiling for download + build/validate# install_llama_prebuilt.py EXIT_NO_SPACE: out of disk, retrying will not help._EXIT_NO_SPACE = 4+# A concrete backend selection could not be satisfied.+_EXIT_BACKEND_UNAVAILABLE = 5+++class _LlamaPhaseError(RuntimeError):+ """A llama phase failed after possibly unloading the active runtime."""++ def __init__(self, message: str, *, reload_required: bool):+ super().__init__(message)+ self.reload_required = reload_required+# Background job state. Single in-flight update at a time, guarded by _job_lock._JOB_IDLE = _flow.JOB_IDLE@@ -65,7 +83,12 @@ _JOB_SUCCESS = _flow.JOB_SUCCESS_JOB_ERROR = _flow.JOB_ERROR_job_lock = threading.Lock()+# Covers the complete operation, including release/backend resolution before the+# worker starts. _job_lock only protects the status dictionary and must never be+# held across network work.+_operation_lock = threading.Lock()_job: dict = _flow.new_job()+_ALREADY_RUNNING_MESSAGE = "Another llama.cpp install is already running."_utcnow = _flow.utcnow_is_under = _flow.is_under@@ -332,7 +355,9 @@ def get_update_status(*, force_refresh: bool = False) -> dict:return _merge_whisper_status(status, force_refresh = force_refresh)-def _llama_only_status(*, force_refresh: bool = False) -> dict:+def _llama_only_status(+ *, force_refresh: bool = False, allow_source_probe_while_running: bool = False+) -> dict:"""The llama.cpp half of get_update_status (no whisper sub-status)."""binary = _find_binary()# A --with-llama-cpp-dir local link is the user's own tree; never offer to@@ -349,7 +374,11 @@ def _llama_only_status(*, force_refresh: bool = False) -> dict:# Skipped while the updater swaps the tree: each 3s poll would exec the# half-replaced binary (on Windows that exec can make the installer's# os.replace fail) and the poller only consumes job progress.- if marker is None and binary is not None and not job_running:+ if (+ marker is None+ and binary is not None+ and (not job_running or allow_source_probe_while_running)+ ):src = _source_build_status(binary, force_refresh = force_refresh)if src is not None:return src@@ -403,6 +432,143 @@ def _llama_only_status(*, force_refresh: bool = False) -> dict:}+# Cache resolver results between polls and clear them after an install.+_backends_memo: dict = {}+++def _resolve_backends_for_host(+ install_dir: Optional[Path],+ *,+ force_refresh: bool = False,+ published_repo: Optional[str] = None,+) -> Optional[dict]:+ """Ask the installer which backends it could install here. None on any failure."""+ args: list[str] = []+ if install_dir is not None:+ args.extend(("--install-dir", str(install_dir)))+ if published_repo:+ args.extend(("--published-repo", published_repo))+ return _flow.resolve_prebuilt_for_host(+ force_refresh = force_refresh,+ memo = _backends_memo,+ installer_script = lambda: _installer_script(),+ log_message = "llama backend: resolve-backends failed",+ mode = ("--resolve-backends", "latest"),+ extra_args = tuple(args),+ )+++def _switch_support(binary: Optional[str], marker: Optional[dict]) -> Optional[str]:+ """Return why this install cannot be switched, or None if it can."""+ if binary is None:+ return "not_installed"+ if _active_install_is_local_link(binary):+ return "local_link"+ if marker is None:+ return "source_build"+ if _install_dir_for(binary) is None:+ return "no_install_dir"+ return None+++def _env_backend_override() -> Optional[str]:+ """Return the environment override that outranks the picker."""+ return environment_backend_override(+ os.environ.get("UNSLOTH_LLAMA_CPP_BACKEND"),+ os.environ.get("UNSLOTH_FORCE_VULKAN"),+ )+++def _backend_options(resolved: Optional[dict], assets: Optional[dict] = None) -> list[dict]:+ """Normalize a resolver payload into the options the picker and the switch+ planner both read, so both judge a request against the same list."""+ options = []+ for entry in (resolved or {}).get("backends") or []:+ backend = normalize_backend(entry.get("backend"))+ if backend is None:+ continue+ asset = entry.get("asset")+ options.append(+ {+ "backend": backend,+ "available": bool(entry.get("available")),+ "unavailable_reason": entry.get("reason"),+ # What "auto" would pick right now, so it can be labelled with it.+ "resolved_backend": normalize_backend(entry.get("resolved_backend")),+ "release_tag": entry.get("release_tag"),+ "download_size_bytes": (assets or {}).get(asset) if asset else None,+ }+ )+ return options+++def _selection_applied(+ backend_request: str, installed_backend: Optional[str], options: list[dict]+) -> bool:+ """Whether the recorded choice still describes the installed backend.++ A concrete choice is applied by definition: the installer records it only on+ an install that honoured it, so it can never disagree with what is on disk.+ ``auto`` is the one that drifts -- a GPU or driver that appears after an+ automatic CPU install makes detection resolve somewhere else -- and applying+ it again is offered exactly then.+ """+ if backend_request != "auto":+ return True+ auto = next((option for option in options if option["backend"] == "auto"), None)+ if not auto or not auto.get("available"):+ return True+ resolved = auto.get("resolved_backend")+ return resolved is None or installed_backend is None or resolved == installed_backend+++def get_backend_status(*, force_refresh: bool = False) -> dict:+ """Return the installed backend and host-compatible alternatives."""+ binary = _find_binary()+ marker = read_install_marker(binary)+ unsupported = _switch_support(binary, marker)+ with _job_lock:+ job = dict(_job)+ status: dict = {+ "supported": unsupported is None,+ "reason": unsupported,+ "env_backend": _env_backend_override(),+ "backend": marker_backend(marker),+ "backend_request": marker_backend_request(marker),+ # Only the resolver can tell that an automatic choice has drifted, so an+ # unresolved status must not invite an apply.+ "selection_applied": True,+ "installed_tag": (marker or {}).get("release_tag") or (marker or {}).get("tag"),+ "options": [],+ "job": job,+ }+ if unsupported is not None:+ return status+ # Do not resolve options while the shared job is replacing the install.+ if job["state"] == _JOB_RUNNING:+ return status+ repo = (marker or {}).get("published_repo") or DEFAULT_PUBLISHED_REPO+ resolved = _resolve_backends_for_host(+ _install_dir_for(binary), force_refresh = force_refresh, published_repo = repo+ )+ if not resolved:+ # Keep showing the installed backend without guessing alternatives.+ status["reason"] = "unresolved"+ status["supported"] = False+ return status+ assets = None+ try:+ assets = latest_release_assets(repo, force_refresh = force_refresh)+ except Exception as exc: # pragma: no cover - network defensive+ logger.debug("llama backend: asset size lookup failed", error = str(exc))+ options = _backend_options(resolved, assets)+ status["options"] = options+ status["selection_applied"] = _selection_applied(+ status["backend_request"], status["backend"], options+ )+ return status++def _run_llama_phase(install_dir: Path,repo: str,@@ -410,9 +576,9 @@ def _run_llama_phase(script: Path,pin_release_tag: Optional[str],set_progress,- force_cpu: bool = False,llama_backend: Optional[str] = None,rocm_gfx: Optional[str] = None,+ backend_request: Optional[str] = None,) -> dict:"""The llama phase of a chained update: put the backend into a maintenancestate, run the installer for the latest prebuilt, then refresh caches so the@@ -464,21 +630,15 @@ def _run_llama_phase(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")- if llama_backend == "vulkan":- cmd.extend(["--llama-backend", "vulkan"])+ # Switches name a backend. Updates preserve the marker's recorded choice.+ if backend_request is not None:+ cmd.extend(["--llama-backend", backend_request])logger.info("llama update: installing", cmd = " ".join(cmd))env = dict(os.environ, UNSLOTH_PROGRESS_PERCENT_STEP = "5")- # Preserve a Vulkan install across updates: detect_host on a CUDA/ROCm box would- # otherwise replace it. An "auto" marker reruns hardware detection instead.- if llama_backend == "vulkan":- env["UNSLOTH_FORCE_VULKAN"] = "1"- env["UNSLOTH_LLAMA_CPP_BACKEND"] = "vulkan"+ if backend_request is not None:+ # Ensure an inherited override cannot defeat the requested switch.+ env.pop("UNSLOTH_FORCE_VULKAN", None)+ env["UNSLOTH_LLAMA_CPP_BACKEND"] = backend_request# A Vulkan asset name carries no arch, so the marker is the only record of the# gfx an automatic AMD route used. Automatic only: elsewhere the asset has the# arch, and replaying it would assert ROCm on a host whose AMD GPU is gone.@@ -495,44 +655,87 @@ def _run_llama_phase(# Drop stale caches so the banner re-checks the swapped marker.# If GitHub is offline, latest stays unknown and the banner fails open.reset_caches(drop_disk = True)+ # The cached options describe the previous install.+ _backends_memo.clear()try:latest_published_release(repo, force_refresh = True)except Exception as exc: # pragma: no cover - network defensivelogger.debug("llama update: post-install freshness refresh failed", error = str(exc))new_marker = read_install_marker(_find_binary())new_tag = (new_marker or {}).get("release_tag") or (new_marker or {}).get("tag")-- # Pinned install must land on that exact release; a same-repo mismatch- # means the pin was ignored (Vulkan/Intel reroute to another repo is fine).- if (- pin_release_tag- and new_tag- and (new_marker or {}).get("published_repo") == repo- and new_tag != pin_release_tag- ):+ new_backend = marker_backend(new_marker)+ new_backend_request = marker_backend_request(new_marker)++ new_repo = (new_marker or {}).get("published_repo")+ if pin_release_tag and backend_request is not None:+ if new_repo != repo or new_tag != pin_release_tag:+ raise RuntimeError(+ "backend switch must preserve "+ f"{repo}@{pin_release_tag}, but installer produced "+ f"{new_repo or 'an unknown repository'}@{new_tag or 'an unknown release'}"+ )+ elif pin_release_tag and new_tag and new_repo == repo and new_tag != pin_release_tag:raise RuntimeError(f"pinned release {pin_release_tag} but installer produced {new_tag}")- logger.info("llama update: success", to_tag = new_tag)+ if backend_request is not None:+ if new_backend is None:+ raise RuntimeError(+ f"requested {backend_request} but the installed backend is unknown"+ )+ if new_backend_request != backend_request:+ raise RuntimeError(+ f"requested {backend_request} but the installer recorded "+ f"{new_backend_request or 'an unknown selection'}"+ )+ if backend_request != "auto" and new_backend != backend_request:+ raise RuntimeError(+ f"requested {backend_request} but the installer produced "+ f"{new_backend or 'an unknown backend'}"+ )++ logger.info("llama update: success", to_tag = new_tag, backend = new_backend)+ reload_hint = " Reload your model to use it." if model_was_active else ""return {"to_tag": new_tag,+ "backend": new_backend,"reload_required": model_was_active,"message": (- f"Updated llama.cpp to {new_tag}."- + (" Reload your model to use it." if model_was_active else "")+ f"llama.cpp is now running on {new_backend or backend_request}.{reload_hint}"+ if backend_request is not None+ else f"Updated llama.cpp to {new_tag}.{reload_hint}"),}except _flow.InstallerExit as exc:# Raw "installer exited 4: <log tail>" says nothing actionable in the UI.if exc.returncode == _EXIT_NO_SPACE:logger.warning("llama update: out of disk space")- raise RuntimeError(+ raise _LlamaPhaseError("Not enough disk space to install llama.cpp. Free up space or point "- "UNSLOTH_STUDIO_HOME/TMPDIR at a larger volume, then retry."+ "UNSLOTH_STUDIO_HOME/TMPDIR at a larger volume, then retry.",+ reload_required = model_was_active,+ ) from exc+ if exc.returncode == _EXIT_BACKEND_UNAVAILABLE:+ # This can race hardware or release changes after option resolution.+ failed_backend = backend_request or _env_backend_override()+ backend_label = (+ failed_backend+ if failed_backend is not None and failed_backend != "auto"+ else "requested"+ )+ logger.warning("llama update: backend unavailable", backend = failed_backend)+ raise _LlamaPhaseError(+ f"Could not install the {backend_label} llama.cpp build on this machine. "+ "The installed backend was kept.",+ reload_required = model_was_active,) from exclogger.warning("llama update: failed", error = str(exc))- raise+ raise _LlamaPhaseError(str(exc), reload_required = model_was_active) from excexcept Exception as exc:logger.warning("llama update: failed", error = str(exc))+ if isinstance(exc, _LlamaPhaseError):+ raise+ if model_was_active:+ raise _LlamaPhaseError(str(exc), reload_required = True) from excraisefinally:# Always clear maintenance state.@@ -565,11 +768,8 @@ _LLAMA_PHASE_WEIGHT = 0.7_WHISPER_PHASE_WEIGHT = 0.3-def _plan_llama_phase() -> dict:- """Decide how the llama phase of a combined update runs. Returns {"spec"}- when llama should install, else {"skip_reason", "refusal"}: skip_reason- marks the phase skipped inside a chained job, refusal is the started=False- response when the whisper phase has nothing to run either."""+def _plan_llama_phase(backend_request: Optional[str] = None) -> dict:+ """Plan the llama phase for an update or backend switch."""binary = _find_binary()# Refuse to update a --with-llama-cpp-dir local link: installing a prebuilt# here would write through the link into the user's own checkout (or fail)@@ -602,8 +802,16 @@ def _plan_llama_phase() -> dict:# Mirror the detection guard: a direct POST or a stale banner must not# start an install when the latest is not actually newer (force a fresh# check so a stale 24h cache can't wrongly block a real update either).- status = _llama_only_status(force_refresh = True)- if not status.get("update_available"):+ # A switch replaces the backend at the same release.+ status = (+ {}+ if backend_request is not None+ else _llama_only_status(+ force_refresh = True,+ allow_source_probe_while_running = True,+ )+ )+ if backend_request is None and not status.get("update_available"):return {"skip_reason": "up_to_date","refusal": {@@ -616,22 +824,35 @@ def _plan_llama_phase() -> 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"))+ # Updates let the installer preserve the marker's recorded choice.llama_backend = marker.get("llama_backend")rocm_gfx = marker.get("rocm_gfx")- # Markers written before #7188 lack llama_backend, so an explicit Vulkan- # choice is indistinguishable from the old automatic Intel route: keep the- # existing bundle rather than switching backends. Newer automatic installs- # carry the key as null and rerun detection to stay eligible for CPU recovery.- if "llama_backend" not in marker and asset and "vulkan" in str(asset).lower():- llama_backend = "vulkan"# 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).# Not on macOS, which needs the older-release walk-back a pin disables# (skipping too-new prebuilts); elsewhere an unusable latest now fails# the job loudly (retryable) instead of walking back.- pin_release_tag = None if sys.platform == "darwin" else status.get("latest_tag")+ #+ # Switch only the backend. Slim whisper bundles require this exact release.+ installed_release_tag = marker.get("release_tag") or marker.get("tag")+ wanted_tag = (+ installed_release_tag if backend_request is not None else status.get("latest_tag")+ )+ pin_release_tag = None if sys.platform == "darwin" else wanted_tag+ elif backend_request is not None:+ # Never replace a user-managed tree with a prebuilt implicitly.+ return {+ "skip_reason": "not_prebuilt",+ "refusal": {+ "started": False,+ "reason": "not_prebuilt",+ "message": (+ "This llama.cpp install was not made from an Unsloth prebuilt, so "+ "its backend cannot be switched from here."+ ),+ },+ }else:# Source build / custom path: only proceed when the same detection logic# would offer the update (prebuilt exists, install is behind, root is@@ -666,8 +887,7 @@ def _plan_llama_phase() -> 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+ # A source build records no choice, so there is nothing to preserve here.llama_backend = Nonerocm_gfx = None# No pin: source-build detection resolves via --resolve-prebuilt latest,@@ -691,9 +911,9 @@ def _plan_llama_phase() -> dict:"script": script,"pin_release_tag": pin_release_tag,"from_tag": from_tag,- "force_cpu": force_cpu,"llama_backend": llama_backend,"rocm_gfx": rocm_gfx,+ "backend_request": backend_request,}}@@ -704,97 +924,312 @@ def start_update() -> dict:behind; either phase no-ops cleanly when its component is current orunmanaged. Idempotent: a second call while one is running returns thein-flight job rather than starting another."""- # A job already in flight wins over any freshness re-check below (and skips- # its network calls). The final lock block re-checks to close the TOCTOU.- with _job_lock:- if _job["state"] == _JOB_RUNNING:- return {"started": False, "reason": "already_running", "job": dict(_job)}+ return _start_llama_job()- llama_plan = _plan_llama_phase()- llama_spec = llama_plan.get("spec")- whisper_plan = _whisper_chain_status(- force_refresh = True,- paired_llama_will_update = llama_spec is not None,- )- whisper_spec = (whisper_plan or {}).get("phase")- if llama_spec is None and whisper_spec is None:- # Nothing to run in either phase: answer with the llama refusal so the- # existing reasons (local_link / up_to_date / ...) keep their meaning.- refusal = dict(llama_plan["refusal"])++def start_backend_switch(backend: str) -> dict:+ """Install the llama.cpp bundle for ``backend`` and record it as the choice.++ Deliberately the same job, lock and phase machinery as an update: both replace+ the same tree while the same server is unloaded, so sharing them is what makes a+ switch and an update mutually exclusive instead of two writers racing over one+ install. Callers poll get_update_status() exactly as they do for an update.+ """+ normalized = normalize_backend(backend)+ if normalized is None or normalized not in REQUESTABLE_BACKENDS:with _job_lock:- refusal["job"] = dict(_job)- return refusal-- whisper_run = None- if whisper_spec is not None:- from utils import whisper_cpp_update as _whisper- whisper_run = lambda set_progress: _whisper.run_chained_phase(whisper_spec, set_progress)-- phases = [- {- "name": "llama",- "weight": _LLAMA_PHASE_WEIGHT,- "failure_message": "llama.cpp update failed.",- "skip_reason": llama_plan.get("skip_reason"),- "run": (- (- lambda set_progress: _run_llama_phase(- llama_spec["install_dir"],- llama_spec["repo"],- llama_spec["asset"],- llama_spec["script"],- llama_spec["pin_release_tag"],- set_progress,- force_cpu = llama_spec.get("force_cpu", False),- llama_backend = llama_spec.get("llama_backend"),- rocm_gfx = llama_spec.get("rocm_gfx"),- )- )- if llama_spec- else None+ job = dict(_job)+ return {+ "started": False,+ "reason": "unknown_backend",+ "message": f"{backend!r} is not a llama.cpp backend Unsloth can install.",+ "job": job,+ }+ env_backend = _env_backend_override()+ if env_backend is not None:+ with _job_lock:+ job = dict(_job)+ return {+ "started": False,+ "reason": "environment_override",+ "message": (+ f"llama.cpp is controlled by the {env_backend} environment override. "+ "Unset it and restart Studio before switching backends here."),- },- {- "name": "whisper",- "weight": _WHISPER_PHASE_WEIGHT,- "failure_message": "whisper.cpp update failed.",- # The sidecar reload is whisper-internal; it must not trip the- # job-level reload flag the chat frontend resyncs on.- "affects_job_reload": False,- "skip_reason": (whisper_plan or {}).get("skip_reason") or "unavailable",- "run": whisper_run,- },- ]- running = " + ".join(- name for name, spec in (("llama.cpp", llama_spec), ("whisper.cpp", whisper_spec)) if spec- )+ "job": job,+ }++ return _start_llama_job(backend_request = normalized)+++def _whisper_phase_plan(+ backend_request: Optional[str],+ *,+ llama_will_run: bool,+ llama_skip_reason: Optional[str] = None,+) -> dict:+ """Whisper's half of the chained job: catch up on releases for an update, or+ re-pair with the new backend for a switch.++ A switch that installs nothing leaves llama's ggml where it was, so there is+ nothing to re-pair either: a refused switch stays refused instead of turning into+ a whisper-only job.++ The exception is the state a failed re-pair leaves behind. The llama phase runs+ first and records the new backend, so a retryable whisper failure (a download that+ dropped, an install that was busy) ends with llama on the requested backend and+ dictation still hardlinked to the old runtime. Retrying that selection is then+ ``already_selected``, and refusing it strands the user: the only escape is to switch+ away and back. So allow a repair-only job for that one refusal, and only while the+ pairing is genuinely stale, which keeps an ordinary already-selected request a+ refusal rather than a no-op job reporting success."""+ if backend_request is None:+ return (+ _whisper_chain_status(force_refresh = True, paired_llama_will_update = llama_will_run) or {}+ )+ try:+ from utils import whisper_cpp_update+ if not llama_will_run:+ if llama_skip_reason != "already_selected":+ return {}+ if not whisper_cpp_update.slim_pairing_is_stale():+ return {}+ return whisper_cpp_update.repair_pairing_plan()+ except Exception as exc: # pragma: no cover - defensive+ logger.debug("llama switch: whisper repair probe failed", error = str(exc))+ return {}++def _claim_operation(backend_request: Optional[str]) -> bool:+ """Reserve the operation and publish its planning state atomically."""with _job_lock:+ if not _operation_lock.acquire(blocking = False):+ return Falseif _job["state"] == _JOB_RUNNING:- return {"started": False, "reason": "already_running", "job": dict(_job)}+ _operation_lock.release()+ return False+ _job.update(_flow.new_job())_job.update(state = _JOB_RUNNING,- message = f"Downloading and installing the latest {running} prebuilt...",- from_tag = (llama_spec or {}).get("from_tag"),- to_tag = None,- reload_required = None,- error = None,+ operation = "switch" if backend_request is not None else "update",+ requested_backend = backend_request,+ message = (+ f"Checking the {backend_request} llama.cpp build..."+ if backend_request is not None+ else "Checking for llama.cpp updates..."+ ),progress = 0.0,started_at = _utcnow(),- finished_at = None,- phases = None,)- job_snapshot = dict(_job)-- thread = threading.Thread(- target = _flow.run_chained_update,- args = (phases,),- kwargs = {"job": _job, "job_lock": _job_lock},- name = "llama-cpp-update",- daemon = True,- )- thread.start()- return {"started": True, "reason": None, "job": job_snapshot}+ return True+++def _finish_planning_refusal(reason: str, message: str) -> dict:+ """Publish a terminal result for an operation that stopped during planning."""+ succeeded = reason in {"up_to_date", "already_selected"}+ with _job_lock:+ _job.update(+ state = _JOB_SUCCESS if succeeded else _JOB_ERROR,+ message = message,+ error = None if succeeded else message,+ progress = 1.0 if succeeded else None,+ finished_at = _utcnow(),+ )+ job = dict(_job)+ return {"started": False, "reason": reason, "message": message, "job": job}+++def _run_claimed_job(phases: list[dict]) -> None:+ """Run a planned job and always release its full-operation reservation."""+ try:+ _flow.run_chained_update(phases, job = _job, job_lock = _job_lock)+ except Exception as exc: # pragma: no cover - phase failures are handled inside the runner+ logger.exception("llama update: job runner failed", error = str(exc))+ with _job_lock:+ _job.update(+ state = _JOB_ERROR,+ message = "llama.cpp install failed.",+ error = str(exc),+ finished_at = _utcnow(),+ )+ finally:+ _operation_lock.release()+++def _start_llama_job(backend_request: Optional[str] = None) -> dict:+ """Shared body of start_update() and start_backend_switch()."""+ if not _claim_operation(backend_request):+ with _job_lock:+ return {+ "started": False,+ "reason": "already_running",+ "message": _ALREADY_RUNNING_MESSAGE,+ "job": dict(_job),+ }++ handed_to_worker = False+ try:+ # The operation reservation starts before any marker read or resolver+ # call. A second update/switch cannot change the install between this+ # plan and the worker that applies it.+ llama_plan = _plan_llama_phase(backend_request)+ llama_spec = llama_plan.get("spec")+ if backend_request is not None and llama_spec is not None:+ resolved = _resolve_backends_for_host(+ llama_spec["install_dir"],+ force_refresh = True,+ published_repo = llama_spec["repo"],+ )+ if not resolved:+ return _finish_planning_refusal(+ "unresolved",+ "Could not verify the available llama.cpp backends. Try again online.",+ )+ options = _backend_options(resolved)+ option = next((o for o in options if o["backend"] == backend_request), None)+ if (+ option is None+ or not option["available"]+ or (backend_request != "auto" and option["resolved_backend"] != backend_request)+ ):+ return _finish_planning_refusal(+ "backend_unavailable",+ f"No {backend_request} llama.cpp build is available for this machine.",+ )+ marker = read_install_marker(_find_binary())+ if marker_backend_request(marker) == backend_request and _selection_applied(+ backend_request, marker_backend(marker), options+ ):+ llama_plan = {+ "skip_reason": "already_selected",+ "refusal": {+ "started": False,+ "reason": "already_selected",+ "message": f"llama.cpp is already set to {backend_request}.",+ },+ }+ llama_spec = None++ whisper_plan = _whisper_phase_plan(+ backend_request,+ llama_will_run = llama_spec is not None,+ llama_skip_reason = llama_plan.get("skip_reason"),+ )+ whisper_spec = (whisper_plan or {}).get("phase")+ if llama_spec is None and whisper_spec is None:+ # Nothing to run: answer with the llama refusal so the existing reasons+ # (local_link / up_to_date / already_selected / ...) keep their meaning.+ refusal = llama_plan["refusal"]+ return _finish_planning_refusal(refusal["reason"], refusal["message"])++ whisper_run = None+ if whisper_spec is not None:+ from utils import whisper_cpp_update as _whisper+ whisper_run = (+ (lambda set_progress: _whisper.run_repair_phase(whisper_spec, set_progress))+ if whisper_spec.get("repair")+ else (lambda set_progress: _whisper.run_chained_phase(whisper_spec, set_progress))+ )++ phases = [+ {+ "name": "llama",+ "weight": _LLAMA_PHASE_WEIGHT,+ "failure_message": (+ f"Could not switch llama.cpp to {backend_request}."+ if backend_request is not None+ else "llama.cpp update failed."+ ),+ "skip_reason": llama_plan.get("skip_reason"),+ "run": (+ (+ lambda set_progress: _run_llama_phase(+ llama_spec["install_dir"],+ llama_spec["repo"],+ llama_spec["asset"],+ llama_spec["script"],+ llama_spec["pin_release_tag"],+ set_progress,+ llama_backend = llama_spec.get("llama_backend"),+ rocm_gfx = llama_spec.get("rocm_gfx"),+ backend_request = llama_spec.get("backend_request"),+ )+ )+ if llama_spec+ else None+ ),+ },+ {+ "name": "whisper",+ "weight": _WHISPER_PHASE_WEIGHT,+ "failure_message": (+ "whisper.cpp could not be re-paired with the new backend."+ if backend_request is not None+ else "whisper.cpp update failed."+ ),+ # The sidecar reload is whisper-internal; it must not trip the+ # job-level reload flag the chat frontend resyncs on.+ "affects_job_reload": False,+ "skip_reason": (whisper_plan or {}).get("skip_reason") or "unavailable",+ "run": whisper_run,+ },+ ]+ running = " + ".join(+ name+ for name, spec in (("llama.cpp", llama_spec), ("whisper.cpp", whisper_spec))+ if spec+ )+ if backend_request is not None and llama_spec is not None:+ starting_message = f"Installing the {backend_request} llama.cpp build..."+ elif backend_request is not None:+ starting_message = "Re-pairing whisper.cpp with llama.cpp..."+ else:+ starting_message = f"Downloading and installing the latest {running} prebuilt..."++ with _job_lock:+ _job.update(+ message = starting_message,+ from_tag = (llama_spec or {}).get("from_tag"),+ )+ job_snapshot = dict(_job)++ thread = threading.Thread(+ target = _run_claimed_job,+ args = (phases,),+ name = "llama-cpp-backend-switch" if backend_request else "llama-cpp-update",+ daemon = True,+ )+ try:+ thread.start()+ except Exception as exc: # pragma: no cover - interpreter resource failure+ with _job_lock:+ _job.update(+ state = _JOB_ERROR,+ message = "Could not start the llama.cpp install worker.",+ error = str(exc),+ finished_at = _utcnow(),+ )+ failed_job = dict(_job)+ return {+ "started": False,+ "reason": "worker_start_failed",+ "message": "Could not start the llama.cpp install worker.",+ "job": failed_job,+ }+ handed_to_worker = True+ return {"started": True, "reason": None, "job": job_snapshot}+ except Exception as exc:+ with _job_lock:+ _job.update(+ state = _JOB_ERROR,+ message = "Could not plan the llama.cpp install.",+ error = str(exc),+ finished_at = _utcnow(),+ )+ raise+ finally:+ if not handed_to_worker:+ _operation_lock.release()def _reset_job_for_tests() -> None:diff --git a/studio/backend/utils/prebuilt/freshness_flow.py b/studio/backend/utils/prebuilt/freshness_flow.pyindex d441df9653f..01495aa5fbc 100644--- a/studio/backend/utils/prebuilt/freshness_flow.py+++ b/studio/backend/utils/prebuilt/freshness_flow.py@@ -37,7 +37,12 @@ def read_install_marker(log_message: str,) -> Optional[dict]:"""Walk up from binary_path to find the install marker JSON.- None = no marker (source build / custom path) or invalid JSON."""+ None = no marker (source build / custom path) or unusable JSON.++ "Unusable" includes JSON that parses but is not an object. A marker holding ``[]``+ or ``123`` reaches every caller as something without ``.get``, and each of them --+ the update planner, the backend picker, crash recovery -- then raises AttributeError+ on what is only a corrupt file. Treat it exactly like unparseable JSON: no marker."""if not binary_path:return Nonecached = cache.get(binary_path)@@ -54,6 +59,14 @@ def read_install_marker(except (OSError, json.JSONDecodeError) as exc:logger.debug(log_message, path = str(candidate), error = str(exc))marker = None+ else:+ if not isinstance(marker, dict):+ logger.debug(+ log_message,+ path = str(candidate),+ error = f"marker is {type(marker).__name__}, not an object",+ )+ marker = Nonebreakcache[binary_path] = markerreturn markerdiff --git a/studio/backend/utils/prebuilt/llama_backend.py b/studio/backend/utils/prebuilt/llama_backend.pynew file mode 100644index 00000000000..d23a0ec4912--- /dev/null+++ b/studio/backend/utils/prebuilt/llama_backend.py@@ -0,0 +1,169 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Canonical llama.cpp backend vocabulary, precedence, and marker readers."""++from __future__ import annotations++from typing import Any, Mapping, Optional++# The standalone installer imports this map, so planning and marker reads share+# one vocabulary instead of relying on mirrored definitions.+INSTALL_KIND_BACKENDS: dict[str, str] = {+ "linux-cuda": "cuda",+ "linux-arm64-cuda": "cuda",+ "windows-cuda": "cuda",+ "linux-rocm": "rocm",+ "windows-hip": "rocm",+ "windows-rocm": "rocm",+ "linux-vulkan": "vulkan",+ "windows-vulkan": "vulkan",+ "linux-cpu": "cpu",+ "linux-arm64": "cpu",+ "windows-cpu": "cpu",+ "windows-arm64": "cpu",+ "macos-arm64": "metal",+ "macos-x64": "metal",+}++# Backends a user may ask for. "metal" is absent on purpose: it is the only macOS+# build, so there is nothing to choose.+REQUESTABLE_BACKENDS = ("auto", "cpu", "cuda", "rocm", "vulkan")++# Longest-token-first, so "cuda13-older" cannot read as something else.+_ASSET_BACKEND_TOKENS = (+ ("vulkan", "vulkan"),+ ("cuda", "cuda"),+ ("rocm", "rocm"),+ ("hip", "rocm"),+ ("macos", "metal"),+ ("cpu", "cpu"),+)+++def normalize_backend(value: Any) -> Optional[str]:+ """Return a canonical backend name, or None for an unknown value."""+ if not isinstance(value, str) or not value.strip():+ return None+ backend = value.strip().lower()+ if backend == "hip":+ return "rocm"+ if backend in REQUESTABLE_BACKENDS or backend == "metal":+ return backend+ return None+++def normalize_backend_request(value: Any) -> Optional[str]:+ """Return a canonical user-selectable backend, excluding actual-only Metal."""+ backend = normalize_backend(value)+ return backend if backend in REQUESTABLE_BACKENDS else None+++def is_requestable_backend(value: Any) -> bool:+ """Whether this build knows how to install ``value``."""+ return normalize_backend_request(value) is not None+++def backend_for_install_kind(install_kind: Any) -> Optional[str]:+ if not isinstance(install_kind, str):+ return None+ return INSTALL_KIND_BACKENDS.get(install_kind.strip())+++def install_kinds_for_backend(backend: Any) -> frozenset[str]:+ """Return every install kind that satisfies ``backend``."""+ normalized = normalize_backend(backend)+ if normalized is None:+ return frozenset()+ return frozenset(+ kind for kind, kind_backend in INSTALL_KIND_BACKENDS.items() if kind_backend == normalized+ )+++def environment_backend_override(primary: Any, legacy_vulkan: Any) -> Optional[str]:+ """Resolve the public selector over the legacy Vulkan boolean.++ A recognized public value is authoritative, including ``auto``. Unknown or+ absent public values leave the legacy flag in effect for compatibility.+ """+ backend = normalize_backend_request(primary)+ if backend is not None:+ return backend+ if isinstance(legacy_vulkan, str) and legacy_vulkan.strip().lower() in {+ "1",+ "true",+ "yes",+ "on",+ }:+ return "vulkan"+ return None+++def backend_from_asset_name(asset: Any) -> Optional[str]:+ """Infer the backend for a marker that predates the backend field."""+ if not isinstance(asset, str) or not asset:+ return None+ name = asset.lower()+ for token, backend in _ASSET_BACKEND_TOKENS:+ if token in name:+ return backend+ return None+++def marker_backend(marker: Optional[Mapping[str, Any]]) -> Optional[str]:+ """What the install described by ``marker`` runs on, or None if unknowable."""+ if not marker:+ return None+ recorded = normalize_backend(marker.get("backend"))+ if recorded is not None:+ return recorded+ from_kind = backend_for_install_kind(marker.get("install_kind"))+ return from_kind if from_kind is not None else backend_from_asset_name(marker.get("asset"))+++def marker_backend_request(marker: Optional[Mapping[str, Any]]) -> str:+ """Return the recorded choice; ``auto`` means hardware detection.++ Always a name, never None, so "detect" and "chosen" can never be confused.+ A value this build does not recognize is returned verbatim: it was written by+ a newer Studio, and every reader here treats it as a choice to leave alone+ rather than as an absent one to overwrite.+ """+ if not marker:+ return "auto"+ recorded = marker.get("backend_request")+ if isinstance(recorded, str) and recorded.strip():+ return normalize_backend_request(recorded) or recorded.strip().lower()+ if bool(marker.get("force_cpu")):+ return "cpu"+ if "llama_backend" not in marker and "vulkan" in str(marker.get("asset") or "").lower():+ # Old markers cannot distinguish chosen Vulkan from automatic Vulkan.+ return "vulkan"+ legacy = marker.get("llama_backend")+ if not isinstance(legacy, str) or legacy in ("", "auto"):+ return "auto"+ return normalize_backend_request(legacy) or legacy.strip().lower()+++def marker_backend_was_chosen(marker: Optional[Mapping[str, Any]]) -> bool:+ """Whether the backend was chosen rather than detected.++ Deliberately not ``marker_backend_request(marker) != "auto"``. The only caller+ is crash recovery, asking whether it may quietly replace a Vulkan install with+ CPU placement, so it answers "chosen" for anything but a plainly automatic+ marker. The two readers part ways on the pre-#7188 Vulkan marker with no+ ``llama_backend`` key, which cannot tell a chosen Vulkan install from the+ automatic Windows-AMD/Intel route: recovery treats it as detected so a startup+ crash stays repairable, while an update keeps the bundle rather than swapping+ backends behind the user. They part ways on a corrupt value too -- recovery+ keeps its hands off it, an update re-detects.+ """+ if not marker:+ return False+ recorded = marker.get("backend_request")+ if isinstance(recorded, str) and recorded.strip():+ return recorded.strip().lower() != "auto"+ if bool(marker.get("force_cpu")):+ return True+ legacy = marker.get("llama_backend")+ return legacy is not None and legacy not in ("", "auto")diff --git a/studio/backend/utils/prebuilt/update_flow.py b/studio/backend/utils/prebuilt/update_flow.pyindex 31b92a47cf9..518843debb4 100644--- a/studio/backend/utils/prebuilt/update_flow.py+++ b/studio/backend/utils/prebuilt/update_flow.py@@ -67,6 +67,8 @@ PHASE_SKIPPED = "skipped"_IDLE_JOB_FIELDS = dict(state = JOB_IDLE,+ operation = None,+ requested_backend = None,message = "",from_tag = None,to_tag = None,@@ -137,12 +139,13 @@ def resolve_prebuilt_for_host(installer_script: Callable[[], Optional[Path]],log_message: str,extra_args: tuple[str, ...] = (),+ mode: tuple[str, ...] = ("--resolve-prebuilt", "latest"),) -> Optional[dict]:- """Run ``<installer> --resolve-prebuilt latest --output-format json`` (no- download); return the parsed payload or None. Fail-open: any error -> None so- a source build never blocks the app."""+ """Run one of the installer's read-only resolvers (``--resolve-prebuilt latest``+ by default) with ``--output-format json``; return the parsed payload or None.+ Fail-open: any error -> None so a source build never blocks the app."""now = time.time()- cache_key = tuple(extra_args)+ cache_key = (*mode, *extra_args)if not force_refresh and memo.get("key") == cache_key:if now - memo.get("at", 0.0) < RESOLVE_TTL_SECONDS:return memo.get("value")@@ -154,8 +157,7 @@ def resolve_prebuilt_for_host(cmd = [sys.executable,str(script),- "--resolve-prebuilt",- "latest",+ *mode,"--output-format","json",*extra_args,@@ -471,6 +473,8 @@ def run_chained_update(phases: list[dict], *, job: dict, job_lock: threading.Locresult = phase["run"](set_progress) or {}except Exception as exc:failure = phase.get("failure_message") or f"{name} update failed."+ if phase.get("affects_job_reload", True):+ reload_required = reload_required or bool(getattr(exc, "reload_required", False))with job_lock:job["phases"][name].update(state = PHASE_ERROR, error = str(exc))for later in phases[index + 1 :]:@@ -485,7 +489,7 @@ def run_chained_update(phases: list[dict], *, job: dict, job_lock: threading.Locerror = str(exc),finished_at = utcnow(),)- if done_messages:+ if done_messages or reload_required:job["reload_required"] = reload_requiredreturnset_progress(1.0)diff --git a/studio/backend/utils/whisper_cpp_update.py b/studio/backend/utils/whisper_cpp_update.pyindex 45a0faf6741..da08fb68236 100644--- a/studio/backend/utils/whisper_cpp_update.py+++ b/studio/backend/utils/whisper_cpp_update.py@@ -401,6 +401,118 @@ def _install_latest_while_blocked(}+def _installed_llama_bundle() -> tuple[Optional[str], Optional[str]]:+ """Backend and asset name of the managed llama.cpp runtime a slim install rides."""+ try:+ from utils.llama_cpp_freshness import read_install_marker as read_llama_marker+ from utils.llama_cpp_update import _find_binary as find_llama_binary+ from utils.prebuilt.llama_backend import marker_backend++ marker = read_llama_marker(find_llama_binary()) or {}+ return marker_backend(marker), marker.get("asset")+ except Exception as exc: # pragma: no cover - defensive+ logger.debug("whisper repair: llama pairing lookup failed", error = str(exc))+ return None, None+++def slim_pairing_is_stale() -> bool:+ """Whether a slim install still hardlinks the runtime of a different backend.++ The same comparison ``run_repair_phase`` makes before it does any work, exposed+ so the llama planner can tell a re-pair that is still owed from one already done.+ A repair that failed retryably leaves exactly this state: llama has moved, whisper+ has not."""+ backend, _ = _installed_llama_bundle()+ if backend is None:+ return False+ marker = read_install_marker(_find_binary())+ if not marker or marker.get("install_kind") != "slim":+ return False+ return marker.get("backend") != backend+++def repair_pairing_plan() -> dict:+ """Whisper's half of a llama.cpp backend switch.++ A slim install has no ggml of its own -- it hardlinks llama's -- so replacing+ the llama bundle leaves dictation on the very backend the switch was meant to+ leave behind. Only whether such an install exists is decided here: which+ backend to install is whatever the llama phase actually lands on, which the+ runner reads from the marker once that phase has finished."""+ plan: dict = {"update_available": False, "skip_reason": None, "phase": None}+ binary = _find_binary()+ if _active_install_is_local_link(binary):+ plan["skip_reason"] = "local_link"+ return plan+ marker = read_install_marker(binary)+ if marker is None:+ plan["skip_reason"] = "source_build" if binary else "not_installed"+ return plan+ if marker.get("install_kind") != "slim":+ # Carries its own ggml, so llama's backend is not its backend.+ plan["skip_reason"] = "self_contained"+ return plan+ script = _installer_script()+ if script is None:+ plan["skip_reason"] = "installer_missing"+ return plan+ install_dir = _install_dir_for(binary)+ if install_dir is None:+ plan["skip_reason"] = "no_install_dir"+ return plan+ plan["update_available"] = True+ plan["phase"] = {+ "install_dir": install_dir,+ "repo": marker.get("published_repo") or DEFAULT_PUBLISHED_REPO,+ "script": script,+ # Unpinned: the installer resolves the whisper release that pairs with+ # whichever llama.cpp release is installed when this phase runs.+ "pin_release_tag": None,+ "repair": True,+ }+ return plan+++def run_repair_phase(phase: dict, set_progress) -> dict:+ """Reinstall the slim whisper bundle for the backend llama.cpp now runs."""+ backend, llama_asset = _installed_llama_bundle()+ if backend is None:+ logger.info("whisper repair: skipped, llama backend unknown")+ return {}+ if (read_install_marker(_find_binary()) or {}).get("backend") == backend:+ # Detection can land back on the backend whisper is already built against,+ # and the switch preserves the release, so the hardlinks still point at the+ # same build. Nothing to repair, and nothing to claim was repaired.+ return {}+ try:+ result = _install_latest(+ phase["install_dir"],+ phase["repo"],+ # The llama asset names the AMD arch the new bundle was built for.+ llama_asset,+ backend,+ phase["script"],+ set_progress,+ pin_release_tag = phase.get("pin_release_tag"),+ )+ except _flow.InstallerExit as exc:+ if exc.returncode != 2:+ raise+ # 2 is "no compatible release": this llama.cpp release publishes no+ # whisper bundle for the new backend. The old hardlinked runtime still+ # works, so dictation degrades rather than failing the switch.+ logger.info("whisper repair: skipped", backend = backend, detail = str(exc)[-500:])+ return {+ "message": (+ "Dictation still uses the previous backend; no whisper.cpp build is "+ f"published for this llama.cpp release on {backend} yet."+ ),+ }+ # Describe the backend change instead of an incidental version change.+ result["message"] = f"Re-paired whisper.cpp with the {backend} backend."+ return result++def chained_phase_plan(*, force_refresh: bool = False, paired_llama_will_update: bool = False) -> dict:diff --git a/studio/frontend/src/features/settings/api/llama-backend-payload.ts b/studio/frontend/src/features/settings/api/llama-backend-payload.tsnew file mode 100644index 00000000000..d840222f4d2--- /dev/null+++ b/studio/frontend/src/features/settings/api/llama-backend-payload.ts@@ -0,0 +1,183 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++/** Import-free payload types and parsers for the llama.cpp backend picker. */++/** Backends a user can ask for. "auto" means hardware detection. */+export const LLAMA_BACKENDS = [+ "auto",+ "cpu",+ "cuda",+ "rocm",+ "vulkan",+] as const;+export type LlamaBackend = (typeof LLAMA_BACKENDS)[number];++/** Backends an install can report running on. Metal is macOS-only and not selectable. */+export type LlamaEffectiveBackend = Exclude<LlamaBackend, "auto"> | "metal";++export function isLlamaBackend(value: unknown): value is LlamaBackend {+ return (+ typeof value === "string" &&+ (LLAMA_BACKENDS as readonly string[]).includes(value)+ );+}++export interface LlamaBackendOption {+ backend: LlamaBackend;+ available: boolean;+ /** For "auto", the backend detection picks right now, so it can be labelled. */+ resolvedBackend: LlamaEffectiveBackend | null;+ releaseTag: string | null;+ downloadSizeBytes: number | null;+}++export interface LlamaBackendJob {+ state: "idle" | "running" | "success" | "error";+ operation: "update" | "switch" | null;+ requestedBackend: LlamaBackend | null;+ message: string;+ error: string | null;+ progress: number | null;+ reloadRequired: boolean | null;+ startedAt: string | null;+ finishedAt: string | null;+}++export interface LlamaBackendStatus {+ /** Whether this install's backend can be switched from here at all. */+ supported: boolean;+ /** Why switching is unavailable. */+ reason: string | null;+ /** Backend pinned by the environment, which overrides anything chosen here. */+ envBackend: LlamaBackend | null;+ /** What the install runs on now. */+ backend: LlamaEffectiveBackend | null;+ /** The recorded choice; null when this client does not recognize it. */+ backendRequest: LlamaBackend | null;+ /** Whether that choice resolves to the installed bundle and paired sidecars. */+ selectionApplied: boolean;+ installedTag: string | null;+ options: LlamaBackendOption[];+ job: LlamaBackendJob;+}++export interface LlamaBackendSwitchStarted {+ started: boolean;+ /** already_running | already_selected | not_prebuilt | unknown_backend | ... */+ reason: string | null;+ message: string | null;+ job: LlamaBackendJob;+}++type ApiObject = Record<string, unknown>;++function asString(value: unknown): string | null {+ return typeof value === "string" && value ? value : null;+}++export function parseLlamaBackendJob(value: unknown): LlamaBackendJob {+ const job = (value ?? {}) as ApiObject;+ const state = job.state;+ return {+ state:+ state === "running" || state === "success" || state === "error"+ ? state+ : "idle",+ operation:+ job.operation === "update" || job.operation === "switch"+ ? job.operation+ : null,+ requestedBackend: isLlamaBackend(job.requested_backend)+ ? job.requested_backend+ : null,+ message: typeof job.message === "string" ? job.message : "",+ error: asString(job.error),+ progress: typeof job.progress === "number" ? job.progress : null,+ reloadRequired:+ typeof job.reload_required === "boolean" ? job.reload_required : null,+ startedAt: asString(job.started_at),+ finishedAt: asString(job.finished_at),+ };+}++function parseOption(value: unknown): LlamaBackendOption | null {+ const option = (value ?? {}) as ApiObject;+ if (!isLlamaBackend(option.backend)) {+ // Older clients cannot label or submit unknown backends.+ return null;+ }+ return {+ backend: option.backend,+ available: option.available === true,+ resolvedBackend:+ (asString(option.resolved_backend) as LlamaEffectiveBackend | null) ??+ null,+ releaseTag: asString(option.release_tag),+ downloadSizeBytes:+ typeof option.download_size_bytes === "number"+ ? option.download_size_bytes+ : null,+ };+}++export function parseLlamaBackendStatus(value: unknown): LlamaBackendStatus {+ const payload = (value ?? {}) as ApiObject;+ const options = Array.isArray(payload.options) ? payload.options : [];+ return {+ supported: payload.supported === true,+ reason: asString(payload.reason),+ envBackend: isLlamaBackend(payload.env_backend)+ ? payload.env_backend+ : null,+ backend:+ (asString(payload.backend) as LlamaEffectiveBackend | null) ?? null,+ backendRequest: isLlamaBackend(payload.backend_request)+ ? payload.backend_request+ : null,+ selectionApplied: payload.selection_applied !== false,+ installedTag: asString(payload.installed_tag),+ options: options+ .map(parseOption)+ .filter((option): option is LlamaBackendOption => option !== null),+ job: parseLlamaBackendJob(payload.job),+ };+}++export function llamaBackendSelectionNeedsApply(+ status: LlamaBackendStatus | null,+ selected: LlamaBackend | null,+): boolean {+ // A null backendRequest is a choice written by a newer Studio. Untouched it is+ // not dirty, but picking a backend over it is an explicit replacement.+ const requested = selected ?? status?.backendRequest ?? null;+ if (!status || requested === null) {+ return false;+ }+ return requested !== status.backendRequest || !status.selectionApplied;+}++export function parseLlamaBackendSwitchStarted(+ value: unknown,+): LlamaBackendSwitchStarted {+ const payload = (value ?? {}) as ApiObject;+ return {+ started: payload.started === true,+ reason: asString(payload.reason),+ message: asString(payload.message),+ job: parseLlamaBackendJob(payload.job),+ };+}++/** Show installable options and preserve the selected value if it became unavailable. */+export function visibleLlamaBackendOptions(+ status: LlamaBackendStatus | null,+ selected: LlamaBackend | null,+): LlamaBackendOption[] {+ if (!status) {+ return [];+ }+ return status.options.filter(+ (option) => option.available || option.backend === selected,+ );+}diff --git a/studio/frontend/src/features/settings/api/llama-backend.ts b/studio/frontend/src/features/settings/api/llama-backend.tsnew file mode 100644index 00000000000..532965aa826--- /dev/null+++ b/studio/frontend/src/features/settings/api/llama-backend.ts@@ -0,0 +1,62 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import { authFetch } from "@/features/auth";+import { readFastApiError } from "@/lib/format-fastapi-error";+import {+ type LlamaBackend,+ type LlamaBackendStatus,+ type LlamaBackendSwitchStarted,+ parseLlamaBackendStatus,+ parseLlamaBackendSwitchStarted,+} from "./llama-backend-payload";++export {+ LLAMA_BACKENDS,+ isLlamaBackend,+ llamaBackendSelectionNeedsApply,+ visibleLlamaBackendOptions,+} from "./llama-backend-payload";+export type {+ LlamaBackend,+ LlamaBackendJob,+ LlamaBackendOption,+ LlamaBackendStatus,+ LlamaBackendSwitchStarted,+ LlamaEffectiveBackend,+} from "./llama-backend-payload";++/**+ * Always refetches: the payload describes the install on disk and an in-flight+ * job, both of which change under it.+ */+export async function loadLlamaBackendStatus(+ forceRefresh = false,+): Promise<LlamaBackendStatus> {+ const res = await authFetch(+ `/api/llama/backend${forceRefresh ? "?force_refresh=true" : ""}`,+ );+ if (!res.ok) {+ throw new Error(+ await readFastApiError(res, "Failed to load llama.cpp backend status"),+ );+ }+ return parseLlamaBackendStatus(await res.json());+}++/** Start the switch. Progress arrives through loadLlamaBackendStatus().job. */+export async function switchLlamaBackend(+ backend: LlamaBackend,+): Promise<LlamaBackendSwitchStarted> {+ const res = await authFetch("/api/llama/backend", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ backend }),+ });+ if (!res.ok) {+ throw new Error(+ await readFastApiError(res, "Failed to switch the llama.cpp backend"),+ );+ }+ return parseLlamaBackendSwitchStarted(await res.json());+}diff --git a/studio/frontend/src/features/settings/components/llama-backend-section.tsx b/studio/frontend/src/features/settings/components/llama-backend-section.tsxnew file mode 100644index 00000000000..486792f5f52--- /dev/null+++ b/studio/frontend/src/features/settings/components/llama-backend-section.tsx@@ -0,0 +1,176 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import { Button } from "@/components/ui/button";+import { Progress } from "@/components/ui/progress";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@/components/ui/select";+import { formatBytes } from "@/features/hub";+import { type TranslationKey, useT } from "@/i18n";+import {+ type LlamaBackendOption,+ isLlamaBackend,+ llamaBackendSelectionNeedsApply,+ visibleLlamaBackendOptions,+} from "../api/llama-backend";+import { useLlamaBackendSwitch } from "../hooks/use-llama-backend-switch";+import { backendDisplayName } from "../lib/llama-backend-labels";+import { SettingsRow } from "./settings-row";+import { SettingsSection } from "./settings-section";++const UNSUPPORTED_REASONS: Record<string, TranslationKey> = {+ not_installed: "settings.resources.llamaBackend.unsupported.notInstalled",+ local_link: "settings.resources.llamaBackend.unsupported.localLink",+ source_build: "settings.resources.llamaBackend.unsupported.sourceBuild",+ no_install_dir: "settings.resources.llamaBackend.unsupported.notInstalled",+ unresolved: "settings.resources.llamaBackend.unsupported.unresolved",+};++export function LlamaBackendSection() {+ const t = useT();+ const { status, selected, setSelected, running, apply, loadError } =+ useLlamaBackendSwitch();++ const optionLabel = (option: LlamaBackendOption) => {+ if (option.backend !== "auto") {+ return backendDisplayName(option.backend, t);+ }+ // "Automatic" alone hides the decision; naming what it picks is the+ // difference between an informed choice and a shot in the dark.+ return option.resolvedBackend+ ? t("settings.resources.llamaBackend.autoWith", {+ backend: backendDisplayName(option.resolvedBackend, t),+ })+ : backendDisplayName("auto", t);+ };++ const job = status?.job;+ const envLocked = status?.envBackend != null;+ // Null means the marker holds a choice a newer Studio wrote. Show it as+ // unknown rather than as Automatic, and let it be replaced deliberately.+ const unknownRecorded = status?.backendRequest === null;+ const value = selected ?? status?.backendRequest ?? "unknown";+ const options = visibleLlamaBackendOptions(+ status,+ selected ?? status?.backendRequest ?? null,+ );+ const pending = options.find((option) => option.backend === value);+ const dirty = !running && llamaBackendSelectionNeedsApply(status, selected);+ const unsupportedKey =+ status && !status.supported && !running+ ? (UNSUPPORTED_REASONS[status.reason ?? ""] ??+ "settings.resources.llamaBackend.unsupported.unresolved")+ : null;++ return (+ <SettingsSection title={t("settings.resources.llamaBackend.title")}>+ <SettingsRow+ label={t("settings.resources.llamaBackend.label")}+ description={+ status?.backend+ ? t("settings.resources.llamaBackend.runningOn", {+ backend: backendDisplayName(status.backend, t),+ })+ : t("settings.resources.llamaBackend.description")+ }+ hint={t("settings.resources.llamaBackend.hint")}+ >+ <div className="flex items-center gap-2">+ <Select+ value={value}+ disabled={!status?.supported || envLocked || running}+ onValueChange={(next) => {+ if (isLlamaBackend(next)) {+ setSelected(next);+ }+ }}+ >+ <SelectTrigger+ aria-label={t("settings.resources.llamaBackend.label")}+ className="w-52"+ size="sm"+ data-testid="llama-backend-select"+ >+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {unknownRecorded ? (+ <SelectItem value="unknown">+ {t("settings.resources.environment.unknown")}+ </SelectItem>+ ) : null}+ {options.map((option) => (+ <SelectItem key={option.backend} value={option.backend}>+ {optionLabel(option)}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ <Button+ size="sm"+ onClick={apply}+ // The same hard blockers as the Select above, not just dirtiness. An+ // environment pin with an automatic choice that has since drifted leaves+ // selectionApplied false, so the row is dirty while the Select is disabled:+ // Apply would then be the only live control, and the server rightly refuses+ // it with environment_override. Do not offer an action that cannot succeed.+ disabled={!dirty || !status?.supported || envLocked}+ data-testid="llama-backend-apply"+ >+ {running+ ? t("settings.resources.llamaBackend.applying")+ : t("settings.resources.llamaBackend.apply")}+ </Button>+ </div>+ </SettingsRow>++ {running ? (+ <div className="pb-3" data-testid="llama-backend-progress">+ <Progress+ value={Math.round((job?.progress ?? 0) * 100)}+ aria-label={t("settings.resources.llamaBackend.applying")}+ className="h-1.5 w-full rounded-full bg-muted"+ />+ <p className="mt-2 text-xs text-muted-foreground">+ {job?.message || t("settings.resources.llamaBackend.applying")}+ </p>+ </div>+ ) : null}++ {dirty ? (+ // The two things a switch costs, said before it is paid: a download, and+ // the loaded model going away with the server it runs in.+ <p className="pb-3 text-xs text-muted-foreground">+ {pending?.downloadSizeBytes+ ? t("settings.resources.llamaBackend.applyHintWithSize", {+ size: formatBytes(pending.downloadSizeBytes),+ })+ : t("settings.resources.llamaBackend.applyHint")}+ </p>+ ) : null}++ {envLocked ? (+ <p className="pb-3 text-xs text-amber-600 dark:text-amber-400">+ {t("settings.resources.llamaBackend.envLocked", {+ backend: backendDisplayName(status?.envBackend, t),+ })}+ </p>+ ) : null}++ {unsupportedKey ? (+ <p className="pb-3 text-xs text-muted-foreground">+ {t(unsupportedKey)}+ </p>+ ) : null}++ {loadError ? (+ <p className="pb-3 text-xs text-destructive">{loadError}</p>+ ) : null}+ </SettingsSection>+ );+}diff --git a/studio/frontend/src/features/settings/hooks/use-llama-backend-switch.ts b/studio/frontend/src/features/settings/hooks/use-llama-backend-switch.tsnew file mode 100644index 00000000000..16a63446297--- /dev/null+++ b/studio/frontend/src/features/settings/hooks/use-llama-backend-switch.ts@@ -0,0 +1,217 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import { useT } from "@/i18n";+import {+ signalLlamaJobStarted,+ subscribeToLlamaJobStarted,+} from "@/lib/llama-job-events";+import {+ type OwnedLlamaSwitchOutcome,+ ownedLlamaSwitchOutcome,+} from "@/lib/llama-job-lifecycle";+import { toast } from "@/lib/toast";+import { useCallback, useEffect, useRef, useState } from "react";+import {+ type LlamaBackend,+ type LlamaBackendStatus,+ loadLlamaBackendStatus,+ switchLlamaBackend,+} from "../api/llama-backend";+import { backendDisplayName } from "../lib/llama-backend-labels";++// Fast enough to track the installer's progress milestones without hammering.+const JOB_POLL_MS = 700;++/** Manage backend selection and the shared llama.cpp install job. */+export function useLlamaBackendSwitch() {+ const t = useT();+ const [status, setStatus] = useState<LlamaBackendStatus | null>(null);+ const [loadError, setLoadError] = useState<string | null>(null);+ const [selected, setSelected] = useState<LlamaBackend | null>(null);+ const [applying, setApplying] = useState(false);+ const pollTimer = useRef<ReturnType<typeof setInterval> | null>(null);+ const mounted = useRef(false);+ // Prevent overlapping resolver polls.+ const polling = useRef(false);+ // Updates share this job, so completion belongs to this surface only when+ // it has the identity of the switch accepted by apply().+ const ownedJob = useRef<{ startedAt: string | null } | null>(null);++ const refresh = useCallback(async (forceRefresh = false) => {+ try {+ const next = await loadLlamaBackendStatus(forceRefresh);+ if (mounted.current) {+ setStatus(next);+ setLoadError(null);+ }+ return next;+ } catch (error) {+ if (mounted.current) {+ setLoadError(error instanceof Error ? error.message : String(error));+ }+ return null;+ }+ }, []);++ useEffect(() => {+ mounted.current = true;+ // Opening the picker is an explicit host-capability recheck. If an install+ // is running, the poll repeats it once the backend can resolve options.+ // eslint-disable-next-line react-hooks/set-state-in-effect+ void refresh(true);+ return () => {+ mounted.current = false;+ if (pollTimer.current) {+ clearInterval(pollTimer.current);+ pollTimer.current = null;+ }+ };+ }, [refresh]);++ const finish = useCallback(+ (next: LlamaBackendStatus, outcome: OwnedLlamaSwitchOutcome | null) => {+ if (!mounted.current) {+ return;+ }+ setApplying(false);+ // The install marker is authoritative after completion.+ setSelected(next.backendRequest);+ if (!outcome) {+ return;+ }+ ownedJob.current = null;+ if (outcome === "error") {+ toast.error(t("settings.resources.llamaBackend.switchFailed"), {+ description: next.job.error ?? undefined,+ });+ return;+ }+ if (outcome !== "success") {+ toast.error(t("settings.resources.llamaBackend.switchFailed"), {+ description: t("settings.resources.llamaBackend.switchInterrupted"),+ });+ return;+ }+ // The job detail includes reload or dictation repair information.+ toast.success(+ t("settings.resources.llamaBackend.switchedTo", {+ backend: backendDisplayName(next.backend, t),+ }),+ { description: next.job.message || undefined },+ );+ },+ [t],+ );++ const startPolling = useCallback(() => {+ if (!mounted.current) {+ return;+ }+ if (pollTimer.current) {+ clearInterval(pollTimer.current);+ }+ pollTimer.current = setInterval(async () => {+ if (polling.current) {+ return;+ }+ polling.current = true;+ try {+ // The backend skips option resolution while a job is running, so this+ // becomes one forced host probe on the first terminal status.+ const next = await refresh(true);+ if (!next) {+ return;+ }+ const owned = ownedJob.current;+ const outcome = owned+ ? ownedLlamaSwitchOutcome(next.job, owned.startedAt)+ : null;+ if (next.job.state === "running" && (!owned || outcome === "running")) {+ return;+ }+ if (pollTimer.current) {+ clearInterval(pollTimer.current);+ pollTimer.current = null;+ }+ finish(next, outcome);+ } finally {+ polling.current = false;+ }+ }, JOB_POLL_MS);+ }, [refresh, finish]);++ // Follow jobs started by another surface or browser tab.+ useEffect(+ () =>+ subscribeToLlamaJobStarted(() => {+ void refresh().then((next) => {+ if (next?.job.state === "running") {+ startPolling();+ }+ });+ }),+ [refresh, startPolling],+ );++ const apply = useCallback(() => {+ const requested = selected ?? status?.backendRequest;+ if (!requested) {+ return;+ }+ setApplying(true);+ void (async () => {+ try {+ const started = await switchLlamaBackend(requested);+ if (!started.started) {+ if (!mounted.current) {+ return;+ }+ setApplying(false);+ toast.error(+ started.message ??+ t("settings.resources.llamaBackend.switchFailed"),+ );+ await refresh();+ return;+ }+ // App-wide recovery continues if Settings closes.+ signalLlamaJobStarted(started.job.startedAt);+ if (!mounted.current) {+ return;+ }+ ownedJob.current = { startedAt: started.job.startedAt };+ setStatus((current) =>+ current ? { ...current, job: started.job } : current,+ );+ startPolling();+ } catch (error) {+ if (!mounted.current) {+ return;+ }+ setApplying(false);+ ownedJob.current = null;+ toast.error(error instanceof Error ? error.message : String(error));+ }+ })();+ }, [selected, status?.backendRequest, refresh, startPolling, t]);++ // The component derives the untouched value from status.backendRequest.+ const running = applying || status?.job.state === "running";++ // Follow any shared job already present in status.+ useEffect(() => {+ if (status?.job.state === "running" && !pollTimer.current) {+ startPolling();+ }+ }, [status, startPolling]);++ return {+ status,+ selected,+ setSelected,+ running: Boolean(running),+ apply,+ loadError,+ };+}diff --git a/studio/frontend/src/features/settings/lib/llama-backend-labels.ts b/studio/frontend/src/features/settings/lib/llama-backend-labels.tsnew file mode 100644index 00000000000..964dcb11f2b--- /dev/null+++ b/studio/frontend/src/features/settings/lib/llama-backend-labels.ts@@ -0,0 +1,26 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import type { TranslationKey } from "@/i18n";++/** Backend labels shared by the picker and notifications. */+export const LLAMA_BACKEND_LABELS: Record<string, TranslationKey> = {+ auto: "settings.resources.llamaBackend.backends.auto",+ cpu: "settings.resources.llamaBackend.backends.cpu",+ cuda: "settings.resources.llamaBackend.backends.cuda",+ rocm: "settings.resources.llamaBackend.backends.rocm",+ vulkan: "settings.resources.llamaBackend.backends.vulkan",+ metal: "settings.resources.llamaBackend.backends.metal",+};++/** Use the backend identifier when this client has no localized label. */+export function backendDisplayName(+ backend: string | null | undefined,+ t: (key: TranslationKey) => string,+): string {+ if (!backend) {+ return t(LLAMA_BACKEND_LABELS.auto);+ }+ const key = LLAMA_BACKEND_LABELS[backend];+ return key ? t(key) : backend;+}diff --git a/studio/frontend/src/features/settings/tabs/resources-tab.tsx b/studio/frontend/src/features/settings/tabs/resources-tab.tsxindex 703266bc626..26bc782f828 100644--- a/studio/frontend/src/features/settings/tabs/resources-tab.tsx+++ b/studio/frontend/src/features/settings/tabs/resources-tab.tsx@@ -30,6 +30,7 @@ import {loadHuggingFaceCacheSettings,updateHuggingFaceCacheSettings,} from "../api/hugging-face-cache";+import { LlamaBackendSection } from "../components/llama-backend-section";import { ModelMemorySection } from "../components/model-memory-section";import { SettingsRow } from "../components/settings-row";import { SettingsSection } from "../components/settings-section";@@ -572,6 +573,10 @@ export function ResourcesTab() {)}</SettingsSection>+ {/* Below the GPU section it describes, above the memory settings that+ apply to whichever backend is selected. */}+ <LlamaBackendSection />+<ModelMemorySection /><SettingsSection title={t("settings.resources.storage.title")}>diff --git a/studio/frontend/src/hooks/use-llama-update-check.ts b/studio/frontend/src/hooks/use-llama-update-check.tsindex 999700ae1f8..598cbafe8aa 100644--- a/studio/frontend/src/hooks/use-llama-update-check.ts+++ b/studio/frontend/src/hooks/use-llama-update-check.ts@@ -3,6 +3,14 @@import { authFetch, getAuthToken } from "@/features/auth";import { refreshHardwareInfo } from "@/hooks/use-hardware-info";+import {+ signalRunningLlamaJob,+ subscribeToLlamaJobStarted,+} from "@/lib/llama-job-events";+import {+ llamaUpdateAdoptsRunningJob,+ llamaUpdatePresentation,+} from "@/lib/llama-job-lifecycle";import { useCallback, useEffect, useRef, useState } from "react";// Initial check plus hourly reminders until dismissed or applied.@@ -15,6 +23,8 @@ const JOB_POLL_INTERVAL_MS = 500;export interface LlamaUpdateJob {state: "idle" | "running" | "success" | "error";+ operation: "update" | "switch" | null;+ requested_backend: "auto" | "cpu" | "cuda" | "rocm" | "vulkan" | null;message: string;from_tag: string | null;to_tag: string | null;@@ -22,6 +32,8 @@ export interface LlamaUpdateJob {error: string | null;// Download fraction while running, 1 on success.progress: number | null;+ // Identifies the accepted job when notifying other surfaces and tabs.+ started_at: string | null;// Set once the job leaves "running"; identifies a completed job so a// repeated fetch of the same success can be told apart from the next one.finished_at: string | null;@@ -42,6 +54,18 @@ function parseJob(value: unknown): LlamaUpdateJob {const job = (value ?? {}) as Record<string, unknown>;return {state: (job.state as LlamaUpdateJob["state"]) ?? "idle",+ operation:+ job.operation === "update" || job.operation === "switch"+ ? job.operation+ : null,+ requested_backend:+ job.requested_backend === "auto" ||+ job.requested_backend === "cpu" ||+ job.requested_backend === "cuda" ||+ job.requested_backend === "rocm" ||+ job.requested_backend === "vulkan"+ ? job.requested_backend+ : null,message: typeof job.message === "string" ? job.message : "",from_tag: typeof job.from_tag === "string" ? job.from_tag : null,to_tag: typeof job.to_tag === "string" ? job.to_tag : null,@@ -49,6 +73,7 @@ function parseJob(value: unknown): LlamaUpdateJob {typeof job.reload_required === "boolean" ? job.reload_required : null,error: typeof job.error === "string" ? job.error : null,progress: typeof job.progress === "number" ? job.progress : null,+ started_at: typeof job.started_at === "string" ? job.started_at : null,finished_at: typeof job.finished_at === "string" ? job.finished_at : null,};}@@ -71,9 +96,7 @@ function parseStatus(value: unknown): LlamaUpdateStatus | null {update_available: s.update_available === true,component,installed_tag:- typeof details.installed_tag === "string"- ? details.installed_tag- : null,+ typeof details.installed_tag === "string" ? details.installed_tag : null,latest_tag:typeof details.latest_tag === "string" ? details.latest_tag : null,update_size_bytes:@@ -180,7 +203,9 @@ export function useLlamaUpdateCheck({// (the job came back embedded in a "not started" response) so none of them// can drop or double-fire the notification.const notifyReloadIfNeeded = useCallback(- (job: Pick<LlamaUpdateJob, "state" | "reload_required" | "finished_at">) => {+ (+ job: Pick<LlamaUpdateJob, "state" | "reload_required" | "finished_at">,+ ) => {// "error" is included for partial chained updates: the llama phase can// land (and unload the server) before a later phase fails, and the// backend keeps reload_required set in exactly that case. Without the@@ -206,11 +231,12 @@ export function useLlamaUpdateCheck({const s = await fetchStatus();if (!s) return;setStatus(s);- if (s.job.state === "running") return;+ const presentation = llamaUpdatePresentation(s.update_available, s.job);+ setApplying(presentation.applying);+ setVisible(presentation.visible);+ if (presentation.running) return;clearPollTimer();- setApplying(false);if (s.job.state === "success") {- setVisible(false);void refreshHardwareInfo();// The update unloads the running model server-side, so the chat// runtime still points at a model that now 400s on send. Let the@@ -240,10 +266,13 @@ export function useLlamaUpdateCheck({(next: LlamaUpdateStatus | null) => {if (!next) return;setStatus(next);- if (next.job.state === "running") {- // Another tab is applying; show progress here too.- setApplying(true);- setVisible(true);+ const presentation = llamaUpdatePresentation(+ next.update_available,+ next.job,+ );+ setApplying(presentation.applying);+ setVisible(presentation.visible);+ if (presentation.running) {if (!pollTimer.current) startJobPoll();return;}@@ -252,9 +281,6 @@ export function useLlamaUpdateCheck({// hourly and misses both the running and just-finished moments) still// needs to resync here, not just from the poll path above.notifyReloadIfNeeded(next.job);- if (next.update_available) {- setVisible(true);- }},[startJobPoll, notifyReloadIfNeeded],);@@ -262,8 +288,6 @@ export function useLlamaUpdateCheck({useEffect(() => {if (!enabled) {// Re-enabling will rediscover any still-running job.- setVisible(false);- setApplying(false);return;}let canceled = false;@@ -312,6 +336,13 @@ export function useLlamaUpdateCheck({return () => window.removeEventListener("storage", onStorage);}, [enabled, surfaceIfAvailable]);+ useEffect(() => {+ if (!enabled) return;+ return subscribeToLlamaJobStarted(() => {+ fetchStatus().then(surfaceIfAvailable);+ });+ }, [enabled, surfaceIfAvailable]);+const dismiss = useCallback(() => {setVisible(false);}, []);@@ -351,17 +382,26 @@ export function useLlamaUpdateCheck({return { ok: false, error: String(e) };}- // Non-started jobs stay idle; already_running is tracked below.+ const actionJob = parseJob(action?.job);+ // The response job is authoritative. Signal both a newly accepted update+ // and an already-running job this tab discovered through the POST, so every+ // open Settings surface disables and follows the same install immediately.+ signalRunningLlamaJob(actionJob);++ // Non-started jobs stay idle; an already-running update is tracked below.+ // A backend switch is not: it shares this job but installs no new release,+ // so following it here would toast an update that never happened. The+ // shared background listener still follows the switch itself.if (action &&action.started === false &&- action.reason !== "already_running"+ !llamaUpdateAdoptsRunningJob(action.reason, actionJob)) {// A stale banner's click can land after another tab already applied the// update (e.g. "up_to_date"): the response still carries that tab's// completed job, so process reload_required here too, not just from the// poll path -- otherwise this rejection silently drops it.- notifyReloadIfNeeded(parseJob(action.job));+ notifyReloadIfNeeded(actionJob);setApplying(false);return {ok: false,@@ -377,7 +417,7 @@ export function useLlamaUpdateCheck({return {status: enabled ? status : null,visible: enabled && visible,- applying,+ applying: enabled && applying,apply,dismiss,snooze,diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.tsindex 89fd382e3b2..155005d17c8 100644--- a/studio/frontend/src/i18n/locales/ar.ts+++ b/studio/frontend/src/i18n/locales/ar.ts@@ -716,6 +716,39 @@ export const ar = {free: "{value} متاح",total: "{value} إجمالي",},+ llamaBackend: {+ title: "محرك استدلال GGUF",+ label: "خلفية الحوسبة",+ description: "الخلفية التي يستخدمها llama.cpp لتشغيل نماذج GGUF.",+ runningOn: "يعمل llama.cpp حاليًا على {backend}.",+ hint: "يثبّت إصدار llama.cpp الخاص بهذه الخلفية ويحافظ عليه عبر التحديثات. مفيد عندما ينهار الاختيار التلقائي أو لا يدعمه تعريف كرت الشاشة لديك. تظهر فقط الخلفيات التي يتوفر لها إصدار لهذا الجهاز، والتدريب لا يتأثر.",+ autoWith: "تلقائي ({backend})",+ apply: "تطبيق",+ applying: "جارٍ التثبيت...",+ applyHint: "ينزّل الإصدار الجديد ويعيد تشغيل llama.cpp. سيتم تفريغ النموذج المحمّل.",+ applyHintWithSize: "ينزّل {size} ويعيد تشغيل llama.cpp. سيتم تفريغ النموذج المحمّل.",+ switchedTo: "يعمل llama.cpp الآن على {backend}.",+ switchFailed: "تعذّر تغيير خلفية llama.cpp.",+ switchInterrupted: "توقفت عملية التبديل قبل اكتمالها.",+ envLocked: "تم ضبطها على {backend} عبر متغيّر البيئة UNSLOTH_LLAMA_CPP_BACKEND، وهو يتجاوز هذا الإعداد.",+ backends: {+ auto: "تلقائي",+ cpu: "CPU",+ cuda: "CUDA",+ rocm: "ROCm",+ vulkan: "Vulkan",+ metal: "Metal",+ },+ unsupported: {+ notInstalled: "لم يُعثر على تثبيت llama.cpp مُدار، لذا لا توجد خلفية لتبديلها.",+ localLink: "llama.cpp مجلد محلي ربطته بنفسك، ولن يستبدله Unsloth.",+ sourceBuild: "بُني هذا الإصدار من llama.cpp من الشيفرة المصدرية، لذا لا يمكن تبديل خلفيته من هنا.",+ unresolved: "تعذّر التحقق من الخلفيات المتاحة. تحقّق من اتصالك وحاول مرة أخرى.",+ },+ // لا يظهر: كلمات إضافية لبحث الإعدادات.+ llamaBackendKeywords:+ "llama.cpp backend gguf استدلال cuda rocm hip vulkan metal cpu gpu مسرّع prebuilt تبديل محرك",+ },modelMemory: {title: "ذاكرة النموذج",keepResident: "إبقاء النموذج في ذاكرة كرت الرسوميات",diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.tsindex b867021ac76..fb281027dc5 100644--- a/studio/frontend/src/i18n/locales/de.ts+++ b/studio/frontend/src/i18n/locales/de.ts@@ -740,6 +740,39 @@ export const de = {free: "{value} frei",total: "{value} gesamt",},+ llamaBackend: {+ title: "GGUF-Inferenz-Engine",+ label: "Compute-Backend",+ description: "Das Backend, mit dem llama.cpp GGUF-Modelle ausführt.",+ runningOn: "llama.cpp läuft derzeit mit {backend}.",+ hint: "Installiert den llama.cpp-Build für dieses Backend und behält ihn über Updates hinweg bei. Nützlich, wenn die automatische Wahl abstürzt oder dein GPU-Treiber sie nicht unterstützt. Es werden nur Backends aufgeführt, für die es einen Build für diesen Rechner gibt; das Training bleibt unberührt.",+ autoWith: "Automatisch ({backend})",+ apply: "Anwenden",+ applying: "Wird installiert ...",+ applyHint: "Lädt den neuen Build herunter und startet llama.cpp neu. Ein geladenes Modell wird entladen.",+ applyHintWithSize: "Lädt {size} herunter und startet llama.cpp neu. Ein geladenes Modell wird entladen.",+ switchedTo: "llama.cpp läuft jetzt mit {backend}.",+ switchFailed: "Das llama.cpp-Backend konnte nicht geändert werden.",+ switchInterrupted: "Der Wechsel wurde vor dem Abschluss unterbrochen.",+ envLocked: "Durch die Umgebungsvariable UNSLOTH_LLAMA_CPP_BACKEND auf {backend} festgelegt; sie überschreibt diese Einstellung.",+ backends: {+ auto: "Automatisch",+ cpu: "CPU",+ cuda: "CUDA",+ rocm: "ROCm",+ vulkan: "Vulkan",+ metal: "Metal",+ },+ unsupported: {+ notInstalled: "Es wurde keine von Unsloth verwaltete llama.cpp-Installation gefunden, daher gibt es kein Backend zum Wechseln.",+ localLink: "llama.cpp ist ein selbst verknüpftes lokales Verzeichnis, das Unsloth nicht ersetzt.",+ sourceBuild: "Dieses llama.cpp wurde aus dem Quellcode gebaut; sein Backend lässt sich hier nicht wechseln.",+ unresolved: "Die verfügbaren Backends konnten nicht geprüft werden. Prüfe deine Verbindung und versuche es erneut.",+ },+ // Wird nicht angezeigt: zusätzliche Begriffe für die Einstellungssuche.+ llamaBackendKeywords:+ "llama.cpp backend gguf inferenz cuda rocm hip vulkan metal cpu gpu beschleuniger prebuilt wechseln engine",+ },modelMemory: {title: "Modellspeicher",keepResident: "Modell im GPU-Speicher behalten",diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.tsindex 98001cc5931..2e69535c3c3 100644--- a/studio/frontend/src/i18n/locales/en.ts+++ b/studio/frontend/src/i18n/locales/en.ts@@ -710,6 +710,39 @@ export const en = {free: "{value} free",total: "{value} total",},+ llamaBackend: {+ title: "GGUF inference engine",+ label: "Compute backend",+ description: "The backend llama.cpp uses to run GGUF models.",+ runningOn: "llama.cpp currently runs on {backend}.",+ hint: "Installs the llama.cpp build for this backend and keeps it across updates. Useful when the automatic choice crashes or your GPU driver does not support it. Only backends with a build for this machine are listed; training is unaffected.",+ autoWith: "Automatic ({backend})",+ apply: "Apply",+ applying: "Installing...",+ applyHint: "Downloads the new build and restarts llama.cpp. A loaded model is unloaded.",+ applyHintWithSize: "Downloads {size} and restarts llama.cpp. A loaded model is unloaded.",+ switchedTo: "llama.cpp now runs on {backend}.",+ switchFailed: "Could not change the llama.cpp backend.",+ switchInterrupted: "The switch was interrupted before completion.",+ envLocked: "Set to {backend} by the UNSLOTH_LLAMA_CPP_BACKEND environment variable, which overrides this setting.",+ backends: {+ auto: "Automatic",+ cpu: "CPU",+ cuda: "CUDA",+ rocm: "ROCm",+ vulkan: "Vulkan",+ metal: "Metal",+ },+ unsupported: {+ notInstalled: "No managed llama.cpp install was found, so there is no backend to switch.",+ localLink: "llama.cpp is a local directory you linked yourself, so Unsloth will not replace it.",+ sourceBuild: "This llama.cpp was built from source, so its backend cannot be switched from here.",+ unresolved: "The available backends could not be checked. Check your connection and try again.",+ },+ // Not rendered: extra terms the settings search matches these rows on.+ llamaBackendKeywords:+ "llama.cpp backend gguf inference cuda rocm hip vulkan metal cpu gpu accelerator prebuilt switch engine",+ },modelMemory: {title: "Model memory",keepResident: "Keep model in GPU memory",diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.tsindex 518f27f10e5..8f8bcd6fde1 100644--- a/studio/frontend/src/i18n/locales/es.ts+++ b/studio/frontend/src/i18n/locales/es.ts@@ -735,6 +735,39 @@ export const es = {free: "Libre: {value}",total: "{value} en total",},+ llamaBackend: {+ title: "Motor de inferencia GGUF",+ label: "Backend de cómputo",+ description: "El backend que llama.cpp usa para ejecutar modelos GGUF.",+ runningOn: "llama.cpp se ejecuta actualmente en {backend}.",+ hint: "Instala la compilación de llama.cpp para este backend y la mantiene entre actualizaciones. Útil cuando la elección automática falla o el controlador de tu GPU no la admite. Solo se listan los backends con una compilación para este equipo; el entrenamiento no se ve afectado.",+ autoWith: "Automático ({backend})",+ apply: "Aplicar",+ applying: "Instalando...",+ applyHint: "Descarga la nueva compilación y reinicia llama.cpp. Se descargará el modelo que esté cargado.",+ applyHintWithSize: "Descarga {size} y reinicia llama.cpp. Se descargará el modelo que esté cargado.",+ switchedTo: "llama.cpp ahora se ejecuta en {backend}.",+ switchFailed: "No se pudo cambiar el backend de llama.cpp.",+ switchInterrupted: "El cambio se interrumpió antes de completarse.",+ envLocked: "Fijado en {backend} por la variable de entorno UNSLOTH_LLAMA_CPP_BACKEND, que tiene prioridad sobre este ajuste.",+ backends: {+ auto: "Automático",+ cpu: "CPU",+ cuda: "CUDA",+ rocm: "ROCm",+ vulkan: "Vulkan",+ metal: "Metal",+ },+ unsupported: {+ notInstalled: "No se encontró una instalación de llama.cpp gestionada, así que no hay backend que cambiar.",+ localLink: "llama.cpp es un directorio local que enlazaste tú, así que Unsloth no lo reemplazará.",+ sourceBuild: "Este llama.cpp se compiló desde el código fuente, así que su backend no se puede cambiar desde aquí.",+ unresolved: "No se pudieron consultar los backends disponibles. Revisa tu conexión e inténtalo de nuevo.",+ },+ // No se muestra: términos adicionales para la búsqueda de ajustes.+ llamaBackendKeywords:+ "llama.cpp backend gguf inferencia cuda rocm hip vulkan metal cpu gpu acelerador prebuilt cambiar motor",+ },modelMemory: {title: "Memoria del modelo",keepResident: "Mantener el modelo en la memoria de la GPU",diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.tsindex aa80bd805ea..1c821611e07 100644--- a/studio/frontend/src/i18n/locales/fr.ts+++ b/studio/frontend/src/i18n/locales/fr.ts@@ -739,6 +739,39 @@ export const fr = {free: "Disponible : {value}",total: "{value} au total",},+ llamaBackend: {+ title: "Moteur d'inférence GGUF",+ label: "Backend de calcul",+ description: "Le backend utilisé par llama.cpp pour exécuter les modèles GGUF.",+ runningOn: "llama.cpp fonctionne actuellement sur {backend}.",+ hint: "Installe la version de llama.cpp pour ce backend et la conserve lors des mises à jour. Utile si le choix automatique plante ou si votre pilote GPU ne le prend pas en charge. Seuls les backends disposant d'une version pour cette machine sont proposés ; l'entraînement n'est pas affecté.",+ autoWith: "Automatique ({backend})",+ apply: "Appliquer",+ applying: "Installation...",+ applyHint: "Télécharge la nouvelle version et redémarre llama.cpp. Un modèle chargé sera déchargé.",+ applyHintWithSize: "Télécharge {size} et redémarre llama.cpp. Un modèle chargé sera déchargé.",+ switchedTo: "llama.cpp fonctionne maintenant sur {backend}.",+ switchFailed: "Impossible de changer le backend llama.cpp.",+ switchInterrupted: "Le changement a été interrompu avant d’être terminé.",+ envLocked: "Fixé à {backend} par la variable d'environnement UNSLOTH_LLAMA_CPP_BACKEND, qui prévaut sur ce réglage.",+ backends: {+ auto: "Automatique",+ cpu: "CPU",+ cuda: "CUDA",+ rocm: "ROCm",+ vulkan: "Vulkan",+ metal: "Metal",+ },+ unsupported: {+ notInstalled: "Aucune installation llama.cpp gérée n'a été trouvée, il n'y a donc pas de backend à changer.",+ localLink: "llama.cpp est un dossier local que vous avez lié vous-même ; Unsloth ne le remplacera pas.",+ sourceBuild: "Ce llama.cpp a été compilé depuis les sources, son backend ne peut pas être changé ici.",+ unresolved: "Impossible de vérifier les backends disponibles. Vérifiez votre connexion et réessayez.",+ },+ // Non affiché : termes supplémentaires pour la recherche dans les réglages.+ llamaBackendKeywords:+ "llama.cpp backend gguf inférence cuda rocm hip vulkan metal cpu gpu accélérateur prebuilt changer moteur",+ },modelMemory: {title: "Mémoire du modèle",keepResident: "Conserver le modèle dans la mémoire du GPU",diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.tsindex 913a3ba0a52..04b61076add 100644--- a/studio/frontend/src/i18n/locales/hi.ts+++ b/studio/frontend/src/i18n/locales/hi.ts@@ -719,6 +719,39 @@ export const hi = {free: "{value} खाली",total: "{value} कुल",},+ llamaBackend: {+ title: "GGUF इनफ़रेंस इंजन",+ label: "कंप्यूट बैकएंड",+ description: "वह बैकएंड जिस पर llama.cpp GGUF मॉडल चलाता है।",+ runningOn: "llama.cpp अभी {backend} पर चल रहा है।",+ hint: "इस बैकएंड के लिए llama.cpp बिल्ड इंस्टॉल करता है और अपडेट के बाद भी वही रखता है। जब स्वचालित चुनाव क्रैश हो या आपका GPU ड्राइवर उसे सपोर्ट न करे, तब उपयोगी है। केवल वही बैकएंड दिखते हैं जिनका बिल्ड इस मशीन के लिए मौजूद है; ट्रेनिंग पर कोई असर नहीं पड़ता।",+ autoWith: "स्वचालित ({backend})",+ apply: "लागू करें",+ applying: "इंस्टॉल हो रहा है...",+ applyHint: "नया बिल्ड डाउनलोड करके llama.cpp को फिर से शुरू करता है। लोड किया गया मॉडल अनलोड हो जाएगा।",+ applyHintWithSize: "{size} डाउनलोड करके llama.cpp को फिर से शुरू करता है। लोड किया गया मॉडल अनलोड हो जाएगा।",+ switchedTo: "अब llama.cpp {backend} पर चल रहा है।",+ switchFailed: "llama.cpp बैकएंड नहीं बदला जा सका।",+ switchInterrupted: "स्विच पूरा होने से पहले बाधित हो गया।",+ envLocked: "पर्यावरण चर UNSLOTH_LLAMA_CPP_BACKEND ने इसे {backend} पर तय किया है, जो इस सेटिंग पर भारी पड़ता है।",+ backends: {+ auto: "स्वचालित",+ cpu: "CPU",+ cuda: "CUDA",+ rocm: "ROCm",+ vulkan: "Vulkan",+ metal: "Metal",+ },+ unsupported: {+ notInstalled: "कोई प्रबंधित llama.cpp इंस्टॉल नहीं मिला, इसलिए बदलने के लिए कोई बैकएंड नहीं है।",+ localLink: "llama.cpp आपकी अपनी लिंक की हुई लोकल डायरेक्टरी है, इसलिए Unsloth उसे नहीं बदलेगा।",+ sourceBuild: "यह llama.cpp सोर्स से बनाया गया है, इसलिए इसका बैकएंड यहाँ से नहीं बदला जा सकता।",+ unresolved: "उपलब्ध बैकएंड की जाँच नहीं हो सकी। अपना कनेक्शन देखकर दोबारा कोशिश करें।",+ },+ // दिखाया नहीं जाता: सेटिंग्स खोज के लिए अतिरिक्त शब्द।+ llamaBackendKeywords:+ "llama.cpp backend gguf इनफ़रेंस cuda rocm hip vulkan metal cpu gpu एक्सेलेरेटर prebuilt बदलें इंजन",+ },modelMemory: {title: "मॉडल मेमोरी",keepResident: "मॉडल को GPU मेमोरी में रखें",diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.tsindex d75b7b990df..344b9e9a6e8 100644--- a/studio/frontend/src/i18n/locales/it.ts+++ b/studio/frontend/src/i18n/locales/it.ts@@ -705,6 +705,39 @@ export const it = {free: "Disponibili: {value}",total: "Totale: {value}",},+ llamaBackend: {+ title: "Motore di inferenza GGUF",+ label: "Backend di calcolo",+ description: "Il backend che llama.cpp usa per eseguire i modelli GGUF.",+ runningOn: "llama.cpp è in esecuzione su {backend}.",+ hint: "Installa la build di llama.cpp per questo backend e la mantiene tra un aggiornamento e l'altro. Utile se la scelta automatica va in crash o se il driver della GPU non la supporta. Sono elencati solo i backend con una build per questa macchina; l'addestramento non cambia.",+ autoWith: "Automatico ({backend})",+ apply: "Applica",+ applying: "Installazione...",+ applyHint: "Scarica la nuova build e riavvia llama.cpp. Il modello caricato verrà scaricato.",+ applyHintWithSize: "Scarica {size} e riavvia llama.cpp. Il modello caricato verrà scaricato.",+ switchedTo: "Ora llama.cpp è in esecuzione su {backend}.",+ switchFailed: "Impossibile cambiare il backend di llama.cpp.",+ switchInterrupted: "Il cambio è stato interrotto prima del completamento.",+ envLocked: "Impostato su {backend} dalla variabile d'ambiente UNSLOTH_LLAMA_CPP_BACKEND, che ha la precedenza su questa opzione.",+ backends: {+ auto: "Automatico",+ cpu: "CPU",+ cuda: "CUDA",+ rocm: "ROCm",+ vulkan: "Vulkan",+ metal: "Metal",+ },+ unsupported: {+ notInstalled: "Nessuna installazione di llama.cpp gestita da Unsloth, quindi non c'è un backend da cambiare.",+ localLink: "llama.cpp è una cartella locale collegata da te, quindi Unsloth non la sostituirà.",+ sourceBuild: "Questo llama.cpp è stato compilato dai sorgenti, quindi il backend non è modificabile da qui.",+ unresolved: "Non è stato possibile controllare i backend disponibili. Verifica la connessione e riprova.",+ },+ // Non visualizzato: termini aggiuntivi per la ricerca nelle impostazioni.+ llamaBackendKeywords:+ "llama.cpp backend gguf inferenza cuda rocm hip vulkan metal cpu gpu acceleratore prebuilt cambiare motore",+ },modelMemory: {title: "Memoria del modello",keepResident: "Mantieni il modello nella memoria della GPU",diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.tsindex 24f8d0f44f0..3e9a01caf0c 100644--- a/studio/frontend/src/i18n/locales/ja.ts+++ b/studio/frontend/src/i18n/locales/ja.ts@@ -699,6 +699,39 @@ export const ja = {free: "{value} 空き",total: "{value} 合計",},+ llamaBackend: {+ title: "GGUF 推論エンジン",+ label: "計算バックエンド",+ description: "llama.cpp が GGUF モデルの実行に使うバックエンドです。",+ runningOn: "llama.cpp は現在 {backend} で動作しています。",+ hint: "このバックエンド向けの llama.cpp ビルドをインストールし、アップデート後も維持します。自動選択がクラッシュする場合や、GPU ドライバーが対応していない場合に役立ちます。このマシン用のビルドがあるバックエンドのみ表示され、学習には影響しません。",+ autoWith: "自動 ({backend})",+ apply: "適用",+ applying: "インストール中...",+ applyHint: "新しいビルドをダウンロードして llama.cpp を再起動します。ロード中のモデルはアンロードされます。",+ applyHintWithSize: "{size} をダウンロードして llama.cpp を再起動します。ロード中のモデルはアンロードされます。",+ switchedTo: "llama.cpp は {backend} で動作するようになりました。",+ switchFailed: "llama.cpp のバックエンドを変更できませんでした。",+ switchInterrupted: "切り替えは完了する前に中断されました。",+ envLocked: "環境変数 UNSLOTH_LLAMA_CPP_BACKEND により {backend} に固定されています。この設定より優先されます。",+ backends: {+ auto: "自動",+ cpu: "CPU",+ cuda: "CUDA",+ rocm: "ROCm",+ vulkan: "Vulkan",+ metal: "Metal",+ },+ unsupported: {+ notInstalled: "管理対象の llama.cpp インストールが見つからないため、切り替えるバックエンドがありません。",+ localLink: "llama.cpp は自分でリンクしたローカルディレクトリのため、Unsloth は置き換えません。",+ sourceBuild: "この llama.cpp はソースからビルドされているため、ここではバックエンドを切り替えられません。",+ unresolved: "利用可能なバックエンドを確認できませんでした。接続を確認して再試行してください。",+ },+ // 非表示: 設定検索用の追加キーワード。+ llamaBackendKeywords:+ "llama.cpp backend gguf 推論 cuda rocm hip vulkan metal cpu gpu アクセラレータ prebuilt 切り替え エンジン",+ },modelMemory: {title: "モデルメモリ",keepResident: "モデルを GPU メモリに保持",diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.tsindex 1269055eb96..bb777890b0d 100644--- a/studio/frontend/src/i18n/locales/ko.ts+++ b/studio/frontend/src/i18n/locales/ko.ts@@ -713,6 +713,39 @@ export const ko = {free: "{value} 여유",total: "총 {value}",},+ llamaBackend: {+ title: "GGUF 추론 엔진",+ label: "연산 백엔드",+ description: "llama.cpp가 GGUF 모델을 실행할 때 사용하는 백엔드입니다.",+ runningOn: "llama.cpp가 현재 {backend}에서 실행 중입니다.",+ hint: "이 백엔드용 llama.cpp 빌드를 설치하고 업데이트 후에도 유지합니다. 자동 선택이 충돌하거나 GPU 드라이버가 지원하지 않을 때 유용합니다. 이 컴퓨터용 빌드가 있는 백엔드만 표시되며 학습에는 영향이 없습니다.",+ autoWith: "자동 ({backend})",+ apply: "적용",+ applying: "설치 중...",+ applyHint: "새 빌드를 내려받고 llama.cpp를 다시 시작합니다. 로드된 모델은 언로드됩니다.",+ applyHintWithSize: "{size}를 내려받고 llama.cpp를 다시 시작합니다. 로드된 모델은 언로드됩니다.",+ switchedTo: "이제 llama.cpp가 {backend}에서 실행됩니다.",+ switchFailed: "llama.cpp 백엔드를 변경하지 못했습니다.",+ switchInterrupted: "전환이 완료되기 전에 중단되었습니다.",+ envLocked: "환경 변수 UNSLOTH_LLAMA_CPP_BACKEND가 {backend}(으)로 고정했으며, 이 설정보다 우선합니다.",+ backends: {+ auto: "자동",+ cpu: "CPU",+ cuda: "CUDA",+ rocm: "ROCm",+ vulkan: "Vulkan",+ metal: "Metal",+ },+ unsupported: {+ notInstalled: "관리되는 llama.cpp 설치를 찾을 수 없어 전환할 백엔드가 없습니다.",+ localLink: "llama.cpp는 직접 연결한 로컬 디렉터리이므로 Unsloth가 교체하지 않습니다.",+ sourceBuild: "이 llama.cpp는 소스에서 빌드되어 여기서 백엔드를 전환할 수 없습니다.",+ unresolved: "사용 가능한 백엔드를 확인하지 못했습니다. 연결을 확인한 뒤 다시 시도하세요.",+ },+ // 표시되지 않음: 설정 검색용 추가 키워드.+ llamaBackendKeywords:+ "llama.cpp backend gguf 추론 cuda rocm hip vulkan metal cpu gpu 가속기 prebuilt 전환 엔진",+ },modelMemory: {title: "모델 메모리",keepResident: "모델을 GPU 메모리에 유지",diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.tsindex 3062ecb1ff1..884fb41e89f 100644--- a/studio/frontend/src/i18n/locales/pt-br.ts+++ b/studio/frontend/src/i18n/locales/pt-br.ts@@ -723,6 +723,39 @@ export const ptBR = {free: "{value} livres",total: "{value} total",},+ llamaBackend: {+ title: "GGUF inference engine",+ label: "Compute backend",+ description: "The backend llama.cpp uses to run GGUF models.",+ runningOn: "llama.cpp currently runs on {backend}.",+ hint: "Installs the llama.cpp build for this backend and keeps it across updates. Useful when the automatic choice crashes or your GPU driver does not support it. Only backends with a build for this machine are listed; training is unaffected.",+ autoWith: "Automatic ({backend})",+ apply: "Apply",+ applying: "Installing...",+ applyHint: "Downloads the new build and restarts llama.cpp. A loaded model is unloaded.",+ applyHintWithSize: "Downloads {size} and restarts llama.cpp. A loaded model is unloaded.",+ switchedTo: "llama.cpp now runs on {backend}.",+ switchFailed: "Could not change the llama.cpp backend.",+ switchInterrupted: "The switch was interrupted before completion.",+ envLocked: "Set to {backend} by the UNSLOTH_LLAMA_CPP_BACKEND environment variable, which overrides this setting.",+ backends: {+ auto: "Automatic",+ cpu: "CPU",+ cuda: "CUDA",+ rocm: "ROCm",+ vulkan: "Vulkan",+ metal: "Metal",+ },+ unsupported: {+ notInstalled: "No managed llama.cpp install was found, so there is no backend to switch.",+ localLink: "llama.cpp is a local directory you linked yourself, so Unsloth will not replace it.",+ sourceBuild: "This llama.cpp was built from source, so its backend cannot be switched from here.",+ unresolved: "The available backends could not be checked. Check your connection and try again.",+ },+ // Not rendered: extra terms the settings search matches these rows on.+ llamaBackendKeywords:+ "llama.cpp backend gguf inference cuda rocm hip vulkan metal cpu gpu accelerator prebuilt switch engine",+ },modelMemory: {title: "Memória do modelo",keepResident: "Manter o modelo na memória da GPU",diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.tsindex c0f44c78ce9..d10c440c93f 100644--- a/studio/frontend/src/i18n/locales/ru.ts+++ b/studio/frontend/src/i18n/locales/ru.ts@@ -720,6 +720,39 @@ export const ru = {free: "{value} свободно",total: "{value} всего",},+ llamaBackend: {+ title: "Движок инференса GGUF",+ label: "Вычислительный бэкенд",+ description: "Бэкенд, на котором llama.cpp выполняет модели GGUF.",+ runningOn: "Сейчас llama.cpp работает на {backend}.",+ hint: "Устанавливает сборку llama.cpp для этого бэкенда и сохраняет выбор при обновлениях. Пригодится, если автоматический выбор падает или драйвер видеокарты его не поддерживает. Показаны только бэкенды, для которых есть сборка под этот компьютер; на обучение это не влияет.",+ autoWith: "Автоматически ({backend})",+ apply: "Применить",+ applying: "Установка...",+ applyHint: "Скачает новую сборку и перезапустит llama.cpp. Загруженная модель будет выгружена.",+ applyHintWithSize: "Скачает {size} и перезапустит llama.cpp. Загруженная модель будет выгружена.",+ switchedTo: "Теперь llama.cpp работает на {backend}.",+ switchFailed: "Не удалось изменить бэкенд llama.cpp.",+ switchInterrupted: "Переключение было прервано до завершения.",+ envLocked: "Значение {backend} задано переменной окружения UNSLOTH_LLAMA_CPP_BACKEND, она важнее этой настройки.",+ backends: {+ auto: "Автоматически",+ cpu: "CPU",+ cuda: "CUDA",+ rocm: "ROCm",+ vulkan: "Vulkan",+ metal: "Metal",+ },+ unsupported: {+ notInstalled: "Управляемая установка llama.cpp не найдена, поэтому менять нечего.",+ localLink: "llama.cpp, это локальный каталог, который вы подключили сами, и Unsloth его не заменяет.",+ sourceBuild: "Этот llama.cpp собран из исходников, его бэкенд нельзя переключить отсюда.",+ unresolved: "Не удалось проверить доступные бэкенды. Проверьте подключение и повторите попытку.",+ },+ // Не отображается: дополнительные слова для поиска по настройкам.+ llamaBackendKeywords:+ "llama.cpp backend gguf инференс cuda rocm hip vulkan metal cpu gpu ускоритель prebuilt переключить движок",+ },modelMemory: {title: "Память модели",keepResident: "Держать модель в памяти GPU",diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.tsindex 22be5412f81..eb32e5ba3d7 100644--- a/studio/frontend/src/i18n/locales/zh-CN.ts+++ b/studio/frontend/src/i18n/locales/zh-CN.ts@@ -696,6 +696,39 @@ export const zhCN = {free: "{value} 可用",total: "共 {value}",},+ llamaBackend: {+ title: "GGUF 推理引擎",+ label: "计算后端",+ description: "llama.cpp 运行 GGUF 模型所用的后端。",+ runningOn: "llama.cpp 当前运行在 {backend} 上。",+ hint: "安装该后端的 llama.cpp 构建,并在更新后继续沿用。当自动选择崩溃或显卡驱动不支持时很有用。只列出本机有对应构建的后端;训练不受影响。",+ autoWith: "自动({backend})",+ apply: "应用",+ applying: "正在安装…",+ applyHint: "下载新的构建并重启 llama.cpp。已加载的模型会被卸载。",+ applyHintWithSize: "下载 {size} 并重启 llama.cpp。已加载的模型会被卸载。",+ switchedTo: "llama.cpp 现在运行在 {backend} 上。",+ switchFailed: "无法更改 llama.cpp 后端。",+ switchInterrupted: "切换在完成前中断。",+ envLocked: "已由环境变量 UNSLOTH_LLAMA_CPP_BACKEND 固定为 {backend},其优先级高于此设置。",+ backends: {+ auto: "自动",+ cpu: "CPU",+ cuda: "CUDA",+ rocm: "ROCm",+ vulkan: "Vulkan",+ metal: "Metal",+ },+ unsupported: {+ notInstalled: "未找到受管理的 llama.cpp 安装,因此没有可切换的后端。",+ localLink: "llama.cpp 是你自己链接的本地目录,Unsloth 不会替换它。",+ sourceBuild: "此 llama.cpp 由源码编译,无法在这里切换后端。",+ unresolved: "无法检查可用的后端。请检查网络连接后重试。",+ },+ // 不显示:用于设置搜索的额外词条。+ llamaBackendKeywords:+ "llama.cpp backend gguf 推理 cuda rocm hip vulkan metal cpu gpu 加速器 prebuilt 切换 引擎",+ },modelMemory: {title: "模型内存",keepResident: "将模型保留在显存中",diff --git a/studio/frontend/src/lib/llama-job-events.ts b/studio/frontend/src/lib/llama-job-events.tsnew file mode 100644index 00000000000..454ca466ab3--- /dev/null+++ b/studio/frontend/src/lib/llama-job-events.ts@@ -0,0 +1,45 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++const LLAMA_JOB_STARTED_STORAGE_KEY = "unsloth_llama_job_started_at";+const LLAMA_JOB_STARTED_EVENT = "unsloth:llama-job-started";++/** Prompt same-window and cross-tab listeners to fetch the shared job state. */+export function signalLlamaJobStarted(startedAt: string | null): void {+ try {+ localStorage.setItem(+ LLAMA_JOB_STARTED_STORAGE_KEY,+ `${startedAt ?? "unknown"}:${Date.now()}`,+ );+ } catch {+ // Storage can be unavailable in restricted browser contexts.+ }+ window.dispatchEvent(new Event(LLAMA_JOB_STARTED_EVENT));+}++/** Signal only when an API response carries the authoritative running job. */+export function signalRunningLlamaJob(job: {+ state: unknown;+ started_at: string | null;+}): boolean {+ if (job.state !== "running") {+ return false;+ }+ signalLlamaJobStarted(job.started_at);+ return true;+}++/** Subscribe to same-window and cross-tab job-start notifications. */+export function subscribeToLlamaJobStarted(listener: () => void): () => void {+ const onStorage = (event: StorageEvent) => {+ if (event.key === LLAMA_JOB_STARTED_STORAGE_KEY) {+ listener();+ }+ };+ window.addEventListener(LLAMA_JOB_STARTED_EVENT, listener);+ window.addEventListener("storage", onStorage);+ return () => {+ window.removeEventListener(LLAMA_JOB_STARTED_EVENT, listener);+ window.removeEventListener("storage", onStorage);+ };+}diff --git a/studio/frontend/src/lib/llama-job-lifecycle.ts b/studio/frontend/src/lib/llama-job-lifecycle.tsnew file mode 100644index 00000000000..894eff89400--- /dev/null+++ b/studio/frontend/src/lib/llama-job-lifecycle.ts@@ -0,0 +1,69 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++export type LlamaJobState = "idle" | "running" | "success" | "error";+export type LlamaJobOperation = "update" | "switch" | null;++interface LlamaJob {+ state: LlamaJobState;+ operation: LlamaJobOperation;+}++interface IdentifiedLlamaJob extends LlamaJob {+ startedAt: string | null;+}++export type OwnedLlamaSwitchOutcome =+ | "running"+ | "success"+ | "error"+ | "interrupted";++/** Interpret a status only as the switch job that this surface accepted. */+export function ownedLlamaSwitchOutcome(+ job: IdentifiedLlamaJob,+ acceptedStartedAt: string | null,+): OwnedLlamaSwitchOutcome {+ if (+ !acceptedStartedAt ||+ job.startedAt !== acceptedStartedAt ||+ job.operation !== "switch"+ ) {+ return "interrupted";+ }+ return job.state === "idle" ? "interrupted" : job.state;+}++/**+ * Whether an `already_running` /update response is the update this apply asked+ * for. A backend switch shares the same job: adopting it would resolve this+ * action as an applied update while the pending release is still uninstalled.+ */+export function llamaUpdateAdoptsRunningJob(+ reason: string | null | undefined,+ job: LlamaJob,+): boolean {+ return reason === "already_running" && job.operation !== "switch";+}++export interface LlamaUpdatePresentation {+ applying: boolean;+ visible: boolean;+ running: boolean;+}++/** Derive the update banner from every shared-job status transition. */+export function llamaUpdatePresentation(+ updateAvailable: boolean,+ job: LlamaJob,+): LlamaUpdatePresentation {+ if (job.state !== "running") {+ return { applying: false, visible: updateAvailable, running: false };+ }+ const switching = job.operation === "switch";+ return {+ applying: !switching,+ visible: !switching,+ running: true,+ };+}diff --git a/studio/frontend/tests/llama-backend-payload.test.ts b/studio/frontend/tests/llama-backend-payload.test.tsnew file mode 100644index 00000000000..484c6fb0310--- /dev/null+++ b/studio/frontend/tests/llama-backend-payload.test.ts@@ -0,0 +1,242 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import assert from "node:assert/strict";+import test from "node:test";+import {+ llamaBackendSelectionNeedsApply,+ parseLlamaBackendStatus,+ visibleLlamaBackendOptions,+} from "../src/features/settings/api/llama-backend-payload.ts";++const FULL_PAYLOAD = {+ supported: true,+ reason: null,+ env_backend: null,+ backend: "cuda",+ backend_request: "auto",+ selection_applied: true,+ installed_tag: "b9596-mix-abc",+ options: [+ {+ backend: "auto",+ available: true,+ resolved_backend: "cuda",+ release_tag: "b9596-mix-abc",+ download_size_bytes: 183239972,+ },+ { backend: "rocm", available: false, unavailable_reason: "unavailable" },+ ],+ job: { state: "idle", message: "", progress: null },+};++test("a status payload is read into the picker's shape", () => {+ const status = parseLlamaBackendStatus(FULL_PAYLOAD);++ assert.equal(status.supported, true);+ assert.equal(status.backend, "cuda");+ assert.equal(status.backendRequest, "auto");+ assert.equal(status.options[0]?.resolvedBackend, "cuda");+ assert.equal(status.options[0]?.downloadSizeBytes, 183239972);+ assert.equal(status.options[1]?.available, false);+});++test("a backend this build does not know about is dropped, not offered", () => {+ // Older clients cannot label or submit unknown backends.+ const status = parseLlamaBackendStatus({+ ...FULL_PAYLOAD,+ options: [...FULL_PAYLOAD.options, { backend: "sycl", available: true }],+ });++ assert.deepEqual(+ status.options.map((option) => option.backend),+ ["auto", "rocm"],+ );+});++test("a backend older than this client's list stays unknown", () => {+ // An unknown recorded choice must not become automatic: the picker would then+ // show detection for an install that is pinned, and overwrite it on the next+ // apply. Untouched it is not dirty, but picking over it deliberately is.+ const status = parseLlamaBackendStatus({+ ...FULL_PAYLOAD,+ backend_request: "sycl",+ });++ assert.equal(status.backendRequest, null);+ assert.equal(llamaBackendSelectionNeedsApply(status, null), false);+ assert.equal(llamaBackendSelectionNeedsApply(status, "cuda"), true);+});++test("a missing or malformed payload degrades instead of throwing", () => {+ const status = parseLlamaBackendStatus(null);++ assert.equal(status.supported, false);+ assert.equal(status.backendRequest, null);+ assert.deepEqual(status.options, []);+ assert.equal(status.job.state, "idle");+});++test("a running job is read with its progress so the bar can move", () => {+ const status = parseLlamaBackendStatus({+ ...FULL_PAYLOAD,+ job: {+ state: "running",+ operation: "switch",+ requested_backend: "vulkan",+ message: "Installing the vulkan llama.cpp build...",+ progress: 0.42,+ reload_required: null,+ started_at: "2026-08-11T12:00:00Z",+ finished_at: null,+ },+ });++ assert.equal(status.job.state, "running");+ assert.equal(status.job.operation, "switch");+ assert.equal(status.job.requestedBackend, "vulkan");+ assert.equal(status.job.startedAt, "2026-08-11T12:00:00Z");+ assert.equal(status.job.progress, 0.42);+ assert.equal(status.job.message, "Installing the vulkan llama.cpp build...");+});++test("only installable backends are offered", () => {+ const status = parseLlamaBackendStatus(FULL_PAYLOAD);++ assert.deepEqual(+ visibleLlamaBackendOptions(status, "auto").map((option) => option.backend),+ ["auto"],+ );+});++test("the selected backend stays listed even when it stops being installable", () => {+ // Keep the selected value in the control even after it becomes unavailable.+ const status = parseLlamaBackendStatus(FULL_PAYLOAD);++ assert.deepEqual(+ visibleLlamaBackendOptions(status, "rocm").map((option) => option.backend),+ ["auto", "rocm"],+ );+});++test("automatic can be applied again when it now resolves differently", () => {+ const status = parseLlamaBackendStatus({+ ...FULL_PAYLOAD,+ backend: "cpu",+ selection_applied: false,+ });++ assert.equal(llamaBackendSelectionNeedsApply(status, null), true);+ assert.equal(llamaBackendSelectionNeedsApply(status, "auto"), true);+});++test("older status payloads do not become dirty without server evidence", () => {+ const { selection_applied: _selectionApplied, ...olderPayload } =+ FULL_PAYLOAD;+ assert.equal(_selectionApplied, true);+ const status = parseLlamaBackendStatus(olderPayload);++ assert.equal(status.selectionApplied, true);+ assert.equal(llamaBackendSelectionNeedsApply(status, null), false);+});++test("an environment pin is never left with Apply as the only live control", () => {+ // The Select is disabled whenever the environment pins the backend. Dirtiness is+ // computed independently, so an automatic install whose detection has since drifted+ // (a GPU appeared under an env-pinned CPU install) makes the row dirty while the+ // Select is disabled. The server refuses that POST with environment_override, so the+ // button must be disabled by the same condition rather than offering the round trip.+ const status = parseLlamaBackendStatus({+ ...FULL_PAYLOAD,+ env_backend: "cpu",+ backend: "cpu",+ backend_request: "auto",+ selection_applied: false,+ });++ assert.equal(status.envBackend, "cpu");+ assert.equal(llamaBackendSelectionNeedsApply(status, status.backendRequest), true);+ const envLocked = status.envBackend !== null;+ const dirty = llamaBackendSelectionNeedsApply(status, status.backendRequest);+ // What the component computes for each control.+ assert.equal(!status.supported || envLocked, true, "Select is disabled");+ assert.equal(!dirty || !status.supported || envLocked, true, "Apply is disabled too");+});++test("every unsupported reason survives the parser verbatim", () => {+ // The section maps these to distinct explanations, including the no_install_dir+ // alias, and a reason that stops round-tripping silently degrades to the generic+ // "could not be checked" copy.+ for (const reason of [+ "not_installed",+ "local_link",+ "source_build",+ "no_install_dir",+ "unresolved",+ ]) {+ const status = parseLlamaBackendStatus({+ ...FULL_PAYLOAD,+ supported: false,+ reason,+ options: [],+ });+ assert.equal(status.reason, reason);+ assert.equal(status.supported, false);+ assert.deepEqual(visibleLlamaBackendOptions(status, null), []);+ // Nothing to apply on an install that cannot be switched.+ assert.equal(llamaBackendSelectionNeedsApply(status, status.backendRequest), false);+ }+});++test("macOS reports Metal as the running backend and offers only automatic", () => {+ // resolve_backends_payload enumerates ("auto",) on macOS, and metal is deliberately+ // absent from LLAMA_BACKENDS: it is a backend an install can RUN, never one a user+ // can request. The parser must keep it as the effective backend all the same.+ const status = parseLlamaBackendStatus({+ ...FULL_PAYLOAD,+ backend: "metal",+ backend_request: "auto",+ options: [+ {+ backend: "auto",+ available: true,+ resolved_backend: "metal",+ release_tag: "b9596-mix-abc",+ download_size_bytes: null,+ },+ ],+ });++ assert.equal(status.backend, "metal");+ assert.equal(status.options.length, 1);+ assert.equal(status.options[0].resolvedBackend, "metal");+ assert.equal(status.options[0].downloadSizeBytes, null);+ assert.equal(llamaBackendSelectionNeedsApply(status, "auto"), false);+});++test("terminal job states round-trip, including a job that failed elsewhere", () => {+ for (const [state, error] of [+ ["success", null],+ ["error", "no cuda prebuilt bundle attempts were available"],+ ["nonsense-from-a-newer-server", null],+ ] as const) {+ const status = parseLlamaBackendStatus({+ ...FULL_PAYLOAD,+ job: {+ state,+ operation: "switch",+ requested_backend: "vulkan",+ message: "done",+ error,+ finished_at: "2026-08-13T00:00:00Z",+ },+ });+ assert.equal(+ status.job.state,+ state === "nonsense-from-a-newer-server" ? "idle" : state,+ );+ assert.equal(status.job.operation, "switch");+ assert.equal(status.job.requestedBackend, "vulkan");+ assert.equal(status.job.error, error);+ }+});diff --git a/studio/frontend/tests/llama-job-events.test.ts b/studio/frontend/tests/llama-job-events.test.tsnew file mode 100644index 00000000000..cb8d1d56f81--- /dev/null+++ b/studio/frontend/tests/llama-job-events.test.ts@@ -0,0 +1,71 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import assert from "node:assert/strict";+import test from "node:test";+import {+ signalLlamaJobStarted,+ signalRunningLlamaJob,+ subscribeToLlamaJobStarted,+} from "../src/lib/llama-job-events.ts";++test("job starts notify this window and other-tab storage listeners", (t) => {+ const target = new EventTarget();+ const writes = new Map<string, string>();+ Object.defineProperty(globalThis, "window", {+ configurable: true,+ value: target,+ });+ Object.defineProperty(globalThis, "localStorage", {+ configurable: true,+ value: {+ setItem(key: string, value: string) {+ writes.set(key, value);+ },+ },+ });+ t.after(() => {+ Reflect.deleteProperty(globalThis, "window");+ Reflect.deleteProperty(globalThis, "localStorage");+ });++ let notifications = 0;+ const unsubscribe = subscribeToLlamaJobStarted(() => {+ notifications += 1;+ });++ signalLlamaJobStarted("2026-08-11T12:00:00Z");+ assert.equal(notifications, 1);+ assert.match(+ writes.get("unsloth_llama_job_started_at") ?? "",+ /^2026-08-11T12:00:00Z:\d+$/,+ );++ const storageEvent = new Event("storage");+ Object.defineProperty(storageEvent, "key", {+ value: "unsloth_llama_job_started_at",+ });+ target.dispatchEvent(storageEvent);+ assert.equal(notifications, 2);++ assert.equal(+ signalRunningLlamaJob({+ state: "running",+ started_at: "2026-08-11T12:01:00Z",+ }),+ true,+ );+ assert.equal(notifications, 3);+ assert.equal(+ signalRunningLlamaJob({+ state: "success",+ started_at: "2026-08-11T12:01:00Z",+ }),+ false,+ );+ assert.equal(notifications, 3);++ unsubscribe();+ signalLlamaJobStarted(null);+ assert.equal(notifications, 3);+});diff --git a/studio/frontend/tests/llama-job-lifecycle.test.ts b/studio/frontend/tests/llama-job-lifecycle.test.tsnew file mode 100644index 00000000000..157e094d110--- /dev/null+++ b/studio/frontend/tests/llama-job-lifecycle.test.ts@@ -0,0 +1,105 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import assert from "node:assert/strict";+import test from "node:test";+import {+ llamaUpdateAdoptsRunningJob,+ llamaUpdatePresentation,+ ownedLlamaSwitchOutcome,+} from "../src/lib/llama-job-lifecycle.ts";++const SWITCH_STARTED_AT = "2026-08-12T15:00:00Z";++test("an owned switch recognizes only its explicit running and terminal states", () => {+ for (const state of ["running", "success", "error"] as const) {+ assert.equal(+ ownedLlamaSwitchOutcome(+ { state, operation: "switch", startedAt: SWITCH_STARTED_AT },+ SWITCH_STARTED_AT,+ ),+ state,+ );+ }+});++test("a lost or replaced switch is interrupted rather than successful", () => {+ for (const job of [+ { state: "idle" as const, operation: null, startedAt: null },+ {+ state: "success" as const,+ operation: "update" as const,+ startedAt: SWITCH_STARTED_AT,+ },+ {+ state: "running" as const,+ operation: "switch" as const,+ startedAt: "a-different-job",+ },+ {+ state: "success" as const,+ operation: "switch" as const,+ startedAt: null,+ },+ ]) {+ assert.equal(+ ownedLlamaSwitchOutcome(job, SWITCH_STARTED_AT),+ "interrupted",+ );+ }+});++test("a running switch hides the update banner without showing update progress", () => {+ assert.deepEqual(+ llamaUpdatePresentation(true, {+ state: "running",+ operation: "switch",+ }),+ { applying: false, visible: false, running: true },+ );+});++test("every terminal switch status restores a pending update", () => {+ for (const state of ["success", "error", "idle"] as const) {+ assert.deepEqual(+ llamaUpdatePresentation(true, { state, operation: "switch" }),+ { applying: false, visible: true, running: false },+ );+ }+});++test("a completed update stays hidden when no update remains", () => {+ assert.deepEqual(+ llamaUpdatePresentation(false, {+ state: "success",+ operation: "update",+ }),+ { applying: false, visible: false, running: false },+ );+});++test("an apply adopts an already-running update but never a switch", () => {+ // Both share one job. Following a switch here would resolve the update action+ // as applied while the release it offered is still not installed.+ assert.equal(+ llamaUpdateAdoptsRunningJob("already_running", {+ state: "running",+ operation: "update",+ }),+ true,+ );+ assert.equal(+ llamaUpdateAdoptsRunningJob("already_running", {+ state: "running",+ operation: "switch",+ }),+ false,+ );+ assert.equal(+ llamaUpdateAdoptsRunningJob("up_to_date", {+ state: "success",+ operation: "update",+ }),+ false,+ );+});diff --git a/studio/install_llama_prebuilt.py b/studio/install_llama_prebuilt.pyindex b1bbcfae70e..6ef4049ead3 100644--- a/studio/install_llama_prebuilt.py+++ b/studio/install_llama_prebuilt.py@@ -53,6 +53,16 @@ if _STUDIO_DIR not in sys.path:sys.path.insert(0, _STUDIO_DIR)import prebuilt_core as _core # noqa: E402+from backend.utils.prebuilt.llama_backend import ( # noqa: E402+ INSTALL_KIND_BACKENDS,+ REQUESTABLE_BACKENDS,+ backend_for_install_kind,+ environment_backend_override,+ install_kinds_for_backend,+ is_requestable_backend,+ marker_backend_request,+ normalize_backend_request,+)# Late-binding seam: core functions resolve collaborators (download_file,# fetch_json, ...) through this module's globals at call time, so tests that@@ -66,6 +76,8 @@ EXIT_FALLBACK = 2EXIT_ERROR = 1EXIT_BUSY = 3EXIT_NO_SPACE = 4+# A concrete backend selection could not be satisfied.+EXIT_BACKEND_UNAVAILABLE = 5# Every gfx a Windows AMD host can be served: ggml-org release.yml windows-hip GPU_TARGETS# plus the fork's windows-rocm bundles. Must stay a superset of the manifest's windows-rocm@@ -128,7 +140,14 @@ UPSTREAM_WINDOWS_HIP_GFX_TARGETS = frozenset(# install_kinds that really are a Vulkan bundle. A Vulkan request can still end on a CPU# bundle (no Vulkan archive on Windows arm64; x64 falls through when it is missing or fails# validation), so check against this to keep the marker honest (#7357).-VULKAN_INSTALL_KINDS = frozenset({"linux-vulkan", "windows-vulkan"})+# Derived from the shared vocabulary rather than spelled out again: a new Vulkan bundle+# family added to INSTALL_KIND_BACKENDS must not be missed here.+VULKAN_INSTALL_KINDS = frozenset(+ kind for kind, kind_backend in INSTALL_KIND_BACKENDS.items() if kind_backend == "vulkan"+)++CONCRETE_BACKENDS = tuple(backend for backend in REQUESTABLE_BACKENDS if backend != "auto")+# DiskPart-prompt suppression. RunAsInvoker does NOT stop amd-smi's runtime# elevation (its manifest is asInvoker), so this is just harmless belt-and-@@ -501,6 +520,18 @@ class ExistingInstallSatisfied(RuntimeError):self.used_fallback = used_fallback+class BackendUnavailable(PrebuiltFallback):+ """This host and these releases publish no bundle for the requested backend.++ It shares the prebuilt rollback path, but remains distinguishable from transport+ failures and from fallbacks where automatic source selection is safe.+ """+++class UnknownBackendRequest(RuntimeError):+ """A newer installer recorded a backend this version cannot preserve."""++_os_error_messages = _core._os_error_messagesis_busy_lock_error = _core.is_busy_lock_error@@ -760,18 +791,49 @@ def download_bytes(headers: dict[str, str] | None = None,progress_label: str | None = None,) -> bytes:- return _core.download_bytes(- _OPS,- url,- timeout = timeout,- attempts = attempts,- headers = headers,- progress_label = progress_label,- )+ def _download() -> bytes:+ return _core.download_bytes(+ _OPS,+ url,+ timeout = timeout,+ attempts = attempts,+ headers = headers,+ progress_label = progress_label,+ )++ # Cache only small metadata. Archive downloads must never be held in memory.+ if url.endswith(".json"):+ return _memoized_fetch(("bytes", url), _download)+ return _download()+++# Enabled only while --resolve-backends plans several options from one metadata snapshot.+_METADATA_MEMO: dict[Any, Any] | None = None+++@contextmanager+def _cached_metadata_fetches() -> Iterator[None]:+ global _METADATA_MEMO+ previous = _METADATA_MEMO+ _METADATA_MEMO = {}+ try:+ yield+ finally:+ _METADATA_MEMO = previous+++def _memoized_fetch(key: Any, produce: Callable[[], Any]) -> Any:+ memo = _METADATA_MEMO+ if memo is None:+ return produce()+ if key not in memo:+ # Cache successes only.+ memo[key] = produce()+ return memo[key]def fetch_json(url: str) -> Any:- return _core.fetch_json(_OPS, url)+ return _memoized_fetch(("json", url), lambda: _core.fetch_json(_OPS, url))def download_file(url: str, destination: Path) -> None:@@ -1312,10 +1374,13 @@ def parse_published_release_bundle(# Mixed repos are filtered by an explicit release-side manifest rather than# by release tag or asset filename conventions.- manifest_bytes = download_bytes(- manifest_url,- timeout = 30,- headers = auth_headers(manifest_url),+ manifest_bytes = _memoized_fetch(+ ("bytes", manifest_url),+ lambda: download_bytes(+ manifest_url,+ timeout = 30,+ headers = auth_headers(manifest_url),+ ),)manifest_sha256 = sha256_bytes(manifest_bytes)try:@@ -1901,7 +1966,9 @@ def _download_host_latest_release_tag(repo: str) -> str | None:def _fetch_download_host_json(url: str) -> Any:- return _core.fetch_download_host_json(_OPS, url)+ return _memoized_fetch(+ ("download-host-json", url), lambda: _core.fetch_download_host_json(_OPS, url)+ )def _download_host_resolved_release(repo: str) -> ResolvedPublishedRelease | None:@@ -2418,7 +2485,7 @@ def windows_intel_gpu_in_registry() -> bool:return False-def detect_host() -> HostInfo:+def detect_host(*, probe_rocm_with_nvidia: bool = False) -> HostInfo:system = platform.system()machine = platform.machine().lower()is_windows = system == "Windows"@@ -2532,9 +2599,11 @@ def detect_host() -> HostInfo:except OSError:pass- # Detect AMD ROCm (HIP) -- require actual GPU, not just tools installed- # NVIDIA takes precedence: when an NVIDIA GPU is usable, skip ROCm probing- # entirely so co-installed ROCm tools cannot misroute the host (PR 6174).+ # Detect AMD ROCm (HIP) -- require actual GPU, not just tools installed.+ # NVIDIA takes precedence for automatic selection: when an NVIDIA GPU is+ # usable, skip ROCm probing so co-installed ROCm tools cannot misroute the+ # host (PR 6174). An explicit ROCm request opts into the probe so mixed-GPU+ # hosts can select their AMD bundle.def _amd_smi_has_gpu(stdout: str) -> bool:"""Check for 'GPU: <number>' data rows, not just a table header."""@@ -2543,7 +2612,7 @@ def detect_host() -> HostInfo:has_rocm = Falserocm_gfx_target: str | None = Nonerocm_gfx_targets: list[str] = []- if is_linux and not has_usable_nvidia:+ if is_linux and (probe_rocm_with_nvidia or not has_usable_nvidia):# WSL2 ROCDXG: the system rocminfo enumerates the GPU over /dev/dxg# only when HSA_ENABLE_DXG_DETECTION=1 (a no-op on bare metal), and# rocminfo can live only under /opt/rocm/bin (the profile.d PATH@@ -2583,7 +2652,7 @@ def detect_host() -> HostInfo:rocm_gfx_targets = _list_rocm_gfx_targets(_result.stdout)rocm_gfx_target = _pick_rocm_gfx_target(_result.stdout)break- elif is_windows and not has_usable_nvidia:+ elif is_windows and (probe_rocm_with_nvidia or not has_usable_nvidia):# Windows: prefer active probes that validate GPU presence.# hipinfo / amd-smi are often NOT on PATH -- the HIP SDK installer# sets HIP_PATH / ROCM_PATH but does not always add the bin dir to@@ -5897,6 +5966,25 @@ def persisted_llama_backend(llama_backend: str | None, choice: AssetChoice) -> sreturn llama_backend+def persisted_marker_backend_request(backend_request: str | None, choice: AssetChoice) -> str:+ """The backend choice to record for an install that landed ``choice``.++ Same rule as persisted_llama_backend, generalized: record the request only when+ the install actually honours it. A request that ended somewhere else -- cpu or+ vulkan on macOS, where the universal Metal bundle is the only build -- is stored+ as automatic, so the next update re-detects instead of re-asserting a choice+ this host never applied. "auto" is stored explicitly rather than omitted: absent+ means "written before this field existed", which reads back as the derived+ legacy choice, not as detection.+ """+ effective = backend_for_install_kind(choice.install_kind)+ if backend_request in (None, "auto"):+ return "auto"+ if effective is not None and effective != backend_request:+ return "auto"+ return backend_request++def write_prebuilt_metadata(install_dir: Path,*,@@ -5908,6 +5996,7 @@ def write_prebuilt_metadata(prebuilt_fallback_used: bool,force_cpu: bool = False,llama_backend: str | None = None,+ backend_request: str | None = None,rocm_gfx: str | None = None,) -> None:source_asset_name, source_sha256 = selected_source_archive_metadata(@@ -5938,9 +6027,12 @@ def write_prebuilt_metadata(# 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,- # Explicit Vulkan is recorded as "vulkan"; automatic Windows AMD routing is- # recorded as "auto" so runtime recovery can distinguish them.+ # Kept for older Studio versions that only understand Vulkan overrides."llama_backend": _persisted_backend,+ # What the installed bundle runs on.+ "backend": backend_for_install_kind(choice.install_kind),+ # What future updates should preserve. "auto" re-detects.+ "backend_request": persisted_marker_backend_request(backend_request, choice),# The AMD gfx an AUTOMATIC route was decided on. A Vulkan asset name carries# no arch, and the Windows driver-only hosts that reach Vulkan automatically# have no probe (hipinfo/amd-smi absent), so the updater would re-detect a@@ -6038,79 +6130,6 @@ def _write_marker(marker_path: Path, marker: dict) -> bool:return False-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(encoding = "utf-8"))- 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- if not _write_marker(marker_path, marker):- # Losing this lets the updater re-route a deliberate CPU user onto a- # GPU/Vulkan bundle (#7213), so warn loudly; do not fail setup over it,- # now that an unexpected exit no longer source builds.- log(- f"WARNING: could not record force_cpu={persist_force_cpu} in {marker_path}; "- "a later update may not re-assert this choice"- )- return- log(f"existing install reused; recorded force_cpu={persist_force_cpu} from this run")---def sync_marker_llama_backend(install_dir: Path, llama_backend: str | None) -> None:- """Sync the persisted llama.cpp backend when the bundle is reused unchanged."""- marker_path = install_dir / "UNSLOTH_PREBUILT_INFO.json"- try:- marker = json.loads(marker_path.read_text(encoding = "utf-8"))- except (OSError, ValueError):- return- if not isinstance(marker, dict) or marker.get("llama_backend") == llama_backend:- return- if llama_backend is None:- marker.pop("llama_backend", None)- else:- marker["llama_backend"] = llama_backend- if not _write_marker(marker_path, marker):- log(- f"WARNING: could not record llama_backend={llama_backend!r} in {marker_path}; "- "a later update may not re-assert this choice"- )- return- log(f"existing install reused; recorded llama_backend={llama_backend!r} from this run")---def sync_marker_rocm_gfx(install_dir: Path, rocm_gfx: str | None) -> None:- """Sync the routing AMD arch when the bundle is reused unchanged. A Vulkan- asset name carries no arch, so a reuse that skipped write_prebuilt_metadata- would leave an automatic marker the next update cannot route from."""- if not rocm_gfx:- return- marker_path = install_dir / "UNSLOTH_PREBUILT_INFO.json"- try:- marker = json.loads(marker_path.read_text(encoding = "utf-8"))- except (OSError, ValueError):- return- if not isinstance(marker, dict) or marker.get("rocm_gfx") == rocm_gfx:- return- # Only the automatic route needs it: elsewhere the asset names the arch, and a- # stale one would outlive the GPU it describes.- if marker.get("llama_backend") != "auto":- return- marker["rocm_gfx"] = rocm_gfx- if not _write_marker(marker_path, marker):- log(- f"WARNING: could not record rocm_gfx={rocm_gfx!r} in {marker_path}; "- "a later update may not reproduce this GPU routing"- )--def recorded_ggml_tree(approved_checksums: ApprovedReleaseChecksums, choice: AssetChoice) -> str | None:@@ -6126,31 +6145,98 @@ def recorded_ggml_tree(return tree if choice.repo == approved_checksums.repo else None-def sync_marker_ggml_tree(install_dir: Path, ggml_tree: str | None) -> None:- """Backfill the ggml tree id when the bundle is reused unchanged.+def _marker_selection_patch(+ marker: dict,+ *,+ choice: AssetChoice,+ backend_request: str | None,+ persist_force_cpu: bool,+ persist_llama_backend: str | None,+ ggml_tree: str | None,+ rocm_gfx: str | None,+) -> dict:+ """The fields a reused install must still take from this run.++ Everything write_prebuilt_metadata records about *how* the install was chosen+ belongs here too, because "the bundle is already correct" does not mean the+ choice behind it is unchanged: someone can switch a CUDA install to CPU and land+ on the very bundle detection would have picked, and only these fields stop the+ next update from routing it straight back.+ """+ patch: dict = {}+ if bool(marker.get("force_cpu")) != persist_force_cpu:+ patch["force_cpu"] = persist_force_cpu+ if marker.get("llama_backend") != persist_llama_backend:+ # None means "no legacy override", which older readers spell as absent.+ patch["llama_backend"] = persist_llama_backend+ effective = backend_for_install_kind(choice.install_kind)+ if effective is not None and marker.get("backend") != effective:+ patch["backend"] = effective+ recorded_request = persisted_marker_backend_request(backend_request, choice)+ if marker.get("backend_request") != recorded_request:+ patch["backend_request"] = recorded_request+ # Unlike the fields above, None here means "this release declares none"+ # (upstream ggml-org tags), not "clear it".+ if ggml_tree and marker.get("ggml_tree") != ggml_tree:+ patch["ggml_tree"] = ggml_tree+ # Only an automatic route needs the arch remembered: elsewhere the asset names+ # it, and a stale copy would outlive the GPU it describes.+ automatic = patch.get("llama_backend", marker.get("llama_backend")) == "auto"+ if rocm_gfx and automatic and marker.get("rocm_gfx") != rocm_gfx:+ patch["rocm_gfx"] = rocm_gfx+ return patch+++def sync_marker_selection(+ install_dir: Path,+ *,+ choice: AssetChoice,+ backend_request: str | None,+ persist_force_cpu: bool = False,+ persist_llama_backend: str | None = None,+ ggml_tree: str | None = None,+ rocm_gfx: str | None = None,+) -> None:+ """Record this run's selection on a marker whose bundle was reused unchanged.- write_prebuilt_metadata only runs on a real install, so without this an- already-current install would keep a tree-less marker forever. Unlike- llama_backend, None means "the release declared none" (upstream ggml-org- tags), not "clear it".+ One write for every field rather than one per field: these are read together by+ the updater, and a partial refresh (say force_cpu recorded but backend_request+ not) describes an install nobody asked for. Best-effort throughout -- the+ install is already valid, so a read-only or full disk warns instead of failing+ setup over metadata."""- if not isinstance(ggml_tree, str) or not ggml_tree:- returnmarker_path = install_dir / "UNSLOTH_PREBUILT_INFO.json"try:marker = json.loads(marker_path.read_text(encoding = "utf-8"))except (OSError, ValueError):return- if not isinstance(marker, dict) or marker.get("ggml_tree") == ggml_tree:+ if not isinstance(marker, dict):+ return+ patch = _marker_selection_patch(+ marker,+ choice = choice,+ backend_request = backend_request,+ persist_force_cpu = persist_force_cpu,+ persist_llama_backend = persist_llama_backend,+ ggml_tree = ggml_tree,+ rocm_gfx = rocm_gfx,+ )+ if not patch:return- marker["ggml_tree"] = ggml_tree+ for key, value in patch.items():+ if value is None and key == "llama_backend":+ marker.pop(key, None)+ else:+ marker[key] = valueif not _write_marker(marker_path, marker):+ # Losing this lets the next update re-route a deliberate choice (#7213), so+ # say so loudly; do not fail an otherwise good install over it.log(- f"WARNING: could not record ggml_tree={ggml_tree!r} in {marker_path}; "- "slim whisper pairing will fall back to the tag suffix"+ f"WARNING: could not record {sorted(patch)} in {marker_path}; "+ "a later update may not re-assert this choice")return- log(f"existing install reused; recorded ggml_tree={ggml_tree!r} from this run")+ log(f"existing install reused; recorded {patch} from this run")def expected_install_fingerprint(@@ -6463,6 +6549,7 @@ def validate_prebuilt_choice(quantized_path: Path,force_cpu: bool = False,llama_backend: str | None = None,+ backend_request: str | None = None,rocm_gfx: str | None = None,) -> tuple[Path, Path]:source_repo, source_ref, source_archive, exact_source = preferred_source_archive(@@ -6510,6 +6597,7 @@ def validate_prebuilt_choice(prebuilt_fallback_used = prebuilt_fallback_used,force_cpu = force_cpu,llama_backend = llama_backend,+ backend_request = backend_request,rocm_gfx = rocm_gfx,)# Hashless external prebuilts are not in the approved-sha256@@ -6601,6 +6689,7 @@ def validate_prebuilt_attempts(existing_install_dir: Path | None = None,force_cpu: bool = False,llama_backend: str | None = None,+ backend_request: str | None = None,rocm_gfx: str | None = None,) -> tuple[AssetChoice, Path, bool]:attempt_list = list(attempts)@@ -6672,6 +6761,7 @@ def validate_prebuilt_attempts(quantized_path = quantized_path,force_cpu = force_cpu,llama_backend = llama_backend,+ backend_request = backend_request,rocm_gfx = rocm_gfx,)except Exception as exc:@@ -6698,29 +6788,51 @@ def validate_prebuilt_attempts(raise PrebuiltFallback("no prebuilt bundle passed validation")-def _normalized_llama_backend(value: str | None) -> str | None:- if not value:- return None- backend = value.strip().lower()- if backend in {"vulkan", "hip", "rocm", "cpu"}:- return "hip" if backend == "rocm" else backend- return None+def llama_backend_from_env() -> str | None:+ """Read the backend preference from UNSLOTH_LLAMA_CPP_BACKEND."""+ return normalize_backend_request(os.environ.get("UNSLOTH_LLAMA_CPP_BACKEND"))-def llama_backend_from_env() -> str | None:- """Read an explicit llama.cpp backend preference from the environment.+def resolved_llama_backend(llama_backend: str | None = None) -> str | None:+ """The backend this run was explicitly told to use: --llama-backend, else the+ env var. None when neither named one we know -- which is distinct from "auto",+ a request to detect that outranks both a stored choice and the legacy+ UNSLOTH_FORCE_VULKAN flag."""+ return normalize_backend_request(llama_backend) or llama_backend_from_env()- ``UNSLOTH_LLAMA_CPP_BACKEND`` is shared with setup.sh/setup.ps1. ``auto`` and- unknown values leave selection automatic. ``cpu`` and ``vulkan`` select those- bundles explicitly, while ``hip``/``rocm`` opt out of automatic Vulkan routing.- """- return _normalized_llama_backend(os.environ.get("UNSLOTH_LLAMA_CPP_BACKEND"))+def persisted_backend_request(install_dir: Path | None) -> str:+ """Return the recorded backend choice, with legacy marker compatibility."""+ if install_dir is None:+ return "auto"+ return marker_backend_request(load_prebuilt_metadata(install_dir))-def resolved_llama_backend(llama_backend: str | None = None) -> str | None:- """The explicit backend for this run: --llama-backend, else the env var. None when- neither is set or the value is not a backend name we know."""- return _normalized_llama_backend(llama_backend) or llama_backend_from_env()++def effective_backend_request(+ llama_backend: str | None = None, *, install_dir: Path | None = None+) -> tuple[str, bool]:+ """Return (backend, mandatory) using CLI, env, then marker precedence.++ Explicit requests are mandatory. A stored choice is advisory: it is dropped+ for detection when the hardware or the published bundles no longer offer it.+ """+ explicit = normalize_backend_request(llama_backend)+ if explicit is None:+ explicit = environment_backend_override(+ os.environ.get("UNSLOTH_LLAMA_CPP_BACKEND"),+ os.environ.get("UNSLOTH_FORCE_VULKAN"),+ )+ if explicit is not None:+ return explicit, True+ stored = persisted_backend_request(install_dir)+ if not is_requestable_backend(stored):+ # Written by a newer Studio. Detection would quietly rewrite the choice+ # to "auto", so refuse instead and leave the install exactly as it is.+ raise UnknownBackendRequest(+ f"this install records an unsupported llama.cpp backend choice ({stored!r}); "+ "update Studio before replacing it"+ )+ return stored, Falsedef force_vulkan_requested(llama_backend: str | None = None) -> bool:@@ -6731,17 +6843,13 @@ def force_vulkan_requested(llama_backend: str | None = None) -> bool:llama.cpp backend; the torch/training stack installs separately and still seesthe real GPU."""- backend = resolved_llama_backend(llama_backend)- if backend is not None:- # Authoritative, so =hip is a real opt-out a stale UNSLOTH_FORCE_VULKAN cannot- # overrule.- return backend == "vulkan"- return os.environ.get("UNSLOTH_FORCE_VULKAN", "").strip().lower() in (- "1",- "true",- "yes",- "on",- )+ backend = normalize_backend_request(llama_backend)+ if backend is None:+ backend = environment_backend_override(+ os.environ.get("UNSLOTH_LLAMA_CPP_BACKEND"),+ os.environ.get("UNSLOTH_FORCE_VULKAN"),+ )+ return backend == "vulkan"def _host_rocm_gfx_targets(host: HostInfo) -> list[str]:@@ -6874,24 +6982,30 @@ def _vulkan_only_host(host: HostInfo) -> HostInfo:)-def _vulkan_only_attempts(attempts: Iterable[AssetChoice]) -> list[AssetChoice]:- """Remove generic CPU fallbacks from an explicit Vulkan install."""- return [- attempt- for attempt in attempts- if attempt.install_kind in ("linux-vulkan", "windows-vulkan")- ]+def _backend_only_attempts(attempts: Iterable[AssetChoice], backend: str) -> list[AssetChoice]:+ """Drop the generic fallbacks a plan appends, keeping only ``backend`` bundles."""+ kinds = install_kinds_for_backend(backend)+ return [attempt for attempt in attempts if attempt.install_kind in kinds]-def _vulkan_only_release_plans(plans: Iterable[InstallReleasePlan]) -> list[InstallReleasePlan]:- """Keep release plans that contain an explicit Vulkan bundle."""+def _backend_only_release_plans(+ plans: Iterable[InstallReleasePlan], backend: str+) -> list[InstallReleasePlan]:+ """Keep release plans that contain a bundle for ``backend``.++ A plan lists its attempts best-first and ends in a generic CPU fallback, which is+ right for detection and wrong for a named request: someone who asked for Vulkan+ because their CUDA build crashes is not served by quietly installing CPU. So a+ request that cannot be met fails here, and the caller decides -- a named one+ surfaces the failure, a stored one falls back to detection.+ """filtered = []for plan in plans:- attempts = _vulkan_only_attempts(plan.attempts)+ attempts = _backend_only_attempts(plan.attempts, backend)if attempts:filtered.append(dataclasses_replace(plan, attempts = attempts))if not filtered:- raise PrebuiltFallback("no Vulkan prebuilt bundle attempts were available")+ raise BackendUnavailable(f"no {backend} prebuilt bundle attempts were available")return filtered@@ -6924,15 +7038,14 @@ def _route_to_vulkan_prebuilt(# Host-only test, so a forced Vulkan run can still tell this box would have# routed itself to Vulkan anyway.amd_no_hip_host = _should_auto_vulkan_for_amd_windows(host, published_repo)- # Auto-fall back only when the run named no backend: an explicit hip/cpu is the opt-out.- auto_no_hip = explicit_backend is None and amd_no_hip_host+ # Auto-fall back only when the run named no accelerator: an explicit hip/cpu/cuda is+ # the opt-out. "auto" names detection itself, so it keeps both automatic routes.+ detecting = explicit_backend in (None, "auto")+ auto_no_hip = detecting and amd_no_hip_host# No PHYSICAL NVIDIA, not merely no usable one: Vulkan ignores CUDA_VISIBLE_DEVICES, so# auto-routing a host that hides its NVIDIA card would let it grab the reserved GPU.auto_intel = (- explicit_backend is None- and host.has_intel_gpu- and not host.has_physical_nvidia- and not host.has_rocm+ detecting and host.has_intel_gpu and not host.has_physical_nvidia and not host.has_rocm)if force_cpu or not (forced or auto_intel or auto_no_hip):return host, published_repo, published_release_tag, None@@ -7139,48 +7252,170 @@ def _fail_no_space(reason: str) -> None:raise SystemExit(EXIT_NO_SPACE)-def install_prebuilt(- install_dir: Path,- llama_tag: str,+@dataclass+class BackendSelection:+ """The install plan for one backend request."""++ backend: str | None+ host: HostInfo+ published_repo: str+ published_release_tag: str+ requested_tag: str+ release_plans: list[InstallReleasePlan]+ persist_llama_backend: str | None+ persist_rocm_gfx: str | None++ @property+ def choice(self) -> AssetChoice | None:+ """The bundle this plan installs first, or None when it found none."""+ plans = self.release_plans+ return plans[0].attempts[0] if plans and plans[0].attempts else None+++@dataclass+class BackendRoute:+ """Where a backend request points this host, before any network call."""++ backend: str | None+ host: HostInfo+ published_repo: str+ published_release_tag: str+ persist_llama_backend: str | None+ persist_rocm_gfx: str | None+++def route_backend_request(+ *,+ backend: str | None,published_repo: str,published_release_tag: str,- *,override_has_rocm: bool = False,override_rocm_gfx: str | None = None,- force_cpu: bool = False,- persist_force_cpu: bool = False,- llama_backend: str | None = None,- 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.- if resolved_llama_backend(llama_backend) == "cpu":- force_cpu = True- persist_force_cpu = True- host = detect_host()- host = _apply_host_overrides(- host,+ cpu_mechanism: bool = False,+ host: HostInfo | None = None,+) -> BackendRoute:+ """Apply a backend request to the host profile without fetching releases."""+ if host is None:+ detected_host = (+ detect_host(probe_rocm_with_nvidia = True) if backend == "rocm" else detect_host()+ )+ elif backend == "rocm" and host.has_usable_nvidia and not host.has_rocm:+ # The shared automatic profile deliberately skips AMD probes once CUDA+ # is usable. Re-probe for an explicit ROCm option or environment request.+ detected_host = detect_host(probe_rocm_with_nvidia = True)+ else:+ detected_host = host+ if backend == "rocm":+ # Explicit ROCm must not let normal NVIDIA precedence generate CUDA+ # attempts that strict backend filtering then discards.+ detected_host = dataclasses_replace(+ detected_host,+ has_physical_nvidia = False,+ has_usable_nvidia = False,+ )+ force_cpu = cpu_mechanism or backend == "cpu"+ resolved_host = _apply_host_overrides(+ detected_host,override_has_rocm = override_has_rocm,override_rocm_gfx = override_rocm_gfx,force_cpu = force_cpu,)- # An explicit Vulkan choice only. The Windows-AMD auto-fallback is a rescue- # from a missing HIP arch, so it must keep the CPU plans it can still use.- strict_vulkan = force_vulkan_requested(llama_backend) and not force_cpu and not host.is_macos# Read before the route, which rewrites the host to Vulkan-only and drops the AMD# arch. Kept in the marker so the next update forwards the same --rocm-gfx.- persist_rocm_gfx = _active_rocm_gfx_target(host)- host, published_repo, published_release_tag, persist_llama_backend = _route_to_vulkan_prebuilt(- host,+ persist_rocm_gfx = _active_rocm_gfx_target(resolved_host)+ routed_host, repo, release_tag, persist_llama_backend = _route_to_vulkan_prebuilt(+ resolved_host,published_repo,published_release_tag,force_cpu = force_cpu,- llama_backend = llama_backend,+ llama_backend = backend,)+ return BackendRoute(+ backend = backend,+ host = routed_host,+ published_repo = repo,+ published_release_tag = release_tag,+ persist_llama_backend = persist_llama_backend,+ persist_rocm_gfx = persist_rocm_gfx,+ )+++def select_backend_install(+ *,+ backend: str | None,+ llama_tag: str,+ published_repo: str,+ published_release_tag: str,+ override_has_rocm: bool = False,+ override_rocm_gfx: str | None = None,+ cpu_mechanism: bool = False,+ host: HostInfo | None = None,+ route: BackendRoute | None = None,+) -> BackendSelection:+ """Resolve bundles for a backend, or raise BackendUnavailable if none match."""+ if route is None:+ route = route_backend_request(+ backend = backend,+ published_repo = published_repo,+ published_release_tag = published_release_tag,+ override_has_rocm = override_has_rocm,+ override_rocm_gfx = override_rocm_gfx,+ cpu_mechanism = cpu_mechanism,+ host = host,+ )+ requested_tag, release_plans = resolve_simple_install_release_plans(+ llama_tag, route.host, route.published_repo, route.published_release_tag+ )+ # macOS publishes one universal Metal bundle, so there is nothing to hold a+ # request to; setup.sh says as much for cpu and vulkan there rather than failing.+ if route.backend in CONCRETE_BACKENDS and not route.host.is_macos:+ release_plans = _backend_only_release_plans(release_plans, route.backend)+ return BackendSelection(+ backend = route.backend,+ host = route.host,+ published_repo = route.published_repo,+ published_release_tag = route.published_release_tag,+ requested_tag = requested_tag,+ release_plans = release_plans,+ persist_llama_backend = route.persist_llama_backend,+ persist_rocm_gfx = route.persist_rocm_gfx,+ )+++def install_prebuilt(+ install_dir: Path,+ llama_tag: str,+ published_repo: str,+ published_release_tag: str,+ *,+ override_has_rocm: bool = False,+ override_rocm_gfx: str | None = None,+ force_cpu: bool = False,+ persist_force_cpu: bool = False,+ llama_backend: str | None = None,+ instruction_cleanup_root: Path | None = None,+) -> None:choice: AssetChoice | None = None+ # The failure handler can run before selection assigns these.+ host: HostInfo | None = None+ backend = "auto"+ backend_mandatory = Falsecleanup_root = install_dir if instruction_cleanup_root is None else instruction_cleanup_roottry:with install_lock(install_lock_path(install_dir)):+ # Read and plan from the marker under the install lock so a waiting+ # update cannot undo a concurrent backend switch.+ backend, backend_mandatory = effective_backend_request(+ llama_backend, install_dir = install_dir+ )+ if backend != "auto" and not backend_mandatory:+ log(f"honouring the backend recorded by this install: {backend}")+ # Preserve caller flags in case a stale stored choice must be discarded.+ caller_force_cpu, caller_persist_force_cpu = force_cpu, persist_force_cpu+ # A deliberate CPU request must persist across updates (#7213).+ if backend == "cpu":+ force_cpu = True+ persist_force_cpu = Trueif (install_dir / "UNSLOTH_PREBUILT_INFO.json").is_file():removed = remove_agent_instruction_files(cleanup_root)if removed:@@ -7195,6 +7430,7 @@ def install_prebuilt(log(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. A# Vulkan host is rewritten above so either resolver takes its Vulkan@@ -7223,31 +7459,81 @@ def install_prebuilt(# problem a source build only makes worse, so those stay EXIT_ERROR# alongside resolver bugs. ENOSPC still reaches EXIT_NO_SPACE via# _environment_fatal_reason in __main__.+ def _select(requested_backend: str | None) -> BackendSelection:+ nonlocal host+ # Routing is deliberately outside the conversion below: it makes no+ # network call, so letting it be caught here would report a bug in+ # host detection as a release-listing failure and source build over+ # it.+ route = route_backend_request(+ backend = requested_backend,+ published_repo = published_repo,+ published_release_tag = published_release_tag,+ override_has_rocm = override_has_rocm,+ override_rocm_gfx = override_rocm_gfx,+ cpu_mechanism = force_cpu,+ )+ host = route.host+ try:+ return select_backend_install(+ backend = route.backend,+ llama_tag = llama_tag,+ published_repo = route.published_repo,+ published_release_tag = route.published_release_tag,+ route = route,+ )+ except (BusyInstallConflict, PrebuiltFallback):+ raise+ except (+ urllib.error.URLError,+ ssl.SSLError,+ ConnectionError,+ TimeoutError,+ RuntimeError,+ ValueError,+ ) as exc:+ raise PrebuiltFallback(+ f"failed to inspect published releases in "+ f"{published_repo or DEFAULT_PUBLISHED_REPO}: {exc}"+ ) from exc+try:- requested_tag, release_plans = resolve_simple_install_release_plans(- llama_tag,- host,- published_repo,- published_release_tag,+ selection = _select(backend)+ except BackendUnavailable:+ if backend_mandatory:+ # The caller named this backend, so installing a different one+ # silently is worse than reporting that it cannot be served.+ raise+ # Re-detect when hardware or published bundles invalidate a stored choice.+ log(+ f"the {backend} backend recorded by this install is not available here; "+ "falling back to hardware detection")- except (BusyInstallConflict, PrebuiltFallback):- raise- except (- urllib.error.URLError,- ssl.SSLError,- ConnectionError,- TimeoutError,- RuntimeError,- ValueError,- ) as exc:- raise PrebuiltFallback(- f"failed to inspect published releases in "- f"{published_repo or DEFAULT_PUBLISHED_REPO}: {exc}"- ) from exc- if strict_vulkan:- # Upstream plans append CPU as a generic fallback. An explicit- # Vulkan selection must fail instead of silently installing it.- release_plans = _vulkan_only_release_plans(release_plans)+ backend = "auto"+ # Restore caller flags before detection chooses a replacement.+ force_cpu, persist_force_cpu = caller_force_cpu, caller_persist_force_cpu+ selection = _select(backend)+ host = selection.host+ published_repo = selection.published_repo+ published_release_tag = selection.published_release_tag+ requested_tag = selection.requested_tag+ release_plans = selection.release_plans+ persist_llama_backend = selection.persist_llama_backend+ persist_rocm_gfx = selection.persist_rocm_gfx+ persist_backend_request = backend++ def _record_reused_selection(plan: InstallReleasePlan, reused: AssetChoice) -> None:+ """Update selection fields when the existing bundle is reused."""+ sync_marker_selection(+ install_dir,+ choice = reused,+ backend_request = persist_backend_request,+ persist_force_cpu = persist_force_cpu,+ persist_llama_backend = persisted_llama_backend(persist_llama_backend, reused),+ ggml_tree = recorded_ggml_tree(plan.approved_checksums, reused),+ rocm_gfx = persist_rocm_gfx,+ )+if release_plans and existing_install_matches_plan(install_dir, host, release_plans[0]):current = release_plans[0]if diffusion_visual_server_backfill_needed(install_dir, host, current.attempts[0]):@@ -7260,18 +7546,8 @@ 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)- sync_marker_llama_backend(- install_dir,- persisted_llama_backend(persist_llama_backend, current.attempts[0]),- )- sync_marker_ggml_tree(- install_dir,- recorded_ggml_tree(current.approved_checksums, current.attempts[0]),- )- sync_marker_rocm_gfx(install_dir, persist_rocm_gfx)+ # Record a changed choice even when the bundle already matches.+ _record_reused_selection(current, current.attempts[0])returnwith scratch_dir("unsloth-llama-prebuilt-") as work_dir:probe = lazy_validation_model(@@ -7305,16 +7581,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)- sync_marker_llama_backend(- install_dir,- persisted_llama_backend(persist_llama_backend, choice),- )- sync_marker_ggml_tree(- install_dir,- recorded_ggml_tree(plan.approved_checksums, choice),- )- sync_marker_rocm_gfx(install_dir, persist_rocm_gfx)+ _record_reused_selection(plan, choice)returnlog("selected "@@ -7338,16 +7605,13 @@ def install_prebuilt(# Persist only the deliberate choice, not a transient fallback.force_cpu = persist_force_cpu,llama_backend = persist_llama_backend,+ backend_request = persist_backend_request,rocm_gfx = persist_rocm_gfx,)except ExistingInstallSatisfied as satisfied:# Third reuse path: the reinstall was skipped, so# write_prebuilt_metadata does not run here either.- sync_marker_ggml_tree(- install_dir,- recorded_ggml_tree(plan.approved_checksums, satisfied.choice),- )- sync_marker_rocm_gfx(install_dir, persist_rocm_gfx)+ _record_reused_selection(plan, satisfied.choice)returnexcept PrebuiltFallback as exc:if _environment_fatal_reason(exc):@@ -7384,20 +7648,37 @@ def install_prebuilt(log("prebuilt install path is blocked by an in-use llama.cpp install")log(f"prebuilt busy reason: {exc}")raise SystemExit(EXIT_BUSY) from exc+ except UnknownBackendRequest as exc:+ # EXIT_ERROR, never the source fallback: detection would replace a choice+ # this build cannot read, which is the one outcome refusing must prevent.+ log(f"prebuilt install refused: {exc}")+ raise SystemExit(EXIT_ERROR) from excexcept PrebuiltFallback as exc:fatal = _environment_fatal_reason(exc)if fatal:log(f"prebuilt install failed: {fatal}")_log_disk_space_help()raise SystemExit(EXIT_NO_SPACE) from exc- log("prebuilt install path failed; falling back to source build")+ # A stored choice that could not be served was already replaced by "auto"+ # above, so a concrete name here is one this run must not walk away from.+ preserve_backend = backend in CONCRETE_BACKENDS and host is not None and not host.is_macos+ log(+ "prebuilt install failed; preserving the selected backend"+ if preserve_backend+ else "prebuilt install path failed; falling back to source build"+ )log(f"prebuilt fallback reason: {exc}")# Diagnostics must never change the verdict: a probe that raises here# would replace the fallback with EXIT_ERROR, which never source builds.try:- print(collect_system_report(host, choice, install_dir))+ if host is not None:+ print(collect_system_report(host, choice, install_dir))except Exception as report_exc:log(f"system report unavailable: {report_exc}")+ if preserve_backend:+ # A concrete choice must not become a hardware-selected source build.+ log(f"the {backend} backend selection was preserved; source fallback was not started")+ raise SystemExit(EXIT_BACKEND_UNAVAILABLE) from excraise SystemExit(EXIT_FALLBACK) from exc@@ -7473,14 +7754,15 @@ def parse_args() -> argparse.Namespace:)parser.add_argument("--llama-backend",- choices = ("vulkan",),+ choices = (*REQUESTABLE_BACKENDS, "hip"),help = (- "Force the llama.cpp prebuilt backend. vulkan installs the Vulkan "- "bundle and records the choice so Studio updates keep it. It is ignored "- "on macOS, which uses Metal, and fails closed on Windows arm64 when no "- "compatible Vulkan bundle is published. "- "Same effect as UNSLOTH_LLAMA_CPP_BACKEND=vulkan / "- "UNSLOTH_FORCE_VULKAN=1."+ "Install the llama.cpp prebuilt for this backend and record the choice, "+ "so later updates keep it instead of re-detecting. cuda and rocm (alias "+ "hip) also opt out of the automatic Vulkan routes. A backend with no "+ "bundle for this host fails rather than installing a different one; "+ "auto restores hardware detection and clears a recorded choice. Ignored "+ "on macOS, which has only the universal Metal build. Same effect as "+ "UNSLOTH_LLAMA_CPP_BACKEND."),)resolve_group = parser.add_mutually_exclusive_group()@@ -7515,6 +7797,16 @@ def parse_args() -> argparse.Namespace:"fork). Use --output-format json."),)+ resolve_group.add_argument(+ "--resolve-backends",+ nargs = "?",+ const = "latest",+ help = (+ "Report every llama.cpp backend installable on this host, plus what "+ "--install-dir currently runs, without downloading. Feeds the Studio "+ "backend picker. Use --output-format json."+ ),+ )resolve_group.add_argument("--validate-install",metavar = "DIR",@@ -7567,9 +7859,129 @@ def emit_resolver_output(payload: dict[str, Any], *, output_format: str) -> Noneprint(json.dumps(payload, sort_keys = True))+def requested_backend_arg(args: argparse.Namespace) -> str | None:+ """Return the requested backend, treating --force-cpu as an explicit choice."""+ if args.llama_backend:+ return args.llama_backend+ return "cpu" if args.force_cpu else None+++def _selection_payload(selection: BackendSelection) -> dict[str, Any]:+ choice = selection.choice+ if choice is None:+ return {"prebuilt_available": False, "repo": selection.published_repo}+ plan = selection.release_plans[0]+ return {+ "prebuilt_available": True,+ "repo": selection.published_repo,+ "release_tag": plan.release_tag,+ "llama_tag": plan.llama_tag,+ "asset": choice.name,+ "install_kind": choice.install_kind,+ "backend": backend_for_install_kind(choice.install_kind),+ }+++def _resolve_prebuilt_payload(+ requested_tag: str, *, backend: str | None, args: argparse.Namespace+) -> dict[str, Any]:+ """--resolve-prebuilt for one backend, through the install path's own selector."""+ route = route_backend_request(+ backend = resolved_llama_backend(backend),+ published_repo = args.published_repo,+ published_release_tag = args.published_release_tag or "",+ override_has_rocm = args.has_rocm,+ override_rocm_gfx = args.rocm_gfx,+ cpu_mechanism = args.cpu_fallback,+ )+ try:+ return _selection_payload(+ select_backend_install(+ backend = route.backend,+ llama_tag = requested_tag,+ published_repo = route.published_repo,+ published_release_tag = route.published_release_tag,+ route = route,+ )+ )+ except PrebuiltFallback:+ return {"prebuilt_available": False, "repo": route.published_repo}+++def resolve_backends_payload(+ requested_tag: str,+ *,+ args: argparse.Namespace,+ install_dir: Path | None = None,+) -> dict[str, Any]:+ """Resolve every requestable backend against the installed release.++ One metadata snapshot answers all of them: the picker asks about five backends+ at once, and re-listing the same release five times is both slow and a way for+ the five answers to disagree with each other.+ """+ host = detect_host()+ marker = load_prebuilt_metadata(install_dir) if install_dir is not None else None+ installed_repo = (marker or {}).get("published_repo")+ installed_release = (marker or {}).get("release_tag") or (marker or {}).get("tag")+ pinned_to = args.published_release_tag or installed_release or ""++ entries: list[dict[str, Any]] = []+ with _cached_metadata_fetches():+ # macOS publishes one universal Metal bundle, so there is nothing to pick.+ for backend in ("auto",) if host.is_macos else REQUESTABLE_BACKENDS:+ entry: dict[str, Any] = {"backend": backend}+ try:+ selection = select_backend_install(+ backend = backend,+ llama_tag = requested_tag,+ published_repo = args.published_repo,+ published_release_tag = pinned_to,+ override_has_rocm = args.has_rocm,+ override_rocm_gfx = args.rocm_gfx,+ host = host,+ )+ except BackendUnavailable as exc:+ entry.update(available = False, reason = "unavailable", detail = str(exc))+ except PrebuiltFallback as exc:+ entry.update(available = False, reason = "no_prebuilt", detail = str(exc))+ except Exception as exc: # noqa: BLE001 - one backend must not sink the list+ entry.update(available = False, reason = "error", detail = str(exc))+ else:+ payload = _selection_payload(selection)+ entry.update(+ {+ key: payload.get(key)+ for key in ("repo", "release_tag", "llama_tag", "asset", "install_kind")+ }+ )+ # What this option installs today, so "auto" can be labelled with it.+ entry["resolved_backend"] = payload.get("backend")+ entry["available"] = bool(payload.get("prebuilt_available"))+ if entry["available"] and (+ (installed_repo and entry["repo"] != installed_repo)+ or (installed_release and entry["release_tag"] != installed_release)+ ):+ # Slim whisper.cpp bundles are paired to the installed release,+ # so a switch that moves llama.cpp is an update in disguise.+ entry["available"] = False+ entry["detail"] = "switching this backend would leave the installed release"+ if not entry["available"]:+ entry["reason"] = "no_prebuilt"+ entries.append(entry)+ if entries and all(entry.get("reason") == "error" for entry in entries):+ # Never cache a transient outage as "nothing is installable here".+ raise RuntimeError("could not resolve any llama.cpp backend")+ return {+ "requested_tag": normalized_requested_llama_tag(requested_tag),+ "pinned_release_tag": pinned_to or None,+ "platform": {"system": host.system, "machine": host.machine, "is_macos": host.is_macos},+ "backends": entries,+ }++def main() -> int:args = parse_args()- cpu_backend_requested = resolved_llama_backend(args.llama_backend) == "cpu"if args.validate_install is not None:try:validate_existing_install(@@ -7637,51 +8049,27 @@ 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.- # CPU fallback and explicit CPU choices drop GPU detection. The probe only- # needs the mechanism; persistence belongs to the install path.- _cpu_mechanism = args.cpu_fallback or args.force_cpu or cpu_backend_requested- host = _apply_host_overrides(- detect_host(),- override_has_rocm = args.has_rocm,- override_rocm_gfx = args.rocm_gfx,- force_cpu = _cpu_mechanism,+ # Use the install selector without consulting the current marker choice.+ payload = _resolve_prebuilt_payload(+ args.resolve_prebuilt,+ backend = requested_backend_arg(args),+ args = args,)- # Same Vulkan routing the install path applies, so the probe's answer- # matches what would install.- host, repo, release_tag, _persist_llama_backend = _route_to_vulkan_prebuilt(- host,- args.published_repo,- args.published_release_tag or "",- force_cpu = _cpu_mechanism,- llama_backend = args.llama_backend,- )- try:- _requested, plans = resolve_simple_install_release_plans(- args.resolve_prebuilt, host, repo, release_tag- )- if (- force_vulkan_requested(args.llama_backend)- and not _cpu_mechanism- and not host.is_macos- ):- plans = _vulkan_only_release_plans(plans)- choice = plans[0].attempts[0] if plans and plans[0].attempts else None- if choice is None:- payload = {"prebuilt_available": False, "repo": repo}- else:- payload = {- "prebuilt_available": True,- "repo": repo,- "release_tag": plans[0].release_tag,- "llama_tag": plans[0].llama_tag,- "asset": choice.name,- "install_kind": choice.install_kind,- }- except PrebuiltFallback:- payload = {"prebuilt_available": False, "repo": repo}emit_resolver_output(payload, output_format = args.output_format)return EXIT_SUCCESS+ if args.resolve_backends is not None:+ # Resolve every option and the current install in one process.+ emit_resolver_output(+ resolve_backends_payload(+ args.resolve_backends,+ args = args,+ install_dir = (Path(args.install_dir).expanduser() if args.install_dir else None),+ ),+ output_format = args.output_format,+ )+ return EXIT_SUCCESS+if not args.install_dir:raise SystemExit("install_llama_prebuilt.py: --install-dir is required unless --resolve-llama-tag, --resolve-install-tag, or --resolve-source-build is used"@@ -7697,11 +8085,11 @@ def main() -> int:published_release_tag = args.published_release_tag or "",override_has_rocm = args.has_rocm,override_rocm_gfx = args.rocm_gfx,- # Explicit CPU choices persist so the updater re-asserts them.- # --cpu-fallback stays transient and heals to GPU.- force_cpu = args.cpu_fallback or args.force_cpu or cpu_backend_requested,- persist_force_cpu = args.force_cpu or cpu_backend_requested,- llama_backend = args.llama_backend,+ # Only the transient rescue is passed as a mechanism. A deliberate CPU+ # choice arrives as the backend request below, which is what makes it+ # persist; --cpu-fallback stays unrecorded and heals to GPU (#6097).+ force_cpu = args.cpu_fallback,+ llama_backend = requested_backend_arg(args),instruction_cleanup_root = install_arg.absolute(),)return EXIT_SUCCESSdiff --git a/studio/setup.ps1 b/studio/setup.ps1index 4f399d18085..357a538c3b9 100644--- a/studio/setup.ps1+++ b/studio/setup.ps1@@ -132,9 +132,9 @@ function Write-StudioLine {# errors. Only use "master" temporarily when the latest release is missing# support for a new model architecture.#-# UNSLOTH_LLAMA_CPP_BACKEND : "auto" (default), "cpu", "vulkan", "hip", or-# "rocm". "cpu" forces the CPU-only prebuilt. "vulkan" selects Vulkan even-# when CUDA or ROCm is detected. "hip"/"rocm" opts out of automatic Vulkan.+# UNSLOTH_LLAMA_CPP_BACKEND : "auto" (default), "cpu", "cuda", "vulkan",+# "hip", or "rocm". Concrete values select and persist a backend across updates;+# "auto" restores detection. Overrides Studio's Settings > System selection.$DefaultLlamaPrForce = ""$DefaultLlamaSource = "https://github.com/ggml-org/llama.cpp"$DefaultLlamaTag = "latest"@@ -5272,16 +5272,14 @@ $ResolvedSourceRefKind = "tag"$ResolvedLlamaTag = $RequestedLlamaTag$sourceLlamaBackend = "$($env:UNSLOTH_LLAMA_CPP_BACKEND)".Trim().ToLowerInvariant()$sourceLegacyForceVulkan = "$($env:UNSLOTH_FORCE_VULKAN)".Trim().ToLowerInvariant()-$explicitVulkanSourceBuild = (- -not $IsMacOS -and- (- $sourceLlamaBackend -eq "vulkan" -or- (- $sourceLlamaBackend -notin @("cpu", "vulkan", "hip", "rocm") -and- $sourceLegacyForceVulkan -in @("1", "true", "yes", "on")- )- )-)+$explicitLlamaSourceBackend = $null+if (-not $IsMacOS) {+ if ($sourceLlamaBackend -in @("cpu", "cuda", "vulkan", "hip", "rocm")) {+ $explicitLlamaSourceBackend = if ($sourceLlamaBackend -eq "hip") { "rocm" } else { $sourceLlamaBackend }+ } elseif ($sourceLlamaBackend -ne "auto" -and $sourceLegacyForceVulkan -in @("1", "true", "yes", "on")) {+ $explicitLlamaSourceBackend = "vulkan"+ }+}if ($env:UNSLOTH_LLAMA_FORCE_COMPILE -eq "1") {$NeedLlamaSourceBuild = $true@@ -5470,11 +5468,11 @@ if ($LocalLlamaCppSrc) {if ($LocalLlamaCppLinked) {# local directory linked above; skip prebuilt install-} elseif ($explicitVulkanSourceBuild -and $NeedLlamaSourceBuild) {+} elseif ($explicitLlamaSourceBackend -and $NeedLlamaSourceBuild) {Write-StudioLine ""- step "llama.cpp" "Vulkan was explicitly requested, but this installation requires a source build" "Red"- substep "Vulkan source builds are not supported by this installer; use the prebuilt Vulkan bundle or unset the Vulkan override" "Yellow"- Exit-SetupFailure "Vulkan was explicitly requested, but this installation requires a source build, which this installer does not support. Use the prebuilt Vulkan bundle or unset the Vulkan override."+ step "llama.cpp" "$explicitLlamaSourceBackend was explicitly requested, but this installation requires a source build" "Red"+ substep "Explicit backend selection requires a matching prebuilt bundle; allow prebuilts or unset UNSLOTH_LLAMA_CPP_BACKEND" "Yellow"+ Exit-SetupFailure "$explicitLlamaSourceBackend was explicitly requested, but this installation requires a source build. Explicit backend selection requires a matching prebuilt bundle."} elseif ($env:UNSLOTH_LLAMA_FORCE_COMPILE -eq "1") {Write-StudioLine ""substep "UNSLOTH_LLAMA_FORCE_COMPILE=1 -- skipping prebuilt llama.cpp install" "Yellow"@@ -5548,11 +5546,11 @@ if ($LocalLlamaCppLinked) {if ($env:UNSLOTH_LLAMA_RELEASE_TAG) {$prebuiltArgs += @("--published-release-tag", $env:UNSLOTH_LLAMA_RELEASE_TAG)}- # The backend override is case-insensitive and whitespace-trimmed. cpu- # maps to the persisted --force-cpu choice. vulkan is consumed directly- # by install_llama_prebuilt.py and does not change the torch backend.+ # Reporting only: the installer reads UNSLOTH_LLAMA_CPP_BACKEND itself, and+ # it is also the only side that can see a choice recorded in the install+ # marker, so forwarding a second copy from here could only ever disagree+ # with it. The override does not change the torch backend.$llamaBackend = $sourceLlamaBackend- $legacyForceVulkan = $sourceLegacyForceVulkan$windowsArm64 = ($env:OS -eq "Windows_NT" -and(@@ -5560,31 +5558,16 @@ if ($LocalLlamaCppLinked) {"$($env:PROCESSOR_ARCHITEW6432)".ToUpperInvariant() -eq "ARM64"))- $explicitVulkanBackend = $false- if ($llamaBackend -eq "cpu") {- $prebuiltArgs += "--force-cpu"- } elseif ($llamaBackend -eq "vulkan") {+ if ($llamaBackend -eq "vulkan" -or $explicitLlamaSourceBackend -eq "vulkan") {if ($IsMacOS) {Write-StudioLine "[WARN] Vulkan has no effect on macOS; the universal build uses Metal" -ForegroundColor Yellow} elseif ($windowsArm64) {- throw "Vulkan was requested, but no Windows ARM64 Vulkan bundle is published. Unset UNSLOTH_LLAMA_CPP_BACKEND or compile llama.cpp from source."+ throw "Vulkan was requested, but no Windows ARM64 Vulkan bundle is published. Unset UNSLOTH_LLAMA_CPP_BACKEND / UNSLOTH_FORCE_VULKAN or compile llama.cpp from source."} else {- $prebuiltArgs += @("--llama-backend", "vulkan")- $explicitVulkanBackend = $trueWrite-StudioLine " llama.cpp Vulkan selected for GGUF inference; the PyTorch training backend is unchanged" -ForegroundColor Cyan}- } elseif ($llamaBackend -and $llamaBackend -notin @("auto", "hip", "rocm")) {- Write-StudioLine "[WARN] Ignoring UNSLOTH_LLAMA_CPP_BACKEND='$llamaBackend' (expected 'auto', 'cpu', 'vulkan', 'hip', or 'rocm')" -ForegroundColor Yellow- }- if (- -not $IsMacOS -and- $llamaBackend -notin @("cpu", "vulkan", "hip", "rocm") -and- $legacyForceVulkan -in @("1", "true", "yes", "on")- ) {- if ($windowsArm64) {- throw "Vulkan was requested, but no Windows ARM64 Vulkan bundle is published. Unset UNSLOTH_FORCE_VULKAN or compile llama.cpp from source."- }- $explicitVulkanBackend = $true+ } elseif ($llamaBackend -and $llamaBackend -notin @("auto", "cpu", "cuda", "hip", "rocm")) {+ Write-StudioLine "[WARN] Ignoring UNSLOTH_LLAMA_CPP_BACKEND='$llamaBackend' (expected 'auto', 'cpu', 'cuda', 'vulkan', 'hip', or 'rocm')" -ForegroundColor Yellow}$prevEAPPrebuilt = $ErrorActionPreference$ErrorActionPreference = "Continue"@@ -5647,27 +5630,32 @@ if ($LocalLlamaCppLinked) {if (Test-PathQuiet $_cand) { $PreservedLlamaServerFound = $true; break }}if (-not $PreservedLlamaServerFound) { $script:LlamaCppDegraded = $true }- # A preserved CUDA/ROCm/CPU server does not satisfy an explicit Vulkan- # request, and it leaves LlamaCppDegraded false, so without this the- # run reports success on the backend the user asked to replace.- if ($explicitVulkanBackend) {- step "llama.cpp" "Vulkan was explicitly requested, so the installer will not keep the existing backend" "Red"- Exit-SetupFailure "Vulkan was explicitly requested, so the installer will not keep the existing llama.cpp backend."+ # A preserved server may not satisfy an explicit backend request, and+ # it leaves LlamaCppDegraded false. Never report success on an+ # unverified backend after the requested replacement ran out of space.+ if ($explicitLlamaSourceBackend) {+ step "llama.cpp" "$explicitLlamaSourceBackend was explicitly requested, so the installer will not keep an unverified existing backend" "Red"+ Exit-SetupFailure "$explicitLlamaSourceBackend was explicitly requested, so the installer will not keep an unverified existing llama.cpp backend."}+ } elseif ($prebuiltExit -eq 5) {+ step "llama.cpp" "selected backend could not be installed" "Red"+ Write-LlamaFailureLog -Output $prebuiltOutput+ if (Test-Path -LiteralPath $LlamaCppDir) {+ substep "Existing install was restored" "Yellow"+ }+ substep "Check the error above, choose another backend, or retry" "Yellow"+ Exit-SetupFailure "The selected llama.cpp backend could not be installed, so the installer will not substitute a different source backend."} elseif ($prebuiltExit -eq 2) {step "llama.cpp" "prebuilt install failed" "Yellow"Write-LlamaFailureLog -Output $prebuiltOutputif (Test-Path -LiteralPath $LlamaCppDir) {substep "Prebuilt update failed; existing install was restored or cleaned before source build fallback" "Yellow"}- if ($explicitVulkanBackend) {- step "llama.cpp" "Vulkan was explicitly requested, so the installer will not substitute a CUDA, ROCm, or CPU source build" "Red"- substep "Check the download error above or try a different UNSLOTH_LLAMA_RELEASE_TAG" "Yellow"- Exit-SetupFailure "Vulkan was explicitly requested, so the installer will not substitute a CUDA, ROCm, or CPU source build. Check the download error above or try a different UNSLOTH_LLAMA_RELEASE_TAG."- } else {- substep "Prebuilt llama.cpp path unavailable or failed validation -- falling back to source build" "Yellow"- $NeedLlamaSourceBuild = $true- }+ # Exit 2 means no concrete backend was in play: a request the installer+ # could not honour -- named here or recorded in the install marker,+ # which this script cannot see -- exits 5 above instead.+ substep "Prebuilt llama.cpp path unavailable or failed validation -- falling back to source build" "Yellow"+ $NeedLlamaSourceBuild = $true} else {step "llama.cpp" "prebuilt helper failed unexpectedly" "Red"Write-LlamaFailureLog -Output $prebuiltOutputdiff --git a/studio/setup.sh b/studio/setup.shindex 262fca38639..21a5d6c221f 100755--- a/studio/setup.sh+++ b/studio/setup.sh@@ -37,11 +37,10 @@ fi# Only use "master" temporarily when the latest release# is missing support for a new model architecture.#-# UNSLOTH_LLAMA_CPP_BACKEND : "auto" (default), "cpu", "vulkan", "hip", or-# "rocm". "cpu" forces the CPU-only prebuilt. "vulkan"-# selects Vulkan even when CUDA or ROCm is detected.-# "hip"/"rocm" keeps the detected HIP backend and opts-# out of automatic Vulkan fallback.+# UNSLOTH_LLAMA_CPP_BACKEND : "auto" (default), "cpu", "cuda", "vulkan",+# "hip", or "rocm". Concrete values select and persist a+# backend across updates; "auto" restores detection.+# Overrides Studio's Settings > System selection.# ──────────────────────────────────────────────────────────────────────────_DEFAULT_LLAMA_PR_FORCE=""_DEFAULT_LLAMA_SOURCE="https://github.com/ggml-org/llama.cpp"@@ -1916,16 +1915,17 @@ _LLAMA_FORCE_COMPILE="${UNSLOTH_LLAMA_FORCE_COMPILE:-0}"_REQUESTED_LLAMA_TAG="${UNSLOTH_LLAMA_TAG:-${_DEFAULT_LLAMA_TAG}}"_HOST_SYSTEM="$(uname -s 2>/dev/null || true)"_HOST_MACHINE="$(uname -m 2>/dev/null || true)"-_source_backend_choice="$(printf '%s' "${UNSLOTH_LLAMA_CPP_BACKEND:-auto}" | awk '{$1=$1; print tolower($0)}')"+_source_backend_choice="$(printf '%s' "${UNSLOTH_LLAMA_CPP_BACKEND:-}" | awk '{$1=$1; print tolower($0)}')"_source_legacy_force_vulkan="$(printf '%s' "${UNSLOTH_FORCE_VULKAN:-}" | awk '{$1=$1; print tolower($0)}')"-_explicit_vulkan_source_build=false+_explicit_llama_source_backend=""if [ "$_HOST_SYSTEM" != "Darwin" ]; thencase "$_source_backend_choice" in- vulkan) _explicit_vulkan_source_build=true ;;- cpu|hip|rocm) ;;+ hip) _explicit_llama_source_backend="rocm" ;;+ cpu|cuda|rocm|vulkan) _explicit_llama_source_backend="$_source_backend_choice" ;;+ auto) ;;*)case "$_source_legacy_force_vulkan" in- 1|true|yes|on) _explicit_vulkan_source_build=true ;;+ 1|true|yes|on) _explicit_llama_source_backend="vulkan" ;;esac;;esac@@ -2099,10 +2099,10 @@ fiif [ "$_LOCAL_LLAMA_CPP_LINKED" = true ]; then: # local directory linked above; skip prebuilt install-elif [ "$_explicit_vulkan_source_build" = true ] && [ "$_NEED_LLAMA_SOURCE_BUILD" = true ]; then- step "llama.cpp" "Vulkan was explicitly requested, but this installation requires a source build" "$C_ERR"- substep "Vulkan source builds are not supported by this installer; use the prebuilt Vulkan bundle or unset the Vulkan override"- setup_fail 1 "Vulkan was explicitly requested, but this installation requires a source build, which this installer does not support. Use the prebuilt Vulkan bundle or unset the Vulkan override."+elif [ -n "$_explicit_llama_source_backend" ] && [ "$_NEED_LLAMA_SOURCE_BUILD" = true ]; then+ step "llama.cpp" "$_explicit_llama_source_backend was explicitly requested, but this installation requires a source build" "$C_ERR"+ substep "Explicit backend selection requires a matching prebuilt bundle; allow prebuilts or unset UNSLOTH_LLAMA_CPP_BACKEND"+ setup_fail 1 "$_explicit_llama_source_backend was explicitly requested, but this installation requires a source build. Explicit backend selection requires a matching prebuilt bundle."elif [ "$_LLAMA_FORCE_COMPILE" = "1" ]; thenstep "llama.cpp" "UNSLOTH_LLAMA_FORCE_COMPILE=1 -- skipping prebuilt" "$C_WARN"_NEED_LLAMA_SOURCE_BUILD=true@@ -2148,40 +2148,26 @@ else# through to the CPU prebuilt instead of breaking the install._PREBUILT_CMD+=(--has-rocm)fi- # The normalized override affects llama.cpp only, not the training backend.- _llama_backend="$_source_backend_choice"- _legacy_force_vulkan="$_source_legacy_force_vulkan"- _explicit_vulkan_backend=false- case "$_llama_backend" in+ # Reporting only: the installer reads UNSLOTH_LLAMA_CPP_BACKEND itself, and it+ # is also the only side that can see a choice recorded in the install marker,+ # so forwarding a second copy from here could only ever disagree with it. The+ # override affects llama.cpp alone, not the training backend.+ case "$_source_backend_choice" incpu)if [ "$_HOST_SYSTEM" = "Darwin" ]; thenstep "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;;vulkan)if [ "$_HOST_SYSTEM" = "Darwin" ]; thenstep "llama.cpp" "Vulkan has no effect on macOS; the universal build uses Metal" "$C_WARN" >&2else- _PREBUILT_CMD+=(--llama-backend vulkan)- _explicit_vulkan_backend=truestep "llama.cpp" "Vulkan selected for GGUF inference; the PyTorch training backend is unchanged" "$C_OK"fi;;- ""|auto|hip|rocm) ;;- *) step "llama.cpp" "Ignoring UNSLOTH_LLAMA_CPP_BACKEND='$_llama_backend' (expected 'auto', 'cpu', 'vulkan', 'hip', or 'rocm')" "$C_WARN" >&2 ;;+ ""|auto|cuda|hip|rocm) ;;+ *) step "llama.cpp" "Ignoring UNSLOTH_LLAMA_CPP_BACKEND='$_source_backend_choice' (expected 'auto', 'cpu', 'cuda', 'vulkan', 'hip', or 'rocm')" "$C_WARN" >&2 ;;esac- if [ "$_HOST_SYSTEM" != "Darwin" ]; then- case "$_llama_backend" in- cpu|vulkan|hip|rocm) ;;- *)- case "$_legacy_force_vulkan" in- 1|true|yes|on) _explicit_vulkan_backend=true ;;- esac- ;;- esac- fi_PREBUILT_LOG="$(mktemp)"set +eif _is_verbose; then@@ -2221,13 +2207,22 @@ elsesubstep "free up disk or move UNSLOTH_STUDIO_HOME/TMPDIR to a larger volume, then re-run"_LLAMA_CPP_NO_SPACE=true_has_local_llama_server "$LLAMA_CPP_DIR" || _LLAMA_CPP_DEGRADED=true- # A preserved CUDA/ROCm/CPU server does not satisfy an explicit Vulkan- # request, and it leaves _LLAMA_CPP_DEGRADED false, so without this the- # run reports success on the backend the user asked to replace.- if [ "$_explicit_vulkan_backend" = true ]; then- step "llama.cpp" "Vulkan was explicitly requested, so the installer will not keep the existing backend" "$C_ERR"- setup_fail 1 "Vulkan was explicitly requested, so the installer will not keep the existing llama.cpp backend."+ # A preserved server may not satisfy an explicit backend request, and it+ # leaves _LLAMA_CPP_DEGRADED false. Never report success on an unverified+ # backend after the requested replacement ran out of space.+ if [ -n "$_explicit_llama_source_backend" ]; then+ step "llama.cpp" "$_explicit_llama_source_backend was explicitly requested, so the installer will not keep an unverified existing backend" "$C_ERR"+ setup_fail 1 "$_explicit_llama_source_backend was explicitly requested, so the installer will not keep an unverified existing llama.cpp backend."fi+ elif [ "$_PREBUILT_STATUS" -eq 5 ]; then+ step "llama.cpp" "selected backend could not be installed" "$C_ERR"+ print_llama_error_log "$_PREBUILT_LOG"+ rm -f "$_PREBUILT_LOG"+ if [ -d "$LLAMA_CPP_DIR" ]; then+ substep "prebuilt update failed; existing install restored"+ fi+ substep "check the error above, choose another backend, or retry"+ setup_fail 1 "The selected llama.cpp backend could not be installed, so the installer will not substitute a different source backend."elif [ "$_PREBUILT_STATUS" -eq 2 ]; thenstep "llama.cpp" "prebuilt install failed" "$C_WARN"print_llama_error_log "$_PREBUILT_LOG"@@ -2235,14 +2230,11 @@ elseif [ -d "$LLAMA_CPP_DIR" ]; thensubstep "prebuilt update failed; existing install restored"fi- if [ "$_explicit_vulkan_backend" = true ]; then- step "llama.cpp" "Vulkan was explicitly requested, so the installer will not substitute a ROCm or CPU source build" "$C_ERR"- substep "check the download error above or try a different UNSLOTH_LLAMA_RELEASE_TAG"- setup_fail 1 "Vulkan was explicitly requested, so the installer will not substitute a ROCm or CPU source build. Check the download error above or try a different UNSLOTH_LLAMA_RELEASE_TAG."- else- substep "falling back to source build"- _NEED_LLAMA_SOURCE_BUILD=true- fi+ # Exit 2 means no concrete backend was in play: a request the installer+ # could not honour -- named here or recorded in the install marker, which+ # this script cannot see -- exits 5 above instead.+ substep "falling back to source build"+ _NEED_LLAMA_SOURCE_BUILD=trueelsestep "llama.cpp" "prebuilt helper failed unexpectedly" "$C_ERR"print_llama_error_log "$_PREBUILT_LOG"diff --git a/tests/studio/install/test_install_llama_prebuilt_logic.py b/tests/studio/install/test_install_llama_prebuilt_logic.pyindex d333f60d4c0..cafebd97b9b 100644--- a/tests/studio/install/test_install_llama_prebuilt_logic.py+++ b/tests/studio/install/test_install_llama_prebuilt_logic.py@@ -1331,6 +1331,7 @@ def test_install_prebuilt_falls_back_to_older_release_plan(existing_install_dir = None,force_cpu = False,llama_backend = None,+ backend_request = None,rocm_gfx = None,):call_log.append((llama_tag, initial_fallback_used))@@ -2540,6 +2541,7 @@ def test_install_prebuilt_skips_when_older_release_fallback_matches_existing_insexisting_install_dir = None,force_cpu = False,llama_backend = None,+ backend_request = None,rocm_gfx = None,):call_log.append(llama_tag)@@ -2690,6 +2692,7 @@ def test_install_prebuilt_skips_same_release_fallback_attempt_when_installed(quantized_path,force_cpu = False,llama_backend = None,+ backend_request = None,rocm_gfx = None,):attempted_names.append(choice.name)@@ -2819,6 +2822,7 @@ def test_install_prebuilt_same_tag_upstream_failure_uses_older_unsloth_release_pexisting_install_dir = None,force_cpu = False,llama_backend = None,+ backend_request = None,rocm_gfx = None,):attempted.append((llama_tag, release_tag, attempts[0].source_label))@@ -3868,7 +3872,7 @@ C_OK=""; C_WARN=""; C_ERR=""_NEED_LLAMA_SOURCE_BUILD=false_LLAMA_CPP_NO_SPACE=false_LLAMA_CPP_DEGRADED=false-_explicit_vulkan_backend=false+_explicit_llama_backend=""_STUDIO_HOME_IS_CUSTOM=false_STUDIO_OWNED_MARKER=".unsloth-owned"step() { echo "step: $2"; }@@ -3900,7 +3904,13 @@ def _setup_sh_routing_block() -> str:return setup_sh[start : end + len("\n fi\n")]-def _run_setup_sh_routing(status: int, tmp_path: Path, *, install_exists: bool) -> dict[str, str]:+def _run_setup_sh_routing(+ status: int,+ tmp_path: Path,+ *,+ install_exists: bool,+ explicit_backend: str = "",+) -> dict[str, str]:"""Drive the real setup.sh exit-code chain with a stubbed helper result."""llama_dir = tmp_path / "llama.cpp"if install_exists:@@ -3914,6 +3924,7 @@ def _run_setup_sh_routing(status: int, tmp_path: Path, *, install_exists: bool)f'LLAMA_CPP_DIR="{llama_dir}"',f'_PREBUILT_LOG="{log_path}"',f"_PREBUILT_STATUS={status}",+ f'_explicit_llama_source_backend="{explicit_backend}"',_setup_sh_routing_block(),_SETUP_SH_HARNESS_TAIL,]@@ -3932,18 +3943,25 @@ def _run_setup_sh_routing(status: int, tmp_path: Path, *, install_exists: bool)"POSIX script through Git Bash with Windows paths proves nothing about either",)@pytest.mark.parametrize(- "status, expect_source_build, expect_exit",+ "status, explicit_backend, expect_source_build, expect_exit",[- (0, False, 0), # installed and validated- (1, False, 1), # helper error -> fail, never compile- (2, True, 0), # the one status that means "prebuilt unusable, go build"- (3, False, 3), # busy: a source build cannot replace locked binaries- (4, False, 0), # out of disk: compiling needs more, not less- (137, False, 1), # SIGKILL/OOM and anything else -> fail, never compile+ (0, "", False, 0), # installed and validated+ (1, "", False, 1), # helper error -> fail, never compile+ (2, "", True, 0), # automatic selection may fall back to a source build+ # Exit 2 means the installer had no concrete request to honour; a request+ # it could not serve arrives as exit 5 instead, so this branch does not+ # second-guess it from the environment.+ (2, "cuda", True, 0),+ (3, "", False, 3), # busy: a source build cannot replace locked binaries+ (4, "", False, 0), # out of disk: compiling needs more, not less+ (4, "rocm", False, 1), # an old install cannot satisfy an unchecked request+ (5, "", False, 1), # a concrete selection failed; never substitute another+ (5, "cuda", False, 1),+ (137, "", False, 1), # SIGKILL/OOM and anything else -> fail, never compile],)def test_setup_sh_starts_source_build_only_for_expected_prebuilt_exit(- tmp_path, status, expect_source_build, expect_exit+ tmp_path, status, explicit_backend, expect_source_build, expect_exit):"""Behavioural cover for the exit-code routing: runs the real block under bash.@@ -3958,7 +3976,9 @@ def test_setup_sh_starts_source_build_only_for_expected_prebuilt_exit(if shutil.which("bash") is None: # pragma: no cover - CI always has bashpytest.skip("bash is required to exercise the setup.sh routing block")- result = _run_setup_sh_routing(status, tmp_path, install_exists = True)+ result = _run_setup_sh_routing(+ status, tmp_path, install_exists = True, explicit_backend = explicit_backend+ )assert result["returncode"] == expect_exit, resultif expect_source_build:@@ -3967,6 +3987,134 @@ def test_setup_sh_starts_source_build_only_for_expected_prebuilt_exit(assert "source_build=true" not in result["stdout"], result+_SETUP_PS1_HARNESS = """+$ErrorActionPreference = "Stop"+$NeedLlamaSourceBuild = $false+$script:LlamaCppDegraded = $false+$StudioHomeIsCustom = $false+$prebuiltOutput = "boom"+function step { param($a, $b, $c) Write-Output "step: $b" }+function substep { param($a, $b) Write-Output "substep: $a" }+function Write-LlamaFailureLog { param($Output) }+function Mark-StudioOwned { param($Path) }+function Get-InstalledLlamaPrebuiltRelease { param($InstallDir) return $null }+function Test-PathQuiet { param($p) return $false }+function Exit-SetupFailure {+ param($Message, $Code = 1)+ Write-Output "setup_fail: $Code"+ exit $Code+}+"""++_SETUP_PS1_HARNESS_TAIL = """+Write-Output "source_build=$($NeedLlamaSourceBuild.ToString().ToLower())"+"""++requires_pwsh = pytest.mark.skipif(+ shutil.which("pwsh") is None, reason = "pwsh is required to execute the setup.ps1 routing block"+)+++def _setup_ps1_routing_block() -> str:+ setup_ps1 = (PACKAGE_ROOT / "studio" / "setup.ps1").read_text(encoding = "utf-8")+ return _extract_block(setup_ps1, _SETUP_PS1_ROUTING_START, 'retry setup."\n }')+++def _run_setup_ps1_routing(+ status: int,+ tmp_path: Path,+ *,+ install_exists: bool,+ explicit_backend: str = "",+) -> dict[str, str]:+ """Drive the real setup.ps1 exit-code chain, the mirror of _run_setup_sh_routing."""+ llama_dir = tmp_path / "llama.cpp"+ if install_exists:+ llama_dir.mkdir(parents = True, exist_ok = True)+ else:+ tmp_path.mkdir(parents = True, exist_ok = True)++ script = "\n".join(+ [+ _SETUP_PS1_HARNESS,+ f'$LlamaCppDir = "{llama_dir}"',+ f"$prebuiltExit = {status}",+ f'$explicitLlamaSourceBackend = "{explicit_backend}"',+ _setup_ps1_routing_block(),+ _SETUP_PS1_HARNESS_TAIL,+ ]+ )+ script_path = tmp_path / "routing.ps1"+ script_path.write_text(script, encoding = "utf-8")+ completed = subprocess.run(+ [+ shutil.which("pwsh") or "pwsh",+ "-NoProfile",+ "-NonInteractive",+ "-File",+ str(script_path),+ ],+ capture_output = True,+ text = True,+ timeout = 120,+ )+ return {+ "returncode": completed.returncode,+ "stdout": completed.stdout,+ "stderr": completed.stderr,+ }+++@requires_pwsh[email protected]("install_exists", [True, False], ids = ["installed", "fresh"])[email protected]("explicit_backend", ["", "cuda", "rocm", "vulkan", "cpu"])[email protected]("status", [0, 1, 2, 3, 4, 5, 137])+def test_setup_ps1_routing_matches_setup_sh(status, explicit_backend, install_exists, tmp_path):+ """Windows must route an installer exit exactly as Linux does.++ The two scripts are maintained side by side and the assertions above compare their+ SOURCE TEXT, which cannot catch a branch that reads the same and behaves differently+ (a PowerShell `$false` string, an `exit` that does not propagate, a guard whose+ variable was never set). Running both and comparing the decision is what makes+ "the mirrored setup.ps1 does the same" a measurement rather than a claim.++ The decision is two values: the process exit code, and whether a source build was+ queued. Exit 5 must fail closed everywhere -- that is the point of the exit code --+ while exit 2 stays the one automatic path allowed to fall back to a compile.+ """+ if shutil.which("bash") is None: # pragma: no cover - CI always has bash+ pytest.skip("bash is required to compare against the setup.sh routing block")++ sh_dir, ps_dir = tmp_path / "sh", tmp_path / "ps"+ sh_dir.mkdir()+ ps_dir.mkdir()+ sh = _run_setup_sh_routing(+ status,+ sh_dir,+ install_exists = install_exists,+ explicit_backend = explicit_backend,+ )+ ps = _run_setup_ps1_routing(+ status,+ ps_dir,+ install_exists = install_exists,+ explicit_backend = explicit_backend,+ )++ assert ps["returncode"] == sh["returncode"], {"bash": sh, "pwsh": ps}+ assert ("source_build=true" in ps["stdout"]) == ("source_build=true" in sh["stdout"]), {+ "bash": sh,+ "pwsh": ps,+ }+ # Pin the two branches the backend selector depends on, so a future edit that keeps+ # the halves in step but changes the contract still fails.+ if status == 5:+ assert ps["returncode"] == 1+ assert "source_build=true" not in ps["stdout"]+ if status == 2:+ assert "source_build=true" in ps["stdout"]++def test_setup_scripts_unexpected_exit_branch_never_sets_source_build():"""The new catch-all must fail loudly, not queue a compile, on both platforms."""setup_sh = (PACKAGE_ROOT / "studio" / "setup.sh").read_text(encoding = "utf-8")@@ -3977,8 +4125,10 @@ def test_setup_scripts_unexpected_exit_branch_never_sets_source_build():assert "_NEED_LLAMA_SOURCE_BUILD=true" not in sh_elseassert "setup_fail 1" in sh_elseassert "prebuilt helper failed unexpectedly (exit code $_PREBUILT_STATUS)" in sh_else- # Only status 2 may queue the source build.+ # Only exit 2 under automatic selection may queue a source build. Exit 5 is+ # a concrete unavailable or failed request and fails closed.assert sh_block.count("_NEED_LLAMA_SOURCE_BUILD=true") == 1+ assert 'elif [ "$_PREBUILT_STATUS" -eq 5 ]; then' in sh_blockassert 'elif [ "$_PREBUILT_STATUS" -eq 2 ]; then' in sh_blockps_block = _extract_block(setup_ps1, _SETUP_PS1_ROUTING_START, 'retry setup."\n }')@@ -3987,6 +4137,7 @@ def test_setup_scripts_unexpected_exit_branch_never_sets_source_build():assert "Exit-SetupFailure" in ps_elseassert "prebuilt helper failed unexpectedly (exit code $prebuiltExit)" in ps_elseassert ps_block.count("$NeedLlamaSourceBuild = $true") == 1+ assert "} elseif ($prebuiltExit -eq 5) {" in ps_blockassert "} elseif ($prebuiltExit -eq 2) {" in ps_block# Statuses 3 and 4 keep their dedicated branches ahead of the catch-all.@@ -4158,7 +4309,7 @@ def test_marker_sync_strands_no_temp_file_when_the_first_write_fails(tmp_path, mmonkeypatch.setattr(INSTALL_LLAMA_PREBUILT.tempfile, "NamedTemporaryFile", lambda **kw: _Ctx())- INSTALL_LLAMA_PREBUILT.sync_marker_force_cpu(install_dir, True)+ _sync_force_cpu(install_dir)assert marker.read_text(encoding = "utf-8") == originalassert [q.name for q in install_dir.iterdir() if ".tmp-" in q.name] == []@@ -4216,7 +4367,7 @@ def test_reused_install_backfills_the_ggml_tree(tmp_path):marker = install_dir / "UNSLOTH_PREBUILT_INFO.json"marker.write_text(json.dumps({"release_tag": "b10173-mix-2c8b9c1"}) + "\n", encoding = "utf-8")- INSTALL_LLAMA_PREBUILT.sync_marker_ggml_tree(install_dir, TREE_A)+ _sync_ggml_tree(install_dir, TREE_A)payload = json.loads(marker.read_text(encoding = "utf-8"))assert payload["ggml_tree"] == TREE_A@@ -4235,7 +4386,7 @@ def test_reused_install_keeps_the_ggml_tree_when_the_release_declares_none(tmp_pencoding = "utf-8",)- INSTALL_LLAMA_PREBUILT.sync_marker_ggml_tree(install_dir, declared)+ _sync_ggml_tree(install_dir, declared)assert json.loads(marker.read_text(encoding = "utf-8"))["ggml_tree"] == TREE_A@@ -4256,7 +4407,7 @@ def test_marker_sync_preserves_the_marker_mode(tmp_path, mode):marker.write_text(json.dumps({"force_cpu": False}) + "\n", encoding = "utf-8")os.chmod(marker, mode)- INSTALL_LLAMA_PREBUILT.sync_marker_force_cpu(install_dir, True)+ _sync_force_cpu(install_dir)assert stat.S_IMODE(marker.stat().st_mode) == modeassert json.loads(marker.read_text(encoding = "utf-8"))["force_cpu"] is True@@ -4282,7 +4433,7 @@ def test_marker_sync_leaves_a_valid_marker_intact_when_the_write_fails(tmp_path,monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "atomic_replace_from_tempfile", out_of_space)- INSTALL_LLAMA_PREBUILT.sync_marker_force_cpu(install_dir, True)+ _sync_force_cpu(install_dir)assert marker.read_text(encoding = "utf-8") == originalassert [q.name for q in install_dir.iterdir() if ".tmp-" in q.name] == []@@ -4402,20 +4553,59 @@ def test_binary_env_linux_skips_inaccessible_inherited_ld_library_path(monkeypat# ── marker sync is advisory, never fatal ──+def _reused_choice(install_kind = "linux-cpu"):+ """The bundle a reuse path re-records the run's selection against."""+ return AssetChoice(+ repo = "unslothai/llama.cpp",+ tag = "b10173",+ name = "bundle.tar.gz",+ url = "file://bundle",+ source_label = "published",+ install_kind = install_kind,+ )+++def _sync_force_cpu(install_dir, value = True):+ """sync_marker_selection with only the deliberate-CPU choice in play."""+ INSTALL_LLAMA_PREBUILT.sync_marker_selection(+ install_dir,+ choice = _reused_choice(),+ backend_request = "cpu" if value else "auto",+ persist_force_cpu = value,+ )+++def _sync_ggml_tree(install_dir, tree):+ """sync_marker_selection with only the paired ggml tree in play."""+ INSTALL_LLAMA_PREBUILT.sync_marker_selection(+ install_dir,+ choice = _reused_choice(),+ backend_request = "auto",+ ggml_tree = tree,+ )++@pytest.mark.parametrize(- "sync, kwargs",+ "kwargs, install_kind, field, expected",[- ("sync_marker_force_cpu", {"persist_force_cpu": True}),- ("sync_marker_llama_backend", {"llama_backend": "vulkan"}),+ ({"persist_force_cpu": True, "backend_request": "cpu"}, "linux-cpu", "force_cpu", True),+ (+ {"persist_llama_backend": "vulkan", "backend_request": "vulkan"},+ "linux-vulkan",+ "llama_backend",+ "vulkan",+ ),+ ({"backend_request": "vulkan"}, "linux-vulkan", "backend_request", "vulkan"),],)-def test_marker_sync_survives_a_read_only_marker(tmp_path, sync, kwargs):+def test_marker_sync_survives_a_read_only_marker(tmp_path, kwargs, install_kind, field, expected):"""A shared or admin-owned install must not fail setup on a marker rewrite.- Re-recording force_cpu / llama_backend runs on the existing-install reuse- path. The read is guarded but the write was not, so a read-only marker- raised PermissionError out of the helper as EXIT_ERROR -- which no longer- falls back to a source build, so it would abort the whole install.+ Re-recording the run's selection (force_cpu, the legacy backend field, the+ recorded choice) happens on the existing-install reuse path. The read is+ guarded but the write was not, so a read-only marker raised PermissionError+ out of the helper as EXIT_ERROR -- which no longer falls back to a source+ build, so it would abort the whole install."""install_dir = tmp_path / "llama.cpp"install_dir.mkdir()@@ -4432,7 +4622,9 @@ def test_marker_sync_survives_a_read_only_marker(tmp_path, sync, kwargs):monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "log", logged.append)try:# Must not raise: that would surface as EXIT_ERROR and abort setup.- getattr(INSTALL_LLAMA_PREBUILT, sync)(install_dir, *kwargs.values())+ INSTALL_LLAMA_PREBUILT.sync_marker_selection(+ install_dir, choice = _reused_choice(install_kind), **kwargs+ )finally:monkeypatch.undo()if marker.exists():@@ -4442,8 +4634,6 @@ def test_marker_sync_survives_a_read_only_marker(tmp_path, sync, kwargs):# Silently losing force_cpu would let a later update re-route a deliberate CPU# user onto a GPU bundle (#7213). Windows refuses os.replace onto a read-only# destination, hence the two-way assert.- field = list(kwargs)[0].replace("persist_", "")- expected = list(kwargs.values())[0]persisted = json.loads(marker.read_text(encoding = "utf-8")).get(field) == expectedassert persisted or any("WARNING" in line and field in line for line in logged), logged@@ -4463,7 +4653,7 @@ def test_marker_sync_never_fails_setup_when_the_write_cannot_land(tmp_path, monklogged: list[str] = []monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "log", logged.append)- INSTALL_LLAMA_PREBUILT.sync_marker_force_cpu(install_dir, True)+ _sync_force_cpu(install_dir)assert any("WARNING" in line and "force_cpu" in line for line in logged), logged@@ -4482,6 +4672,7 @@ _VALIDATOR_KEYWORD_ONLY = {"existing_install_dir","force_cpu","llama_backend",+ "backend_request","rocm_gfx",),"validate_prebuilt_choice": (@@ -4493,6 +4684,7 @@ _VALIDATOR_KEYWORD_ONLY = {"quantized_path","force_cpu","llama_backend",+ "backend_request","rocm_gfx",),}