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: stop the Load Model panel flagging Auto context loads as over VRAM (#12555)
oobabooga58c9cd6aca29
diff --git a/studio/backend/core/inference/llama_server_args.py b/studio/backend/core/inference/llama_server_args.pyindex ac59d7be0a4..87e8acb7c9d 100644--- a/studio/backend/core/inference/llama_server_args.py+++ b/studio/backend/core/inference/llama_server_args.py@@ -590,6 +590,8 @@ _FIT_FLAGS: frozenset[str] = frozenset({"-fit", "--fit"})# The fitter's per-device margin. Never stripped (llama.cpp is last-wins), so a pass-through value is what the child# really keeps free; see fit_target_margin_in._FIT_TARGET_FLAGS: frozenset[str] = frozenset({"-fitt", "--fit-target"})+# The fitter's context floor, also never stripped; see fit_ctx_in.+_FIT_CTX_FLAGS: frozenset[str] = frozenset({"-fitc", "--fit-ctx"})_LAYER_OFFLOAD_FLAGS: frozenset[str] = _GPU_LAYER_FLAGS | _FIT_FLAGS_MOE_OFFLOAD_FLAGS: frozenset[str] = frozenset({"-ncmoe", "--n-cpu-moe", "-cmoe", "--cpu-moe"})_OFFLOAD_SHADOWING_FLAGS: frozenset[str] = _LAYER_OFFLOAD_FLAGS | _MOE_OFFLOAD_FLAGS@@ -1074,6 +1076,25 @@ def fit_is_effectively_on(return str(raw_value).strip().lower() not in _ENV_FALSE_VALUES+def fit_ctx_in(+ args: Optional[Iterable[str]], env: Optional[Mapping[str, str]] = None+) -> Optional[int]:+ """Return the last --fit-ctx, falling back to the supplied environment.++ Unset or invalid values return None. Preserve negatives: llama.cpp stores them+ unsigned, disabling context reduction.+ """+ raw_value = _last_flag_value(args, _FIT_CTX_FLAGS)+ if raw_value is None and env:+ raw_value = env.get("LLAMA_ARG_FIT_CTX")+ if raw_value is None:+ return None+ try:+ return int(str(raw_value).strip())+ except ValueError:+ return None++def fit_target_margin_in(args: Optional[Iterable[str]], env: Optional[Mapping[str, str]] = None) -> Optional[float]:diff --git a/studio/backend/core/inference/memory_contract.py b/studio/backend/core/inference/memory_contract.pyindex e567a8dfa49..20f8b3937f9 100644--- a/studio/backend/core/inference/memory_contract.py+++ b/studio/backend/core/inference/memory_contract.py@@ -86,6 +86,7 @@ def build_memory_estimate(quant_file_bytes: int,native_context: Optional[int] = None,gpu_floor_bytes: Optional[int] = None,+ floor_can_offload: bool = False,context_is_pinned: bool = True,inherited_device_pin: bool = False,spec_unpriced: bool = False,@@ -156,6 +157,7 @@ def build_memory_estimate(else (None if gpu_bytes is None else int(gpu_bytes))),gpu_floor_bytes = None if gpu_floor_bytes is None else int(gpu_floor_bytes),+ floor_can_offload = bool(floor_can_offload),kv_estimable = bool(getattr(breakdown, "kv_estimable", True)),kv_on_gpu = bool(getattr(breakdown, "kv_on_gpu", True)),n_ctx = (@@ -201,6 +203,9 @@ def project_estimate_memory_response(estimate: MemoryEstimate) -> dict:"kv_on_gpu": estimate.kv_on_gpu,"n_ctx": estimate.n_ctx,"context_fitted": estimate.context_fitted,+ "context_is_pinned": estimate.context_is_pinned,+ "gpu_floor_bytes": estimate.gpu_floor_bytes,+ "floor_can_offload": estimate.floor_can_offload,"cache_type_kv": estimate.cache_type_kv,"n_parallel": estimate.n_parallel,"layer_count": estimate.layer_count,diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.pyindex e5f18fbd8c7..1e46f682023 100644--- a/studio/backend/models/inference.py+++ b/studio/backend/models/inference.py@@ -1101,6 +1101,21 @@ class EstimateMemoryResponse(BaseModel):"one, when the machine holds the model's own window, or when the footprint of the ""load cannot be described.",)+ context_is_pinned: bool = Field(+ True,+ description = "False only when the loader will shrink n_ctx to fit, so the "+ "context-linear share of gpu_bytes is an upper bound rather than a reservation.",+ )+ gpu_floor_bytes: Optional[int] = Field(+ None,+ description = "gpu_bytes at the shortest context the loader's fit settles for; "+ "past it the launch offloads layers instead. Set only when context_is_pinned is false.",+ )+ floor_can_offload: bool = Field(+ False,+ description = "Whether a load still over the card at the floor moves layers to the "+ "CPU. False when the layer count is fixed or the fitter is off, where it may fail.",+ )cache_type_kv: Optional[str] = Field(None, description = "KV dtype the estimate priced, after flags and fallbacks resolve")@@ -1188,10 +1203,15 @@ class MemoryEstimate(BaseModel):)gpu_floor_bytes: Optional[int] = Field(None,- description = "What still lands on the GPU at the SHORTEST context: drafter "- "weights, flat compute buffers, recurrent rollback state. None of it shrinks "- "when the context does, so it separates an overage a shorter context fixes from "- "one it cannot. None when it was not computed.",+ description = "gpu_bytes at the shortest context the route prices: the Hub's 256, "+ "which leaves what no context reduction frees (drafter weights, flat compute "+ "buffers, recurrent rollback state), and the Load Model panel's loader fit floor, "+ "past which the launch offloads layers instead. None when it was not computed.",+ )+ floor_can_offload: bool = Field(+ False,+ description = "Whether a load still over the card at the floor moves layers to the "+ "CPU rather than keep a placement llama.cpp's fitter refuses to change.",)kv_estimable: bool = Field(True, description = "False when the header could not size the cache")diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex 3e3aa1321e9..255390d39e8 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -12054,6 +12054,95 @@ def _inherited_ctx_size() -> int:return 0+class _EstimateContextFloor(NamedTuple):+ """Minimum Auto context and whether GPU layers can move to the CPU."""++ ctx: int+ can_offload: bool+++def _estimate_context_floor(+ n_ctx: Optional[int],+ llama_extra_args: Optional[list[str]],+ gpu_memory_mode: Optional[str],+ gpu_layers: Optional[int],+ breakdown: Any,+) -> Optional[_EstimateContextFloor]:+ """The loader's Auto context floor, or None for a pinned context.++ Manual with Auto layers floors at --fit-ctx; fixed layers can still shrink context (common/fit.cpp).+ """+ from core.inference.llama_cpp import (+ _FIT_FLOOR_MIN_CTX,+ _FIT_MIN_CTX,+ _LLAMA_FIT_MIN_CTX,+ LlamaCppBackend,+ _env_asks_for_the_native_context,+ _env_fixes_gpu_layers,+ )+ from core.inference.llama_server_args import (+ _GPU_LAYER_FLAGS,+ _last_flag_value,+ fit_ctx_in,+ fit_is_effectively_on,+ parse_ctx_override,+ parse_gpu_layers_override,+ )+ from utils.hardware import is_apple_silicon++ if (n_ctx or 0) > 0 or not breakdown.kv_on_gpu or not breakdown.kv_estimable:+ return None+ extras = list(llama_extra_args or [])+ try:+ # Keep -c 0 pinned even on Metal: checking its fit budget would require MLX.+ if parse_ctx_override(extras) is not None:+ return None+ # The last -ngl wins. llama.cpp also takes "auto" and "all" here.+ layer_arg = _last_flag_value(extras, _GPU_LAYER_FLAGS)+ except ValueError:+ return None+ if _inherited_ctx_size() > 0:+ return None+ if gpu_memory_mode != "manual":+ # The launch's own --fit on precedes the extras, so only they can turn it off.+ try:+ fitter_runs = fit_is_effectively_on(["--fit", "on", *extras], os.environ)+ except ValueError:+ return None+ # Arguments beat the environment; only auto/-1 let the fitter move layers.+ layers_fixed = _env_fixes_gpu_layers(+ os.environ if layer_arg is None else {"LLAMA_ARG_N_GPU_LAYERS": layer_arg}+ )+ floor_ctx = _FIT_FLOOR_MIN_CTX if is_apple_silicon() else _FIT_MIN_CTX+ return _EstimateContextFloor(floor_ctx, fitter_runs and not layers_fixed)+ # Manual /load folds -ngl into gpu_layers and strips --fit.+ try:+ layer_override = parse_gpu_layers_override(extras)+ except ValueError:+ return None+ if layer_override is not None:+ gpu_layers = layer_override+ if gpu_layers is not None and gpu_layers >= 0:+ return None+ # Manual clears inherited fit/layer settings. Use argv, then the launcher's+ # 8192 when supported, then llama.cpp's 4096.+ try:+ fit_ctx = fit_ctx_in(extras)+ except ValueError:+ return None+ if fit_ctx is None and LlamaCppBackend.probe_server_capabilities().get("supports_fit_ctx"):+ fit_ctx = _FIT_MIN_CTX+ if fit_ctx is None:+ # Without --fit-ctx, an inherited zero keeps native context.+ if _env_asks_for_the_native_context():+ return None+ fit_ctx = _LLAMA_FIT_MIN_CTX+ # Negative wraps unsigned; zero resolves to native context. Neither shrinks.+ if fit_ctx <= 0:+ return None+ return _EstimateContextFloor(fit_ctx, True)++def _launch_required_ubatch_for_config(config,llama_extra_args: Optional[list[str]] = None,@@ -19951,7 +20040,10 @@ async def estimate_memory(if account_access.managed_account() and not native_access_deferred:await asyncio.to_thread(account_access.require_model_access, request.model_path)from core.inference.llama_cpp import _args_place_tensors_on_cpu- from core.inference.llama_server_args import _effective_tensor_parallel+ from core.inference.llama_server_args import (+ _effective_tensor_parallel,+ strip_split_mode_only,+ )request = _resolve_llama_cpp_config(request)if _custom_llama_config(request):@@ -20055,11 +20147,38 @@ async def estimate_memory(# Price the files on this disk, not the repository they came from.config = _localized_estimate_config(config, gguf_path)- breakdown = _gguf_memory_breakdown(+ # A CPU-only launch drops the split flags, so a pin charges no per-device buffers.+ pinned_gpu_ids = (+ None+ if _gguf_offloaded_layer_fraction(+ request.gpu_memory_mode,+ request.gpu_layers,+ None,+ request.llama_extra_args,+ device_pin_governs = bool(request.selected_gpu_ids),+ )+ == 0.0+ else request.selected_gpu_ids or None+ )+ # Resolved as the breakdown does: extras --split-mode wins, Manual fixed layers drop tensor.+ tensor_split = (+ _effective_tensor_parallel(request.llama_extra_args, bool(request.tensor_parallel))+ and _tensor_split_possible(request.selected_gpu_ids or None)+ and _manual_keeps_tensor_split(+ request.gpu_memory_mode,+ request.gpu_layers,+ request.llama_extra_args,+ )+ )+ # The probed inventory is the pool: a Vulkan build's _effective_gpu_count sees none of it.+ device_count = _guard_device_count(+ pinned_gpu_ids, _cached_inference_devices(), tensor_parallel = tensor_split+ )+ price = functools.partial(+ _gguf_memory_breakdown,config,gguf_path,hf_token = request.hf_token,- n_ctx = request.n_ctx or 0,llama_extra_args = request.llama_extra_args,speculative_type = request.speculative_type,n_parallel = resolved_slots,@@ -20068,46 +20187,7 @@ async def estimate_memory(n_batch = request.n_batch,n_ubatch = request.n_ubatch,ctx_checkpoints = request.ctx_checkpoints,- # A layer split across pinned cards replicates the context-linear- # compute term and adds per-device pipeline overhead, so the count- # matters there too, not just in tensor mode. Automatic placement- # stays at one: _guard_device_count makes the same call.- n_devices = _guard_device_count(- # A pin names cards for a launch that puts something on them. At an- # effective layer count of zero the launch is CPU-only and the loader- # drops the split flags, so charging the pinned count added per-device- # pipeline overhead and replicated the context-linear compute term for- # buffers no card allocates: on a two-card pin, 1039 -> 2105 MiB at 4k- # and 1417 -> 5129 MiB at 262k. Asked of the same function the panel- # prices placement with, so the two cannot disagree.- None- if _gguf_offloaded_layer_fraction(- request.gpu_memory_mode,- request.gpu_layers,- None,- request.llama_extra_args,- device_pin_governs = bool(request.selected_gpu_ids),- )- == 0.0- else request.selected_gpu_ids or None,- # Tensor mode replicates its buffers over the whole pool, and on a- # Vulkan build _effective_gpu_count sees none of it. The probed- # inventory is the pool; None falls through to the CUDA count as before.- _cached_inference_devices(),- # Same resolution the breakdown prices with: an extras --split-mode- # decides the mode, not the toggle alone, and one card cannot split.- tensor_parallel = _effective_tensor_parallel(- request.llama_extra_args, bool(request.tensor_parallel)- )- and _tensor_split_possible(request.selected_gpu_ids or None)- # And the Manual drops, about the layer count rather than the pool: a- # tensor count here sizes per-device buffers for a CPU layer split.- and _manual_keeps_tensor_split(- request.gpu_memory_mode,- request.gpu_layers,- request.llama_extra_args,- ),- ),+ n_devices = device_count,disable_vision = bool(request.disable_vision),gpu_memory_mode = request.gpu_memory_mode,gpu_layers = request.gpu_layers,@@ -20118,8 +20198,37 @@ async def estimate_memory(# otherwise and this must read the same way.device_pin_governs = bool(request.selected_gpu_ids),)+ breakdown = price(n_ctx = request.n_ctx or 0)if breakdown is None:return EstimateMemoryResponse(available = False, reason = "unsizable")+ context_floor = _estimate_context_floor(+ request.n_ctx,+ request.llama_extra_args,+ request.gpu_memory_mode,+ request.gpu_layers,+ breakdown,+ )+ floor = None+ if context_floor is not None and breakdown.n_ctx > context_floor.ctx:+ floor = price(n_ctx = context_floor.ctx)+ # A tensor launch can fall back to a layer split on the same cards+ # (preserve_multi_gpu_on_layer), which replicates compute buffers: take the larger.+ if floor is not None and tensor_split:+ layer = price(+ n_ctx = context_floor.ctx,+ tensor_parallel = False,+ # As tensor_fallback.py relaunches.+ llama_extra_args = [+ *(strip_split_mode_only(request.llama_extra_args) or []),+ "--split-mode",+ "layer",+ ],+ n_devices = device_count,+ )+ if layer is not None and layer.gpu_bytes > floor.gpu_bytes:+ floor = layer+ elif context_floor is not None:+ floor = breakdown# Shaped through the canonical MemoryEstimate, the same one# GET /models/kv-cache-estimate goes through, so the two routes cannot# drift apart in vocabulary. The projection is what preserves THIS@@ -20134,6 +20243,11 @@ async def estimate_memory(# below does not carry the field, and inventing a value would put a# wrong number on the canonical route for the sake of a non-null.quant_file_bytes = 0,+ gpu_floor_bytes = (+ None if floor is None else min(int(floor.gpu_bytes), int(breakdown.gpu_bytes))+ ),+ floor_can_offload = context_floor is not None and context_floor.can_offload,+ context_is_pinned = context_floor is None,moe_offload_unmodelled = bool((request.gpu_memory_mode == "manual" and (request.n_cpu_moe or 0) > 0)# Outside Manual the extras keep their expert-placement flags: /loaddiff --git a/studio/backend/tests/test_memory_estimate.py b/studio/backend/tests/test_memory_estimate.pyindex b5e180de1f8..4878e8be834 100644--- a/studio/backend/tests/test_memory_estimate.py+++ b/studio/backend/tests/test_memory_estimate.py@@ -3066,6 +3066,229 @@ class TestAnInheritedContextIsPriced:assert out.n_ctx == 8192+class TestAnAutoContextIsMarkedShrinkable:+ """Only contexts the loader can shrink should use a floor for memory warnings."""++ @pytest.fixture(autouse = True)+ def wide(self, tmp_path, monkeypatch):+ gguf = _write_gguf(tmp_path, "qwen3", {**_GQA_FIELDS, "context_length": 262144})+ config = SimpleNamespace(+ identifier = "local/wide",+ gguf_file = gguf,+ is_gguf = True,+ gguf_variant = None,+ gguf_mmproj_file = None,+ gguf_mtp_file = None,+ gguf_dspark_file = None,+ gguf_dflash_file = None,+ )+ monkeypatch.setattr(ri, "_cached_estimate_config", lambda *a, **kw: config)+ monkeypatch.setattr(ri, "_cached_inference_devices", lambda: [(0, 0, 0)])+ monkeypatch.delenv("LLAMA_ARG_CTX_SIZE", raising = False)+ monkeypatch.delenv("LLAMA_ARG_FIT_CTX", raising = False)+ self.fit_ctx_supported(monkeypatch, True)+ return gguf++ @staticmethod+ def fit_ctx_supported(monkeypatch, supported):+ from core.inference.llama_cpp import LlamaCppBackend+ real = LlamaCppBackend.probe_server_capabilities+ monkeypatch.setattr(+ LlamaCppBackend,+ "probe_server_capabilities",+ classmethod(lambda cls, binary = None: {**real(binary), "supports_fit_ctx": supported}),+ )++ @pytest.mark.parametrize(+ ("request_fields", "fit_ctx_supported", "floor_ctx"),+ [+ ({}, True, 8192),+ ({"gpu_memory_mode": "auto"}, True, 8192),+ # Manual with Auto layers: load_model emits --fit-ctx 8192 where the build takes it.+ ({"gpu_memory_mode": "manual"}, True, 8192),+ ({"gpu_memory_mode": "manual"}, False, 4096),+ # A pass-through --fit-ctx comes last, so it is the floor.+ ({"gpu_memory_mode": "manual", "llama_extra_args": ["-fitc", "16384"]}, True, 16384),+ # /load strips Manual's --fit flags, so the fitter still runs.+ ({"gpu_memory_mode": "manual", "llama_extra_args": ["--fit", "off"]}, True, 8192),+ ],+ )+ def test_an_unnamed_context_is_priced_at_the_fit_floor(+ self, wide, monkeypatch, request_fields, fit_ctx_supported, floor_ctx+ ):+ """Use the loader's fit floor, not the smallest possible context."""+ self.fit_ctx_supported(monkeypatch, fit_ctx_supported)+ resp = _estimate(model_path = wide, **request_fields)+ assert resp.n_ctx == 262144+ assert resp.context_is_pinned is False+ config = ri._cached_estimate_config()+ floor = ri._gguf_memory_breakdown(config, wide, n_ctx = floor_ctx, **request_fields)+ shorter = ri._gguf_memory_breakdown(config, wide, n_ctx = 256, **request_fields)+ assert shorter.gpu_bytes < resp.gpu_floor_bytes == floor.gpu_bytes < resp.gpu_bytes++ def test_a_native_context_under_the_fit_floor_has_nothing_to_shrink(+ self, tmp_path, monkeypatch+ ):+ gguf = _write_gguf(+ tmp_path, "qwen3", {**_GQA_FIELDS, "context_length": 4096}, name = "short.gguf"+ )+ config = SimpleNamespace(**{**vars(ri._cached_estimate_config()), "gguf_file": gguf})+ monkeypatch.setattr(ri, "_cached_estimate_config", lambda *a, **kw: config)+ resp = _estimate(model_path = gguf)+ assert resp.context_is_pinned is False+ assert resp.gpu_floor_bytes == resp.gpu_bytes++ @pytest.mark.parametrize(+ ("request_fields", "env_ctx", "fit_ctx_supported"),+ [+ ({"n_ctx": 8192}, None, True),+ ({"llama_extra_args": ["-c", "0"]}, None, True),+ ({"llama_extra_args": ["--ctx-size=4096"]}, None, True),+ ({"llama_extra_args": ["-nkvo"]}, None, True),+ ({"gpu_memory_mode": "manual", "gpu_layers": 0}, None, True),+ ({"gpu_memory_mode": "manual", "gpu_layers": 99}, None, True),+ # /load folds a Manual -ngl into the layer field, which fixes the placement.+ ({"gpu_memory_mode": "manual", "llama_extra_args": ["-ngl", "99"]}, None, True),+ ({}, "4096", True),+ # Without -c or --fit-ctx, inherited zero preserves native context.+ ({"gpu_memory_mode": "manual"}, "0", False),+ # llama.cpp stores --fit-ctx unsigned, so -1 disables the reduction.+ ({"gpu_memory_mode": "manual", "llama_extra_args": ["--fit-ctx", "-1"]}, None, True),+ ],+ )+ def test_a_context_the_launch_opens_verbatim_stays_pinned(+ self, wide, monkeypatch, request_fields, env_ctx, fit_ctx_supported+ ):+ self.fit_ctx_supported(monkeypatch, fit_ctx_supported)+ if env_ctx is not None:+ monkeypatch.setenv("LLAMA_ARG_CTX_SIZE", env_ctx)+ resp = _estimate(model_path = wide, **request_fields)+ assert resp.available is True+ assert resp.context_is_pinned is True, (request_fields, env_ctx)+ assert resp.gpu_floor_bytes is None++ @pytest.mark.parametrize(("fit_ctx_supported", "floor_ctx"), [(True, 8192), (False, 4096)])+ def test_manual_ignores_the_fit_variables_its_launch_clears(+ self, wide, monkeypatch, fit_ctx_supported, floor_ctx+ ):+ # _MANUAL_PLACEMENT_ENV_VARS: the child never sees LLAMA_ARG_FIT_CTX or the layers.+ monkeypatch.setenv("LLAMA_ARG_FIT_CTX", "16384")+ monkeypatch.setenv("LLAMA_ARG_N_GPU_LAYERS", "20")+ self.fit_ctx_supported(monkeypatch, fit_ctx_supported)+ manual = {"gpu_memory_mode": "manual"}+ floor = ri._gguf_memory_breakdown(+ ri._cached_estimate_config(), wide, n_ctx = floor_ctx, **manual+ )+ resp = _estimate(model_path = wide, **manual)+ assert resp.gpu_floor_bytes == floor.gpu_bytes+ assert resp.floor_can_offload is True++ @pytest.mark.parametrize("request_fields", [{}, {"gpu_memory_mode": "manual"}])+ def test_an_inherited_zero_is_overruled_by_the_launch(self, wide, monkeypatch, request_fields):+ # Auto placement emits its own -c, and Manual its --fit-ctx, after the environment.+ monkeypatch.setenv("LLAMA_ARG_CTX_SIZE", "0")+ assert _estimate(model_path = wide, **request_fields).context_is_pinned is False++ @pytest.mark.parametrize(+ ("request_fields", "env", "can_offload"),+ [+ ({}, {}, True),+ ({"gpu_memory_mode": "manual"}, {}, True),+ # Context can shrink even when these settings prevent layer offload.+ ({"llama_extra_args": ["--fit", "off"]}, {}, False),+ ({"llama_extra_args": ["-ngl", "99"]}, {}, False),+ ({}, {"LLAMA_ARG_N_GPU_LAYERS": "20"}, False),+ # The final -ngl -1 enables offload, overriding earlier arguments and env.+ ({"llama_extra_args": ["-ngl", "-1"]}, {}, True),+ ({"llama_extra_args": ["-ngl", "99", "-ngl", "-1"]}, {}, True),+ ({"llama_extra_args": ["-ngl", "-1"]}, {"LLAMA_ARG_N_GPU_LAYERS": "20"}, True),+ # llama.cpp's spellings: auto is its default, all a count that stands.+ ({"llama_extra_args": ["-ngl", "auto"]}, {}, True),+ ({"llama_extra_args": ["-ngl", "all"]}, {}, False),+ ],+ )+ def test_the_floor_says_whether_layers_can_move_past_it(+ self, wide, monkeypatch, request_fields, env, can_offload+ ):+ for key, value in env.items():+ monkeypatch.setenv(key, value)+ resp = _estimate(model_path = wide, **request_fields)+ assert resp.context_is_pinned is False+ assert resp.floor_can_offload is can_offload, (request_fields, env)++ @pytest.mark.parametrize(+ "request_fields",+ [+ {"llama_extra_args": ["--fit"]},+ {"gpu_memory_mode": "manual", "llama_extra_args": ["--fit-ctx"]},+ {"gpu_memory_mode": "manual", "llama_extra_args": ["-fitc="]},+ ],+ )+ def test_a_half_typed_fit_flag_still_prices(self, wide, request_fields):+ # The panel prices every keystroke of the extras field.+ resp = _estimate(model_path = wide, **request_fields)+ assert resp.available is True+ assert resp.context_is_pinned is True+ assert resp.gpu_floor_bytes is None++ def test_a_zero_fit_ctx_can_land_on_the_native_length(self, wide):+ # The fitter may settle on n_ctx 0, which llama.cpp reads as native.+ resp = _estimate(model_path = wide, gpu_memory_mode = "manual", llama_extra_args = ["-fitc", "0"])+ assert resp.context_is_pinned is True++ @pytest.mark.parametrize("selected_gpu_ids", [None, [0, 1]])+ def test_tensor_mode_takes_the_layer_fallback_floor(self, wide, monkeypatch, selected_gpu_ids):+ """Tensor mode falls back to a layer split on conditions only the launch sees, which+ opens at the layer floor and replicates compute buffers per device. The fallback keeps+ every card the tensor launch had, picked automatically or not, so the floor is priced+ as that layer split whenever it needs more than tensor mode."""+ devices = [(0, 0, 0), (1, 0, 0)]+ monkeypatch.setattr(ri, "_cached_inference_devices", lambda: devices)+ monkeypatch.setattr(ri, "_tensor_split_possible", lambda ids: True)+ config = ri._cached_estimate_config()+ pinned = bool(selected_gpu_ids)+ cards = ri._guard_device_count(selected_gpu_ids, devices, tensor_parallel = True)+ assert cards == 2+ common = dict(+ n_ctx = 8192, n_devices = cards, tensor_split_possible = True, device_pin_governs = pinned+ )+ as_tensor = ri._gguf_memory_breakdown(config, wide, tensor_parallel = True, **common)+ as_layer = ri._gguf_memory_breakdown(+ config,+ wide,+ tensor_parallel = False,+ llama_extra_args = ["--split-mode", "layer"],+ **common,+ )+ # The case under test: tensor alone would read as fitting a budget the fallback misses.+ assert as_tensor.gpu_bytes < as_layer.gpu_bytes+ resp = _estimate(model_path = wide, tensor_parallel = True, selected_gpu_ids = selected_gpu_ids)+ assert resp.context_is_pinned is False+ assert resp.gpu_floor_bytes == as_layer.gpu_bytes+++class TestTheContextFloorFollowsThePlacementPath:+ """Auto placement stops shrinking at a floor that depends on the path the load takes."""++ @staticmethod+ def floor(monkeypatch, *, apple = False):+ import utils.hardware as hardware++ monkeypatch.setattr(hardware, "is_apple_silicon", lambda: apple)+ monkeypatch.delenv("LLAMA_ARG_CTX_SIZE", raising = False)+ monkeypatch.delenv("LLAMA_ARG_N_GPU_LAYERS", raising = False)+ breakdown = SimpleNamespace(kv_on_gpu = True, kv_estimable = True)+ return ri._estimate_context_floor(None, [], "auto", None, breakdown)++ def test_a_layer_split_stops_at_the_fit_floor(self, monkeypatch):+ from core.inference.llama_cpp import _FIT_MIN_CTX+ assert self.floor(monkeypatch).ctx == _FIT_MIN_CTX == 8192++ def test_metal_reprices_down_to_the_smallest_context_it_searches(self, monkeypatch):+ from core.inference.llama_cpp import _FIT_FLOOR_MIN_CTX+ assert self.floor(monkeypatch, apple = True).ctx == _FIT_FLOOR_MIN_CTX == 256++class TestTheResolutionTriesOfflineFirst:"""A repo already on this disk is priced without asking the Hub.diff --git a/studio/frontend/src/features/model-picker/api/memory-estimate.ts b/studio/frontend/src/features/model-picker/api/memory-estimate.tsindex 163de0dd26b..b1392953847 100644--- a/studio/frontend/src/features/model-picker/api/memory-estimate.ts+++ b/studio/frontend/src/features/model-picker/api/memory-estimate.ts@@ -50,6 +50,12 @@ export interface MemoryEstimate {/** What was actually priced, after overrides and clamps resolve. */nCtx: number;contextFitted: number | null;+ /** False when Auto can shrink the priced context to fit. */+ contextIsPinned: boolean;+ /** GPU bytes at the loader's context floor; null when pinned. */+ gpuFloorBytes: number | null;+ /** Whether a load still over the card at the floor moves layers to the CPU. */+ floorCanOffload: boolean;cacheTypeKv: string | null;nParallel: number;layerCount: number | null;@@ -103,6 +109,9 @@ const UNAVAILABLE: MemoryEstimate = {kvOnGpu: true,nCtx: 0,contextFitted: null,+ contextIsPinned: true,+ gpuFloorBytes: null,+ floorCanOffload: false,cacheTypeKv: null,nParallel: 1,layerCount: null,@@ -128,6 +137,9 @@ interface ApiEstimateResponse {kv_on_gpu: boolean;n_ctx: number;context_fitted?: number | null;+ context_is_pinned?: boolean;+ gpu_floor_bytes?: number | null;+ floor_can_offload?: boolean;cache_type_kv: string | null;n_parallel: number;layer_count: number | null;@@ -242,6 +254,10 @@ function toMemoryEstimate(body: ApiEstimateResponse): MemoryEstimate {kvOnGpu: flag(body.kv_on_gpu, true),nCtx: finiteCount(body.n_ctx, 0),contextFitted: nullableCount(body.context_fitted),+ // Preserve older backends' verdicts when these fields are absent.+ contextIsPinned: flag(body.context_is_pinned, true),+ gpuFloorBytes: nullableCount(body.gpu_floor_bytes),+ floorCanOffload: flag(body.floor_can_offload, false),cacheTypeKv:typeof body.cache_type_kv === "string" ? body.cache_type_kv : null,nParallel: finiteCount(body.n_parallel, 1),diff --git a/studio/frontend/src/features/model-picker/model-config/memory-fit.ts b/studio/frontend/src/features/model-picker/model-config/memory-fit.tsindex 6c874ee011f..28620b2c674 100644--- a/studio/frontend/src/features/model-picker/model-config/memory-fit.ts+++ b/studio/frontend/src/features/model-picker/model-config/memory-fit.ts@@ -76,6 +76,14 @@ export interface MemoryFitEstimate {adaptersUnsized: boolean;/** `--n-cpu-moe` is set, so the GPU figure ignores it and reads high. */moeOffloadUnmodelled: boolean;+ /** False when the loader will shrink the priced context to fit. Absent reads as pinned. */+ contextIsPinned?: boolean;+ /** `gpuBytes` at the context the loader stops shrinking at, sent with an unpinned context. */+ gpuFloorBytes?: number | null;+ /** Whether a load still over the card at the floor moves layers to the CPU. */+ floorCanOffload?: boolean;+ /** The context the figures were priced at. */+ nCtx?: number;}/** What the load may draw on, as resolved by resolveMemoryCapacityGb and the host. */@@ -226,6 +234,43 @@ export interface MemoryFitResult {advisory: MemoryAdvisory | null;}+/** Whether Auto has a usable GPU estimate at its context floor. */+function hasContextFloor(estimate: MemoryFitEstimate): boolean {+ return estimate.contextIsPinned === false && Number.isFinite(estimate.gpuFloorBytes);+}++/** Use the GPU floor when Auto's native context exceeds capacity. Keep host terms at+ * native as an upper bound: the fitted context is unknown and cache growth can be nonlinear. */+function autoContextFigures(+ estimate: MemoryFitEstimate,+ capacity: MemoryFitCapacity,+ cpuOnly: boolean,+): { gpuBytes: number; totalBytes: number; contextShrinks: boolean } {+ const native = { gpuBytes: estimate.gpuBytes, totalBytes: estimate.totalBytes, contextShrinks: false };+ // Avoid coercing invalid figures into a fit.+ if (+ cpuOnly ||+ !hasContextFloor(estimate) ||+ !Number.isFinite(estimate.gpuBytes) ||+ !Number.isFinite(estimate.totalBytes)+ ) {+ return native;+ }+ const nativeFit = capacity.singleMemoryPool+ ? classifyMemoryFit(estimate.totalBytes, capacity.totalCapacityGb)+ : classifyMemoryFit(estimate.gpuBytes, capacity.gpuCapacityGb);+ // A context that fits is opened at its native length.+ if (nativeFit !== "exceeds") {+ return native;+ }+ const shrink = Math.max(0, estimate.gpuBytes - (estimate.gpuFloorBytes as number));+ return {+ gpuBytes: estimate.gpuBytes - shrink,+ totalBytes: estimate.totalBytes - shrink,+ contextShrinks: true,+ };+}+/** Every verdict the row shows, plus the one note it prints. `_host_offload_shortfall_message`* refuses a load whose offloaded weights exceed psutil's AVAILABLE memory less a reserve,* not the physical total, so a 70 GB host share read as fitting a 128 GB box with 32 GB@@ -238,10 +283,12 @@ export function resolveMemoryFit(const { singleMemoryPool } = capacity;const cpuOnly =!singleMemoryPool && estimate.gpuBytes === 0 && estimate.totalBytes > 0;- const rawGpuFit = classifyMemoryFit(- estimate.gpuBytes,- capacity.gpuCapacityGb,+ const { gpuBytes, totalBytes, contextShrinks } = autoContextFigures(+ estimate,+ capacity,+ cpuOnly,);+ const rawGpuFit = classifyMemoryFit(gpuBytes, capacity.gpuCapacityGb);// Studio unloads the resident model BEFORE the replacement allocates, so its bytes are about to// be free rather than competing. Charging them counted a model against ITSELF: reloading an// unchanged config warned it would not fit the memory its own resident copy held. Free-memory@@ -256,7 +303,7 @@ export function resolveMemoryFit(// total rather than a GPU share that is not a separate reservation. Asking it of gpuBytes// alone let a partly CPU-offloaded load on a Vulkan iGPU look comfortable.const freeGpuFit = classifyAvailableMemory(- singleMemoryPool ? estimate.totalBytes : estimate.gpuBytes,+ singleMemoryPool ? totalBytes : gpuBytes,capacity.freeGpuCapacityGb,capacity.freeGpuCapacityKnown,singleMemoryPool ? reclaimableTotal : reclaimableGpu,@@ -266,12 +313,12 @@ export function resolveMemoryFit(// Guarded, not subtracted blind: a non-finite figure makes the difference NaN, which// `Math.max(0, ...)` propagates rather than clamps. 0 classifies the same and is printable.const hostShareBytes =- Number.isFinite(estimate.totalBytes) && Number.isFinite(estimate.gpuBytes)- ? Math.max(0, estimate.totalBytes - estimate.gpuBytes)+ Number.isFinite(totalBytes) && Number.isFinite(gpuBytes)+ ? Math.max(0, totalBytes - gpuBytes): 0;// Same question for the other pool, with the same credit. See the two notes above.const usableHostFit = classifyAvailableMemory(- singleMemoryPool ? estimate.totalBytes : hostShareBytes,+ singleMemoryPool ? totalBytes : hostShareBytes,capacity.usableSystemRamGb,capacity.usableSystemRamKnown,singleMemoryPool ? reclaimableTotal : reclaimableTotal - reclaimableGpu,@@ -287,7 +334,7 @@ export function resolveMemoryFit(? "unknown": classifyMemoryFit(hostShareBytes, capacity.systemRamCapacityGb);const combinedFit = classifyMemoryFit(- estimate.totalBytes,+ totalBytes,capacity.totalCapacityGb,);const totalFit = worseMemoryFit(combinedFit, hostShareFit);@@ -321,6 +368,7 @@ export function resolveMemoryFit(rawGpuFit,gpuPressured,hostPressured,+ contextShrinks,}),};}@@ -335,6 +383,8 @@ interface AdvisoryVerdicts {rawGpuFit: MemoryFitVerdict;gpuPressured: boolean;hostPressured: boolean;+ /** The native-context figure exceeds the pool, but Auto context shrinks it to fit. */+ contextShrinks: boolean;}function classifyAvailableMemory(@@ -361,6 +411,19 @@ function classifyAvailableMemory(return classifyMemoryFit(bytes, afterUnloadGb);}+/** Explain why Auto's native estimate can exceed capacity without a warning. */+function contextShrinksAdvisory(estimate: MemoryFitEstimate): MemoryAdvisory {+ const nCtx = estimate.nCtx;+ const priced =+ nCtx != null && Number.isFinite(nCtx) && nCtx > 0+ ? `the full ${nCtx.toLocaleString()}-token context`+ : "the model's full context";+ return {+ tone: "muted",+ text: `Estimated at ${priced}. Auto context will shrink it to fit.`,+ };+}+/** At most one note, most actionable first. An unsizable cache outranks any verdict drawn from* the figures, since it says they are incomplete. Branches on `kvEstimable`, not `bounded`:* both make the figures a floor, but only this one is about the header. The pool split used@@ -421,9 +484,15 @@ export function resolveMemoryAdvisory(if (verdicts.hostPressured || verdicts.gpuPressured) {return {tone: "muted",- text: "Fits this machine, but little memory is free right now. Free memory or try Auto context.",+ text: hasContextFloor(estimate)+ ? "Fits this machine, but little memory is free right now, so Auto may pick a shorter context. Free memory first."+ : "Fits this machine, but little memory is free right now. Free memory or try Auto context.",};}+ // Free-memory pressure takes priority because the loader fits against available memory.+ if (verdicts.contextShrinks) {+ return contextShrinksAdvisory(estimate);+ }return null;}// Moving layers cannot fix a combined capacity shortfall.@@ -452,6 +521,15 @@ export function resolveMemoryAdvisory(};}if (verdicts.gpuFit === "exceeds") {+ // At Auto's floor, further relief requires CPU offload, if these settings allow it.+ if (hasContextFloor(estimate)) {+ return {+ tone: "warn",+ text: estimate.floorCanOffload+ ? "Exceeds GPU memory even at the shortest context the loader tries, so some layers will run on the CPU and generation will be slower."+ : "Exceeds GPU memory even at the shortest context the loader tries, and these settings keep layers from moving to the CPU, so loading may fail.",+ };+ }return {tone: "warn",text: "Exceeds GPU memory. Try Auto context or fewer GPU layers; loading may still fail.",@@ -463,12 +541,19 @@ export function resolveMemoryAdvisory(text: "Fits system RAM, but little is free right now. Free memory, or try a shorter context or smaller model.",};}- if (verdicts.rawGpuFit === "fits" && verdicts.gpuPressured) {+ // Tight still fits the card.+ if ((verdicts.rawGpuFit === "fits" || verdicts.rawGpuFit === "tight") && verdicts.gpuPressured) {return {tone: "muted",- text: "Fits this GPU, but little VRAM is free right now. Free memory or try Auto context.",+ text: hasContextFloor(estimate)+ ? `Fits this GPU, but little VRAM is free right now, so Auto may pick a shorter context${estimate.floorCanOffload ? " or run some layers on the CPU" : ""}. Free memory first.`+ : "Fits this GPU, but little VRAM is free right now. Free memory or try Auto context.",};}+ // As above, show free-memory pressure before the Auto note.+ if (verdicts.contextShrinks) {+ return contextShrinksAdvisory(estimate);+ }return null;}diff --git a/studio/frontend/tests/memory-estimate-narrow-panel.test.ts b/studio/frontend/tests/memory-estimate-narrow-panel.test.tsindex c974c686fe5..518f2bd68e7 100644--- a/studio/frontend/tests/memory-estimate-narrow-panel.test.ts+++ b/studio/frontend/tests/memory-estimate-narrow-panel.test.ts@@ -49,6 +49,9 @@ const props: Props = {adaptersUnsized: false,totalBytes: 5.5 * GIB,contextFitted: null,+ contextIsPinned: true,+ gpuFloorBytes: null,+ floorCanOffload: false,gpuBytes: 4.75 * GIB,kvEstimable: true,kvOnGpu: true,diff --git a/studio/frontend/tests/memory-fit.test.ts b/studio/frontend/tests/memory-fit.test.tsindex 293f320382d..d30019f2214 100644--- a/studio/frontend/tests/memory-fit.test.ts+++ b/studio/frontend/tests/memory-fit.test.ts@@ -644,3 +644,188 @@ test("capacity advice does not assume a pageable load mode", () => {assert.doesNotMatch(result.advisory?.text ?? "", /paging|will load|will fit/);}});++// ---------------------------------------------------------------------------+// Auto context: an unpinned context is priced at the native length, which the loader shrinks++/** An 8 GB card at the default budget, beside 32 GB of RAM. */+const EIGHT_GB_CARD: Partial<MemoryFitCapacity> = {+ gpuCapacityGb: 7.2,+ totalCapacityGb: 39.2,+ systemRamCapacityGb: 32,+ freeGpuCapacityGb: 7,+ usableSystemRamGb: 22,+};+/** Qwen3-8B Q4_K_M at its native 40,960 tokens, and what remains at the shortest context. */+const NATIVE_QWEN3_8B = { gpuBytes: 10.45 * GB, totalBytes: 10.45 * GB, nCtx: 40960 };+const QWEN3_8B_FLOOR = 4.82 * GB;+/** An unpinned context the loader shrinks to `bytes`, with layers free to move past it. */+const floorAt = (bytes: number) => ({+ contextIsPinned: false,+ gpuFloorBytes: bytes,+ floorCanOffload: true,+});++test("an unpinned context over the card is not an overage when the floor fits", () => {+ const result = fit(+ { ...NATIVE_QWEN3_8B, ...floorAt(QWEN3_8B_FLOOR) },+ EIGHT_GB_CARD,+ );+ assert.equal(result.gpuFit, "fits");+ assert.equal(result.totalFit, "fits");+ assert.equal(+ result.advisory?.text,+ "Estimated at the full 40,960-token context. Auto context will shrink it to fit.",+ );+ assert.equal(result.advisory?.tone, "muted");+});++test("a pinned context over the card still exceeds, as does an older backend's answer", () => {+ for (const pin of [{ contextIsPinned: true }, {}]) {+ const result = fit({ ...NATIVE_QWEN3_8B, ...pin }, EIGHT_GB_CARD);+ assert.equal(result.gpuFit, "exceeds", JSON.stringify(pin));+ assert.equal(result.advisory?.text, ADVISORY_TEXTS.gpuExceeds);+ }+});++test("an unpinned context without a floor keeps the native verdict", () => {+ const result = fit(+ { ...NATIVE_QWEN3_8B, contextIsPinned: false, gpuFloorBytes: null },+ EIGHT_GB_CARD,+ );+ assert.equal(result.gpuFit, "exceeds");+});++test("a floor over the card is a real overage, and the note does not send the user to Auto", () => {+ // The floor is Auto's shortest context; past it the launch spills layers to the CPU.+ const result = fit(+ {+ gpuBytes: 14 * GB,+ totalBytes: 14 * GB,+ nCtx: 131072,+ ...floorAt(9 * GB),+ },+ EIGHT_GB_CARD,+ );+ assert.equal(result.gpuFit, "exceeds");+ assert.equal(result.advisory?.tone, "warn");+ assert.equal(+ result.advisory?.text,+ "Exceeds GPU memory even at the shortest context the loader tries, so some layers will run on the CPU and generation will be slower.",+ );+});++test("an unpinned context that already fits prints no note", () => {+ const result = fit(+ { gpuBytes: 4 * GB, totalBytes: 4 * GB, nCtx: 8192, ...floorAt(3.5 * GB) },+ EIGHT_GB_CARD,+ );+ assert.equal(result.gpuFit, "fits");+ assert.equal(result.advisory, null);+});++test("a single pool draws the same verdict from the floor", () => {+ const result = fit(+ { gpuBytes: 70 * GB, totalBytes: 70 * GB, nCtx: 262144, ...floorAt(20 * GB) },+ {},+ APPLE,+ );+ assert.equal(result.totalFit, "fits");+ assert.equal(+ result.advisory?.text,+ "Estimated at the full 262,144-token context. Auto context will shrink it to fit.",+ );+});++test("free-memory pressure outranks the Auto note, since the loader fits against what is free", () => {+ const result = fit(+ { ...NATIVE_QWEN3_8B, ...floorAt(5.92 * GB) },+ { ...EIGHT_GB_CARD, freeGpuCapacityGb: 3 },+ );+ assert.equal(result.gpuFit, "tight");+ assert.equal(+ result.advisory?.text,+ "Fits this GPU, but little VRAM is free right now, so Auto may pick a shorter context or run some layers on the CPU. Free memory first.",+ );+});++test("on one pool, pressure outranks the Auto note too", () => {+ const result = fit(+ { gpuBytes: 70 * GB, totalBytes: 70 * GB, nCtx: 262144, ...floorAt(20 * GB) },+ { freeGpuCapacityGb: 10, usableSystemRamGb: 10 },+ APPLE,+ );+ assert.equal(+ result.advisory?.text,+ "Fits this machine, but little memory is free right now, so Auto may pick a shorter context. Free memory first.",+ );+});++test("pressure still outranks the Auto note when the floor itself is tight", () => {+ // A 7.05 GiB floor on a 7.2 GiB budget classifies tight rather than fits.+ const result = fit(+ { ...NATIVE_QWEN3_8B, ...floorAt(7.05 * GB) },+ { ...EIGHT_GB_CARD, freeGpuCapacityGb: 3 },+ );+ assert.equal(result.rawGpuFit, "tight");+ assert.equal(+ result.advisory?.text,+ "Fits this GPU, but little VRAM is free right now, so Auto may pick a shorter context or run some layers on the CPU. Free memory first.",+ );+});++test("a pinned tight fit under pressure gets the pressure note too", () => {+ const result = fit({ gpuBytes: 7.05 * GB, totalBytes: 7.05 * GB }, { ...EIGHT_GB_CARD, freeGpuCapacityGb: 3 });+ assert.equal(result.rawGpuFit, "tight");+ assert.equal(+ result.advisory?.text,+ "Fits this GPU, but little VRAM is free right now. Free memory or try Auto context.",+ );+});++test("a floor over the card says loading may fail where layers cannot move", () => {+ const result = fit(+ { gpuBytes: 14 * GB, totalBytes: 14 * GB, nCtx: 131072, ...floorAt(9 * GB), floorCanOffload: false },+ EIGHT_GB_CARD,+ );+ assert.equal(result.gpuFit, "exceeds");+ assert.equal(+ result.advisory?.text,+ "Exceeds GPU memory even at the shortest context the loader tries, and these settings keep layers from moving to the CPU, so loading may fail.",+ );+});++test("pressure where layers cannot move promises only a shorter context", () => {+ const result = fit(+ { ...NATIVE_QWEN3_8B, ...floorAt(5.92 * GB), floorCanOffload: false },+ { ...EIGHT_GB_CARD, freeGpuCapacityGb: 3 },+ );+ assert.equal(+ result.advisory?.text,+ "Fits this GPU, but little VRAM is free right now, so Auto may pick a shorter context. Free memory first.",+ );+});++/** 16 GB of RAM beside the 8 GB card, so a host share can be over or under it. */+const SMALL_HOST = { systemRamCapacityGb: 16, totalCapacityGb: 23.2, usableSystemRamGb: 15 };++test("a context whose GPU share fits is opened native, so its host share is too", () => {+ // A drafter cache on the CPU grows with the context, and nothing shrinks it here.+ const result = fit(+ { gpuBytes: 2 * GB, totalBytes: 30 * GB, nCtx: 262144, ...floorAt(1 * GB) },+ { ...EIGHT_GB_CARD, ...SMALL_HOST },+ );+ assert.equal(result.hostShareBytes, 28 * GB);+ assert.equal(result.hostShareFit, "exceeds");+});++test("a shrunk context keeps its host terms at native, the bound that holds", () => {+ // The fitted context is unknown, and sliding-window caches do not grow linearly.+ const result = fit(+ { gpuBytes: 9 * GB, totalBytes: 29 * GB, nCtx: 131072, ...floorAt(5 * GB) },+ { ...EIGHT_GB_CARD, ...SMALL_HOST },+ );+ assert.equal(result.gpuFit, "fits");+ assert.equal(result.hostShareBytes, 20 * GB);+ assert.equal(result.hostShareFit, "exceeds");+});