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
fix(AMD): retry ROCm llama-server with bundled HIP on HIP/ROCR mismatch (#9002)
Indrajit swainb38490f0a208
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.pyindex 6b42d47f1cc..d698240d66b 100644--- a/studio/backend/core/inference/llama_cpp.py+++ b/studio/backend/core/inference/llama_cpp.py@@ -411,8 +411,9 @@ def _native_linux_system_rocm_lib_dirs(binary_dir: str = "") -> "list[str]":in hsa_init(); prepending the whole system ROCm lib dir loads a driver-matched,version-consistent stack (libhsa-runtime64 / libamdhip64 / librocblas) ahead of it.The whole dir is deliberate: mixing the bundle's rocBLAS with a different-version- system HIP/ROCR risks missing symbols. UNSLOTH_LLAMA_NO_SYSTEM_ROCM=1 keeps the pure- bundle (for a host whose system ROCm lacks this arch); no-op on WSL / non-Linux.+ system HIP/ROCR risks missing symbols, and when it does load_model retries once+ with the bundle only. UNSLOTH_LLAMA_NO_SYSTEM_ROCM=1 skips the prepend up front,+ for a host whose system ROCm lacks this arch. No-op on WSL / non-Linux."""if os.environ.get("UNSLOTH_LLAMA_NO_SYSTEM_ROCM") == "1":return []@@ -7694,8 +7695,14 @@ class LlamaCppBackend:return path_dirs@staticmethod- def _llama_server_env_for_binary(binary: str) -> dict[str, str]:- """Build a subprocess env that lets llama-server resolve native libs."""+ def _llama_server_env_for_binary(+ binary: str, *, use_system_rocm: bool = True+ ) -> dict[str, str]:+ """Build a subprocess env that lets llama-server resolve native libs.++ ``use_system_rocm=False`` skips the native-Linux system ROCm prepend.+ WSL's librocdxg prepend is independent and is not gated by this flag.+ """env = child_env_without_native_path_secret()# _llama_lib_dir resolves the llama-server symlink to the real build/bin.binary_dir = str(_llama_lib_dir(binary))@@ -7737,8 +7744,9 @@ class LlamaCppBackend:if lib_dirs:env.setdefault("HSA_ENABLE_DXG_DETECTION", "1")# Native Linux AMD: system ROCm libs before the bundle's HIP runtime,- # which can be incompatible with the host amdkfd driver.- lib_dirs.extend(_native_linux_system_rocm_lib_dirs(binary_dir))+ # which can be incompatible with the host amdkfd driver (#7233).+ if use_system_rocm and not LlamaCppBackend._prefers_bundle_only_rocm(binary):+ lib_dirs.extend(_native_linux_system_rocm_lib_dirs(binary_dir))lib_dirs.append(binary_dir)_arch = platform.machine() # x86_64, aarch64, etc.@@ -11997,6 +12005,18 @@ class LlamaCppBackend:# LLAMA_SERVER_PATH), and what a "symbol lookup error" from a mismatched# runtime exits with. Name both causes instead of blaming a distro# package -- but still keep it off the GGUF and off memory.+ # A ROCm symbol lookup is also 127, but the generic text below would send+ # the user to reinstall a binary Vulkan and a shell launch both run fine.+ _rocm_miss = LlamaCppBackend._bundled_hip_symbol_miss(output or "")+ if _rocm_miss:+ _miss_obj, _miss_sym = _rocm_miss+ return (+ f"llama-server could not start: bundled {_short(os.path.basename(_miss_obj))} "+ f"looked up {_short(_miss_sym)} in a different ROCm than it was built "+ "against. That is a HIP/ROCR version mix, not a missing "+ "binary and not out of VRAM. Try the Vulkan backend, or "+ f"{LlamaCppBackend._runtime_remedy(binary)}."+ )if returncode == 127:# Same provenance split as the library branches: the updater cannot# touch a pinned binary, so do not send its owner there.@@ -12651,6 +12671,59 @@ class LlamaCppBackend:# the split-axis enum token, unique to this assert (not the source file).return "split_axis" in text+ # The prepend covers the whole system ROCm dir, so any lib in it can be the+ # one that fails to resolve, not just HIP. Matched on the basename so a path+ # component (/opt/librocm-custom/...) cannot stand in for the object.+ _ROCM_OBJECT_HINTS = ("libamdhip", "libamd_comgr", "libhsa-runtime", "libhip", "libroc")++ # Build dirs where a bundle-only launch has come up healthy after the mix+ # crashed, paired with the binary revision that proved it. The installer+ # swaps a new runtime into the same path, so the revision prevents an old+ # proof from suppressing the system ROCm prepend for the new build.+ _bundle_only_rocm_dirs: dict[str, tuple] = {}+ _bundle_only_rocm_lock = threading.Lock()++ @staticmethod+ def _remember_bundle_only_rocm(binary: str) -> None:+ resolved = _resolve_llama_binary(binary)+ revision = LlamaCppBackend._binary_stamp(resolved)+ with LlamaCppBackend._bundle_only_rocm_lock:+ LlamaCppBackend._bundle_only_rocm_dirs[str(resolved.parent)] = revision++ @staticmethod+ def _prefers_bundle_only_rocm(binary: str) -> bool:+ resolved = _resolve_llama_binary(binary)+ revision = LlamaCppBackend._binary_stamp(resolved)+ with LlamaCppBackend._bundle_only_rocm_lock:+ return LlamaCppBackend._bundle_only_rocm_dirs.get(str(resolved.parent)) == revision++ @staticmethod+ def _bundled_hip_symbol_miss(output: str) -> "Optional[tuple[str, str]]":+ """(object, symbol) when a bundled ROCm lib failed a symbol lookup (#8998).++ glibc prints ``symbol lookup error: <object>: undefined symbol: <sym>[,+ version <v>]``. A ggml symbol, or an absent .so (``error while loading+ shared libraries``), is a different failure. The object is echoed+ verbatim, so split on the ": undefined symbol:" that follows it rather+ than on whitespace, the same way the missing-library branch above keeps+ "/opt/My Runtime/libfoo.so" whole.+ """+ match = re.search(+ r"symbol lookup error:[ \t]*([^\r\n]{1,4096}?):"+ r"[ \t]*undefined symbol:[ \t]*([^\s,]+)",+ output or "",+ )+ if not match:+ return None+ obj = os.path.basename(match.group(1)).lower()+ if not obj.startswith(LlamaCppBackend._ROCM_OBJECT_HINTS):+ return None+ return match.group(1), match.group(2)++ @staticmethod+ def _is_bundled_hip_rocr_mismatch(output: str) -> bool:+ return LlamaCppBackend._bundled_hip_symbol_miss(output) is not None+@staticmethoddef _is_signal_crash(returncode: Optional[int]) -> bool:"""True only on a hard fault (SIGSEGV/SIGABRT/SIGILL/SIGFPE/SIGBUS or a@@ -17406,20 +17479,27 @@ class LlamaCppBackend:# Argv actually launched (post --fit off / MTP); text-only retry strips this._last_spawn_cmd = list(cmd)_spawn_cwd: Optional[str] = None+ # Load-scoped, not per call: the correction edits the shared env,+ # so it outlives this spawn, and the launch that finally comes up+ # healthy is often a later one (drafterless, no-flash, arch+ # fallback). A per-call flag left those successes unrecorded.+ _did_rocm_retry = Falsedef _spawn_and_wait(run_cmd, *, label = ""):"""Start llama-server with run_cmd and wait for health.- Retries once with --fit off when the first attempt- crashes during startup and run_cmd is eligible (see- _fit_off_retry_eligible).+ Up to three launches: the first, one ROCm env correction,+ and one --fit recovery. Separate flags, so a library mix+ does not spend the fit slot and a VRAM crash after the+ correction can still fit-retry."""# _mem_host_resident too: the --fit on retry re-arms the# page-lock and writes it back, which without this makes the# read below an UnboundLocalError instead.- nonlocal _last_spawn_cmd, _mem_host_resident+ nonlocal _last_spawn_cmd, _mem_host_resident, _did_rocm_retry_fit_retry_allowed = self._fit_off_retry_eligible(run_cmd, use_fit)- for _spawn_attempt in (0, 1):+ _did_fit_retry = False+ for _spawn_attempt in (0, 1, 2):# Defensive kill: drop an orphan Popen a concurrent load may# have stored before we overwrite the reference (#5161).# Also reaps the crashed first attempt on the retry pass.@@ -17475,20 +17555,52 @@ class LlamaCppBackend:)self._stdout_thread.start()if self._wait_for_health(timeout = 600.0):+ if _did_rocm_retry:+ # Proved on this host: every later child skips the+ # prepend instead of crashing into it first.+ self._remember_bundle_only_rocm(binary)return True_startup_crashed = (self._process.poll() is not None and self._process.returncode != 0)# A split-axis abort (#6415) is fit-independent: skip the# --fit off retry and let the caller latch it.- _split_axis_crash = self._is_tensor_split_assert(- "\n".join(self._stdout_lines[-50:])- )+ _startup_output = "\n".join(self._stdout_lines[-50:])+ _split_axis_crash = self._is_tensor_split_assert(_startup_output)+ _hip_rocr_mismatch = self._is_bundled_hip_rocr_mismatch(_startup_output)+ if (+ not _did_rocm_retry+ and _startup_crashed+ and not _split_axis_crash+ and _hip_rocr_mismatch+ ):+ # The prepend is what a shell launch does not do, which+ # is why the same binary runs from a terminal. Drop+ # those dirs only: the rest of env holds the pooling+ # and memory scrubs.+ _bundle_only = self._llama_server_env_for_binary(+ binary, use_system_rocm = False+ )+ _retry_ld = _bundle_only.get("LD_LIBRARY_PATH", "")+ # "" on a host that never had the var: nothing to undo.+ if _retry_ld and _retry_ld != env.get("LD_LIBRARY_PATH"):+ logger.warning(+ "llama-server crashed during startup (exit code %s) "+ "because a bundled ROCm library could not resolve a "+ "symbol against the system ROCm; retrying once "+ "with the bundled runtime only. Crash log: %s",+ self._process.returncode,+ self._llama_log_path,+ )+ env["LD_LIBRARY_PATH"] = _retry_ld+ _did_rocm_retry = True+ continueif (- _spawn_attempt == 0+ not _did_fit_retryand fully_gpu_offloadedand _startup_crashedand not _split_axis_crash+ and not _hip_rocr_mismatch):# We forced --fit off because Unsloth's (conservative) VRAM# math placed the model fully on GPU. A startup crash here@@ -17532,12 +17644,14 @@ class LlamaCppBackend:)run_cmd = _runself._memory_state = resolve_effective_memory_state(_run, env)+ _did_fit_retry = Truecontinueif (- _spawn_attempt == 0+ not _did_fit_retryand _fit_retry_allowedand _startup_crashedand not _split_axis_crash+ and not _hip_rocr_mismatch):logger.warning("llama-server crashed during startup (exit code %s) "@@ -17581,6 +17695,7 @@ class LlamaCppBackend:"the --fit off retry; it offloads every layer.")self._memory_state = resolve_effective_memory_state(run_cmd, env)+ _did_fit_retry = Truecontinuereturn Falsediff --git a/studio/backend/tests/test_gpu_init_crash_message.py b/studio/backend/tests/test_gpu_init_crash_message.pyindex 2c164bbb4bc..d5366cdd063 100644--- a/studio/backend/tests/test_gpu_init_crash_message.py+++ b/studio/backend/tests/test_gpu_init_crash_message.py@@ -1508,3 +1508,202 @@ def test_success_response_reports_cpu_downgrade(model_cls):kwargs.update(status = "loaded", model = "owner/model", display_name = "model", inference = {})response = model_cls(**kwargs)assert response.model_dump()["cpu_fallback_reason"] == "vulkan_startup_crash"+++_HIP_ROCR_MISMATCH = (+ "llama-server: symbol lookup error: "+ "/home/t/.unsloth/llama.cpp/build/bin/libamdhip64.so.7: "+ "undefined symbol: hsa_amd_queue_create, version ROCR_1"+)+_VRAM_CRASH = "ggml_backend_hip_buffer_type_alloc_buffer: failed to allocate"+++def _fit_mode(cmd):+ if "--fit" in cmd:+ return cmd[cmd.index("--fit") + 1]+ return None+++def _run_full_offload_spawns(monkeypatch, tmp_path, *, outputs, returncodes):+ """Drive load_model with a model that fits on GPU (--fit off).++ Each spawn's stdout is ``outputs[i]`` and its exit is ``returncodes[i]``+ (None means healthy). The child env prepends /opt/rocm/lib unless+ ``use_system_rocm=False``, which is the retry under test.+ """++ def _gguf_string(value: str) -> bytes:+ encoded = value.encode()+ return struct.pack("<Q", len(encoded)) + encoded++ metadata = _gguf_string("general.architecture") + struct.pack("<I", 8) + _gguf_string("llama")+ gguf = tmp_path / "model.gguf"+ gguf.write_bytes(struct.pack("<IIQQ", 0x46554747, 3, 0, 1) + metadata)++ backend = LlamaCppBackend()+ backend._get_gpu_memory = lambda _binary = None, **_kw: [(0, 24 * 1024**3, 24 * 1024**3)]+ backend._get_gpu_free_memory = lambda _binary = None, **_kw: [(0, 24 * 1024**3)]+ backend._read_gguf_metadata = lambda _path: None+ backend._can_estimate_kv = lambda: False+ backend._get_gguf_size_bytes = lambda _path: 1024+ backend._mmproj_vram_bytes = lambda _path: 0+ backend._resolve_launch_mmproj_path = lambda **_kwargs: None+ backend._apu_ram_shortfall_message = lambda *_args, **_kwargs: None+ backend._amd_apu_wants_unified_memory = lambda *_args, **_kwargs: False+ backend._find_llama_server_binary = lambda include_denied = False: "/fake/llama-server"+ backend._select_gpus = lambda *_a, **_k: ([0], False)+ backend._host_torch_is_rocm = lambda: False+ monkeypatch.setattr(+ LlamaCppBackend, "_is_vulkan_backend", staticmethod(lambda _binary = None: False)+ )+ backend.probe_server_capabilities = lambda _binary: {"found": True}+ backend._record_server_pid = lambda _pid: None+ backend._clear_server_pid = lambda: None+ monkeypatch.setattr(+ llama_cpp, "_swa_cache_path", lambda: tmp_path / "studio" / "swa_cache.json"+ )++ def _env_for_binary(+ _binary,+ *,+ use_system_rocm = True,+ **_k,+ ):+ ld = "/opt/rocm/lib:/bundle/bin" if use_system_rocm else "/bundle/bin"+ return {"PATH": os.environ.get("PATH", ""), "LD_LIBRARY_PATH": ld}++ backend._llama_server_env_for_binary = _env_for_binary+ backend._prepare_cpu_fallback_launch = lambda *_a, **_kw: None+ # Class-level and set by a successful bundle-only retry, so give every run a+ # fresh one rather than leaking a correction into the next test.+ monkeypatch.setattr(LlamaCppBackend, "_bundle_only_rocm_dirs", {})++ launches = []++ class _Process:+ pid = 123+ stdout = ()++ def __init__(self, returncode):+ self.returncode = returncode++ def poll(self):+ return self.returncode++ def terminate(self):+ return None++ def wait(self, timeout = None):+ return self.returncode++ def kill(self):+ return None++ _real_popen = subprocess.Popen++ def _popen(cmd, **kwargs):+ # Only the server is a launch. A host with the rocm_sdk wheel installed+ # shells out to offload-arch from inside load_model, which would land at+ # index 0 and shift every assertion below onto the wrong process.+ if not cmd or str(cmd[0]) != "/fake/llama-server":+ return _real_popen(cmd, **kwargs)+ idx = len(launches)+ launches.append((list(cmd), dict(kwargs["env"])))+ code = returncodes[idx] if idx < len(returncodes) else 1+ return _Process(code)++ def _wait_for_health(timeout = 600.0):+ idx = len(launches) - 1+ if 0 <= idx < len(outputs):+ backend._stdout_lines = [outputs[idx]]+ code = returncodes[idx] if 0 <= idx < len(returncodes) else 1+ return code is None++ backend._wait_for_health = _wait_for_health+ monkeypatch.setattr(subprocess, "Popen", _popen)+ loaded = False+ error = None+ try:+ loaded = backend.load_model(+ GgufLoadIntent(gguf_path = str(gguf), model_identifier = "owner/model")+ )+ except Exception as exc:+ error = exc+ return launches, loaded, error+++class TestHipRocrRetryKeepsFitBudget:+ """The ROCm env correction has its own attempt, so a later VRAM crash+ after the bundle-only launch can still take the --fit on recovery.+ """++ def test_mix_then_vram_still_gets_fit_on(self, monkeypatch, tmp_path):+ launches, loaded, error = _run_full_offload_spawns(+ monkeypatch,+ tmp_path,+ outputs = [_HIP_ROCR_MISMATCH, _VRAM_CRASH, ""],+ returncodes = [127, 1, None],+ )+ assert error is None+ assert loaded+ assert len(launches) == 3+ cmd0, env0 = launches[0]+ cmd1, env1 = launches[1]+ cmd2, env2 = launches[2]+ assert env0["LD_LIBRARY_PATH"].startswith("/opt/rocm/lib")+ assert "/opt/rocm/lib" not in env1["LD_LIBRARY_PATH"].split(":")+ assert "/opt/rocm/lib" not in env2["LD_LIBRARY_PATH"].split(":")+ assert _fit_mode(cmd0) == "off"+ assert _fit_mode(cmd1) == "off"+ assert _fit_mode(cmd2) == "on"++ def test_mix_then_healthy_bundled_hip_does_not_fit_retry(self, monkeypatch, tmp_path):+ launches, loaded, error = _run_full_offload_spawns(+ monkeypatch,+ tmp_path,+ outputs = [_HIP_ROCR_MISMATCH, ""],+ returncodes = [127, None],+ )+ assert error is None+ assert loaded+ assert len(launches) == 2+ assert _fit_mode(launches[0][0]) == "off"+ assert _fit_mode(launches[1][0]) == "off"+ assert "/opt/rocm/lib" not in launches[1][1]["LD_LIBRARY_PATH"].split(":")+ # Proved on this host, so later children skip the prepend outright.+ assert LlamaCppBackend._prefers_bundle_only_rocm("/fake/llama-server")++ def test_a_later_launch_in_the_same_load_still_records_the_correction(+ self, monkeypatch, tmp_path+ ):+ # The correction edits the shared env, so it survives into the outer+ # recovery spawns (no-flash here). Those call _spawn_and_wait afresh, so+ # a per-call flag left the launch that actually came up healthy+ # unrecorded and the sidecar kept the prepend.+ launches, loaded, error = _run_full_offload_spawns(+ monkeypatch,+ tmp_path,+ outputs = [_HIP_ROCR_MISMATCH, "", "", ""],+ returncodes = [127, -11, -11, None],+ )+ assert error is None+ assert loaded+ assert len(launches) == 4+ assert "/opt/rocm/lib" not in launches[-1][1]["LD_LIBRARY_PATH"].split(":")+ assert LlamaCppBackend._prefers_bundle_only_rocm("/fake/llama-server")++ def test_a_mix_the_retry_did_not_fix_does_not_spend_the_fit_slot(self, monkeypatch, tmp_path):+ # Bundle-only did not help, so the symbol is still missing. --fit cannot+ # load a missing symbol: stop at two launches and report the mix.+ launches, loaded, error = _run_full_offload_spawns(+ monkeypatch,+ tmp_path,+ outputs = [_HIP_ROCR_MISMATCH, _HIP_ROCR_MISMATCH],+ returncodes = [127, 127],+ )+ assert not loaded+ assert len(launches) == 2+ assert _fit_mode(launches[1][0]) == "off"+ assert "HIP/ROCR" in str(error)+ # The retry did not fix it, so nothing was proved: do not latch.+ assert not LlamaCppBackend._prefers_bundle_only_rocm("/fake/llama-server")diff --git a/studio/backend/tests/test_llama_cpp_darwin_loader_env.py b/studio/backend/tests/test_llama_cpp_darwin_loader_env.pyindex d5084a52669..8b2f6d04bf1 100644--- a/studio/backend/tests/test_llama_cpp_darwin_loader_env.py+++ b/studio/backend/tests/test_llama_cpp_darwin_loader_env.py@@ -150,6 +150,100 @@ class TestLinuxUnchanged:assert env["LD_LIBRARY_PATH"].split(":")[0] == "/wsl/rocm"assert env.get("HSA_ENABLE_DXG_DETECTION") == "1"+ def test_use_system_rocm_false_skips_native_linux_prepend(self, monkeypatch, binary):+ # The retry keeps the CUDA and bundle dirs, drops the system ROCm one.+ monkeypatch.setattr(sys, "platform", "linux")+ monkeypatch.delenv("LD_LIBRARY_PATH", raising = False)+ monkeypatch.setattr(llama_module, "_wsl_system_rocm_lib_dirs", lambda: [])+ monkeypatch.setattr(+ llama_module, "_native_linux_system_rocm_lib_dirs", lambda _d: ["/opt/rocm/lib"]+ )+ with_system = LlamaCppBackend._llama_server_env_for_binary(str(binary))+ bundle_only = LlamaCppBackend._llama_server_env_for_binary(+ str(binary), use_system_rocm = False+ )+ assert with_system["LD_LIBRARY_PATH"].split(":")[0] == "/opt/rocm/lib"+ assert "/opt/rocm/lib" not in bundle_only["LD_LIBRARY_PATH"].split(":")+ assert bundle_only["LD_LIBRARY_PATH"].startswith(str(binary.parent))++ def test_a_proved_bundle_only_host_stops_prepending_for_every_child(self, monkeypatch, binary):+ # The retry fixes one launch. Without the latch the STT sidecar, which+ # builds its env through this same helper, would keep crashing into the+ # prepend that was already proved wrong on this host.+ monkeypatch.setattr(sys, "platform", "linux")+ monkeypatch.delenv("LD_LIBRARY_PATH", raising = False)+ monkeypatch.setattr(llama_module, "_wsl_system_rocm_lib_dirs", lambda: [])+ monkeypatch.setattr(+ llama_module, "_native_linux_system_rocm_lib_dirs", lambda _d: ["/opt/rocm/lib"]+ )+ monkeypatch.setattr(LlamaCppBackend, "_bundle_only_rocm_dirs", {})+ before = LlamaCppBackend._llama_server_env_for_binary(str(binary))+ assert before["LD_LIBRARY_PATH"].split(":")[0] == "/opt/rocm/lib"++ LlamaCppBackend._remember_bundle_only_rocm(str(binary))++ after = LlamaCppBackend._llama_server_env_for_binary(str(binary))+ assert "/opt/rocm/lib" not in after["LD_LIBRARY_PATH"].split(":")+ # The sidecar reaches the same helper, so it inherits the correction.+ from core.inference.stt_mtmd_sidecar import _llama_server_child_env++ sidecar = _llama_server_child_env(str(binary))+ assert "/opt/rocm/lib" not in sidecar["LD_LIBRARY_PATH"].split(":")++ def test_a_replaced_runtime_retests_the_system_rocm_prepend(+ self, monkeypatch, binary, tmp_path+ ):+ # The in-app updater swaps a new install into the same path. A proof+ # from the old binary must not force the new runtime to stay bundle-only.+ monkeypatch.setattr(sys, "platform", "linux")+ monkeypatch.delenv("LD_LIBRARY_PATH", raising = False)+ monkeypatch.setattr(llama_module, "_wsl_system_rocm_lib_dirs", lambda: [])+ monkeypatch.setattr(+ llama_module, "_native_linux_system_rocm_lib_dirs", lambda _d: ["/opt/rocm/lib"]+ )+ monkeypatch.setattr(LlamaCppBackend, "_bundle_only_rocm_dirs", {})+ LlamaCppBackend._remember_bundle_only_rocm(str(binary))+ assert LlamaCppBackend._prefers_bundle_only_rocm(str(binary))++ replacement = tmp_path / "replacement-llama-server"+ replacement.write_bytes(b"new runtime binary")+ os.replace(replacement, binary)++ assert not LlamaCppBackend._prefers_bundle_only_rocm(str(binary))+ env = LlamaCppBackend._llama_server_env_for_binary(str(binary))+ assert env["LD_LIBRARY_PATH"].split(":")[0] == "/opt/rocm/lib"++ def test_a_different_build_dir_still_gets_the_prepend(self, monkeypatch, binary, tmp_path):+ # The proof is about one install tree, not about the host in general.+ monkeypatch.setattr(sys, "platform", "linux")+ monkeypatch.delenv("LD_LIBRARY_PATH", raising = False)+ monkeypatch.setattr(llama_module, "_wsl_system_rocm_lib_dirs", lambda: [])+ monkeypatch.setattr(+ llama_module, "_native_linux_system_rocm_lib_dirs", lambda _d: ["/opt/rocm/lib"]+ )+ monkeypatch.setattr(LlamaCppBackend, "_bundle_only_rocm_dirs", {})+ LlamaCppBackend._remember_bundle_only_rocm(str(binary))+ other = tmp_path / "other" / "llama-server"+ other.parent.mkdir(parents = True)+ other.write_bytes(b"binary")+ env = LlamaCppBackend._llama_server_env_for_binary(str(other))+ assert env["LD_LIBRARY_PATH"].split(":")[0] == "/opt/rocm/lib"++ def test_use_system_rocm_false_keeps_the_wsl_prepend(self, monkeypatch, binary):+ # librocdxg is a different mix (WSL). The native-Linux flag must not+ # drop it.+ monkeypatch.setattr(sys, "platform", "linux")+ monkeypatch.delenv("LD_LIBRARY_PATH", raising = False)+ monkeypatch.setattr(llama_module, "_wsl_system_rocm_lib_dirs", lambda: ["/wsl/rocm"])+ monkeypatch.setattr(+ llama_module, "_native_linux_system_rocm_lib_dirs", lambda _d: ["/opt/rocm/lib"]+ )+ env = LlamaCppBackend._llama_server_env_for_binary(str(binary), use_system_rocm = False)+ parts = env["LD_LIBRARY_PATH"].split(":")+ assert parts[0] == "/wsl/rocm"+ assert "/opt/rocm/lib" not in parts+ assert env.get("HSA_ENABLE_DXG_DETECTION") == "1"+class TestWindowsUnchanged:def test_path_is_semicolon_joined_and_no_unix_vars_appear(self, monkeypatch, binary):diff --git a/studio/backend/tests/test_llama_cpp_start_failure_classification.py b/studio/backend/tests/test_llama_cpp_start_failure_classification.pyindex 11cbfb4f0cc..4a83af57c9f 100644--- a/studio/backend/tests/test_llama_cpp_start_failure_classification.py+++ b/studio/backend/tests/test_llama_cpp_start_failure_classification.py@@ -293,6 +293,9 @@ class TestMissingSharedLibrary:out = "llama-server: symbol lookup error: llama-server: undefined symbol: ggml_backend_init"msg = _classify(out, "/models/x.gguf", "local/x", 127)assert "package manager" not in msg+ # Must not steal the ROCm branch: the object here is llama-server.+ assert "HIP/ROCR" not in msg+ assert "hsa_amd_queue_create" not in msgdef test_bundled_runtime_library_points_at_the_installer(self):# libggml/libllama/libmtmd ship in build/bin (runtime_payload_health_groups)@@ -499,6 +502,132 @@ class TestMissingSharedLibrary:assert "system library" not in msg+class TestBundledHipRocrMismatch:+ """Studio prepends system ROCm, the prebuilt still binds its bundled HIP,+ and glibc exits 127 on the symbol lookup (#8998). That used to read as a+ missing llama-server and get retried as a VRAM miss. Neither is true.+ """++ _FIELD_OUT = (+ "0.00.018.048 I srv load_model: loading model '/models/x.gguf'\n"+ "/home/t/.unsloth/llama.cpp/llama-server: symbol lookup error: "+ "/home/t/.unsloth/llama.cpp/build/bin/libamdhip64.so.7: "+ "undefined symbol: hsa_amd_queue_create, version ROCR_1"+ )++ def test_field_log_is_the_hip_rocr_mix(self):+ assert LlamaCppBackend._is_bundled_hip_rocr_mismatch(self._FIELD_OUT)++ def test_ggml_symbol_lookup_is_not_the_hip_rocr_mix(self):+ out = (+ "llama-server: symbol lookup error: llama-server: "+ "undefined symbol: ggml_backend_init"+ )+ assert not LlamaCppBackend._is_bundled_hip_rocr_mismatch(out)++ def test_missing_libamdhip64_is_not_the_hip_rocr_mix(self):+ # Absent file is the glibc loader line, not a symbol lookup.+ out = (+ "llama-server: error while loading shared libraries: "+ "libamdhip64.so.7: cannot open shared object file: "+ "No such file or directory"+ )+ assert not LlamaCppBackend._is_bundled_hip_rocr_mismatch(out)++ def test_empty_and_none_are_not_the_mix(self):+ assert not LlamaCppBackend._is_bundled_hip_rocr_mismatch("")+ assert not LlamaCppBackend._is_bundled_hip_rocr_mismatch(None)++ def test_another_lib_from_the_prepended_dir_is_the_same_mix(self):+ # The prepend covers the whole system ROCm dir, so rocBLAS against a+ # different-version HIP fails the same way and wants the same retry.+ out = (+ "llama-server: symbol lookup error: "+ "/home/t/.unsloth/llama.cpp/build/bin/librocblas.so.4: "+ "undefined symbol: hipGraphicsResourceGetMappedPointer"+ )+ assert LlamaCppBackend._is_bundled_hip_rocr_mismatch(out)+ msg = _classify(out, "/models/x.gguf", "local/x", 127)+ assert "librocblas.so.4" in msg+ assert "hipGraphicsResourceGetMappedPointer" in msg+ # The field log's symbol is not this crash; do not name it.+ assert "hsa_amd_queue_create" not in msg++ def test_an_oversized_loader_token_is_bounded_in_the_message(self):+ # Straight from the child, and _drain_stdout keeps an unterminated line+ # whole, so the message has to bound both captures.+ out = (+ "llama-server: symbol lookup error: "+ f"/b/libamdhip64.so.{'9' * 3000}: undefined symbol: {'s' * 8192}"+ )+ msg = _classify(out, "/models/x.gguf", "local/x", 127)+ assert "HIP/ROCR" in msg+ assert len(msg) < 1000++ def test_an_object_longer_than_a_path_is_not_the_mix(self):+ # The object capture stops at PATH_MAX: no such path can exist, and an+ # unbounded one lets a single hostile line drive the scan quadratically.+ out = (+ "llama-server: symbol lookup error: "+ f"/b/libamdhip64.so.{'9' * 8192}: undefined symbol: hsa_amd_queue_create"+ )+ assert not LlamaCppBackend._is_bundled_hip_rocr_mismatch(out)++ def test_a_bundle_under_a_path_with_spaces_is_still_the_mix(self):+ # glibc echoes the object verbatim, and a custom LLAMA_SERVER_PATH can+ # sit under a directory with spaces. Splitting on whitespace dropped+ # those into the generic 127 text instead of the retry.+ out = (+ "llama-server: symbol lookup error: "+ "/opt/My Runtime/build/bin/libamdhip64.so.7: "+ "undefined symbol: hsa_amd_queue_create, version ROCR_1"+ )+ assert LlamaCppBackend._is_bundled_hip_rocr_mismatch(out)+ assert LlamaCppBackend._bundled_hip_symbol_miss(out)[0].endswith(+ "/opt/My Runtime/build/bin/libamdhip64.so.7"+ )+ assert "libamdhip64.so.7" in _classify(out, "/models/x.gguf", "local/x", 127)++ def test_a_path_component_does_not_stand_in_for_the_object(self):+ out = (+ "llama-server: symbol lookup error: "+ "/opt/librocm-vendor/lib/libfoo.so.1: undefined symbol: foo_init"+ )+ assert not LlamaCppBackend._is_bundled_hip_rocr_mismatch(out)++ def test_classify_names_the_mix_not_a_missing_binary(self):+ msg = _classify(self._FIELD_OUT, "/models/x.gguf", "local/x", 127)+ assert "HIP/ROCR" in msg+ assert "hsa_amd_queue_create" in msg+ assert "Vulkan" in msg+ assert "could not be found or run" not in msg+ assert "not out of VRAM" in msg+ assert "GGUF file is valid" not in msg+ assert "enough memory" not in msg.lower()++ def test_classify_on_a_pinned_binary_does_not_send_it_to_the_updater(self, monkeypatch):+ monkeypatch.setenv("LLAMA_SERVER_PATH", "/opt/custom/llama-server")+ msg = _classify(+ self._FIELD_OUT, "/models/x.gguf", "local/x", 127, "/opt/custom/llama-server"+ )+ assert "unsloth studio update" not in msg+ assert "custom llama.cpp" in msg++ def test_hip_rocr_retry_is_checked_before_the_fit_on_retry(self):+ # --fit cannot load a missing symbol, so the library check has to come+ # first. The launch sequence itself is asserted behaviourally in+ # test_gpu_init_crash_message.py::TestHipRocrRetryKeepsFitBudget.+ src = Path(__file__).resolve().parent.parent / "core" / "inference" / "llama_cpp.py"+ text = src.read_text(encoding = "utf-8")+ spawn_start = text.index("def _spawn_and_wait(")+ spawn_end = text.index("def _raise_terminal_load_failure", spawn_start)+ body = text[spawn_start:spawn_end]+ assert body.index("_is_bundled_hip_rocr_mismatch") < body.index(+ "retrying once with --fit on so it can offload"+ )+ assert "use_system_rocm = False" in body++# Real dyld output. macOS says none of the things glibc says, so before #8566# every one of these fell through to "invalid GGUF or not enough memory" on a# Mac that had neither problem. Classification is pure text matching, so these