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
Studio: name the llama.cpp graph-scheduler abort and stop reloading into it (#6741)
Daniel Han9a2c9823b31d
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.pyindex 62cd457b8c9..de10ecb908d 100644--- a/studio/backend/core/inference/llama_cpp.py+++ b/studio/backend/core/inference/llama_cpp.py@@ -4100,6 +4100,14 @@ def _vram_usable_mib()+def _model_memory_settings_or_none() -> Optional[tuple[bool, bool]]:+ try:+ from utils.model_memory_settings import get_model_memory_settings+ return get_model_memory_settings()+ except Exception:+ return None++def _active_vram_fraction() -> float:"""The user's VRAM budget, or ``_CTX_FIT_VRAM_FRACTION`` when they set none.@@ -15697,6 +15705,26 @@ class LlamaCppBackend:if key is not None:cls._tensor_split_abort_keys.add(key)+ # Keyed like the tensor latch: binary mtime drops entries after an update.+ _sched_reserve_abort_keys: set[tuple] = set()++ @classmethod+ def _sched_reserve_aborts(cls, binary: Optional[str], model: Optional[str]) -> bool:+ key = cls._tensor_split_cache_key(binary, model)+ return key is not None and key in cls._sched_reserve_abort_keys++ @classmethod+ def _record_sched_reserve_abort(cls, binary: Optional[str], model: Optional[str]) -> None:+ key = cls._tensor_split_cache_key(binary, model)+ if key is not None:+ cls._sched_reserve_abort_keys.add(key)++ @classmethod+ def _forget_sched_reserve_abort(cls, binary: Optional[str], model: Optional[str]) -> None:+ key = cls._tensor_split_cache_key(binary, model)+ if key is not None:+ cls._sched_reserve_abort_keys.discard(key)+@staticmethoddef _windows_pip_nvidia_dll_dirs(prefix: str) -> list[str]:"""Return DLL dirs from pip-installed CUDA wheels under@@ -20833,6 +20861,9 @@ class LlamaCppBackend:"settings and reload.")+ if LlamaCppBackend._is_sched_reserve_abort(output or ""):+ return LlamaCppBackend._sched_reserve_abort_message()+# An older llama.cpp refusing a quantized KV cache under --split-mode tensor.# Naming the build is the point: the remedy is an update, where the generic# invalid-GGUF/OOM fallback sends the user to check their file or buy VRAM.@@ -21866,6 +21897,34 @@ class LlamaCppBackend:def _is_bundled_hip_rocr_mismatch(output: str) -> bool:return LlamaCppBackend._bundled_hip_symbol_miss(output) is not None+ @staticmethod+ def _is_sched_reserve_abort(output: str) -> bool:+ """GGML_ASSERT(*cur_backend_id != -1); matches backtrace frames, which outlive the [New LWP] dump."""+ text = (output or "").lower()+ if "ggml_assert" not in text and "ggml_abort" not in text:+ return False+ # The #6415 split-axis abort shares the frame but has its own latch.+ if "split_axis" in text:+ return False+ if "cur_backend_id" in text:+ return True+ # Never sched_reserve / graph_reserve alone (a reserve-time CUDA OOM passes through them);+ # split_graph has other aborts, so its bare frame counts only with no other message.+ if "failed to initialize context" in text or "ggml_assert(" in text:+ return False+ return "ggml_backend_sched_split_graph" in text++ @staticmethod+ def _sched_reserve_abort_message() -> str:+ return (+ "llama.cpp aborted while reserving the compute graph "+ "(GGML_ASSERT(*cur_backend_id != -1)): no backend can place part of this model's "+ "graph. Either this llama.cpp build lacks an operation the model needs on this "+ "device (common for new attention types on CPU), or the model does not fit in "+ "memory. Try `unsloth studio update` for a newer llama.cpp, a smaller "+ "quantization, a lower context length, or turning off speculative decoding."+ )+@staticmethoddef _is_signal_crash(returncode: Optional[int]) -> bool:"""True only on a hard fault (SIGSEGV/SIGABRT/SIGILL/SIGFPE/SIGBUS or a@@ -23504,6 +23563,25 @@ class LlamaCppBackend:logger.info("Load cancelled before teardown")return False+ # Fail fast before killing the live server; an explicit reload retries (freed memory+ # can make the same load fit) and clears the entry.+ _abort_memo_model = repr(+ (+ replace(intent, hf_token = None, force_reload = False, verified_gguf = None),+ _vram_frac,+ _model_memory_settings_or_none(),+ )+ )+ if intent.force_reload:+ LlamaCppBackend._forget_sched_reserve_abort(binary, _abort_memo_model)+ elif LlamaCppBackend._sched_reserve_aborts(binary, _abort_memo_model):+ logger.warning(+ "Skipping reload of '%s': it already aborted in the llama.cpp graph "+ "scheduler this session.",+ model_identifier,+ )+ raise RuntimeError(self._sched_reserve_abort_message())+# ── Phase 1: kill old process (under lock, fast) ──────────# The previous load's advisory is dropped HERE, at the one point this call# commits to replacing the resident server, rather than on the first line of@@ -29372,6 +29450,9 @@ class LlamaCppBackend:)return stripped+ # Memoed only when the load ends terminally, so a recovering fallback is not blocked.+ _sched_abort_seen = False+def _spawn_and_wait(run_cmd, *, label = ""):"""Start llama-server with run_cmd and wait for health.@@ -29384,6 +29465,7 @@ class LlamaCppBackend:# page-lock and writes it back, which without this makes the# read below an UnboundLocalError instead.nonlocal _last_spawn_cmd, _mem_host_resident, _did_rocm_retry+ nonlocal _sched_abort_seen# One revocation point for the tensor-spill plan instead of a# strip per retry site. `label` is empty ONLY on the first# spawn, so a retry added later is covered automatically. The@@ -29517,6 +29599,11 @@ class LlamaCppBackend:# offload spends a second full model load on a theory unrelated# to the failure. The caller latches both, so both skip alike._startup_output = "\n".join(self._stdout_lines[-50:])+ # Wider tail: the GGML_ASSERT line scrolls past the [New LWP] dump.+ if _startup_crashed and self._is_sched_reserve_abort(+ "\n".join(self._stdout_lines[-200:])+ ):+ _sched_abort_seen = True_tensor_capability_crash = self._is_tensor_split_assert(_startup_output) or self._is_tensor_quant_kv_unsupported(_startup_output)@@ -29735,6 +29822,8 @@ class LlamaCppBackend:_launched_mmproj_has_audio = self._mmproj_has_audiodef _raise_terminal_load_failure(detail: str) -> NoReturn:+ if _sched_abort_seen and not _load_cancelled():+ LlamaCppBackend._record_sched_reserve_abort(binary, _abort_memo_model)if intent.cpu_fallback:self._cleanup_failed_cpu_fallback()# No child will carry this budget; left set, the route reads it@@ -29835,6 +29924,8 @@ class LlamaCppBackend:(self._api_key,),self._extra_args,)+ if _sched_abort_seen:+ LlamaCppBackend._record_sched_reserve_abort(binary, _abort_memo_model)self._cleanup_failed_cpu_fallback()self._vram_fraction_pending = Noneraise RuntimeError(detail)@@ -30951,6 +31042,11 @@ class LlamaCppBackend:# Snapshot: re-reading races the teardown._retry_proc = self._process_retry_rc = _retry_proc.poll() if _retry_proc is not None else None+ # This retry bypasses _spawn_and_wait's abort detection.+ if _retry_rc not in (None, 0) and self._is_sched_reserve_abort(+ "\n".join(self._stdout_lines[-200:])+ ):+ _sched_abort_seen = Trueself._kill_process()if _finish_cancelled_health_wait("Load cancelled during the text-only retry health wait"diff --git a/studio/backend/tests/test_sched_reserve_abort.py b/studio/backend/tests/test_sched_reserve_abort.pynew file mode 100644index 00000000000..896874079e7--- /dev/null+++ b/studio/backend/tests/test_sched_reserve_abort.py@@ -0,0 +1,311 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""ggml graph-scheduler abort (GGML_ASSERT(*cur_backend_id != -1)): matcher, message, memo."""++from __future__ import annotations++import os+import struct+import subprocess+import sys+from pathlib import Path+from unittest.mock import patch++import pytest++_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)+if _BACKEND_DIR not in sys.path:+ sys.path.insert(0, _BACKEND_DIR)++from core.inference.llama_cpp import GgufLoadIntent, LlamaCppBackend # noqa: E402+++# Real crash log: the GGML_ASSERT line scrolls out of a short tail behind the [New LWP] dump.+_FULL_ABORT = "\n".join(+ [+ "0.09.350.752 W llama_context: n_ctx_seq (4096) < n_ctx_train (1048576)",+ "/tmp/llama.cpp/ggml/src/ggml-backend.cpp:1242: GGML_ASSERT(*cur_backend_id != -1) failed",+ ]+ + [f"[New LWP {2147067 - i}]" for i in range(130)]+ + [+ "[Thread debugging using libthread_db enabled]",+ "#1 0x... in ggml_print_backtrace () from /tmp/llama.cpp/build/bin/libggml-base.so.0",+ "#2 0x... in ggml_abort () from /tmp/llama.cpp/build/bin/libggml-base.so.0",+ "#3 0x... in ggml_backend_sched_split_graph () from /tmp/llama.cpp/build/bin/libggml-base.so.0",+ "#4 0x... in llama_context::graph_reserve(...) () from /tmp/llama.cpp/build/bin/libllama.so.0",+ "#5 0x... in llama_context::sched_reserve() () from /tmp/llama.cpp/build/bin/libllama.so.0",+ ]+)++_ABORT_TAIL = "\n".join(_FULL_ABORT.splitlines()[-50:])++_SPLIT_AXIS_ABORT = (+ "ggml/src/ggml-backend-meta.cpp:541: "+ "GGML_ASSERT(src_ss[0].axis != GGML_BACKEND_SPLIT_AXIS_0) failed\n"+ "#3 ggml_backend_sched_split_graph ()"+)++# Same reserve frames, different assert.+_CUDA_OOM_ABORT = "\n".join(+ [+ "ggml_backend_cuda_buffer_type_alloc_buffer: allocating 23810.00 MiB on device 0: "+ "cudaMalloc failed: out of memory",+ "/src/ggml/src/ggml-cuda/ggml-cuda.cu:95: GGML_ASSERT(err == cudaSuccess) failed",+ "#2 ggml_abort () from libggml-base.so",+ "#3 ggml_gallocr_reserve_n () from libggml-base.so",+ "#4 ggml_backend_sched_reserve () from libggml-base.so",+ "#5 llama_context::graph_reserve(...) () from libllama.so",+ "#6 llama_context::sched_reserve() () from libllama.so",+ ]+)+# Other aborts inside split_graph (ggml-backend.cpp) share its frame.+_CONTEXT_INIT_ABORT = (+ "ggml/src/ggml-backend.cpp:1082: ggml_backend_sched_split_graph: failed to initialize context\n"+ "#2 ggml_abort ()\n#3 ggml_backend_sched_split_graph ()"+)+_SPLITS_ALLOC_ABORT = (+ "ggml/src/ggml-backend.cpp:1352: GGML_ASSERT(sched->splits != NULL) failed\n"+ "#2 ggml_abort ()\n#3 ggml_backend_sched_split_graph ()"+)+_OOM_OUTPUT = "llama_model_load: error loading model: unable to allocate buffer\nkilled"+_CLEAN_OUTPUT = "main: server is listening on http://127.0.0.1:8080 - starting the main loop"+++def test_matcher_fires_on_full_abort_and_short_tail():+ assert LlamaCppBackend._is_sched_reserve_abort(_FULL_ABORT)+ assert "GGML_ASSERT(*cur_backend_id != -1)".lower() not in _ABORT_TAIL.lower()+ assert LlamaCppBackend._is_sched_reserve_abort(_ABORT_TAIL)+++def test_matcher_ignores_unrelated_crashes():+ assert not LlamaCppBackend._is_sched_reserve_abort(_SPLIT_AXIS_ABORT)+ assert not LlamaCppBackend._is_sched_reserve_abort(_OOM_OUTPUT)+ assert not LlamaCppBackend._is_sched_reserve_abort(_CUDA_OOM_ABORT)+ assert not LlamaCppBackend._is_sched_reserve_abort(_CONTEXT_INIT_ABORT)+ assert not LlamaCppBackend._is_sched_reserve_abort(_SPLITS_ALLOC_ABORT)+ assert not LlamaCppBackend._is_sched_reserve_abort(_CLEAN_OUTPUT)+ assert not LlamaCppBackend._is_sched_reserve_abort("")+++def test_matcher_requires_both_a_ggml_marker_and_a_scheduler_marker():+ assert not LlamaCppBackend._is_sched_reserve_abort("graph_reserve completed in 3ms")+ assert not LlamaCppBackend._is_sched_reserve_abort("ggml_abort: tensor type mismatch")+++def test_classifier_surfaces_actionable_message():+ msg = LlamaCppBackend._classify_llama_start_failure(+ _ABORT_TAIL,+ gguf_path = "/x/GLM-5.2-UD-Q6_K-00001-of-00014.gguf",+ model_identifier = "unsloth/GLM-5.2-GGUF",+ returncode = -6,+ )+ assert msg == LlamaCppBackend._sched_reserve_abort_message()+ assert "cur_backend_id" in msg+ assert "failed to start" not in msg # not the generic fallback+++def test_classifier_generic_fallback_unchanged_for_unknown_crash():+ msg = LlamaCppBackend._classify_llama_start_failure(+ "some unrelated failure",+ gguf_path = None,+ model_identifier = None,+ returncode = -6,+ )+ assert "failed to start" in msg and "enough memory" in msg+++def test_memo_round_trip_and_isolation(tmp_path):+ binary = tmp_path / "llama-server"+ binary.write_text("x")+ b, model = str(binary), "unsloth/GLM-5.2-GGUF"++ LlamaCppBackend._sched_reserve_abort_keys.clear()+ assert not LlamaCppBackend._sched_reserve_aborts(b, model)+ LlamaCppBackend._record_sched_reserve_abort(b, model)+ assert LlamaCppBackend._sched_reserve_aborts(b, model)+ assert not LlamaCppBackend._sched_reserve_aborts(b, "unsloth/Qwen3.5-4B-MTP-GGUF")+ LlamaCppBackend._sched_reserve_abort_keys.clear()+++def test_memo_invalidated_by_binary_mtime_change(tmp_path):+ binary = tmp_path / "llama-server"+ binary.write_text("v1")+ b, model = str(binary), "unsloth/GLM-5.2-GGUF"++ LlamaCppBackend._sched_reserve_abort_keys.clear()+ LlamaCppBackend._record_sched_reserve_abort(b, model)+ assert LlamaCppBackend._sched_reserve_aborts(b, model)+ st = binary.stat()+ os.utime(binary, ns = (st.st_atime_ns + 10**9, st.st_mtime_ns + 10**9))+ assert not LlamaCppBackend._sched_reserve_aborts(b, model)+ LlamaCppBackend._sched_reserve_abort_keys.clear()+++def test_memo_safe_with_missing_binary_or_model():+ assert not LlamaCppBackend._sched_reserve_aborts(None, "m")+ assert not LlamaCppBackend._sched_reserve_aborts("/x", None)+ LlamaCppBackend._record_sched_reserve_abort(None, None) # no-op, no raise+++_REAL_POPEN = subprocess.Popen+_ABORT_OUTPUT = [+ "/src/ggml/src/ggml-backend.cpp:1242: GGML_ASSERT(*cur_backend_id != -1) failed\n",+ "#3 ggml_backend_sched_split_graph ()\n",+ "#5 llama_context::sched_reserve() ()\n",+]+++def _write_gguf(path: Path) -> Path:+ def string(value: str) -> bytes:+ data = value.encode()+ return struct.pack("<Q", len(data)) + data++ metadata = string("general.architecture") + struct.pack("<I", 8) + string("llama")+ path.write_bytes(struct.pack("<IIQQ", 0x46554747, 3, 0, 1) + metadata)+ return path+++class _Crashing:+ """A CPU-only backend whose every llama-server spawn aborts in the graph scheduler."""++ def __init__(self, tmp_path):+ binary = tmp_path / "llama-server"+ binary.write_text("x")+ b = LlamaCppBackend()+ b._get_gpu_memory = lambda _binary = None, **kw: []+ b._get_gpu_free_memory = lambda _binary = None, **kw: []+ b._read_gguf_metadata = lambda _path: None+ b._can_estimate_kv = lambda: False+ b._get_gguf_size_bytes = lambda _path: 1024+ b._mmproj_vram_bytes = lambda _path: 0+ b._resolve_launch_mmproj_path = lambda **kwargs: None+ b._apu_ram_shortfall_message = lambda *args, **kwargs: None+ b._amd_apu_wants_unified_memory = lambda *args, **kwargs: False+ b._find_llama_server_binary = lambda include_denied = False: str(binary)+ b._is_vulkan_backend = lambda _binary = None: False+ b._detect_audio_type_strict = lambda: None+ b._apply_detected_audio = lambda _detected: True++ def crashed(timeout, **_kw):+ # As the real wait does on exit: let the drain thread collect the tail.+ if b._stdout_thread is not None:+ b._stdout_thread.join(timeout = 2)+ return False++ b._wait_for_health = crashed+ self.backend = b+ self.gguf = _write_gguf(tmp_path / "model.gguf")+ self.spawns = 0+ self.outputs = None # per-spawn output override, consumed in order+ self.projector_fails = False # --mmproj spawns fail without the abort++ def load(self, **load_kwargs) -> str:+ def fake_popen(cmd, **kwargs):+ if not cmd or "--port" not in [str(c) for c in cmd]:+ return _REAL_POPEN(cmd, **kwargs)+ self.spawns += 1+ lines = self.outputs.pop(0) if self.outputs else _ABORT_OUTPUT+ if self.projector_fails and "--mmproj" in [str(c) for c in cmd]:+ lines = ["clip_init: failed to load model\n"]+ return type(+ "Process",+ (),+ {+ "pid": 123,+ "returncode": -6,+ "stdout": iter(lines),+ "poll": lambda self: -6,+ "terminate": lambda self: None,+ "wait": lambda self, timeout = None: -6,+ "kill": lambda self: None,+ },+ )()++ with (+ patch.object(subprocess, "Popen", side_effect = fake_popen),+ pytest.raises(RuntimeError) as err,+ ):+ self.backend.load_model(+ GgufLoadIntent(gguf_path = str(self.gguf), model_identifier = "t", **load_kwargs)+ )+ return str(err.value)+++def crashing(tmp_path):+ LlamaCppBackend._sched_reserve_abort_keys.clear()+ yield _Crashing(tmp_path)+ LlamaCppBackend._sched_reserve_abort_keys.clear()+++def test_scheduler_abort_names_the_cause(crashing):+ assert crashing.load() == LlamaCppBackend._sched_reserve_abort_message()+++def test_identical_replay_fails_fast_without_spawning(crashing):+ crashing.load()+ before = crashing.spawns+ kills = []+ crashing.backend._kill_process = lambda: kills.append(1)+ assert crashing.load() == LlamaCppBackend._sched_reserve_abort_message()+ assert crashing.spawns == before+ assert not kills, "a memoed replay must not tear down the running server"+++ "change", [{"n_ctx": 2048}, {"tensor_parallel": True}, {"force_reload": True}]+)+def test_a_changed_setting_is_allowed_to_retry(crashing, change):+ crashing.load()+ before = crashing.spawns+ crashing.load(**change)+ assert crashing.spawns > before+++def test_hub_cache_hint_does_not_defeat_the_memo(crashing):+ crashing.load()+ before = crashing.spawns+ hint = (str(crashing.gguf), "unsloth/GLM-5.2-GGUF", "main", ((crashing.gguf.name, 1),))+ crashing.load(verified_gguf = hint)+ assert crashing.spawns == before+++def test_forced_reload_that_does_not_abort_clears_the_memo(crashing):+ crashing.load()+ crashing.outputs = [["llama_model_load: error loading model\n"]] * 2+ crashing.load(force_reload = True)+ before = crashing.spawns+ crashing.load()+ assert crashing.spawns > before+++def test_text_only_retry_abort_is_memoed(crashing, tmp_path):+ mmproj = _write_gguf(tmp_path / "mmproj.gguf")+ crashing.backend._resolve_launch_mmproj_path = lambda **kwargs: str(mmproj)+ crashing.projector_fails = True+ crashing.load(mmproj_path = str(mmproj), is_vision = True)+ before = crashing.spawns+ crashing.load(mmproj_path = str(mmproj), is_vision = True)+ assert crashing.spawns == before+++def test_a_changed_vram_budget_is_allowed_to_retry(crashing):+ crashing.load()+ before = crashing.spawns+ with patch("core.inference.llama_cpp._active_vram_fraction", return_value = 0.5):+ crashing.load()+ assert crashing.spawns > before+++def test_a_changed_model_memory_setting_is_allowed_to_retry(crashing):+ with patch(+ "core.inference.llama_cpp._model_memory_settings_or_none", return_value = (False, False)+ ):+ crashing.load()+ before = crashing.spawns+ with patch(+ "core.inference.llama_cpp._model_memory_settings_or_none", return_value = (True, False)+ ):+ crashing.load()+ assert crashing.spawns > before