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
Unsloth Studio (AMD): retry an unpinned llama-server arch crash on the cards the build has kernels for (#16513)
Leo Borcherding95c5d5825259
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.pyindex 89f0501c963..5fc861e8fe3 100644--- a/studio/backend/core/inference/llama_cpp.py+++ b/studio/backend/core/inference/llama_cpp.py@@ -22374,6 +22374,48 @@ class LlamaCppBackend:return []return discrete if 0 < len(discrete) < len(_selected) else []+ _CURRENT_DEVICE_RE = re.compile(r"current device:\s*(\d+)")++ @classmethod+ def _unpinned_arch_crash_retry(+ cls,+ output: str,+ enumerated,+ child_ids: Optional[Sequence[int]] = None,+ ) -> tuple[list[int], list[int]]:+ """``(crashed, remaining)`` physical ids from the child's "current device: N", or ``([], [])``.+ ``child_ids`` maps the child's ordinals when Studio masked it."""+ if not cls._host_torch_is_rocm():+ return [], [] # an unmasked CUDA child orders devices by speed, not by our ids+ matches = cls._CURRENT_DEVICE_RE.findall(output or "")+ if not matches:+ return [], []+ ordinal = int(matches[-1])+ # Ordinals we cannot map back to physical ids; guessing could expose a hidden card.+ if cls._gpu_device_ordinal_active() or (+ child_ids is None+ and (cls._visibility_mask_is_unmappable() or cls._rocm_visibility_masks_are_stacked())+ ):+ return [], []+ physical_ids = (+ list(child_ids) if child_ids is not None else cls._resolve_visible_physical_ids()+ )+ if physical_ids is not None:+ if ordinal >= len(physical_ids):+ return [], []+ ordinal = physical_ids[ordinal]+ _enumerated = sorted(set(enumerated or ()))+ if ordinal not in _enumerated:+ return [], []+ remaining = [i for i in _enumerated if i != ordinal]+ # A shared-memory iGPU is the usual second uncovered arch; kept only when nothing else is left.+ try:+ unified = cls._rocm_unified_memory_gpu_ids()+ discrete = [i for i in remaining if i not in unified]+ except Exception:+ discrete = []+ return [ordinal], (discrete or remaining)+@staticmethoddef _cache_tuning_target_unknown(extra_args: Optional[Iterable[str]], device_flags_owned: bool, env: Mapping[str, str]@@ -23217,10 +23259,11 @@ class LlamaCppBackend:"UNSLOTH_LLAMA_CPP_BACKEND=cpu unsloth studio update.")if backend == "hip":+ var = "HIP_VISIBLE_DEVICES" if sys.platform == "win32" else "ROCR_VISIBLE_DEVICES"return base + ("This often means an unsupported secondary GPU; on AMD/ROCm, hide it "- "with ROCR_VISIBLE_DEVICES (e.g. ROCR_VISIBLE_DEVICES=0 exposes only "- "the first GPU) before launching Unsloth Studio."+ f"with {var} (e.g. {var}=0 exposes only the first GPU) before "+ "launching Unsloth Studio.")if backend == "cuda":return base + (@@ -31751,22 +31794,51 @@ class LlamaCppBackend:"update llama.cpp to use tensor parallelism with a ""quantized cache.")- # Auto-pinned device has no kernels in this binary: retry once on a narrowed set, since the gate cannot see custom builds; explicit picks keep their error.+ # A launched device has no kernels in this binary: retry once on a narrowed set (the gate cannot see custom builds or unreadable coverage); explicit picks keep their error.+ _arch_crash_tail = "\n".join(self._stdout_lines[-80:])if (not healthyand not _load_cancelled()and not gpu_idsand not is_vulkan_backend- and gpu_indices- and self._kernel_image_invalid("\n".join(self._stdout_lines[-80:]))+ and self._kernel_image_invalid(_arch_crash_tail)):- _crashed = sorted(set(gpu_indices))# _detected_gpus, not gpus: the post-picker enumeration this launch# planned against, and unlike `gpus` it survives the manual mode that# empties the pool to bypass the planner.- _remaining = self._arch_crash_retry_gpu_ids(- gpu_indices, [i for i, _free in _detected_gpus]- )+ _enumerated = [i for i, _free in _detected_gpus]+ if gpu_indices:+ _crashed = sorted(set(gpu_indices))+ _remaining = self._arch_crash_retry_gpu_ids(gpu_indices, _enumerated)+ elif (+ _cache_target_unknown+ or str(env.get("LLAMA_ARG_MAIN_GPU", "")).strip()+ or _GPU_DEVICE_TOKEN_RE.match(+ str(env.get("MTMD_BACKEND_DEVICE", "")).strip()+ )+ ):+ # A user --device / --main-gpu / projector device env numbers cards by the unnarrowed set.+ _crashed, _remaining = [], []+ else:+ # Unpinned (manual split, or unreadable coverage): only the child's "current device" names the card.+ _crashed, _remaining = self._unpinned_arch_crash_retry(+ _arch_crash_tail, _enumerated, _child_gpu_physical_ids+ )+ if (+ _remaining+ and _companion_fit_mask is None+ and any(+ _flag_name(str(tok)) in flags+ for tok in cmd+ for flags in _COMPANION_DEVICE_FLAG_GROUPS+ )+ ):+ # Companion ROCm<n> tokens number this child's devices; the refit below remaps them.+ _companion_fit_mask = (+ list(_child_gpu_physical_ids)+ if _child_gpu_physical_ids is not None+ else self._resolve_visible_physical_ids() or sorted(_enumerated)+ )if _remaining:# Earlier notices priced the crashed selection; re-price on the respawn set, since first notice wins._retry_wants_unified = self._amd_apu_wants_unified_memory(_remaining)@@ -31907,7 +31979,6 @@ class LlamaCppBackend:env, ",".join(str(i) for i in _retry_mask), prefer_rocr = True)_child_gpu_physical_ids = tuple(int(i) for i in _retry_mask)- # No ratio record here: _tensor_split is set only in manual mode, where gpu_indices stays None.self._clear_split_placement_env(env)# The mask re-indexes survivors, so drop a --tensor-split sized for the crashed set._arch_retry_cmd = self._without_tensor_split(cmd)@@ -31918,9 +31989,9 @@ class LlamaCppBackend:"devices and the narrowed set re-indexes them.")cmd = _arch_retry_cmd- # No ratio record, unlike the proactive gate: _tensor_split- # is non-None only in manual mode, which leaves gpu_indices- # None, and this arm needs it truthy.+ # Recorded like the proactive gate, or the next Apply sees a different server and reloads.+ if self._tensor_split:+ self._arch_gate_dropped_tensor_split = tuple(self._tensor_split)self._tensor_split = None# The auto twin, which this arm CAN reach: an auto# tensor-parallel fallback emits its ratio withdiff --git a/studio/backend/tests/test_gpu_arch_gate_7624.py b/studio/backend/tests/test_gpu_arch_gate_7624.pyindex f6d2c199a2e..05addae2586 100644--- a/studio/backend/tests/test_gpu_arch_gate_7624.py+++ b/studio/backend/tests/test_gpu_arch_gate_7624.py@@ -411,6 +411,128 @@ class TestArchGateCoexistsWithUnifiedMemory:]+# The tail of a ROCm llama-server that split a manual ratio onto a card the build lacks.+_UNPINNED_CRASH = (+ "llama_kv_cache: ROCm2 KV buffer size = 4248.00 MiB\n"+ "ROCm error: invalid kernel file\n"+ " current device: 2, in function ggml_cuda_kernel_launch at common.cuh:1740\n"+)+++class TestUnpinnedArchCrashRetry:+ """A manual split, or a gate that could not read the build's coverage, launches with+ no mask, so the child's own "current device" is the only name for the bad card."""++ @pytest.fixture(autouse = True)+ def _rocm_host(self, monkeypatch):+ monkeypatch.setattr(LlamaCppBackend, "_host_torch_is_rocm", staticmethod(lambda: True))+ monkeypatch.setattr(+ LlamaCppBackend, "_resolve_visible_physical_ids", staticmethod(lambda: None)+ )+ monkeypatch.setattr(+ LlamaCppBackend, "_rocm_unified_memory_gpu_ids", staticmethod(lambda: set())+ )+ monkeypatch.setattr(+ LlamaCppBackend, "_visibility_mask_is_unmappable", staticmethod(lambda: False)+ )+ monkeypatch.setattr(+ LlamaCppBackend, "_rocm_visibility_masks_are_stacked", staticmethod(lambda: False)+ )+ monkeypatch.delenv("GPU_DEVICE_ORDINAL", raising = False)++ def test_drops_the_crashed_card(self):+ assert LlamaCppBackend._unpinned_arch_crash_retry(_UNPINNED_CRASH, [0, 1, 2]) == (+ [2],+ [0, 1],+ )++ def test_also_drops_a_shared_memory_igpu(self, monkeypatch):+ # 7900 XTX + Ryzen iGPU + R9700 on a gfx110X build: the iGPU is uncovered too.+ monkeypatch.setattr(+ LlamaCppBackend, "_rocm_unified_memory_gpu_ids", staticmethod(lambda: {1})+ )+ assert LlamaCppBackend._unpinned_arch_crash_retry(_UNPINNED_CRASH, [0, 1, 2]) == (+ [2],+ [0],+ )++ def test_keeps_the_igpu_when_it_is_all_that_is_left(self, monkeypatch):+ monkeypatch.setattr(+ LlamaCppBackend, "_rocm_unified_memory_gpu_ids", staticmethod(lambda: {0})+ )+ assert LlamaCppBackend._unpinned_arch_crash_retry(_UNPINNED_CRASH, [0, 2]) == ([2], [0])++ def test_maps_the_child_ordinal_through_an_inherited_mask(self, monkeypatch):+ monkeypatch.setattr(+ LlamaCppBackend, "_resolve_visible_physical_ids", staticmethod(lambda: [1, 3, 5])+ )+ assert LlamaCppBackend._unpinned_arch_crash_retry(_UNPINNED_CRASH, [1, 3, 5]) == (+ [5],+ [1, 3],+ )++ def test_the_childs_own_mask_wins_over_the_parents(self):+ # A manual split pins the child's order (or the gate pins survivors) without gpu_indices.+ assert LlamaCppBackend._unpinned_arch_crash_retry(+ _UNPINNED_CRASH, [0, 1, 2], child_ids = (0, 2, 1)+ ) == ([1], [0, 2])++ def test_ordinal_outside_the_childs_mask_is_not_guessed(self):+ assert LlamaCppBackend._unpinned_arch_crash_retry(+ _UNPINNED_CRASH, [0, 1, 2], child_ids = (0, 1)+ ) == ([], [])++ def test_an_unmappable_mask_is_left_alone(self, monkeypatch):+ # A UUID/MIG mask resolves to no ids; reading the ordinal as physical could expose a hidden card.+ monkeypatch.setattr(+ LlamaCppBackend, "_visibility_mask_is_unmappable", staticmethod(lambda: True)+ )+ assert LlamaCppBackend._unpinned_arch_crash_retry(_UNPINNED_CRASH, [0, 1, 2]) == ([], [])++ def test_gpu_device_ordinal_is_left_alone(self, monkeypatch):+ monkeypatch.setenv("GPU_DEVICE_ORDINAL", "2,0")+ assert LlamaCppBackend._unpinned_arch_crash_retry(_UNPINNED_CRASH, [0, 1, 2]) == ([], [])+ assert LlamaCppBackend._unpinned_arch_crash_retry(+ _UNPINNED_CRASH, [0, 1, 2], child_ids = (0, 2, 1)+ ) == ([], [])++ def test_stacked_rocr_and_hip_masks_are_left_alone(self, monkeypatch):+ # HIP ordinals index the ROCr-filtered set, so the resolved ids are not physical.+ monkeypatch.setattr(+ LlamaCppBackend, "_rocm_visibility_masks_are_stacked", staticmethod(lambda: True)+ )+ assert LlamaCppBackend._unpinned_arch_crash_retry(_UNPINNED_CRASH, [0, 1, 2]) == ([], [])+ assert LlamaCppBackend._unpinned_arch_crash_retry(+ _UNPINNED_CRASH, [0, 1, 2], child_ids = (0, 2, 1)+ ) == ([1], [0, 2])++ def test_the_childs_own_mask_still_maps_under_an_unmappable_parent(self, monkeypatch):+ monkeypatch.setattr(+ LlamaCppBackend, "_visibility_mask_is_unmappable", staticmethod(lambda: True)+ )+ assert LlamaCppBackend._unpinned_arch_crash_retry(+ _UNPINNED_CRASH, [0, 1, 2], child_ids = (0, 2, 1)+ ) == ([1], [0, 2])++ def test_ordinal_outside_the_mask_is_not_guessed(self, monkeypatch):+ monkeypatch.setattr(+ LlamaCppBackend, "_resolve_visible_physical_ids", staticmethod(lambda: [0, 1])+ )+ assert LlamaCppBackend._unpinned_arch_crash_retry(_UNPINNED_CRASH, [0, 1]) == ([], [])++ def test_no_device_line_means_no_retry(self):+ out = "ROCm error: invalid kernel file\n"+ assert LlamaCppBackend._unpinned_arch_crash_retry(out, [0, 1]) == ([], [])++ def test_single_gpu_has_nowhere_to_go(self):+ assert LlamaCppBackend._unpinned_arch_crash_retry(_UNPINNED_CRASH, [2]) == ([2], [])++ def test_cuda_host_is_left_alone(self, monkeypatch):+ # An unmasked CUDA child orders devices by speed, so its ordinal is not our id.+ monkeypatch.setattr(LlamaCppBackend, "_host_torch_is_rocm", staticmethod(lambda: False))+ assert LlamaCppBackend._unpinned_arch_crash_retry(_UNPINNED_CRASH, [0, 1, 2]) == ([], [])++class TestArchCrashRetrySet:"""The reactive recovery for markerless / custom-linked builds, where theproactive gate cannot know what the binary covers."""diff --git a/studio/backend/tests/test_gpu_arch_gate_consumers_7624.py b/studio/backend/tests/test_gpu_arch_gate_consumers_7624.pyindex 3cf541d2834..64a73fdafbe 100644--- a/studio/backend/tests/test_gpu_arch_gate_consumers_7624.py+++ b/studio/backend/tests/test_gpu_arch_gate_consumers_7624.py@@ -19,6 +19,7 @@ _BACKEND_DIR = str(Path(__file__).resolve().parent.parent)if _BACKEND_DIR not in sys.path:sys.path.insert(0, _BACKEND_DIR)+from core.inference import llama_cpp # noqa: E402from core.inference.llama_cpp import GgufLoadIntent, LlamaCppBackend # noqa: E402_REAL_POPEN = subprocess.Popen@@ -524,11 +525,173 @@ class TestArchRetryDropsTensorSplit:text = path.read_text(encoding = "utf-8")# Arch-crash retry and the gated manual-split launch both mask devices under a positional ratio.assert text.count("self._without_tensor_split(") == 2- block = text.split("_arch_crash_retry_gpu_ids(\n")[-1].split('label = "-archfallback"')[0]+ block = text.split("self._kernel_image_invalid(_arch_crash_tail)")[1]+ block = block.split('label = "-archfallback"')[0]assert "_without_tensor_split(cmd)" in blockassert "self._tensor_split = None" in block # /status must not report a dropped split+_MANUAL_SPLIT_CRASH = (+ "ROCm error: invalid kernel file\n"+ " current device: 1, in function ggml_cuda_kernel_launch at common.cuh:1740"+)+++def _load_manual_split(+ monkeypatch,+ tmp_path,+ *,+ outputs,+ returncodes,+ env = None,+ extra_args = None,+):+ """load_model in manual mode over two ROCm GPUs, each spawn answering from the lists."""+ for name in (+ "HIP_VISIBLE_DEVICES",+ "ROCR_VISIBLE_DEVICES",+ "CUDA_VISIBLE_DEVICES",+ "GPU_DEVICE_ORDINAL",+ "LLAMA_ARG_DEVICE",+ "LLAMA_ARG_MAIN_GPU",+ ):+ monkeypatch.delenv(name, raising = False)+ for name, value in (env or {}).items():+ monkeypatch.setenv(name, value)+ monkeypatch.setattr(llama_cpp.sys, "platform", "linux")++ def _s(value):+ return struct.pack("<Q", len(value)) + value.encode()++ gguf = tmp_path / "model.gguf"+ gguf.write_bytes(+ struct.pack("<IIQQ", 0x46554747, 3, 0, 1)+ + _s("general.architecture")+ + struct.pack("<I", 8)+ + _s("llama")+ )+ gib16 = 16 * 1024**3+ backend = LlamaCppBackend()+ backend._get_gpu_memory = lambda _b = None, **_k: [(0, gib16, gib16), (1, gib16, gib16)]+ backend._get_gpu_free_memory = lambda _b = None, **_k: [(0, gib16), (1, gib16)]+ backend._effective_gpu_count = lambda *_a, **_k: 2+ backend._read_gguf_metadata = lambda _p: None+ backend._can_estimate_kv = lambda: False+ backend._get_gguf_size_bytes = lambda _p: 1024+ backend._mmproj_vram_bytes = lambda _p: 0+ backend._resolve_launch_mmproj_path = lambda **_k: None+ backend._apu_ram_shortfall_message = lambda *_a, **_k: None+ backend._amd_apu_wants_unified_memory = lambda *_a, **_k: False+ backend._find_llama_server_binary = lambda include_denied = False: "/fake/llama-server"+ backend.probe_server_capabilities = lambda _b: {"found": True}+ backend._record_server_pid = lambda _p: None+ backend._clear_server_pid = lambda: None+ backend._llama_server_env_for_binary = lambda _b, **_k: dict(os.environ)+ backend._prepare_cpu_fallback_launch = lambda *_a, **_k: None+ monkeypatch.setattr(LlamaCppBackend, "_host_torch_is_rocm", staticmethod(lambda: True))+ monkeypatch.setattr(+ LlamaCppBackend, "_rocm_unified_memory_gpu_ids", staticmethod(lambda: set())+ )+ monkeypatch.setattr(LlamaCppBackend, "_is_vulkan_backend", staticmethod(lambda _b = None: False))+ monkeypatch.setattr(LlamaCppBackend, "_bundle_only_rocm_dirs", {})+ monkeypatch.setattr(llama_cpp, "_swa_cache_path", lambda: tmp_path / "swa.json")+ 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):+ if not cmd or str(cmd[0]) != "/fake/llama-server":+ return real_popen(cmd, **kwargs)+ launches.append((list(cmd), dict(kwargs["env"])))+ return _Process(returncodes[min(len(launches), len(returncodes)) - 1])++ def _wait_for_health(timeout = 600.0, **_k):+ backend._stdout_lines = outputs[min(len(launches), len(outputs)) - 1].splitlines()+ return returncodes[min(len(launches), len(returncodes)) - 1] is None++ backend._wait_for_health = _wait_for_health+ monkeypatch.setattr(subprocess, "Popen", _popen)+ try:+ loaded = backend.load_model(+ GgufLoadIntent(+ gguf_path = str(gguf),+ model_identifier = "owner/model",+ gpu_memory_mode = "manual",+ gpu_layers = 999,+ tensor_split = (1.0, 1.0),+ extra_args = extra_args,+ )+ )+ except RuntimeError:+ loaded = False+ return backend, launches, loaded+++def _tensor_split_arg(cmd):+ return cmd[cmd.index("--tensor-split") + 1] if "--tensor-split" in cmd else None+++class TestUnpinnedArchCrashRetryLoad:+ """A manual split launches unpinned; the arch-crash retry must still narrow it."""++ def test_the_crashed_card_is_dropped_and_the_load_recovers(self, monkeypatch, tmp_path):+ backend, launches, loaded = _load_manual_split(+ monkeypatch, tmp_path, outputs = [_MANUAL_SPLIT_CRASH, ""], returncodes = [1, None]+ )+ assert loaded+ assert len(launches) == 2+ assert _tensor_split_arg(launches[0][0]) == "1,1"+ retry_cmd, retry_env = launches[1]+ assert _tensor_split_arg(retry_cmd) is None+ assert retry_env["CUDA_VISIBLE_DEVICES"] == "0"+ assert backend._arch_gate_dropped_tensor_split == (1.0, 1.0)++ def test_a_companion_device_on_the_survivor_is_renumbered(self, monkeypatch, tmp_path):+ crash_on_0 = _MANUAL_SPLIT_CRASH.replace("current device: 1", "current device: 0")+ _backend, launches, loaded = _load_manual_split(+ monkeypatch,+ tmp_path,+ outputs = [crash_on_0, ""],+ returncodes = [1, None],+ extra_args = ["--spec-draft-device", "ROCm1"],+ )+ assert loaded+ retry_cmd, retry_env = launches[1]+ assert retry_env.get("ROCR_VISIBLE_DEVICES", retry_env["CUDA_VISIBLE_DEVICES"]) == "1"+ assert retry_cmd[retry_cmd.index("--spec-draft-device") + 1] == "ROCm0"++ @pytest.mark.parametrize("env", [{"LLAMA_ARG_MAIN_GPU": "1"}, {"MTMD_BACKEND_DEVICE": "ROCm1"}])+ def test_a_user_device_env_keeps_its_error(self, monkeypatch, tmp_path, env):+ _backend, launches, loaded = _load_manual_split(+ monkeypatch,+ tmp_path,+ outputs = [_MANUAL_SPLIT_CRASH],+ returncodes = [1],+ env = env,+ )+ assert not loaded+ assert all(_tensor_split_arg(cmd) == "1,1" for cmd, _env in launches)++class TestArchRetryRestoresTheMemoryPolicy:"""The --fit retry appends a page-lock to its OWN argv and records it, but thearch-crash respawn starts from `cmd`, which never carried it, so without a restorediff --git a/studio/backend/tests/test_gpu_init_crash_message.py b/studio/backend/tests/test_gpu_init_crash_message.pyindex d175108beaa..1e01298fe89 100644--- a/studio/backend/tests/test_gpu_init_crash_message.py+++ b/studio/backend/tests/test_gpu_init_crash_message.py@@ -268,9 +268,16 @@ class TestGpuInitCrashMessage:assert "UNSLOTH_LLAMA_CPP_BACKEND=cpu" in messagedef test_rocm_host_keeps_the_original_advice(self, monkeypatch):+ monkeypatch.setattr(sys, "platform", "linux")message = self._message(monkeypatch, "hip")assert "ROCR_VISIBLE_DEVICES=0" in message+ def test_windows_rocm_host_is_told_the_variable_that_masks_there(self, monkeypatch):+ monkeypatch.setattr(sys, "platform", "win32")+ message = self._message(monkeypatch, "hip")+ assert "HIP_VISIBLE_DEVICES=0" in message+ assert "ROCR_VISIBLE_DEVICES" not in message+def test_cuda_host_gets_cuda_advice(self, monkeypatch):message = self._message(monkeypatch, "cuda")assert "CUDA_VISIBLE_DEVICES" in message