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
Reject a macOS llama.cpp prebuilt that dyld will not load (#9843)
Daniel Han6386137fecb6
diff --git a/studio/install_llama_prebuilt.py b/studio/install_llama_prebuilt.pyindex b74a66a8857..401642953e7 100644--- a/studio/install_llama_prebuilt.py+++ b/studio/install_llama_prebuilt.py@@ -5191,6 +5191,38 @@ def looks_like_macos_incompatibility(text: str) -> bool:return "Symbol not found" in text and "MTLResidency" in text+_MACOS_LOADER_FAILURE_MARKERS = (+ "library not loaded",+ "symbol not found",+ "image not found",+ "no suitable image found",+ "incompatible library version",+ "code signature",+)+++def looks_like_macos_loader_failure(text: str) -> bool:+ """True when output is dyld refusing to load the image, rather than a program+ that started and exited non-zero.++ The distinction is the whole point: llama-quantize answers --version by+ printing its quantization table and exiting non-zero, so an exit code cannot+ separate "never reached main" from "ran and disagreed". dyld failures are+ recognisable by what they say, and they say it before any program output.+ Deliberately narrow -- a false positive here rejects a working prebuilt and+ spends a source build, so anything unrecognised is treated as healthy and+ left to the runtime validation that follows.+ """+ if not text:+ return False+ lowered = text.lower()+ if any(marker in lowered for marker in _MACOS_LOADER_FAILURE_MARKERS):+ return True+ # No bare "dyld[pid]:" rule: DYLD_PRINT_LIBRARIES narrates a healthy load+ # under that same prefix. It says who is speaking, not that anything failed.+ return looks_like_macos_incompatibility(text)++def macos_binary_minos_issues(binaries: Iterable[Path], install_dir: Path, host: HostInfo) -> list[str]:@@ -5221,19 +5253,84 @@ def macos_binary_minos_issues(return issues+def macos_dyld_load_issues(+ binaries: Iterable[Path], install_dir: Path, host: HostInfo+) -> list[str]:+ """Issue strings for every installed executable dyld refuses to load.++ `--version` costs a process spawn and still makes dyld resolve the whole link+ graph, so it catches a missing dylib, a missing symbol or a too-new slice --+ unlike validate_server, which loads a model and is off for checksummed bundles+ (#5854). Executables only: a broken dylib surfaces through whatever links it."""+ issues: list[str] = []+ seen: set[Path] = set()+ for binary_path in binaries:+ try:+ resolved = binary_path.resolve()+ except Exception:+ resolved = binary_path+ if resolved in seen or not binary_path.is_file():+ continue+ seen.add(resolved)+ env = binary_env(binary_path, install_dir, host)+ # Keep the user's dyld diagnostics out of output we are about to parse:+ # DYLD_PRINT_* narrates, DYLD_INSERT_LIBRARIES can fail and blame the bundle.+ for noisy in [k for k in env if k.startswith("DYLD_PRINT_")]:+ env.pop(noisy, None)+ env.pop("DYLD_INSERT_LIBRARIES", None)+ try:+ result = run_capture([str(binary_path), "--version"], timeout = 60, env = env)+ except Exception as exc:+ # A timeout or a refusal to spawn is not evidence of a bad link, and+ # calling it one would reject a healthy bundle on a loaded machine.+ log(f"macos load probe could not run {binary_path.name}: {exc}")+ continue+ if result.returncode == 0:+ continue+ output = (result.stdout + result.stderr).strip()+ # A non-zero exit is not evidence of a bad link: llama-quantize answers+ # --version by printing its table and exiting 1. Reading the code as the+ # verdict rejected every published prebuilt and fell back to a source+ # build. Require dyld's own signature instead -- it also names the dylib+ # that asked, which otool -L cannot, since an absolute install name absent+ # from disk is the normal case for /usr/lib's shared-cache members.+ if not looks_like_macos_loader_failure(output):+ continue+ detail = " | ".join(output.splitlines()[-5:]) or f"exit {result.returncode}"+ issues.append(f"{binary_path.name}: {detail}")+ return issues++def preflight_macos_installed_binaries(binaries: Iterable[Path], install_dir: Path, host: HostInfo) -> None:- """Reject a macos prebuilt whose minimum-OS is newer than the host. The- upstream selector pins a loadable release up front, so here this is the- post-download backstop; the published/fork path also uses it to advance the- walk-back. No-op when the host macOS version is unknown (runtime validates)."""- if not host.is_macos or host.macos_version is None:+ """Reject a macos prebuilt whose minimum-OS is newer than the host, or that+ dyld will not load at all. The upstream selector pins a loadable release up+ front, so here this is the post-download backstop; the published/fork path+ also uses it to advance the walk-back.++ The load probe is the macOS counterpart of preflight_linux_installed_binaries'+ ldd sweep, which this side went without: a bundle whose libggml-rpc.0.dylib+ links a /usr/lib/librdma.dylib that exists on the builder and nowhere else+ passed the minos scan, was logged "prebuilt installed and validated", and+ then died on first launch. Raising PrebuiltFallback here spends a source+ build instead of installing something that cannot start.++ Only the static comparison needs the host version; dyld does not. Skipping+ both on an unparseable ``platform.mac_ver()`` left that host with no check at+ all, since the runtime validation it deferred to is off by default (#5854)."""+ if not host.is_macos:return- issues = macos_binary_minos_issues(binaries, install_dir, host)- if issues:+ if host.macos_version is not None:+ issues = macos_binary_minos_issues(binaries, install_dir, host)+ if issues:+ raise PrebuiltFallback(+ "macos prebuilt requires a newer macOS than this host:\n" + "\n".join(issues)+ )+ load_issues = macos_dyld_load_issues(binaries, install_dir, host)+ if load_issues:raise PrebuiltFallback(- "macos prebuilt requires a newer macOS than this host:\n" + "\n".join(issues)+ "macos prebuilt does not load on this host:\n" + "\n".join(load_issues))@@ -6837,6 +6934,18 @@ def existing_install_matches_choice()except Exception:return False+ # The macOS side, and the one that reaches most affected users: a bundle that+ # cannot load is usually already installed by the time the installer learns to+ # reject it, so a matching fingerprint would reuse the broken tree forever.+ elif host.is_macos:+ try:+ preflight_macos_installed_binaries(+ [runtime_dir / "llama-server", runtime_dir / "llama-quantize"],+ install_dir,+ host,+ )+ except Exception:+ return Falseexpected_fingerprint = expected_install_fingerprint(llama_tag = llama_tag,release_tag = release_tag,diff --git a/tests/studio/install/test_install_llama_prebuilt_logic.py b/tests/studio/install/test_install_llama_prebuilt_logic.pyindex 8625ad5ef4e..8ae391e2f74 100644--- a/tests/studio/install/test_install_llama_prebuilt_logic.py+++ b/tests/studio/install/test_install_llama_prebuilt_logic.py@@ -4283,6 +4283,98 @@ def test_existing_install_matches_choice_fails_when_install_tree_incomplete_maco)+def test_existing_macos_install_that_cannot_load_is_not_reused(tmp_path: Path, monkeypatch):+ """A bundle that dyld refuses must not be accepted just because its+ fingerprint matches.++ This is the path that reaches the users who matter: a bundle that cannot+ load is usually ALREADY installed by the time the installer learns to reject+ it, and the reuse check ran the Linux preflight only. Re-running the+ installer then saw a matching fingerprint, kept the broken tree and failed at+ first launch again.+ """+ install_dir = tmp_path / "llama.cpp"+ install_dir.mkdir()+ write_macos_install_shape(install_dir)++ host = 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,+ macos_version = (15, 5),+ )+ choice = AssetChoice(+ repo = "unslothai/llama.cpp",+ tag = "release-1",+ name = "llama-b9001-bin-macos-arm64.tar.gz",+ url = "https://example.com/llama-b9001-bin-macos-arm64.tar.gz",+ source_label = "upstream",+ install_kind = "macos-arm64",+ expected_sha256 = "a" * 64,+ )+ checksums = ApprovedReleaseChecksums(+ repo = "unslothai/llama.cpp",+ release_tag = "release-1",+ upstream_tag = "b9001",+ source_commit = "deadbeef",+ artifacts = {+ source_archive_logical_name("b9001"): ApprovedArtifactHash(+ asset_name = source_archive_logical_name("b9001"),+ sha256 = "b" * 64,+ repo = "ggml-org/llama.cpp",+ kind = "upstream-source",+ ),+ choice.name: ApprovedArtifactHash(+ asset_name = choice.name,+ sha256 = choice.expected_sha256,+ repo = "ggml-org/llama.cpp",+ kind = "upstream-prebuilt",+ ),+ },+ )+ write_prebuilt_metadata(+ install_dir,+ requested_tag = "latest",+ llama_tag = "b9001",+ release_tag = "release-1",+ choice = choice,+ approved_checksums = checksums,+ prebuilt_fallback_used = False,+ )++ def matches() -> bool:+ return existing_install_matches_choice(+ install_dir,+ host,+ llama_tag = "b9001",+ release_tag = "release-1",+ choice = choice,+ approved_checksums = checksums,+ )++ # Loads cleanly -> reuse is correct.+ monkeypatch.setattr(INSTALL_LLAMA_PREBUILT, "macos_dyld_load_issues", lambda *a, **k: [])+ assert matches() is True++ # dyld refuses it -> the cached tree must be rejected so it gets reinstalled.+ monkeypatch.setattr(+ INSTALL_LLAMA_PREBUILT,+ "macos_dyld_load_issues",+ lambda *a, **k: ["llama-server: Library not loaded: /usr/lib/librdma.dylib"],+ )+ assert matches() is False++def test_paired_runtime_dll_patterns_excludes_executables() -> None:"""The paired runtime archive must contribute only CUDA DLLs (no *.exe/*.dll) so it can't overwrite binaries."""paired_runtime_dll_patterns = INSTALL_LLAMA_PREBUILT.paired_runtime_dll_patternsdiff --git a/tests/studio/install/test_macos_version_compat.py b/tests/studio/install/test_macos_version_compat.pyindex c2b2dc9225b..ed1e1d05b1b 100644--- a/tests/studio/install/test_macos_version_compat.py+++ b/tests/studio/install/test_macos_version_compat.py@@ -182,9 +182,10 @@ class TestPreflightMacosInstalledBinaries:# Must not raise on a macOS 15 host.ILP.preflight_macos_installed_binaries(binaries, install_dir, make_macos_host((15, 5)))- def test_skips_when_host_version_unknown(self, tmp_path):+ def test_skips_the_minos_comparison_when_host_version_unknown(self, tmp_path):install_dir, binaries = self._install_dir(tmp_path, (26, 0))- # Unknown host version -> defer to runtime validation, do not raise.+ # No host version to compare against, so the static check cannot run.+ # These fixtures are not executable, so the load probe finds nothing either.ILP.preflight_macos_installed_binaries(binaries, install_dir, make_macos_host(None))def test_noop_on_non_macos_host(self, tmp_path):@@ -207,6 +208,170 @@ class TestPreflightMacosInstalledBinaries:ILP.preflight_macos_installed_binaries(binaries, install_dir, linux_host)+class TestMacosDyldLoadProbe:+ """The minos scan reads a header; it cannot see an install name pointing at a+ library that exists on the builder and nowhere else. That shipped: a bundle+ whose libggml-rpc.0.dylib wanted /usr/lib/librdma.dylib passed preflight, was+ logged "prebuilt installed and validated", and then died on first launch."""++ def _bundle(+ self,+ tmp_path,+ *,+ exit_code,+ message = "",+ ):+ bin_dir = tmp_path / "build" / "bin"+ bin_dir.mkdir(parents = True)+ # A real spawnable file, not a Mach-O sample: the point is to reach dyld.+ # macho_minimum_macos returns None for a non-Mach-O, so the minos gate+ # ahead of the probe stays quiet and the probe is what decides.+ server = bin_dir / "llama-server"+ server.write_text(f'#!/bin/sh\necho "{message}" >&2\nexit {exit_code}\n')+ server.chmod(0o755)+ return tmp_path, (server,)++ def test_rejects_a_binary_dyld_will_not_load(self, tmp_path):+ install_dir, binaries = self._bundle(+ tmp_path,+ exit_code = 1,+ message = "dyld: Library not loaded: /usr/lib/librdma.dylib",+ )+ with pytest.raises(PrebuiltFallback, match = "does not load on this host"):+ ILP.preflight_macos_installed_binaries(binaries, install_dir, make_macos_host((15, 5)))++ def test_the_message_names_the_library(self, tmp_path):+ install_dir, binaries = self._bundle(+ tmp_path,+ exit_code = 1,+ message = "dyld: Library not loaded: /usr/lib/librdma.dylib",+ )+ with pytest.raises(PrebuiltFallback) as caught:+ ILP.preflight_macos_installed_binaries(binaries, install_dir, make_macos_host((15, 5)))+ # Without the name the operator gets an exit code and no lead to follow.+ assert "librdma" in str(caught.value)++ def test_accepts_a_binary_that_loads(self, tmp_path):+ install_dir, binaries = self._bundle(tmp_path, exit_code = 0, message = "")+ ILP.preflight_macos_installed_binaries(binaries, install_dir, make_macos_host((15, 5)))++ def test_a_binary_that_cannot_be_spawned_is_not_a_link_failure(self, tmp_path):+ """A refusal to exec says nothing about the link graph, and treating it as+ a verdict would reject healthy bundles on a loaded or locked-down host."""+ install_dir, binaries = self._bundle(tmp_path, exit_code = 0)+ binaries[0].chmod(0o644)+ ILP.preflight_macos_installed_binaries(binaries, install_dir, make_macos_host((15, 5)))++ def test_the_probe_still_runs_when_the_host_version_is_unknown(self, tmp_path):+ """Only the static comparison needs the version; dyld does not.++ Skipping both left the checksummed path with no check at all, since the+ runtime validation it deferred to is disabled by default (#5854).+ """+ install_dir, binaries = self._bundle(+ tmp_path,+ exit_code = 1,+ message = "dyld[1]: Library not loaded: /usr/lib/librdma.dylib",+ )+ with pytest.raises(PrebuiltFallback, match = "does not load on this host"):+ ILP.preflight_macos_installed_binaries(binaries, install_dir, make_macos_host(None))++ def test_a_nonzero_exit_with_program_output_is_not_a_link_failure(self, tmp_path):+ """llama-quantize answers --version by printing its quantization table and+ exiting non-zero. Reading the exit code as the verdict rejected every+ published prebuilt, walked the release history to its end, and fell back to+ a source build on every macOS runner.+ """+ install_dir, binaries = self._bundle(+ tmp_path,+ exit_code = 1,+ message = (+ "llama-quantize: 7 or Q8_0 : 7.96G, +0.0026 ppl @ Llama-3-8B | "+ "1 or F16 : 14.00G, +0.0020 ppl @ Mistral-7B"+ ),+ )+ ILP.preflight_macos_installed_binaries(binaries, install_dir, make_macos_host((15, 5)))++ def test_the_referencing_dylib_survives_into_the_message(self, tmp_path):+ """dyld names the library AND the dylib that asked for it. The second half+ is what says libggml-rpc rather than llama-server is at fault, so keep+ enough of the tail to carry it."""+ real = (+ "dyld[41694]: Library not loaded: /usr/lib/librdma.dylib\\n"+ " Referenced from: /Users/r/.unsloth/llama.cpp/build/bin/libggml-rpc.0.dylib\\n"+ " Reason: tried: '/usr/lib/librdma.dylib' (no such file)"+ )+ install_dir, binaries = self._bundle(tmp_path, exit_code = 1, message = real)+ with pytest.raises(PrebuiltFallback) as caught:+ ILP.preflight_macos_installed_binaries(binaries, install_dir, make_macos_host((15, 5)))+ message = str(caught.value)+ assert "librdma" in message+ assert "libggml-rpc" in message+++class TestLooksLikeMacosLoaderFailure:+ """Narrow by design: a false positive rejects a working prebuilt."""++ @pytest.mark.parametrize(+ "text",+ [+ "dyld[41694]: Library not loaded: /usr/lib/librdma.dylib",+ "dyld: Library not loaded: /usr/lib/libfoo.dylib",+ "Symbol not found: _OBJC_CLASS_$_MTLResidencySetDescriptor",+ "dyld[1]: no suitable image found.",+ ],+ )+ def test_loader_failures_are_recognised(self, text):+ assert ILP.looks_like_macos_loader_failure(text)++ @pytest.mark.parametrize(+ "text",+ [+ "",+ "llama-quantize: 7 or Q8_0 : 7.96G, +0.0026 ppl @ Llama-3-8B",+ "usage: llama-quantize [--help] model-f32.gguf",+ "error: failed to load model 'foo.gguf'",+ "main: build = 10639 (f6f92fe)",+ # DYLD_PRINT_LIBRARIES narrates a perfectly healthy load under the+ # same prefix a failure uses, so the prefix alone cannot be the test.+ "dyld[4711]: /usr/lib/libSystem.B.dylib\ndyld[4711]: /usr/lib/libc++.1.dylib",+ ],+ )+ def test_ordinary_program_output_is_not_a_loader_failure(self, text):+ assert not ILP.looks_like_macos_loader_failure(text)+++class TestTheProbeEnvironment:+ def test_dyld_diagnostics_are_kept_out_of_the_probe(self, tmp_path, monkeypatch):+ """A user's DYLD_PRINT_* would otherwise be echoed into the output the+ probe reads, and llama-quantize's nonzero --version would turn that+ narration into a rejection."""+ monkeypatch.setenv("DYLD_PRINT_LIBRARIES", "1")+ monkeypatch.setenv("DYLD_INSERT_LIBRARIES", "/tmp/evil.dylib")+ seen = {}++ bin_dir = tmp_path / "build" / "bin"+ bin_dir.mkdir(parents = True)+ server = bin_dir / "llama-server"+ server.write_text("#!/bin/sh\nexit 0\n")+ server.chmod(0o755)++ def capture(command, **kwargs):+ seen.update(kwargs.get("env") or {})++ class Result:+ returncode = 0+ stdout = ""+ stderr = ""++ return Result()++ monkeypatch.setattr(ILP, "run_capture", capture)+ ILP.macos_dyld_load_issues([server], tmp_path, make_macos_host((15, 5)))+ assert "DYLD_PRINT_LIBRARIES" not in seen+ assert "DYLD_INSERT_LIBRARIES" not in seen++def _fake_macos_releases(tags):return [{