Skip to content

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

Read a llama install's ggml tree from its release when the marker lacks one (#7912)

Daniel Han20c015f29268
diff --git a/studio/install_whisper_prebuilt.py b/studio/install_whisper_prebuilt.py
index 3501a0323bf..db57ebe19e3 100644
--- a/studio/install_whisper_prebuilt.py
+++ b/studio/install_whisper_prebuilt.py
@@ -53,6 +53,7 @@ that already matches logs "already matches" and returns 0 without downloading
from __future__ import annotations
import argparse
+import json
import os
import re
import shutil
@@ -369,31 +370,93 @@ def _llama_ggml_commit(tag: str) -> str | None:
return tag[end:] if idx >= 0 and end < len(tag) else None
+_PUBLISHED_GGML_TREE_CACHE: dict[tuple[str, str], str | None] = {}
+
+
+def published_llama_ggml_tree(tag: Any, repo: Any = None) -> str | None:
+ """ggml tree id recorded in the published llama release for ``tag``.
+
+ An install made before ggml_tree was recorded has no tree locally, and
+ nothing can backfill one without reinstalling llama. The release manifest
+ carries it, so read that instead of falling back to the "-mix-" suffix,
+ which does not track ggml. Failures return None: the caller then uses the
+ old fallback rather than refusing an otherwise valid install, so this
+ fetches once with no retries -- the retry policy exists for downloads we
+ need, and an unreachable host would otherwise stall every uncached tag."""
+ if not isinstance(tag, str) or not tag:
+ return None
+ if not (isinstance(repo, str) and repo):
+ repo = llama.DEFAULT_PUBLISHED_REPO
+ key = (repo, tag)
+ if key in _PUBLISHED_GGML_TREE_CACHE:
+ return _PUBLISHED_GGML_TREE_CACHE[key]
+ tree = None
+ try:
+ payload = _download_host_json_once(
+ release_asset_download_url(repo, tag, llama.DEFAULT_PUBLISHED_MANIFEST_ASSET)
+ )
+ if isinstance(payload, dict):
+ candidate = payload.get("ggml_tree")
+ if isinstance(candidate, str) and candidate:
+ tree = candidate
+ except Exception as exc:
+ log(f"slim_selection: could not read ggml_tree for llama {tag}: {exc}")
+ _PUBLISHED_GGML_TREE_CACHE[key] = tree
+ return tree
+
+
+def installed_llama_tree_repo() -> str | None:
+ """Repo whose published ggml tree describes the installed llama binaries.
+
+ None when there is nothing to read, or when the binaries came from a repo
+ other than the one that published the release: recorded_ggml_tree() leaves
+ the marker's tree unset in that case precisely because the fork tree does
+ not describe an upstream-built libggml, so it must not be inferred either."""
+ metadata = llama.load_prebuilt_metadata(llama.default_managed_llama_dir())
+ if metadata is None:
+ return None
+ published = metadata.get("published_repo")
+ if not isinstance(published, str) or not published:
+ return None
+ binary = metadata.get("binary_repo")
+ if isinstance(binary, str) and binary and binary != published:
+ return None
+ return published
+
+
def llama_runtime_pairs(
installed_tag: str,
required_tag: Any,
*,
installed_ggml_tree: Any = None,
required_ggml_tree: Any = None,
+ installed_repo: Any = None,
) -> bool:
"""Whether an installed llama tag can back a slim bundle needing required_tag.
An exact tag always pairs; otherwise the ggml tree ids decide, since they
change exactly when ggml does. The "-mix-" suffix does not track ggml at all
(see _llama_ggml_commit) and is only used when either tree is missing.
- requires_ggml_sonames stays the per-file ABI gate."""
+ requires_ggml_sonames stays the per-file ABI gate.
+
+ installed_repo is the repo that published the installed runtime (from
+ installed_llama_tree_repo()); without it the installed tag's tree is not
+ inferred, since only the caller knows the binaries came from that release."""
if not isinstance(required_tag, str):
return False
if installed_tag == required_tag:
return True
- # Only decidable with both trees. Refusing when the install predates
- # ggml_tree would strand it: nothing can backfill a tree-less marker
- # without a llama release to install.
- if (
- isinstance(installed_ggml_tree, str)
- and installed_ggml_tree
- and isinstance(required_ggml_tree, str)
- and required_ggml_tree
- ):
+ # An install predating ggml_tree has no tree locally, so read it from that
+ # tag's published release rather than stranding the install on a suffix
+ # comparison that ignores ggml.
+ if not (isinstance(installed_ggml_tree, str) and installed_ggml_tree):
+ if isinstance(installed_repo, str) and installed_repo:
+ installed_ggml_tree = published_llama_ggml_tree(installed_tag, installed_repo)
+ # Only probe the required release once the installed side actually resolved:
+ # the comparison below needs both trees, so with no installed tree the answer
+ # cannot change the verdict and the request is a 30s stall for nothing.
+ if installed_ggml_tree and not (isinstance(required_ggml_tree, str) and required_ggml_tree):
+ required_ggml_tree = published_llama_ggml_tree(required_tag)
+ if installed_ggml_tree and required_ggml_tree:
return installed_ggml_tree == required_ggml_tree
commit = _llama_ggml_commit(installed_tag)
return commit is not None and commit == _llama_ggml_commit(required_tag)
@@ -429,6 +492,7 @@ def slim_pairing_for_artifact(
requires_tag,
installed_ggml_tree = installed_llama_ggml_tree(),
required_ggml_tree = artifact.get("requires_ggml_tree"),
+ installed_repo = installed_llama_tree_repo(),
):
log(
f"slim_selection: {asset} skipped: installed llama tag {llama_tag!r} "
@@ -557,6 +621,7 @@ def _slim_release_incompatibility(manifest: dict[str, Any], host: HostInfo) -> s
return None
installed_tag = runtime[1]
installed_tree = installed_llama_ggml_tree()
+ installed_repo = installed_llama_tree_repo()
# Normalise the tree: llama_runtime_pairs treats a non-string as absent, but
# an unhashable one (list/dict) would blow up the set first.
required_pairs = {
@@ -572,7 +637,11 @@ def _slim_release_incompatibility(manifest: dict[str, Any], host: HostInfo) -> s
required_tags = {tag for tag, _tree in required_pairs}
if required_tags and not any(
llama_runtime_pairs(
- installed_tag, tag, installed_ggml_tree = installed_tree, required_ggml_tree = tree
+ installed_tag,
+ tag,
+ installed_ggml_tree = installed_tree,
+ required_ggml_tree = tree,
+ installed_repo = installed_repo,
)
for tag, tree in required_pairs
):
@@ -638,6 +707,22 @@ def _download_host_json(url: str) -> Any:
return core.fetch_download_host_json(_OPS, url)
+def _download_host_json_once(url: str) -> Any:
+ """One attempt, for a probe whose failure path is a cheap fallback.
+
+ A refused or blackholed host is a retryable URLError, so the default policy
+ would spend four attempts with backoff per tag before returning the answer
+ the caller already has a fallback for.
+
+ Only the ATTEMPT count is overridden. ``download_bytes`` falls back to
+ ``auth_headers(url)`` when headers are absent, so passing a bare User-Agent
+ silently dropped auth: a private published repo 404s and the caller drops to
+ the "-mix-" suffix compare this exists to replace, and an anonymous
+ huggingface.co fetch shares the per-IP limit that 429s CI fleets."""
+ data = download_bytes(url, timeout = 30, attempts = 1, headers = auth_headers(url))
+ return json.loads(data.decode("utf-8"))
+
+
def _resolve_release_via_download_host(
repo: str, published_release_tag: str | None
) -> tuple[ReleaseBundle, dict[str, str]] | None:
@@ -942,6 +1027,7 @@ def selection_from_artifact(
artifact.get("requires_llama_tag"),
installed_ggml_tree = installed_llama_ggml_tree(),
required_ggml_tree = artifact.get("requires_ggml_tree"),
+ installed_repo = installed_llama_tree_repo(),
):
raise PrebuiltFallback(
"the paired llama.cpp runtime changed underneath the slim whisper selection"
diff --git a/tests/studio/install/test_install_whisper_prebuilt_logic.py b/tests/studio/install/test_install_whisper_prebuilt_logic.py
index d9b70308493..8ef59fbfec8 100644
--- a/tests/studio/install/test_install_whisper_prebuilt_logic.py
+++ b/tests/studio/install/test_install_whisper_prebuilt_logic.py
@@ -964,6 +964,40 @@ def test_llama_runtime_pairs_falls_back_to_mix_suffix(installed, required, pairs
assert M.llama_runtime_pairs(installed, required) is pairs
+LLAMA_REPO = "unslothai/llama.cpp"
+# A publisher that is NOT the default, so a lookup that dropped installed_repo
+# and fell back to unslothai/llama.cpp builds a different URL and gets caught.
+FORK_REPO = "acme-fork/llama.cpp"
+
+
[email protected](autouse = True)
+def _offline_published_tree_lookup(monkeypatch):
+ """Keep llama_runtime_pairs offline and its per-tag cache test-local.
+
+ A missing tree sends published_llama_ggml_tree to the llama release, so
+ without this the pairing assertions below would depend on live release
+ assets and on this machine's own llama marker. The cache is module level
+ and outlives monkeypatch, so clear it too. Tests wanting the lookup stub
+ _download_host_json_once themselves, which wins because this fixture is
+ applied first."""
+ M._PUBLISHED_GGML_TREE_CACHE.clear()
+
+ def unreachable(url):
+ raise OSError(f"offline test tried to fetch {url}")
+
+ monkeypatch.setattr(M, "_download_host_json_once", unreachable)
+ # No marker to read, so installed_llama_tree_repo() stays None unless a
+ # test points it somewhere; the lookup then needs an explicit repo.
+ monkeypatch.setattr(M.llama, "default_managed_llama_dir", lambda: Path("/nonexistent-llama"))
+ yield
+ M._PUBLISHED_GGML_TREE_CACHE.clear()
+
+
+# The autouse fixture above replaces _download_host_json_once with an offline guard, so a test
+# exercising the real wrapper has to hold a reference taken at import, before any fixture runs.
+_REAL_DOWNLOAD_HOST_JSON_ONCE = M._download_host_json_once
+
+
# Real releases: same -mix-2c8b9c1 suffix, but genuinely different ggml trees.
SUFFIX_SHARED_A = "b10173-mix-2c8b9c1"
SUFFIX_SHARED_B = "b10181-mix-2c8b9c1"
@@ -978,8 +1012,8 @@ TREE_B = "e96ffb0e063f66952b0c54796a74755b6041c867"
(SUFFIX_SHARED_A, SUFFIX_SHARED_B, TREE_A, TREE_B, False),
# Different suffixes, same ggml: ABI-identical.
("b10241-mix-89aa77b", "b10225-mix-345e1e3", TREE_A, TREE_A, True),
- # A missing tree either side falls back to the suffix, so installs
- # predating ggml_tree are not stranded.
+ # A missing tree falls back to the suffix only when the release does
+ # not publish one either; the lookup is stubbed offline above.
(SUFFIX_SHARED_A, SUFFIX_SHARED_B, None, TREE_B, True),
(SUFFIX_SHARED_A, SUFFIX_SHARED_B, TREE_A, None, True),
(SUFFIX_SHARED_A, SUFFIX_SHARED_B, "", "", True),
@@ -1001,6 +1035,153 @@ def test_llama_runtime_pairs_prefers_ggml_tree(
)
+def test_llama_runtime_pairs_reads_the_published_tree_when_the_marker_has_none(monkeypatch):
+ # The case the fallback got wrong: one -mix- suffix, two ggml trees. An
+ # install predating ggml_tree has no local tree, so both come from the
+ # releases.
+ trees = {SUFFIX_SHARED_A: TREE_A, SUFFIX_SHARED_B: TREE_B}
+ fetched = []
+
+ def fake(url):
+ fetched.append(url)
+ return {"ggml_tree": trees[next(t for t in trees if t in url)]}
+
+ monkeypatch.setattr(M, "_download_host_json_once", fake)
+ assert (
+ M.llama_runtime_pairs(SUFFIX_SHARED_A, SUFFIX_SHARED_B, installed_repo = FORK_REPO) is False
+ )
+ assert len(fetched) == 2
+ # The installed tag is read from the repo that published it. FORK_REPO is
+ # not the default publisher, so a lookup ignoring installed_repo would
+ # build a unslothai/llama.cpp URL here and this would catch it.
+ assert any(f"/{FORK_REPO}/releases/download/{SUFFIX_SHARED_A}/" in url for url in fetched)
+
+
+def test_published_ggml_tree_is_fetched_once_per_tag(monkeypatch):
+ calls = []
+
+ def fake(url):
+ calls.append(url)
+ return {"ggml_tree": TREE_A}
+
+ monkeypatch.setattr(M, "_download_host_json_once", fake)
+ assert M.published_llama_ggml_tree(SUFFIX_SHARED_A) == TREE_A
+ assert M.published_llama_ggml_tree(SUFFIX_SHARED_A) == TREE_A
+ assert calls == [
+ f"https://github.com/unslothai/llama.cpp/releases/download/"
+ f"{SUFFIX_SHARED_A}/llama-prebuilt-manifest.json"
+ ]
+
+
+def test_the_manifest_probe_still_authenticates(monkeypatch):
+ """download_bytes falls back to auth_headers(url) only when headers are ABSENT, so a bare
+ User-Agent silently dropped auth. A private published repo then 404s and the caller falls
+ back to the -mix- suffix compare this probe exists to replace; an anonymous huggingface.co
+ fetch shares the per-IP limit that 429s CI fleets."""
+ seen = {}
+
+ def fake_download_bytes(
+ url,
+ timeout = None,
+ attempts = None,
+ headers = None,
+ **kwargs,
+ ):
+ seen["headers"] = headers
+ seen["attempts"] = attempts
+ return b'{"ggml_tree": "abc"}'
+
+ monkeypatch.setenv("GH_TOKEN", "gh-secret")
+ monkeypatch.delenv("GITHUB_TOKEN", raising = False)
+ monkeypatch.setattr(M, "download_bytes", fake_download_bytes)
+
+ assert _REAL_DOWNLOAD_HOST_JSON_ONCE("https://github.com/o/r/releases/download/t/m.json") == {
+ "ggml_tree": "abc"
+ }
+ assert seen["headers"].get("Authorization") == "Bearer gh-secret"
+ # The single-attempt policy is the ONLY thing this wrapper overrides.
+ assert seen["attempts"] == 1
+
+
+ "payload",
+ [{}, {"ggml_tree": ""}, {"ggml_tree": None}, {"ggml_tree": ["x"]}, ["not", "a", "dict"]],
+)
+def test_published_ggml_tree_ignores_a_manifest_without_a_usable_tree(monkeypatch, payload):
+ monkeypatch.setattr(M, "_download_host_json_once", lambda url: payload)
+ assert M.published_llama_ggml_tree(SUFFIX_SHARED_A) is None
+
+
+def test_published_ggml_tree_survives_an_unreachable_release(monkeypatch):
+ # Fail closed to the old comparison rather than stranding a valid install.
+ def boom(url):
+ raise OSError("network down")
+
+ monkeypatch.setattr(M, "_download_host_json_once", boom)
+ assert M.published_llama_ggml_tree(SUFFIX_SHARED_A) is None
+ assert (
+ M.llama_runtime_pairs(SUFFIX_SHARED_A, SUFFIX_SHARED_B, installed_repo = LLAMA_REPO) is True
+ )
+
+
+def test_published_tree_is_not_consulted_when_both_trees_are_known(monkeypatch):
+ def boom(url):
+ raise AssertionError(f"should not fetch {url}")
+
+ monkeypatch.setattr(M, "_download_host_json_once", boom)
+ assert (
+ M.llama_runtime_pairs(
+ SUFFIX_SHARED_A,
+ SUFFIX_SHARED_B,
+ installed_ggml_tree = TREE_A,
+ required_ggml_tree = TREE_B,
+ )
+ is False
+ )
+ assert M.llama_runtime_pairs(SUFFIX_SHARED_A, SUFFIX_SHARED_A) is True
+
+
+ "marker,expected",
+ [
+ ({"published_repo": LLAMA_REPO}, LLAMA_REPO),
+ ({"published_repo": LLAMA_REPO, "binary_repo": LLAMA_REPO}, LLAMA_REPO),
+ # Binaries from another repo: the fork release's tree does not describe
+ # them, which is why the installer leaves the marker's tree unset.
+ ({"published_repo": LLAMA_REPO, "binary_repo": "ggml-org/llama.cpp"}, None),
+ ({"binary_repo": LLAMA_REPO}, None),
+ ({}, None),
+ ],
+)
+def test_installed_llama_tree_repo_follows_the_marker(monkeypatch, tmp_path, marker, expected):
+ root = tmp_path / "llama.cpp"
+ root.mkdir()
+ (root / "UNSLOTH_PREBUILT_INFO.json").write_text(json.dumps({"release_tag": "b1", **marker}))
+ monkeypatch.setattr(M.llama, "default_managed_llama_dir", lambda: root)
+ assert M.installed_llama_tree_repo() == expected
+
+
+def test_pairing_does_not_infer_a_tree_for_non_fork_binaries(monkeypatch):
+ # Without a repo the installed tag's tree is never fetched, so an upstream
+ # built runtime cannot be paired by a tree that does not describe it.
+ # A raising stub cannot police this: published_llama_ggml_tree() catches
+ # every exception, so the raise would be swallowed and the test would pass
+ # either way. Record the URLs instead, and give the two tags different
+ # trees so an inferred installed tree also flips the verdict.
+ trees = {SUFFIX_SHARED_A: TREE_A, SUFFIX_SHARED_B: TREE_B}
+ fetched = []
+
+ def record(url):
+ fetched.append(url)
+ return {"ggml_tree": trees[next(t for t in trees if t in url)]}
+
+ monkeypatch.setattr(M, "_download_host_json_once", record)
+ assert M.llama_runtime_pairs(SUFFIX_SHARED_A, SUFFIX_SHARED_B, installed_repo = None) is True
+ # Nothing at all is probed: the installed tag because there is no repo, and
+ # the required tag because a lone required tree cannot decide the pairing.
+ assert fetched == []
+
+
def test_installed_llama_ggml_tree_reads_marker(tmp_path):
root = tmp_path / "llama.cpp"
root.mkdir()