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
Make the VRAM budget fraction tunable (#8589)
Daniel Han98cefae6dfde
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.pyindex 6c98a9129fd..19587f565c9 100644--- a/studio/backend/core/inference/llama_cpp.py+++ b/studio/backend/core/inference/llama_cpp.py@@ -1948,6 +1948,68 @@ _APPLE_UNIFIED_MEMORY_FRACTION = 0.85_MTP_VRAM_RESERVE_FRAC = 0.05+# Left on every card even at 100%, matching the --fit-target margin llama.cpp+# keeps for its own fitter.+_VRAM_FLOOR_RESERVE_MIB = 512.0++# llama-server's own --fit-target default ("target margin per device for --fit,+# ... default: 1024"): what the fallback fitter leaves when we pass nothing.+_LLAMA_FIT_TARGET_DEFAULT_MIB = 1024.0+++def _vram_reserve_floor_mib(total_mib: float) -> float:+ """Smallest margin a card keeps: 512 MiB, or the default's own reserve if smaller.++ Capping it at the default keeps the budget monotonic. A flat 512 MiB would+ RAISE the reserve the moment the slider passed the default on any card under+ about 17 GiB, where 3% is already less than that: an 8 GiB card offers 7946 MiB+ at 0.97 but only 7680 at 0.971, so nudging the slider up would hand back less+ context, the opposite of what the control promises. Capped, the reserve never+ rises with the fraction, and at or below the default the percentage term always+ wins, so an unset budget is untouched on every card size.+ """+ return min(_VRAM_FLOOR_RESERVE_MIB, (1.0 - _CTX_FIT_VRAM_FRACTION) * total_mib)+++def _vram_usable_mib(+ free_mib: float,+ total_mib: float,+ frac: float,+ *,+ pooled: bool = False,+) -> float:+ """Free MiB one card offers a load at ``frac``, unclamped.++ ``pooled`` marks an already absolute budget summed over cards that have each+ paid their own reserve; charging it again would double count. Everything else+ is one device, including a probe reporting free memory with no total, which+ still has to keep a margin: there the free reading is the only scale available,+ and it agrees with the known-total form at the default.+ """+ if total_mib and total_mib > 0:+ reserve = max((1.0 - frac) * total_mib, _vram_reserve_floor_mib(total_mib))+ return free_mib - reserve+ if pooled:+ return free_mib * frac+ return min(free_mib * frac, free_mib - _vram_reserve_floor_mib(free_mib))+++def _active_vram_fraction() -> float:+ """The user's VRAM budget, or ``_CTX_FIT_VRAM_FRACTION`` when they set none.++ The settings module clamps to a supported range and swallows a corrupt stored+ value, so this cannot widen the budget past 1.0 or hand back a NaN. Imported+ lazily to keep the settings/storage layer off this module's import path, and+ read per call so a change applies to the next load without a restart.+ """+ try:+ from utils.vram_budget_settings import get_vram_budget_fraction+ return get_vram_budget_fraction()+ except Exception:+ # Settings are a convenience; a load must never fail because of them.+ return _CTX_FIT_VRAM_FRACTION++def _kv_bytes_per_elem(cache_type: Optional[str]) -> float:"""Bytes per KV-cache element for a llama.cpp cache type (f16 default)."""return {@@ -3415,6 +3477,12 @@ class LlamaCppBackend:self._effective_parallel_slots: int = 1# --parallel the last load asked for, before any fit-time reduction.self._requested_n_parallel: int = 1+ # Budget the running child was sized against; None before any load, so the+ # settings route reports a stale budget instead of nagging on every save.+ self._vram_fraction_launched: Optional[float] = None+ # Budget a load has committed to but not published, covering planning ->+ # Popen as _memory_launch_pending does for Model Memory placement.+ self._vram_fraction_pending: Optional[float] = None# --batch-size / --ubatch-size the last load asked for; none = defaults or extras / envself._requested_n_batch: Optional[int] = Noneself._requested_n_ubatch: Optional[int] = None@@ -6351,16 +6419,15 @@ class LlamaCppBackend:min_gpus = max(1, min(min_gpus, len(gpus)))model_size_mib = model_size_bytes / (1024 * 1024)if usable_fraction is None:- usable_fraction = LlamaCppBackend._GPU_PIN_VRAM_FRACTION+ usable_fraction = _active_vram_fraction()overhead_mib = per_device_overhead_bytes / (1024 * 1024)- # Per-GPU usable budget: free - (1-frac)*total when total is known, else+ # Per-GPU usable budget: free minus the reserve when total is known, else# the legacy free*frac (also covers a total-0 two-column probe).def _usable(idx: int, free_mib: int) -> float:t = total_by_idx.get(idx, 0) if total_by_idx else 0- if t > 0:- return max(0.0, free_mib - (1.0 - usable_fraction) * t)- return free_mib * usable_fraction+ usable = _vram_usable_mib(free_mib, t, usable_fraction)+ return max(0.0, usable) if t > 0 else usable# Rank by usable budget (free - reserve), not raw free: a more-used large# card can have less usable room than a less-used small one.@@ -7165,6 +7232,8 @@ class LlamaCppBackend:flash_attn: bool = True,kv_on_gpu: bool = True,mtp_engaged: bool = False,+ # True only for an absolute budget already summed across cards.+ pooled: bool = False,mtp_overhead_fn: Optional[Callable[[int], int]] = None,compute_ctx_bytes_fn: Optional[Callable[[int], int]] = None,budget_frac: Optional[float] = None,@@ -7208,12 +7277,11 @@ class LlamaCppBackend:# when dims can't size the draft KV); callers may override budget_frac.if budget_frac is None:flat_mtp = mtp_engaged and mtp_overhead_fn is None- budget_frac = _CTX_FIT_VRAM_FRACTION - (_MTP_VRAM_RESERVE_FRAC if flat_mtp else 0.0)+ budget_frac = _active_vram_fraction() - (_MTP_VRAM_RESERVE_FRAC if flat_mtp else 0.0)# Absolute reserve off total when known, else fraction-of-free; clamp >=0.+ budget_mib = _vram_usable_mib(available_mib, total_mib or 0, budget_frac, pooled = pooled)if total_mib is not None and total_mib > 0:- budget_mib = max(0.0, available_mib - (1.0 - budget_frac) * total_mib)- else:- budget_mib = available_mib * budget_frac+ budget_mib = max(0.0, budget_mib)budget_bytes = budget_mib * 1024 * 1024model_footprint = model_size_bytes@@ -9934,6 +10002,7 @@ class LlamaCppBackend:swa_full: bool = False,kv_unified: bool = True,flash_attn: bool = True,+ vram_fraction: Optional[float] = None,) -> tuple[int, int, list[int], Optional[list[int]]]:"""Plan a ``--split-mode tensor`` load. Pure: no model or GPU needed.@@ -9966,11 +10035,19 @@ class LlamaCppBackend:# Per-GPU usable budget: free - (1-frac)*total, else (unknown total, e.g. a# two-column probe) the legacy free*frac. Mirrors _select_gpus and# _gpu_usable so the 5% cushion is kept on every path, not dropped here.+ # Prefer the caller's resolved budget, so placement and ranking price the+ # SAME fraction even if a save lands mid-load; resolved here only for the+ # direct callers (tests) with no load to inherit from, and once, not per GPU.+ _tp_frac = vram_fraction if vram_fraction is not None else _active_vram_fraction()+def _usable(idx: int, free_mib: int) -> float:+ # Through the shared helper, so the floor reserve the ranking and the+ # layer path apply is charged here too. Tensor mode has no --fit valve,+ # so a budget spent above the floor fails at startup rather than+ # offloading. Clamped on both branches, unlike _select_gpus: this pool+ # is summed, and one negative card must not fund another.t = total_by_idx.get(idx, 0) if total_by_idx else 0- if t > 0:- return max(0.0, free_mib - (1.0 - _CTX_FIT_VRAM_FRACTION) * t)- return max(0.0, free_mib * _CTX_FIT_VRAM_FRACTION)+ return max(0.0, _vram_usable_mib(free_mib, t, _tp_frac))# Drop GPUs whose usable budget can't hold the per-device compute-graph# buffer; they'd OOM in tensor mode. Admitting on raw free would let a@@ -10884,6 +10961,24 @@ class LlamaCppBackend:)self._stdout_thread.start()+ @contextlib.contextmanager+ def _serial_load_scope(self):+ """Hold the serial load lock, and release the pending budget with it.++ The pending fraction is armed before the download, so every exit ahead of+ the spawn has to give it back or the settings route, which reads it before+ is_active, answers from a load that is over. Clearing it on the way out of+ the lock rather than on the way out of the call is what makes that safe:+ a queued load arms its own value the instant it takes the lock, and a+ clear running after that point would discard the marker of a load that is+ still going.+ """+ with self._serial_load_lock:+ try:+ yield+ finally:+ self._vram_fraction_pending = None+@_with_gguf_load_markerdef load_model(self,@@ -10927,7 +11022,7 @@ class LlamaCppBackend:preserve_multi_gpu_on_layer = intent.preserve_multi_gpu_on_layer# Serialise the whole load so concurrent /load calls never leave two# llama-server processes alive (#5401 / #5161). Doesn't block /unload.- with self._serial_load_lock:+ with self._serial_load_scope():# In-app update swapping binaries: refuse fast (set under this lock,# so any in-flight load has drained) instead of using a half-swapped one.if getattr(self, "_llama_update_in_progress", False):@@ -11005,6 +11100,54 @@ class LlamaCppBackend:tensor_split = None,)+ # Fraction of each card this load may claim, resolved ONCE so ranking+ # and fitting price the same number (mixed totals mis-order otherwise);+ # unset means _CTX_FIT_VRAM_FRACTION, the historical behaviour. Under+ # the lock and ahead of the duplicate check, or a queued load would plan+ # with a stale fraction while the check reads the live one, and could+ # evict the resident child for a budget it then fails to apply.+ _vram_frac = _active_vram_fraction()+ # How far this budget moves llama.cpp's own fitter margin, set once the+ # devices are known. Signed: lowering holds more back, raising packs+ # closer to the card. Zero at the default.+ _fit_target_delta_mib = 0.0+ # Set only if that margin actually reached the command line, which is+ # what makes the child budget-priced in a mode the planner skipped.+ _fit_target_priced = False++ def _budget_priced_placement() -> Optional[float]:+ """The fraction this child was sized against, or None if it wasn't.++ Read at call time, because both names it closes over are rebound+ during the load. Every consumer of the fraction is gated on a+ non-empty ``gpus``, so manual mode and a host with no discrete GPU+ plan without it; and an auto Vulkan crash that recovers on CPU+ rewrites the intent to CPU placement while leaving ``gpus``+ populated from the attempt that failed. Recording a budget for+ either would make a later change to the setting evict a healthy+ child for a reload that cannot move anything.+ """+ if intent.cpu_fallback:+ return None+ if gpus:+ return _vram_frac+ # Manual + Auto empties gpus to bypass the planner, but --fit-target+ # still carries the budget to llama.cpp's fitter, so that child IS+ # priced. Without this a later change reports no reload needed and+ # the duplicate check adopts a child on the old margin.+ return _vram_frac if _fit_target_priced else None++ # Armed before the duplicate check, not merely cleared: on an inactive+ # backend a save landing in that gap saw no pending value and no live+ # process, so it was told no reload was needed while this load went on to+ # launch against the captured fraction. The load scope hands it back on+ # every exit, the fast path below included.+ self._vram_fraction_pending = _vram_frac+ # _vram_fraction_launched is committed at the launch site instead: the+ # duplicate-load fast path, a cancellation and every failed preflight+ # return with the previous child still serving, so setting it here would+ # claim that stale child carries the new budget and hide its reload.+# Duplicate /load that raced past the route check: do nothing if the# live server already satisfies this request.if self.adopt_load_intent_if_matched(intent):@@ -11026,6 +11169,9 @@ class LlamaCppBackend:return Falsereturn True+ # Stays armed through the download and planning, which can take minutes.+ # Placement is undecided until the spawn site narrows it: a needless+ # reload prompt beats sizing a child against a replaced budget.self._cancel_event.clear()if _load_cancelled():logger.info("Load cancelled before GGUF resolution")@@ -11425,6 +11571,10 @@ class LlamaCppBackend:# Discovery runs before the metadata read that says diffusion, so a# transient sidecar failure can set this for a drafterless server.self._dflash_retry_needed = False+ # Same reason: this path returns before the launch block, and the+ # diffusion runner ignores the budget, so a previous llama-server's+ # fraction would relaunch a healthy diffusion server on every Apply.+ self._vram_fraction_launched = Nonewith self._lock:if _load_cancelled():logger.info("Load cancelled before diffusion server start")@@ -11832,16 +11982,36 @@ class LlamaCppBackend:# GPU-aware speculative defaults; the list feeds the# CPU-fallback check._detected_gpus = list(gpus)+ # The --fit fallback is llama.cpp's own fitter, which knows nothing+ # about this budget: it keeps its own margin and packs the rest on,+ # so the slider never reached the path that runs when the fit is+ # tightest. Hand it the difference, both directions, measured from+ # the default so an untouched slider leaves the command alone.+ # One broadcast value: --fit-target does take a per-device list, but+ # in llama.cpp's enumeration order, which the visible-device pin and+ # the ROCr/Vulkan ordinal quirks make not ours to assume, and a+ # misaligned list hands a card the wrong margin. So the direction+ # picks the card: lowering scales by the largest, so no device ends+ # up under the margin it asked for, raising by the smallest, so none+ # is taken below its own. Mixed cards gain a little less, and hold+ # back a little more, than a per-device list would.+ if _vram_frac != _CTX_FIT_VRAM_FRACTION and gpus:+ # Free stands in for an unreported total, the same scale+ # _vram_usable_mib falls back to: MIG/vGPU and the two-column+ # probe report no total, and deriving the whole adjustment+ # from a zero would silently drop the budget on exactly the+ # devices whose headroom is hardest to see.+ _scales = [total_by_idx.get(_idx) or _free for _idx, _free in gpus]+ _scale = (+ max(_scales) if _vram_frac < _CTX_FIT_VRAM_FRACTION else min(_scales)+ )+ _fit_target_delta_mib = (_CTX_FIT_VRAM_FRACTION - _vram_frac) * _scale- def _gpu_usable(g, frac = _CTX_FIT_VRAM_FRACTION):- # Per-GPU usable budget for ranking: free - (1-frac)*total.+ def _gpu_usable(g, frac = _vram_frac):# Callers pass the ACTIVE fraction so the ranking matches the- # budget the fit then tests (else mixed totals mis-order).+ # budget the fit then tests, else mixed totals mis-order.idx, free = g- t = total_by_idx.get(idx, 0)- if t > 0:- return free - (1.0 - frac) * t- return free * frac+ return _vram_usable_mib(free, total_by_idx.get(idx, 0), frac)def _pool_budget_mib(subset, frac):# Sum each GPU's own usable budget. Pooling free and total@@ -12327,7 +12497,9 @@ class LlamaCppBackend:def _probe_frac(drafter: bool) -> float:# The flat fraction is the reserve whenever _mtp_bytes is 0.- return self._GPU_PIN_VRAM_FRACTION - (+ # Same budget the fit uses, else the probe answers for a+ # card size the fit never tests.+ return _vram_frac - (_MTP_VRAM_RESERVE_FRACif (drafter and (mtp_overhead_fn is None or _mtp_kv_unsized))else 0.0@@ -12420,6 +12592,7 @@ class LlamaCppBackend:mtp_overhead_fn = None,compute_ctx_bytes_fn = _cc_n,budget_frac = 1.0,+ pooled = True,total_mib = None,))@@ -12499,6 +12672,7 @@ class LlamaCppBackend:mtp_overhead_fn = mtp_overhead_fn,compute_ctx_bytes_fn = _cc_n,budget_frac = 1.0,+ pooled = True,total_mib = None,))@@ -12562,7 +12736,7 @@ class LlamaCppBackend:if (_flat_mtp_engages and not _draft_cpu_no_embedded)else 0.0)- _pin_fraction = self._GPU_PIN_VRAM_FRACTION - _flat_mtp_reserve+ _pin_fraction = _vram_frac - _flat_mtp_reserve# Charge the soft overhead _CTX_FIT_VRAM_FRACTION under-covers on tight# tiers, gated so plain dense loads (#5106) only pay the CUDA-ctx base.@@ -12659,6 +12833,10 @@ class LlamaCppBackend:swa_full = swa_full,kv_unified = planned_kv_unified,flash_attn = planned_flash_attn,+ # Already resolved, not a second read: a mid-load save+ # would otherwise size placement against a fraction the+ # ranking above never used.+ vram_fraction = _vram_frac,)use_fit = Falseelif gpus and self._can_estimate_kv() and effective_ctx > 0:@@ -12669,13 +12847,11 @@ class LlamaCppBackend:if native_ctx_for_cap > 0:ranked_for_cap = sorted(gpus,- key = lambda g: _gpu_usable(- g, _CTX_FIT_VRAM_FRACTION - _flat_mtp_reserve- ),+ key = lambda g: _gpu_usable(g, _vram_frac - _flat_mtp_reserve),reverse = True,)best_cap = 0- _cap_fraction = _CTX_FIT_VRAM_FRACTION - _flat_mtp_reserve+ _cap_fraction = _vram_frac - _flat_mtp_reservefor n_gpus in range(1, len(ranked_for_cap) + 1):subset = ranked_for_cap[:n_gpus]# Per-GPU-consistent pool budget (fixes mixed@@ -12700,6 +12876,7 @@ class LlamaCppBackend:mtp_overhead_fn = mtp_overhead_fn,compute_ctx_bytes_fn = _cc_sub,budget_frac = 1.0,+ pooled = True,total_mib = None,)kv = _kv_bytes(capped)@@ -12786,6 +12963,7 @@ class LlamaCppBackend:mtp_overhead_fn = mtp_overhead_fn,compute_ctx_bytes_fn = _cc_sub,budget_frac = 1.0,+ pooled = True,total_mib = None,)kv = _kv_bytes(capped)@@ -12911,6 +13089,7 @@ class LlamaCppBackend:mtp_overhead_fn = mtp_overhead_fn,compute_ctx_bytes_fn = _cc_bytes,budget_frac = 1.0,+ pooled = True,total_mib = None,)_cap_footprint_mib = (@@ -13261,16 +13440,20 @@ class LlamaCppBackend:except OSError:self._slot_save_dir = Noneself._slot_save_binary = None- cmd.extend(- self._ctx_integrity_flags(- n_parallel,- use_fit,- auto_fit,- requested_ctx,- effective_ctx,- server_caps,- )+ _integrity_flags = self._ctx_integrity_flags(+ n_parallel,+ use_fit,+ auto_fit,+ requested_ctx,+ effective_ctx,+ server_caps,+ fit_target_delta_mib = _fit_target_delta_mib,)+ # From the flags, not the inputs: --fit off, an older server without+ # the capability and a budget at the default all leave the child+ # unpriced, and each is decided inside that call.+ _fit_target_priced = "--fit-target" in _integrity_flags+ cmd.extend(_integrity_flags)offload_overridden = _extra_args_set_any_flag(extra_args, _GPU_OFFLOAD_OVERRIDE_FLAGS)@@ -14300,6 +14483,9 @@ class LlamaCppBackend:def _raise_terminal_load_failure(detail: str) -> NoReturn:if intent.cpu_fallback:self._cleanup_failed_cpu_fallback()+ # No child will carry this budget; left set, the route reads it+ # ahead of is_active and asks for a reload with nothing loaded.+ self._vram_fraction_pending = Noneraise RuntimeError(detail)def _try_auto_vulkan_cpu_fallback(@@ -14362,6 +14548,7 @@ class LlamaCppBackend:binary,)self._cleanup_failed_cpu_fallback()+ self._vram_fraction_pending = Noneraise RuntimeError(detail)intent = self._apply_cpu_fallback_state(@@ -14466,6 +14653,8 @@ class LlamaCppBackend:# child is already committed. Popen clears it, and so does every# exit below, so a failed spawn cannot leave it stuck on.self._memory_launch_pending = True+ self._vram_fraction_pending = _budget_priced_placement()+ healthy = Falsetry:healthy = _spawn_and_wait(cmd)finally:@@ -15032,6 +15221,12 @@ class LlamaCppBackend:# marker intact, and the diffusion runner returns well before it without# consuming, or paying for, any llama-server capability.self._capability_probe_inconclusive = _launch_probe_inconclusive+ # The budget this child was sized against, committed with the rest of+ # the known-good state so a duplicate-load fast path or failed launch+ # leaves the previous marker intact and the route keeps asking for the+ # reload. None when placement never used it (_budget_priced_placement).+ self._vram_fraction_launched = _budget_priced_placement()+ self._vram_fraction_pending = Noneself._requested_n_batch = intent.n_batchself._requested_n_ubatch = intent.n_ubatch# Commit the known-good snapshot + whether MTP+tensor is live, then@@ -15675,6 +15870,21 @@ class LlamaCppBackend:):logger.info("Model Memory policy changed since launch; forcing a reload")return False+ # Same shape as the Model Memory check above: the budget is server-wide, so+ # a save leaves the intent identical and this would report already-loaded with+ # the child still on the old fraction. None means placement never used it+ # (manual, or no discrete GPU), where a reload would change nothing.+ _launched_frac = self._vram_fraction_launched+ # The pending marker, not a fresh read: a load in flight captured its budget+ # under the lock, and re-reading could decide against a different number than+ # the plan that follows. The route's fast path finds it unset and resolves+ # live as before. Reading the marker rather than taking a parameter keeps the+ # signature every caller and test double already has.+ _pending_frac = self._vram_fraction_pending+ _active_frac = _pending_frac if _pending_frac is not None else _active_vram_fraction()+ if _launched_frac is not None and float(_launched_frac) != _active_frac:+ logger.info("VRAM budget changed since launch; forcing a reload")+ return Falseif not self._runtime_matches_intent(intent, candidate_extra_args):return Falseself._record_matching_gpu_request(@@ -15841,6 +16051,7 @@ class LlamaCppBackend:self._memory_policy_active = Falseself._memory_mlock_applicable = Trueself._memory_launch_pending = False+ self._vram_fraction_pending = Noneself._loaded_by_user_action = Falseself._n_ubatch = self._DEFAULT_N_UBATCHself._flash_attn_enabled = True@@ -17035,6 +17246,8 @@ class LlamaCppBackend:requested_ctx: int,effective_ctx: int,caps: dict,+ *,+ fit_target_delta_mib: float = 0.0,) -> list[str]:"""Flags that keep the per-request window equal to the advertised ctx.@@ -17043,10 +17256,13 @@ class LlamaCppBackend:windows of ``-c / N``; restore the shared pool so one request can usethe full context. With ``--fit on``, ``--fit-ctx`` floors the fit stepat an explicitly requested ctx so it offloads or fails instead of- silently shrinking the window. The 8192 auto-floor and tighter- ``--fit-target`` margin apply only under Manual + Auto (``auto_fit``),- which omits ``-c``: on the legacy auto path ``-c 0`` already pins the- native window and ``--fit-ctx 8192`` would override it down to 8192.+ silently shrinking the window. The 8192 auto-floor applies only under+ Manual + Auto (``auto_fit``), which omits ``-c``: on the legacy auto path+ ``-c 0`` already pins the native window and ``--fit-ctx 8192`` would+ override it down to 8192. ``--fit-target`` starts from the tighter 512 MiB+ margin there and from llama.cpp's own default on the legacy path, moved by+ whatever the VRAM budget asks for either way (``fit_target_delta_mib``)+ and never below the 512 MiB floor."""flags: list[str] = []if n_parallel > 1 and caps.get("supports_kv_unified"):@@ -17059,10 +17275,19 @@ class LlamaCppBackend:# Manual + Auto omits -c, so floor at 8192 so --fit doesn't# shrink the window below a usable size.flags.extend(["--fit-ctx", "8192"])- if use_fit and auto_fit and caps.get("supports_fit_target"):- # Leave 512 MiB free per device so llama.cpp packs more of the- # model onto the GPU before spilling to system RAM.- flags.extend(["--fit-target", "512"])+ if use_fit and caps.get("supports_fit_target"):+ # Each path keeps its own starting margin: the tighter 512 under Manual+ # + Auto, so llama.cpp packs more on before spilling to system RAM, and+ # llama.cpp's own 1024 on the legacy path, which passes nothing today.+ # The budget moves that margin from where the path already sits, so the+ # default changes neither, and a raise stops at the same 512 floor every+ # other reserve here respects.+ _base = _VRAM_FLOOR_RESERVE_MIB if auto_fit else _LLAMA_FIT_TARGET_DEFAULT_MIB+ _target = max(_VRAM_FLOOR_RESERVE_MIB, _base + fit_target_delta_mib)+ # The legacy path stays silent when it would only restate llama.cpp's+ # own default, so an untouched slider leaves the command unchanged.+ if auto_fit or _target != _LLAMA_FIT_TARGET_DEFAULT_MIB:+ flags.extend(["--fit-target", str(int(_target))])return flagsdef _query_server_n_ctx(self) -> Optional[int]:diff --git a/studio/backend/routes/settings.py b/studio/backend/routes/settings.pyindex 046387195ec..69a7539c433 100644--- a/studio/backend/routes/settings.py+++ b/studio/backend/routes/settings.py@@ -54,6 +54,13 @@ from utils.model_memory_settings import (set_model_memory_settings,should_mlock,)+from utils.vram_budget_settings import (+ VRAM_FRACTION_DEFAULT,+ VRAM_FRACTION_MAX,+ VRAM_FRACTION_MIN,+ get_vram_budget_state,+ set_vram_budget_fraction,+)from utils.openai_auto_switch_settings import (BATCH_SIZE_MAX,BATCH_SIZE_MIN,@@ -218,6 +225,35 @@ class ModelMemoryResponse(BaseModel):memlock_limit_bytes: Optional[int] = None+class VramBudgetPayload(BaseModel):+ # None clears the stored budget so env/default applies again; it cannot also+ # mean "leave untouched" as the model-memory switches do, since there is one+ # field. Hence required, not defaulted: with a default, {} would mean "clear it"+ # and a client that dropped the field would silently discard the stored budget.+ fraction: Optional[float] = Field(ge = VRAM_FRACTION_MIN, le = VRAM_FRACTION_MAX)++ @field_validator("fraction", mode = "before")+ @classmethod+ def _reject_bool(cls, value: object) -> object:+ # bool subclasses int, so non-strict parsing turns True into 1.0 and stores+ # the max budget instead of 422; pydantic coerces before the util's guard.+ if isinstance(value, bool):+ raise ValueError("fraction must be a number, not a boolean")+ return value+++class VramBudgetResponse(BaseModel):+ fraction: float+ # False when inherited from UNSLOTH_VRAM_FRACTION or the default, so the UI+ # knows whether clearing it would change anything.+ is_stored: bool+ default_fraction: float = VRAM_FRACTION_DEFAULT+ min_fraction: float = VRAM_FRACTION_MIN+ max_fraction: float = VRAM_FRACTION_MAX+ # Read when a load sizes itself, so a change cannot reach a running child.+ reload_required: bool++class HuggingFaceCachePayload(BaseModel):cache_home: Optional[str] = Field(default = None, max_length = 4096)@@ -452,6 +488,45 @@ def _model_memory_response() -> ModelMemoryResponse:)+def _vram_budget_reload_required(fraction: float) -> bool:+ """True when a child is running that was sized against a different budget.++ Compares against the fraction the child actually launched with, not merely+ "is something loaded", so re-saving the same value does not nag for a reload.+ Exact equality is fine: both sides come from the same clamp, so a stored 0.97+ and a launched 0.97 are the same float.+ """+ try:+ from routes.inference import get_llama_cpp_backend++ backend = get_llama_cpp_backend()+ # A planned-but-unspawned load has no _process, so is_active is False while+ # the child is already committed to its captured fraction; answer from the+ # pending value there, as _active_launch_placement does for Model Memory.+ pending = getattr(backend, "_vram_fraction_pending", None)+ if pending is not None:+ return float(pending) != float(fraction)+ if not backend.is_active:+ return False+ launched = getattr(backend, "_vram_fraction_launched", None)+ # A child predating this field, or from a path that never set it, cannot be+ # compared; say no rather than nagging on every save.+ if launched is None:+ return False+ return float(launched) != float(fraction)+ except Exception:+ return False+++def _vram_budget_response() -> VramBudgetResponse:+ fraction, is_stored = get_vram_budget_state()+ return VramBudgetResponse(+ fraction = fraction,+ is_stored = is_stored,+ reload_required = _vram_budget_reload_required(fraction),+ )++def _hugging_face_cache_response() -> HuggingFaceCacheResponse:return HuggingFaceCacheResponse(**cache_status(get_hf_cache_paths()))@@ -547,6 +622,28 @@ def update_model_memory(return _model_memory_response()[email protected]("/vram-budget", response_model = VramBudgetResponse)+def get_vram_budget(current_subject: str = Depends(get_current_subject)) -> VramBudgetResponse:+ return _vram_budget_response()++[email protected]("/vram-budget", response_model = VramBudgetResponse)+def update_vram_budget(+ payload: VramBudgetPayload, current_subject: str = Depends(get_current_subject)+) -> VramBudgetResponse:+ try:+ set_vram_budget_fraction(payload.fraction)+ except ValueError as exc:+ raise log_and_http_error(+ exc,+ 400,+ safe_error_detail(exc, fallback = "Invalid VRAM budget."),+ event = "settings.update_vram_budget_failed",+ log = logger,+ ) from exc+ return _vram_budget_response()++class CodingAgentsResponse(BaseModel):# All agents `unsloth start` supports, in the CLI's declared order.agents: tuple[str, ...] = CODING_AGENTSdiff --git a/studio/backend/tests/test_mtp_vram_budget.py b/studio/backend/tests/test_mtp_vram_budget.pyindex ce4de29172f..483a2bac2f5 100644--- a/studio/backend/tests/test_mtp_vram_budget.py+++ b/studio/backend/tests/test_mtp_vram_budget.py@@ -625,10 +625,13 @@ class TestExtraArgsMtpDetection:def test_load_model_ranks_subsets_by_active_pin_fraction(self):# Auto/cap subset ranking uses the active budget fraction (lowered by the# flat MTP reserve), not a hard-coded 0.95, so the ranking order matches- # the fit budget that is then tested (Finding G4).+ # the fit budget that is then tested (Finding G4). _vram_frac is that+ # fraction resolved once per load: the user's budget, else the constant.compact = "".join(inspect.getsource(LlamaCppBackend.load_model).split())assert "_gpu_usable(g,pin_fraction)" in compact- assert "_gpu_usable(g,_CTX_FIT_VRAM_FRACTION-_flat_mtp_reserve)" in compact+ assert "_gpu_usable(g,_vram_frac-_flat_mtp_reserve)" in compact+ # Resolved once, so a mid-load save cannot split ranking from fitting.+ assert "_vram_frac=_active_vram_fraction()" in compact@pytest.mark.parametrize("args,expected",diff --git a/studio/backend/tests/test_tensor_parallel.py b/studio/backend/tests/test_tensor_parallel.pyindex 8ab7d991946..6b69c908706 100644--- a/studio/backend/tests/test_tensor_parallel.py+++ b/studio/backend/tests/test_tensor_parallel.py@@ -1073,6 +1073,97 @@ def test_fit_context_budget_frac_override_is_tighter():assert backend._fit_context_to_vram(131072, pool_mib, model_size, "f16") == fit_default+def test_fit_context_follows_the_user_vram_budget(monkeypatch):+ """The VRAM budget setting moves the fitted context, in both directions.++ This is the whole point of the setting: the reserve it controls is worth real+ context. An unset budget must land exactly on the historical default, so the+ change is a no-op for anyone who never touches it.+ """+ import utils.vram_budget_settings as vb++ backend = _kv_seeded_backend()+ model_size = 8 * 1024**3+ pool_mib = 24 * 1024+ total_mib = 24 * 1024++ def _fit():+ return backend._fit_context_to_vram(+ 131072, pool_mib, model_size, "f16", total_mib = total_mib+ )++ monkeypatch.delenv(vb.VRAM_FRACTION_ENV_VAR, raising = False)+ monkeypatch.setattr(vb, "_cached_setting", lambda _key: None)+ fit_default = _fit()+ assert fit_default < 131072, "expected the context to be capped at this VRAM tier"++ monkeypatch.setattr(vb, "_cached_setting", lambda _key: 1.0)+ fit_max = _fit()++ monkeypatch.setattr(vb, "_cached_setting", lambda _key: vb.VRAM_FRACTION_MIN)+ fit_min = _fit()++ assert fit_max > fit_default, "claiming the whole card must buy context back"+ assert fit_min < fit_default, "a smaller budget must give context up"++ # And clearing it returns to exactly the historical number, not merely close.+ monkeypatch.setattr(vb, "_cached_setting", lambda _key: None)+ assert _fit() == fit_default+++def test_tensor_plan_leaves_the_floor_reserve_at_a_full_budget():+ """At 100% a tensor plan must leave the same 512 MiB the layer path leaves.++ ``_plan_tensor_parallel`` sized its per-device budget with an inline+ ``free - (1-frac)*total`` instead of ``_vram_usable_mib``, so it skipped+ ``_VRAM_FLOOR_RESERVE_MIB``. The GPU ranking ahead of it applies the floor and+ the model-config panel promises it in so many words ("At 100% a load still+ leaves 512 MiB per card"), so a tensor plan could spend up to 512 MiB per card+ that nothing had reserved -- and tensor mode has no ``--fit`` fallback to+ absorb the overshoot, so it fails at startup instead.+ """+ import core.inference.llama_cpp as lc++ backend = _kv_seeded_backend()+ total_mib = 24 * 1024+ gpus = [(0, total_mib), (1, total_mib)]+ total_by_idx = {0: total_mib, 1: total_mib}++ def _plan(frac: float, model_gb: int):+ return backend._plan_tensor_parallel(+ list(gpus),+ model_gb * 1024**3,+ 131072,+ cache_type_kv = "f16",+ total_by_idx = dict(total_by_idx),+ vram_fraction = frac,+ )++ # The fraction whose percentage reserve is exactly the floor on this card, so+ # a floored 100% and this must plan identically.+ floor_frac = 1.0 - lc._VRAM_FLOOR_RESERVE_MIB / total_mib+ assert floor_frac > lc._CTX_FIT_VRAM_FRACTION, "24 GiB: 1% is under the floor"++ # The weighted split exposes the per-device budget directly: each weight is+ # the usable budget less the per-device buffers.+ *_, split_full = _plan(1.0, 40)+ *_, split_floor = _plan(floor_frac, 40)+ *_, split_default = _plan(lc._CTX_FIT_VRAM_FRACTION, 40)+ assert split_full is not None, "expected a weighted split at this model size"+ assert (+ split_full == split_floor+ ), f"100% spent {split_full} per card where the floor allows {split_floor}"+ # The default still reserves its full 3% (737 MiB > the floor), so the floor+ # must not have flattened every budget onto the same number.+ assert all(d < f for d, f in zip(split_default, split_full))++ # And the fitted context, which is what actually OOMs at startup.+ ctx_full, *_ = _plan(1.0, 36)+ ctx_floor, *_ = _plan(floor_frac, 36)+ assert ctx_full < 131072, "expected the context to be capped at this VRAM tier"+ assert ctx_full == ctx_floor++# ── unsupported-arch load failure -> clean message ───────────────────diff --git a/studio/backend/tests/test_vram_budget_settings.py b/studio/backend/tests/test_vram_budget_settings.pynew file mode 100644index 00000000000..42a653b1ef5--- /dev/null+++ b/studio/backend/tests/test_vram_budget_settings.py@@ -0,0 +1,756 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Unit tests for the VRAM budget setting.++The budget decides how much of each card a load may claim, so the bar is that an+unset budget behaves exactly as the hard-coded 0.97 did, and that no malformed+value can ever reach the fit. A NaN in particular would turn every per-GPU budget+into NaN and silently fit nothing.+"""++from __future__ import annotations++import pytest++import utils.vram_budget_settings as vb++[email protected](autouse = True)+def _isolate(monkeypatch):+ """No stored value and no environment, so each test states its own inputs."""+ monkeypatch.delenv(vb.VRAM_FRACTION_ENV_VAR, raising = False)+ monkeypatch.setattr(vb, "_cached_setting", lambda _key: None)+++class TestCoerceFraction:+ @pytest.mark.parametrize("value", [0.80, 0.9, 0.97, 1.0, "0.85", "1.00"])+ def test_accepts_in_range(self, value):+ assert vb.coerce_fraction(value) == pytest.approx(float(value))++ @pytest.mark.parametrize(+ "value",+ [+ 0.79,+ 1.01,+ 0.0,+ -1.0,+ 2.0, # out of range+ "nan",+ "NaN",+ float("nan"), # NaN loses every comparison+ "inf",+ float("inf"),+ float("-inf"),+ "",+ " ",+ "abc",+ "0.9x",+ None,+ [],+ {},+ ],+ )+ def test_rejects_unusable(self, value):+ assert vb.coerce_fraction(value) is None++ def test_rejects_bool(self):+ # bool subclasses int, so True would coerce to a legitimate-looking 1.0.+ assert vb.coerce_fraction(True) is None+ assert vb.coerce_fraction(False) is None++ def test_boundaries_are_inclusive(self):+ assert vb.coerce_fraction(vb.VRAM_FRACTION_MIN) == vb.VRAM_FRACTION_MIN+ assert vb.coerce_fraction(vb.VRAM_FRACTION_MAX) == vb.VRAM_FRACTION_MAX+++class TestPrecedence:+ def test_unset_is_the_historical_default(self):+ assert vb.get_vram_budget_fraction() == vb.VRAM_FRACTION_DEFAULT++ def test_default_matches_the_constant_it_replaced(self):+ # A no-op when nobody sets a budget, so this must track+ # _CTX_FIT_VRAM_FRACTION. Imported lazily: the inference package is heavy.+ from core.inference.llama_cpp import _CTX_FIT_VRAM_FRACTION+ assert vb.VRAM_FRACTION_DEFAULT == _CTX_FIT_VRAM_FRACTION++ def test_env_beats_default(self, monkeypatch):+ monkeypatch.setenv(vb.VRAM_FRACTION_ENV_VAR, "0.93")+ assert vb.get_vram_budget_fraction() == pytest.approx(0.93)++ def test_bad_env_falls_back_without_raising(self, monkeypatch):+ for bad in ("nan", "12", "-0.5", "abc", ""):+ monkeypatch.setenv(vb.VRAM_FRACTION_ENV_VAR, bad)+ assert vb.get_vram_budget_fraction() == vb.VRAM_FRACTION_DEFAULT++ def test_stored_beats_env(self, monkeypatch):+ monkeypatch.setenv(vb.VRAM_FRACTION_ENV_VAR, "0.90")+ monkeypatch.setattr(vb, "_cached_setting", lambda _key: 0.99)+ assert vb.get_vram_budget_fraction() == pytest.approx(0.99)++ def test_corrupt_stored_value_falls_through_to_env(self, monkeypatch):+ monkeypatch.setenv(vb.VRAM_FRACTION_ENV_VAR, "0.90")+ monkeypatch.setattr(vb, "_cached_setting", lambda _key: "garbage")+ assert vb.get_vram_budget_fraction() == pytest.approx(0.90)++ def test_out_of_range_stored_value_is_ignored(self, monkeypatch):+ # A future build's wider range must not widen the budget on this one.+ monkeypatch.setattr(vb, "_cached_setting", lambda _key: 4.0)+ assert vb.get_vram_budget_fraction() == vb.VRAM_FRACTION_DEFAULT++ def test_unreadable_db_does_not_fail_a_load(self, monkeypatch):+ def _boom(_key):+ raise RuntimeError("database is locked")++ monkeypatch.setattr(vb, "_cached_setting", _boom)+ with pytest.raises(RuntimeError):+ vb.get_vram_budget_fraction()+ # ...but the llama_cpp caller swallows it, which is what protects the load.+ from core.inference.llama_cpp import _active_vram_fraction, _CTX_FIT_VRAM_FRACTION++ assert _active_vram_fraction() == _CTX_FIT_VRAM_FRACTION+++class TestGrid:+ def test_a_tenth_of_a_percent_is_a_legal_budget(self):+ # The slider steps in tenths, so the fraction has to survive storage on+ # that grid or the control would show a value the backend never held.+ assert vb.coerce_fraction(0.975) == 0.975+ assert vb.coerce_fraction("0.975") == 0.975++ def test_off_grid_values_are_quantised_rather_than_refused(self):+ # An environment variable or a hand-written row need not land on a stop.+ assert vb.coerce_fraction(0.9749999999) == 0.975+ assert vb.coerce_fraction(0.9754) == 0.975+ assert vb.coerce_fraction(0.8) == 0.8+ assert vb.coerce_fraction(1.0) == 1.0+++class TestState:+ def test_reports_inherited_values_as_not_stored(self, monkeypatch):+ monkeypatch.setenv(vb.VRAM_FRACTION_ENV_VAR, "0.91")+ fraction, is_stored = vb.get_vram_budget_state()+ assert fraction == pytest.approx(0.91)+ assert is_stored is False++ def test_reports_a_saved_value_as_stored(self, monkeypatch):+ monkeypatch.setattr(vb, "_cached_setting", lambda _key: 0.99)+ fraction, is_stored = vb.get_vram_budget_state()+ assert fraction == pytest.approx(0.99)+ assert is_stored is True+++class TestWrite:+ def test_rejects_out_of_range(self, monkeypatch):+ monkeypatch.setattr(vb, "_invalidate", lambda _key: None)+ for bad in (0.5, 1.5, float("nan"), "abc"):+ with pytest.raises(ValueError):+ vb.set_vram_budget_fraction(bad)++ def test_stores_a_valid_value(self, monkeypatch):+ written: dict = {}+ monkeypatch.setattr(vb, "_invalidate", lambda _key: None)+ monkeypatch.setitem(+ __import__("sys").modules,+ "storage.studio_db",+ type("_M", (), {"upsert_app_settings": staticmethod(written.update)}),+ )+ monkeypatch.setattr(+ vb, "_cached_setting", lambda _key: written.get(vb.VRAM_BUDGET_SETTING_KEY)+ )+ assert vb.set_vram_budget_fraction(0.99) == pytest.approx(0.99)+ assert written == {vb.VRAM_BUDGET_SETTING_KEY: 0.99}++ def test_none_clears_back_to_the_default(self, monkeypatch):+ written: dict = {}+ monkeypatch.setattr(vb, "_invalidate", lambda _key: None)+ monkeypatch.setitem(+ __import__("sys").modules,+ "storage.studio_db",+ type("_M", (), {"upsert_app_settings": staticmethod(written.update)}),+ )+ assert vb.set_vram_budget_fraction(None) == vb.VRAM_FRACTION_DEFAULT+ # A null row reads back as "no value", so env/default applies again.+ assert written == {vb.VRAM_BUDGET_SETTING_KEY: None}+++class TestActiveFractionWiring:+ def test_llama_cpp_uses_the_setting(self, monkeypatch):+ import core.inference.llama_cpp as lc+ monkeypatch.setenv(vb.VRAM_FRACTION_ENV_VAR, "0.88")+ assert lc._active_vram_fraction() == pytest.approx(0.88)++ def test_llama_cpp_defaults_to_the_old_constant(self):+ import core.inference.llama_cpp as lc+ assert lc._active_vram_fraction() == lc._CTX_FIT_VRAM_FRACTION+++class TestLaunchedMarker:+ """``_vram_fraction_launched`` must describe the child that is actually running.++ The settings route reports "reload required" by comparing the saved budget+ against this marker, so a path that returns without launching must leave it+ alone. The duplicate-load fast path is the reachable one: the route declines+ to reuse a resident model while its audio probe is unfinished, so the request+ reaches ``load_model``, which adopts the live server and returns without+ replacing it.+ """++ @staticmethod+ def _resident_backend(monkeypatch, *, launched: float, active: float):+ import core.inference.llama_cpp as lc++ backend = lc.LlamaCppBackend()+ # is_loaded / is_active only test "is not None"; nothing here talks to it.+ backend._process = object()+ backend._healthy = True+ backend._vram_fraction_launched = launched+ # The saved budget the next load would use, different from the running one.+ monkeypatch.setattr(lc, "_active_vram_fraction", lambda: active)+ monkeypatch.setattr(backend, "adopt_load_intent_if_matched", lambda _intent, **_kw: True)+ return backend, lc++ def test_duplicate_load_leaves_the_running_child_marker(self, monkeypatch):+ backend, lc = self._resident_backend(monkeypatch, launched = 0.97, active = 0.85)+ backend._audio_probed = True++ assert backend.load_model(lc.GgufLoadIntent(model_identifier = "owner/repo"))+ # Nothing relaunched, so the child is still on 0.97 and needs a reload.+ assert backend._vram_fraction_launched == pytest.approx(0.97)++ @staticmethod+ def _adoptable(monkeypatch, *, launched):+ """A backend whose every other adopt predicate already matches."""+ import core.inference.llama_cpp as lc++ backend = lc.LlamaCppBackend()+ backend._process = object()+ backend._healthy = True+ backend._vram_fraction_launched = launched+ monkeypatch.setattr(backend, "matches_load_source", lambda _i: True)+ monkeypatch.setattr(backend, "_runtime_matches_intent", lambda _i, _e: True)+ monkeypatch.setattr(backend, "_record_matching_gpu_request", lambda *_a, **_k: None)+ return backend, lc++ def test_adopt_is_refused_when_the_budget_changed(self, monkeypatch):+ # The budget is server-wide and on no request field, so the intent is+ # identical; without this check the slider silently does nothing.+ backend, lc = self._adoptable(monkeypatch, launched = 0.97)+ monkeypatch.setattr(lc, "_active_vram_fraction", lambda: 0.85)++ assert not backend.adopt_load_intent_if_matched(+ lc.GgufLoadIntent(model_identifier = "owner/repo")+ )++ def test_adopt_is_allowed_when_the_budget_is_unchanged(self, monkeypatch):+ backend, lc = self._adoptable(monkeypatch, launched = 0.97)+ monkeypatch.setattr(lc, "_active_vram_fraction", lambda: 0.97)++ assert backend.adopt_load_intent_if_matched(+ lc.GgufLoadIntent(model_identifier = "owner/repo")+ )++ def test_adopt_is_allowed_when_placement_never_used_the_budget(self, monkeypatch):+ # Manual mode and GPU-less hosts plan with no devices, so a reload changes+ # nothing.+ backend, lc = self._adoptable(monkeypatch, launched = None)+ monkeypatch.setattr(lc, "_active_vram_fraction", lambda: 0.85)++ assert backend.adopt_load_intent_if_matched(+ lc.GgufLoadIntent(model_identifier = "owner/repo")+ )++ def test_marker_is_committed_with_the_rest_of_the_launch_state(self):+ # Guards the placement: next to _requested_n_batch, inside the block only a+ # _healthy=True launch runs, not at the top of load_model with no child yet.+ import inspect++ import core.inference.llama_cpp as lc++ compact = "".join(inspect.getsource(lc.LlamaCppBackend.load_model).split())+ assert (+ "self._vram_fraction_launched=_budget_priced_placement()"+ "self._vram_fraction_pending=Noneself._requested_n_batch" in compact+ )++ def test_marker_is_none_when_placement_had_no_devices(self):+ # gpus is empty in manual mode and on GPU-less hosts, and every consumer of+ # the fraction is gated on it, so a value there is a budget the child never+ # applied. Pending value and committed marker share the one predicate.+ import inspect++ import core.inference.llama_cpp as lc++ compact = "".join(inspect.getsource(lc.LlamaCppBackend.load_model).split())+ assert "self._vram_fraction_pending=_budget_priced_placement()" in compact+ assert "self._vram_fraction_launched=_budget_priced_placement()" in compact+++class TestRouteContract:+ """The two places the HTTP layer can answer wrongly on well-formed input."""++ @staticmethod+ def _settings_module():+ import routes.settings as rs+ return rs++ def test_payload_rejects_a_boolean_fraction(self):+ # bool subclasses int, so non-strict parsing turns True into 1.0 and stores+ # the max budget instead of 422; pydantic coerces before the util's guard.+ import pydantic+ import pytest as _pytest++ rs = self._settings_module()+ with _pytest.raises(pydantic.ValidationError):+ rs.VramBudgetPayload.model_validate({"fraction": True})+ with _pytest.raises(pydantic.ValidationError):+ rs.VramBudgetPayload.model_validate_json('{"fraction": true}')+ assert rs.VramBudgetPayload.model_validate({"fraction": 0.9}).fraction == 0.9+ assert rs.VramBudgetPayload.model_validate({"fraction": None}).fraction is None++ def test_reload_required_answers_from_a_load_that_has_not_spawned(self, monkeypatch):+ # The window: load_model captured its fraction but _process is still None,+ # so is_active would report no reload while the child is already committed.+ rs = self._settings_module()++ class _Backend:+ is_active = False+ _vram_fraction_pending = 0.97+ _vram_fraction_launched = None++ monkeypatch.setattr(rs, "get_llama_cpp_backend", lambda: _Backend(), raising = False)+ import routes.inference as ri++ monkeypatch.setattr(ri, "get_llama_cpp_backend", lambda: _Backend(), raising = False)++ assert rs._vram_budget_reload_required(0.85)+ assert not rs._vram_budget_reload_required(0.97)++ def test_reload_not_required_when_no_load_is_in_flight(self, monkeypatch):+ rs = self._settings_module()++ class _Backend:+ is_active = False+ _vram_fraction_pending = None+ _vram_fraction_launched = 0.97++ import routes.inference as ri++ monkeypatch.setattr(ri, "get_llama_cpp_backend", lambda: _Backend(), raising = False)++ assert not rs._vram_budget_reload_required(0.85)+++class TestDiffusionPath:+ def test_the_diffusion_launch_clears_the_marker(self):+ # The diffusion branch returns before the launch block that commits the+ # marker, so a previous llama-server's fraction would survive and, since the+ # dedupe compares it, relaunch a healthy diffusion runner on every Apply.+ import inspect++ import core.inference.llama_cpp as lc++ source = inspect.getsource(lc.LlamaCppBackend.load_model)+ diffusion = source[source.index("if self._is_diffusion:") :]+ diffusion = diffusion[: diffusion.index("_start_diffusion_server")]+ compact = "".join(diffusion.split())+ assert "self._vram_fraction_launched=None" in compact+++class TestLaunchFinalization:+ """The marker and the pending value must describe the child that is running."""++ @staticmethod+ def _load_model_source():+ import inspect++ import core.inference.llama_cpp as lc+ return "".join(inspect.getsource(lc.LlamaCppBackend.load_model).split())++ def test_the_fraction_is_resolved_under_the_load_lock(self):+ # A queued request would otherwise plan with the fraction as it stood on+ # arrival while the duplicate check reads the live one, evicting the+ # resident child for a budget the queued load then fails to apply.+ compact = self._load_model_source()+ lock_at = compact.index("withself._serial_load_scope():")+ resolve_at = compact.index("_vram_frac=_active_vram_fraction()")+ dedupe_at = compact.index("ifself.adopt_load_intent_if_matched(intent)")+ assert lock_at < resolve_at < dedupe_at++ def test_a_healthy_spawn_keeps_the_pending_value_until_the_commit(self):+ # The decode probe and the no-flash, drafter and projector retries run after+ # the first spawn and the marker is committed after them, so releasing the+ # pending value at the spawn would answer from the PREVIOUS child's marker.+ compact = self._load_model_source()+ # Nothing releases it around the spawn now: a failed first attempt can+ # still be retried into a healthy child, and the load scope hands the+ # value back on every exit.+ assert "ifnothealthy:self._vram_fraction_pending=None" not in compact+ assert (+ "self._vram_fraction_launched=_budget_priced_placement()self._vram_fraction_pending=None"+ in compact+ )++ def test_a_cpu_fallback_child_is_not_stamped_with_a_budget(self):+ # An auto Vulkan crash that recovers on CPU rewrites the intent but leaves+ # gpus populated from the failed attempt, so gpus alone would stamp a+ # CPU-only child.+ import inspect++ import core.inference.llama_cpp as lc++ source = inspect.getsource(lc.LlamaCppBackend.load_model)+ helper = source[source.index("def _budget_priced_placement()") :]+ # Bounded by the first statement after the nested def, not by a comment:+ # the comments here get rewritten and the slice should not care.+ helper = helper[: helper.index("self._vram_fraction_pending")]+ compact = "".join(helper.split())+ assert "ifintent.cpu_fallback:returnNone" in compact+ # ...and it is tested first, so no later branch can stamp one.+ assert compact.index("ifintent.cpu_fallback:returnNone") < compact.index("ifgpus:")+++class TestPreLaunchWindow:+ @staticmethod+ def _compact():+ import inspect++ import core.inference.llama_cpp as lc+ return "".join(inspect.getsource(lc.LlamaCppBackend.load_model).split())++ def test_the_pending_value_is_armed_before_the_duplicate_check(self):+ # On an inactive backend a save landing in that gap saw no pending value and+ # no live process, so it was told no reload was needed.+ compact = self._compact()+ armed = compact.index("self._vram_fraction_pending=_vram_frac")+ dedupe = compact.index("ifself.adopt_load_intent_if_matched(intent)")+ assert armed < dedupe++ def test_the_pending_value_is_armed_before_the_download(self):+ # The download and planning before the spawn take minutes with the old child+ # gone, so a save there would be told no reload is needed while the eventual+ # child carries the old fraction.+ compact = self._compact()+ armed = compact.index("self._vram_fraction_pending=_vram_frac\n".strip())+ cancel = compact.index("self._cancel_event.clear()")+ spawn = compact.index("self._vram_fraction_pending=_budget_priced_placement()")+ assert armed < cancel < spawn++ def test_a_terminal_failure_releases_the_pending_value(self):+ # The route reads the pending value before it checks is_active, so a value+ # left behind by a failed load would ask for a reload with nothing loaded.+ import inspect++ import core.inference.llama_cpp as lc++ source = inspect.getsource(lc.LlamaCppBackend.load_model)+ funnel = source[source.index("def _raise_terminal_load_failure") :]+ funnel = funnel[: funnel.index("def _try_auto_vulkan_cpu_fallback")]+ compact = "".join(funnel.split())+ assert "self._vram_fraction_pending=None" in compact+ assert compact.index("self._vram_fraction_pending=None") < compact.index(+ "raiseRuntimeError(detail)"+ )+++class TestPendingOwnership:+ def test_the_pending_value_is_released_with_the_load_lock(self):+ # Armed before the download, so every exit ahead of the spawn must give it+ # back and the route reads it before is_active. The release belongs to the+ # lock, not the call: overlapping /load calls hand the lock over before the+ # first returns, so clearing on the way out would discard the queued marker.+ import inspect++ import core.inference.llama_cpp as lc++ code = [+ line+ for line in inspect.getsource(lc.LlamaCppBackend._serial_load_scope).splitlines()+ if not line.strip().startswith("#")+ ]+ compact = "".join("".join(code).split())+ assert "withself._serial_load_lock:try:yieldfinally:" in compact+ assert compact.endswith("self._vram_fraction_pending=None")+ # And the load has to go through it, or the scope guards nothing.+ load = "".join(inspect.getsource(lc.LlamaCppBackend.load_model).split())+ assert "withself._serial_load_scope():" in load++ def test_a_pre_launch_exit_leaves_no_pending_value(self, monkeypatch):+ # Exercised rather than read: the diffusion path returns before the spawn.+ import core.inference.llama_cpp as lc++ backend = lc.LlamaCppBackend()+ backend._audio_probed = True+ monkeypatch.setattr(lc, "_active_vram_fraction", lambda: 0.9)+ monkeypatch.setattr(backend, "adopt_load_intent_if_matched", lambda _intent: False)+ # Any failure ahead of the spawn will do; the wrapper must still clean up.+ monkeypatch.setattr(+ backend,+ "_find_llama_server_binary",+ lambda *_a, **_k: (_ for _ in ()).throw(RuntimeError("no binary")),+ )+ with pytest.raises(Exception):+ backend.load_model(lc.GgufLoadIntent(model_identifier = "owner/repo"))+ assert backend._vram_fraction_pending is None+++class TestFloorReserve:+ """100% still leaves a card the margin llama.cpp keeps for its own fitter."""++ @staticmethod+ def _usable(free, total, frac):+ import core.inference.llama_cpp as lc+ return lc._vram_usable_mib(free, total, frac)++ @pytest.mark.parametrize("total", [4_096, 8_192, 16_384, 24_576, 81_920])+ def test_raising_the_budget_never_hands_back_less(self, total):+ # A flat floor was non-monotonic under ~17 GiB, where 3% is already less+ # than 512 MiB: an 8 GiB card offered 7946 MiB at 0.97 and 7680 at 0.971,+ # so nudging the slider up cost context.+ usable = [self._usable(total, total, frac) for frac in (0.80, 0.90, 0.97, 0.971, 0.99, 1.0)]+ assert usable == sorted(usable), usable++ def test_the_floor_never_exceeds_the_default_reserve(self):+ import core.inference.llama_cpp as lc+ for total in (4_096, 8_192, 16_384, 24_576, 81_920):+ floor = lc._vram_reserve_floor_mib(total)+ assert floor <= (1.0 - lc._CTX_FIT_VRAM_FRACTION) * total+ assert floor <= lc._VRAM_FLOOR_RESERVE_MIB++ def test_a_card_with_no_reported_total_still_keeps_a_margin(self):+ # MIG/vGPU and the two-column probe report free with no total, so the free+ # reading is the only scale; it agrees with the known-total form at 0.97.+ import core.inference.llama_cpp as lc+ assert self._usable(24_576, 0, 1.0) == pytest.approx(24_576 - lc._VRAM_FLOOR_RESERVE_MIB)+ assert self._usable(24_576, 0, lc._CTX_FIT_VRAM_FRACTION) == pytest.approx(+ 24_576 * lc._CTX_FIT_VRAM_FRACTION+ )++ def test_full_budget_still_leaves_the_floor(self):+ import core.inference.llama_cpp as lc++ # 24 GB card, nothing else resident.+ assert self._usable(24_576, 24_576, 1.0) == pytest.approx(+ 24_576 - lc._VRAM_FLOOR_RESERVE_MIB+ )+ # A card too small for the full floor keeps the default's own reserve, the+ # most that can be left without costing context to someone raising it.+ assert self._usable(8_192, 8_192, 1.0) == pytest.approx(8_192 * lc._CTX_FIT_VRAM_FRACTION)++ @pytest.mark.parametrize("total", [4_096, 8_192, 16_384, 24_576, 81_920])+ def test_the_default_reserve_is_unchanged_on_every_card_size(self, total):+ # The acceptance bar for the whole setting: unset behaves exactly as the+ # hard-coded 0.97 did. The floor must not reach below the default, which+ # it otherwise would on any card under about 17 GB.+ import core.inference.llama_cpp as lc+ assert self._usable(total, total, lc._CTX_FIT_VRAM_FRACTION) == pytest.approx(+ total - (1.0 - lc._CTX_FIT_VRAM_FRACTION) * total+ )++ def test_the_floor_only_binds_where_the_percentage_reserves_less(self):+ import core.inference.llama_cpp as lc++ # 1% of 80 GB is 819 MiB, above the floor, so 99% keeps its percentage.+ assert self._usable(81_920, 81_920, 0.99) == pytest.approx(81_920 * 0.99)+ # 1% of 24 GB is 245 MiB, under the floor, so the floor takes over.+ assert self._usable(24_576, 24_576, 0.99) == pytest.approx(+ 24_576 - lc._VRAM_FLOOR_RESERVE_MIB+ )++ def test_an_absolute_pool_budget_is_not_charged_twice(self):+ # The tensor-parallel paths pass an already computed pool budget with+ # budget_frac = 1.0 and total_mib = None. Flooring there would subtract a+ # reserve the pool budget has already paid for on each of its cards.+ # Said explicitly rather than inferred from the sentinel, or a real card+ # with no reported total would lose its margin at 100% too.+ import core.inference.llama_cpp as lc+ assert lc._vram_usable_mib(12_000, 0, 1.0, pooled = True) == pytest.approx(12_000)+ assert lc._vram_usable_mib(12_000, None, 1.0, pooled = True) == pytest.approx(12_000)++ def test_every_pooled_caller_says_so(self):+ # Five call sites hand _fit_context_to_vram an absolute pool budget; each+ # has to be marked, since the flag is what keeps them from double-paying.+ import inspect++ import core.inference.llama_cpp as lc++ compact = "".join(inspect.getsource(lc.LlamaCppBackend.load_model).split())+ assert compact.count("budget_frac=1.0,pooled=True,total_mib=None,") == 5+++class TestRetriesAndDedup:+ def test_a_nonterminal_retry_keeps_the_pending_value(self):+ # The flash-attn-off and drafterless retries spawn a replacement child, so+ # releasing at the first spawn left that window answered from the previous+ # child's marker. The load scope releases it on every exit.+ import inspect++ import core.inference.llama_cpp as lc++ compact = "".join(inspect.getsource(lc.LlamaCppBackend.load_model).split())+ assert "ifnothealthy:self._vram_fraction_pending=None" not in compact++ def test_the_duplicate_check_uses_the_captured_fraction(self):+ # Resolve-once: the load captured a fraction under the lock, so the check+ # must not read the setting again and decide against a different number.+ import inspect++ import core.inference.llama_cpp as lc++ compact = "".join(inspect.getsource(lc.LlamaCppBackend.load_model).split())+ assert "self._vram_fraction_pending=_vram_frac" in compact+ assert "adopt_load_intent_if_matched(intent)" in compact++ def test_the_route_fast_path_still_resolves_its_own(self, monkeypatch):+ # It has no load to inherit from, so with no marker armed it reads live.+ import core.inference.llama_cpp as lc++ backend = lc.LlamaCppBackend()+ backend._process = object()+ backend._healthy = True+ backend._vram_fraction_launched = 0.97+ monkeypatch.setattr(backend, "matches_load_source", lambda _i: True)+ monkeypatch.setattr(backend, "_runtime_matches_intent", lambda _i, _e: True)+ monkeypatch.setattr(backend, "_record_matching_gpu_request", lambda *_a, **_k: None)+ monkeypatch.setattr(lc, "_active_vram_fraction", lambda: 0.85)+ intent = lc.GgufLoadIntent(model_identifier = "owner/repo")++ assert not backend.adopt_load_intent_if_matched(intent)+ # ...and a load in flight hands its captured fraction over, ahead of that read.+ backend._vram_fraction_pending = 0.97+ assert backend.adopt_load_intent_if_matched(intent)+++class TestFitTarget:+ """The budget has to reach llama.cpp's own fitter on the --fit fallback.++ ``--fit-target`` is documented by the bundled llama-server as the "target+ margin per device for --fit ... default: 1024". Studio passes a tighter 512+ under Manual + Auto and nothing at all on the legacy auto path, so a lowered+ budget stopped at the planner and the fitter still packed to its own margin.+ """++ _CAPS = {"supports_fit_ctx": True, "supports_fit_target": True, "supports_kv_unified": True}++ def _flags(self, *, auto_fit, delta):+ import core.inference.llama_cpp as lc+ return lc.LlamaCppBackend._ctx_integrity_flags(+ 1,+ True,+ auto_fit,+ 0,+ 0,+ self._CAPS,+ fit_target_delta_mib = delta,+ )++ def test_the_default_budget_emits_exactly_what_it_did_before(self):+ # The acceptance bar for the whole feature: an untouched slider must not+ # move a single flag.+ assert self._flags(auto_fit = True, delta = 0.0)[-2:] == ["--fit-target", "512"]+ assert "--fit-target" not in self._flags(auto_fit = False, delta = 0.0)++ def test_a_lowered_budget_reaches_the_fitter_on_both_paths(self):+ # Raised from each path's own starting margin, not from zero: measuring+ # from zero would hand the legacy path 512 where it used to keep 1024, so+ # lowering the slider would have made llama.cpp pack MORE onto the card.+ assert self._flags(auto_fit = True, delta = 4096.0)[-2:] == ["--fit-target", "4608"]+ assert self._flags(auto_fit = False, delta = 4096.0)[-2:] == ["--fit-target", "5120"]++ def test_the_margin_grows_as_the_budget_falls(self):+ seen = [+ int(self._flags(auto_fit = auto, delta = delta)[-1])+ for auto in (True, False)+ for delta in (512.0, 1024.0, 2048.0)+ ]+ assert seen == sorted(seen[:3]) + sorted(seen[3:])++ def test_a_raised_budget_reaches_the_fallback_too(self):+ # 100% is meant to reclaim VRAM on exactly the tight models that fall back+ # to --fit, and there llama.cpp was still keeping its own 1024 MiB, so the+ # slider said one thing and the fitter did another.+ assert self._flags(auto_fit = False, delta = -369.0)[-2:] == ["--fit-target", "655"]++ def test_a_raised_budget_stops_at_the_floor(self):+ # The same 512 MiB floor every other reserve here respects: at 100% a card+ # keeps that much and no less, on this path as on the planner's.+ assert self._flags(auto_fit = False, delta = -4096.0)[-2:] == ["--fit-target", "512"]+ # Manual + Auto already sits on the floor, so raising cannot move it.+ assert self._flags(auto_fit = True, delta = -4096.0)[-2:] == ["--fit-target", "512"]++ def test_nothing_is_emitted_without_the_capability(self):+ # An older llama-server rejects unknown flags outright.+ caps = {"supports_fit_ctx": True, "supports_fit_target": False}+ import core.inference.llama_cpp as lc++ flags = lc.LlamaCppBackend._ctx_integrity_flags(+ 1,+ True,+ True,+ 0,+ 0,+ caps,+ fit_target_delta_mib = 4096.0,+ )+ assert "--fit-target" not in flags++ def test_the_move_is_measured_from_the_card_that_makes_it_safe(self):+ # --fit-target takes a per-device list, but in llama.cpp's enumeration+ # order, which the visible-device pin and the ROCr/Vulkan ordinal quirks+ # make not ours to assume; a misaligned list hands a card the wrong margin.+ # One broadcast value instead, sized by whichever card makes it safe in the+ # direction asked for.+ import inspect++ import core.inference.llama_cpp as lc++ compact = "".join(inspect.getsource(lc.LlamaCppBackend.load_model).split())+ assert "if_vram_frac!=_CTX_FIT_VRAM_FRACTIONandgpus:" in compact+ assert "_fit_target_delta_mib=(_CTX_FIT_VRAM_FRACTION-_vram_frac)*_scale" in compact+ # Direction picks the card, since one value is broadcast to all of them:+ # lowering may leave no device under the margin it asked for, and raising+ # may take none below its own.+ assert "_scale=(max(_scales)if_vram_frac<_CTX_FIT_VRAM_FRACTIONelsemin(_scales))" in compact+ assert "fit_target_delta_mib=_fit_target_delta_mib," in compact+ # Free stands in for an unreported total (MIG/vGPU, two-column probe), or+ # the whole adjustment would come out of a zero and the budget would be+ # dropped on the devices whose headroom is hardest to see.+ assert "total_by_idx.get(_idx)or_freefor_idx,_freeingpus" in compact+++class TestManualAutoIsPriced:+ """Manual + Auto empties ``gpus``, but --fit-target still spends the budget."""++ def _helper(self):+ import inspect++ import core.inference.llama_cpp as lc++ source = inspect.getsource(lc.LlamaCppBackend.load_model)+ helper = source[source.index("def _budget_priced_placement()") :]+ helper = helper[: helper.index("self._vram_fraction_pending")]+ return "".join(helper.split())++ def test_an_unplanned_but_fitted_child_is_still_stamped(self):+ # Otherwise a later change to the setting reports no reload needed and the+ # duplicate check adopts a child still fitting to the old margin. The+ # planner's own consumers are all gated on a non-empty gpus, which is what+ # made an empty one mean "unpriced" until --fit-target started spending it.+ assert "return_vram_fracif_fit_target_pricedelseNone" in self._helper()++ def test_priced_is_read_off_the_emitted_flags(self):+ # --fit off, an older server without the capability, and a budget at the+ # default all leave the child unpriced, and each is decided inside the call+ # that builds the flags rather than by its inputs.+ import inspect++ import core.inference.llama_cpp as lc++ compact = "".join(inspect.getsource(lc.LlamaCppBackend.load_model).split())+ assert '_fit_target_priced="--fit-target"in_integrity_flags' in compact++ def test_a_cpu_fallback_child_is_still_refused(self):+ # The recovery path leaves gpus populated AND may have emitted the flag on+ # the attempt that failed, so this has to be tested ahead of both.+ helper = self._helper()+ assert helper.index("ifintent.cpu_fallback:returnNone") < helper.index("_fit_target_priced")diff --git a/studio/backend/utils/vram_budget_settings.py b/studio/backend/utils/vram_budget_settings.pynew file mode 100644index 00000000000..c163f590eb9--- /dev/null+++ b/studio/backend/utils/vram_budget_settings.py@@ -0,0 +1,161 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Persisted VRAM budget fraction: how much of each GPU a load may claim.++The fit reserves a slice of every card that the model and KV cache may not use,+covering fragmentation, the per-device CUDA context and MoE routing. That slice+was two hard-coded 0.97 constants in ``core.inference.llama_cpp``+(``_CTX_FIT_VRAM_FRACTION``, ``_GPU_PIN_VRAM_FRACTION``), so the only way to+trade it for context was to edit the source.++Raising the fraction hands the reserve back as context; the load can then OOM,+which llama.cpp takes as a hard crash rather than a graceful degrade. Lowering it+pushes tight fits into CPU offload, which is what 0.90 did in #5106. Neither+direction is free, so the default stays exactly where it was and an unset budget+must resolve to ``VRAM_FRACTION_DEFAULT``.++Precedence, matching ``openai_auto_switch_settings``: a stored value wins, the+environment is a standalone startup default, the constant is the last resort.+"""++from __future__ import annotations++import os+import threading+import time+from typing import Any, Optional++VRAM_BUDGET_SETTING_KEY = "vram_budget_fraction"++VRAM_FRACTION_ENV_VAR = "UNSLOTH_VRAM_FRACTION"++# Mirrored in per-model-config.ts as percent for the slider, a pair+# test_vram_budget_settings.py pins together. The default is the historical+# _CTX_FIT_VRAM_FRACTION / _GPU_PIN_VRAM_FRACTION.+VRAM_FRACTION_MIN = 0.80+VRAM_FRACTION_MAX = 1.00+VRAM_FRACTION_DEFAULT = 0.97++# The slider steps in tenths, so 0.975 is legal. Quantising to that grid keeps a+# stored fraction exactly representable as the percent shown.+VRAM_FRACTION_DECIMALS = 3++# Read on the load path, so memo briefly to spare SQLite, as model_memory_settings.+_CACHE_TTL_S = 2.0+_cache_lock = threading.Lock()+_cache: dict[str, tuple[float, Any]] = {}+# Bumped on every write: a read that began before it must not cache its stale+# value, or the new budget would appear to revert for the rest of the TTL.+_generation: dict[str, int] = {}++# Retries converge; the bound only stops a write storm spinning here forever.+_MAX_REREADS = 3+++def _cached_setting(key: str) -> Any:+ for _attempt in range(_MAX_REREADS):+ with _cache_lock:+ hit = _cache.get(key)+ if hit is not None and time.monotonic() - hit[0] < _CACHE_TTL_S:+ return hit[1]+ generation = _generation.get(key, 0)+ try:+ from storage.studio_db import get_app_setting+ stored = get_app_setting(key, None)+ except Exception:+ # An unreadable DB must not fail a load; fall back to the default.+ return None+ with _cache_lock:+ if _generation.get(key, 0) == generation:+ _cache[key] = (time.monotonic(), stored)+ return stored+ # A write landed mid-read, so `stored` predates it and must not be cached.+ return stored+++def _invalidate(key: str) -> None:+ with _cache_lock:+ _cache.pop(key, None)+ _generation[key] = _generation.get(key, 0) + 1+++def coerce_fraction(value: Any) -> Optional[float]:+ """A VRAM fraction in ``[VRAM_FRACTION_MIN, VRAM_FRACTION_MAX]``, else None.++ Accepts the stored JSON number and the raw environment string through the same+ path so a value can never be legal in one and not the other.+ """+ if isinstance(value, bool):+ # bool is an int subclass, and True would otherwise read as 1.0.+ return None+ try:+ fraction = float(value) # None -> TypeError, "" / " " -> ValueError+ except (TypeError, ValueError):+ return None+ # Two-sided on purpose: NaN loses every comparison, so this rejects it; the+ # one-sided form would let NaN through and NaN every per-GPU budget. Mirrors+ # _parse_mem_fraction_env.+ if not VRAM_FRACTION_MIN <= fraction <= VRAM_FRACTION_MAX:+ return None+ return round(fraction, VRAM_FRACTION_DECIMALS)+++def _env_fraction() -> Optional[float]:+ """``UNSLOTH_VRAM_FRACTION``, or None when unset or unusable.++ Read here rather than at import so tests can monkeypatch the environment+ without reloading the module, and so a value exported after startup is picked+ up by the next load.+ """+ return coerce_fraction(os.environ.get(VRAM_FRACTION_ENV_VAR))+++def get_vram_budget_fraction() -> float:+ """The fraction of each GPU a load may claim.++ Never raises and never returns a value outside the supported range: a corrupt+ stored value or a malformed environment variable falls through to the default+ rather than failing the load.+ """+ stored = coerce_fraction(_cached_setting(VRAM_BUDGET_SETTING_KEY))+ if stored is not None:+ return stored+ from_env = _env_fraction()+ if from_env is not None:+ return from_env+ return VRAM_FRACTION_DEFAULT+++def get_vram_budget_state() -> tuple[float, bool]:+ """``(fraction, is_stored)`` for the settings route.++ The flag lets the UI distinguish "saved by the user" from "inherited from the+ environment or the default", which decides whether Reset is meaningful.+ """+ stored = coerce_fraction(_cached_setting(VRAM_BUDGET_SETTING_KEY))+ if stored is not None:+ return stored, True+ return get_vram_budget_fraction(), False+++def set_vram_budget_fraction(fraction: Any = None) -> float:+ """Store a budget, or clear it with ``None`` so env/default applies again."""+ if fraction is None:+ from storage.studio_db import upsert_app_settings++ upsert_app_settings({VRAM_BUDGET_SETTING_KEY: None})+ _invalidate(VRAM_BUDGET_SETTING_KEY)+ return get_vram_budget_fraction()++ parsed = coerce_fraction(fraction)+ if parsed is None:+ raise ValueError(+ f"VRAM budget must be a number between {VRAM_FRACTION_MIN} and {VRAM_FRACTION_MAX}."+ )++ from storage.studio_db import upsert_app_settings++ upsert_app_settings({VRAM_BUDGET_SETTING_KEY: parsed})+ _invalidate(VRAM_BUDGET_SETTING_KEY)+ return get_vram_budget_fraction()diff --git a/studio/frontend/src/features/model-picker/components/model-config-page.tsx b/studio/frontend/src/features/model-picker/components/model-config-page.tsxindex d4ebcd1082b..7edd433ff47 100644--- a/studio/frontend/src/features/model-picker/components/model-config-page.tsx+++ b/studio/frontend/src/features/model-picker/components/model-config-page.tsx@@ -22,6 +22,19 @@ import {useChatRuntimeStore,} from "@/features/chat";import { prepareHfTokenForUse } from "@/features/hf-auth";+import {+ type VramBudgetSettings,+ dropVramBudgetRetry,+ flushVramBudgetSave,+ isVramBudgetLocked,+ loadVramBudgetSettings,+ setVramBudgetLocked,+ settleVramBudgetSave,+ stageVramBudgetSave,+ subscribeVramBudgetLock,+ subscribeVramBudgetSettings,+ updateVramBudgetSettings,+} from "@/features/settings/api/vram-budget";import {type GpuIndexKind,type SystemGpuDevice,@@ -77,6 +90,9 @@ import {saveAdvancedSettingsOpen,savePerModelConfig,subscribeAdvancedSettingsOpen,+ VRAM_BUDGET_PERCENT_STEP,+ vramFractionToPercent,+ vramPercentToFraction,} from "../model-config/per-model-config";import { ChatTemplateEditorDialog } from "./chat-template-editor-dialog";import type { ModelPickTarget } from "./model-selector/types";@@ -290,6 +306,8 @@ function AdvancedGpuSlider({displayValue,info,inputRef,+ step = 1,+ disabled = false,}: {label: string;value: number;@@ -299,6 +317,8 @@ function AdvancedGpuSlider({displayValue?: string;info?: ReactNode;inputRef?: Ref<NumericValueInputHandle>;+ step?: number;+ disabled?: boolean;}) {return (<div className="space-y-3">@@ -312,23 +332,234 @@ function AdvancedGpuSlider({value={value}min={min}max={max}- step={1}+ step={step}onChange={onChange}displayValue={displayValue}ariaLabel={label}className={NUMBER_INPUT_CLASS}size={8}+ disabled={disabled}/></div><Slidermin={min}max={max}- step={1}+ step={step}value={[value]}onValueChange={([next]) => onChange(next)}className="panel-slider"aria-label={label}+ disabled={disabled}+ />+ </div>+ );+}++// How much of each card a load may claim. SERVER-WIDE, not a per-model override:+// it replaces two constants the fit reads, so there is nothing per-model to attach+// it to, and the label says so. Driven in whole percent so a dragged value+// round-trips exactly; the fraction is rebuilt at the API boundary.+function VramBudgetRow() {+ // The caller already gates on a discrete GPU and non-Manual mode. macOS is gated+ // here too: it reports no discrete GPUs, so the Metal path sizes itself from+ // _APPLE_UNIFIED_MEMORY_FRACTION and fits with budget_frac = 1.0. Showing the+ // slider would promise "applies on the next load" for a setting it ignores.+ const isMac = usePlatformStore((s) => s.deviceType === "mac");+ const [settings, setSettings] = useState<VramBudgetSettings | null>(null);+ const [percent, setPercent] = useState<number | null>(null);+ const saveTimer = useRef<ReturnType<typeof setTimeout> | null>(null);+ const adviceId = useId();+ const modelLoading = useChatRuntimeStore((s) => s.modelLoading);+ const wasModelLoading = useRef(false);+ // Closed while a Run is settling this budget: an edit made in that window would+ // be flushed by the teardown alongside the load request.+ const [locked, setLocked] = useState(isVramBudgetLocked);+ useEffect(() => subscribeVramBudgetLock(setLocked), []);++ // Adopt what the last save or read published: the row's own GET races the PUT a+ // previous unmount fired, so reopening Advanced straight after a drag could show+ // a value the server no longer holds. A queued edit outranks the publish, or a+ // save landing mid-drag would pull the slider out from under the pointer.+ useEffect(() => {+ if (isMac) {+ return;+ }+ return subscribeVramBudgetSettings((next) => {+ if (saveTimer.current) {+ return;+ }+ setSettings(next);+ setPercent(vramFractionToPercent(next.fraction));+ });+ }, [isMac]);++ useEffect(() => {+ let cancelled = false;+ if (isMac) {+ // Nothing to show, so do not even ask; the row is hidden below.+ return;+ }+ loadVramBudgetSettings().then((loaded) => {+ if (cancelled || !loaded) {+ return;+ }+ setSettings(loaded);+ setPercent(vramFractionToPercent(loaded.fraction));+ });+ return () => {+ cancelled = true;+ };+ // deviceType settles once /api/health answers, so re-run if the seed guess flips.+ }, [isMac]);++ // reloadRequired describes the running child, so it goes stale the moment a load+ // finishes. In the sidebar editor nothing remounts this row on a reload, so the+ // notice below would keep telling the user to reload a model already sized with+ // this budget. Only the falling edge: the read during a load answers about the+ // child being replaced.+ useEffect(() => {+ const finished = wasModelLoading.current && !modelLoading;+ wasModelLoading.current = modelLoading;+ if (isMac || !finished) {+ return;+ }+ let cancelled = false;+ // Forced: a read that began before the load finished describes the child being+ // replaced, and sharing it would republish the notice this refresh is clearing.+ loadVramBudgetSettings({ force: true }).then((loaded) => {+ if (cancelled || !loaded) {+ return;+ }+ setSettings(loaded);+ });+ return () => {+ cancelled = true;+ };+ }, [isMac, modelLoading]);++ // Flush, don't drop: the timer is cleared so nothing fires against a torn-down+ // view, but the fraction is still sent. It is held nowhere else, so a drag+ // followed within the debounce by Run, the Advanced toggle or closing the panel+ // would be lost. The view is gone, so the response only reaches subscribers.+ useEffect(+ () => () => {+ if (saveTimer.current) {+ clearTimeout(saveTimer.current);+ saveTimer.current = null;+ }+ flushVramBudgetSave()?.catch((error: unknown) => {+ toast.error(+ error instanceof Error ? error.message : "Failed to save VRAM budget",+ );+ });+ },+ [],+ );++ // A null response means an older backend; hide rather than render a dead control.+ if (isMac || !settings || percent === null) {+ return null;+ }++ const defaultPercent = vramFractionToPercent(settings.defaultFraction);+ // Stored beats UNSLOTH_VRAM_FRACTION, so once the slider has been touched there+ // is otherwise no way back to inheriting it: dragging to the same number stores+ // that number, and a later change to the variable stays masked. Clearing is what+ // the null the API already accepts is for.+ const resetBudget = () => {+ if (saveTimer.current) {+ clearTimeout(saveTimer.current);+ saveTimer.current = null;+ }+ // Drop a queued drag, or its debounce would store back what this clears.+ stageVramBudgetSave(null);+ updateVramBudgetSettings(null)+ .then((next) => {+ setSettings(next);+ setPercent(vramFractionToPercent(next.fraction));+ })+ .catch((error: unknown) => {+ toast.error(+ error instanceof Error ? error.message : "Failed to reset VRAM budget",+ );+ });+ };+ const commit = (next: number) => {+ setPercent(next);+ // Debounced: the slider fires per pointer move, so a drag would be dozens of+ // writes, each invalidating the read cache.+ if (saveTimer.current) {+ clearTimeout(saveTimer.current);+ }+ stageVramBudgetSave(vramPercentToFraction(next));+ saveTimer.current = setTimeout(() => {+ saveTimer.current = null;+ flushVramBudgetSave()+ ?.then(setSettings)+ .catch((error: unknown) => {+ // The client re-stages it, where the write generation can say whether+ // it is still the newest intent.+ toast.error(+ error instanceof Error ? error.message : "Failed to save VRAM budget",+ );+ });+ }, 400);+ };++ return (+ <div className="space-y-2">+ <AdvancedGpuSlider+ label="VRAM Budget"+ value={percent}+ min={vramFractionToPercent(settings.minFraction)}+ max={vramFractionToPercent(settings.maxFraction)}+ step={VRAM_BUDGET_PERCENT_STEP}+ displayValue={`${percent}%`}+ onChange={commit}+ disabled={locked}+ info={+ <div className="flex flex-col gap-1.5">+ <div>+ Share of each GPU Unsloth will claim when it sizes the model and+ context. The rest is left for memory fragmentation, the per-device+ CUDA context on a multi-GPU split, and MoE routing.+ </div>+ <div>+ Applies to every model, not just this one, and takes effect on the+ next load. Default {defaultPercent}%. Even at 100% a load leaves a+ margin on each card, up to the 512 MiB llama.cpp keeps for its own+ fitter, and never more than the default would have reserved.+ </div>+ <div>+ Reset clears the stored value, so UNSLOTH_VRAM_FRACTION applies+ again if it is set.+ </div>+ </div>+ }/>+ {percent !== defaultPercent && (+ <p id={adviceId} className="text-ui-11 text-amber-500">+ {percent > defaultPercent+ ? "Above the default fits more context but leaves less slack, so a load can run out of memory. llama.cpp treats that as a hard failure rather than falling back."+ : "Below the default is safer on a shared GPU, but a tight fit may push layers onto the CPU and generate slowly."}+ </p>+ )}+ {settings.isStored && (+ <button+ type="button"+ disabled={locked}+ onClick={resetBudget}+ className="text-ui-11 text-muted-foreground underline underline-offset-2 hover:text-nav-fg"+ >+ Reset to the server default+ </button>+ )}+ {settings.reloadRequired && (+ <p className="text-ui-11 text-muted-foreground">+ The loaded model was sized with a different budget. Reload it to apply+ this one.+ </p>+ )}</div>);}@@ -435,6 +666,13 @@ function GpuMemorySettings({</SelectContent></Select></div>+ {/* A fixed manual layer count is the one placement the budget cannot move,+ and a CPU-only host has no GPU to act on, so "applies on the next load"+ would be false. Manual + Auto is included: it leaves the planner no device+ list, but --fit-target still carries the budget to llama.cpp's fitter. */}+ {!isDiffusion && (!isManual || autoLayers) && gpuDevices.length > 0 && (+ <VramBudgetRow />+ )}{!isDiffusion && isManual && (<><AdvancedGpuSlider@@ -1150,6 +1388,21 @@ export function ModelConfigPage({resolvedIsDiffusion,gpuDevices,);+ // Held for the window where Run is waiting on a budget PUT rather than on the+ // load it looks like it started.+ const [budgetSettling, setBudgetSettling] = useState(false);+ // The budget is on no per-model field, so changing it leaves this page at its+ // baseline and the Reload button disabled, with the row asking for a reload the+ // user could not start. Read off the same publish the row uses, so nothing is+ // threaded through GpuMemorySettings and a row that never mounts leaves it false.+ const [budgetReloadRequired, setBudgetReloadRequired] = useState(false);+ useEffect(+ () =>+ subscribeVramBudgetSettings((next) => {+ setBudgetReloadRequired(next.reloadRequired);+ }),+ [],+ );const stagedMetadataPending =contextFetchKey != null &&stagedDims == null &&@@ -1251,6 +1504,9 @@ export function ModelConfigPage({: "Load model";const handleRun = () => {+ if (budgetSettling) {+ return;+ }// Same-click Load/Reload: a numeric draft the user just typed is flushed only by that input's// blur handler, which runs after this click closure captured the stale value. Commit every// numeric input imperatively so the staged load honors what was typed, not just Context.@@ -1381,6 +1637,44 @@ export function ModelConfigPage({const effectiveLoadConfig = target.isGguf? effectiveRuntimeConfig: { ...effectiveRuntimeConfig, maxSeqLength: effectiveMaxSeqLengthValue };+ // Same reason as the numeric commits above: the budget row flushes on unmount,+ // which for this click lands after onRun has staged the load, so that load (the+ // very one the control promises) would use the old fraction. A failed save must+ // not swallow the load, hence finally; nothing staged stays synchronous.+ // Closed before the settle, not after: the control has to stop taking edits at+ // the moment this click owns the fraction, or a drag landing in between is the+ // very race the lock exists to remove.+ setVramBudgetLocked(true);+ const stagedBudget = settleVramBudgetSave();+ if (stagedBudget) {+ // The click is answered by a network round trip now, so the button stays live+ // for as long as that takes. A second click in that window would settle the+ // same chain again and run onRun twice, i.e. two loads from one intent.+ setBudgetSettling(true);+ // Caught, not voided: finally alone re-rejects into an unhandled rejection,+ // and the load would proceed on the old fraction with nothing said.+ void stagedBudget+ .catch((error: unknown) => {+ // Dropped rather than left for the next flush: the picker teardown that+ // onRun triggers flushes it, and that PUT would then race the load+ // request this click is about to send. Either fraction could win, which+ // is the one thing this control promises cannot happen. Only the retry+ // goes, never a newer edit staged over it. The toast says the budget+ // did not change, and the slider is still there to retry.+ dropVramBudgetRetry();+ toast.error(+ error instanceof Error ? error.message : "Failed to save VRAM budget",+ );+ })+ .finally(() => {+ setVramBudgetLocked(false);+ setBudgetSettling(false);+ onRun(effectiveLoadConfig, classifiedIsDiffusion);+ });+ return;+ }+ // Nothing to wait for, so the control never actually closes for the user.+ setVramBudgetLocked(false);onRun(effectiveLoadConfig, classifiedIsDiffusion);};@@ -1568,7 +1862,11 @@ export function ModelConfigPage({className="h-8"disabled={stagedMetadataPending ||- (isActiveModel && atBaseline && !rememberChanged)+ budgetSettling ||+ (isActiveModel &&+ atBaseline &&+ !rememberChanged &&+ !budgetReloadRequired)}onClick={handleRun}>diff --git a/studio/frontend/src/features/model-picker/model-config/per-model-config.ts b/studio/frontend/src/features/model-picker/model-config/per-model-config.tsindex 7bea44f5cbd..57e51b2324c 100644--- a/studio/frontend/src/features/model-picker/model-config/per-model-config.ts+++ b/studio/frontend/src/features/model-picker/model-config/per-model-config.ts@@ -52,6 +52,27 @@ export const DEFAULT_PER_MODEL_CONFIG: PerModelConfig = {export const N_PARALLEL_MIN = 1;export const N_PARALLEL_MAX = 64;+// Mirrors vram_budget_settings.py VRAM_FRACTION_MIN/MAX/DEFAULT as whole percent+// (the slider works in integers). Server-wide, so these are only the bounds the+// control clamps to; the value lives in /api/settings/vram-budget.+export const VRAM_BUDGET_PERCENT_MIN = 80;+export const VRAM_BUDGET_PERCENT_MAX = 100;+export const VRAM_BUDGET_PERCENT_DEFAULT = 97;+// Tenths: a whole percent is ~245 MiB of context on a 24 GB card. Mirrors+// VRAM_FRACTION_DECIMALS = 3 in vram_budget_settings.py.+export const VRAM_BUDGET_PERCENT_STEP = 0.1;++/** Percent for the slider; the fraction is rebuilt at the API boundary. */+export function vramFractionToPercent(fraction: number): number {+ return Math.round(fraction * 1000) / 10;+}++export function vramPercentToFraction(percent: number): number {+ // Three decimals, so 0.975 cannot come back as 0.9750000000000001 and read as+ // "changed" after a drag that ended where it began.+ return Math.round(percent * 10) / 1000;+}+// mirrors llama_server_args.py BATCH_MIN/MAX; null = follow the llama.cpp defaults (2048 / 512)export const N_BATCH_MIN = 1;export const N_BATCH_MAX = 65536;diff --git a/studio/frontend/src/features/settings/api/vram-budget.ts b/studio/frontend/src/features/settings/api/vram-budget.tsnew file mode 100644index 00000000000..5877b5ec369--- /dev/null+++ b/studio/frontend/src/features/settings/api/vram-budget.ts@@ -0,0 +1,279 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import { authFetch } from "@/features/auth";+import { readFastApiError } from "@/lib/format-fastapi-error";++const VRAM_BUDGET_EVENT = "unsloth-vram-budget-change";+const VRAM_BUDGET_LOCK_EVENT = "unsloth-vram-budget-lock";++export type VramBudgetSettings = {+ /** Fraction of each GPU a load may claim, e.g. 0.97. */+ fraction: number;+ /** False when inherited from UNSLOTH_VRAM_FRACTION or the built-in default. */+ isStored: boolean;+ defaultFraction: number;+ minFraction: number;+ maxFraction: number;+ /** A model is loaded that was sized against a different budget. */+ reloadRequired: boolean;+};++type ApiVramBudgetSettings = {+ fraction: number;+ // biome-ignore lint/style/useNamingConvention: API schema+ is_stored: boolean;+ // biome-ignore lint/style/useNamingConvention: API schema+ default_fraction: number;+ // biome-ignore lint/style/useNamingConvention: API schema+ min_fraction: number;+ // biome-ignore lint/style/useNamingConvention: API schema+ max_fraction: number;+ // biome-ignore lint/style/useNamingConvention: API schema+ reload_required: boolean;+};++let inFlightVramBudget: Promise<VramBudgetSettings> | null = null;++// Held here, not in the row: the row unmounts on Run and on the Advanced toggle,+// and the load must still be able to flush that edit.+let stagedVramBudgetFraction: number | null = null;++// Bumped on every stage, so a retry put back by a failed write can be told apart+// from a newer edit the user staged over it.+let stagedVramBudgetSequence = 0;+let retryVramBudgetSequence = -1;++/** Record a fraction a debounced save has not sent yet. */+export function stageVramBudgetSave(fraction: number | null) {+ stagedVramBudgetFraction = fraction;+ stagedVramBudgetSequence += 1;+}++/**+ * Drop a retry a failed write put back, unless something newer is staged over it.+ * For a caller that is about to start a load: the retry would otherwise be flushed+ * by the teardown and race the load request.+ */+export function dropVramBudgetRetry() {+ if (stagedVramBudgetSequence === retryVramBudgetSequence) {+ stagedVramBudgetFraction = null;+ }+}++/**+ * Send a staged fraction now. Returns null when nothing is staged, so callers keep+ * their synchronous path in the common case.+ */+export function flushVramBudgetSave(): Promise<VramBudgetSettings> | null {+ const fraction = stagedVramBudgetFraction;+ stagedVramBudgetFraction = null;+ return fraction === null ? null : updateVramBudgetSettings(fraction);+}++/**+ * Everything the next load must wait for: a staged fraction, or a debounced save+ * still in flight. A user who pauses past the 400 ms debounce and clicks Load has+ * nothing staged but an open PUT, and the load would otherwise use the fraction+ * that request replaces. The chain swallows rejections the debounced save reported.+ */+export function settleVramBudgetSave(): Promise<unknown> | null {+ // The newest write, not the chain: the chain swallows rejections so one failed+ // save cannot strand those behind it, and a caller waiting on it would be told+ // the save succeeded. Only the newest can have re-staged a retry, and writes+ // settle in order, so it still covers every open write.+ return (+ flushVramBudgetSave() ??+ (vramBudgetWritesOpen > 0 ? vramBudgetNewestWrite : null)+ );+}++// A load waits on the budget it is about to launch against, so an edit made in+// that window is flushed by the teardown alongside the load request and either+// fraction could size the child. Settling in a loop only shrinks that window;+// closing the control closes it. Held here because the row unmounts and the load+// does not.+let vramBudgetLocked = false;++export function setVramBudgetLocked(locked: boolean) {+ vramBudgetLocked = locked;+ window.dispatchEvent(+ new CustomEvent(VRAM_BUDGET_LOCK_EVENT, { detail: locked }),+ );+}++export function isVramBudgetLocked() {+ return vramBudgetLocked;+}++export function subscribeVramBudgetLock(listener: (locked: boolean) => void) {+ const handleChange = (event: Event) => {+ listener((event as CustomEvent<boolean>).detail);+ };+ window.addEventListener(VRAM_BUDGET_LOCK_EVENT, handleChange);+ return () => window.removeEventListener(VRAM_BUDGET_LOCK_EVENT, handleChange);+}++export function subscribeVramBudgetSettings(+ listener: (settings: VramBudgetSettings) => void,+) {+ const handleChange = (event: Event) => {+ listener((event as CustomEvent<VramBudgetSettings>).detail);+ };+ window.addEventListener(VRAM_BUDGET_EVENT, handleChange);+ return () => window.removeEventListener(VRAM_BUDGET_EVENT, handleChange);+}++function fromApi(settings: ApiVramBudgetSettings): VramBudgetSettings {+ return {+ fraction: settings.fraction,+ isStored: settings.is_stored,+ defaultFraction: settings.default_fraction,+ minFraction: settings.min_fraction,+ maxFraction: settings.max_fraction,+ reloadRequired: settings.reload_required,+ };+}++// No read-through cache: reloadRequired describes the running process and goes+// stale on any load or swap. This only fans the latest value out to subscribers.+function publishVramBudget(settings: VramBudgetSettings) {+ window.dispatchEvent(+ new CustomEvent(VRAM_BUDGET_EVENT, { detail: settings }),+ );+ return settings;+}++async function fetchVramBudgetSettings(): Promise<VramBudgetSettings> {+ const res = await authFetch("/api/settings/vram-budget");+ if (!res.ok) {+ throw new Error(await readFastApiError(res, "Failed to load VRAM budget"));+ }+ return fromApi(await res.json());+}++/**+ * Always refetches, since `reloadRequired` describes the loaded process;+ * concurrent calls share one request. Returns null rather than throwing when the+ * endpoint is absent, so a newer UI on an older backend hides the control.+ */+export async function loadVramBudgetSettings(+ options: { force?: boolean } = {},+): Promise<VramBudgetSettings | null> {+ // Read behind any open write: a row remounting right after a flushed drag can+ // otherwise GET the old fraction before the PUT commits and answer after it,+ // repainting the control with the value the server just replaced. The+ // subscription cannot untangle that, since only the order is wrong.+ const pendingWrites =+ vramBudgetWritesOpen > 0 ? vramBudgetWriteChain : Promise.resolve();+ // Waiting behind the writes open now says nothing about a save issued while the+ // GET is in the air: that PUT can publish first, and this answer would repaint+ // the slider, and the Reload state, with what the server held before it. The+ // post-load refresh is the way in, since the control is live while the load runs.+ const generationAtRead = vramBudgetWriteGeneration;+ if (options.force) {+ // reloadRequired describes the running child, so a read that started before a+ // load finished answers about the child being replaced. Sharing it would+ // republish that stale answer as if it described the new one.+ inFlightVramBudget = null;+ }+ if (!inFlightVramBudget) {+ const read: Promise<VramBudgetSettings> = pendingWrites+ .then(fetchVramBudgetSettings)+ .then((settings) => {+ // Answer only while this is still the current read and nothing newer has+ // been written. A displaced read describes the child being replaced, an+ // overtaken one the fraction a save replaced; either restores state the+ // newer answer just corrected. Refused, not merely unpublished: the caller+ // applies the return value by hand and would put the same answer back.+ if (+ inFlightVramBudget !== read ||+ generationAtRead !== vramBudgetWriteGeneration+ ) {+ throw new Error("superseded");+ }+ return publishVramBudget(settings);+ })+ .finally(() => {+ // Identity-checked: a forced read displaces this one, and clearing blindly+ // would drop the newer request's handle and leave it unshared.+ if (inFlightVramBudget === read) {+ inFlightVramBudget = null;+ }+ });+ inFlightVramBudget = read;+ }+ try {+ return await inFlightVramBudget;+ } catch {+ // Null is already the "no usable answer" contract here: an older backend with+ // no such route reads the same way, and every caller keeps what it has.+ return null;+ }+}++async function putVramBudget(+ fraction: number | null,+): Promise<VramBudgetSettings> {+ const res = await authFetch("/api/settings/vram-budget", {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ fraction }),+ });+ if (!res.ok) {+ throw new Error(+ await readFastApiError(res, "Failed to update VRAM budget"),+ );+ }+ return fromApi(await res.json());+}++// One drag can outrun its own saves: on a slow link a second PUT starts while the+// first is open, and either order of apply or response could let the older edit win+// the database row and the published value. Chaining serialises the writes; the+// generation lets only the newest publish, so a late response cannot repaint.+let vramBudgetWriteChain: Promise<unknown> = Promise.resolve();+// The same write, unswallowed, for callers that need to hear about a failure.+let vramBudgetNewestWrite: Promise<unknown> = Promise.resolve();+let vramBudgetWriteGeneration = 0;+// Issued but unsettled writes, so a load can tell whether to wait.+let vramBudgetWritesOpen = 0;++/** `null` clears the stored budget so the env var or the default applies again. */+export function updateVramBudgetSettings(+ fraction: number | null,+): Promise<VramBudgetSettings> {+ vramBudgetWriteGeneration += 1;+ const generation = vramBudgetWriteGeneration;+ vramBudgetWritesOpen += 1;+ const write = vramBudgetWriteChain+ .then(+ () => putVramBudget(fraction),+ () => putVramBudget(fraction),+ )+ .finally(() => {+ vramBudgetWritesOpen -= 1;+ });+ // The chain must survive a rejection, or one failed save strands all later ones.+ vramBudgetWriteChain = write.catch(() => undefined);+ vramBudgetNewestWrite = write;+ return write.then(+ (settings) =>+ generation === vramBudgetWriteGeneration+ ? publishVramBudget(settings)+ : settings,+ (error: unknown) => {+ // Put a failed edit back for the next flush or Run, but only while it is+ // still the newest intent: a later edit may already be staged, or already+ // sent past this one, and resending would undo it.+ if (+ generation === vramBudgetWriteGeneration &&+ stagedVramBudgetFraction === null+ ) {+ stageVramBudgetSave(fraction);+ retryVramBudgetSequence = stagedVramBudgetSequence;+ }+ throw error;+ },+ );+}diff --git a/studio/frontend/tests/vram-budget.test.ts b/studio/frontend/tests/vram-budget.test.tsnew file mode 100644index 00000000000..b23d0ef7b64--- /dev/null+++ b/studio/frontend/tests/vram-budget.test.ts@@ -0,0 +1,528 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import test from "node:test";+import { fileURLToPath } from "node:url";++import {+ installLocalStorageFake,+ registerBundlerResolver,+} from "./helpers/kit.ts";++registerBundlerResolver();+installLocalStorageFake();++const {+ VRAM_BUDGET_PERCENT_DEFAULT,+ VRAM_BUDGET_PERCENT_MAX,+ VRAM_BUDGET_PERCENT_MIN,+ VRAM_BUDGET_PERCENT_STEP,+ vramFractionToPercent,+ vramPercentToFraction,+} = await import(+ "../src/features/model-picker/model-config/per-model-config.ts"+);++test("percent and fraction round-trip exactly across the whole range", () => {+ // Every stop the slider can land on: a value that does not survive the trip+ // reads as "changed" and re-saves itself on every remount.+ const steps = Math.round(+ (VRAM_BUDGET_PERCENT_MAX - VRAM_BUDGET_PERCENT_MIN) /+ VRAM_BUDGET_PERCENT_STEP,+ );+ for (let i = 0; i <= steps; i += 1) {+ const percent =+ Math.round(+ (VRAM_BUDGET_PERCENT_MIN + i * VRAM_BUDGET_PERCENT_STEP) * 10,+ ) / 10;+ assert.equal(+ vramFractionToPercent(vramPercentToFraction(percent)),+ percent,+ );+ }+});++test("a tenth of a percent survives the trip to the backend and back", () => {+ assert.equal(vramPercentToFraction(97.5), 0.975);+ assert.equal(vramFractionToPercent(0.975), 97.5);+ assert.equal(VRAM_BUDGET_PERCENT_STEP, 0.1);+});++test("the default fraction is exactly 0.97, not a float-drifted neighbour", () => {+ // A drifted 0.9700000000000001 never equals the backend default, so the UI would+ // show the budget as changed after a drag that ended where it began.+ assert.equal(vramPercentToFraction(VRAM_BUDGET_PERCENT_DEFAULT), 0.97);+ assert.equal(vramFractionToPercent(0.97), VRAM_BUDGET_PERCENT_DEFAULT);+});++test("the bounds mirror the backend range", () => {+ // vram_budget_settings.py: VRAM_FRACTION_MIN 0.80, MAX 1.00, DEFAULT 0.97.+ assert.equal(vramPercentToFraction(VRAM_BUDGET_PERCENT_MIN), 0.8);+ assert.equal(vramPercentToFraction(VRAM_BUDGET_PERCENT_MAX), 1);+ assert.equal(VRAM_BUDGET_PERCENT_DEFAULT, 97);+});++test("fractionToPercent rounds rather than truncating", () => {+ // A value set through UNSLOTH_VRAM_FRACTION need not land on the grid.+ assert.equal(vramFractionToPercent(0.8555), 85.6);+ assert.equal(vramFractionToPercent(0.8554), 85.5);+});++test("percentToFraction tolerates an off-grid slider value", () => {+ assert.equal(vramPercentToFraction(90.44), 0.904);+ assert.equal(vramPercentToFraction(90.46), 0.905);+});++// The component cannot be mounted here (no DOM, and renderToStaticMarkup never+// runs effects), so the unmount contract is asserted against the source, as the+// chat-adapter tests do. The bug it guards: clearing the timer without sending the+// pending fraction discarded a drag followed within 400ms by Run, the Advanced+// toggle or closing the panel, and the server-wide budget lives nowhere else.+const pageSource = readFileSync(+ fileURLToPath(+ new URL(+ "../src/features/model-picker/components/model-config-page.tsx",+ import.meta.url,+ ),+ ),+ "utf8",+);++function vramBudgetRowSource(): string {+ const start = pageSource.indexOf("function VramBudgetRow()");+ assert.ok(start >= 0, "VramBudgetRow is no longer defined");+ const end = pageSource.indexOf("\n}\n", start);+ assert.ok(end > start, "could not delimit VramBudgetRow");+ return pageSource.slice(start, end);+}++test("unmount flushes the pending budget save instead of dropping it", () => {+ const row = vramBudgetRowSource();+ const cleanupStart = row.indexOf("useEffect(\n () => () => {");+ assert.ok(cleanupStart >= 0, "the unmount-only effect is gone");+ const cleanup = row.slice(+ cleanupStart,+ row.indexOf("\n [],\n );", cleanupStart),+ );+ // Still cancels the timer, so no callback fires against a torn-down view...+ assert.match(cleanup, /clearTimeout\(saveTimer\.current\)/);+ // ...but the value the user set is sent rather than discarded.+ assert.match(cleanup, /flushVramBudgetSave\(\)/);+ // Fire-and-forget: the component is gone, so no response may reach its state.+ assert.doesNotMatch(cleanup, /\.then\(setSettings\)/);+});++test("commit stages the fraction before arming the debounce", () => {+ const row = vramBudgetRowSource();+ const commitStart = row.indexOf("const commit = (next: number) => {");+ assert.ok(commitStart >= 0, "commit is gone");+ const commit = row.slice(commitStart);+ // Staged before the timer, so an unfinished drag still has a value to flush.+ assert.ok(+ commit.indexOf("stageVramBudgetSave(vramPercentToFraction(next))") <+ commit.indexOf("setTimeout("),+ "the fraction must be staged before the debounce is armed",+ );+ // The debounced save uses the same flush, which clears the staged value as it+ // sends, so unmount cannot re-send a save that already happened.+ const timer = commit.slice(commit.indexOf("setTimeout("));+ assert.match(timer, /flushVramBudgetSave\(\)/);+ assert.doesNotMatch(timer, /updateVramBudgetSettings\(/);+});++test("the staged fraction is held outside the component that unmounts", () => {+ // The row unmounts on Run, so a ref inside it cannot be read by the load.+ const client = readFileSync(+ fileURLToPath(+ new URL("../src/features/settings/api/vram-budget.ts", import.meta.url),+ ),+ "utf8",+ );+ assert.match(client, /export function stageVramBudgetSave/);+ assert.match(client, /export function flushVramBudgetSave/);+ // Cleared as it sends, so two flushes cannot write the same edit twice.+ const flush = client.slice(+ client.indexOf("export function flushVramBudgetSave"),+ );+ assert.ok(+ flush.indexOf("stagedVramBudgetFraction = null") <+ flush.indexOf("updateVramBudgetSettings(fraction)"),+ "the flush must clear the staged value before sending it",+ );+ // Nothing staged must stay cheap for the caller: null, not a resolved promise.+ assert.match(flush, /fraction === null \? null :/);+});++test("Run waits for a staged budget save before starting the load", () => {+ // The control promises the budget applies on the next load, but if Run stages+ // the load while the PUT is open, that load uses the old fraction.+ const handlerStart = pageSource.indexOf("const handleRun = () => {");+ assert.ok(handlerStart >= 0, "handleRun is gone");+ const handler = pageSource.slice(+ handlerStart,+ pageSource.indexOf("\n };", handlerStart),+ );+ const flushAt = handler.indexOf("settleVramBudgetSave()");+ assert.ok(flushAt >= 0, "handleRun no longer flushes the staged budget");+ assert.ok(+ flushAt < handler.indexOf("onRun(effectiveLoadConfig"),+ "the flush must come before the load is staged",+ );+ // A failed save must not swallow the load.+ assert.match(handler, /\.finally\(\(\) => \{/);+});++test("the row adopts published settings instead of only its own read", () => {+ const row = vramBudgetRowSource();+ assert.match(row, /subscribeVramBudgetSettings\(/);+ // A queued edit outranks the publish, or a mid-drag save moves the slider.+ const subscribeAt = row.indexOf("subscribeVramBudgetSettings(");+ const guard = row.slice(subscribeAt, subscribeAt + 260);+ assert.match(guard, /if \(saveTimer\.current\) \{\s*return;/);+});++test("Run reports a rejected budget flush instead of voiding it", () => {+ const handlerStart = pageSource.indexOf("const handleRun = () => {");+ const handler = pageSource.slice(+ handlerStart,+ pageSource.indexOf("\n };", handlerStart),+ );+ const flush = handler.slice(handler.indexOf("settleVramBudgetSave()"));+ // finally alone re-rejects into an unhandled rejection, and the load proceeds+ // on the old fraction with nothing said.+ assert.ok(+ flush.indexOf(".catch(") < flush.indexOf(".finally("),+ "the rejection must be handled before finally starts the load",+ );+ assert.match(flush, /Failed to save VRAM budget/);+});++test("budget writes are serialised and only the newest publishes", () => {+ const client = readFileSync(+ fileURLToPath(+ new URL("../src/features/settings/api/vram-budget.ts", import.meta.url),+ ),+ "utf8",+ );+ // Two debounced saves can overlap on a slow link; out-of-order responses would+ // let the older edit win both the row and the stored value.+ assert.match(client, /vramBudgetWriteChain/);+ assert.match(client, /vramBudgetWriteGeneration/);+ const update = client.slice(+ client.indexOf("export function updateVramBudgetSettings"),+ );+ assert.match(+ update,+ /generation === vramBudgetWriteGeneration\s*\?\s*publishVramBudget/,+ );+ // A failed save must not strand every later one behind it.+ assert.match(update, /vramBudgetWriteChain = write\.catch/);+});++test("Run also waits for a save the debounce already sent", () => {+ const client = readFileSync(+ fileURLToPath(+ new URL("../src/features/settings/api/vram-budget.ts", import.meta.url),+ ),+ "utf8",+ );+ // Pause past the 400 ms debounce, then click Load: nothing is staged any more,+ // but the PUT is still open and the load would use the fraction it replaces.+ const settle = client.slice(+ client.indexOf("export function settleVramBudgetSave"),+ );+ assert.match(settle, /flushVramBudgetSave\(\) \?\?/);+ assert.match(+ settle,+ /vramBudgetWritesOpen > 0 \? vramBudgetNewestWrite : null/,+ );+ // The counter has to come back down however the write ends.+ assert.match(client, /\.finally\(\(\) => \{\s*vramBudgetWritesOpen -= 1;/);+});++test("a read waits behind an open write", () => {+ const client = readFileSync(+ fileURLToPath(+ new URL("../src/features/settings/api/vram-budget.ts", import.meta.url),+ ),+ "utf8",+ );+ // A remount right after a flushed drag can read before the PUT commits and+ // answer after it, repainting the row with the value the server just replaced.+ const read = client.slice(+ client.indexOf("export async function loadVramBudgetSettings"),+ );+ assert.match(read, /vramBudgetWritesOpen > 0 \? vramBudgetWriteChain/);+ assert.ok(+ read.indexOf("pendingWrites") <+ read.indexOf(".then(fetchVramBudgetSettings)"),+ "the fetch must be chained behind the open writes, not raced with them",+ );+});++test("the budget reads as a percentage and steps in tenths", () => {+ const row = vramBudgetRowSource();+ // Without the suffix, 97 sits between controls measured in layers and tokens+ // and reads as neither.+ assert.match(row, /displayValue=\{`\$\{percent\}%`\}/);+ assert.match(row, /step=\{VRAM_BUDGET_PERCENT_STEP\}/);+ // The shared slider defaults to whole steps, so the other callers are untouched.+ const slider = pageSource.slice(+ pageSource.indexOf("function AdvancedGpuSlider"),+ );+ assert.match(slider.slice(0, slider.indexOf("</div>")), /step = 1,/);+});++test("a failed save is re-staged, but never over a newer edit", () => {+ const client = readFileSync(+ fileURLToPath(+ new URL("../src/features/settings/api/vram-budget.ts", import.meta.url),+ ),+ "utf8",+ );+ // The flush clears the staged value as it sends, so without putting it back the+ // control shows a fraction the server never took. It goes back only while it is+ // still the newest intent.+ const update = client.slice(+ client.indexOf("export function updateVramBudgetSettings"),+ );+ // Whitespace-collapsed: the formatter wraps this condition across lines.+ const rejection = update+ .slice(update.indexOf("(error: unknown) =>"))+ .replace(/\s+/g, " ");+ assert.match(+ rejection,+ /generation === vramBudgetWriteGeneration && stagedVramBudgetFraction === null/,+ );+ assert.match(rejection, /stageVramBudgetSave\(fraction\);/);+ // Still rejects, so the caller can report it.+ assert.match(rejection, /throw error;/);+});++test("the reload notice is refreshed once a load finishes", () => {+ const row = vramBudgetRowSource().replace(/\s+/g, " ");+ // reloadRequired describes the running child. In the sidebar editor nothing+ // remounts this row on a reload, so without a refetch the notice kept asking for+ // a reload the user had just done.+ assert.match(+ row,+ /const modelLoading = useChatRuntimeStore\(\(s\) => s\.modelLoading\)/,+ );+ // Falling edge only: a read taken during the load answers about the child being+ // replaced, and would re-arm the very notice it is meant to clear.+ assert.match(+ row,+ /const finished = wasModelLoading\.current && !modelLoading; wasModelLoading\.current = modelLoading;/,+ );+ assert.match(row, /\}, \[isMac, modelLoading\]\)/);+});++test("Run waits out the budget save without starting two loads", () => {+ const run = pageSource.slice(pageSource.indexOf("const handleRun = () => {"));+ const body = run.slice(0, run.indexOf("\n return (")).replace(/\s+/g, " ");+ // The click is answered by a PUT, so the button stays live for a round trip. A+ // second click would settle the same chain again and call onRun twice.+ assert.match(body, /if \(budgetSettling\) \{ return; \}/);+ assert.match(body, /setBudgetSettling\(true\);/);+ assert.match(body, /setBudgetSettling\(false\); onRun\(/);+ const disabled = pageSource+ .slice(pageSource.indexOf("onClick={handleRun}") - 400)+ .replace(/\s+/g, " ");+ assert.match(disabled, /budgetSettling \|\|/);+});++test("a save that fails during Run is dropped, not left to race the load", () => {+ const run = pageSource.slice(pageSource.indexOf("const handleRun = () => {"));+ const rejection = run+ .slice(run.indexOf("void stagedBudget"))+ .replace(/\s+/g, " ");+ // onRun tears the picker down, and that unmount flushes whatever is staged. A+ // re-staged retry would therefore PUT alongside the load request this click is+ // sending, and either fraction could size the child.+ assert.match(rejection, /dropVramBudgetRetry\(\); toast\.error\(/);+});++test("only the retry is dropped, never a newer edit staged over it", () => {+ const client = readFileSync(+ fileURLToPath(+ new URL("../src/features/settings/api/vram-budget.ts", import.meta.url),+ ),+ "utf8",+ );+ const flat = client.replace(/\s+/g, " ");+ // Run drops the failed fraction so it cannot race the load, but a drag landing+ // during that PUT stages a newer one, and dropping that would discard the edit+ // the user is looking at.+ assert.match(flat, /stagedVramBudgetSequence \+= 1;/);+ assert.match(+ flat,+ /export function dropVramBudgetRetry\(\) \{ if \(stagedVramBudgetSequence === retryVramBudgetSequence\)/,+ );+ assert.match(+ flat,+ /stageVramBudgetSave\(fraction\); retryVramBudgetSequence = stagedVramBudgetSequence;/,+ );+});++test("a post-load read is not answered by one taken before the load finished", () => {+ const client = readFileSync(+ fileURLToPath(+ new URL("../src/features/settings/api/vram-budget.ts", import.meta.url),+ ),+ "utf8",+ );+ const flat = client.replace(/\s+/g, " ");+ // reloadRequired describes the running child, so an in-flight GET answers about+ // the child being replaced; sharing it republishes the stale notice.+ assert.match(flat, /if \(options\.force\) \{[^}]*inFlightVramBudget = null;/);+ // The displaced read must not then clear the newer handle on its way out.+ assert.match(+ flat,+ /if \(inFlightVramBudget === read\) \{ inFlightVramBudget = null;/,+ );+ const row = readFileSync(+ fileURLToPath(+ new URL(+ "../src/features/model-picker/components/model-config-page.tsx",+ import.meta.url,+ ),+ ),+ "utf8",+ );+ assert.match(row, /loadVramBudgetSettings\(\{ force: true \}\)/);+});++test("the budget closes while Run settles it, instead of racing the load", () => {+ const run = pageSource.slice(pageSource.indexOf("const handleRun = () => {"));+ const body = run.slice(0, run.indexOf("\n return (")).replace(/\s+/g, " ");+ // Settling again in a loop only shrinks the window: an edit made during the last+ // attempt is still staged when onRun tears the picker down and flushes it+ // alongside the load request. Closing the control closes the window.+ assert.match(+ body,+ /setVramBudgetLocked\(true\); const stagedBudget = settleVramBudgetSave\(\);/,+ );+ assert.match(+ body,+ /setVramBudgetLocked\(false\); setBudgetSettling\(false\); onRun\(/,+ );+ // Nothing staged means nothing to wait for, so the control never closes.+ assert.match(body, /setVramBudgetLocked\(false\); onRun\(/);+ const row = vramBudgetRowSource().replace(/\s+/g, " ");+ assert.match(+ row,+ /useEffect\(\(\) => subscribeVramBudgetLock\(setLocked\), \[\]\)/,+ );+ assert.match(row, /disabled=\{locked\}/);+});++test("a stored budget can be cleared back to the inherited one", () => {+ const row = vramBudgetRowSource().replace(/\s+/g, " ");+ // Stored beats UNSLOTH_VRAM_FRACTION, so without this the first drag masks the+ // variable for good: dragging back to the same number stores that number.+ assert.match(row, /\{settings\.isStored && \( <button/);+ assert.match(row, /updateVramBudgetSettings\(null\)/);+ // A queued drag would otherwise store back what the reset just cleared.+ assert.match(+ row,+ /stageVramBudgetSave\(null\); updateVramBudgetSettings\(null\)/,+ );+});++test("Reload is reachable when only the server-wide budget changed", () => {+ // The budget is on no per-model field, so the page stays at its baseline and the+ // button stayed disabled while the row asked for a reload.+ assert.match(+ pageSource.replace(/\s+/g, " "),+ /isActiveModel && atBaseline && !rememberChanged && !budgetReloadRequired/,+ );+ assert.match(+ pageSource.replace(/\s+/g, " "),+ /subscribeVramBudgetSettings\(\(next\) => \{ setBudgetReloadRequired\(next\.reloadRequired\); \}\)/,+ );+});++test("a read displaced by a forced one does not publish", () => {+ const client = readFileSync(+ fileURLToPath(+ new URL("../src/features/settings/api/vram-budget.ts", import.meta.url),+ ),+ "utf8",+ );+ // Clearing the handle is not enough: the displaced GET still resolves, and it+ // describes the child being replaced, so publishing would restore the notice and+ // the Reload button that the forced read had just cleared.+ assert.match(+ client.replace(/\s+/g, " "),+ /if \( inFlightVramBudget !== read \|\|/,+ );+});++test("settling before a load hears about the write that failed", () => {+ const client = readFileSync(+ fileURLToPath(+ new URL("../src/features/settings/api/vram-budget.ts", import.meta.url),+ ),+ "utf8",+ );+ const flat = client.replace(/\s+/g, " ");+ // The chain swallows rejections so one failed save cannot strand the ones behind+ // it, so a Run waiting on the chain was told the save succeeded and never+ // dropped the retry, which the teardown then flushed against the load.+ assert.match(+ flat,+ /vramBudgetWritesOpen > 0 \? vramBudgetNewestWrite : null/,+ );+ assert.match(+ flat,+ /vramBudgetWriteChain = write\.catch\(\(\) => undefined\); vramBudgetNewestWrite = write;/,+ );+});++test("a read does not repaint over a write issued while it was in the air", () => {+ const client = readFileSync(+ fileURLToPath(+ new URL("../src/features/settings/api/vram-budget.ts", import.meta.url),+ ),+ "utf8",+ );+ const flat = client.replace(/\s+/g, " ");+ // Waiting behind the writes open at read time says nothing about a save made+ // while the GET is in the air; that PUT can publish first and the late GET would+ // then restore the fraction the server no longer holds.+ assert.match(flat, /const generationAtRead = vramBudgetWriteGeneration;/);+ assert.match(+ flat,+ /generationAtRead !== vramBudgetWriteGeneration \) \{ throw new Error\("superseded"\)/,+ );+});++test("Manual with automatic layers still shows the budget", () => {+ // --fit-target carries the budget into that mode, and the launched fraction is+ // recorded for it, so hiding the row left a model loaded under an older budget+ // with neither the notice nor a way to reload.+ assert.match(+ pageSource.replace(/\s+/g, " "),+ /\{!isDiffusion && \(!isManual \|\| autoLayers\) && gpuDevices\.length > 0 && \( <VramBudgetRow \/> \)\}/,+ );+});++test("a superseded read is refused, not handed back to the caller", () => {+ const client = readFileSync(+ fileURLToPath(+ new URL("../src/features/settings/api/vram-budget.ts", import.meta.url),+ ),+ "utf8",+ );+ // Holding back the publish is not enough: the row applies the return value with+ // setSettings, so a read overtaken by a save would put back the isStored and+ // reloadRequired that save had just changed. Null is already this function's+ // "no usable answer", which every caller treats as keep what you have.+ const flat = client.replace(/\s+/g, " ");+ assert.match(flat, /throw new Error\("superseded"\); \}/);+ assert.match(flat, /try \{ return await inFlightVramBudget; \} catch \{/);+ const row = vramBudgetRowSource().replace(/\s+/g, " ");+ assert.match(row, /if \(cancelled \|\| !loaded\) \{ return; \}/);+});