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: fit Auto context to system RAM on CPU-only machines (#16689)
Nilay80cf144094e7
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.pyindex ec2c83de002..489bc54ed7a 100644--- a/studio/backend/core/inference/llama_cpp.py+++ b/studio/backend/core/inference/llama_cpp.py@@ -27006,6 +27006,42 @@ class LlamaCppBackend:if need_mib > budget_mib:_metal_alongside_shortfall = (need_mib, budget_mib)+ elif (+ not explicit_ctx+ and gpu_memory_mode != "manual"+ and effective_ctx > 0+ and (_arch_gate_forced_cpu or self._binary_ships_no_gpu_backend(binary))+ and not (_extra_args_device(extra_args, {"--rpc"}) or "").strip()+ and not str(os.environ.get("LLAMA_ARG_RPC", "")).strip()+ ):+ # -c is emitted, so --fit cannot shrink it to host RAM. An empty probe is not+ # CPU-only (SYCL is never probed), and --rpc places KV on remote devices.+ effective_ctx = min(+ effective_ctx,+ _APPLE_AUTO_CTX if self._can_estimate_kv() else _FIT_MIN_CTX,+ )+ _host_avail_mib = self._available_system_memory_mib()+ if _host_avail_mib is not None:+ effective_ctx = self._fit_context_to_vram(+ effective_ctx,+ _host_avail_mib - _HOST_RAM_HEADROOM_MIB,+ model_size_fit,+ cache_type_kv,+ min_ctx = _FIT_MIN_CTX,+ swa_full = swa_full,+ n_parallel = n_parallel,+ kv_unified = planned_kv_unified,+ n_ubatch = _effective_ubatch,+ flash_attn = planned_flash_attn,+ mtp_engaged = _mtp_reserves_gpu,+ mtp_overhead_fn = mtp_overhead_fn,+ compute_ctx_bytes_fn = _cc_bytes,+ budget_frac = 1.0,+ pooled = True,+ total_mib = None,+ ctx_checkpoints = _fit_ctx_checkpoints,+ )+# Prefer fewer serving slots on GPU over --fit on offload: when the extra# --parallel slots push the footprint past the pin budget, llama-server# offloads layers to host and decode collapses ~3x (#6718). Retry the fitdiff --git a/studio/backend/tests/test_cpu_auto_context_fits_host_ram.py b/studio/backend/tests/test_cpu_auto_context_fits_host_ram.pynew file mode 100644index 00000000000..a72ecb0df2d--- /dev/null+++ b/studio/backend/tests/test_cpu_auto_context_fits_host_ram.py@@ -0,0 +1,112 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Auto context on a machine with no GPU fits host RAM instead of the model's native window."""++from __future__ import annotations++import importlib.util+from pathlib import Path++import pytest++_TESTS_DIR = Path(__file__).resolve().parent+_spec = importlib.util.spec_from_file_location(+ "_placement_harness_cpu_auto_ctx", _TESTS_DIR / "test_llama_cpp_placement.py"+)+_placement = importlib.util.module_from_spec(_spec)+_spec.loader.exec_module(_placement)++from core.inference.llama_cpp import _FIT_MIN_CTX, _HOST_RAM_HEADROOM_MIB, LlamaCppBackend # noqa: E402++GIB = 1024**3+MIB = 1024**2+WEIGHTS = int(2.5 * GIB)+COMPUTE = 512 * MIB+NATIVE = 262144+++def _qwen3_4b_header(backend, native):+ def read(_path):+ backend._context_length = native+ backend._n_layers = 36+ backend._n_kv_heads = 8+ backend._n_heads = 32+ backend._embedding_length = 2560+ backend._kv_key_length = 128+ backend._kv_value_length = 128++ return read+++def _cpu_load(+ tmp_path,+ monkeypatch,+ *,+ available_mib,+ native = NATIVE,+ cpu_only_build = True,+ **load_kwargs,+):+ monkeypatch.setattr(+ LlamaCppBackend,+ "_binary_ships_no_gpu_backend",+ staticmethod(lambda *_a, **_kw: cpu_only_build),+ )+ monkeypatch.setattr(+ LlamaCppBackend, "_apple_metal_memory_budget_bytes", staticmethod(lambda: 0)+ )+ monkeypatch.setattr(+ LlamaCppBackend, "_available_system_memory_mib", staticmethod(lambda: available_mib)+ )+ backend, gguf = _placement._backend(tmp_path, vulkan = False, memory = [])+ del backend._can_estimate_kv+ backend._read_gguf_metadata = _qwen3_4b_header(backend, native)+ backend._get_gguf_size_bytes = lambda _path: WEIGHTS+ backend._estimate_compute_buffer_bytes = lambda **_kw: COMPUTE+ backend._compute_buffer_ctx_bytes = lambda *_a, **_kw: 0+ result = _placement._launch(backend, gguf, **load_kwargs)+ return backend, int(_placement._launched(result, "-c"))+++def test_auto_on_a_roomy_cpu_host_does_not_reserve_the_whole_native_window(tmp_path, monkeypatch):+ _backend, ctx = _cpu_load(tmp_path, monkeypatch, available_mib = 64 * 1024, n_ctx = 0)+ assert ctx == 65536+++def test_auto_on_a_small_cpu_host_fits_the_kv_cache_in_free_ram(tmp_path, monkeypatch):+ available_mib = 8 * 1024+ backend, ctx = _cpu_load(tmp_path, monkeypatch, available_mib = available_mib, n_ctx = 0)+ assert _FIT_MIN_CTX <= ctx < 65536+ need = WEIGHTS + COMPUTE + backend._estimate_kv_cache_bytes(ctx)+ assert need <= (available_mib - _HOST_RAM_HEADROOM_MIB) * MIB+++def test_a_shorter_native_window_keeps_its_own_length(tmp_path, monkeypatch):+ _backend, ctx = _cpu_load(tmp_path, monkeypatch, available_mib = 64 * 1024, native = 40960, n_ctx = 0)+ assert ctx == 40960++[email protected]("available_mib", [8 * 1024, 64 * 1024])+def test_an_explicit_context_is_launched_as_asked(tmp_path, monkeypatch, available_mib):+ _backend, ctx = _cpu_load(tmp_path, monkeypatch, available_mib = available_mib, n_ctx = 131072)+ assert ctx == 131072++[email protected]("via_env", [False, True])+def test_rpc_offload_is_not_sized_against_coordinator_ram(tmp_path, monkeypatch, via_env):+ if via_env:+ monkeypatch.setenv("LLAMA_ARG_RPC", "10.0.0.2:50052")+ extra = {}+ else:+ monkeypatch.delenv("LLAMA_ARG_RPC", raising = False)+ extra = {"extra_args": ["--rpc", "10.0.0.2:50052"]}+ _backend, ctx = _cpu_load(tmp_path, monkeypatch, available_mib = 8 * 1024, n_ctx = 0, **extra)+ assert ctx == NATIVE+++def test_an_empty_gpu_probe_on_a_gpu_build_is_not_sized_against_host_ram(tmp_path, monkeypatch):+ _backend, ctx = _cpu_load(+ tmp_path, monkeypatch, available_mib = 8 * 1024, cpu_only_build = False, n_ctx = 0+ )+ assert ctx == NATIVEdiff --git a/studio/backend/tests/test_ctx_checkpoint_host_budget.py b/studio/backend/tests/test_ctx_checkpoint_host_budget.pyindex 70931e90214..48c5d81ec7a 100644--- a/studio/backend/tests/test_ctx_checkpoint_host_budget.py+++ b/studio/backend/tests/test_ctx_checkpoint_host_budget.py@@ -451,7 +451,8 @@ class TestCheckpointsNeverReachAVramFigure:source = inspect.getsource(LlamaCppBackend.load_model)assert "0 if self._rollback_state_bytes(1) > 0 else _requested_ctx_checkpoints" in source- assert source.count("ctx_checkpoints = _fit_ctx_checkpoints,") == 1+ # Host-memory budgets only: Metal unified memory and the CPU-only host RAM fit.+ assert source.count("ctx_checkpoints = _fit_ctx_checkpoints,") == 2# +1: the drafter probe's one-slot fit (#8872)# Per subset (incl. the drafter's slot search): a discrete-tier subset pays none.# The context ceiling (best_cap) prices per subset too.diff --git a/studio/backend/tests/test_vram_budget_settings.py b/studio/backend/tests/test_vram_budget_settings.pyindex 1b00928ffcb..f90a2cedd59 100644--- a/studio/backend/tests/test_vram_budget_settings.py+++ b/studio/backend/tests/test_vram_budget_settings.py@@ -499,11 +499,10 @@ class TestFloorReserve:assert lc._vram_usable_mib(12_000, None, 1.0, pooled = True) == pytest.approx(12_000)def test_every_pooled_caller_says_so(self):- # Six call sites hand _fit_context_to_vram an absolute pool budget (the sixth is- # the drafter probe's one-slot fit, #8872); each has to be marked, since the flag- # is what keeps them from double-paying.+ # Seven call sites pass an absolute pool budget (incl. the drafter probe, #8872, and the+ # CPU-only host RAM fit); each must be marked, or they double-pay.compact = _shared_setup_1()- assert compact.count("budget_frac=1.0,pooled=True,total_mib=None,") == 6+ assert compact.count("budget_frac=1.0,pooled=True,total_mib=None,") == 7class TestRetriesAndDedup: