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
Fetch the llama.cpp validation model only when the smoke test reads it (#8248)
Daniel Han82bf2e6b9fc0
diff --git a/studio/install_llama_prebuilt.py b/studio/install_llama_prebuilt.pyindex 5709d889d75..a634a5828d9 100644--- a/studio/install_llama_prebuilt.py+++ b/studio/install_llama_prebuilt.py@@ -42,7 +42,7 @@ except ImportError:FileLock = NoneFileLockTimeout = Nonefrom pathlib import Path-from typing import Any, Iterable, Iterator+from typing import Any, Callable, Iterable, Iterator, Union# Shared component-agnostic machinery lives in prebuilt_core (same directory);# put studio/ on sys.path so it resolves whether this file is run as a script@@ -4471,6 +4471,35 @@ def download_validation_model(path: Path, cache_path: Path | None = None) -> Nonraise PrebuiltFallback(f"validation model unavailable: {exc}") from exc+# A probe model supplied either directly or as a thunk fetched on first use.+ValidationModelProvider = Union[Path, Callable[[], Path]]+++def lazy_validation_model(path: Path, cache_path: Path | None = None) -> Callable[[], Path]:+ """Fetch the tiny GGUF probe on first use, at most once.++ An approved bundle proves its integrity by sha256 and so skips the staged smoke+ test, leaving the probe unread on the default install path. Fetching it up front+ still made huggingface.co a hard gate: a 429 there raised PrebuiltFallback and+ forced a multi-minute source build over a file nothing went on to open.+ """+ fetched = False++ def ensure() -> Path:+ nonlocal fetched+ if not fetched:+ download_validation_model(path, cache_path)+ fetched = True+ return path++ return ensure+++def resolve_validation_model(probe: ValidationModelProvider) -> Path:+ """Materialize a probe model that may have been supplied lazily."""+ return probe() if callable(probe) else probe++def free_local_port() -> int:sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)sock.bind(("127.0.0.1", 0))@@ -6292,7 +6321,7 @@ def validate_prebuilt_choice(host: HostInfo,install_dir: Path,work_dir: Path,- probe_path: Path,+ probe: ValidationModelProvider,*,requested_tag: str,llama_tag: str,@@ -6360,6 +6389,8 @@ def validate_prebuilt_choice(# disabled for now. The check and the source-build fallback it triggers are# kept intact; flip the flag / env to restore it (#5854).if choice.expected_sha256 is None or staged_validation_enabled():+ # Only branch that reads the probe, so this is where a lazy one is fetched.+ probe_path = resolve_validation_model(probe)validate_quantize(quantize_path,probe_path,@@ -6428,7 +6459,7 @@ def validate_prebuilt_attempts(host: HostInfo,install_dir: Path,work_dir: Path,- probe_path: Path,+ probe: ValidationModelProvider,*,requested_tag: str,llama_tag: str,@@ -6444,6 +6475,14 @@ def validate_prebuilt_attempts(if not attempt_list:raise PrebuiltFallback("no prebuilt bundle attempts were available")+ # Resolve the probe up front when any attempt will validate. The per-candidate+ # handler below catches Exception, so a probe download failing inside it would+ # read as a bad bundle and demote a healthy GPU pick to CPU -- and, since the+ # thunk memoises success but not failure, re-download once per attempt. Plans+ # that skip validation never call the thunk, so they stay lazy.+ if staged_validation_enabled() or any(a.expected_sha256 is None for a in attempt_list):+ probe = resolve_validation_model(probe)+tried_fallback = initial_fallback_usedfor index, attempt in enumerate(attempt_list):if index > 0:@@ -6492,7 +6531,7 @@ def validate_prebuilt_attempts(host,staging_dir,work_dir,- probe_path,+ probe,requested_tag = requested_tag,llama_tag = llama_tag,release_tag = release_tag,@@ -7103,8 +7142,22 @@ def install_prebuilt(sync_marker_rocm_gfx(install_dir, persist_rocm_gfx)returnwith scratch_dir("unsloth-llama-prebuilt-") as work_dir:- probe_path = work_dir / "stories260K.gguf"- download_validation_model(probe_path, validation_model_cache_path(install_dir))+ probe = lazy_validation_model(+ work_dir / "stories260K.gguf",+ validation_model_cache_path(install_dir),+ )+ # Same reason as the per-candidate guard in validate_prebuilt_attempts,+ # one level up: the per-release handler below also swallows+ # PrebuiltFallback and moves to an older plan, so a probe failure raised+ # inside it would install an older llama.cpp over a transient 429. The+ # probe is independent of which release was picked, so resolve it once+ # here when any plan will smoke-test.+ if staged_validation_enabled() or any(+ attempt.expected_sha256 is None+ for release_plan in release_plans+ for attempt in release_plan.attempts+ ):+ probe = resolve_validation_model(probe)release_count = len(release_plans)for release_index, plan in enumerate(release_plans):choice = plan.attempts[0]@@ -7142,7 +7195,7 @@ def install_prebuilt(host,install_dir,work_dir,- probe_path,+ probe,requested_tag = requested_tag,llama_tag = plan.llama_tag,release_tag = plan.release_tag,diff --git a/tests/studio/install/test_install_llama_prebuilt_logic.py b/tests/studio/install/test_install_llama_prebuilt_logic.pyindex 2679efb6667..d333f60d4c0 100644--- a/tests/studio/install/test_install_llama_prebuilt_logic.py+++ b/tests/studio/install/test_install_llama_prebuilt_logic.py@@ -2386,9 +2386,12 @@ def test_install_prebuilt_does_not_skip_unhealthy_existing_install([plan],),)+ # Trip on the first real step past the skip check. The probe download used to+ # stand in for it, but it is fetched lazily now and an approved bundle never+ # reads it, so that tripwire would sit unarmed while the flow ran on.monkeypatch.setattr(INSTALL_LLAMA_PREBUILT,- "download_validation_model",+ "validate_prebuilt_attempts",lambda *args, **kwargs: (_ for _ in ()).throw(AssertionError("unhealthy install must continue into normal install flow")),@@ -3326,7 +3329,13 @@ def _nvidia_linux_host():)-def _run_validate_prebuilt_choice(monkeypatch, tmp_path, *, expected_sha256):+def _run_validate_prebuilt_choice(+ monkeypatch,+ tmp_path,+ *,+ expected_sha256,+ probe = None,+):"""Run validate_prebuilt_choice with heavy steps stubbed; return the quantize/server smoke-test call counts."""calls = {"quantize": 0, "server": 0}server_path = tmp_path / "install" / "build" / "bin" / "llama-server"@@ -3374,7 +3383,7 @@ def _run_validate_prebuilt_choice(monkeypatch, tmp_path, *, expected_sha256):_nvidia_linux_host(),tmp_path / "install",tmp_path / "work",- tmp_path / "stories260K.gguf",+ probe if probe is not None else tmp_path / "stories260K.gguf",requested_tag = "b9998",llama_tag = "b9998",release_tag = "b9998",@@ -3409,6 +3418,251 @@ def test_validate_prebuilt_choice_approved_validation_runs_when_flag_enabled(tmpassert calls == {"quantize": 1, "server": 1}+def test_validate_prebuilt_choice_never_fetches_probe_for_approved_bundle(tmp_path, monkeypatch):+ # The probe is only read by the smoke test, so an approved bundle with the flag off+ # must not fetch it at all: a huggingface.co outage or 429 used to raise+ # PrebuiltFallback here and force a source build over a file nothing opens.+ def refuse() -> Path:+ raise AssertionError("probe model must not be fetched when the smoke test is skipped")++ calls = _run_validate_prebuilt_choice(+ monkeypatch, tmp_path, expected_sha256 = "ab" * 32, probe = refuse+ )+ assert calls == {"quantize": 0, "server": 0}+++def test_validate_prebuilt_choice_fetches_probe_once_when_validating(tmp_path, monkeypatch):+ # A hashless build validates, so the probe is fetched -- once for both smoke steps.+ fetches = []+ probe_path = tmp_path / "stories260K.gguf"++ def fetch() -> Path:+ fetches.append(1)+ return probe_path++ calls = _run_validate_prebuilt_choice(monkeypatch, tmp_path, expected_sha256 = None, probe = fetch)+ assert calls == {"quantize": 1, "server": 1}+ assert len(fetches) == 1+++def test_lazy_validation_model_downloads_once_on_first_use(tmp_path, monkeypatch):+ downloads = []+ monkeypatch.setattr(+ INSTALL_LLAMA_PREBUILT,+ "download_validation_model",+ lambda path, cache_path = None: downloads.append((path, cache_path)),+ )+ probe_path = tmp_path / "stories260K.gguf"+ ensure = INSTALL_LLAMA_PREBUILT.lazy_validation_model(probe_path, tmp_path / "cache.gguf")++ assert downloads == [] # constructing the thunk touches the network never+ assert ensure() == probe_path+ assert ensure() == probe_path+ assert len(downloads) == 1 # and repeat use is served from the first fetch+++def test_probe_rate_limit_no_longer_forces_a_source_build(tmp_path, monkeypatch):+ # End to end over install_prebuilt: the probe download used to run before the+ # release loop, so a huggingface.co 429 raised PrebuiltFallback and cost a+ # multi-minute source build over a file an approved bundle never opens.+ install_dir = tmp_path / "llama.cpp"+ install_dir.mkdir()++ host = HostInfo(+ system = "Linux",+ machine = "x86_64",+ is_windows = False,+ is_linux = True,+ is_macos = False,+ is_x86_64 = True,+ is_arm64 = False,+ nvidia_smi = None,+ driver_cuda_version = None,+ compute_caps = [],+ visible_cuda_devices = None,+ has_physical_nvidia = False,+ has_usable_nvidia = False,+ )+ choice = AssetChoice(+ repo = "unslothai/llama.cpp",+ tag = "release-1",+ name = "llama-b9001-bin-ubuntu-x64.tar.gz",+ url = "https://example.com/llama-b9001-bin-ubuntu-x64.tar.gz",+ source_label = "upstream",+ install_kind = "linux-cpu",+ expected_sha256 = "a" * 64,+ )+ checksums = ApprovedReleaseChecksums(+ repo = "unslothai/llama.cpp",+ release_tag = "release-1",+ upstream_tag = "b9001",+ source_commit = "deadbeef",+ artifacts = {+ choice.name: ApprovedArtifactHash(+ asset_name = choice.name,+ sha256 = choice.expected_sha256,+ repo = "ggml-org/llama.cpp",+ kind = "upstream-prebuilt",+ ),+ },+ )+ plan = INSTALL_LLAMA_PREBUILT.InstallReleasePlan(+ requested_tag = "latest",+ llama_tag = "b9001",+ release_tag = "release-1",+ attempts = [choice],+ approved_checksums = checksums,+ )++ monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "detect_host", lambda: host)+ monkeypatch.setattr(+ INSTALL_LLAMA_PREBUILT,+ "resolve_simple_install_release_plans",+ lambda llama_tag, host, published_repo, published_release_tag: ("latest", [plan]),+ )+ monkeypatch.setattr(+ INSTALL_LLAMA_PREBUILT,+ "download_validation_model",+ lambda *args, **kwargs: (_ for _ in ()).throw(+ urllib.error.HTTPError(+ INSTALL_LLAMA_PREBUILT.TEST_MODEL_URL, 429, "Too Many Requests", None, None+ )+ ),+ )+ monkeypatch.setattr(+ INSTALL_LLAMA_PREBUILT,+ "validate_prebuilt_attempts",+ lambda *args, **kwargs: (_ for _ in ()).throw(AssertionError("reached the install flow")),+ )++ # Reaching validate_prebuilt_attempts is the point: the rate limit no longer+ # short-circuits into SystemExit(EXIT_FALLBACK) before the release loop runs.+ with pytest.raises(AssertionError, match = "reached the install flow"):+ install_prebuilt(install_dir, "latest", "unslothai/llama.cpp", "")+++def test_probe_failure_does_not_demote_to_a_lower_priority_candidate(tmp_path, monkeypatch):+ # validate_prebuilt_attempts catches Exception per candidate, so a probe download+ # failing inside that try would read as a bad bundle and quietly install the CPU+ # asset over the healthy GPU one -- re-downloading each time, since the thunk+ # memoises success but not failure. Hashless attempts always validate, so the+ # probe has to be resolved before the loop.+ fetches = []++ def refuse() -> Path:+ fetches.append(1)+ raise INSTALL_LLAMA_PREBUILT.PrebuiltFallback(+ "validation model unavailable: HTTP Error 429: Too Many Requests"+ )++ attempted: list[str] = []+ monkeypatch.setattr(+ INSTALL_LLAMA_PREBUILT,+ "validate_prebuilt_choice",+ lambda attempt, *args, **kwargs: attempted.append(attempt.name),+ )++ def hashless(name: str, install_kind: str) -> AssetChoice:+ return AssetChoice(+ repo = "unslothai/llama.cpp",+ tag = "release-1",+ name = name,+ url = f"https://example.com/{name}",+ source_label = "direct-upstream",+ install_kind = install_kind,+ expected_sha256 = None, # hashless: the smoke test is its only integrity gate+ )++ with pytest.raises(INSTALL_LLAMA_PREBUILT.PrebuiltFallback, match = "429"):+ INSTALL_LLAMA_PREBUILT.validate_prebuilt_attempts(+ [+ hashless("llama-b9001-bin-win-cuda-x64.zip", "windows-cuda"),+ hashless("llama-b9001-bin-win-cpu-x64.zip", "windows-cpu"),+ ],+ _nvidia_linux_host(),+ tmp_path / "install",+ tmp_path / "work",+ refuse,+ requested_tag = "b9001",+ llama_tag = "b9001",+ release_tag = "release-1",+ approved_checksums = ApprovedReleaseChecksums(+ repo = "unslothai/llama.cpp",+ release_tag = "release-1",+ upstream_tag = "b9001",+ source_commit = None,+ artifacts = {},+ ),+ )++ assert attempted == [] # the CPU asset was never reached+ assert len(fetches) == 1 # and the probe was not retried per candidate+++def test_probe_failure_does_not_demote_to_an_older_release(tmp_path, monkeypatch):+ # The per-release handler in install_prebuilt also swallows PrebuiltFallback and+ # continues to an older plan, so a probe failure raised inside it would install an+ # older llama.cpp over a transient 429. The probe does not depend on the release.+ install_dir = tmp_path / "llama.cpp"+ install_dir.mkdir()++ def hashless_plan(release_tag: str, llama_tag: str):+ choice = AssetChoice(+ repo = "unslothai/llama.cpp",+ tag = release_tag,+ name = f"llama-{llama_tag}-bin-ubuntu-x64.tar.gz",+ url = f"https://example.com/{llama_tag}.tar.gz",+ source_label = "direct-upstream",+ install_kind = "linux-cpu",+ expected_sha256 = None, # hashless plans always smoke-test+ )+ return INSTALL_LLAMA_PREBUILT.InstallReleasePlan(+ requested_tag = "latest",+ llama_tag = llama_tag,+ release_tag = release_tag,+ attempts = [choice],+ approved_checksums = ApprovedReleaseChecksums(+ repo = "unslothai/llama.cpp",+ release_tag = release_tag,+ upstream_tag = llama_tag,+ source_commit = None,+ artifacts = {},+ ),+ )++ plans = [hashless_plan("release-2", "b9002"), hashless_plan("release-1", "b9001")]+ monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "detect_host", lambda: _nvidia_linux_host())+ monkeypatch.setattr(+ INSTALL_LLAMA_PREBUILT,+ "resolve_simple_install_release_plans",+ lambda llama_tag, host, published_repo, published_release_tag: ("latest", plans),+ )+ monkeypatch.setattr(+ INSTALL_LLAMA_PREBUILT,+ "download_validation_model",+ # The real one wraps transport errors in PrebuiltFallback; mirror that.+ lambda *args, **kwargs: (_ for _ in ()).throw(+ INSTALL_LLAMA_PREBUILT.PrebuiltFallback(+ "validation model unavailable: HTTP Error 429: Too Many Requests"+ )+ ),+ )+ validated: list[str] = []+ monkeypatch.setattr(+ INSTALL_LLAMA_PREBUILT,+ "validate_prebuilt_attempts",+ lambda attempts, *args, **kwargs: validated.append(list(attempts)[0].name),+ )+ monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "collect_system_report", lambda *a, **k: "report")++ with pytest.raises(SystemExit) as caught:+ install_prebuilt(install_dir, "latest", "unslothai/llama.cpp", "")++ # One clean fallback to the source build, not a silent downgrade to release-1.+ assert caught.value.code == INSTALL_LLAMA_PREBUILT.EXIT_FALLBACK+ assert validated == []++def test_staged_validation_enabled_default_off(monkeypatch):monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "_RUN_STAGED_PREBUILT_VALIDATION", False)monkeypatch.delenv("UNSLOTH_LLAMA_STAGED_VALIDATION", raising = False)