Skip to content

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.

Studio: show a VRAM memory bar on downloaded models (#7880)

IMJONEZZ54367e5910c8
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.py
index bba8c3433c5..130ef72365a 100644
--- a/studio/backend/core/inference/llama_cpp.py
+++ b/studio/backend/core/inference/llama_cpp.py
@@ -2488,6 +2488,22 @@ def _pick_dspark(candidates: list[str]) -> Optional[str]:
return files[0] if files else None
+def _pick_mtp(candidates: list[str]) -> Optional[str]:
+ """The MTP drafter a listing offers, or None. Module level for the same reason
+ ``_pick_dspark`` is: both are handed a live repo listing as well as a snapshot,
+ and ``/kv-cache-estimate`` has to price the drafter the launch will open."""
+ # Root-level only: MTP/ subdir copies now share the mtp- prefix but
+ # are explicit-selection, not auto-fetch (they'd sort ahead of root).
+ # The mtp- prefix also excludes AppleDouble shadows ("._mtp-x.gguf"), which
+ # is why this picker needs no drop_shadowed_appledouble_names of its own.
+ mtp_files = sorted(
+ f
+ for f in candidates
+ if f.lower().endswith(".gguf") and "/" not in f and Path(f).name.lower().startswith("mtp-")
+ )
+ return mtp_files[0] if mtp_files else None
+
+
def _pick_mmproj(candidates: list[str]) -> Optional[str]:
from hub.utils.gguf import drop_shadowed_appledouble_names
@@ -12757,18 +12773,6 @@ class LlamaCppBackend:
are intentionally skipped. Returns the local path, or None.
"""
- def _pick_mtp(candidates: list[str]) -> Optional[str]:
- # Root-level only: MTP/ subdir copies now share the mtp- prefix but
- # are explicit-selection, not auto-fetch (they'd sort ahead of root).
- mtp_files = sorted(
- f
- for f in candidates
- if f.lower().endswith(".gguf")
- and "/" not in f
- and Path(f).name.lower().startswith("mtp-")
- )
- return mtp_files[0] if mtp_files else None
-
if near_path:
cached = _companion_snapshot_sibling(near_path, _pick_mtp)
if cached:
diff --git a/studio/backend/routes/models.py b/studio/backend/routes/models.py
index 2607f31b6d7..431de8ea54e 100644
--- a/studio/backend/routes/models.py
+++ b/studio/backend/routes/models.py
@@ -14,7 +14,7 @@ import time
import uuid
import weakref
from pathlib import Path
-from fastapi import APIRouter, Body, Depends, Header, HTTPException, Query
+from fastapi import APIRouter, Body, Depends, Header, HTTPException, Query, Request
from pydantic import BaseModel
from typing import List, NamedTuple, Optional
from loggers import get_logger
@@ -284,6 +284,13 @@ from utils.paths.path_utils import is_appledouble_metadata
router = APIRouter()
logger = get_logger(__name__)
+# The shortest context worth pricing, used to separate the part of a footprint
+# that shrinks with context from the part that does not. Not zero: zero means
+# "the model's native length" to the planner, which is the opposite of what this
+# asks. One llama.cpp KV stream pads to 256, so a smaller number would not make
+# the cache any smaller and only invites a divide-by-zero somewhere downstream.
+_MIN_PRICED_CONTEXT = 256
+
def derive_model_type(
is_vision: bool,
@@ -3598,6 +3605,16 @@ def _resolve_quant_gguf(repo_id: str, quant: str, is_local: bool) -> tuple[Optio
"""
try:
if is_local:
+ # A direct file selection names the weights outright: custom, LM
+ # Studio and other local inventory entries whose path ends in .gguf
+ # never go through variant selection, so there is no quant label to
+ # match and nothing to scan for. Answer with the file itself, and
+ # with the whole split family's size rather than this shard's, the
+ # same way the quant scan below totals its shards.
+ direct = Path(repo_id)
+ if direct.is_file() and direct.suffix.lower() == ".gguf":
+ from core.inference.llama_cpp import LlamaCppBackend
+ return str(direct), LlamaCppBackend._get_gguf_size_bytes(str(direct))
roots = [Path(repo_id)]
else:
from hub.utils.hf_cache_state import iter_repo_cache_dirs
@@ -3650,68 +3667,678 @@ def _resolve_quant_gguf(repo_id: str, quant: str, is_local: bool) -> tuple[Optio
return None, 0
+def _resolve_mtp_drafter(
+ main_gguf_path: str, search_root: Optional[str] = None
+) -> tuple[Optional[str], int]:
+ """Separate MTP drafter GGUF for a resolved main quant, or (None, 0).
+
+ Some repos ship the drafter as its own file beside the weights (Gemma 4's
+ ``mtp-*.gguf``). The main GGUF has no ``nextn_predict_layers`` in that case,
+ so the estimator's embedded-head path returns None and the reserve reads as
+ zero unless we hand it the drafter.
+
+ Delegates to the two resolvers the LOAD path already uses, rather than
+ scanning for a drafter itself: ``_companion_snapshot_sibling`` with the
+ loader's own ``_pick_mtp`` for an HF snapshot, and ``detect_mtp_file`` for a
+ local folder, which is what ``model_config`` calls when it builds the launch.
+ A bespoke scan here is how the estimate ends up pricing a different file from
+ the one llama-server opens: ``_pick_mtp`` is root-level and prefix-matched, so
+ it cannot be fooled by a directory that happens to be named ``mtp``, it finds
+ the snapshot-root companion when the weights sit in a quant subdirectory, it
+ sorts on relative strings rather than ``Path`` objects (whose ordering is
+ case-folded on Windows and not on POSIX, so two hosts really can disagree),
+ and it rejects an incomplete split set. Never raises: a drafter we cannot
+ find just costs a segment.
+ """
+ try:
+ from core.inference.llama_cpp import (
+ _companion_snapshot_sibling,
+ _pick_mtp,
+ _snapshot_dir_of,
+ )
+
+ if _snapshot_dir_of(main_gguf_path) is not None:
+ # An HF snapshot. ``_download_mtp`` resolves through ``_pick_mtp``,
+ # which is root-level only, so the ``MTP/`` precision copies are not
+ # auto-fetched and must not be priced: charging one would report a
+ # reserve for a drafter the load will not open.
+ drafter = _companion_snapshot_sibling(main_gguf_path, _pick_mtp)
+ else:
+ # A local folder, where the load path (model_config) pairs the drafter
+ # to the weight by name so a multi-model folder cannot attach a foreign
+ # one, and does accept the ``MTP/`` copy when no root drafter exists.
+ # No ``accept`` filter: the load path's one enforces a native-lease
+ # boundary, which a read-only estimate does not cross.
+ from utils.models.model_config import detect_mtp_file
+ drafter = detect_mtp_file(main_gguf_path, search_root = search_root)
+ if not drafter:
+ return None, 0
+ # The whole split family, not just the shard llama-server is handed:
+ # the load planner sizes the drafter with _get_gguf_size_bytes, and a
+ # split companion reserves every shard. Billing shard 1 alone reports a
+ # fit for a launch that allocates several times as much.
+ from core.inference.llama_cpp import LlamaCppBackend
+
+ return drafter, LlamaCppBackend._get_gguf_size_bytes(drafter)
+ except Exception:
+ return None, 0
+
+
@router.get("/kv-cache-estimate")
async def get_kv_cache_estimate(
repo_id: str = Query(..., description = "HF repo ID or local path"),
quant: str = Query(..., description = "Quantization label (e.g. Q4_K_M)"),
- n_ctx: int = Query(..., ge = 1, description = "Context length to size the KV cache for"),
+ n_ctx: Optional[int] = Query(
+ None,
+ ge = 1,
+ description = "Context length to size the KV cache for; omit for the model's native length",
+ ),
cache_type_kv: Optional[str] = Query(
None,
description = "KV cache dtype (e.g. q8_0, q4_0, q5_0, iq4_nl, f32)",
),
+ n_parallel: Optional[int] = Query(
+ None,
+ ge = 1,
+ description = (
+ "--parallel slots; scales the per-slot KV stream padding. Omit to use "
+ "the server's own slot count, which is what a default load gets."
+ ),
+ ),
+ speculative_type: Optional[str] = Query(
+ None,
+ description = "Speculative decoding mode (mtp, ngram, mtp+ngram, dspark, dflash, auto)",
+ ),
+ spec_draft_n_max: Optional[int] = Query(
+ None,
+ ge = 0,
+ description = (
+ "--spec-draft-n-max. A Hybrid Mamba target keeps one recurrent rollback "
+ "state per drafted token, so this is the dominant speculative cost there."
+ ),
+ ),
+ spec_draft_cache_type: Optional[str] = Query(
+ None,
+ description = "Draft KV cache dtype (--spec-draft-type-k/-v), independent of the main cache",
+ ),
+ ctx_checkpoints: Optional[int] = Query(
+ None,
+ ge = 0,
+ description = "--ctx-checkpoints; each one adds an SWA snapshot per slot",
+ ),
+ n_batch: Optional[int] = Query(
+ None,
+ ge = 1,
+ description = "--batch-size; the compute buffers scale with it",
+ ),
+ n_ubatch: Optional[int] = Query(
+ None,
+ ge = 1,
+ description = "--ubatch-size; the dominant term in the flat compute buffer",
+ ),
+ tensor_parallel: bool = Query(
+ False,
+ description = "Tensor mode replicates compute buffers on every device in the pool",
+ ),
+ disable_vision: bool = Query(
+ False,
+ description = "Load a vision GGUF without its mmproj, freeing the projector's VRAM",
+ ),
+ request: Request = None, # type: ignore[assignment]
current_subject: str = Depends(get_current_subject),
):
- """Estimate KV cache + weight bytes for a downloaded GGUF at n_ctx.
+ """KV cache, weight and speculative-decoding bytes for a downloaded GGUF.
+
+ Backs the load dialog's "exceeds memory" warning and the picker's memory
+ bar, using the same architecture-aware estimator as load. Best-effort: on
+ missing metadata it returns nulls and the UI simply shows nothing.
- Powers the load dialog's "exceeds memory" warning using the same
- architecture-aware estimator as load. Best-effort: returns nulls when the
- metadata is unavailable so the UI simply shows no warning.
+ ``spec_bytes`` is what an MTP draft mode costs on top of ``kv_bytes``. It is
+ null for ngram, which drafts from the generated text and costs no VRAM, and
+ for models with no drafter -- the caller draws no segment either way.
"""
- null = {"kv_bytes": None, "weights_bytes": None, "native_context": None}
- try:
- from utils.models.model_config import is_local_path
- is_local = is_local_path(repo_id)
- path, weights_bytes = _resolve_quant_gguf(repo_id, quant, is_local)
- if not path:
- return null
+ # The header read, the HF cache walk in _resolve_quant_gguf, the drafter
+ # lookup and the capability probe are all blocking disk work, and this
+ # route is called once per visible row. Run it in a worker so a long model
+ # list cannot stall the streamed tokens of a chat in the same process.
+ # n_ctx and n_parallel are bound as arguments rather than closed over: the
+ # body assigns to both (defaulting them), which would otherwise make them
+ # locals of this function and raise before either default could be applied.
+ def _estimate(n_ctx: Optional[int] = n_ctx, n_parallel: Optional[int] = n_parallel) -> dict:
+ null = {
+ "kv_bytes": None,
+ "weights_bytes": None,
+ "native_context": None,
+ "spec_bytes": None,
+ "n_ctx": None,
+ "projector_bytes": None,
+ "spec_unpriced": False,
+ "kv_checkpoint_bytes": None,
+ "spec_fixed_bytes": None,
+ "gpu_bytes": None,
+ "compute_bytes": None,
+ "total_bytes": None,
+ "gpu_floor_bytes": None,
+ "context_is_pinned": None,
+ "inherited_device_pin": None,
+ }
+ try:
+ from utils.models.model_config import is_local_path
+
+ is_local = is_local_path(repo_id)
+ path, weights_bytes = _resolve_quant_gguf(repo_id, quant, is_local)
+ if not path:
+ return null
+
+ from core.inference.llama_cpp import LlamaCppBackend
+
+ be = LlamaCppBackend.__new__(LlamaCppBackend)
+ for attr in (
+ "_context_length",
+ "_n_layers",
+ "_n_kv_heads",
+ "_n_heads",
+ "_embedding_length",
+ "_kv_key_length",
+ "_kv_value_length",
+ "_kv_lora_rank",
+ "_sliding_window",
+ "_sliding_window_pattern",
+ "_ssm_inner_size",
+ "_full_attention_interval",
+ "_key_length_mla",
+ "_n_kv_heads_by_layer",
+ "_kv_key_length_swa",
+ "_kv_value_length_swa",
+ "_shared_kv_layers",
+ "_nextn_predict_layers",
+ ):
+ setattr(be, attr, None)
+ be._model_identifier = "kv-estimate"
+ be._read_gguf_metadata(path)
+
+ # With no pinned context a GGUF loads at its own native length, which
+ # only the metadata we just read knows. Defaulting here saves the caller
+ # a round trip spent discovering the number it then asks about.
+ # Mirror _resolve_parallel_slots: an omitted count means the server's
+ # standing slot count, not one slot. The KV estimator scales per-slot
+ # padding, so assuming 1 understates a default load.
+ if n_parallel is None:
+ state = getattr(getattr(request, "app", None), "state", None)
+ n_parallel = getattr(state, "llama_parallel_slots", 1) or 1
+ # What the launch will actually serve, not what was asked for. A build
+ # without --kv-unified splits the window per slot, so load_model falls
+ # back to one; pricing a four-slot default against such a build
+ # inflates the cache several times over and can warn OOM about a
+ # command that would never launch that way. Same resolution
+ # /estimate-memory applies, so the two cannot disagree.
+ try:
+ from routes.inference import _effective_parallel_slots
+ n_parallel = _effective_parallel_slots(n_parallel, diffusion_kind = False)
+ except Exception as e:
+ logger.debug(f"slot clamp unavailable for '{repo_id}' {quant}: {e}")
+
+ # Whether the caller pinned a context, kept before the default below
+ # overwrites it. The planner reads the inherited LLAMA_ARG_CTX_SIZE
+ # only when its own n_ctx input is zero, so handing it the native
+ # length here priced the header's window for a child that will run at
+ # the environment's -- and an inherited context LARGER than native is
+ # then underpriced while still reading as auto-fitted.
+ _inherited_device_pin = False
+ try:
+ _dev = (os.environ.get("LLAMA_ARG_DEVICE") or "").strip()
+ # "none" is a CPU-only launch, which the planner already answers
+ # with zero GPU bytes; that path draws no bar on its own.
+ _inherited_device_pin = bool(_dev) and _dev.lower() != "none"
+ except Exception as e:
+ logger.debug(f"inherited device pin unreadable: {e}")
+
+ _ctx_was_omitted = not n_ctx
+ # Whether the launch will auto-fit at all. Only a context nobody
+ # pinned gets reduced to fit: load_model keeps a positive inherited
+ # LLAMA_ARG_CTX_SIZE rather than fitting it, so an inherited window
+ # over budget is a real overage the caller must be allowed to warn
+ # about. Resolved below once the inherited value is known.
+ _context_is_pinned = not _ctx_was_omitted
+ # Same precedence the launch uses: an inherited positive context beats
+ # the header, since load_model drops it only when it is zero.
+ if _ctx_was_omitted:
+ try:
+ from routes.inference import _inherited_ctx_size
+
+ _inherited = _inherited_ctx_size()
+ _context_is_pinned = bool(_inherited)
+ n_ctx = _inherited or be._context_length
+ except Exception as e:
+ logger.debug(f"inherited context unavailable: {e}")
+ n_ctx = be._context_length
+ if not n_ctx or n_ctx < 1:
+ return null
+
+ # The K/V types the launch will really open, including an inherited
+ # LLAMA_ARG_CACHE_TYPE_K/V that no structured setting overrode. The
+ # planner already resolves these for gpu_bytes; without the same
+ # resolution here kv_bytes stayed at f16 and the KV segment, the
+ # per-token rate and the readout all contradicted the total beside
+ # them. The heavier of the pair, matching the planner's own choice.
+ _effective_cache_type = cache_type_kv
+ try:
+ from core.inference.llama_cpp import (
+ _kv_bytes_per_elem,
+ _planned_main_cache_types,
+ )
+ _effective_cache_type = max(
+ _planned_main_cache_types(cache_type_kv, None), key = _kv_bytes_per_elem
+ )
+ except Exception as e:
+ logger.debug(f"cache type resolution failed for '{repo_id}': {e}")
+
+ # ctx_checkpoints is not a rounding error: each saved checkpoint is an
+ # SWA snapshot per slot, so a 4-slot SWA model at 32k measures 5.82 GiB
+ # with none and 11.82 GiB at the llama.cpp default of 32.
+ kv = be._estimate_kv_cache_bytes(
+ n_ctx,
+ _effective_cache_type,
+ n_parallel = n_parallel,
+ ctx_checkpoints = ctx_checkpoints or 0,
+ n_ubatch = n_ubatch,
+ )
- from core.inference.llama_cpp import LlamaCppBackend
+ # The checkpoint share of that cache, by difference rather than by
+ # re-deriving the SWA layer walk -- the snapshots are the only term that
+ # separates the two calls, so asking the same function twice cannot drift
+ # from it. This is the same derivation the load planner uses at
+ # routes/inference.py, and it is reported separately because llama.cpp
+ # keeps these snapshots in HOST heap: the planner's GPU figure is
+ # kv_bytes - kv_checkpoint_bytes. Folded into the bar's VRAM total they
+ # warn OOM over memory that never touches the card.
+ kv_checkpoint = 0
+ if ctx_checkpoints:
+ _kv_without = be._estimate_kv_cache_bytes(
+ n_ctx,
+ _effective_cache_type,
+ n_parallel = n_parallel,
+ ctx_checkpoints = 0,
+ n_ubatch = n_ubatch,
+ )
+ kv_checkpoint = max(0, int(kv) - int(_kv_without))
+
+ # DSpark and DFlash attach a separate draft GGUF with its own weights
+ # and KV context, and Auto promotes to either ahead of MTP. Pricing
+ # them means reproducing the loader's whole sidecar precedence, which
+ # is how an estimate ends up charging a drafter the launch never
+ # opens. A DSpark sidecar alone runs to about 11 GB, so reporting a
+ # comfortable fit that omits it is the worst of the options: say the
+ # reserve is unpriced and let the caller draw nothing instead.
+ _spec_mode = (speculative_type or "").lower()
+ spec_unpriced = _spec_mode in ("dspark", "dflash")
+ # Auto is not a mode that declines a sidecar: the load planner promotes it
+ # to DSpark or DFlash whenever the repo ships one and the binary supports
+ # it, ahead of MTP. Reading the explicit modes alone left the largest
+ # single allocation this route can miss -- a DSpark sidecar is about 11 GB
+ # -- silently absent from an Auto row, which is the case that reports a
+ # comfortable fit and then fails to load. Gated on the binary's own
+ # capability for the same reason the planner gates on it: charging (or
+ # here, abstaining over) a sidecar the launch never opens would blank the
+ # bar on hosts whose llama-server cannot run one.
+ if not spec_unpriced and _spec_mode == "auto":
+ try:
+ # Imported here, not borrowed from _resolve_mtp_drafter: these
+ # live in that function's local scope, so referencing them from
+ # this one raised NameError into the except below and left
+ # spec_unpriced false -- the silent no-op this guard exists to
+ # prevent, and invisible precisely because it failed quietly.
+ from core.inference.llama_cpp import (
+ _companion_snapshot_sibling,
+ _is_dflash_drafter_path,
+ _pick_dspark,
+ _snapshot_dir_of,
+ )
- be = LlamaCppBackend.__new__(LlamaCppBackend)
- for attr in (
- "_context_length",
- "_n_layers",
- "_n_kv_heads",
- "_n_heads",
- "_embedding_length",
- "_kv_key_length",
- "_kv_value_length",
- "_kv_lora_rank",
- "_sliding_window",
- "_sliding_window_pattern",
- "_ssm_inner_size",
- "_full_attention_interval",
- "_key_length_mla",
- "_n_kv_heads_by_layer",
- "_kv_key_length_swa",
- "_kv_value_length_swa",
- "_shared_kv_layers",
- "_nextn_predict_layers",
- ):
- setattr(be, attr, None)
- be._model_identifier = "kv-estimate"
- be._read_gguf_metadata(path)
-
- kv = be._estimate_kv_cache_bytes(n_ctx, cache_type_kv)
- return {
- "kv_bytes": int(kv) if kv else None,
- "weights_bytes": weights_bytes or None,
- "native_context": be._context_length,
- }
- except Exception as e:
- logger.debug(f"kv-cache-estimate failed for '{repo_id}' {quant}: {e}")
- return null
+ def _pick_dflash(candidates: list[str]) -> Optional[str]:
+ hits = sorted(f for f in candidates if _is_dflash_drafter_path(f))
+ return hits[0] if hits else None
+
+ _caps = be.probe_server_capabilities() or {}
+ if _snapshot_dir_of(path) is not None:
+ _has_dspark = bool(_companion_snapshot_sibling(path, _pick_dspark))
+ _has_dflash = bool(_companion_snapshot_sibling(path, _pick_dflash))
+ else:
+ # A plain local folder resolves its sidecars the way the load
+ # path does, through the same detectors that populate
+ # gguf_dspark_file / gguf_dflash_file. Restricting this to
+ # snapshots left every local model charting a total with the
+ # drafter missing.
+ from utils.models.drafters.dflash import detect_dflash_file
+ from utils.models.model_config import detect_dspark_file
+
+ _root = repo_id if is_local else None
+ _has_dspark = bool(detect_dspark_file(path, search_root = _root))
+ _has_dflash = bool(detect_dflash_file(path, search_root = _root))
+ if (_caps.get("supports_dspark") and _has_dspark) or (
+ _caps.get("supports_dflash") and _has_dflash
+ ):
+ spec_unpriced = True
+ except Exception as e:
+ logger.debug(f"auto sidecar probe failed for '{repo_id}' {quant}: {e}")
+
+ # A vision GGUF launches with its mmproj resident unless the user
+ # turned vision off, and the projector is charged at a worst-case
+ # multiple of its file size (_MMPROJ_VRAM_SAFETY), not at it. Left
+ # out, a vision row shows a comfortable fit for a launch that has to
+ # find another gigabyte or push the projector to the CPU.
+ projector = None
+ if not disable_vision:
+ try:
+ from core.inference.llama_cpp import LlamaCppBackend as _Be
+ from utils.models.model_config import detect_mmproj_file
+
+ # A cached HF layout puts the weights under a quant subdir
+ # (snapshot/Q4_K_M/model.gguf) and the projector at the
+ # snapshot ROOT, so scanning the weights' own directory finds
+ # nothing. Anchored the same way the drafter lookup is, and
+ # the same way the loader's _download_mmproj anchors on
+ # near_path.
+ from core.inference.llama_cpp import (
+ _companion_snapshot_sibling,
+ _pick_mmproj,
+ _snapshot_dir_of,
+ )
+
+ if _snapshot_dir_of(path) is not None:
+ mmproj = _companion_snapshot_sibling(path, _pick_mmproj)
+ else:
+ mmproj = detect_mmproj_file(path, search_root = repo_id if is_local else None)
+ if mmproj:
+ projector = int(_Be._get_gguf_size_bytes(mmproj) * _Be._MMPROJ_VRAM_SAFETY)
+ except Exception as e:
+ logger.debug(f"mmproj estimate failed for '{repo_id}' {quant}: {e}")
+
+ # Only the MTP modes reserve memory; ngram is free. "auto" may or may
+ # not resolve to MTP, and the estimator returns None when it doesn't.
+ # Guarded separately: the MTP path reads more metadata than the KV path,
+ # and a model it can't size should still get its KV bar rather than
+ # dropping the whole response to nulls.
+ spec = None
+ spec_fixed = None
+ if (speculative_type or "").lower() in ("mtp", "mtp+ngram", "auto"):
+ try:
+ from core.inference.llama_cpp import (
+ _auto_mode_drops_mtp,
+ _extract_model_size_b,
+ _is_mtp_model_name,
+ _mla_mtp_auto_enabled,
+ )
+
+ drafter_path, drafter_bytes = _resolve_mtp_drafter(
+ path, search_root = repo_id if is_local else None
+ )
+ # Auto declines MTP on a sub-3B embedded head, where the
+ # per-token cost regresses; a separate drafter is exempt. Pricing
+ # a reserve the load will not take would overstate the bar and
+ # could warn OOM on a model that fits.
+ _mode = (speculative_type or "").lower()
+
+ # Same reason, one level down: llama-server only takes the MTP
+ # path when it advertises a --spec-type mtp token, and the loader
+ # declines on an inconclusive probe too. Both cover the
+ # separate-drafter path, which is emitted behind the same gate.
+ # Probes are cached on (path, mtime), so this stays cheap.
+ _binary_lacks_mtp = not (be.probe_server_capabilities() or {}).get("mtp_token")
+ # Auto also declines an MLA embedded head (GLM/DeepSeek/Kimi):
+ # that path keeps a duplicated full target-KV context and runs
+ # slower than no speculation, so it is off unless opted into.
+ # A separate drafter is unaffected, as is a non-MLA head.
+ _auto_drops_mla = (
+ _mode == "auto"
+ and be._kv_lora_rank is not None
+ and bool(be._nextn_predict_layers)
+ and not drafter_path
+ and not _mla_mtp_auto_enabled()
+ )
+ # The loader's own precondition (is_mtp_model): a model with no
+ # embedded head, no MTP name and no separate drafter cannot run
+ # MTP at all, so llama-server gets --spec-default and reserves
+ # nothing. Without this check _estimate_mtp_overhead_bytes still
+ # charges its target-side terms, and because
+ # mtp_keeps_target_ctx defaults to True -- deliberately, so an
+ # unsure caller over-reserves -- every MLA model was billed a
+ # second full f16 copy of its own KV. That is the whole cache
+ # again, which is the largest way this bar could be wrong, and it
+ # is wrong in the direction that warns OOM on a model that loads.
+ _not_an_mtp_model = not (
+ bool(be._nextn_predict_layers)
+ or _is_mtp_model_name(repo_id, path)
+ or bool(drafter_path)
+ )
+ if (
+ _binary_lacks_mtp
+ or _auto_drops_mla
+ or _not_an_mtp_model
+ or _auto_mode_drops_mtp(
+ _mode,
+ _extract_model_size_b(repo_id),
+ has_separate_drafter = bool(drafter_path),
+ )
+ ):
+ pass
+ else:
+ # The drafter's own weights: resident for as long as the
+ # drafter is open and not reducible by shortening context.
+ # Reported separately so the caller's auto-fit softening,
+ # which exists for the context-linear part of the cache,
+ # cannot swallow a fixed overage no shorter context fixes.
+ spec_fixed = int(drafter_bytes or 0) or None
+ _effective_draft_n_max = spec_draft_n_max
+ if _effective_draft_n_max is None:
+ try:
+ from routes.inference import (
+ _cached_estimate_config,
+ _estimate_draft_n_max,
+ )
+ _effective_draft_n_max = _estimate_draft_n_max(
+ _cached_estimate_config(repo_id, quant, None, False),
+ drafter_path or "",
+ requested = None,
+ extras = [],
+ )
+ except Exception as e:
+ logger.debug(f"draft depth default failed: {e}")
+ _effective_draft_n_max = 0
+ spec = be._estimate_mtp_overhead_bytes(
+ n_ctx,
+ # Draft K/V types are independent of the main cache and
+ # default to f16 at load; leaving them unset keeps this
+ # from underpricing a quantized-main-cache setup.
+ draft_cache_type_k = spec_draft_cache_type,
+ draft_cache_type_v = spec_draft_cache_type,
+ drafter_path = drafter_path,
+ draft_weights_bytes = drafter_bytes,
+ n_parallel = n_parallel,
+ # A Hybrid Mamba target keeps one recurrent rollback
+ # state per drafted token, which dominates everything
+ # else here: on a 4-slot model at 32k the reserve is
+ # 0.125 GiB at the zero default and 6.944 GiB at a
+ # depth of 16, so omitting it is a 55x understatement.
+ # Blank is not zero. _build_speculative_flags emits
+ # its own default when the field is unset (2 with a
+ # GPU, 3 without), and the rollback state is
+ # multiplied by it, so pricing zero dropped the
+ # dominant allocation on a Hybrid Mamba target
+ # outright. An explicit 0 is still honoured, since
+ # that is a real request to draft nothing.
+ spec_draft_n_max = _effective_draft_n_max,
+ )
+ except Exception as e:
+ logger.debug(f"mtp overhead estimate failed for '{repo_id}' {quant}: {e}")
+
+ # The load planner's own answer, alongside this route's field-by-field
+ # one. It is the authoritative figure: it applies the inherited
+ # environment (LLAMA_ARG_CACHE_TYPE_K/V, LLAMA_ARG_SWA_FULL,
+ # LLAMA_ARG_CTX_SIZE), derives the companion search roots the loader
+ # derives, and includes the compute buffers -- every term this route
+ # would otherwise have to reproduce, and has repeatedly reproduced
+ # incompletely. gpu_bytes is what lands on the card, with the host-heap
+ # checkpoint share already subtracted.
+ #
+ # Added beside the existing fields rather than replacing them: the
+ # planner defines weights_bytes as the weights PLUS whichever projector
+ # and drafter the launch opens, while this route's field shipped meaning
+ # the quant file alone. Redefining it would move a number an existing
+ # caller already reads.
+ planner_gpu = None
+ planner_compute = None
+ planner_total = None
+ planner_floor = None
+ planner_unsized = False
+ try:
+ from routes.inference import (
+ _ESTIMATE_NOT_ON_DISK,
+ _cached_estimate_config,
+ _gguf_memory_breakdown,
+ _localized_estimate_config,
+ )
+
+ # Tensor mode replicates its compute buffers on every device in
+ # the pool, so pricing one device understates the reserve by a
+ # factor of however many cards the launch would use. Only consulted
+ # in tensor mode: a layer split does not replicate them the same
+ # way, and this is the same count the load panel derives.
+ # The effective mode, not the request boolean: the planner turns
+ # tensor mode on for an inherited LLAMA_ARG_SPLIT_MODE=tensor even
+ # when the per-model toggle is off, and it replicates the compute
+ # buffers per device when it does. Reading the toggle alone left
+ # n_devices at one for exactly that launch.
+ _effective_tp = tensor_parallel
+ try:
+ from core.inference.llama_server_args import _effective_tensor_parallel
+ _effective_tp = _effective_tensor_parallel(None, bool(tensor_parallel))
+ except Exception as e:
+ logger.debug(f"tensor mode resolution failed for '{repo_id}': {e}")
+ _planner_devices = 1
+ if _effective_tp:
+ from routes.inference import (
+ _cached_inference_devices,
+ _guard_device_count,
+ )
+ _planner_devices = max(
+ 1,
+ _guard_device_count(
+ None, _cached_inference_devices(), tensor_parallel = True
+ ),
+ )
+ _cfg = _cached_estimate_config(repo_id, quant, None, False)
+ if _cfg is not None and _cfg is not _ESTIMATE_NOT_ON_DISK:
+ _cfg = _localized_estimate_config(_cfg, path)
+ _b = _gguf_memory_breakdown(
+ _cfg,
+ path,
+ n_ctx = 0 if _ctx_was_omitted else n_ctx,
+ speculative_type = speculative_type,
+ n_parallel = n_parallel,
+ cache_type_kv = cache_type_kv,
+ ctx_checkpoints = ctx_checkpoints,
+ disable_vision = disable_vision,
+ spec_draft_n_max = spec_draft_n_max,
+ spec_draft_cache_type = spec_draft_cache_type,
+ n_batch = n_batch,
+ n_ubatch = n_ubatch,
+ tensor_parallel = tensor_parallel,
+ n_devices = _planner_devices,
+ )
+ if _b is not None:
+ # `or None` would fold a real zero into "no answer".
+ # Zero is a meaningful result: inherited placement such as
+ # LLAMA_ARG_DEVICE=none makes the launch entirely CPU
+ # resident, and discarding that sent the caller back to
+ # summing segments and drawing VRAM pressure for a load
+ # that touches no card at all.
+ planner_gpu = int(_b.gpu_bytes)
+ planner_compute = int(_b.compute_bytes) or None
+ planner_total = int(_b.total_bytes) or None
+ planner_unsized = bool(_b.drafter_kv_unsized)
+ # The same plan priced at the shortest context worth
+ # asking for. Whatever is still there cannot be reduced by
+ # shortening context: the drafter's weights, the flat
+ # compute buffer, a Hybrid Mamba target's recurrent
+ # rollback state. Taken by difference against the real
+ # plan rather than by naming those terms, because naming
+ # them is how this route kept missing one; the planner
+ # decides what is fixed, and asking it twice cannot drift
+ # from itself.
+ #
+ # This is what an unpinned row's hard verdict must be
+ # drawn against. Auto-fit can shrink the cache, so a
+ # context-driven overage is not a failure, but nothing it
+ # can do touches this floor.
+ _floor = _gguf_memory_breakdown(
+ _cfg,
+ path,
+ n_ctx = _MIN_PRICED_CONTEXT,
+ speculative_type = speculative_type,
+ n_parallel = n_parallel,
+ cache_type_kv = cache_type_kv,
+ ctx_checkpoints = ctx_checkpoints,
+ disable_vision = disable_vision,
+ spec_draft_n_max = spec_draft_n_max,
+ spec_draft_cache_type = spec_draft_cache_type,
+ n_batch = n_batch,
+ n_ubatch = n_ubatch,
+ tensor_parallel = tensor_parallel,
+ n_devices = _planner_devices,
+ )
+ if _floor is not None:
+ planner_floor = min(int(_floor.gpu_bytes), planner_gpu)
+ except Exception as e:
+ logger.debug(f"planner breakdown failed for '{repo_id}' {quant}: {e}")
+
+ return {
+ "kv_bytes": int(kv) if kv else None,
+ "weights_bytes": weights_bytes or None,
+ "native_context": be._context_length,
+ "spec_bytes": int(spec) if spec else None,
+ "n_ctx": int(n_ctx),
+ "projector_bytes": projector or None,
+ # The part of kv_bytes that llama.cpp keeps in host heap rather than
+ # on the card, so a VRAM bar can subtract it. Included in kv_bytes,
+ # not beside it: the field shipped meaning the whole cache and an
+ # existing caller still reads it that way.
+ "kv_checkpoint_bytes": kv_checkpoint or None,
+ # The part of spec_bytes a shorter context cannot reduce.
+ "spec_fixed_bytes": spec_fixed if spec else None,
+ # The load planner's figures. gpu_bytes is the complete footprint
+ # that lands on the card and is what a fit verdict should be drawn
+ # against; the rest are itemized for the caller that wants them.
+ "gpu_bytes": planner_gpu,
+ "compute_bytes": planner_compute,
+ "total_bytes": planner_total,
+ # What remains on the card at the shortest context, so a caller
+ # can tell a context-driven overage from one no context fixes.
+ "gpu_floor_bytes": planner_floor,
+ # False only when the loader is free to shrink the context. A
+ # caller that softens its verdict for an auto-fitted row has to
+ # stop softening here, or an inherited window over budget reads
+ # as a fit for a launch that will OOM.
+ "context_is_pinned": _context_is_pinned,
+ # An inherited LLAMA_ARG_DEVICE confines the child to the cards it
+ # names, and an automatic launch preserves it. The caller's budget
+ # is an aggregate over the whole visible inventory, which then
+ # describes a pool the launch will not open -- a 30 GiB model
+ # reads as fitting 2x24 GiB while the child has one card. The
+ # caller cannot see the environment, so it is reported here.
+ # Any pin at all is enough to say so: the route does not know the
+ # host's inventory, and abstaining is the safe direction.
+ "inherited_device_pin": _inherited_device_pin,
+ # The planner saw a drafter whose cache it could not size, so its
+ # own total is a floor.
+ "spec_unpriced": spec_unpriced or planner_unsized,
+ }
+ except Exception as e:
+ logger.debug(f"kv-cache-estimate failed for '{repo_id}' {quant}: {e}")
+ return null
+
+ return await asyncio.to_thread(_estimate)
@router.get("/gguf-variants", response_model = GgufVariantsResponse)
diff --git a/studio/backend/tests/test_kv_cache_estimate_compat.py b/studio/backend/tests/test_kv_cache_estimate_compat.py
new file mode 100644
index 00000000000..6985269c948
--- /dev/null
+++ b/studio/backend/tests/test_kv_cache_estimate_compat.py
@@ -0,0 +1,146 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+"""Compatibility contract for GET /kv-cache-estimate.
+
+The route already shipped, so an existing caller must keep working across an
+upgrade. Two directions matter:
+
+* An OLD client still sends n_ctx and reads kv_bytes / weights_bytes /
+ native_context. Making n_ctx optional is a widening, and the new spec_bytes
+ and n_ctx fields are additions, so nothing it relies on may move.
+
+* A NEW client may omit n_ctx to ask for the model's native length. That is the
+ only request shape the previous version would have rejected, so it is the one
+ worth pinning.
+
+No GPU, no network.
+"""
+
+import asyncio
+import inspect
+import sys
+from pathlib import Path
+
+_TESTS_DIR = str(Path(__file__).resolve().parent)
+if _TESTS_DIR not in sys.path:
+ sys.path.insert(0, _TESTS_DIR)
+
+_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)
+if _BACKEND_DIR not in sys.path:
+ sys.path.insert(0, _BACKEND_DIR)
+
+from test_kv_cache_estimation import _make_gguf_bytes # noqa: E402
+
+import routes.models as models_routes # noqa: E402
+
+_FIELDS = {
+ "context_length": 8192,
+ "block_count": 32,
+ "attention.head_count": 32,
+ "attention.head_count_kv": 8,
+ "embedding_length": 4096,
+ "attention.key_length": 128,
+ "attention.value_length": 128,
+}
+
+# What a client written against the previous version reads back.
+_LEGACY_KEYS = {"kv_bytes", "weights_bytes", "native_context"}
+
+
+def _gguf(tmp_path: Path) -> Path:
+ kv = {"general.architecture": "llama"}
+ for k, v in _FIELDS.items():
+ kv[f"llama.{k}"] = v
+ p = tmp_path / "model-Q4_K_M.gguf"
+ p.write_bytes(_make_gguf_bytes("llama", kv))
+ return p
+
+
+def _call(monkeypatch, path: Path | None, **overrides):
+ # path=None leaves whatever the caller already patched in place, for the
+ # cases that are about the route's answer when nothing resolves.
+ if path is not None:
+ monkeypatch.setattr(
+ models_routes,
+ "_resolve_quant_gguf",
+ lambda *_a, **_k: (str(path), 4_000_000_000),
+ )
+ kwargs = dict(
+ repo_id = "org/repo",
+ quant = "Q4_K_M",
+ n_ctx = 4096,
+ cache_type_kv = None,
+ n_parallel = None,
+ speculative_type = None,
+ spec_draft_n_max = None,
+ spec_draft_cache_type = None,
+ ctx_checkpoints = None,
+ disable_vision = False,
+ n_batch = None,
+ n_ubatch = None,
+ tensor_parallel = False,
+ request = None,
+ current_subject = "test",
+ )
+ kwargs.update(overrides)
+ return asyncio.run(models_routes.get_kv_cache_estimate(**kwargs))
+
+
+def test_every_parameter_an_old_caller_sent_is_still_accepted(tmp_path):
+ """Signature check: nothing an existing client passes may have been removed
+ or made required in a way it does not satisfy."""
+ sig = inspect.signature(models_routes.get_kv_cache_estimate)
+ for name in ("repo_id", "quant", "n_ctx", "cache_type_kv"):
+ assert name in sig.parameters, f"{name} was removed from the route"
+ # The new ones must be optional, or an old caller's request 422s.
+ for name in ("n_parallel", "speculative_type"):
+ assert sig.parameters[name].default is not inspect.Parameter.empty
+
+
+def test_an_old_callers_request_still_answers_the_old_keys(monkeypatch, tmp_path):
+ out = _call(monkeypatch, _gguf(tmp_path), n_ctx = 4096)
+ assert _LEGACY_KEYS <= set(out), f"missing legacy keys: {_LEGACY_KEYS - set(out)}"
+ assert out["kv_bytes"] and out["kv_bytes"] > 0
+ assert out["weights_bytes"] == 4_000_000_000
+ assert out["native_context"] == 8192
+
+
+def test_the_answer_for_a_pinned_context_did_not_move(monkeypatch, tmp_path):
+ """The added parameters default to what the previous version implied, so an
+ unchanged request must produce an unchanged number."""
+ gguf = _gguf(tmp_path)
+ before = _call(monkeypatch, gguf, n_ctx = 4096)
+ # Exactly what an old client sends: no n_parallel, no speculative_type.
+ after = _call(monkeypatch, gguf, n_ctx = 4096, n_parallel = None, speculative_type = None)
+ assert before["kv_bytes"] == after["kv_bytes"]
+
+
+def test_omitting_the_context_sizes_at_the_models_native_length(monkeypatch, tmp_path):
+ """The new shape: no n_ctx. The response says which length it used."""
+ gguf = _gguf(tmp_path)
+ native = _call(monkeypatch, gguf, n_ctx = None)
+ assert native["n_ctx"] == 8192
+ assert native["native_context"] == 8192
+ explicit = _call(monkeypatch, gguf, n_ctx = 8192)
+ assert native["kv_bytes"] == explicit["kv_bytes"]
+
+
+def test_the_failure_answer_carries_every_key(monkeypatch):
+ """A row that cannot be sized still has to be readable by both clients,
+ rather than arriving as a short dict that KeyErrors in the caller."""
+ monkeypatch.setattr(models_routes, "_resolve_quant_gguf", lambda *_a, **_k: (None, 0))
+ out = _call(monkeypatch, None)
+ assert _LEGACY_KEYS <= set(out)
+ assert {"spec_bytes", "n_ctx", "projector_bytes", "spec_unpriced"} <= set(out)
+ # Every byte figure is absent. spec_unpriced is a flag, not a measurement:
+ # False is its correct value here, since nothing was left unpriced.
+ assert all(v is None for k, v in out.items() if k != "spec_unpriced")
+ assert out["spec_unpriced"] is False
+
+
+def test_speculative_modes_that_cost_nothing_report_none(monkeypatch, tmp_path):
+ gguf = _gguf(tmp_path)
+ for mode in (None, "", "off", "ngram"):
+ out = _call(monkeypatch, gguf, speculative_type = mode)
+ assert out["spec_bytes"] is None, f"{mode!r} reserved memory"
diff --git a/studio/backend/tests/test_kv_cache_estimate_off_event_loop.py b/studio/backend/tests/test_kv_cache_estimate_off_event_loop.py
new file mode 100644
index 00000000000..c50c30e08a6
--- /dev/null
+++ b/studio/backend/tests/test_kv_cache_estimate_off_event_loop.py
@@ -0,0 +1,89 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+"""GET /kv-cache-estimate must not block the event loop.
+
+The route reads a GGUF header, walks every HF cache root in _resolve_quant_gguf,
+looks for a drafter and probes the llama-server binary. All of that is blocking
+disk work, and the memory bar calls it once per visible row, so a long model list
+ran it many times over. Doing that inside the coroutine stalls everything else
+the process is serving, streamed chat tokens included.
+
+Mirrors test_scan_loras_off_event_loop.py.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import sys
+import time
+from pathlib import Path
+
+_TESTS_DIR = str(Path(__file__).resolve().parent)
+if _TESTS_DIR not in sys.path:
+ sys.path.insert(0, _TESTS_DIR)
+
+# Installs the process-wide loggers/structlog/httpx stubs, so this module can be
+# run on its own rather than only after something else has imported them.
+import test_kv_cache_estimation # noqa: F401,E402
+
+import routes.models as models_routes # noqa: E402
+
+
+def test_the_estimate_does_not_stall_other_requests(monkeypatch, tmp_path):
+ """A heartbeat coroutine keeps ticking while a deliberately slow resolve runs.
+
+ On the unfixed route the sleep happens inside the coroutine, so the heartbeat
+ gets no turn at all between the call and its return.
+ """
+ resolve_seconds = 0.3
+ heartbeat_seconds = 0.01
+
+ def _slow_resolve(repo_id: str, quant: str, is_local: bool):
+ time.sleep(resolve_seconds)
+ return None, 0 # no path -> the handler returns its null answer
+
+ monkeypatch.setattr(models_routes, "_resolve_quant_gguf", _slow_resolve)
+
+ ticks: list[float] = []
+ during: list[int] = []
+
+ async def _drive():
+ stop = False
+
+ async def heartbeat():
+ while not stop:
+ ticks.append(time.perf_counter())
+ await asyncio.sleep(heartbeat_seconds)
+
+ beat = asyncio.create_task(heartbeat())
+ await asyncio.sleep(heartbeat_seconds * 5)
+ # Ticks recorded strictly between the call and its return: a gap measured
+ # over the whole list cannot separate the two versions, because the stall
+ # leaves no gap in the list at all.
+ before = len(ticks)
+ result = await models_routes.get_kv_cache_estimate(
+ repo_id = "org/repo",
+ quant = "Q4_K_M",
+ n_ctx = 4096,
+ cache_type_kv = None,
+ n_parallel = 1,
+ speculative_type = None,
+ request = None,
+ current_subject = "test-user",
+ )
+ during.append(len(ticks) - before)
+ # The answer still has to be the route's, not a coroutine object.
+ assert result["kv_bytes"] is None
+ stop = True
+ beat.cancel()
+ try:
+ await beat
+ except asyncio.CancelledError:
+ pass
+
+ asyncio.run(_drive())
+
+ # A loaded runner lands well below the ~30 an idle one records; blocking
+ # records exactly 0, so the floor is loose and still separates the two.
+ assert during[0] >= 3, f"heartbeat ran {during[0]} times during a {resolve_seconds}s estimate"
diff --git a/studio/backend/tests/test_kv_cache_estimate_route.py b/studio/backend/tests/test_kv_cache_estimate_route.py
new file mode 100644
index 00000000000..78616f33a9e
--- /dev/null
+++ b/studio/backend/tests/test_kv_cache_estimate_route.py
@@ -0,0 +1,865 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+"""Route-level tests for ``GET /kv-cache-estimate``.
+
+The estimate is only worth showing if it describes the load llama-server will
+actually perform, so these drive the real handler and the real drafter resolver
+rather than a replayed copy of their logic.
+
+Two classes of defect are covered:
+
+* The MTP reserve must follow the loader's own ``is_mtp_model`` precondition. A
+ model with no embedded head, no MTP name and no separate drafter cannot run
+ MTP, so the loader emits ``--spec-default`` and reserves nothing. Because
+ ``_estimate_mtp_overhead_bytes`` defaults ``mtp_keeps_target_ctx=True`` (so an
+ unsure caller over-reserves), skipping that precondition billed every MLA
+ model a second full f16 copy of its own KV.
+
+* Drafter discovery must resolve the same file ``_download_mtp`` opens, on every
+ platform. The estimate runs on hosts whose filesystems disagree about case and
+ whose ``Path`` ordering differs, and it is reached for both HF snapshots and
+ plain local folders.
+
+No GPU, no network. Cross-platform: the layout cases below construct real
+directories under ``tmp_path`` and assert against the loader's own picker.
+"""
+
+import asyncio
+import sys
+from pathlib import Path
+
+import pytest
+
+_TESTS_DIR = str(Path(__file__).resolve().parent)
+if _TESTS_DIR not in sys.path:
+ sys.path.insert(0, _TESTS_DIR)
+
+_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)
+if _BACKEND_DIR not in sys.path:
+ sys.path.insert(0, _BACKEND_DIR)
+
+# Installs the process-wide loggers/structlog/httpx stubs and the GGUF builder.
+from test_kv_cache_estimation import _backend_from_gguf, _make_gguf_bytes # noqa: E402
+
+import routes.models as models_routes # noqa: E402
+from core.inference.llama_cpp import _pick_mtp # noqa: E402
+
+# The platform keys the repo already parametrises over elsewhere
+# (test_diffusion_predownload_guard_platforms.py).
+PLATFORMS = ("linux", "wsl", "win32", "darwin")
+
+# MLA (kv_lora_rank set) with NO MTP head: no nextn_predict_layers. This is the
+# shape that was charged a duplicate KV.
+_MLA_NO_HEAD = {
+ "context_length": 131072,
+ "block_count": 62,
+ "attention.head_count": 32,
+ "attention.head_count_kv": 16,
+ "embedding_length": 5376,
+ "attention.key_length": 128,
+ "attention.value_length": 128,
+ "attention.kv_lora_rank": 512,
+ "attention.key_length_mla": 256,
+}
+
+
+# An ordinary GQA model with nothing special about it, for asserting that the
+# shared machinery ran at all.
+_PLAIN_GQA = {
+ "context_length": 32768,
+ "block_count": 32,
+ "attention.head_count": 32,
+ "attention.head_count_kv": 8,
+ "embedding_length": 4096,
+ "attention.key_length": 128,
+ "attention.value_length": 128,
+}
+
+# A sliding-window model, which is the only shape where --ctx-checkpoints costs
+# anything: each checkpoint is an SWA snapshot per slot.
+_SWA_MODEL = {
+ "context_length": 131072,
+ "block_count": 32,
+ "attention.head_count": 32,
+ "attention.head_count_kv": 8,
+ "embedding_length": 4096,
+ "attention.key_length": 128,
+ "attention.value_length": 128,
+ "attention.sliding_window": 4096,
+ "attention.sliding_window_pattern": 6,
+}
+
+
+def _write_gguf(
+ path: Path,
+ fields: dict,
+ arch: str = "testarch",
+) -> Path:
+ kv = {"general.architecture": arch}
+ for k, v in fields.items():
+ kv[f"{arch}.{k}"] = v
+ path.parent.mkdir(parents = True, exist_ok = True)
+ path.write_bytes(_make_gguf_bytes(arch, kv))
+ return path
+
+
+def _call_route(
+ monkeypatch,
+ *,
+ path: Path,
+ weights_bytes: int,
+ repo_id: str,
+ speculative_type: str | None,
+ mtp_token: bool = True,
+ is_local: bool = False,
+ n_parallel: int = 1,
+ spec_draft_n_max: int | None = None,
+ ctx_checkpoints: int | None = None,
+ disable_vision: bool = False,
+ n_ctx: int | None = 32768,
+):
+ """Drive the real handler with the quant already resolved to *path*."""
+ monkeypatch.setattr(
+ models_routes,
+ "_resolve_quant_gguf",
+ lambda _repo, _quant, _local: (str(path), weights_bytes),
+ )
+ monkeypatch.setattr(models_routes, "is_local_path", lambda _p: is_local, raising = False)
+ from core.inference.llama_cpp import LlamaCppBackend
+
+ monkeypatch.setattr(
+ LlamaCppBackend,
+ "probe_server_capabilities",
+ classmethod(lambda cls, *a, **k: {"mtp_token": mtp_token}),
+ )
+ return asyncio.run(
+ models_routes.get_kv_cache_estimate(
+ repo_id = repo_id,
+ quant = "Q4_K_M",
+ n_ctx = n_ctx,
+ cache_type_kv = None,
+ n_parallel = n_parallel,
+ speculative_type = speculative_type,
+ spec_draft_n_max = spec_draft_n_max,
+ spec_draft_cache_type = None,
+ ctx_checkpoints = ctx_checkpoints,
+ disable_vision = disable_vision,
+ n_batch = None,
+ n_ubatch = None,
+ tensor_parallel = False,
+ request = None,
+ current_subject = "test",
+ )
+ )
+
+
+class TestMtpReserveFollowsTheLoader:
+ """The reserve is charged only when the loader could run MTP."""
+
+ @pytest.mark.parametrize("mode", ["mtp", "auto", "mtp+ngram"])
+ def test_headless_mla_is_not_charged_a_duplicate_kv(self, monkeypatch, tmp_path, mode):
+ gguf = _write_gguf(tmp_path / "plain-model-Q4_K_M.gguf", _MLA_NO_HEAD)
+ out = _call_route(
+ monkeypatch,
+ path = gguf,
+ weights_bytes = 4096,
+ repo_id = "org/plain-model",
+ speculative_type = mode,
+ )
+ # The KV itself must still be reported; only the reserve goes away.
+ assert out["kv_bytes"] and out["kv_bytes"] > 0
+ assert out["spec_bytes"] is None, (
+ f"{mode}: a model with no head, no MTP name and no drafter was charged "
+ f"{out['spec_bytes']} bytes; the loader reserves nothing for it"
+ )
+
+ def test_embedded_head_is_still_charged(self, monkeypatch, tmp_path):
+ """The gate must not suppress a model that genuinely runs MTP."""
+ fields = dict(_MLA_NO_HEAD)
+ fields["nextn_predict_layers"] = 1
+ gguf = _write_gguf(tmp_path / "headed-Q4_K_M.gguf", fields)
+ out = _call_route(
+ monkeypatch,
+ path = gguf,
+ weights_bytes = 4096,
+ repo_id = "org/headed",
+ speculative_type = "mtp",
+ )
+ assert out["spec_bytes"] and out["spec_bytes"] > 0
+
+ def test_ngram_costs_nothing(self, monkeypatch, tmp_path):
+ """ngram drafts from generated text, so it holds no VRAM."""
+ gguf = _write_gguf(tmp_path / "plain-Q4_K_M.gguf", _MLA_NO_HEAD)
+ out = _call_route(
+ monkeypatch,
+ path = gguf,
+ weights_bytes = 4096,
+ repo_id = "org/plain",
+ speculative_type = "ngram",
+ )
+ assert out["spec_bytes"] is None
+
+ def test_binary_without_mtp_support_reserves_nothing(self, monkeypatch, tmp_path):
+ fields = dict(_MLA_NO_HEAD)
+ fields["nextn_predict_layers"] = 1
+ gguf = _write_gguf(tmp_path / "headed-Q4_K_M.gguf", fields)
+ out = _call_route(
+ monkeypatch,
+ path = gguf,
+ weights_bytes = 4096,
+ repo_id = "org/headed",
+ speculative_type = "mtp",
+ mtp_token = False,
+ )
+ assert out["spec_bytes"] is None
+
+
+class TestDrafterDiscoveryMatchesTheLoader:
+ """_resolve_mtp_drafter must name the file _pick_mtp names."""
+
+ @staticmethod
+ def _snapshot(tmp_path: Path) -> Path:
+ """An HF cache snapshot, the layout _companion_snapshot_sibling expects."""
+ snap = tmp_path / "models--org--repo" / "snapshots" / ("a" * 40)
+ snap.mkdir(parents = True)
+ return snap
+
+ def test_finds_root_companion_when_weights_are_in_a_quant_subdir(self, tmp_path):
+ snap = self._snapshot(tmp_path)
+ main = _write_gguf(snap / "BF16" / "model.gguf", _MLA_NO_HEAD)
+ companion = _write_gguf(snap / "mtp-model.gguf", _MLA_NO_HEAD)
+
+ got, size = models_routes._resolve_mtp_drafter(str(main))
+ assert got == str(companion), (
+ "the loader fetches the snapshot-root companion; an estimate that "
+ "misses it prices the reserve at 0"
+ )
+ assert size == companion.stat().st_size
+
+ def test_a_directory_named_mtp_does_not_make_every_sibling_a_drafter(self, tmp_path):
+ """_drafter_path_kind matches ancestor segments; _pick_mtp does not."""
+ root = tmp_path / "mtp"
+ main = _write_gguf(root / "model-Q4_K_M.gguf", _MLA_NO_HEAD)
+ _write_gguf(root / "another-model-Q8_0.gguf", _MLA_NO_HEAD)
+
+ got, size = models_routes._resolve_mtp_drafter(str(main), search_root = str(root))
+ assert got is None, f"billed an unrelated sibling as a drafter: {got} ({size} bytes)"
+
+ def test_the_main_weight_is_never_its_own_drafter(self, tmp_path):
+ root = tmp_path / "mtp"
+ main = _write_gguf(root / "model-Q4_K_M.gguf", _MLA_NO_HEAD)
+ got, _ = models_routes._resolve_mtp_drafter(str(main), search_root = str(root))
+ assert got != str(main)
+
+ def test_nested_mtp_subdir_copies_are_skipped(self, tmp_path):
+ """MTP/ copies are explicit-selection; the loader does not auto-fetch them."""
+ snap = self._snapshot(tmp_path)
+ main = _write_gguf(snap / "model-Q4_K_M.gguf", _MLA_NO_HEAD)
+ _write_gguf(snap / "MTP" / "mtp-model-Q8_0.gguf", _MLA_NO_HEAD)
+
+ got, _ = models_routes._resolve_mtp_drafter(str(main))
+ assert got is None
+
+ def test_root_companion_wins_over_a_nested_copy(self, tmp_path):
+ snap = self._snapshot(tmp_path)
+ main = _write_gguf(snap / "model-Q4_K_M.gguf", _MLA_NO_HEAD)
+ root_companion = _write_gguf(snap / "mtp-model.gguf", _MLA_NO_HEAD)
+ _write_gguf(snap / "MTP" / "mtp-model-Q8_0.gguf", _MLA_NO_HEAD)
+
+ got, _ = models_routes._resolve_mtp_drafter(str(main))
+ assert got == str(root_companion)
+
+ def test_appledouble_shadow_is_not_billed(self, tmp_path):
+ """macOS/exFAT/SMB write "._name" metadata beside every file."""
+ snap = self._snapshot(tmp_path)
+ main = _write_gguf(snap / "model-Q4_K_M.gguf", _MLA_NO_HEAD)
+ real = _write_gguf(snap / "mtp-model.gguf", _MLA_NO_HEAD)
+ # Sorts ahead of "mtp-model.gguf" on a plain byte sort.
+ (snap / "._mtp-model.gguf").write_bytes(b"\x00\x05\x16\x07" + b"x" * 4000)
+
+ got, _ = models_routes._resolve_mtp_drafter(str(main))
+ assert got == str(real), f"AppleDouble shadow billed as the drafter: {got}"
+
+ def test_uppercase_extension_is_recognised(self, tmp_path):
+ """Case-insensitive filesystems (Windows, APFS) can hand back .GGUF."""
+ assert _pick_mtp(["MTP-Model.GGUF"]) == "MTP-Model.GGUF"
+
+ def test_picker_ordering_is_platform_independent(self):
+ """sorted() over Path is case-folded on Windows and not on POSIX;
+ _pick_mtp sorts relative strings, so every host agrees."""
+ listing = ["mtp-b.gguf", "MTP-a.gguf", "model.gguf"]
+ assert _pick_mtp(listing) == _pick_mtp(list(reversed(listing)))
+
+ @pytest.mark.parametrize("platform", PLATFORMS)
+ def test_resolution_is_stable_across_platforms(self, monkeypatch, tmp_path, platform):
+ monkeypatch.setattr(sys, "platform", platform)
+ snap = self._snapshot(tmp_path)
+ main = _write_gguf(snap / "BF16" / "model.gguf", _MLA_NO_HEAD)
+ companion = _write_gguf(snap / "mtp-model.gguf", _MLA_NO_HEAD)
+
+ got, _ = models_routes._resolve_mtp_drafter(str(main))
+ assert got == str(companion)
+
+ def test_broken_symlink_is_skipped_not_billed(self, tmp_path):
+ """HF snapshots are symlinks into blobs/; an interrupted download dangles."""
+ snap = self._snapshot(tmp_path)
+ main = _write_gguf(snap / "model-Q4_K_M.gguf", _MLA_NO_HEAD)
+ (snap / "mtp-model.gguf").symlink_to(snap / "blobs" / "missing")
+
+ got, size = models_routes._resolve_mtp_drafter(str(main))
+ assert (got, size) == (None, 0)
+
+ def test_live_symlink_reports_the_target_size(self, tmp_path):
+ """The real HF cache layout: snapshot entry -> blob."""
+ snap = self._snapshot(tmp_path)
+ blobs = snap.parent.parent / "blobs"
+ blobs.mkdir(parents = True)
+ blob = _write_gguf(blobs / "deadbeef", _MLA_NO_HEAD)
+ main = _write_gguf(snap / "model-Q4_K_M.gguf", _MLA_NO_HEAD)
+ (snap / "mtp-model.gguf").symlink_to(blob)
+
+ got, size = models_routes._resolve_mtp_drafter(str(main))
+ assert got == str(snap / "mtp-model.gguf")
+ assert size == blob.stat().st_size, "must follow the link to the blob"
+
+ def test_missing_directory_is_survivable(self, tmp_path):
+ got, size = models_routes._resolve_mtp_drafter(str(tmp_path / "gone" / "x.gguf"))
+ assert (got, size) == (None, 0)
+
+
+if __name__ == "__main__":
+ sys.exit(pytest.main([__file__, "-v", "-s"]))
+
+
+class TestTheEstimateMatchesTheConfiguredLoad:
+ """Settings a user can save must reach the estimator that prices them.
+
+ Each of these is a term the load planner forwards and this route did not, so
+ the bar reported a comfortable fit for a launch that reserves more.
+ """
+
+ def test_saved_context_checkpoints_are_priced(self, monkeypatch, tmp_path):
+ """Each checkpoint is an SWA snapshot per slot, so this is not small."""
+ fields = {
+ "context_length": 131072,
+ "block_count": 48,
+ "attention.head_count": 32,
+ "attention.head_count_kv": 8,
+ "embedding_length": 4096,
+ "attention.key_length": 128,
+ "attention.value_length": 128,
+ "attention.sliding_window": 4096,
+ "attention.sliding_window_pattern": [True, True, True, False],
+ }
+ gguf = _write_gguf(tmp_path / "swa-Q4_K_M.gguf", fields)
+ none = _call_route(
+ monkeypatch,
+ path = gguf,
+ weights_bytes = 4096,
+ repo_id = "org/swa",
+ speculative_type = None,
+ n_parallel = 4,
+ )
+ many = _call_route(
+ monkeypatch,
+ path = gguf,
+ weights_bytes = 4096,
+ repo_id = "org/swa",
+ speculative_type = None,
+ n_parallel = 4,
+ ctx_checkpoints = 32,
+ )
+ assert (
+ many["kv_bytes"] > none["kv_bytes"]
+ ), "saved ctx_checkpoints did not reach the KV estimator"
+
+ def test_draft_depth_is_priced_on_a_hybrid_mamba_target(self, monkeypatch, tmp_path):
+ """The rollback copies dominate the reserve; the zero default omits them."""
+ fields = {
+ "context_length": 131072,
+ "block_count": 48,
+ "attention.head_count": 32,
+ "attention.head_count_kv": 8,
+ "embedding_length": 4096,
+ "attention.key_length": 128,
+ "attention.value_length": 128,
+ "ssm.inner_size": 6144,
+ "ssm.state_size": 128,
+ "ssm.group_count": 16,
+ "ssm.conv_kernel": 4,
+ "full_attention_interval": 4,
+ "nextn_predict_layers": 1,
+ }
+ gguf = _write_gguf(tmp_path / "mamba-Q4_K_M.gguf", fields)
+
+ def at(depth):
+ return _call_route(
+ monkeypatch,
+ path = gguf,
+ weights_bytes = 4096,
+ repo_id = "org/mamba",
+ speculative_type = "mtp",
+ n_parallel = 4,
+ spec_draft_n_max = depth,
+ )
+
+ none = at(None)
+ zero = at(0)
+ deep = at(16)
+ assert (
+ deep["spec_bytes"] > zero["spec_bytes"] * 10
+ ), "spec_draft_n_max did not reach the MTP estimator"
+ # A blank field is NOT zero: _build_speculative_flags emits its own
+ # default (2 with a GPU, 3 without) and the rollback state is multiplied
+ # by it, so pricing an unset field as zero dropped the dominant
+ # allocation on this exact model shape. An explicit zero still means
+ # zero, which is what separates the two calls below.
+ assert (
+ none["spec_bytes"] > zero["spec_bytes"]
+ ), "an unset draft depth was priced as zero, dropping every rollback copy"
+ assert (
+ none["spec_bytes"] < deep["spec_bytes"]
+ ), "the default depth should sit between drafting nothing and a depth of 16"
+
+ def test_a_split_drafter_is_billed_for_every_shard(self, tmp_path):
+ snap = TestDrafterDiscoveryMatchesTheLoader._snapshot(tmp_path)
+ _write_gguf(snap / "model-Q4_K_M.gguf", _MLA_NO_HEAD)
+ # A two-shard companion. llama-server opens shard 1 and reserves both.
+ one = snap / "mtp-model-00001-of-00002.gguf"
+ two = snap / "mtp-model-00002-of-00002.gguf"
+ _write_gguf(one, _MLA_NO_HEAD)
+ two.write_bytes(b"\x00" * 500_000)
+
+ got, size = models_routes._resolve_mtp_drafter(str(snap / "model-Q4_K_M.gguf"))
+ assert got == str(one), "llama-server is handed shard 1"
+ assert (
+ size >= one.stat().st_size + two.stat().st_size
+ ), f"billed {size} bytes, which is shard 1 alone rather than the family"
+
+ def test_a_dspark_or_dflash_mode_reports_its_reserve_unpriced(self, monkeypatch, tmp_path):
+ """Rather than a fit that omits the launch's largest allocation."""
+ gguf = _write_gguf(tmp_path / "plain-Q4_K_M.gguf", _MLA_NO_HEAD)
+ for mode in ("dspark", "dflash"):
+ out = _call_route(
+ monkeypatch,
+ path = gguf,
+ weights_bytes = 4096,
+ repo_id = "org/plain",
+ speculative_type = mode,
+ )
+ assert out["spec_unpriced"] is True, f"{mode} claimed to be priced"
+ assert out["spec_bytes"] is None
+
+ def test_a_priceable_mode_is_not_marked_unpriced(self, monkeypatch, tmp_path):
+ gguf = _write_gguf(tmp_path / "plain-Q4_K_M.gguf", _MLA_NO_HEAD)
+ for mode in (None, "ngram", "mtp", "auto"):
+ out = _call_route(
+ monkeypatch,
+ path = gguf,
+ weights_bytes = 4096,
+ repo_id = "org/plain",
+ speculative_type = mode,
+ )
+ assert out["spec_unpriced"] is False, f"{mode} wrongly marked unpriced"
+
+ def test_the_vision_projector_is_charged_unless_vision_is_off(self, monkeypatch, tmp_path):
+ gguf = _write_gguf(tmp_path / "vision-Q4_K_M.gguf", _MLA_NO_HEAD)
+ mmproj = tmp_path / "mmproj-F16.gguf"
+ mmproj.write_bytes(b"\x00" * 800_000)
+
+ on = _call_route(
+ monkeypatch,
+ path = gguf,
+ weights_bytes = 4096,
+ repo_id = str(tmp_path),
+ speculative_type = None,
+ is_local = True,
+ )
+ assert (
+ on["projector_bytes"] and on["projector_bytes"] > mmproj.stat().st_size
+ ), "the projector is charged above its file size (_MMPROJ_VRAM_SAFETY)"
+
+ off = _call_route(
+ monkeypatch,
+ path = gguf,
+ weights_bytes = 4096,
+ repo_id = str(tmp_path),
+ speculative_type = None,
+ is_local = True,
+ disable_vision = True,
+ )
+ assert off["projector_bytes"] is None, "vision off must free the projector"
+
+ def test_a_model_with_no_projector_reports_none(self, monkeypatch, tmp_path):
+ gguf = _write_gguf(tmp_path / "text-Q4_K_M.gguf", _MLA_NO_HEAD)
+ out = _call_route(
+ monkeypatch,
+ path = gguf,
+ weights_bytes = 4096,
+ repo_id = str(tmp_path),
+ speculative_type = None,
+ is_local = True,
+ )
+ assert out["projector_bytes"] is None
+
+
+class TestHostMemoryIsNotChargedToTheCard:
+ """Context checkpoints live in host heap, so a VRAM bar must be able to
+ exclude them. The load planner's own GPU figure is
+ ``kv_bytes - kv_checkpoint_bytes``; without the second term reported the bar
+ warns OOM over memory that never reaches the GPU."""
+
+ def test_checkpoints_are_reported_as_their_own_share(self, monkeypatch, tmp_path):
+ gguf = _write_gguf(tmp_path / "swa-model-Q4_K_M.gguf", _SWA_MODEL)
+ with_checkpoints = _call_route(
+ monkeypatch,
+ path = gguf,
+ weights_bytes = 4096,
+ repo_id = "org/swa",
+ speculative_type = None,
+ ctx_checkpoints = 8,
+ )
+ without = _call_route(
+ monkeypatch,
+ path = gguf,
+ weights_bytes = 4096,
+ repo_id = "org/swa",
+ speculative_type = None,
+ ctx_checkpoints = 0,
+ )
+ share = with_checkpoints["kv_checkpoint_bytes"]
+ assert share, "checkpoints were requested but no host share was reported"
+ # By difference against the same call with none, which is how the load
+ # planner derives it -- asking one function twice cannot drift from it.
+ assert share == with_checkpoints["kv_bytes"] - without["kv_bytes"]
+ # And it is a SHARE of kv_bytes, not a figure beside it: the field
+ # shipped meaning the whole cache and an existing caller still reads it
+ # that way.
+ assert share < with_checkpoints["kv_bytes"]
+
+ def test_no_checkpoints_means_no_host_share(self, monkeypatch, tmp_path):
+ gguf = _write_gguf(tmp_path / "swa-model-Q4_K_M.gguf", _SWA_MODEL)
+ out = _call_route(
+ monkeypatch,
+ path = gguf,
+ weights_bytes = 4096,
+ repo_id = "org/swa",
+ speculative_type = None,
+ ctx_checkpoints = None,
+ )
+ assert out["kv_checkpoint_bytes"] is None
+
+
+class TestAutoAbstainsOverASidecar:
+ """Auto promotes to DSpark or DFlash when the model ships one, so the route
+ must say the reserve is unpriced rather than chart a total without it.
+
+ These assert the OUTCOME, not that the block runs: the first version of this
+ guard referenced two helpers that were only in another function's scope, and
+ the resulting NameError was swallowed by the surrounding except, leaving
+ spec_unpriced false with nothing in the response to show it had failed.
+ """
+
+ def _call(self, monkeypatch, tmp_path, *, sidecar: str | None, supports: bool):
+ model_dir = tmp_path / "local-model"
+ gguf = _write_gguf(model_dir / "model-Q4_K_M.gguf", _MLA_NO_HEAD)
+ if sidecar:
+ # A DFlash sidecar is identified by its header, not its name:
+ # detect_dflash_file confirms general.architecture = dflash, which
+ # settles the adversarial case of a real model merely CALLED DFlash.
+ _write_gguf(
+ model_dir / sidecar,
+ _MLA_NO_HEAD,
+ arch = "dflash" if sidecar.startswith("dflash") else "testarch",
+ )
+ from core.inference.llama_cpp import LlamaCppBackend
+
+ monkeypatch.setattr(
+ LlamaCppBackend,
+ "probe_server_capabilities",
+ classmethod(
+ lambda cls, *a, **k: {
+ "mtp_token": True,
+ "supports_dspark": supports,
+ "supports_dflash": supports,
+ }
+ ),
+ )
+ monkeypatch.setattr(
+ models_routes,
+ "_resolve_quant_gguf",
+ lambda _repo, _quant, _local: (str(gguf), 4096),
+ )
+ monkeypatch.setattr(models_routes, "is_local_path", lambda _p: True, raising = False)
+ return asyncio.run(
+ models_routes.get_kv_cache_estimate(
+ repo_id = str(model_dir),
+ quant = "Q4_K_M",
+ n_ctx = 32768,
+ cache_type_kv = None,
+ n_parallel = 1,
+ speculative_type = "auto",
+ spec_draft_n_max = None,
+ spec_draft_cache_type = None,
+ ctx_checkpoints = None,
+ disable_vision = False,
+ n_batch = None,
+ n_ubatch = None,
+ tensor_parallel = False,
+ request = None,
+ current_subject = "test",
+ )
+ )
+
+ @pytest.mark.parametrize("sidecar", ["dspark-model-Q8_0.gguf", "dflash-model-Q8_0.gguf"])
+ def test_a_local_sidecar_makes_the_reserve_unpriced(self, monkeypatch, tmp_path, sidecar):
+ out = self._call(monkeypatch, tmp_path, sidecar = sidecar, supports = True)
+ assert out["spec_unpriced"] is True, (
+ "Auto charted a total with the sidecar missing; a DSpark drafter is "
+ "about 11 GB, so this is the largest single allocation the route can drop"
+ )
+
+ def test_no_sidecar_leaves_the_estimate_priced(self, monkeypatch, tmp_path):
+ out = self._call(monkeypatch, tmp_path, sidecar = None, supports = True)
+ assert out["spec_unpriced"] is False
+
+ def test_a_binary_that_cannot_run_one_still_prices_normally(self, monkeypatch, tmp_path):
+ # The planner gates sidecar selection on the binary's own capability, so
+ # abstaining where the launch would never open one blanks the bar for
+ # nothing.
+ out = self._call(monkeypatch, tmp_path, sidecar = "dspark-model-Q8_0.gguf", supports = False)
+ assert out["spec_unpriced"] is False
+
+
+class TestThePlannerFiguresArrive:
+ """The route delegates to the load planner for the terms it cannot derive
+ itself, inside a try/except so a planner that cannot size a model still
+ leaves the KV bar drawn.
+
+ That except is the hazard: every earlier version of this delegation failed
+ into it silently and returned nulls that looked like "not sizeable" rather
+ than "the call is broken". These assert the figures are actually present for
+ a model the planner can size, so a signature drift or an unresolved
+ parameter fails the suite instead of quietly blanking the bar.
+ """
+
+ def test_the_planner_terms_are_populated(self, monkeypatch, tmp_path):
+ model_dir = tmp_path / "planner-model"
+ gguf = _write_gguf(model_dir / "model-Q4_K_M.gguf", _PLAIN_GQA)
+ monkeypatch.setattr(
+ models_routes,
+ "_resolve_quant_gguf",
+ lambda _repo, _quant, _local: (str(gguf), 4_000_000_000),
+ )
+ monkeypatch.setattr(models_routes, "is_local_path", lambda _p: True, raising = False)
+ out = asyncio.run(
+ models_routes.get_kv_cache_estimate(
+ repo_id = str(model_dir),
+ quant = "Q4_K_M",
+ n_ctx = 8192,
+ cache_type_kv = None,
+ n_parallel = 1,
+ speculative_type = None,
+ spec_draft_n_max = None,
+ spec_draft_cache_type = None,
+ ctx_checkpoints = None,
+ disable_vision = False,
+ n_batch = None,
+ n_ubatch = None,
+ tensor_parallel = False,
+ request = None,
+ current_subject = "test",
+ )
+ )
+ assert out["compute_bytes"], (
+ "the planner delegation failed into its except; every launch reserves "
+ "compute buffers, so a null here means the call broke rather than that "
+ "the model has none"
+ )
+ assert out["gpu_bytes"], "no authoritative GPU total"
+ assert out["gpu_floor_bytes"], "no irreducible floor"
+ # The floor is what survives shrinking the context, so it cannot exceed
+ # the full plan, and for a context-sensitive model it should be smaller.
+ assert out["gpu_floor_bytes"] <= out["gpu_bytes"]
+ assert out["gpu_floor_bytes"] < out["gpu_bytes"], (
+ "the floor equals the full plan, so the second pricing did not use a "
+ "shorter context and cannot separate reducible from fixed"
+ )
+
+
+class TestADirectGgufFileResolves:
+ """A custom or LM Studio entry whose path is the .gguf itself never goes
+ through variant selection, so there is no quant label to match. The file
+ names the weights on its own."""
+
+ def test_a_direct_file_is_its_own_resolution(self, tmp_path):
+ gguf = _write_gguf(tmp_path / "some-model-Q4_K_M.gguf", _PLAIN_GQA)
+ path, size = models_routes._resolve_quant_gguf(str(gguf), "", True)
+ assert path == str(gguf), "a direct file selection did not resolve to itself"
+ assert size == gguf.stat().st_size
+
+ def test_a_directory_still_takes_the_quant_scan(self, tmp_path):
+ # The direct-file branch must not swallow the ordinary case: a folder is
+ # still scanned for the quant that was asked for.
+ model_dir = tmp_path / "folder"
+ _write_gguf(model_dir / "model-Q4_K_M.gguf", _PLAIN_GQA)
+ path, size = models_routes._resolve_quant_gguf(str(model_dir), "Q4_K_M", True)
+ assert path and path.endswith("model-Q4_K_M.gguf")
+ assert size > 0
+ # And a quant it does not hold resolves to nothing rather than to
+ # whatever happened to be there.
+ missing, _ = models_routes._resolve_quant_gguf(str(model_dir), "Q2_K", True)
+ assert missing is None
+
+
+class TestTheInheritedEnvironmentIsPriced:
+ """Studio can be launched with llama.cpp's own environment variables set, and
+ the child inherits them. The estimate has to price what the child will run,
+ not what the request said."""
+
+ def test_an_inherited_context_beats_the_native_length(self, monkeypatch, tmp_path):
+ # load_model drops an inherited context only when it is zero, so a
+ # positive one is the legitimate way to set the window. Falling through
+ # to native priced a 4k load at the header's length.
+ gguf = _write_gguf(tmp_path / "model-Q4_K_M.gguf", _PLAIN_GQA)
+ monkeypatch.setenv("LLAMA_ARG_CTX_SIZE", "4096")
+ out = _call_route(
+ monkeypatch,
+ path = gguf,
+ weights_bytes = 4096,
+ repo_id = "org/repo",
+ speculative_type = None,
+ n_ctx = None,
+ )
+ assert out["n_ctx"] == 4096, (
+ "the estimate used the header's native window for a launch the "
+ "environment pins to 4096"
+ )
+ assert out["native_context"] == _PLAIN_GQA["context_length"]
+
+ def test_no_inherited_context_still_uses_native(self, monkeypatch, tmp_path):
+ gguf = _write_gguf(tmp_path / "model-Q4_K_M.gguf", _PLAIN_GQA)
+ monkeypatch.delenv("LLAMA_ARG_CTX_SIZE", raising = False)
+ out = _call_route(
+ monkeypatch,
+ path = gguf,
+ weights_bytes = 4096,
+ repo_id = "org/repo",
+ speculative_type = None,
+ n_ctx = None,
+ )
+ assert out["n_ctx"] == _PLAIN_GQA["context_length"]
+
+ def test_an_inherited_cache_type_sizes_the_cache(self, monkeypatch, tmp_path):
+ # A q8_0 cache is roughly half an f16 one. Pricing f16 while the child
+ # opens q8_0 makes the KV segment and the per-token readout contradict
+ # the planner total drawn beside them.
+ gguf = _write_gguf(tmp_path / "model-Q4_K_M.gguf", _PLAIN_GQA)
+ monkeypatch.delenv("LLAMA_ARG_CACHE_TYPE_K", raising = False)
+ monkeypatch.delenv("LLAMA_ARG_CACHE_TYPE_V", raising = False)
+ default = _call_route(
+ monkeypatch,
+ path = gguf,
+ weights_bytes = 4096,
+ repo_id = "org/repo",
+ speculative_type = None,
+ )
+ monkeypatch.setenv("LLAMA_ARG_CACHE_TYPE_K", "q8_0")
+ monkeypatch.setenv("LLAMA_ARG_CACHE_TYPE_V", "q8_0")
+ inherited = _call_route(
+ monkeypatch,
+ path = gguf,
+ weights_bytes = 4096,
+ repo_id = "org/repo",
+ speculative_type = None,
+ )
+ assert inherited["kv_bytes"] < default["kv_bytes"], (
+ "an inherited q8_0 cache was priced as f16, so the KV segment was "
+ "about twice the size the launch reserves"
+ )
+
+ def test_an_inherited_context_is_reported_as_pinned(self, monkeypatch, tmp_path):
+ # The loader keeps a positive inherited context rather than fitting it,
+ # so a caller must not soften its verdict for that launch. Saying
+ # "auto-fitted" there suppressed the overage AND drew only the
+ # irreducible floor, which is a comfortable fit for a load that OOMs.
+ gguf = _write_gguf(tmp_path / "model-Q4_K_M.gguf", _PLAIN_GQA)
+ monkeypatch.setenv("LLAMA_ARG_CTX_SIZE", "4096")
+ assert (
+ _call_route(
+ monkeypatch,
+ path = gguf,
+ weights_bytes = 4096,
+ repo_id = "org/repo",
+ speculative_type = None,
+ n_ctx = None,
+ )["context_is_pinned"]
+ is True
+ )
+
+ def test_an_omitted_context_with_no_inheritance_is_not_pinned(self, monkeypatch, tmp_path):
+ gguf = _write_gguf(tmp_path / "model-Q4_K_M.gguf", _PLAIN_GQA)
+ monkeypatch.delenv("LLAMA_ARG_CTX_SIZE", raising = False)
+ assert (
+ _call_route(
+ monkeypatch,
+ path = gguf,
+ weights_bytes = 4096,
+ repo_id = "org/repo",
+ speculative_type = None,
+ n_ctx = None,
+ )["context_is_pinned"]
+ is False
+ )
+
+ def test_an_explicit_context_is_pinned(self, monkeypatch, tmp_path):
+ gguf = _write_gguf(tmp_path / "model-Q4_K_M.gguf", _PLAIN_GQA)
+ monkeypatch.delenv("LLAMA_ARG_CTX_SIZE", raising = False)
+ assert (
+ _call_route(
+ monkeypatch,
+ path = gguf,
+ weights_bytes = 4096,
+ repo_id = "org/repo",
+ speculative_type = None,
+ n_ctx = 8192,
+ )["context_is_pinned"]
+ is True
+ )
+
+ def test_an_inherited_device_pin_is_reported(self, monkeypatch, tmp_path):
+ # The child is confined to the cards LLAMA_ARG_DEVICE names and an
+ # automatic launch preserves the pin, so an aggregate VRAM budget
+ # describes a pool the launch will not open. The caller cannot see the
+ # environment, so the route has to say.
+ gguf = _write_gguf(tmp_path / "model-Q4_K_M.gguf", _PLAIN_GQA)
+ monkeypatch.setenv("LLAMA_ARG_DEVICE", "CUDA0")
+ assert (
+ _call_route(
+ monkeypatch,
+ path = gguf,
+ weights_bytes = 4096,
+ repo_id = "org/repo",
+ speculative_type = None,
+ )["inherited_device_pin"]
+ is True
+ )
+
+ @pytest.mark.parametrize("value", ["", "none", "NONE"])
+ def test_no_usable_pin_is_not_reported_as_one(self, monkeypatch, tmp_path, value):
+ # "none" is a CPU-only launch, which the planner already answers with
+ # zero GPU bytes and which draws no bar on its own; reporting it as a pin
+ # would blank the row for a second, unrelated reason.
+ gguf = _write_gguf(tmp_path / "model-Q4_K_M.gguf", _PLAIN_GQA)
+ monkeypatch.setenv("LLAMA_ARG_DEVICE", value)
+ assert (
+ _call_route(
+ monkeypatch,
+ path = gguf,
+ weights_bytes = 4096,
+ repo_id = "org/repo",
+ speculative_type = None,
+ )["inherited_device_pin"]
+ is False
+ )
diff --git a/studio/backend/utils/hardware/hardware.py b/studio/backend/utils/hardware/hardware.py
index 18555413772..9bcdee7f72a 100644
--- a/studio/backend/utils/hardware/hardware.py
+++ b/studio/backend/utils/hardware/hardware.py
@@ -4672,6 +4672,13 @@ def get_backend_visible_gpu_info() -> Dict[str, Any]:
"memory_total_gb": td["total_gb"],
"shared_memory": bool(td.get("shared_memory")),
"shared_memory_host_backed_gb": td.get("shared_memory_host_backed_gb"),
+ # Surfaced from the inventory's own `_rocm_known_unified`
+ # rather than re-derived: a ROCm APU's total is the GTT pool,
+ # which moves with host usage and is not a VRAM ceiling a fit
+ # verdict can be measured against. Distinct from
+ # `shared_memory`, which is that flag AND Windows, so a Linux
+ # APU reads as not-shared while still having no such ceiling.
+ "unified_memory": bool(td.get("_rocm_known_unified")),
}
for td in torch_devices
]
diff --git a/studio/frontend/src/components/model-memory-bar.tsx b/studio/frontend/src/components/model-memory-bar.tsx
new file mode 100644
index 00000000000..2773e26cdbf
--- /dev/null
+++ b/studio/frontend/src/components/model-memory-bar.tsx
@@ -0,0 +1,232 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+/**
+ * VRAM bar for a downloaded model row: weights, then KV cache, then the MTP
+ * draft reserve.
+ *
+ * Deliberately shaped like the live monitor's meter -- same height, same track
+ * -- so "how full is my GPU" looks the same wherever it's asked. Colours come
+ * from the user's Appearance settings (`--primary`, `--foreground`), so it
+ * re-themes with everything else instead of pinning its own palette.
+ */
+
+import {
+ type ModelMemorySource,
+ useModelMemory,
+} from "@/hooks/use-model-memory";
+import { useT } from "@/i18n";
+import {
+ type ModelMemoryPressure,
+ type ModelMemorySegments,
+ formatKvRate,
+ formatMemoryGb,
+} from "@/lib/model-memory";
+import { cn } from "@/lib/utils";
+
+/**
+ * Self-sizing bar for one model. Use this inside a `.map()`, where calling the
+ * hook directly would break the rules of hooks. Renders nothing if the model
+ * can't be sized.
+ */
+export function ModelMemoryBarFor({
+ gpuGb,
+ showReadout,
+ compact,
+ className,
+ ...source
+}: ModelMemorySource & {
+ gpuGb?: number | null;
+ showReadout?: boolean;
+ compact?: boolean;
+ className?: string;
+}) {
+ const segments = useModelMemory(source, gpuGb);
+ if (segments.status === "unknown") return null;
+ return (
+ <ModelMemoryBar
+ segments={segments}
+ showReadout={showReadout}
+ compact={compact}
+ className={className}
+ />
+ );
+}
+
+/**
+ * Minimum width for a segment that isn't zero. On a 128 GB host a 0.7 GB KV
+ * cache works out to two pixels, which reads as "nothing here" rather than
+ * "small". Presentational only -- the percentages behind it stay exact.
+ */
+const MIN_SEGMENT_PX = 3;
+
+/**
+ * The MTP reserve is a darker shade of the accent rather than its own colour:
+ * it's a second set of weights, so it belongs visually with the weights segment
+ * while staying distinguishable from it.
+ */
+const SPEC_COLOR = "color-mix(in oklab, var(--primary) 62%, black)";
+
+/**
+ * Segment colours per pressure band. Below 80% the bar keeps the user's accent;
+ * above it the hue takes over to signal how tight things are. Each band keeps
+ * three distinguishable steps so the weights / KV / draft split survives.
+ */
+const SEGMENT_COLORS: Record<
+ ModelMemoryPressure,
+ { weights: string; kv: string; spec: string }
+> = {
+ normal: {
+ weights: "var(--primary)",
+ kv: "var(--foreground)",
+ spec: SPEC_COLOR,
+ },
+ high: {
+ weights: "var(--color-amber-500, #f59e0b)",
+ kv: "var(--color-amber-600, #d97706)",
+ spec: "var(--color-amber-800, #92400e)",
+ },
+ critical: {
+ weights: "var(--destructive)",
+ kv: "color-mix(in oklab, var(--destructive) 78%, black)",
+ spec: "color-mix(in oklab, var(--destructive) 55%, black)",
+ },
+};
+
+export function ModelMemoryBar({
+ segments,
+ showReadout = false,
+ compact = false,
+ className,
+}: {
+ segments: ModelMemorySegments;
+ /** Print the GB breakdown beside the bar. For roomy surfaces (the hub card),
+ * where a two-pixel segment alone cannot convey the numbers. */
+ showReadout?: boolean;
+ /** Dense-list styling: thinner, and held back until the numbers matter. A row
+ * in a scannable list should read as a row, not as a chart. */
+ compact?: boolean;
+ className?: string;
+}) {
+ const t = useT();
+ if (segments.status === "unknown") return null;
+
+ const {
+ modelPct,
+ kvPct,
+ specPct,
+ modelGb,
+ kvGb,
+ specGb,
+ totalGb,
+ budgetGb,
+ kvBytesPerToken,
+ pressure,
+ } = segments;
+ const colors = SEGMENT_COLORS[pressure];
+ // Two failures, two fixes: oversized weights need a smaller quant, while a
+ // total that only overflows with context needs a shorter context or a
+ // quantized KV cache. Both get said -- staying silent on the first reads as
+ // "this is fine" on a model that can't load at all.
+ const warning =
+ segments.status === "model-exceeds"
+ ? t("modelMemory.tooLarge")
+ : segments.status === "context-exceeds"
+ ? t("modelMemory.oomLikely")
+ : null;
+
+ const readout =
+ specGb > 0
+ ? t("modelMemory.readoutWithSpec", {
+ model: formatMemoryGb(modelGb),
+ kv: formatMemoryGb(kvGb),
+ spec: formatMemoryGb(specGb),
+ total: formatMemoryGb(totalGb),
+ budget: formatMemoryGb(budgetGb),
+ })
+ : t("modelMemory.readout", {
+ model: formatMemoryGb(modelGb),
+ context: formatMemoryGb(kvGb + specGb),
+ total: formatMemoryGb(totalGb),
+ budget: formatMemoryGb(budgetGb),
+ });
+
+ // llama.cpp reserves the whole KV cache up front -- 131072 context allocates
+ // 131072 cells before a token arrives -- so the bar charts the reservation.
+ // The rate is what says whether a shorter context would help.
+ const perTokenLine =
+ kvBytesPerToken > 0
+ ? t("modelMemory.kvRate", { rate: formatKvRate(kvBytesPerToken) })
+ : null;
+
+ return (
+ <div className={cn("mt-1 w-full", className)}>
+ {/* Decorative: the row already carries a Radix tooltip, so a native
+ `title` here would stack a second one on hover, and an aria-label on a
+ descendant would be concatenated into the row button's accessible
+ name. The numbers stay reachable through `showReadout`. */}
+ <div
+ aria-hidden="true"
+ className={cn(
+ "flex w-full overflow-hidden rounded-full bg-muted",
+ compact ? "h-[3px]" : "h-1.5",
+ // Comfortable fits recede; the bar gains presence as it fills.
+ compact && pressure === "normal" && "opacity-55",
+ )}
+ >
+ <div
+ data-testid="model-memory-weights"
+ className="h-full"
+ style={{
+ width: `${modelPct}%`,
+ minWidth: modelGb > 0 ? MIN_SEGMENT_PX : 0,
+ backgroundColor: colors.weights,
+ }}
+ />
+ <div
+ data-testid="model-memory-context"
+ className="h-full"
+ style={{
+ width: `${kvPct}%`,
+ minWidth: kvGb > 0 ? MIN_SEGMENT_PX : 0,
+ backgroundColor: colors.kv,
+ }}
+ />
+ <div
+ data-testid="model-memory-spec"
+ className="h-full"
+ style={{
+ width: `${specPct}%`,
+ minWidth: specGb > 0 ? MIN_SEGMENT_PX : 0,
+ backgroundColor: colors.spec,
+ }}
+ />
+ </div>
+ {showReadout ? (
+ <>
+ <p className="mt-1 text-ui-10 text-muted-foreground tabular-nums">
+ {readout}
+ </p>
+ {perTokenLine ? (
+ <p className="text-ui-10 text-muted-foreground/80 tabular-nums">
+ {perTokenLine}
+ </p>
+ ) : null}
+ </>
+ ) : null}
+ {warning ? (
+ <p
+ data-testid="model-memory-warning"
+ className={cn(
+ "mt-1 text-ui-11",
+ segments.status === "model-exceeds"
+ ? "text-rose-600 dark:text-rose-400"
+ : "text-amber-600 dark:text-amber-500",
+ )}
+ >
+ {warning}
+ </p>
+ ) : null}
+ </div>
+ );
+}
diff --git a/studio/frontend/src/features/chat/api/chat-api.ts b/studio/frontend/src/features/chat/api/chat-api.ts
index e56fa134c1b..aa879022f3a 100644
--- a/studio/frontend/src/features/chat/api/chat-api.ts
+++ b/studio/frontend/src/features/chat/api/chat-api.ts
@@ -1310,23 +1310,109 @@ export interface KvCacheEstimate {
kv_bytes: number | null;
weights_bytes: number | null;
native_context: number | null;
+ /** Extra MTP draft reserve; null for ngram or a model with no MTP head. */
+ spec_bytes: number | null;
+ /** Context the estimate was computed at, which is the native length when the
+ * request omitted one. */
+ n_ctx: number | null;
+ /** Vision projector footprint, at its worst-case VRAM multiple. Null when the
+ * model ships none or vision is disabled. */
+ projector_bytes: number | null;
+ /** True when the configured speculative mode attaches a drafter the route did
+ * not price (dspark/dflash, and Auto where it promotes to one). The total is
+ * then a floor, not an answer. */
+ spec_unpriced: boolean;
+ /** The share of kv_bytes llama.cpp keeps in HOST heap rather than on the card:
+ * the SWA checkpoint snapshots. Included in kv_bytes, so a VRAM figure has to
+ * subtract it; the planner's own GPU total does exactly that. */
+ kv_checkpoint_bytes: number | null;
+ /** The share of spec_bytes no shorter context can reduce, being the separate
+ * drafter's resident weights. Auto-fit softening must not cover it. */
+ spec_fixed_bytes: number | null;
+ /** The load planner's compute buffers, which every launch reserves on top of
+ * weights and cache. Scales with slots and micro-batch. */
+ compute_bytes: number | null;
+ /** The planner's complete GPU-resident figure, and its everything-total. */
+ gpu_bytes: number | null;
+ total_bytes: number | null;
+ /** What still lands on the card at the shortest context: the share no context
+ * reduction can recover. */
+ gpu_floor_bytes: number | null;
+ /** False only when the loader is free to shrink the context to fit. An
+ * inherited LLAMA_ARG_CTX_SIZE is kept, not fitted. */
+ context_is_pinned: boolean | null;
+ /** An inherited LLAMA_ARG_DEVICE confines the launch to the cards it names, so
+ * an aggregate VRAM budget describes a pool it will not open. */
+ inherited_device_pin: boolean | null;
+}
+
+export interface KvCacheEstimateOptions {
+ cacheTypeKv?: string | null;
+ /** --parallel slots; scales per-slot KV stream padding. */
+ nParallel?: number | null;
+ /** Speculative mode, so an MTP draft reserve is priced into the estimate. */
+ speculativeType?: string | null;
+ /** --spec-draft-n-max; a Hybrid Mamba target keeps one rollback state per
+ * drafted token, which dominates its reserve. */
+ specDraftNMax?: number | null;
+ /** Draft KV dtype, quantized independently of the main cache. */
+ specDraftCacheType?: string | null;
+ /** --ctx-checkpoints; each adds an SWA snapshot per slot. */
+ ctxCheckpoints?: number | null;
+ /** Batch and micro-batch size the compute buffers scale with. */
+ nBatch?: number | null;
+ nUbatch?: number | null;
+ /** Tensor mode replicates buffers on every device in the pool. */
+ tensorParallel?: boolean | null;
+ /** Vision off frees the projector, so it is not charged. */
+ disableVision?: boolean;
+ signal?: AbortSignal;
}
-/** Estimate KV cache + weight bytes for a downloaded quant at a context length,
- * for the load dialog's memory warning. */
+/** Estimate KV cache + weight + speculative bytes for a downloaded quant, for
+ * the load dialog's memory warning and the picker's memory bar. Omit `nCtx` to
+ * size against the model's own context length; the response says which was
+ * used. */
export async function estimateKvCache(
repoId: string,
quant: string,
- nCtx: number,
- cacheTypeKv?: string | null,
- signal?: AbortSignal,
+ nCtx?: number,
+ options: KvCacheEstimateOptions = {},
): Promise<KvCacheEstimate> {
- const params = new URLSearchParams({
- repo_id: repoId,
- quant,
- n_ctx: String(nCtx),
- });
+ const {
+ cacheTypeKv,
+ nParallel,
+ speculativeType,
+ specDraftNMax,
+ specDraftCacheType,
+ ctxCheckpoints,
+ nBatch,
+ nUbatch,
+ tensorParallel,
+ disableVision,
+ signal,
+ } = options;
+ const params = new URLSearchParams({ repo_id: repoId, quant });
+ if (nCtx && nCtx > 0) params.set("n_ctx", String(nCtx));
if (cacheTypeKv) params.set("cache_type_kv", cacheTypeKv);
+ // Any positive override goes, including 1: omitting it means "use the
+ // server's slot count", which now defaults to more than one.
+ if (nParallel && nParallel > 0) params.set("n_parallel", String(nParallel));
+ if (speculativeType) params.set("speculative_type", speculativeType);
+ // Zero is a real choice for both of these (no rollback states, no
+ // checkpoints), so they are sent whenever set rather than when truthy.
+ if (specDraftNMax != null && specDraftNMax >= 0)
+ params.set("spec_draft_n_max", String(specDraftNMax));
+ if (specDraftCacheType)
+ params.set("spec_draft_cache_type", specDraftCacheType);
+ if (ctxCheckpoints != null && ctxCheckpoints >= 0)
+ params.set("ctx_checkpoints", String(ctxCheckpoints));
+ // The compute buffers scale with these, and the planner defaults them when
+ // they are absent, which underprices a config that raised either.
+ if (nBatch && nBatch > 0) params.set("n_batch", String(nBatch));
+ if (nUbatch && nUbatch > 0) params.set("n_ubatch", String(nUbatch));
+ if (tensorParallel) params.set("tensor_parallel", "true");
+ if (disableVision) params.set("disable_vision", "true");
const response = await authFetch(
`/api/models/kv-cache-estimate?${params}`,
signal ? { signal } : undefined,
diff --git a/studio/frontend/src/features/chat/index.ts b/studio/frontend/src/features/chat/index.ts
index 044ee12ecdc..0b74c25e85c 100644
--- a/studio/frontend/src/features/chat/index.ts
+++ b/studio/frontend/src/features/chat/index.ts
@@ -16,6 +16,7 @@ export {
listChatAttachments,
listGgufVariants,
listLocalModels,
+ estimateKvCache,
listLoras,
listModels,
listRecommendedFolders,
@@ -30,6 +31,7 @@ export {
type CachedModelRepo,
type ChatAttachmentPage,
type ChatAttachmentRecord,
+ type KvCacheEstimate,
type LocalModelInfo,
type ScanFolderInfo,
} from "./api/chat-api";
@@ -58,6 +60,8 @@ export {
CHAT_RAG_OCR_KEY,
normalizeSpeculativeType,
readPersistedSpeculativeType,
+ CHAT_GPU_MEMORY_MODE_KEY,
+ CHAT_SPECULATIVE_TYPE_KEY,
readPersistedGpuMemoryMode,
reconcilePersistedGpuIds,
reconcilePersistedGpuSelection,
diff --git a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts b/studio/frontend/src/features/chat/stores/chat-runtime-store.ts
index 471ab9054ab..28f263e22fc 100644
--- a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts
+++ b/studio/frontend/src/features/chat/stores/chat-runtime-store.ts
@@ -108,6 +108,7 @@ export const CHAT_EXPAND_QUANTIZATIONS_KEY =
"unsloth_chat_expand_quantizations";
export const CHAT_SHOW_ALL_QUANTIZATIONS_KEY =
"unsloth_chat_show_all_quantizations";
+export const CHAT_SHOW_MEMORY_BAR_KEY = "unsloth_chat_show_memory_bar";
export const MODELS_FIT_ON_DEVICE_ONLY_KEY =
"unsloth_models_fit_on_device_only";
export const CHAT_BYPASS_PERMISSIONS_KEY = "unsloth_chat_bypass_permissions";
@@ -2728,6 +2729,10 @@ type ChatRuntimeStore = {
expandQuantizations: boolean;
/** Persisted: show non-downloaded quantizations too, not just downloaded. */
showAllQuantizations: boolean;
+ /** Persisted, off by default: chart each downloaded model's VRAM footprint
+ * under its row. Opt-in because the figures are estimates, and a row that
+ * cannot be sized is better left plain than annotated with a guess. */
+ showMemoryBar: boolean;
/** Persisted, shared by the chat model selector and the Hub page: list only
* models whose size fits this device's memory budget. */
fitOnDeviceOnly: boolean;
@@ -2957,6 +2962,7 @@ type ChatRuntimeStore = {
) => void;
setExpandQuantizations: (value: boolean) => void;
setShowAllQuantizations: (value: boolean) => void;
+ setShowMemoryBar: (value: boolean) => void;
setFitOnDeviceOnly: (value: boolean) => void;
setPendingAudio: (base64: string, name: string) => void;
clearPendingAudio: () => void;
@@ -3821,6 +3827,7 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({
expandQuantizations: loadBool(CHAT_EXPAND_QUANTIZATIONS_KEY, false),
// Off by default: On Device lists what is on disk, not the whole repo.
showAllQuantizations: loadBool(CHAT_SHOW_ALL_QUANTIZATIONS_KEY, false),
+ showMemoryBar: loadBool(CHAT_SHOW_MEMORY_BAR_KEY, false),
fitOnDeviceOnly: loadBool(MODELS_FIT_ON_DEVICE_ONLY_KEY, false),
loadedIsMultimodal: false,
loadedIsDiffusion: false,
@@ -5203,6 +5210,10 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({
saveBool(CHAT_SHOW_ALL_QUANTIZATIONS_KEY, showAllQuantizations);
set({ showAllQuantizations });
},
+ setShowMemoryBar: (showMemoryBar) => {
+ saveBool(CHAT_SHOW_MEMORY_BAR_KEY, showMemoryBar);
+ set({ showMemoryBar });
+ },
setFitOnDeviceOnly: (fitOnDeviceOnly) => {
saveBool(MODELS_FIT_ON_DEVICE_ONLY_KEY, fitOnDeviceOnly);
set({ fitOnDeviceOnly });
diff --git a/studio/frontend/src/features/hub/catalog/download-section.tsx b/studio/frontend/src/features/hub/catalog/download-section.tsx
index b9b523bfca3..3c914415a8b 100644
--- a/studio/frontend/src/features/hub/catalog/download-section.tsx
+++ b/studio/frontend/src/features/hub/catalog/download-section.tsx
@@ -29,6 +29,7 @@ export function DownloadSection({
onEject,
onTrain,
onChange,
+ showMemoryBar = true,
}: {
repoId: string;
isGguf: boolean;
@@ -53,6 +54,9 @@ export function DownloadSection({
onEject?: () => void;
onTrain?: () => void;
onChange?: () => void;
+ /** False for diffusion / audio / video GGUFs, which do not load through
+ * llama.cpp and so have nothing the KV estimator can say about them. */
+ showMemoryBar?: boolean;
}) {
if (isGguf || preferredGgufFile) {
return (
@@ -72,6 +76,7 @@ export function DownloadSection({
onUseInChat={onUseInChat}
onEject={onEject}
onChange={onChange}
+ showMemoryBar={showMemoryBar}
/>
);
}
diff --git a/studio/frontend/src/features/hub/catalog/gguf-download-card.tsx b/studio/frontend/src/features/hub/catalog/gguf-download-card.tsx
index efe0bf72530..6f7762012c0 100644
--- a/studio/frontend/src/features/hub/catalog/gguf-download-card.tsx
+++ b/studio/frontend/src/features/hub/catalog/gguf-download-card.tsx
@@ -1,6 +1,7 @@
// 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 { ModelMemoryBarFor } from "@/components/model-memory-bar";
import {
DropdownMenu,
DropdownMenuContent,
@@ -24,6 +25,7 @@ import { getCachedModelPath, revealCachedModel } from "@/features/chat";
import { pinKey, usePinnedModelsStore } from "@/features/model-picker";
import { ChevronDownStandardIcon } from "@/lib/chevron-icons";
import { copyToClipboard } from "@/lib/copy-to-clipboard";
+import { type GgufFitClass, classifyGgufFit } from "@/lib/gguf-fit";
import { toast } from "@/lib/toast";
import { cn } from "@/lib/utils";
import {
@@ -56,7 +58,7 @@ import {
} from "../download-manager";
import { useOnlineStatus } from "../hooks/use-online-status";
import { type GgufVariantDetail, deleteCachedModel } from "../inventory";
-import { type GgufFitClass, classifyGgufFit } from "../lib/gguf-fit";
+import { formatBytes } from "../lib/format";
import {
ggufFilenamesMatch,
ggufSelectionOverrideMatchesIntent,
@@ -555,6 +557,7 @@ export function GgufDownloadCard({
onLoad,
onEject,
onChange,
+ showMemoryBar = true,
}: {
repoId: string;
isActive: boolean;
@@ -573,6 +576,13 @@ export function GgufDownloadCard({
onUseInChat?: () => void;
onEject?: () => void;
onChange?: () => void;
+ /** False for diffusion / audio / video GGUFs. They load through a different
+ * planner onto a single torch device rather than the aggregate inference
+ * pool, so the llama.cpp estimator has nothing to say about them -- and when
+ * it returns unsized the bar falls back to the file size and draws a
+ * weights-only verdict anyway, which is a confident number about the wrong
+ * runtime. The picker suppresses these rows for the same reason. */
+ showMemoryBar?: boolean;
}) {
const hfToken = useHfTokenStore((s) => s.token);
const online = useOnlineStatus();
@@ -1165,6 +1175,18 @@ export function GgufDownloadCard({
)}
</button>
</DownloadCard>
+ {/* Only a quant actually on disk gets charted: an undownloaded one has no
+ weights to measure, and the fit badge already tiers those. */}
+ {selected?.downloaded && showMemoryBar ? (
+ <ModelMemoryBarFor
+ repoId={repoId}
+ quant={selected.quant}
+ sizeBytes={selected.size_bytes}
+ gpuGb={gpuGb}
+ showReadout={true}
+ className="px-1"
+ />
+ ) : null}
{refreshError && (
<button
type="button"
diff --git a/studio/frontend/src/features/hub/catalog/local-on-device-card.tsx b/studio/frontend/src/features/hub/catalog/local-on-device-card.tsx
index a020dde3577..16fc595b277 100644
--- a/studio/frontend/src/features/hub/catalog/local-on-device-card.tsx
+++ b/studio/frontend/src/features/hub/catalog/local-on-device-card.tsx
@@ -1,6 +1,7 @@
// 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 { ModelMemoryBarFor } from "@/components/model-memory-bar";
import {
Popover,
PopoverContent,
@@ -80,6 +81,11 @@ interface LocalOnDeviceCardProps {
sourceLabel: string;
source: LocalModelInfo["source"];
path: string;
+ /** False for a local diffusion / audio / video GGUF: it runs through the media
+ * planner rather than llama.cpp, so the KV estimator describes the wrong
+ * runtime -- and it still falls back to the file size, so it draws a
+ * confident weights-only verdict rather than nothing. */
+ showMemoryBar?: boolean;
isGguf: boolean;
requiresVariant?: boolean;
modelFormat: ModelInventoryFormat | null;
@@ -111,7 +117,10 @@ interface LocalOnDeviceCardProps {
* it came from this card's selector or was derived from the resident model, which
* decides whether a fresher status read may override it.
*/
- onOpenSettings?: (ggufVariant: string | null, quantIsUserPicked: boolean) => void;
+ onOpenSettings?: (
+ ggufVariant: string | null,
+ quantIsUserPicked: boolean,
+ ) => void;
}
function formatAdapterLabel(
@@ -209,6 +218,7 @@ export function LocalOnDeviceCard({
sourceLabel,
source,
path,
+ showMemoryBar = true,
isGguf,
requiresVariant = false,
modelFormat,
@@ -705,6 +715,31 @@ export function LocalOnDeviceCard({
</button>
</div>
</div>
+ {/* Below the action row, not inside it: the row is a horizontal flex
+ container, so a full-width bar there becomes another flex item and
+ squeezes the Run/Train buttons. */}
+ {/* A direct .gguf path skips variant selection entirely, so selectedQuant
+ is null for exactly the local files this is meant to cover. The path
+ names the weights on its own there, and the backend resolves a
+ direct file without needing a quant to match. */}
+ {showMemoryBar &&
+ (repoId || localGgufPath) &&
+ (selectedQuant || localGgufPath.toLowerCase().endsWith(".gguf")) ? (
+ <ModelMemoryBarFor
+ // The card's own path is what Run opens, so it is the identity the
+ // estimate has to use: a repo cached under several roots or revisions
+ // can otherwise resolve a different snapshot and chart weights the
+ // click does not load. It is also the only identity a custom or local
+ // GGUF has, where repoId is null and the bar used to be suppressed
+ // outright despite a perfectly good path being right here.
+ repoId={repoId || localGgufPath}
+ loadId={localGgufPath}
+ quant={selectedQuant ?? ""}
+ sizeBytes={selectedVariant?.size_bytes}
+ gpuGb={gpuGb}
+ className="px-3 pb-2"
+ />
+ ) : null}
</div>
{baseModel && (
<BaseModelReference
diff --git a/studio/frontend/src/features/hub/catalog/model-inspector.tsx b/studio/frontend/src/features/hub/catalog/model-inspector.tsx
index 0f8bc69a2d6..2ce54f7a020 100644
--- a/studio/frontend/src/features/hub/catalog/model-inspector.tsx
+++ b/studio/frontend/src/features/hub/catalog/model-inspector.tsx
@@ -578,6 +578,15 @@ export const ModelInspector = memo(function ModelInspector({
// row is one onLoad can actually route there: those pages resolve a routed `model` as a
// Hub id, so a filesystem row fails routableToMediaPage and the click falls through to
// the chat loader, which unloads the resident model for a load that can only fail.
+ // Whether this model's runtime is llama.cpp at all. Deliberately NOT
+ // runsOnMediaPage below: that one also asks whether the click can be ROUTED to
+ // the page, which is a different question. A diffusion GGUF on a filesystem row
+ // is not routable and still does not load through llama.cpp, so a memory bar
+ // there would describe the wrong runtime either way.
+ const runsOnMediaRuntime =
+ studioPageForTask(
+ taskForMediaPick(model.pipelineTag, model.task) ?? undefined,
+ ) !== undefined;
const runsOnMediaPage =
studioPageForTask(
taskForMediaPick(model.pipelineTag, model.task) ?? undefined,
@@ -700,6 +709,7 @@ export const ModelInspector = memo(function ModelInspector({
<InspectorDownloadSlot>
{model.isLocal && !hasActiveHubDownload ? (
<LocalOnDeviceCard
+ showMemoryBar={!runsOnMediaRuntime}
modelId={model.id}
repoId={model.hubRepoId}
sourceLabel={model.sourceLabel}
@@ -740,6 +750,7 @@ export const ModelInspector = memo(function ModelInspector({
/>
) : (
<DownloadSection
+ showMemoryBar={!runsOnMediaRuntime}
repoId={model.isLocal ? (model.hubRepoId ?? model.id) : model.id}
isGguf={model.isGguf}
isDownloaded={model.isDownloaded}
diff --git a/studio/frontend/src/features/hub/lib/gguf-variant-sort.ts b/studio/frontend/src/features/hub/lib/gguf-variant-sort.ts
index 70244bb3a56..350586fe1b5 100644
--- a/studio/frontend/src/features/hub/lib/gguf-variant-sort.ts
+++ b/studio/frontend/src/features/hub/lib/gguf-variant-sort.ts
@@ -3,7 +3,7 @@
import type { GgufVariantDetail } from "@/features/hub/inventory";
import { formatBytes } from "@/features/hub/lib/format";
-import { classifyGgufFit } from "@/features/hub/lib/gguf-fit";
+import { classifyGgufFit } from "@/lib/gguf-fit";
import { ggufVariantsMatch } from "@/features/hub/lib/model-identity";
type GgufVariantResources = {
diff --git a/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsx b/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsx
index bf0ab9d85cf..e5eac56e563 100644
--- a/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsx
+++ b/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsx
@@ -1,6 +1,7 @@
// 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 { ModelMemoryBar } from "@/components/model-memory-bar";
import { shouldRefreshPickerInventoryOnMount } from "@/components/resource-picker/picker-tab-policy";
import { Checkbox } from "@/components/ui/checkbox";
import { Input } from "@/components/ui/input";
@@ -68,6 +69,10 @@ import {
useHostClass,
useInferenceGpuInfo,
} from "@/hooks";
+import {
+ type ModelMemorySource,
+ useModelMemory,
+} from "@/hooks/use-model-memory";
import { diffusionRouteSearch } from "@/lib/diffusion-route-search";
import { extractParamLabel } from "@/lib/model-size";
import { toast } from "@/lib/toast";
@@ -813,6 +818,7 @@ function ModelRow({
tags,
alignMeta,
showSize,
+ memory,
className,
}: {
label: string;
@@ -850,6 +856,10 @@ function ModelRow({
/** Hold the size column open. Hub rows pass this on the MLX and Safetensors
* filters, where a repo is one download with one size. */
showSize?: boolean;
+ /** Identifies the on-disk model whose VRAM split the row should chart.
+ * Omit for rows that are not downloaded -- there is nothing to size until
+ * the weights exist locally. */
+ memory?: ModelMemorySource;
className?: string;
}) {
const exceeds = vramStatus === "exceeds";
@@ -894,6 +904,12 @@ function ModelRow({
}
: null;
+ // Only the selected row charts itself. A meter under every row turns a list
+ // you scan into a wall of charts, and a model that comfortably fits is not
+ // news; the one you are actually considering is. At most one bar is on screen.
+ const memorySegments = useModelMemory(selected ? memory : undefined, gpuGb);
+ const showMemoryBar = memorySegments.status !== "unknown";
+
const content = (
<button
type="button"
@@ -907,147 +923,153 @@ function ModelRow({
}}
onClick={onClick}
className={cn(
- "flex w-full items-center gap-2 rounded-full px-2 py-1.5 text-left text-sm transition-colors hover:bg-[#ececec] focus-visible:bg-[#ececec] focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring dark:hover:bg-[var(--sidebar-accent)] dark:focus-visible:bg-[var(--sidebar-accent)]",
+ "flex w-full flex-col items-stretch px-2 py-1.5 text-left text-sm transition-colors hover:bg-[#ececec] focus-visible:bg-[#ececec] focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring dark:hover:bg-[var(--sidebar-accent)] dark:focus-visible:bg-[var(--sidebar-accent)]",
+ showMemoryBar ? "rounded-2xl" : "rounded-full",
selected && "bg-[#ececec] dark:bg-[var(--sidebar-accent)]",
className,
)}
>
- <span className="flex min-w-0 flex-1 items-baseline">
- {/* Fixed slot, so names start on one line with or without a dot. */}
- {aligned ? (
- <span
- className={cn(
- "mr-1 flex shrink-0 items-center self-center",
- META_COLUMN.format,
- )}
- >
- {formatDot ? <FormatTag {...formatDot} /> : null}
- </span>
- ) : formatDot ? (
- <span className="mr-1 flex shrink-0 items-center self-center">
- <FormatTag {...formatDot} />
- </span>
- ) : null}
- {showOwner ? (
- <span className="inline-flex min-w-0 max-w-[45%] shrink items-baseline text-ui-13 text-muted-foreground/90">
- <span className="truncate">{owner}</span>
- <span className="shrink-0 text-muted-foreground/45">/</span>
- </span>
- ) : null}
- <span className="min-w-0 flex-1 truncate">{name}</span>
- {/* Here it eats name width instead of moving the meta columns. */}
- {aligned && loaded && (
- <DotTag
- tone="success"
- label="Loaded"
- className="ml-2 h-[18px] shrink-0 gap-1 rounded-md px-1.5"
- dotClassName="size-[5px]"
- />
- )}
- {alignMeta === "device" ? (
- <span
- className={cn(
- "ml-1.5 flex shrink-0 items-center self-center text-ui-9",
- META_COLUMN.quant,
- )}
- >
- {quantChip ? <QuantChip label={quantChip} /> : null}
- </span>
- ) : quantChip ? (
- <span className="ml-2 shrink-0 rounded-md bg-black/[0.06] px-1.5 py-px font-mono text-ui-10 text-muted-foreground dark:bg-white/[0.1]">
- {quantChip}
- </span>
- ) : null}
- {tags && tags.length > 0 ? (
- <span className="ml-1.5 flex shrink-0 items-center gap-1 self-center">
- {tags.map((tag) => (
- <QuantChip key={tag} label={tag} />
- ))}
- </span>
- ) : null}
- </span>
- <span
- className={cn(
- "ml-auto flex shrink-0 items-center",
- aligned ? "gap-1" : "gap-1.5",
- )}
- >
- {/* Capabilities, vision and the Hub lists' "on disk" mark share one
- column; two of them widen the slot rather than overlap. */}
- {aligned ? (
- <span
- className={cn(
- "flex shrink-0 items-center justify-center gap-1 text-ui-10",
- badgeColumn,
- )}
- >
- {showCaps && <CapabilityIcons caps={caps} />}
- {showVision && <VisionBadge />}
- {downloaded && !loaded ? <DownloadedBadge /> : null}
- </span>
- ) : (
- <>
- {showCaps && <CapabilityIcons caps={caps} />}
- {showVision && <VisionBadge />}
- {loaded && (
- <DotTag
- tone="success"
- label="Loaded"
- className="h-[18px] gap-1 rounded-md px-1.5"
- dotClassName="size-[5px]"
- />
- )}
- {downloaded && !loaded ? <DownloadedBadge /> : null}
- </>
- )}
- {alignMeta === "hub" ? (
- <span
- className={cn(
- "flex shrink-0 items-center justify-end text-ui-9",
- META_COLUMN.vram,
- )}
- >
+ <span className="flex w-full items-center gap-2">
+ <span className="flex min-w-0 flex-1 items-baseline">
+ {/* Fixed slot, so names start on one line with or without a dot. */}
+ {aligned ? (
+ <span
+ className={cn(
+ "mr-1 flex shrink-0 items-center self-center",
+ META_COLUMN.format,
+ )}
+ >
+ {formatDot ? <FormatTag {...formatDot} /> : null}
+ </span>
+ ) : formatDot ? (
+ <span className="mr-1 flex shrink-0 items-center self-center">
+ <FormatTag {...formatDot} />
+ </span>
+ ) : null}
+ {showOwner ? (
+ <span className="inline-flex min-w-0 max-w-[45%] shrink items-baseline text-ui-13 text-muted-foreground/90">
+ <span className="truncate">{owner}</span>
+ <span className="shrink-0 text-muted-foreground/45">/</span>
+ </span>
+ ) : null}
+ <span className="min-w-0 flex-1 truncate">{name}</span>
+ {/* Here it eats name width instead of moving the meta columns. */}
+ {aligned && loaded && (
+ <DotTag
+ tone="success"
+ label="Loaded"
+ className="ml-2 h-[18px] shrink-0 gap-1 rounded-md px-1.5"
+ dotClassName="size-[5px]"
+ />
+ )}
+ {alignMeta === "device" ? (
+ <span
+ className={cn(
+ "ml-1.5 flex shrink-0 items-center self-center text-ui-9",
+ META_COLUMN.quant,
+ )}
+ >
+ {quantChip ? <QuantChip label={quantChip} /> : null}
+ </span>
+ ) : quantChip ? (
+ <span className="ml-2 shrink-0 rounded-md bg-black/[0.06] px-1.5 py-px font-mono text-ui-10 text-muted-foreground dark:bg-white/[0.1]">
+ {quantChip}
+ </span>
+ ) : null}
+ {tags && tags.length > 0 ? (
+ <span className="ml-1.5 flex shrink-0 items-center gap-1 self-center">
+ {tags.map((tag) => (
+ <QuantChip key={tag} label={tag} />
+ ))}
+ </span>
+ ) : null}
+ </span>
+ <span
+ className={cn(
+ "ml-auto flex shrink-0 items-center",
+ aligned ? "gap-1" : "gap-1.5",
+ )}
+ >
+ {/* Capabilities, vision and the Hub lists' "on disk" mark share one
+ column; two of them widen the slot rather than overlap. */}
+ {aligned ? (
+ <span
+ className={cn(
+ "flex shrink-0 items-center justify-center gap-1 text-ui-10",
+ badgeColumn,
+ )}
+ >
+ {showCaps && <CapabilityIcons caps={caps} />}
+ {showVision && <VisionBadge />}
+ {downloaded && !loaded ? <DownloadedBadge /> : null}
+ </span>
+ ) : (
+ <>
+ {showCaps && <CapabilityIcons caps={caps} />}
+ {showVision && <VisionBadge />}
+ {loaded && (
+ <DotTag
+ tone="success"
+ label="Loaded"
+ className="h-[18px] gap-1 rounded-md px-1.5"
+ dotClassName="size-[5px]"
+ />
+ )}
+ {downloaded && !loaded ? <DownloadedBadge /> : null}
+ </>
+ )}
+ {alignMeta === "hub" ? (
+ <span
+ className={cn(
+ "flex shrink-0 items-center justify-end text-ui-9",
+ META_COLUMN.vram,
+ )}
+ >
+ <VramBadge status={vramStatus} />
+ </span>
+ ) : (
<VramBadge status={vramStatus} />
- </span>
- ) : (
- <VramBadge status={vramStatus} />
- )}
- {aligned ? (
- <span
- className={cn(
- "flex shrink-0 justify-end text-ui-10",
- alignMeta === "hub" ? META_COLUMN.paramWide : META_COLUMN.param,
- )}
- >
- {paramLabel ? <ParamChip label={paramLabel} /> : null}
- </span>
- ) : paramLabel ? (
- <ParamChip label={paramLabel} />
- ) : null}
- {parsed.texts.map((text) => (
- <span key={text} className="text-ui-10 text-muted-foreground">
- {text}
- </span>
- ))}
- {/* GGUF repos hold several quants of different sizes, so their rows
- report one only once expanded, leaving the column an empty gap. */}
- {alignMeta === "device" || showSize ? (
- <span
- className={cn(
- "shrink-0 whitespace-nowrap text-right font-mono text-ui-10 text-muted-foreground tabular-nums",
- META_COLUMN.size,
- )}
- >
- {parsed.size === undefined ? null : (
+ )}
+ {aligned ? (
+ <span
+ className={cn(
+ "flex shrink-0 justify-end text-ui-10",
+ alignMeta === "hub" ? META_COLUMN.paramWide : META_COLUMN.param,
+ )}
+ >
+ {paramLabel ? <ParamChip label={paramLabel} /> : null}
+ </span>
+ ) : paramLabel ? (
+ <ParamChip label={paramLabel} />
+ ) : null}
+ {parsed.texts.map((text) => (
+ <span key={text} className="text-ui-10 text-muted-foreground">
+ {text}
+ </span>
+ ))}
+ {/* GGUF repos hold several quants of different sizes, so their rows
+ report one only once expanded, leaving the column an empty gap. */}
+ {alignMeta === "device" || showSize ? (
+ <span
+ className={cn(
+ "shrink-0 whitespace-nowrap text-right font-mono text-ui-10 text-muted-foreground tabular-nums",
+ META_COLUMN.size,
+ )}
+ >
+ {parsed.size === undefined ? null : (
+ <SizeText value={parsed.size} />
+ )}
+ </span>
+ ) : aligned ? null : parsed.size !== undefined ? (
+ <span className="font-mono text-ui-10 text-muted-foreground tabular-nums">
<SizeText value={parsed.size} />
- )}
- </span>
- ) : aligned ? null : parsed.size !== undefined ? (
- <span className="font-mono text-ui-10 text-muted-foreground tabular-nums">
- <SizeText value={parsed.size} />
- </span>
- ) : null}
+ </span>
+ ) : null}
+ </span>
</span>
+ {showMemoryBar ? (
+ <ModelMemoryBar segments={memorySegments} compact={true} />
+ ) : null}
</button>
);
@@ -4778,9 +4800,17 @@ export function HubModelPicker({
// Not focus-within: the dots menu returns focus to its trigger on close, so
// the row stayed lit after the pointer left. Keyboard focus and an open menu
// still light it.
- const downloadedRowShellClassName = (selected: boolean) =>
+ //
+ // A row carrying a memory bar is two lines tall, and the shell paints the
+ // hover and selected background (the inner button is transparent at these
+ // sites), so the radius relaxes with it or the row renders as a stadium.
+ const downloadedRowShellClassName = (
+ selected: boolean,
+ hasMemoryBar = false,
+ ) =>
cn(
- "group flex items-center rounded-full transition-colors hover:bg-[#ececec] has-[:focus-visible]:bg-[#ececec] has-[[data-state=open]]:bg-[#ececec] dark:hover:bg-[var(--sidebar-accent)] dark:has-[:focus-visible]:bg-[var(--sidebar-accent)] dark:has-[[data-state=open]]:bg-[var(--sidebar-accent)]",
+ "group flex items-center transition-colors hover:bg-[#ececec] has-[:focus-visible]:bg-[#ececec] has-[[data-state=open]]:bg-[#ececec] dark:hover:bg-[var(--sidebar-accent)] dark:has-[:focus-visible]:bg-[var(--sidebar-accent)] dark:has-[[data-state=open]]:bg-[var(--sidebar-accent)]",
+ hasMemoryBar ? "rounded-2xl" : "rounded-full",
selected && "bg-[#ececec] dark:bg-[var(--sidebar-accent)]",
);
@@ -4798,7 +4828,10 @@ export function HubModelPicker({
!ggufVariantsMatchForPicker(activeGgufVariant, null) &&
ggufVariantsMatchForPicker(activeGgufVariant, entry.quant);
return (
- <div key={optionKey} className={downloadedRowShellClassName(isSelected)}>
+ <div
+ key={optionKey}
+ className={downloadedRowShellClassName(isSelected, true)}
+ >
{/* Through ModelRow, so a pinned quant lands in the same columns as
the rows below it. */}
<div className="min-w-0 flex-1">
@@ -4809,6 +4842,20 @@ export function HubModelPicker({
)})`}
meta="GGUF"
quantChip={ggufQuantChipLabel(entry.quant)}
+ // Same runtime gate the sole-quant row below applies. A pinned quant
+ // can belong to an image, video or audio task, and those load through
+ // the media planner rather than llama.cpp, so the KV estimator is
+ // measuring the wrong runtime -- and it falls back to the file size
+ // when it cannot size the model, so the row draws a confident
+ // weights-only verdict rather than nothing.
+ memory={
+ mediaPageForTask(
+ diffusionTaskById.get(entry.repoId.toLowerCase()),
+ )
+ ? undefined
+ : { repoId: entry.repoId, quant: entry.quant }
+ }
+ gpuGb={inferenceGpu.memoryTotalGb}
alignMeta="device"
selected={isSelected}
loaded={isLoaded}
@@ -4922,7 +4969,10 @@ export function HubModelPicker({
pipelineTag: c.task ?? null,
};
return (
- <div key={c.repo_id} className={downloadedRowShellClassName(isSelected)}>
+ <div
+ key={c.repo_id}
+ className={downloadedRowShellClassName(isSelected, true)}
+ >
<div className="min-w-0 flex-1">
<ModelRow
label={c.repo_id}
@@ -4933,6 +4983,25 @@ export function HubModelPicker({
)}
meta={`GGUF · ${formatBytes(variant.size_bytes)}`}
quantChip={ggufQuantChipLabel(variant.quant)}
+ // Only for models the llama.cpp path actually loads. The Images and
+ // Video pickers deliberately keep diffusion GGUFs listed, and those
+ // run on the diffusion planner with different runtime buffers, on a
+ // single torch device rather than the aggregate inference pool. The
+ // KV estimator has nothing to say about them, and when it returns
+ // unsized the bar falls back to the file size and draws a
+ // weights-only verdict anyway -- a confident number about the wrong
+ // runtime, which is the failure this bar exists to avoid.
+ memory={
+ mediaPageForTask(c.task)
+ ? undefined
+ : {
+ repoId: c.repo_id,
+ quant: variant.quant,
+ sizeBytes: variant.size_bytes,
+ loadId: c.load_id,
+ }
+ }
+ gpuGb={inferenceGpu.memoryTotalGb}
showVision={c.has_vision || sole.hasVision}
selected={isSelected}
loaded={rowState.loaded}
diff --git a/studio/frontend/src/features/model-picker/index.ts b/studio/frontend/src/features/model-picker/index.ts
index 8e761485c48..0b8bf94c47d 100644
--- a/studio/frontend/src/features/model-picker/index.ts
+++ b/studio/frontend/src/features/model-picker/index.ts
@@ -48,7 +48,10 @@ export {
DEFAULT_PER_MODEL_CONFIG,
normalizeMaxSeqLength,
type PerModelConfig,
+ PER_MODEL_CONFIG_STORAGE_KEY,
+ PER_MODEL_CONFIG_UPDATED_EVENT,
adoptLegacyConfigKey,
+ listPerModelConfigs,
isServedByMlx,
presetLoadSettingNames,
resolveInitialConfig,
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.ts
index a27fb23ad7f..562cd99a7eb 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
@@ -1,6 +1,7 @@
// 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 type { GpuIndexKind } from "@/hooks/use-gpu-info";
import {
ggufVariantFromStorageKey,
modelIdFromStorageKey,
@@ -9,7 +10,6 @@ import {
normalizeModelIdentity,
publicModelId,
} from "./model-identity";
-import type { GpuIndexKind } from "@/hooks/use-gpu-info";
import {
DRAFT_N_MAX_SPEC_TYPES,
SEPARATE_DRAFT_MODEL_SPEC_TYPES,
@@ -206,7 +206,10 @@ export {
SPECULATIVE_TYPES,
} from "@/lib/speculative-modes";
-const STORAGE_KEY = "unsloth_model_configs";
+/** Exported so cross-tab listeners can tell this key's storage event from the
+ * dozens of others Studio writes. */
+export const PER_MODEL_CONFIG_STORAGE_KEY = "unsloth_model_configs";
+const STORAGE_KEY = PER_MODEL_CONFIG_STORAGE_KEY;
const LEGACY_STORAGE_KEY = "unsloth_load_settings";
const LEGACY_MIGRATION_FLAG = "unsloth_model_configs_migrated";
// v2 added nBatch / nUbatch, v3 llamaExtraArgs, v4 disableVision and v5 the
@@ -722,17 +725,28 @@ function readMap(): StoredMap {
return readMapRaw();
}
+/** Fires when any model's saved config changes, in this tab. The browser's own
+ * `storage` event only reaches *other* tabs, so readers that need to react to
+ * an edit made here (the picker's memory bar) have nothing else to listen to. */
+export const PER_MODEL_CONFIG_UPDATED_EVENT =
+ "unsloth-per-model-config-updated";
+
function writeMap(map: StoredMap): boolean {
if (!canUseStorage()) {
return false;
}
try {
localStorage.setItem(STORAGE_KEY, JSON.stringify(map));
- return true;
} catch (err) {
console.warn("Failed to persist per-model config:", err);
return false;
}
+ // Best-effort: the write already landed, so a host that cannot dispatch
+ // events must not make a saved config report back as unsaved.
+ if (typeof window?.dispatchEvent === "function") {
+ window.dispatchEvent(new Event(PER_MODEL_CONFIG_UPDATED_EVENT));
+ }
+ return true;
}
function warnDroppedFields(
diff --git a/studio/frontend/src/features/settings/tabs/chat-tab.tsx b/studio/frontend/src/features/settings/tabs/chat-tab.tsx
index 63d7faf8036..bbac398d4d8 100644
--- a/studio/frontend/src/features/settings/tabs/chat-tab.tsx
+++ b/studio/frontend/src/features/settings/tabs/chat-tab.tsx
@@ -187,6 +187,10 @@ export function ChatTab() {
const setShowAllQuantizations = useChatRuntimeStore(
(state) => state.setShowAllQuantizations,
);
+ const showMemoryBar = useChatRuntimeStore((state) => state.showMemoryBar);
+ const setShowMemoryBar = useChatRuntimeStore(
+ (state) => state.setShowMemoryBar,
+ );
const organizeBy = useSidebarOrganizationStore((s) => s.organizeBy);
const setOrganizeBy = useSidebarOrganizationStore((s) => s.setOrganizeBy);
const showModelDisclaimer = useChatPreferencesStore(
@@ -260,6 +264,14 @@ export function ChatTab() {
onCheckedChange={setShowAllQuantizations}
/>
</SettingsRow>
+ <SettingsRow
+ label={t("settings.chat.modelSelection.showMemoryBar")}
+ description={t(
+ "settings.chat.modelSelection.showMemoryBarDescription",
+ )}
+ >
+ <Switch checked={showMemoryBar} onCheckedChange={setShowMemoryBar} />
+ </SettingsRow>
</SettingsSection>
<SettingsSection
diff --git a/studio/frontend/src/features/settings/tabs/general-tab.tsx b/studio/frontend/src/features/settings/tabs/general-tab.tsx
index 7bb60219a3f..9faf44af18e 100644
--- a/studio/frontend/src/features/settings/tabs/general-tab.tsx
+++ b/studio/frontend/src/features/settings/tabs/general-tab.tsx
@@ -122,6 +122,16 @@ const PREFS_KEYS: string[] = [
// Model selector settings ("Select model settings" group)
"unsloth_chat_expand_quantizations",
"unsloth_chat_show_all_quantizations",
+ // The memory bar's opt-in. Reset All advertises restoring defaults and this
+ // feature's default is off, so leaving the key out left it switched on across
+ // a reset that said it had turned everything back.
+ //
+ // Spelled out rather than imported as CHAT_SHOW_MEMORY_BAR_KEY, for the same
+ // reason the note above gives: it lives in chat-runtime-store, which is in an
+ // import cycle with this file, so the constant would still be in its temporal
+ // dead zone when this module-scope list is built. A test pins this literal
+ // against the store's constant so the two cannot drift apart silently.
+ "unsloth_chat_show_memory_bar",
"unsloth_models_fit_on_device_only",
// Chat presets
"unsloth_chat_custom_presets",
diff --git a/studio/frontend/src/hooks/use-gpu-info.ts b/studio/frontend/src/hooks/use-gpu-info.ts
index a8a704914f3..83705420e3d 100644
--- a/studio/frontend/src/hooks/use-gpu-info.ts
+++ b/studio/frontend/src/hooks/use-gpu-info.ts
@@ -38,6 +38,9 @@ export interface GpuInfo {
budgetKnown: boolean;
/** true when the visible GPUs use only the host memory pool. */
sharedMemory: boolean;
+ /** True when any device's budget is a unified host pool (a ROCm APU), which is
+ * not a VRAM ceiling a fit verdict can be measured against. */
+ unifiedMemory: boolean;
/** The backend torch resolved: cuda, rocm, xpu, mlx, cpu. Carried on every path, including the
* GPU-less one, because "which runtimes can this host place" is exactly the question a host
* with no usable GPU has to answer. Empty until system info arrives. */
@@ -67,6 +70,7 @@ const DEFAULT_GPU: GpuInfo = {
available: false,
budgetKnown: false,
sharedMemory: false,
+ unifiedMemory: false,
backend: "",
name: "Unknown",
memoryTotalGb: 0,
@@ -111,6 +115,11 @@ function toGpuInfo(
gpuSharedHostMemoryGb(devices),
),
sharedMemory: memoryTotals.shared > 0 && memoryTotals.dedicated === 0,
+ // Additive, and deliberately some() where sharedMemory above is "no dedicated
+ // pool at all": one unified part makes the aggregate total partly host RAM,
+ // which is already enough to stop it being a VRAM ceiling a fit verdict can
+ // be measured against.
+ unifiedMemory: devices.some((device) => device.unified_memory === true),
available: true,
budgetKnown: true,
name: devices[0]?.name ?? "Unknown",
diff --git a/studio/frontend/src/hooks/use-model-memory.ts b/studio/frontend/src/hooks/use-model-memory.ts
new file mode 100644
index 00000000000..fcd768cca5c
--- /dev/null
+++ b/studio/frontend/src/hooks/use-model-memory.ts
@@ -0,0 +1,611 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+/**
+ * VRAM estimate for one downloaded model, for the picker's memory bar.
+ *
+ * Per row, because the rows are spread across a dozen render sites. The work is
+ * shared though: `/kv-cache-estimate` reads GGUF metadata off disk, so answers
+ * are cached by the inputs that change them and duplicate requests fold into
+ * one. Ten rows of the same model cost one read.
+ */
+
+import {
+ CHAT_GPU_MEMORY_MODE_KEY,
+ CHAT_SPECULATIVE_TYPE_KEY,
+ estimateKvCache,
+ readPersistedGpuMemoryMode,
+ readPersistedSpeculativeType,
+ useChatRuntimeStore,
+} from "@/features/chat";
+import {
+ normalizeGgufVariantIdentity,
+ normalizeModelIdentity,
+} from "@/features/hub";
+import {
+ PER_MODEL_CONFIG_STORAGE_KEY,
+ PER_MODEL_CONFIG_UPDATED_EVENT,
+ type PerModelConfig,
+ listPerModelConfigs,
+} from "@/features/model-picker";
+import {
+ loadVramBudgetSettings,
+ subscribeVramBudgetSettings,
+} from "@/features/settings/api/vram-budget";
+import {
+ type ModelMemorySegments,
+ computeModelMemory,
+ estimateCacheKey,
+ estimateIsUnsized,
+ extraArgsAddResidentFiles,
+ extraArgsOwnPlacement,
+ extraArgsShapeKvCache,
+} from "@/lib/model-memory";
+import { useInferenceGpuInfo } from "./use-gpu-info";
+import { useEffect, useMemo, useState, useSyncExternalStore } from "react";
+
+/** The on-disk model a row would load. */
+export interface ModelMemorySource {
+ repoId: string;
+ quant: string;
+ /** Size from the listing, so the bar draws before the estimate arrives. */
+ sizeBytes?: number | null;
+ /**
+ * The concrete thing this row loads, when the listing resolved one.
+ *
+ * Selecting the row loads this, while the estimate resolved by repo id alone,
+ * so on a duplicate or recovered HF cache the two could pick different copies
+ * of the same quant and the bar would describe a model the click does not
+ * open. Falls back to the repo id upstream, so sending it changes nothing for
+ * an ordinary row.
+ */
+ loadId?: string | null;
+}
+
+interface Estimate {
+ kvBytes: number | null;
+ weightsBytes: number | null;
+ specBytes: number | null;
+ /** Context the KV figure was computed at, for the per-token rate. */
+ nCtx: number;
+ /** Vision projector footprint, resident alongside the weights. */
+ projectorBytes: number | null;
+ /** The host-heap share of kvBytes (SWA checkpoint snapshots), never on the card. */
+ kvCheckpointBytes: number | null;
+ /** The share of specBytes no shorter context can reduce (the drafter's weights). */
+ specFixedBytes: number | null;
+ /** llama.cpp's compute buffers, which every launch reserves. */
+ computeBytes: number | null;
+ /** False only when the loader is free to shrink the context to fit. */
+ contextIsPinned: boolean | null;
+ /** An inherited LLAMA_ARG_DEVICE confines the launch to fewer cards than the
+ * aggregate budget credits. */
+ inheritedDevicePin: boolean | null;
+ /** The planner's own GPU-resident total, which supersedes the segment sum. */
+ gpuTotalBytes: number | null;
+ /** What the planner still reserves at the shortest context. */
+ gpuFloorBytes: number | null;
+ /** The configured drafter could not be priced, so the total is a floor. */
+ specUnpriced: boolean;
+}
+
+const CACHE = new Map<string, Estimate>();
+const IN_FLIGHT = new Map<string, Promise<Estimate>>();
+
+/**
+ * Cap on remembered answers. A session can browse a lot of models, and each
+ * entry is keyed by settings as well as identity, so the key space is larger
+ * than the model count. Oldest-first eviction; a re-fetch costs one disk read.
+ */
+const CACHE_LIMIT = 256;
+
+/**
+ * How long a failure is remembered. Failures are cached so an unsizable model
+ * doesn't re-request on every reopen, but the common cause is the backend being
+ * briefly unavailable -- without expiry those rows would stay blank for the rest
+ * of the session.
+ */
+const FAILURE_TTL_MS = 30_000;
+
+const failedAt = new Map<string, number>();
+
+function remember(cacheKey: string, estimate: Estimate, failed: boolean): void {
+ // Only a new key grows the map, so re-pricing an existing one must not evict
+ // an unrelated row to make room it does not need.
+ if (CACHE.size >= CACHE_LIMIT && !CACHE.has(cacheKey)) {
+ const oldest = CACHE.keys().next().value;
+ if (oldest !== undefined) {
+ CACHE.delete(oldest);
+ failedAt.delete(oldest);
+ }
+ }
+ CACHE.set(cacheKey, estimate);
+ if (failed) failedAt.set(cacheKey, Date.now());
+ else failedAt.delete(cacheKey);
+}
+
+function cached(cacheKey: string): Estimate | undefined {
+ const hit = CACHE.get(cacheKey);
+ if (!hit) return undefined;
+ const failedTime = failedAt.get(cacheKey);
+ if (failedTime !== undefined && Date.now() - failedTime > FAILURE_TTL_MS) {
+ CACHE.delete(cacheKey);
+ failedAt.delete(cacheKey);
+ return undefined;
+ }
+ return hit;
+}
+
+const MISS: Estimate = {
+ kvBytes: null,
+ weightsBytes: null,
+ specBytes: null,
+ nCtx: 0,
+ projectorBytes: null,
+ kvCheckpointBytes: null,
+ specFixedBytes: null,
+ computeBytes: null,
+ contextIsPinned: null,
+ inheritedDevicePin: null,
+ gpuTotalBytes: null,
+ gpuFloorBytes: null,
+ specUnpriced: false,
+};
+
+/**
+ * Re-read saved settings whenever any of them are written.
+ *
+ * Two sources, because a model with no override follows the standing
+ * preference: the per-model configs, which announce themselves, and the
+ * standing GPU-memory mode and speculative type, which live in localStorage and
+ * so raise no same-tab event of their own. The runtime store changes in lockstep
+ * with those writes in-session, so it stands in as their notification.
+ */
+function subscribeToConfigChanges(onChange: () => void): () => void {
+ if (typeof window === "undefined") return () => {};
+ const onConfigWrite = () => {
+ configsDirty = true;
+ onChange();
+ };
+ window.addEventListener(PER_MODEL_CONFIG_UPDATED_EVENT, onConfigWrite);
+ // The custom event above is same-tab only, by construction: the native
+ // storage event fires in every OTHER document sharing the origin and never in
+ // the one that made the write. So settings edited in a second Studio tab
+ // arrive here as a storage event and nowhere else, and without this a mounted
+ // bar kept its old fit or OOM verdict indefinitely.
+ const onStorage = (event: Event) => {
+ const key = (event as StorageEvent).key;
+ // A null key means the whole store was cleared, which counts.
+ if (key == null || WATCHED_STORAGE_KEYS.includes(key)) onConfigWrite();
+ };
+ window.addEventListener("storage", onStorage);
+ const unsubscribeStore = useChatRuntimeStore.subscribe(onChange);
+ return () => {
+ window.removeEventListener(PER_MODEL_CONFIG_UPDATED_EVENT, onConfigWrite);
+ window.removeEventListener("storage", onStorage);
+ unsubscribeStore();
+ };
+}
+
+/** localStorage keys whose cross-tab writes change what the bar should show. */
+const WATCHED_STORAGE_KEYS = [
+ PER_MODEL_CONFIG_STORAGE_KEY,
+ CHAT_GPU_MEMORY_MODE_KEY,
+ CHAT_SPECULATIVE_TYPE_KEY,
+];
+
+/** Subscriber for a disabled bar: nothing to watch, nothing to unwatch. */
+const subscribeNothing = () => () => {};
+
+/** Snapshot for a disabled bar. Constant, so it can never force a re-render. */
+const readZeroEpoch = () => 0;
+
+let configEpoch = 0;
+let lastConfigSignature = "";
+let lastPrefSignature = "";
+// Serialising every saved config is the expensive half, and only a config write
+// can change it. The store ticks on every streamed token, so doing that work on
+// each tick would put an O(all configs) stringify in the render path.
+let configsDirty = true;
+
+/**
+ * A value that changes whenever any saved config does, so the estimate can be
+ * re-keyed. The settings sheet sits directly beside these rows, and without
+ * this a context change leaves the bar showing the old KV segment.
+ */
+function readConfigEpoch(): number {
+ // The standing GPU-memory mode and speculative type matter as much as the
+ // saved configs: a model with no override follows them. Without them,
+ // switching the global mode to Manual left every mounted bar drawn against a
+ // budget the load would no longer use, and turning MTP on globally left the
+ // draft reserve missing, until the row happened to remount. Both are two
+ // short strings, so they are cheap to check on every read.
+ // The session GPU pin belongs here because budgetIsMeaningful reads it. It
+ // lives in the runtime store rather than in a saved config, so a preset or a
+ // session-only load configuration changes it with no config write: the
+ // whole-store subscription did fire, but this snapshot did not move, so
+ // useSyncExternalStore suppressed the rerender and a bar stayed drawn against
+ // aggregate multi-GPU VRAM after the launch had been pinned to one card.
+ const pin = useChatRuntimeStore.getState();
+ // The session speculative mode belongs here for the same reason: it is read
+ // above and never written to a config, so nothing else would move the epoch.
+ const pinSignature = `${(pin.selectedGpuIds ?? []).join(",")} ${pin.selectedGpuIndexKind ?? ""} ${pin.speculativeType ?? ""}`;
+ const prefSignature = `${readPersistedGpuMemoryMode()} ${readPersistedSpeculativeType()} ${pinSignature}`;
+ if (prefSignature !== lastPrefSignature) {
+ lastPrefSignature = prefSignature;
+ configEpoch += 1;
+ }
+ if (configsDirty) {
+ configsDirty = false;
+ const signature = JSON.stringify(listPerModelConfigs());
+ if (signature !== lastConfigSignature) {
+ lastConfigSignature = signature;
+ configEpoch += 1;
+ }
+ }
+ return configEpoch;
+}
+
+/**
+ * The user's saved settings for this exact variant, if any.
+ *
+ * Variant-exact only, matching `resolveInitialConfig`: the load path looks up
+ * (modelId, ggufVariant) and drops to defaults when there's no hit. Falling back
+ * to a model-level entry here would size the bar from settings the variant will
+ * never load with.
+ *
+ * Keys are stored normalized, which lower-cases hub repo ids, so comparing raw
+ * strings would miss every mixed-case repo and quietly use defaults instead of
+ * the context length and KV dtype the user chose.
+ */
+function configFor(source: ModelMemorySource): PerModelConfig | undefined {
+ const wantId = normalizeModelIdentity(source.repoId);
+ const wantVariant = normalizeGgufVariantIdentity(source.quant);
+ return listPerModelConfigs().find(
+ (e) =>
+ normalizeModelIdentity(e.modelId) === wantId &&
+ normalizeGgufVariantIdentity(e.ggufVariant) === wantVariant,
+ )?.config;
+}
+
+/** A context the user pinned, or undefined to let the model use its own. */
+function pinnedContext(config: PerModelConfig | undefined): number | undefined {
+ return config?.customContextLength || config?.maxSeqLength || undefined;
+}
+
+/**
+ * Whether the budget we're handed still describes where this model will load.
+ *
+ * Callers pass the total across visible GPUs. Pin the model to a subset, or
+ * offload layers to CPU, and that total stops being the ceiling the model is
+ * judged against -- charting against it would call a 30 GB quant "fits" on a
+ * 2x24 GB host pinned to one card. Better to draw nothing than to mislead.
+ *
+ * The "at default" tests mirror `gpuFieldsAtDefault` in per-model-config: note
+ * that a negative gpuLayers is the runtime's Auto value, not an override, so a
+ * truthiness check here would hide the bar for ordinary saved configs. GPU mode
+ * falls back to the standing preference, which is what the loader does when a
+ * model has no override of its own.
+ */
+function budgetIsMeaningful(config: PerModelConfig | undefined): boolean {
+ const mode = config?.gpuMemoryMode ?? readPersistedGpuMemoryMode();
+ if (mode === "manual") return false;
+ // A session pin lives in the runtime store rather than in a saved config, so
+ // a user who pinned cards without ever saving a per-model override reached
+ // none of the tests below and was charted against the whole multi-GPU sum.
+ const sessionPin = useChatRuntimeStore.getState().selectedGpuIds;
+ if (sessionPin != null && sessionPin.length > 0) return false;
+ if (!config) return true;
+ // Pass-through args are appended after Unsloth's own flags, so an -ngl or a
+ // device pin in that box is what the launch actually uses. Reading only the
+ // structured fields left the bar charting a CPU-offloaded run against every
+ // GPU on the host.
+ if (extraArgsOwnPlacement(config.llamaExtraArgs)) return false;
+ // Same reasoning one term over: these do not move the cache, they resize it.
+ // The estimate is built from the structured controls, so a --swa-full in the
+ // box has the launch reserve a full-context cache while the bar priced the
+ // compact sliding window, and the row reads as a comfortable fit.
+ if (extraArgsShapeKvCache(config.llamaExtraArgs)) return false;
+ // And these add resident files nothing here priced -- a LoRA, a control
+ // vector, a hand-named drafter. The total would be short by whatever they
+ // weigh, with no sign of it in the bar.
+ if (extraArgsAddResidentFiles(config.llamaExtraArgs)) return false;
+ return (
+ config.selectedGpuIds == null &&
+ (config.gpuLayers == null || config.gpuLayers < 0) &&
+ (config.nCpuMoe == null || config.nCpuMoe === 0)
+ );
+}
+
+/**
+ * The speculative mode the load will actually use. A null per-model value means
+ * "follow the standing preference", which is where the loader looks too --
+ * sending nothing would omit the draft reserve until a per-model override is
+ * saved.
+ */
+function effectiveSpeculativeType(
+ config: PerModelConfig | undefined,
+): string | undefined {
+ // The live runtime value before the persisted one. Forced modes (mtp,
+ // mtp+ngram, dspark, dflash) are deliberately session-only and are never
+ // returned by readPersistedSpeculativeType, so a model loaded with one of them
+ // but not remembered was priced as auto -- and auto drops MTP on an MLA target
+ // while the forced load engages it and opens another full cache.
+ return (
+ config?.speculativeType ??
+ useChatRuntimeStore.getState().speculativeType ??
+ readPersistedSpeculativeType()
+ );
+}
+
+async function fetchEstimate(
+ cacheKey: string,
+ source: ModelMemorySource,
+ nCtx: number | undefined,
+ config: PerModelConfig | undefined,
+): Promise<Estimate> {
+ const known = cached(cacheKey) ?? IN_FLIGHT.get(cacheKey);
+ if (known) return known;
+
+ const run = estimateKvCache(source.repoId, source.quant, nCtx, {
+ cacheTypeKv: config?.kvCacheDtype,
+ nParallel: config?.nParallel,
+ speculativeType: effectiveSpeculativeType(config),
+ specDraftNMax: config?.specDraftNMax,
+ specDraftCacheType: config?.specDraftCacheDtype,
+ ctxCheckpoints: config?.ctxCheckpoints,
+ disableVision: config?.disableVision,
+ nBatch: config?.nBatch,
+ nUbatch: config?.nUbatch,
+ tensorParallel: config?.tensorParallel,
+ })
+ .then((r) => {
+ const estimate: Estimate = {
+ kvBytes: r.kv_bytes,
+ weightsBytes: r.weights_bytes,
+ specBytes: r.spec_bytes,
+ nCtx: r.n_ctx ?? 0,
+ projectorBytes: r.projector_bytes ?? null,
+ kvCheckpointBytes: r.kv_checkpoint_bytes ?? null,
+ specFixedBytes: r.spec_fixed_bytes ?? null,
+ computeBytes: r.compute_bytes ?? null,
+ contextIsPinned: r.context_is_pinned ?? null,
+ inheritedDevicePin: r.inherited_device_pin ?? null,
+ gpuTotalBytes: r.gpu_bytes ?? null,
+ gpuFloorBytes: r.gpu_floor_bytes ?? null,
+ specUnpriced: r.spec_unpriced === true,
+ };
+ // A 200 that could size nothing arrives down the success path, so
+ // remembering it as a success pinned the row blank for the rest of the
+ // session, which is exactly what FAILURE_TTL_MS exists to stop.
+ remember(cacheKey, estimate, estimateIsUnsized(estimate));
+ return estimate;
+ })
+ // A model we can't size still draws its weights. The miss is remembered
+ // briefly so a long list doesn't retry on every reopen, then expires.
+ .catch(() => {
+ remember(cacheKey, MISS, true);
+ return MISS;
+ })
+ .finally(() => IN_FLIGHT.delete(cacheKey));
+
+ IN_FLIGHT.set(cacheKey, run);
+ return run;
+}
+
+/**
+ * Bar geometry for one row. Pass no source for rows that aren't on disk; the
+ * hook then does nothing and reports "unknown", which draws nothing.
+ */
+export function useModelMemory(
+ source: ModelMemorySource | undefined,
+ gpuGb?: number | null,
+): ModelMemorySegments {
+ // Held with its key so a source change invalidates the old answer by
+ // comparison rather than by clearing state from inside an effect.
+ const [entry, setEntry] = useState<{
+ key: string;
+ estimate: Estimate;
+ } | null>(null);
+ // Opt-in, off by default. Checked here rather than at each render site so a
+ // disabled bar also costs no request.
+ const enabled = useChatRuntimeStore((state) => state.showMemoryBar);
+
+ // Read before the subscription below, because that subscription is not free:
+ // subscribeToConfigChanges watches the whole chat runtime store, which ticks on
+ // every streamed token. Every row in the list mounts this hook, so subscribing
+ // unconditionally meant each token woke every mounted row to re-read a snapshot
+ // it would not use -- including with the feature switched off entirely. Both
+ // branches are module-level constants, so swapping between them resubscribes
+ // once on toggle rather than on every render.
+ // `source` as well as `enabled`: an unselected picker row calls this hook with
+ // no source and can never draw a bar, but it still reached the subscription
+ // and so re-read the epoch -- localStorage included -- on every streamed
+ // token. A long list multiplied each token by the number of mounted rows.
+ const watching = enabled && source != null;
+ const epoch = useSyncExternalStore(
+ watching ? subscribeToConfigChanges : subscribeNothing,
+ watching ? readConfigEpoch : readZeroEpoch,
+ () => 0,
+ );
+
+ // Whether the number the caller handed us is a dedicated VRAM pool at all.
+ // On a Vulkan iGPU the backend reports free shared system RAM minus a host
+ // reserve, so the same model flips between "fits" and "OOM likely" as the
+ // desktop's RAM moves; on Apple the figure is the entire machine's RAM, which
+ // says "fits" for almost anything Metal would refuse. Neither is a VRAM
+ // ceiling, so the bar declines to draw rather than warn against the wrong
+ // pool. Known gap: a ROCm APU reports its whole GTT pool and is not flagged
+ // as shared, which needs a unified-memory signal in hardware.py to fix.
+ const inferenceGpu = useInferenceGpuInfo();
+ const budgetIsDedicatedVram =
+ !inferenceGpu.sharedMemory &&
+ // A ROCm APU reports the GTT/system pool, which moves with host usage and is
+ // not an independent ceiling. The backend classifies these positively; it is
+ // reported as its own field rather than through shared_memory, which the
+ // total and free aggregates already act on.
+ !inferenceGpu.unifiedMemory &&
+ inferenceGpu.backend !== "mlx";
+
+ // The loader's own admission fraction, which the user can change. Cached and
+ // shared, so a long list of rows costs one request.
+ const [budgetFraction, setBudgetFraction] = useState<number | null>(null);
+
+ const repoId = source?.repoId;
+ const quant = source?.quant;
+ const sizeBytes = source?.sizeBytes;
+ const loadId = source?.loadId;
+ // Keyed on primitives rather than the object: callers build the source inline,
+ // so a fresh identity each render would loop forever.
+ const plan = useMemo(() => {
+ // A direct .gguf selection has no quant label and does not need one: the
+ // path names the weights outright and the route resolves such a file to
+ // itself. Requiring a label here suppressed the bar for exactly the custom
+ // and LM Studio models the direct-file support was added for.
+ const isDirectGgufFile = (loadId ?? "").toLowerCase().endsWith(".gguf");
+ if (!enabled || !repoId || (!quant && !isDirectGgufFile)) return null;
+ // Empty rather than undefined past this point: a direct file legitimately
+ // has no label, and the route resolves such a path without one, but every
+ // consumer below wants a string it can key and send.
+ const quantLabel = quant ?? "";
+ const config = configFor({ repoId, quant: quantLabel });
+ const nCtx = pinnedContext(config);
+ const cacheKey = estimateCacheKey({
+ repoId: loadId || repoId,
+ quant: quantLabel,
+ sizeBytes,
+ nCtx,
+ kvCacheDtype: config?.kvCacheDtype,
+ speculativeType: effectiveSpeculativeType(config),
+ nParallel: config?.nParallel,
+ specDraftNMax: config?.specDraftNMax,
+ specDraftCacheType: config?.specDraftCacheDtype,
+ ctxCheckpoints: config?.ctxCheckpoints,
+ disableVision: config?.disableVision,
+ nBatch: config?.nBatch,
+ nUbatch: config?.nUbatch,
+ tensorParallel: config?.tensorParallel,
+ });
+ return {
+ // Identity for the request is the row's own load target; the saved config
+ // is still looked up by repo id, which is how it is keyed.
+ source: { repoId: loadId || repoId, quant: quantLabel },
+ config,
+ nCtx,
+ cacheKey,
+ trustBudget: budgetIsMeaningful(config) && budgetIsDedicatedVram,
+ };
+ // `epoch` is a real dependency the linter cannot see: `configFor` reads
+ // localStorage, and epoch is what changes when that storage does. Folding it
+ // into the cache key instead would evict every row's answer on any save.
+ // biome-ignore lint/correctness/useExhaustiveDependencies: see above
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [enabled, repoId, loadId, quant, sizeBytes, epoch, budgetIsDedicatedVram]);
+
+ // Gated on a real plan, not merely on the feature being on. Every row in the
+ // list mounts this hook, including remote and undownloaded ones that will never
+ // draw a bar, and loadVramBudgetSettings folds only calls that are already in
+ // flight together -- it holds no read-through cache. Gating on `enabled` alone
+ // therefore turned scrolling or filtering a long list into a repeated request
+ // per row that appeared.
+ useEffect(() => {
+ if (!plan) return;
+ let alive = true;
+ const unsubscribe = subscribeVramBudgetSettings((s) => {
+ if (alive) setBudgetFraction(s.fraction);
+ });
+ void loadVramBudgetSettings()
+ .then((s) => {
+ // Null on a backend too old to serve the route; the fallback covers it.
+ if (alive && s) setBudgetFraction(s.fraction);
+ })
+ .catch(() => {
+ // Falls back to the shared headroom ratio, which is what the fit badge
+ // beside the bar already uses.
+ });
+ return () => {
+ alive = false;
+ unsubscribe();
+ };
+ }, [plan]);
+
+ useEffect(() => {
+ if (!plan) return;
+ let alive = true;
+ void fetchEstimate(plan.cacheKey, plan.source, plan.nCtx, plan.config).then(
+ (estimate) => {
+ if (alive) setEntry({ key: plan.cacheKey, estimate });
+ },
+ );
+ return () => {
+ alive = false;
+ };
+ }, [plan]);
+
+ // The dedicated aggregate is the only figure that is VRAM beside system RAM.
+ // Falls back to the supplied total when the inventory reports no shared device
+ // at all, which is the ordinary discrete-card host and the two agree there.
+ const budgetGb =
+ inferenceGpu.dedicatedMemoryTotalGb > 0 &&
+ inferenceGpu.dedicatedMemoryTotalGb < inferenceGpu.memoryTotalGb
+ ? inferenceGpu.dedicatedMemoryTotalGb
+ : gpuGb;
+
+ return useMemo(() => {
+ if (!plan?.trustBudget) return computeModelMemory({});
+ const estimate = entry?.key === plan.cacheKey ? entry.estimate : undefined;
+ // A drafter we could not price is the launch's largest single allocation
+ // (a DSpark sidecar runs to about 11 GB). Charting the rest would read as a
+ // comfortable fit for a load that is nothing of the sort, so draw nothing.
+ if (estimate?.specUnpriced) return computeModelMemory({});
+ // The environment can pin the launch to a subset of the cards the aggregate
+ // budget credits, and an automatic launch preserves that pin. budgetIsMeaningful
+ // can only see browser-side pins and saved config, so this is the one placement
+ // override it cannot reach: without it a 30 GiB model reads as fitting 2x24 GiB
+ // while the child is confined to one of them.
+ if (estimate?.inheritedDevicePin) return computeModelMemory({});
+ const weights = estimate?.weightsBytes ?? source?.sizeBytes;
+ return computeModelMemory({
+ // The projector is resident alongside the weights, so it belongs in that
+ // segment rather than as a fourth sliver the eye cannot resolve.
+ weightsBytes:
+ weights == null ? weights : weights + (estimate?.projectorBytes ?? 0),
+ // Context checkpoints are part of the cache, but llama.cpp keeps those
+ // snapshots in host heap: the load planner's GPU figure is
+ // kv_bytes - kv_checkpoint_bytes. Charged against a VRAM bar they warn OOM
+ // over memory that never reaches the card.
+ kvBytes:
+ estimate?.kvBytes == null
+ ? estimate?.kvBytes
+ : Math.max(0, estimate.kvBytes - (estimate.kvCheckpointBytes ?? 0)),
+ specBytes: estimate?.specBytes,
+ specFixedBytes: estimate?.specFixedBytes,
+ computeBytes: estimate?.computeBytes,
+ gpuTotalBytes: estimate?.gpuTotalBytes,
+ gpuFloorBytes: estimate?.gpuFloorBytes,
+ nCtx: estimate?.nCtx,
+ // The dedicated-only aggregate, never the combined one. On a discrete card
+ // beside a Vulkan iGPU the combined total adds the iGPU's allowance, which
+ // is a capped view of free system RAM, so a model would be judged against
+ // 24 GiB of real VRAM plus whatever the desktop happened not to be using.
+ // `sharedMemory` cannot carry this: it is every(), so a mixed host reads
+ // false and the gate above lets exactly this case through.
+ gpuGb: budgetGb,
+ budgetFraction,
+ // With no pinned context the estimate is sized at the model's native
+ // length, but a default load sends 0 and the loader auto-reduces to the
+ // largest context that fits. Warning OOM for a length it would never have
+ // tried is the false positive this whole bar exists to avoid, so the
+ // verdict softens and only the weights can still fail outright.
+ // The route's answer when it gave one: only a context nobody pinned gets
+ // auto-fitted, and load_model keeps a positive inherited LLAMA_ARG_CTX_SIZE
+ // rather than fitting it. Reading plan.nCtx alone said "auto-fitted" for
+ // that launch, which suppressed the overage AND drew only the irreducible
+ // floor, so an inherited window over budget reported a comfortable fit.
+ contextIsAutoFitted:
+ estimate?.contextIsPinned == null
+ ? plan.nCtx == null
+ : !estimate.contextIsPinned,
+ });
+ }, [plan, entry, source?.sizeBytes, budgetGb, budgetFraction]);
+}
diff --git a/studio/frontend/src/hooks/use-system.ts b/studio/frontend/src/hooks/use-system.ts
index 40a0a5e0ff5..50fab8b097a 100644
--- a/studio/frontend/src/hooks/use-system.ts
+++ b/studio/frontend/src/hooks/use-system.ts
@@ -20,6 +20,8 @@ export interface GpuDevice {
vram_utilization_pct?: number | null;
/** True when the reported GPU budget comes from shared system memory. */
shared_memory?: boolean;
+ /** A unified host pool (ROCm APU): a total, but not a VRAM ceiling. */
+ unified_memory?: boolean;
/** host-backed portion of the shared pool; the rest is reserved GPU memory. */
shared_memory_host_backed_gb?: number | null;
}
diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.ts
index e854fbcde98..55123089e19 100644
--- a/studio/frontend/src/i18n/locales/ar.ts
+++ b/studio/frontend/src/i18n/locales/ar.ts
@@ -1331,6 +1331,9 @@ export const ar = {
showAllQuantizations: "إظهار جميع خيارات التكميم",
showAllQuantizationsDescription:
"عند التفعيل: تُدرج جميع خيارات التكميم ضمن «On Device»، بما فيها الخيارات غير المُنزَّلة. عند التعطيل: لا تظهر إلا خيارات التكميم المُنزَّلة.",
+ showMemoryBar: "إظهار شريط استخدام VRAM",
+ showMemoryBarDescription:
+ "يعرض أسفل صف كل نموذج تم تنزيله الاستخدام التقديري لذاكرة VRAM: الأوزان، وذاكرة KV المؤقتة عند طول السياق الذي سيُحمَّل به، وأي حجز لمسودة فك التشفير التخميني.",
},
menu: {
title: "قائمة المحادثة",
@@ -2353,4 +2356,13 @@ export const ar = {
modelWeights: "أوزان النموذج",
},
},
+ modelMemory: {
+ readout:
+ "الأوزان {model} + السياق {context} = {total} من {budget} من VRAM القابلة للاستخدام",
+ readoutWithSpec:
+ "الأوزان {model} + KV {kv} + مسودة MTP {spec} = {total} من {budget} من VRAM القابلة للاستخدام",
+ kvRate: "KV محجوزة مسبقًا، ~{rate}/توكن",
+ oomLikely: "مع الإعدادات الحالية يُرجَّح نفاد الذاكرة",
+ tooLarge: "أكبر من ذاكرة الرسوميات، وسيُفرَّغ جزء منه إلى المعالج. التكميم الأصغر أسرع",
+ },
} satisfies DeepPartialMessageTree<typeof en>;
diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.ts
index 6e83153b5a1..b43824527bd 100644
--- a/studio/frontend/src/i18n/locales/de.ts
+++ b/studio/frontend/src/i18n/locales/de.ts
@@ -1367,6 +1367,9 @@ export const de = {
showAllQuantizations: "Alle Quantisierungen anzeigen",
showAllQuantizationsDescription:
"Ein: Alle Quantisierungen unter „On Device“ auflisten, auch nicht heruntergeladene. Aus: Nur heruntergeladene Quantisierungen anzeigen.",
+ showMemoryBar: "VRAM-Auslastungsbalken anzeigen",
+ showMemoryBarDescription:
+ "Zeigt unter jeder Zeile eines heruntergeladenen Modells den geschätzten VRAM-Bedarf: Gewichte, KV-Cache bei der Kontextlänge, mit der das Modell geladen wird, und eine eventuelle Reserve für spekulatives Decoding.",
},
menu: {
title: "Chatmenü",
@@ -2420,4 +2423,13 @@ export const de = {
modelWeights: "Modellgewichte",
},
},
+ modelMemory: {
+ readout:
+ "Gewichte {model} + Kontext {context} = {total} von {budget} nutzbarem VRAM",
+ readoutWithSpec:
+ "Gewichte {model} + KV {kv} + MTP-Entwurf {spec} = {total} von {budget} nutzbarem VRAM",
+ kvRate: "KV reserviert, ca. {rate}/Token",
+ oomLikely: "Mit den aktuellen Einstellungen ist ein Speicherüberlauf wahrscheinlich",
+ tooLarge: "Größer als der VRAM, wird auf die CPU ausgelagert. Eine kleinere Quantisierung läuft schneller",
+ },
} satisfies DeepPartialMessageTree<typeof en>;
diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.ts
index b0ff9af7cec..bc7d4156ba3 100644
--- a/studio/frontend/src/i18n/locales/en.ts
+++ b/studio/frontend/src/i18n/locales/en.ts
@@ -1324,6 +1324,9 @@ export const en = {
showAllQuantizations: "Show all quantizations",
showAllQuantizationsDescription:
"On: list every quantization in “On Device”, including not downloaded. Off: show only downloaded quantizations.",
+ showMemoryBar: "Show VRAM usage bar",
+ showMemoryBarDescription:
+ "Chart each downloaded model's estimated VRAM use under its row: weights, KV cache at the context it will load with, and any speculative draft reserve.",
},
menu: {
title: "Chat menu",
@@ -2335,4 +2338,15 @@ export const en = {
modelWeights: "Model weights",
},
},
+ modelMemory: {
+ readout:
+ "Weights {model} + context {context} = {total} of {budget} usable VRAM",
+ readoutWithSpec:
+ "Weights {model} + KV {kv} + MTP draft {spec} = {total} of {budget} usable VRAM",
+ // Measured against llama.cpp: the cache is allocated at context creation,
+ // sized to n_ctx, so the rate is what a longer context actually costs.
+ kvRate: "KV reserved, ~{rate}/token",
+ oomLikely: "With current settings OOM likely",
+ tooLarge: "Larger than VRAM, will offload to CPU. A smaller quantization runs faster",
+ },
} as const;
diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.ts
index 4b8f324157b..42fc4cdb5e8 100644
--- a/studio/frontend/src/i18n/locales/es.ts
+++ b/studio/frontend/src/i18n/locales/es.ts
@@ -1358,6 +1358,9 @@ export const es = {
showAllQuantizations: "Mostrar todas las cuantizaciones",
showAllQuantizationsDescription:
"Activado: muestra todas las cuantizaciones de «On Device», incluidas las que no están descargadas. Desactivado: muestra solo las cuantizaciones descargadas.",
+ showMemoryBar: "Mostrar barra de uso de VRAM",
+ showMemoryBarDescription:
+ "Muestra debajo de la fila de cada modelo descargado su uso estimado de VRAM: pesos, caché KV con la longitud de contexto con la que se cargará y cualquier reserva de borrador especulativo.",
},
menu: {
title: "Menú del chat",
@@ -2417,4 +2420,13 @@ export const es = {
modelWeights: "Pesos del modelo",
},
},
+ modelMemory: {
+ readout:
+ "Pesos {model} + contexto {context} = {total} de {budget} de VRAM utilizable",
+ readoutWithSpec:
+ "Pesos {model} + KV {kv} + borrador MTP {spec} = {total} de {budget} de VRAM utilizable",
+ kvRate: "KV reservado, ~{rate}/token",
+ oomLikely: "Con la configuración actual es probable un error de memoria",
+ tooLarge: "Más grande que la VRAM, se descargará a la CPU. Una cuantización más pequeña es más rápida",
+ },
} satisfies DeepPartialMessageTree<typeof en>;
diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.ts
index 615152a42b8..63ce45247ad 100644
--- a/studio/frontend/src/i18n/locales/fr.ts
+++ b/studio/frontend/src/i18n/locales/fr.ts
@@ -1364,6 +1364,9 @@ export const fr = {
showAllQuantizations: "Afficher toutes les quantifications",
showAllQuantizationsDescription:
"Activé : affiche toutes les quantifications de « On Device », y compris celles qui ne sont pas téléchargées. Désactivé : affiche uniquement les quantifications téléchargées.",
+ showMemoryBar: "Afficher la barre d’utilisation de la VRAM",
+ showMemoryBarDescription:
+ "Affiche sous la ligne de chaque modèle téléchargé son utilisation estimée de la VRAM : poids, cache KV à la longueur de contexte avec laquelle il sera chargé, et toute réserve de brouillon spéculatif.",
},
menu: {
title: "Menu du chat",
@@ -2429,4 +2432,13 @@ export const fr = {
modelWeights: "Poids du modèle",
},
},
+ modelMemory: {
+ readout:
+ "Poids {model} + contexte {context} = {total} sur {budget} de VRAM utilisable",
+ readoutWithSpec:
+ "Poids {model} + KV {kv} + brouillon MTP {spec} = {total} sur {budget} de VRAM utilisable",
+ kvRate: "KV réservé, ~{rate}/token",
+ oomLikely: "Avec les réglages actuels, un dépassement de mémoire est probable",
+ tooLarge: "Plus volumineux que la VRAM, sera déchargé sur le CPU. Une quantification plus petite est plus rapide",
+ },
} satisfies DeepPartialMessageTree<typeof en>;
diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.ts
index 609e36cdd67..0f17c1362c5 100644
--- a/studio/frontend/src/i18n/locales/hi.ts
+++ b/studio/frontend/src/i18n/locales/hi.ts
@@ -1337,6 +1337,9 @@ export const hi = {
showAllQuantizations: "सभी क्वांटाइज़ेशन दिखाएँ",
showAllQuantizationsDescription:
"चालू: “On Device” के सभी क्वांटाइज़ेशन की सूची दिखेगी, जिनमें डाउनलोड न किए गए क्वांटाइज़ेशन भी शामिल हैं। बंद: केवल डाउनलोड किए गए क्वांटाइज़ेशन दिखेंगे।",
+ showMemoryBar: "VRAM उपयोग बार दिखाएँ",
+ showMemoryBarDescription:
+ "हर डाउनलोड किए गए मॉडल की पंक्ति के नीचे उसका अनुमानित VRAM उपयोग दिखाएँ: वेट्स, जिस कॉन्टेक्स्ट लंबाई पर वह लोड होगा उस पर KV कैश, और स्पेकुलेटिव ड्राफ़्ट के लिए आरक्षित मेमोरी।",
},
menu: {
title: "चैट मेन्यू",
@@ -2360,4 +2363,13 @@ export const hi = {
modelWeights: "मॉडल वेट्स",
},
},
+ modelMemory: {
+ readout:
+ "वेट्स {model} + कॉन्टेक्स्ट {context} = {budget} उपयोग-योग्य VRAM में से {total}",
+ readoutWithSpec:
+ "वेट्स {model} + KV {kv} + MTP ड्राफ़्ट {spec} = {budget} उपयोग-योग्य VRAM में से {total}",
+ kvRate: "KV आरक्षित, ~{rate}/टोकन",
+ oomLikely: "मौजूदा सेटिंग्स के साथ मेमोरी कम पड़ सकती है",
+ tooLarge: "VRAM से बड़ा है, CPU पर ऑफ़लोड होगा। छोटा क्वांटाइज़ेशन तेज़ चलता है",
+ },
} satisfies DeepPartialMessageTree<typeof en>;
diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.ts
index 3af4facb312..11e3d66cf0d 100644
--- a/studio/frontend/src/i18n/locales/it.ts
+++ b/studio/frontend/src/i18n/locales/it.ts
@@ -1332,6 +1332,9 @@ export const it = {
showAllQuantizations: "Mostra tutte le quantizzazioni",
showAllQuantizationsDescription:
"Attivata: elenca tutte le quantizzazioni in «On Device», incluse quelle non scaricate. Disattivata: mostra solo le quantizzazioni scaricate.",
+ showMemoryBar: "Mostra la barra di utilizzo della VRAM",
+ showMemoryBarDescription:
+ "Mostra sotto la riga di ogni modello scaricato il consumo stimato di VRAM: pesi, cache KV alla lunghezza di contesto con cui verrà caricato ed eventuale riserva per il draft speculativo.",
},
menu: {
title: "Menu della chat",
@@ -2418,4 +2421,13 @@ export const it = {
modelWeights: "Pesi del modello",
},
},
+ modelMemory: {
+ readout:
+ "Pesi {model} + contesto {context} = {total} di {budget} di VRAM utilizzabile",
+ readoutWithSpec:
+ "Pesi {model} + KV {kv} + draft MTP {spec} = {total} di {budget} di VRAM utilizzabile",
+ kvRate: "KV riservato, ~{rate}/token",
+ oomLikely: "Con le impostazioni attuali è probabile un errore di memoria",
+ tooLarge: "Più grande della VRAM, verrà scaricato sulla CPU. Una quantizzazione più piccola è più veloce",
+ },
} as const;
diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.ts
index 8ee3cff40da..f4bf4d32790 100644
--- a/studio/frontend/src/i18n/locales/ja.ts
+++ b/studio/frontend/src/i18n/locales/ja.ts
@@ -1319,6 +1319,9 @@ export const ja = {
showAllQuantizations: "すべての量子化オプションを表示",
showAllQuantizationsDescription:
"オン: 「On Device」にあるすべての量子化オプションを、未ダウンロードのものも含めて一覧表示します。オフ: ダウンロード済みの量子化オプションのみを表示します。",
+ showMemoryBar: "VRAM 使用量バーを表示",
+ showMemoryBarDescription:
+ "ダウンロード済みモデルの行の下に、推定 VRAM 使用量を表示します。内訳は重み、実際に読み込まれるコンテキスト長での KV キャッシュ、および投機的デコードの下書き用に確保される領域です。",
},
menu: {
title: "チャットメニュー",
@@ -2306,4 +2309,13 @@ export const ja = {
modelWeights: "モデルの重み",
},
},
+ modelMemory: {
+ readout:
+ "重み {model} + コンテキスト {context} = 使用可能な VRAM {budget} 中 {total}",
+ readoutWithSpec:
+ "重み {model} + KV {kv} + MTP 下書き {spec} = 使用可能な VRAM {budget} 中 {total}",
+ kvRate: "KV は事前確保、約 {rate}/トークン",
+ oomLikely: "現在の設定ではメモリ不足になる可能性があります",
+ tooLarge: "VRAM を超えるため CPU にオフロードされます。より小さい量子化の方が高速です",
+ },
} satisfies DeepPartialMessageTree<typeof en>;
diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.ts
index c18a56dcf9a..a31c52761a8 100644
--- a/studio/frontend/src/i18n/locales/ko.ts
+++ b/studio/frontend/src/i18n/locales/ko.ts
@@ -1328,6 +1328,9 @@ export const ko = {
showAllQuantizations: "모든 양자화 표시",
showAllQuantizationsDescription:
"켬: 아직 다운로드하지 않은 항목을 포함해 ‘On Device’의 모든 양자화를 표시합니다. 끔: 다운로드한 양자화만 표시합니다.",
+ showMemoryBar: "VRAM 사용량 막대 표시",
+ showMemoryBarDescription:
+ "다운로드한 모델의 행 아래에 예상 VRAM 사용량을 표시합니다. 가중치, 실제로 로드될 컨텍스트 길이 기준 KV 캐시, 그리고 추측 디코딩 초안용 예약 공간으로 나뉩니다.",
},
menu: {
title: "채팅 메뉴",
@@ -2351,4 +2354,13 @@ export const ko = {
modelWeights: "모델 가중치",
},
},
+ modelMemory: {
+ readout:
+ "가중치 {model} + 컨텍스트 {context} = 사용 가능한 VRAM {budget} 중 {total}",
+ readoutWithSpec:
+ "가중치 {model} + KV {kv} + MTP 초안 {spec} = 사용 가능한 VRAM {budget} 중 {total}",
+ kvRate: "KV 사전 예약, 약 {rate}/토큰",
+ oomLikely: "현재 설정에서는 메모리 부족이 발생할 수 있습니다",
+ tooLarge: "VRAM보다 커서 CPU로 오프로드됩니다. 더 작은 양자화가 더 빠릅니다",
+ },
} satisfies DeepPartialMessageTree<typeof en>;
diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.ts
index f86307eea72..4ad08ab47c6 100644
--- a/studio/frontend/src/i18n/locales/pt-br.ts
+++ b/studio/frontend/src/i18n/locales/pt-br.ts
@@ -1346,6 +1346,9 @@ export const ptBR = {
showAllQuantizations: "Mostrar todas as quantizações",
showAllQuantizationsDescription:
"Ativado: lista todas as quantizações em “On Device”, inclusive as que não foram baixadas. Desativado: mostra apenas as quantizações baixadas.",
+ showMemoryBar: "Mostrar barra de uso de VRAM",
+ showMemoryBarDescription:
+ "Mostra abaixo da linha de cada modelo baixado o uso estimado de VRAM: pesos, cache KV no comprimento de contexto com que será carregado e qualquer reserva de rascunho especulativo.",
},
menu: {
title: "Menu do chat",
@@ -2380,4 +2383,13 @@ export const ptBR = {
modelWeights: "Pesos do modelo",
},
},
+ modelMemory: {
+ readout:
+ "Pesos {model} + contexto {context} = {total} de {budget} de VRAM utilizável",
+ readoutWithSpec:
+ "Pesos {model} + KV {kv} + rascunho MTP {spec} = {total} de {budget} de VRAM utilizável",
+ kvRate: "KV reservado, ~{rate}/token",
+ oomLikely: "Com as configurações atuais, é provável um erro de memória",
+ tooLarge: "Maior que a VRAM, será descarregado para a CPU. Uma quantização menor roda mais rápido",
+ },
} satisfies DeepPartialMessageTree<typeof en>;
diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.ts
index de84af69d74..d9f0d1f7f90 100644
--- a/studio/frontend/src/i18n/locales/ru.ts
+++ b/studio/frontend/src/i18n/locales/ru.ts
@@ -1343,6 +1343,9 @@ export const ru = {
showAllQuantizations: "Показывать все квантизации",
showAllQuantizationsDescription:
"Включено: показываются все квантизации из раздела «On Device», в том числе не скачанные. Выключено: показываются только скачанные квантизации.",
+ showMemoryBar: "Показывать шкалу использования VRAM",
+ showMemoryBarDescription:
+ "Показывает под строкой каждой скачанной модели её ожидаемое потребление VRAM: веса, KV-кеш при той длине контекста, с которой модель будет загружена, и резерв для спекулятивного черновика.",
},
menu: {
title: "Меню чата",
@@ -2380,4 +2383,13 @@ export const ru = {
modelWeights: "Веса модели",
},
},
+ modelMemory: {
+ readout:
+ "Веса {model} + контекст {context} = {total} из {budget} доступной VRAM",
+ readoutWithSpec:
+ "Веса {model} + KV {kv} + черновик MTP {spec} = {total} из {budget} доступной VRAM",
+ kvRate: "KV зарезервирован, ~{rate}/токен",
+ oomLikely: "При текущих настройках вероятна нехватка памяти",
+ tooLarge: "Больше объёма VRAM, часть уйдёт на CPU. Меньшая квантизация работает быстрее",
+ },
} satisfies DeepPartialMessageTree<typeof en>;
diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.ts
index cf593e82dc7..4913557d5e6 100644
--- a/studio/frontend/src/i18n/locales/zh-CN.ts
+++ b/studio/frontend/src/i18n/locales/zh-CN.ts
@@ -1303,6 +1303,9 @@ export const zhCN = {
showAllQuantizations: "显示所有量化版本",
showAllQuantizationsDescription:
"开启:列出“On Device”中的所有量化版本,包括尚未下载的版本。关闭:仅显示已下载的量化版本。",
+ showMemoryBar: "显示显存占用条",
+ showMemoryBarDescription:
+ "在每个已下载模型的行下方显示预计显存占用:权重、按实际加载的上下文长度计算的 KV 缓存,以及推测解码草稿所需的预留。",
},
menu: {
title: "聊天菜单",
@@ -2274,4 +2277,13 @@ export const zhCN = {
modelWeights: "模型权重",
},
},
+ modelMemory: {
+ readout:
+ "权重 {model} + 上下文 {context} = {total},可用显存 {budget}",
+ readoutWithSpec:
+ "权重 {model} + KV {kv} + MTP 草稿 {spec} = {total},可用显存 {budget}",
+ kvRate: "KV 预先分配,约 {rate}/token",
+ oomLikely: "按当前设置可能显存不足",
+ tooLarge: "超出显存,将卸载到 CPU 运行。更小的量化版本速度更快",
+ },
} satisfies DeepPartialMessageTree<typeof en>;
diff --git a/studio/frontend/src/features/hub/lib/gguf-fit.ts b/studio/frontend/src/lib/gguf-fit.ts
similarity index 91%
rename from studio/frontend/src/features/hub/lib/gguf-fit.ts
rename to studio/frontend/src/lib/gguf-fit.ts
index b9e8cd91bc4..bd3374286c8 100644
--- a/studio/frontend/src/features/hub/lib/gguf-fit.ts
+++ b/studio/frontend/src/lib/gguf-fit.ts
@@ -15,8 +15,10 @@ export interface GgufFitInput {
systemRamGb?: number;
}
-/** Fraction of GPU VRAM treated as usable, matching the backend's 0.90 budget. */
-const VRAM_HEADROOM_RATIO = 0.9;
+/** Fraction of GPU VRAM treated as usable, matching the backend's 0.90 budget.
+ * Exported so the picker's memory bar draws its track against the same budget
+ * this classifier judges against. */
+export const VRAM_HEADROOM_RATIO = 0.9;
/** GGUF weights are file size; runtime activations add roughly this fraction. */
const ACTIVATIONS_RATIO = 0.15;
/** Flat KV/context allowance at a typical 4K window. */
diff --git a/studio/frontend/src/lib/model-memory.ts b/studio/frontend/src/lib/model-memory.ts
new file mode 100644
index 00000000000..d9cdb9e8cb8
--- /dev/null
+++ b/studio/frontend/src/lib/model-memory.ts
@@ -0,0 +1,539 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+/**
+ * Splits a downloaded model's VRAM footprint into weights and what the current
+ * settings add on top: KV cache at the context it will load with, plus an MTP
+ * draft reserve when speculative decoding is on.
+ *
+ * They're kept apart because the fixes differ. Oversized weights need a smaller
+ * quant; a total that only overflows once context is added needs a shorter
+ * context or a quantized KV cache.
+ *
+ * Budget matches `gguf-fit.ts` and the backend's `_select_gpus`, so the bar and
+ * the fit badge on a row can't contradict each other.
+ */
+
+import { VRAM_HEADROOM_RATIO } from "@/lib/gguf-fit";
+
+const BYTES_PER_GB = 1024 ** 3;
+
+export interface ModelMemoryInput {
+ /** GGUF weights on disk. Null when the quant could not be resolved. */
+ weightsBytes?: number | null;
+ /** KV cache at the effective context length. */
+ kvBytes?: number | null;
+ /** MTP draft reserve; null for ngram (which is free) or a model without one. */
+ specBytes?: number | null;
+ /**
+ * llama.cpp's compute buffers, from the load planner's own `compute_bytes`.
+ *
+ * Every launch reserves these, and they scale with slots and micro-batch, so a
+ * row near the budget could report a fit while omitting gigabytes the server
+ * allocates. Folded into the KV segment rather than drawn as a fourth sliver:
+ * it is context-linear in part and too small at default settings to resolve on
+ * its own, but it still has to count against the total.
+ */
+ computeBytes?: number | null;
+ /**
+ * The load planner's own GPU-resident total, which supersedes the sum of the
+ * segments when present.
+ *
+ * The segments are assembled here from separate fields and so can only include
+ * what this file knows to ask for; the planner's figure already applies the
+ * inherited environment, resolves companions through the loader's search roots
+ * and counts every buffer. Segment geometry still comes from the individual
+ * terms -- this decides the verdict, not the picture.
+ */
+ gpuTotalBytes?: number | null;
+ /**
+ * What the planner still reserves at the shortest context: drafter weights,
+ * flat compute buffers, recurrent rollback state. None of it shrinks when the
+ * context does, so it is the floor an auto-fitted row is judged against.
+ */
+ gpuFloorBytes?: number | null;
+ /** The share of specBytes a shorter context cannot reduce (drafter weights). */
+ specFixedBytes?: number | null;
+ /** Total VRAM of the GPU the model would load onto. */
+ gpuGb?: number | null;
+ /** Context the KV figure was measured at, for the per-token rate. */
+ nCtx?: number | null;
+ /**
+ * Fraction of that VRAM a load may claim, from /api/settings/vram-budget.
+ * Defaults to VRAM_HEADROOM_RATIO when unknown. This is the loader's own
+ * number and the user can change it, so a bar that hardcodes one warns at a
+ * line admission does not use.
+ */
+ budgetFraction?: number | null;
+ /**
+ * True when no context is pinned, so the loader will auto-fit rather than
+ * open the model's native length. The KV figure is then an upper bound on a
+ * context the load would have reduced, so it cannot justify an OOM verdict.
+ */
+ contextIsAutoFitted?: boolean | null;
+}
+
+/**
+ * How close the total sits to the budget.
+ *
+ * Studio's live meters step at 70/90 (`resources-tab.tsx`), but they show usage
+ * as it happens, where a sustained 70% is worth flagging. This is a reservation
+ * you can see coming, so it holds the accent until 80.
+ */
+export type ModelMemoryPressure = "normal" | "high" | "critical";
+
+/** Fill fraction (%) at which the bar leaves the accent colour. */
+export const PRESSURE_HIGH_PCT = 80;
+/** Fill fraction (%) at which the bar turns destructive. */
+export const PRESSURE_CRITICAL_PCT = 90;
+
+export type ModelMemoryStatus =
+ /** Not enough information to draw anything. */
+ | "unknown"
+ /** Weights + settings both inside the budget. */
+ | "fits"
+ /** Weights fit alone, but the configured context pushes the total over. */
+ | "context-exceeds"
+ /** The weights alone are over budget; context settings cannot save it. */
+ | "model-exceeds";
+
+export interface ModelMemorySegments {
+ status: ModelMemoryStatus;
+ /** Usable VRAM the bar's full width represents. */
+ budgetGb: number;
+ modelGb: number;
+ /** KV cache alone, at the effective context length. */
+ kvGb: number;
+ /** MTP draft reserve. Zero for ngram or a model with no drafter. */
+ specGb: number;
+ totalGb: number;
+ /** Widths as percentages of the track, already clamped to sum <= 100. */
+ modelPct: number;
+ kvPct: number;
+ specPct: number;
+ /** KV cost per token, for judging what a shorter context would save. */
+ kvBytesPerToken: number;
+ /** Total as a percentage of budget; reads above 100 when over. */
+ fillPct: number;
+ pressure: ModelMemoryPressure;
+}
+
+const EMPTY: ModelMemorySegments = {
+ status: "unknown",
+ budgetGb: 0,
+ modelGb: 0,
+ kvGb: 0,
+ specGb: 0,
+ totalGb: 0,
+ modelPct: 0,
+ kvPct: 0,
+ specPct: 0,
+ kvBytesPerToken: 0,
+ fillPct: 0,
+ pressure: "normal",
+};
+
+function toGb(bytes?: number | null): number {
+ return bytes && bytes > 0 ? bytes / BYTES_PER_GB : 0;
+}
+
+/**
+ * Bar geometry and fit status for one row.
+ *
+ * Weights are required, KV is not: a row whose estimate hasn't arrived draws
+ * its weights now and fills in the rest, instead of appearing late.
+ */
+export function computeModelMemory(
+ input: ModelMemoryInput,
+): ModelMemorySegments {
+ const gpuGb = input.gpuGb ?? 0;
+ const modelGb = toGb(input.weightsBytes);
+ if (gpuGb <= 0 || modelGb <= 0) return EMPTY;
+ // The planner says this launch puts nothing on the card. A VRAM bar has
+ // nothing to say about it, and drawing one implies a reservation that is not
+ // going to happen.
+ if (input.gpuTotalBytes === 0) return EMPTY;
+
+ // The loader's own budget when the caller knows it, so the bar warns at the
+ // line admission actually draws. VRAM_HEADROOM_RATIO stays the fallback: it
+ // is what the fit badge on the same row judges against, and it is the only
+ // answer available before the settings request lands.
+ const fraction =
+ input.budgetFraction && input.budgetFraction > 0
+ ? input.budgetFraction
+ : VRAM_HEADROOM_RATIO;
+ const budgetGb = gpuGb * fraction;
+ const kvGb = toGb(input.kvBytes) + toGb(input.computeBytes);
+ const specGb = toGb(input.specBytes);
+ // The planner's total when it gave one, since it accounts for terms these
+ // segments cannot see. Falls back to the sum for a backend too old to send it.
+ const segmentSumGb = modelGb + kvGb + specGb;
+ // Explicitly null-checked, because zero is an answer rather than the absence
+ // of one: inherited placement can make the launch entirely CPU resident, and
+ // `||` would have quietly swapped that for the segment sum and drawn VRAM
+ // pressure for a load that touches no card.
+ const totalGb =
+ input.gpuTotalBytes == null ? segmentSumGb : toGb(input.gpuTotalBytes);
+
+ // Only the weights are a hard verdict: they are what they are. The context
+ // term is a reservation the loader is free to shrink when nothing pinned it,
+ // so an unpinned row that only tips over because of KV reports "fits" rather
+ // than warning about a length the load would never have opened.
+ //
+ // The speculative segment is not wholly context-linear though: a separate
+ // drafter's own weights are resident whatever the context, and no auto-fit can
+ // shrink them. So the hard floor is the weights plus that fixed share -- if
+ // target and drafter weights together do not fit, saying "fits" because the
+ // context is unpinned describes a load that cannot open at any length.
+ // The planner's floor when it gave one: it names every fixed term, including
+ // the flat compute buffer and a Hybrid Mamba target's rollback state, which
+ // the drafter-weights figure alone misses. Both can be several GiB, and both
+ // survive any context reduction, so folding them into the reducible part let
+ // auto-fit suppress an overage nothing could fix.
+ const specFixedGb = toGb(input.specFixedBytes);
+ const irreducibleGb =
+ input.gpuFloorBytes == null
+ ? modelGb + specFixedGb
+ : toGb(input.gpuFloorBytes);
+ const status: ModelMemoryStatus =
+ irreducibleGb > budgetGb
+ ? "model-exceeds"
+ : totalGb > budgetGb && !input.contextIsAutoFitted
+ ? "context-exceeds"
+ : "fits";
+
+ // Clamp to the track, so an oversized model can't push the later segments
+ // out of the row.
+ const modelPct = Math.min(100, (modelGb / budgetGb) * 100);
+ const kvPct = Math.min(100 - modelPct, (kvGb / budgetGb) * 100);
+ const specPct = Math.min(100 - modelPct - kvPct, (specGb / budgetGb) * 100);
+
+ // KV is linear in context above the SWA floor, so the marginal rate is what
+ // says whether a shorter context would actually help.
+ const nCtx = input.nCtx && input.nCtx > 0 ? input.nCtx : 0;
+ const kvBytesPerToken =
+ nCtx > 0 && input.kvBytes && input.kvBytes > 0 ? input.kvBytes / nCtx : 0;
+
+ // Uncapped: widths clamp to the track, but pressure still needs to tell
+ // "just full" from "twice over".
+ //
+ // For an unpinned row the total is priced at the model's NATIVE context while
+ // the loader will reduce that context to fit, so this number is an upper bound
+ // on a length the load would never open. Suppressing only the textual verdict
+ // and leaving the picture alone gave a model that loads perfectly well a full
+ // destructive-red bar and an over-budget readout, which says "this will not
+ // work" louder than the words did. The floor is what the launch cannot avoid
+ // reserving, so it is the honest figure to draw pressure from; when the
+ // planner did not give one, the fill is capped at the budget rather than
+ // invented, since the true fitted total is not known here.
+ const autoFitted = Boolean(input.contextIsAutoFitted);
+ const pressureGb =
+ autoFitted && input.gpuFloorBytes != null
+ ? // The floor alone. Auto-fit sizes the cache to whatever is left, so the
+ // useful signal is how much of the budget is spoken for before the
+ // context gets any: capping the native total at the budget instead just
+ // pins every such row at exactly 100%, which reads as critical for a
+ // load that is fine.
+ Math.min(irreducibleGb, totalGb)
+ : autoFitted
+ ? Math.min(totalGb, budgetGb)
+ : totalGb;
+ const fillPct = (pressureGb / budgetGb) * 100;
+ const pressure: ModelMemoryPressure =
+ fillPct >= PRESSURE_CRITICAL_PCT
+ ? "critical"
+ : fillPct >= PRESSURE_HIGH_PCT
+ ? "high"
+ : "normal";
+
+ return {
+ status,
+ budgetGb,
+ modelGb,
+ kvGb,
+ specGb,
+ kvPct,
+ specPct,
+ kvBytesPerToken,
+ totalGb,
+ modelPct,
+ fillPct,
+ pressure,
+ };
+}
+
+/**
+ * Pass-through llama-server args that decide where the model is placed.
+ *
+ * Exported for the policy tests: these are the flags whose presence means the
+ * VRAM total stops describing the load, so the bar has to abstain exactly as it
+ * does for the equivalent structured controls.
+ */
+export const PLACEMENT_OWNING_ARGS = [
+ // _GPU_LAYER_FLAGS and _FIT_FLAGS
+ "--gpu-layers",
+ "-ngl",
+ "--n-gpu-layers",
+ "--fit",
+ "-fit",
+ // _DEVICE_FLAGS -- all four spellings. `-dev cuda0` on a multi-GPU host
+ // confines the load while the bar was still comparing it with aggregate VRAM.
+ "--device",
+ "-dev",
+ "--main-gpu",
+ "-mg",
+ "--tensor-split",
+ "-ts",
+ "--split-mode",
+ "-sm",
+ // _MOE_OFFLOAD_FLAGS -- the --cpu-moe pair as well as the -ncmoe one
+ "--n-cpu-moe",
+ "-ncmoe",
+ "--cpu-moe",
+ "-cmoe",
+ "--override-tensor",
+ "-ot",
+ "--no-kv-offload",
+ "-nkvo",
+ // _DRAFT_GPU_LAYER_FLAGS and the drafter's own device pin. A drafter pinned
+ // to the CPU is host memory the bar would otherwise charge to the card.
+ "--spec-draft-ngl",
+ "-ngld",
+ "--gpu-layers-draft",
+ "--n-gpu-layers-draft",
+ "--spec-draft-device",
+ // _MMPROJ_OFFLOAD_FLAGS: either spelling is the user taking ownership of
+ // where the projector lands.
+ "--mmproj-offload",
+ "--no-mmproj-offload",
+];
+
+/**
+ * Pass-through args that change the SIZE of the KV cache rather than where it
+ * sits.
+ *
+ * The bar prices the cache from the structured controls alone, so any of these
+ * in the box means the launch reserves something other than what was priced.
+ * `--swa-full` is the sharp one: on a sliding-window model it replaces the
+ * compact window with a full-context cache, which the loader honours at
+ * `_estimate_kv_cache_bytes` via `_swa_full_from_args_or_env`. Pricing the
+ * window and reporting a fit for a launch that allocates the full context is the
+ * exact false "fits" this bar exists to prevent, so it abstains instead.
+ */
+export const KV_SHAPING_ARGS = [
+ "--swa-full",
+ // Turning flash attention off changes the cache layout, not just its size:
+ // _estimate_kv_cache_bytes then pads variable-width V tensors to the
+ // model-wide maximum, which can reserve materially more than the default
+ // enabled layout this estimate prices.
+ "--flash-attn",
+ "-fa",
+ // The loader treats an extras --spec-type as authoritative over the
+ // structured mode, so a config saying "off" can still open an embedded NextN
+ // head. The request carries only the structured mode, so the draft KV and the
+ // target rollback state would both be missing from the total.
+ "--spec-type",
+ "--spec-default",
+ // Draft depth in llama.cpp's spellings as well as Unsloth's: a recurrent
+ // target keeps one rollback state per drafted token, so --draft-max 16 is a
+ // materially different reservation from the structured default.
+ "--spec-draft-n-max",
+ "--draft-max",
+ "--draft-min",
+ // _SPEC_DRAFT_CACHE_K_FLAGS / _SPEC_DRAFT_CACHE_V_FLAGS, every alias. The
+ // structured control sets one dtype for both, so an inherited pair that split
+ // K from V describes a cache this estimate never priced.
+ "--spec-draft-type-k",
+ "--cache-type-k-draft",
+ "-ctkd",
+ "--spec-draft-type-v",
+ "--cache-type-v-draft",
+ "-ctvd",
+ "--kv-unified",
+ "-kvu",
+ "--ctx-size",
+ "-c",
+ "--parallel",
+ "-np",
+ "--batch-size",
+ "-b",
+ "--ubatch-size",
+ "-ub",
+ "--cache-type-k",
+ "-ctk",
+ "--cache-type-v",
+ "-ctv",
+ "--ctx-checkpoints",
+ // _CTX_CHECKPOINTS_FLAGS: --swa-checkpoints is upstream's older spelling.
+ "-ctxcp",
+ "--swa-checkpoints",
+];
+
+/**
+ * Pass-through args that make the launch hold files this estimate never sized.
+ *
+ * A LoRA, a control vector, an explicit projector or a hand-named drafter are
+ * all resident bytes chosen in the extras box, and none of them reach the
+ * planner through the structured settings. Unlike the KV-shaping flags these do
+ * not reshape a term that was priced -- they add one that was not -- so the
+ * total is a floor rather than an answer and the bar abstains.
+ */
+export const RESIDENT_ADDING_ARGS = [
+ // _LOCAL_DRAFT_FLAGS and _HF_DRAFT_FLAGS in full. A hand-named drafter is
+ // weights plus a cache that nothing here priced, and the flags are last-wins,
+ // so any of these spellings means the launch opens one.
+ "--model-draft",
+ "--spec-draft-model",
+ "-md",
+ "--spec-draft-hf",
+ "-hfd",
+ "-hfrd",
+ "--hf-repo-draft",
+ "--lora",
+ "--lora-scaled",
+ "--control-vector",
+ "--control-vector-scaled",
+ "--mmproj",
+ "--model-draft",
+ "-md",
+ "--spec-draft-hf",
+];
+
+/** Whether pass-through args add resident files this estimate did not price. */
+export function extraArgsAddResidentFiles(
+ args: string[] | null | undefined,
+): boolean {
+ if (!args || args.length === 0) return false;
+ return args.some((arg) => RESIDENT_ADDING_ARGS.includes(flagName(arg)));
+}
+
+/** Whether pass-through args resize the KV cache, so the priced figure stops applying. */
+export function extraArgsShapeKvCache(
+ args: string[] | null | undefined,
+): boolean {
+ if (!args || args.length === 0) return false;
+ return args.some((arg) => KV_SHAPING_ARGS.includes(flagName(arg)));
+}
+
+/**
+ * A pass-through token reduced to the flag name the launch will parse.
+ *
+ * Mirrors the backend's `_flag_name`: peel `--key=value`, and normalise
+ * underscores in long options, which llama.cpp accepts interchangeably with
+ * dashes. Without the second step `--gpu_layers` or `--ctx_size` passed every
+ * one of the three predicates below while still changing the real launch, so a
+ * single spelling defeated the whole abstention policy rather than one entry in
+ * one list.
+ */
+function flagName(arg: unknown): string {
+ const token = String(arg ?? "").trim();
+ if (!token.startsWith("-")) return "";
+ const name = token.split("=")[0];
+ return name.startsWith("--") ? name.replace(/_/g, "-") : name;
+}
+
+/** Whether pass-through args decide placement, so the GPU total stops applying. */
+export function extraArgsOwnPlacement(
+ args: string[] | null | undefined,
+): boolean {
+ if (!args?.length) return false;
+ // flagName accepts both "--gpu-layers 0" and "--gpu-layers=0" argv shapes, and
+ // normalises the underscore spelling the launch also accepts.
+ return args.some((raw) => PLACEMENT_OWNING_ARGS.includes(flagName(raw)));
+}
+
+/** The inputs that change an estimate, and so key its cached answer. */
+export interface EstimateCacheKeyParts {
+ repoId: string;
+ quant: string;
+ /** A re-download can change the file under a stable quant name. */
+ sizeBytes?: number | null;
+ /** Undefined means the model's own native length. */
+ nCtx?: number | null;
+ kvCacheDtype?: string | null;
+ speculativeType?: string | null;
+ /** Undefined or non-positive means the server's standing slot count. */
+ nParallel?: number | null;
+ /** Draft depth; zero is a real value (no rollback states), so it is kept. */
+ specDraftNMax?: number | null;
+ specDraftCacheType?: string | null;
+ /** Saved context checkpoints; zero is a real value. */
+ ctxCheckpoints?: number | null;
+ /** Vision off frees the projector, which changes the footprint. */
+ disableVision?: boolean | null;
+ /** Compute buffers scale with these, so they re-key the answer. */
+ nBatch?: number | null;
+ nUbatch?: number | null;
+ tensorParallel?: boolean | null;
+}
+
+/**
+ * Cache key for one estimate.
+ *
+ * Every field the request carries appears here, because two rows that would ask
+ * the backend different questions must not share an answer. The slot count is
+ * the one that is easy to get wrong: an omitted count is not one slot, it is
+ * "whatever the server is configured for", which defaults above one. Joined with
+ * a separator that cannot occur in a normalized repo id or quant label, since a
+ * space can.
+ */
+export function estimateCacheKey(parts: EstimateCacheKeyParts): string {
+ return [
+ parts.repoId,
+ parts.quant,
+ parts.sizeBytes ?? "",
+ parts.nCtx ?? "native",
+ parts.kvCacheDtype ?? "",
+ parts.speculativeType ?? "",
+ parts.nParallel && parts.nParallel > 0 ? parts.nParallel : "server-default",
+ parts.specDraftNMax ?? "default",
+ parts.specDraftCacheType ?? "",
+ parts.ctxCheckpoints ?? "default",
+ parts.disableVision ? "novision" : "",
+ parts.nBatch ?? "default",
+ parts.nUbatch ?? "default",
+ parts.tensorParallel ? "tp" : "",
+ ].join("\x00");
+}
+
+/**
+ * Whether a response says "I could not size this model".
+ *
+ * The route is best-effort: it answers 200 with every field null rather than
+ * failing, so this arrives down the success path. Callers cache it as a failure
+ * so it expires, because the usual cause is a backend that is briefly away, not
+ * a model that can never be sized.
+ */
+export function estimateIsUnsized(estimate: {
+ kvBytes: number | null;
+ weightsBytes: number | null;
+ specBytes: number | null;
+}): boolean {
+ return (
+ estimate.kvBytes === null &&
+ estimate.weightsBytes === null &&
+ estimate.specBytes === null
+ );
+}
+
+/** Compact label for a per-token KV rate, which lands in KB or MB. */
+export function formatKvRate(bytes: number): string {
+ if (bytes <= 0) return "0 KB";
+ const kb = bytes / 1024;
+ if (kb < 1024) return `${kb < 10 ? kb.toFixed(1) : Math.round(kb)} KB`;
+ const mb = kb / 1024;
+ return `${mb < 10 ? mb.toFixed(1) : Math.round(mb)} MB`;
+}
+
+/**
+ * Compact label for the bar's readout ("7.2 GiB").
+ *
+ * GiB, not GB: every figure here is a binary divide. Weights and KV come from
+ * bytes / 1024**3, and gpuGb arrives from the backend as
+ * props.total_memory / 1024**3 with nothing subtracting a budget on the way, so
+ * calling any of them GB overstates each by 7.4% (#9570).
+ */
+export function formatMemoryGb(gb: number): string {
+ if (gb <= 0) return "0 GiB";
+ return `${gb < 10 ? gb.toFixed(1) : Math.round(gb)} GiB`;
+}
diff --git a/studio/frontend/tests/model-memory-arg-alias-parity.test.ts b/studio/frontend/tests/model-memory-arg-alias-parity.test.ts
new file mode 100644
index 00000000000..6a06dad71ff
--- /dev/null
+++ b/studio/frontend/tests/model-memory-arg-alias-parity.test.ts
@@ -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
+
+// The bar abstains when a pass-through arg means the estimate no longer
+// describes the launch. That policy is only as good as its spelling list, and
+// llama.cpp accepts several spellings for most of these flags.
+//
+// Three review rounds in a row found an alias missing here -- -dev, --cpu-moe,
+// --draft-max, -ctkd, --swa-checkpoints -- and each was fixed by appending one
+// more string, which is a fix that lasts until the next alias. So this reads the
+// backend's own frozensets, which are what the launch actually honours, and
+// fails when one of them contains a flag the frontend would not act on.
+//
+// It deliberately does NOT require the two sides to be equal. The frontend lists
+// are a superset by design: they also carry flags no single backend set groups
+// together. The invariant is one-directional -- everything the backend parses in
+// these groups must be recognised here.
+
+import assert from "node:assert/strict";
+import test from "node:test";
+import { readFileSync } from "node:fs";
+
+import { registerBundlerResolver } from "./helpers/kit.ts";
+
+registerBundlerResolver();
+
+const {
+ PLACEMENT_OWNING_ARGS,
+ KV_SHAPING_ARGS,
+ RESIDENT_ADDING_ARGS,
+ extraArgsOwnPlacement,
+ extraArgsShapeKvCache,
+ extraArgsAddResidentFiles,
+} = await import("../src/lib/model-memory.ts");
+
+const BACKEND = new URL("../../backend/", import.meta.url);
+
+/**
+ * The string literals of a `frozenset({...})` assignment in the backend source.
+ *
+ * Parsed rather than imported because there is no Python runtime here, and
+ * duplicated rather than skipped because a test that silently passes when it
+ * cannot find its subject is worse than no test: the miss it is guarding
+ * against looks exactly like success.
+ */
+function frozensetLiterals(source: string, name: string): string[] {
+ const start = source.indexOf(name);
+ assert.ok(start >= 0, `${name} is gone from the backend; update this test`);
+ const open = source.indexOf("frozenset(", start);
+ assert.ok(open >= 0, `${name} is no longer a frozenset literal`);
+ const close = source.indexOf(")", open);
+ const body = source.slice(open, close);
+ const found = [...body.matchAll(/"([^"]+)"/g)].map((m) => m[1]);
+ assert.ok(found.length > 0, `${name} parsed as empty`);
+ return found;
+}
+
+const SERVER_ARGS = readFileSync(
+ new URL("core/inference/llama_server_args.py", BACKEND),
+ "utf8",
+);
+const LLAMA_CPP = readFileSync(
+ new URL("core/inference/llama_cpp.py", BACKEND),
+ "utf8",
+);
+
+test("every placement spelling the launch honours makes the bar abstain", () => {
+ const groups = [
+ ["_DEVICE_FLAGS", SERVER_ARGS],
+ ["_GPU_LAYER_FLAGS", SERVER_ARGS],
+ ["_MOE_OFFLOAD_FLAGS", SERVER_ARGS],
+ ["_DRAFT_GPU_LAYER_FLAGS", LLAMA_CPP],
+ ["_MMPROJ_OFFLOAD_FLAGS", LLAMA_CPP],
+ ] as const;
+ for (const [name, source] of groups) {
+ for (const flag of frozensetLiterals(source, name)) {
+ assert.ok(
+ PLACEMENT_OWNING_ARGS.includes(flag),
+ `${flag} (${name}) is parsed by the launch but not by PLACEMENT_OWNING_ARGS, ` +
+ `so a config using that spelling is charted against a budget it does not use`,
+ );
+ }
+ }
+});
+
+test("every draft-memory spelling the launch honours makes the bar abstain", () => {
+ const groups = [
+ "_SPEC_DRAFT_CACHE_K_FLAGS",
+ "_SPEC_DRAFT_CACHE_V_FLAGS",
+ "_CTX_CHECKPOINTS_FLAGS",
+ ];
+ for (const name of groups) {
+ for (const flag of frozensetLiterals(SERVER_ARGS, name)) {
+ assert.ok(
+ KV_SHAPING_ARGS.includes(flag),
+ `${flag} (${name}) resizes the cache at launch but is not in KV_SHAPING_ARGS`,
+ );
+ }
+ }
+});
+
+test("the batch and ubatch spellings are covered", () => {
+ for (const name of ["_BATCH_FLAGS", "_UBATCH_FLAGS"]) {
+ for (const flag of frozensetLiterals(SERVER_ARGS, name)) {
+ assert.ok(
+ KV_SHAPING_ARGS.includes(flag),
+ `${flag} (${name}) scales the compute buffers but is not in KV_SHAPING_ARGS`,
+ );
+ }
+ }
+});
+
+test("the three policies stay disjoint in intent", () => {
+ // A flag that both moves the load and resizes its cache would be ambiguous
+ // about why the bar abstained. They abstain identically today, so this is
+ // about keeping the reasons legible rather than about behaviour.
+ const resident = new Set(RESIDENT_ADDING_ARGS);
+ for (const flag of PLACEMENT_OWNING_ARGS) {
+ assert.ok(
+ !resident.has(flag),
+ `${flag} is classified as both placement-owning and resident-adding`,
+ );
+ }
+});
+
+test("every drafter-selecting spelling makes the bar abstain", () => {
+ // A hand-named drafter is weights plus a cache nothing here priced, and the
+ // flags are last-wins, so any accepted spelling means the launch opens one.
+ for (const name of ["_LOCAL_DRAFT_FLAGS", "_HF_DRAFT_FLAGS"]) {
+ for (const flag of frozensetLiterals(LLAMA_CPP, name)) {
+ assert.ok(
+ RESIDENT_ADDING_ARGS.includes(flag),
+ `${flag} (${name}) selects a drafter at launch but is not in RESIDENT_ADDING_ARGS`,
+ );
+ }
+ }
+});
+
+test("underscore spellings are classified like their dashed twins", () => {
+ // llama.cpp accepts both, and the backend normalises underscores to dashes
+ // before parsing. Comparing raw tokens let a single spelling slip past ALL
+ // THREE predicates at once, which is a hole in the policy rather than a
+ // missing entry in one list -- so this checks the normalisation, not a list.
+ const cases: [string, (a: string[]) => boolean][] = [
+ ["--gpu_layers", extraArgsOwnPlacement],
+ ["--ctx_size", extraArgsShapeKvCache],
+ ["--spec_draft_hf", extraArgsAddResidentFiles],
+ ];
+ for (const [flag, predicate] of cases) {
+ assert.ok(predicate([flag]), `${flag} was not recognised`);
+ assert.ok(predicate([`${flag}=4`]), `${flag}=4 was not recognised`);
+ // The dashed twin must still work, so normalisation did not replace one
+ // spelling with the other.
+ const dashed = flag.replace(/_/g, "-");
+ assert.ok(predicate([dashed]), `${dashed} stopped being recognised`);
+ }
+ // A short option keeps its underscores: only long options are normalised, so
+ // this must not start matching things that are not flags at all.
+ assert.equal(extraArgsOwnPlacement(["not_a_flag"]), false);
+ assert.equal(extraArgsOwnPlacement(["--temp", "0.7"]), false);
+});
diff --git a/studio/frontend/tests/model-memory-cache-policy.test.ts b/studio/frontend/tests/model-memory-cache-policy.test.ts
new file mode 100644
index 00000000000..491a0b2bbe5
--- /dev/null
+++ b/studio/frontend/tests/model-memory-cache-policy.test.ts
@@ -0,0 +1,184 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// The estimate cache is what stops a long model list costing one metadata read
+// per row, so its key has to be exactly as specific as the request. Two rows
+// that would ask the backend different questions must not share an answer, and
+// a row that could not be sized must not stay blank for the rest of the session.
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { registerBundlerResolver } from "./helpers/kit.ts";
+
+registerBundlerResolver();
+
+const { estimateCacheKey, estimateIsUnsized } = await import(
+ "../src/lib/model-memory.ts"
+);
+
+const BASE = { repoId: "unsloth/gemma-4-12b-it-GGUF", quant: "Q4_K_M" };
+
+test("an omitted slot count is not the same request as an explicit one slot", () => {
+ // The request omits n_parallel when there is no override, and the backend
+ // fills in the server's standing count, which defaults above one. Keying both
+ // as 1 served a single-slot answer to a default-slot row.
+ assert.notEqual(
+ estimateCacheKey({ ...BASE }),
+ estimateCacheKey({ ...BASE, nParallel: 1 }),
+ );
+});
+
+test("a non-positive slot count reads as the server default", () => {
+ const serverDefault = estimateCacheKey({ ...BASE });
+ assert.equal(estimateCacheKey({ ...BASE, nParallel: 0 }), serverDefault);
+ assert.equal(estimateCacheKey({ ...BASE, nParallel: null }), serverDefault);
+ assert.equal(
+ estimateCacheKey({ ...BASE, nParallel: undefined }),
+ serverDefault,
+ );
+});
+
+test("distinct slot counts key apart", () => {
+ assert.notEqual(
+ estimateCacheKey({ ...BASE, nParallel: 1 }),
+ estimateCacheKey({ ...BASE, nParallel: 4 }),
+ );
+});
+
+test("every input that changes the answer changes the key", () => {
+ const base = estimateCacheKey(BASE);
+ const variants = [
+ { ...BASE, sizeBytes: 1 },
+ { ...BASE, nCtx: 4096 },
+ { ...BASE, kvCacheDtype: "q8_0" },
+ { ...BASE, speculativeType: "mtp" },
+ { ...BASE, nParallel: 2 },
+ { ...BASE, quant: "Q5_K_M" },
+ { ...BASE, repoId: "unsloth/other-GGUF" },
+ ];
+ for (const v of variants) {
+ assert.notEqual(estimateCacheKey(v), base);
+ }
+ // and they are all distinct from one another
+ const keys = variants.map(estimateCacheKey);
+ assert.equal(new Set(keys).size, keys.length);
+});
+
+test("a re-download under a stable quant name re-keys", () => {
+ // Same repo and quant, different file: the cached weights would otherwise
+ // outrank the row's fresh size.
+ assert.notEqual(
+ estimateCacheKey({ ...BASE, sizeBytes: 7_000_000_000 }),
+ estimateCacheKey({ ...BASE, sizeBytes: 7_100_000_000 }),
+ );
+});
+
+test("a native-context row is distinct from one pinned to a number", () => {
+ assert.notEqual(
+ estimateCacheKey({ ...BASE }),
+ estimateCacheKey({ ...BASE, nCtx: 131072 }),
+ );
+});
+
+test("the key is stable for the same inputs", () => {
+ assert.equal(
+ estimateCacheKey({ ...BASE, nCtx: 4096, nParallel: 4 }),
+ estimateCacheKey({ ...BASE, nCtx: 4096, nParallel: 4 }),
+ );
+});
+
+test("a 200 that sized nothing counts as unsized", () => {
+ assert.equal(
+ estimateIsUnsized({ kvBytes: null, weightsBytes: null, specBytes: null }),
+ true,
+ );
+});
+
+test("any figure at all means the answer is real", () => {
+ // Weights alone is a real answer: a model whose header cannot be read still
+ // charts its file size, and that must not expire in 30 seconds.
+ assert.equal(
+ estimateIsUnsized({
+ kvBytes: null,
+ weightsBytes: 7 * 1024 ** 3,
+ specBytes: null,
+ }),
+ false,
+ );
+ assert.equal(
+ estimateIsUnsized({ kvBytes: 1, weightsBytes: null, specBytes: null }),
+ false,
+ );
+ assert.equal(
+ estimateIsUnsized({ kvBytes: null, weightsBytes: null, specBytes: 1 }),
+ false,
+ );
+});
+
+test("a zero figure is a measurement, not a missing one", () => {
+ assert.equal(
+ estimateIsUnsized({ kvBytes: 0, weightsBytes: 0, specBytes: 0 }),
+ false,
+ );
+});
+
+// --- settings that must reach the request, and the ones that must suppress it ---
+
+const { extraArgsOwnPlacement, PLACEMENT_OWNING_ARGS } = await import(
+ "../src/lib/model-memory.ts"
+);
+
+test("draft depth and checkpoints key apart, including zero", () => {
+ // Zero is a real choice for both (no rollback states, no checkpoints), so it
+ // must not collapse into "unset" the way a `?? ""` would make it.
+ for (const field of ["specDraftNMax", "ctxCheckpoints"] as const) {
+ const unset = estimateCacheKey({ ...BASE });
+ const zero = estimateCacheKey({ ...BASE, [field]: 0 });
+ const some = estimateCacheKey({ ...BASE, [field]: 16 });
+ assert.notEqual(zero, unset, `${field}: 0 collapsed into unset`);
+ assert.notEqual(some, zero);
+ assert.notEqual(some, unset);
+ }
+});
+
+test("draft cache dtype and vision both re-key", () => {
+ assert.notEqual(
+ estimateCacheKey({ ...BASE, specDraftCacheType: "q8_0" }),
+ estimateCacheKey({ ...BASE }),
+ );
+ assert.notEqual(
+ estimateCacheKey({ ...BASE, disableVision: true }),
+ estimateCacheKey({ ...BASE }),
+ );
+});
+
+test("pass-through args that own placement make the bar abstain", () => {
+ // These are appended after Unsloth's own flags, so they decide where the load
+ // runs and the VRAM total stops describing it.
+ for (const flag of PLACEMENT_OWNING_ARGS) {
+ assert.equal(
+ extraArgsOwnPlacement([flag, "0"]),
+ true,
+ `${flag} did not suppress the bar`,
+ );
+ // The "--flag=value" argv shape has to be recognised too.
+ assert.equal(extraArgsOwnPlacement([`${flag}=0`]), true, `${flag}=0`);
+ }
+});
+
+test("ordinary pass-through args do not suppress the bar", () => {
+ // Sampling and logging flags say nothing about placement.
+ assert.equal(extraArgsOwnPlacement(null), false);
+ assert.equal(extraArgsOwnPlacement(undefined), false);
+ assert.equal(extraArgsOwnPlacement([]), false);
+ assert.equal(extraArgsOwnPlacement(["--temp", "0.7", "--verbose"]), false);
+ // A near-miss must not match on a prefix. `--device-draft` is not a spelling
+ // any parser accepts, so it stays out.
+ assert.equal(extraArgsOwnPlacement(["--device-draft"]), false);
+ // `--gpu-layers-draft` used to be listed here as a near-miss, which was wrong:
+ // it is in the backend's _DRAFT_GPU_LAYER_FLAGS and does own placement, just
+ // the drafter's rather than the target's. A drafter pinned off the GPU is host
+ // memory the bar would otherwise charge to the card.
+ assert.equal(extraArgsOwnPlacement(["--gpu-layers-draft"]), true);
+});
diff --git a/studio/frontend/tests/model-memory-hardware-matrix.test.ts b/studio/frontend/tests/model-memory-hardware-matrix.test.ts
new file mode 100644
index 00000000000..46edeaa64fd
--- /dev/null
+++ b/studio/frontend/tests/model-memory-hardware-matrix.test.ts
@@ -0,0 +1,235 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// The memory bar draws a hard "OOM likely" line against whatever budget it is
+// handed, so what that number means on each host is the whole correctness
+// question. It is not the same quantity everywhere:
+//
+// NVIDIA / Intel / discrete AMD card total, GiB, per device, summed
+// AMD or Intel iGPU on Vulkan FREE shared system RAM minus a host reserve
+// Apple Silicon the entire machine's RAM
+// CPU-only zero
+//
+// Only the first is a VRAM ceiling. These cases pin what the bar does with each
+// of the others, across the four platform keys the backend already
+// distinguishes.
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { registerBundlerResolver } from "./helpers/kit.ts";
+
+registerBundlerResolver();
+
+const { computeModelMemory } = await import("../src/lib/model-memory.ts");
+const { aggregateGpuMemoryTotalGb } = await import("../src/hooks/gpu-vram.ts");
+
+const GB = 1024 ** 3;
+const PLATFORMS = ["linux", "wsl", "win32", "darwin"] as const;
+
+type Device = { memory_total_gb: number; shared_memory?: boolean };
+
+/** One row of the hardware matrix, as /api/system reports it. */
+interface Host {
+ label: string;
+ devices: Device[];
+ backend: string;
+ /** Whether the aggregate is a dedicated VRAM pool the bar may judge against. */
+ dedicated: boolean;
+}
+
+const HOSTS: Host[] = [
+ {
+ label: "NVIDIA single 24 GB",
+ devices: [{ memory_total_gb: 24 }],
+ backend: "cuda",
+ dedicated: true,
+ },
+ {
+ label: "NVIDIA 2x24 GB",
+ devices: [{ memory_total_gb: 24 }, { memory_total_gb: 24 }],
+ backend: "cuda",
+ dedicated: true,
+ },
+ {
+ label: "AMD ROCm discrete 32 GB",
+ devices: [{ memory_total_gb: 32 }],
+ backend: "rocm",
+ dedicated: true,
+ },
+ {
+ label: "Intel XPU 16 GB",
+ devices: [{ memory_total_gb: 16 }],
+ backend: "xpu",
+ dedicated: true,
+ },
+ {
+ label: "AMD Vulkan iGPU (shared)",
+ devices: [{ memory_total_gb: 12, shared_memory: true }],
+ backend: "vulkan",
+ dedicated: false,
+ },
+ {
+ label: "Apple Silicon unified 128 GB",
+ devices: [{ memory_total_gb: 128 }],
+ backend: "mlx",
+ dedicated: false,
+ },
+ {
+ label: "CPU only",
+ devices: [],
+ backend: "cpu",
+ dedicated: false,
+ },
+];
+
+/** The gate the hook applies before it lets the bar draw. */
+function budgetIsDedicatedVram(host: Host): boolean {
+ return (
+ !host.devices.some((d) => d.shared_memory === true) &&
+ host.backend !== "mlx" &&
+ host.devices.length > 0
+ );
+}
+
+for (const platform of PLATFORMS) {
+ for (const host of HOSTS) {
+ test(`${platform} / ${host.label}: the gate matches what the budget means`, () => {
+ assert.equal(
+ budgetIsDedicatedVram(host),
+ host.dedicated,
+ `${host.label} is ${host.dedicated ? "" : "not "}a dedicated VRAM pool`,
+ );
+ });
+ }
+}
+
+test("a shared-memory iGPU never draws, however roomy the pool looks", () => {
+ const host = HOSTS.find((h) => h.label.includes("Vulkan"));
+ assert.ok(host);
+ assert.equal(budgetIsDedicatedVram(host), false);
+ // The figure itself is generous, which is exactly why drawing against it is
+ // dangerous: it is free RAM at probe time and shrinks as the desktop is used.
+ assert.equal(aggregateGpuMemoryTotalGb(host.devices), 12);
+});
+
+test("Apple's unified pool is the whole machine's RAM, so the bar stands down", () => {
+ const host = HOSTS.find((h) => h.label.includes("Apple"));
+ assert.ok(host);
+ assert.equal(budgetIsDedicatedVram(host), false);
+ // Drawn against 128 GB at any sane fraction, a 70 GB model reads "fits" while
+ // Metal's working set would refuse it.
+ const wouldHaveSaid = computeModelMemory({
+ weightsBytes: 70 * GB,
+ gpuGb: aggregateGpuMemoryTotalGb(host.devices),
+ });
+ assert.equal(wouldHaveSaid.status, "fits");
+});
+
+test("a CPU-only host draws nothing rather than warning", () => {
+ const result = computeModelMemory({ weightsBytes: 8 * GB, gpuGb: 0 });
+ assert.equal(result.status, "unknown");
+});
+
+test("multi-GPU reports the sum, which only a tensor-split load may use", () => {
+ const host = HOSTS.find((h) => h.label === "NVIDIA 2x24 GB");
+ assert.ok(host);
+ assert.equal(aggregateGpuMemoryTotalGb(host.devices), 48);
+ // A 30 GB quant "fits" in 48 GB and does not fit on either card alone, which
+ // is why a pin has to suppress the bar rather than rescale it.
+ const summed = computeModelMemory({ weightsBytes: 30 * GB, gpuGb: 48 });
+ const oneCard = computeModelMemory({ weightsBytes: 30 * GB, gpuGb: 24 });
+ assert.equal(summed.status, "fits");
+ assert.equal(oneCard.status, "model-exceeds");
+});
+
+test("a shared pool is counted once, not summed with the dedicated cards", () => {
+ assert.equal(
+ aggregateGpuMemoryTotalGb([
+ { memory_total_gb: 24 },
+ { memory_total_gb: 12, shared_memory: true },
+ { memory_total_gb: 12, shared_memory: true },
+ ]),
+ 36,
+ );
+});
+
+test("the budget follows the loader's fraction, not a hardcoded one", () => {
+ // 0.90 vs the loader's 0.97 default on a 24 GB card is 1.68 GiB of headroom
+ // the loader would have admitted. llama_cpp.py records that 0.90 was tried
+ // and reverted because it dropped 91-94% fits to CPU offload (#5106).
+ // 24 GiB card: 21.6 usable at 0.90, 23.28 at 0.97. A 22 GiB model sits in
+ // the band between them, which is the band that got a false OOM warning.
+ const at90 = computeModelMemory({
+ weightsBytes: 22 * GB,
+ gpuGb: 24,
+ budgetFraction: 0.9,
+ });
+ const at97 = computeModelMemory({
+ weightsBytes: 22 * GB,
+ gpuGb: 24,
+ budgetFraction: 0.97,
+ });
+ assert.equal(at90.status, "model-exceeds");
+ assert.equal(at97.status, "fits");
+});
+
+test("an absent or nonsense fraction falls back to the shared headroom ratio", () => {
+ const fallback = computeModelMemory({ weightsBytes: 8 * GB, gpuGb: 16 });
+ for (const budgetFraction of [null, undefined, 0, -1]) {
+ assert.equal(
+ computeModelMemory({ weightsBytes: 8 * GB, gpuGb: 16, budgetFraction })
+ .budgetGb,
+ fallback.budgetGb,
+ );
+ }
+});
+
+test("a user-narrowed budget is respected", () => {
+ // The fraction is user-settable, so the bar must move with it in both
+ // directions rather than only widening.
+ const narrow = computeModelMemory({
+ weightsBytes: 12 * GB,
+ gpuGb: 24,
+ budgetFraction: 0.5,
+ });
+ assert.equal(narrow.budgetGb, 12);
+ assert.equal(narrow.status, "fits");
+ assert.equal(
+ computeModelMemory({
+ weightsBytes: 13 * GB,
+ gpuGb: 24,
+ budgetFraction: 0.5,
+ }).status,
+ "model-exceeds",
+ );
+});
+
+test("segments never sum past the track on any host in the matrix", () => {
+ for (const host of HOSTS) {
+ const gpuGb = aggregateGpuMemoryTotalGb(host.devices);
+ for (const fraction of [0.5, 0.9, 0.97, 1]) {
+ for (const weights of [1, 8, 64, 512]) {
+ const r = computeModelMemory({
+ weightsBytes: weights * GB,
+ kvBytes: weights * GB,
+ specBytes: weights * GB,
+ gpuGb,
+ budgetFraction: fraction,
+ });
+ const sum = r.modelPct + r.kvPct + r.specPct;
+ assert.ok(sum <= 100.0001, `${host.label}: segments sum to ${sum}`);
+ assert.ok(r.modelPct >= 0 && r.kvPct >= 0 && r.specPct >= 0);
+ for (const v of [r.budgetGb, r.totalGb, r.fillPct]) {
+ assert.ok(Number.isFinite(v), `${host.label}: ${v} is not finite`);
+ }
+ if (r.status === "fits") {
+ assert.ok(
+ r.totalGb <= r.budgetGb,
+ `${host.label}: reported fits while over budget`,
+ );
+ }
+ }
+ }
+ }
+});
diff --git a/studio/frontend/tests/model-memory-opt-in.test.ts b/studio/frontend/tests/model-memory-opt-in.test.ts
new file mode 100644
index 00000000000..0a3ab54ace7
--- /dev/null
+++ b/studio/frontend/tests/model-memory-opt-in.test.ts
@@ -0,0 +1,144 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// The memory bar is opt-in, and that is the whole backwards-compatibility
+// story: an existing install upgrading into this build has no such key in
+// localStorage, so it must read false and the app must behave exactly as it did
+// before. The hook checks the flag before it builds a request, so an install
+// that never opts in also generates no extra traffic.
+//
+// This asserts the source of both, since the default is one boolean and losing
+// it would silently turn a new chart on for every existing user.
+
+import assert from "node:assert/strict";
+import test from "node:test";
+import { readFileSync } from "node:fs";
+
+const SRC = new URL("../src/", import.meta.url);
+
+const STORE = readFileSync(
+ new URL("features/chat/stores/chat-runtime-store.ts", SRC),
+ "utf8",
+);
+const HOOK = readFileSync(new URL("hooks/use-model-memory.ts", SRC), "utf8");
+
+test("the bar is off unless the user turns it on", () => {
+ const key = STORE.match(
+ /CHAT_SHOW_MEMORY_BAR_KEY\s*=\s*"([^"]+)"/,
+ );
+ assert.ok(key, "no CHAT_SHOW_MEMORY_BAR_KEY");
+
+ const hydrate = STORE.match(
+ /showMemoryBar:\s*loadBool\(\s*CHAT_SHOW_MEMORY_BAR_KEY\s*,\s*(true|false)\s*\)/,
+ );
+ assert.ok(hydrate, "showMemoryBar is not hydrated through loadBool");
+ assert.equal(
+ hydrate[1],
+ "false",
+ "an install with no such key would get the bar switched on",
+ );
+});
+
+test("a disabled bar issues no estimate request", () => {
+ // The enabled check has to come before the plan is built, or a user who never
+ // opted in still pays one backend read per visible row.
+ const plan = HOOK.indexOf("const plan = useMemo(");
+ assert.ok(plan > 0, "no plan memo");
+ // The first statement of the memo, so no request is even described when the
+ // feature is off. Searched from the memo rather than from the top of the
+ // file, since the budget effect above it carries its own enabled guard.
+ // Widened from 200 characters: the guard is still the memo's first statement,
+ // but it now carries a comment explaining the direct-.gguf case above it, and
+ // a window sized to the code alone fails on the prose rather than on the
+ // property. Still bounded, so a check buried after real work does not pass.
+ assert.match(
+ HOOK.slice(plan, plan + 600),
+ /if \(!enabled\b/,
+ "the plan memo does not stand down when the bar is disabled",
+ );
+
+ // And the fetch has to be gated on that plan rather than run unconditionally.
+ assert.match(
+ HOOK,
+ /useEffect\(\(\) => \{\s*if \(!plan\) return;/,
+ "the estimate effect does not stand down when there is no plan",
+ );
+});
+
+test("the settings request is gated on a row that will draw a bar", () => {
+ // The VRAM budget lookup is a second request, and its gate is `plan` rather
+ // than `enabled`. That is strictly stronger: the plan memo stands down when the
+ // feature is off, so a plan can only exist when enabled is true, and it also
+ // excludes the remote and undownloaded rows that mount this hook but will never
+ // draw a bar. loadVramBudgetSettings folds together only calls already in
+ // flight -- it keeps no read-through cache -- so gating on the flag alone made
+ // scrolling a long list issue one request per row that appeared.
+ const effect = HOOK.match(
+ /useEffect\(\(\) => \{\s*if \(!plan\) return;[\s\S]*?loadVramBudgetSettings/,
+ );
+ assert.ok(
+ effect,
+ "the vram budget request is not gated on the row having a plan",
+ );
+});
+
+test("Reset All clears the memory-bar opt-in", () => {
+ // The feature's default is off, so a reset that leaves the key behind leaves
+ // the bar switched on while telling the user it restored defaults.
+ const GENERAL_TAB = readFileSync(
+ new URL("features/settings/tabs/general-tab.tsx", SRC),
+ "utf8",
+ );
+ const key = STORE.match(/CHAT_SHOW_MEMORY_BAR_KEY\s*=\s*"([^"]+)"/);
+ assert.ok(key, "no CHAT_SHOW_MEMORY_BAR_KEY");
+ // The reset list spells the key out because importing it would hit an import
+ // cycle and read the constant in its temporal dead zone. That makes drift
+ // possible, which is what this pins.
+ assert.match(
+ GENERAL_TAB,
+ new RegExp(`PREFS_KEYS[\\s\\S]*?"${key[1]}"`),
+ `Reset All does not clear ${key[1]}`,
+ );
+});
+
+test("only a row that could draw a bar watches the runtime store", () => {
+ // The subscription watches the whole chat runtime store, which ticks on every
+ // streamed token, and re-reads the epoch (localStorage included) each time.
+ // Every mounted picker row calls this hook, most with no source at all, so
+ // gating on the opt-in alone multiplied each token by the row count.
+ assert.match(
+ HOOK,
+ /const watching = enabled && source != null;/,
+ "the store subscription is not gated on the row having a source",
+ );
+ assert.match(
+ HOOK,
+ /useSyncExternalStore\(\s*watching \? subscribeToConfigChanges : subscribeNothing/,
+ "the subscription does not stand down for a row that cannot draw",
+ );
+});
+
+test("the session GPU pin moves the config epoch", () => {
+ // budgetIsMeaningful reads selectedGpuIds, but the pin lives in the runtime
+ // store rather than in a saved config, so a preset changes it with no config
+ // write. Without it in the snapshot the store update fires and
+ // useSyncExternalStore suppresses the rerender anyway, leaving a bar drawn
+ // against aggregate VRAM after the launch was pinned to one card.
+ assert.match(
+ HOOK,
+ /pinSignature[\s\S]{0,160}selectedGpuIds/,
+ "the epoch signature ignores the session GPU pin",
+ );
+ // The namespace too: the same ordinals mean different cards under a different
+ // index kind, and the field is selectedGpuIndexKind, not gpuIndexKind.
+ assert.match(
+ HOOK,
+ /selectedGpuIndexKind/,
+ "the epoch signature ignores the pin's index namespace",
+ );
+ assert.match(
+ HOOK,
+ /const prefSignature = [^;]*pinSignature/,
+ "pinSignature is computed but not folded into the epoch signature",
+ );
+});
diff --git a/studio/frontend/tests/model-memory-round5.test.ts b/studio/frontend/tests/model-memory-round5.test.ts
new file mode 100644
index 00000000000..47b1af02239
--- /dev/null
+++ b/studio/frontend/tests/model-memory-round5.test.ts
@@ -0,0 +1,213 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// The frontend half of the round-5 review: three ways the bar reported a
+// confident "fits" for a load that would not fit.
+//
+// Each case here failed before its fix, and each is a false NEGATIVE -- the bar
+// staying quiet when it should warn. That direction matters more than the
+// opposite one: a spurious warning is an annoyance, while a missing one is the
+// whole feature failing silently at the moment it was supposed to earn its keep.
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { registerBundlerResolver } from "./helpers/kit.ts";
+
+registerBundlerResolver();
+
+const { computeModelMemory, extraArgsShapeKvCache } = await import(
+ "../src/lib/model-memory.ts"
+);
+
+const GB = 1024 ** 3;
+
+test("a drafter's fixed weights cannot be auto-fitted away", () => {
+ // 24 GiB card at the default fraction. Target weights fit alone; target plus
+ // an 8 GiB drafter do not, and no shorter context can recover that -- the
+ // drafter's weights are resident whatever the context length is.
+ const segments = computeModelMemory({
+ weightsBytes: 14 * GB,
+ specBytes: 9 * GB,
+ specFixedBytes: 8 * GB,
+ kvBytes: 4 * GB,
+ gpuGb: 24,
+ budgetFraction: 0.9,
+ contextIsAutoFitted: true,
+ });
+ assert.equal(
+ segments.status,
+ "model-exceeds",
+ "auto-fit softening swallowed an overage no context change can fix",
+ );
+});
+
+test("auto-fit still softens a purely context-driven overage", () => {
+ // The counterpart, so the fix above does not simply warn on everything: with
+ // no fixed speculative cost the KV term alone is reducible, and an unpinned
+ // row must stay quiet exactly as it did before.
+ const segments = computeModelMemory({
+ weightsBytes: 14 * GB,
+ kvBytes: 20 * GB,
+ gpuGb: 24,
+ budgetFraction: 0.9,
+ contextIsAutoFitted: true,
+ });
+ assert.equal(segments.status, "fits");
+});
+
+test("context checkpoints are not charged against the card", () => {
+ // llama.cpp keeps SWA checkpoint snapshots in host heap, so a VRAM bar that
+ // counts them warns OOM over memory that never reaches the GPU. Modelled the
+ // way the hook does it: the host share subtracted from the cache figure.
+ const kvBytes = 18 * GB;
+ const kvCheckpointBytes = 12 * GB;
+ const onCard = computeModelMemory({
+ weightsBytes: 6 * GB,
+ kvBytes: kvBytes - kvCheckpointBytes,
+ gpuGb: 24,
+ budgetFraction: 0.9,
+ nCtx: 32768,
+ });
+ const everythingCharged = computeModelMemory({
+ weightsBytes: 6 * GB,
+ kvBytes,
+ gpuGb: 24,
+ budgetFraction: 0.9,
+ nCtx: 32768,
+ });
+ assert.equal(onCard.status, "fits");
+ assert.equal(
+ everythingCharged.status,
+ "context-exceeds",
+ "test is not exercising the difference it claims to",
+ );
+});
+
+test("KV-shaping pass-through args are recognised", () => {
+ // --swa-full replaces a sliding window with a full-context cache, so a bar
+ // priced from the structured controls alone is describing a different load.
+ assert.equal(extraArgsShapeKvCache(["--swa-full"]), true);
+ assert.equal(extraArgsShapeKvCache(["--ctx-size=131072"]), true);
+ assert.equal(extraArgsShapeKvCache(["-ub", "2048"]), true);
+ // Placement flags are a separate category with its own guard; this one must
+ // not claim them, or the two abstention reasons become indistinguishable.
+ assert.equal(extraArgsShapeKvCache(["--verbose"]), false);
+ assert.equal(extraArgsShapeKvCache([]), false);
+ assert.equal(extraArgsShapeKvCache(null), false);
+});
+
+test("a mixed shared-memory host is judged on dedicated VRAM only", () => {
+ // A 24 GiB discrete card beside a Vulkan iGPU reporting 12 GiB of free system
+ // RAM. `sharedMemory` is every(), so it reads false here and the dedicated-vs-
+ // combined choice is the only thing standing between this model and a wrong
+ // verdict: 26 GiB fits the 36 GiB combined figure and does not fit the card.
+ const combined = computeModelMemory({
+ weightsBytes: 26 * GB,
+ gpuGb: 36,
+ budgetFraction: 0.9,
+ });
+ const dedicated = computeModelMemory({
+ weightsBytes: 26 * GB,
+ gpuGb: 24,
+ budgetFraction: 0.9,
+ });
+ assert.equal(combined.status, "fits");
+ assert.equal(
+ dedicated.status,
+ "model-exceeds",
+ "the dedicated-only budget must still refuse a model larger than the card",
+ );
+});
+
+test("a CPU-resident launch draws no VRAM bar", () => {
+ // Inherited placement (LLAMA_ARG_DEVICE=none) makes the planner report zero
+ // GPU bytes. That is an answer, not a missing one, and a `||` fallback used to
+ // swap it for the segment sum and draw pressure for a load that touches no
+ // card at all.
+ const segments = computeModelMemory({
+ weightsBytes: 8 * GB,
+ kvBytes: 2 * GB,
+ gpuTotalBytes: 0,
+ gpuGb: 24,
+ budgetFraction: 0.9,
+ });
+ assert.equal(segments.status, "unknown");
+});
+
+test("the planner's total wins over the segment sum", () => {
+ // The segments are assembled from separate fields and can only include what
+ // this file knows to ask for; the planner's figure already counts the terms it
+ // does not. A total below the sum still has to be taken, or the delegation is
+ // decorative.
+ const segments = computeModelMemory({
+ weightsBytes: 10 * GB,
+ kvBytes: 4 * GB,
+ gpuTotalBytes: 20 * GB,
+ gpuGb: 24,
+ budgetFraction: 0.9,
+ });
+ assert.equal(Math.round(segments.totalGb), 20);
+});
+
+test("KV-shaping recognises the flags that override structured settings", () => {
+ // --flash-attn off changes the cache LAYOUT, and an extras --spec-type beats
+ // the structured speculative mode outright, so both make the priced figure
+ // describe a different launch.
+ assert.equal(extraArgsShapeKvCache(["--flash-attn", "off"]), true);
+ assert.equal(extraArgsShapeKvCache(["-fa", "off"]), true);
+ assert.equal(extraArgsShapeKvCache(["--spec-type", "draft-mtp"]), true);
+ assert.equal(extraArgsShapeKvCache(["--spec-draft-n-max=8"]), true);
+});
+
+test("an auto-fitted row does not paint red for a context it will not open", () => {
+ // Priced at the native context, which the loader will reduce. The textual
+ // verdict was already suppressed; the bar itself was not, so a model that
+ // loads fine showed a full destructive bar and an over-budget readout.
+ const segments = computeModelMemory({
+ weightsBytes: 8 * GB,
+ kvBytes: 40 * GB,
+ gpuFloorBytes: 9 * GB,
+ gpuGb: 24,
+ budgetFraction: 0.9,
+ contextIsAutoFitted: true,
+ });
+ assert.equal(segments.status, "fits");
+ assert.ok(
+ segments.fillPct <= 100,
+ `auto-fitted pressure read ${segments.fillPct}% of budget`,
+ );
+ assert.notEqual(segments.pressure, "critical");
+});
+
+test("a pinned row still reports the pressure it really has", () => {
+ // The counterpart: with a context the user pinned there is no fitting to come,
+ // so an over-budget total must still read as over budget.
+ const segments = computeModelMemory({
+ weightsBytes: 8 * GB,
+ kvBytes: 40 * GB,
+ gpuGb: 24,
+ budgetFraction: 0.9,
+ contextIsAutoFitted: false,
+ });
+ assert.equal(segments.status, "context-exceeds");
+ assert.ok(segments.fillPct > 100);
+ assert.equal(segments.pressure, "critical");
+});
+
+test("a pinned context still warns even when nothing was pinned in the UI", () => {
+ // An inherited LLAMA_ARG_CTX_SIZE is kept by the loader, not fitted, so the
+ // route reports it as pinned. Before that flag existed the frontend read
+ // "auto-fitted" from the absence of a saved context, which both suppressed the
+ // overage and drew only the floor: a comfortable fit for a launch that OOMs.
+ const inherited = computeModelMemory({
+ weightsBytes: 8 * GB,
+ kvBytes: 40 * GB,
+ gpuFloorBytes: 9 * GB,
+ gpuGb: 24,
+ budgetFraction: 0.9,
+ contextIsAutoFitted: false,
+ });
+ assert.equal(inherited.status, "context-exceeds");
+ assert.ok(inherited.fillPct > 100);
+});
diff --git a/studio/frontend/tests/model-memory.test.ts b/studio/frontend/tests/model-memory.test.ts
new file mode 100644
index 00000000000..fffa36e2559
--- /dev/null
+++ b/studio/frontend/tests/model-memory.test.ts
@@ -0,0 +1,224 @@
+// 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 test from "node:test";
+
+import { registerBundlerResolver } from "./helpers/kit.ts";
+
+registerBundlerResolver();
+
+const { computeModelMemory, formatKvRate, formatMemoryGb } = await import(
+ "../src/lib/model-memory.ts"
+);
+
+const GB = 1024 ** 3;
+
+// 16 GB card -> 14.4 GB usable at the shared 0.90 headroom.
+const GPU_GB = 16;
+const BUDGET_GB = 14.4;
+
+test("no GPU or no weights cannot be charted", () => {
+ assert.equal(
+ computeModelMemory({ weightsBytes: 8 * GB, gpuGb: 0 }).status,
+ "unknown",
+ );
+ assert.equal(
+ computeModelMemory({ weightsBytes: null, gpuGb: GPU_GB }).status,
+ "unknown",
+ );
+});
+
+test("weights and context inside the budget report fits", () => {
+ const result = computeModelMemory({
+ weightsBytes: 6 * GB,
+ kvBytes: 2 * GB,
+ gpuGb: GPU_GB,
+ });
+ assert.equal(result.status, "fits");
+ assert.equal(result.modelGb, 6);
+ assert.equal(result.kvGb, 2);
+ assert.equal(result.totalGb, 8);
+ assert.ok(Math.abs(result.budgetGb - BUDGET_GB) < 1e-9);
+});
+
+// The case the warning exists for: nothing wrong with the model, everything
+// wrong with the settings on top of it.
+test("weights fit but context pushes past the budget", () => {
+ const result = computeModelMemory({
+ weightsBytes: 12 * GB,
+ kvBytes: 4 * GB,
+ gpuGb: GPU_GB,
+ });
+ assert.equal(result.status, "context-exceeds");
+});
+
+test("oversized weights are not blamed on the context", () => {
+ const result = computeModelMemory({
+ weightsBytes: 20 * GB,
+ kvBytes: 1 * GB,
+ gpuGb: GPU_GB,
+ });
+ assert.equal(result.status, "model-exceeds");
+});
+
+test("speculative reserve counts toward the context segment", () => {
+ const withoutSpec = computeModelMemory({
+ weightsBytes: 10 * GB,
+ kvBytes: 3 * GB,
+ gpuGb: GPU_GB,
+ });
+ const withSpec = computeModelMemory({
+ weightsBytes: 10 * GB,
+ kvBytes: 3 * GB,
+ specBytes: 2 * GB,
+ gpuGb: GPU_GB,
+ });
+ assert.equal(withoutSpec.status, "fits");
+ assert.equal(withSpec.kvGb + withSpec.specGb, 5);
+ // Turning on speculative decoding is what tips this one over.
+ assert.equal(withSpec.status, "context-exceeds");
+});
+
+test("segments never overflow the track", () => {
+ const result = computeModelMemory({
+ weightsBytes: 13 * GB,
+ kvBytes: 40 * GB,
+ gpuGb: GPU_GB,
+ });
+ assert.ok(result.modelPct + result.kvPct + result.specPct <= 100 + 1e-9);
+ assert.ok(result.kvPct >= 0);
+});
+
+test("an oversized model alone fills the track without a negative context", () => {
+ const result = computeModelMemory({
+ weightsBytes: 50 * GB,
+ kvBytes: 5 * GB,
+ gpuGb: GPU_GB,
+ });
+ assert.equal(result.modelPct, 100);
+ assert.equal(result.kvPct, 0);
+});
+
+test("a missing context estimate still charts the weights", () => {
+ const result = computeModelMemory({
+ weightsBytes: 6 * GB,
+ kvBytes: null,
+ gpuGb: GPU_GB,
+ });
+ assert.equal(result.status, "fits");
+ assert.equal(result.kvGb, 0);
+ assert.ok(result.modelPct > 0);
+});
+
+test("memory labels stay compact", () => {
+ assert.equal(formatMemoryGb(0), "0 GiB");
+ assert.equal(formatMemoryGb(7.24), "7.2 GiB");
+ assert.equal(formatMemoryGb(23.6), "24 GiB");
+});
+
+test("KV and speculative reserve are separate segments", () => {
+ const result = computeModelMemory({
+ weightsBytes: 6 * GB,
+ kvBytes: 2 * GB,
+ specBytes: 1 * GB,
+ gpuGb: GPU_GB,
+ });
+ assert.equal(result.kvGb, 2);
+ assert.equal(result.specGb, 1);
+ // Still summed for callers that draw context as one block.
+ assert.equal(result.kvGb + result.specGb, 3);
+});
+
+test("three segments never overflow the track", () => {
+ const result = computeModelMemory({
+ weightsBytes: 13 * GB,
+ kvBytes: 40 * GB,
+ specBytes: 20 * GB,
+ gpuGb: GPU_GB,
+ });
+ const sum = result.modelPct + result.kvPct + result.specPct;
+ assert.ok(sum <= 100 + 1e-9, `segments summed to ${sum}`);
+ assert.ok(result.specPct >= 0);
+});
+
+test("per-token KV rate derives from the context it was measured at", () => {
+ const result = computeModelMemory({
+ weightsBytes: 6 * GB,
+ kvBytes: 1024 * 1024 * 1024,
+ nCtx: 131072,
+ gpuGb: GPU_GB,
+ });
+ // 1 GiB over 131072 tokens is exactly 8 KiB/token.
+ assert.equal(result.kvBytesPerToken, 8192);
+});
+
+test("no context length means no rate rather than a wrong one", () => {
+ const result = computeModelMemory({
+ weightsBytes: 6 * GB,
+ kvBytes: 2 * GB,
+ gpuGb: GPU_GB,
+ });
+ assert.equal(result.kvBytesPerToken, 0);
+});
+
+test("KV rate labels pick sane units", () => {
+ assert.equal(formatKvRate(0), "0 KB");
+ assert.equal(formatKvRate(6234), "6.1 KB");
+ assert.equal(formatKvRate(1024 * 1024 * 3), "3.0 MB");
+});
+
+test("an unloadable model is flagged, not silently drawn as full", () => {
+ // 184 GB of weights on a 128 GB host: no context setting can rescue this,
+ // so it must still say something rather than rely on a fit badge elsewhere.
+ const result = computeModelMemory({
+ weightsBytes: 184 * GB,
+ kvBytes: 4 * GB,
+ gpuGb: 128,
+ });
+ assert.equal(result.status, "model-exceeds");
+ assert.equal(result.modelPct, 100);
+ assert.equal(result.kvPct, 0);
+ assert.ok(result.totalGb > result.budgetGb);
+});
+
+test("bar holds the accent below 80% of budget", () => {
+ // 14.4 GB budget; 11 GB total is ~76%.
+ const result = computeModelMemory({
+ weightsBytes: 9 * GB,
+ kvBytes: 2 * GB,
+ gpuGb: GPU_GB,
+ });
+ assert.equal(result.pressure, "normal");
+ assert.ok(result.fillPct < 80);
+});
+
+test("bar warns from 80% and turns critical from 90%", () => {
+ const high = computeModelMemory({
+ weightsBytes: 10 * GB,
+ kvBytes: 2 * GB,
+ gpuGb: GPU_GB,
+ });
+ assert.ok(high.fillPct >= 80 && high.fillPct < 90, `got ${high.fillPct}`);
+ assert.equal(high.pressure, "high");
+
+ const critical = computeModelMemory({
+ weightsBytes: 12 * GB,
+ kvBytes: 1 * GB,
+ gpuGb: GPU_GB,
+ });
+ assert.ok(critical.fillPct >= 90, `got ${critical.fillPct}`);
+ assert.equal(critical.pressure, "critical");
+});
+
+test("fill percentage is uncapped so over-budget stays distinguishable", () => {
+ const result = computeModelMemory({
+ weightsBytes: 184 * GB,
+ kvBytes: 4 * GB,
+ gpuGb: 128,
+ });
+ // Widths clamp to the track, but the pressure read must not.
+ assert.ok(result.fillPct > 100, `got ${result.fillPct}`);
+ assert.equal(result.pressure, "critical");
+ assert.equal(result.modelPct, 100);
+});
diff --git a/studio/frontend/tests/vram-total-gib-suffix.test.ts b/studio/frontend/tests/vram-total-gib-suffix.test.ts
index 8d1da75dc0b..6f68d1a49ce 100644
--- a/studio/frontend/tests/vram-total-gib-suffix.test.ts
+++ b/studio/frontend/tests/vram-total-gib-suffix.test.ts
@@ -101,3 +101,26 @@ test("helper-formatted totals pick the GiB helper, not the disk one", () => {
}
}
});
+
+// The memory bar names its own unit rather than going through formatGiB, and it
+// divides by 1024**3 throughout, including the gpuGb it measures against. Listed
+// separately because the check is on its formatter, not on a call site.
+const BINARY_FORMATTERS: [string, string][] = [
+ ["lib/model-memory.ts", "formatMemoryGb"],
+];
+
+test("the memory bar's own formatter names a binary unit", () => {
+ for (const [relative, fn] of BINARY_FORMATTERS) {
+ const source = readFileSync(new URL(relative, SRC), "utf8");
+ const helper = source.match(
+ new RegExp(`export function ${fn}[\\s\\S]*?\\n}`),
+ );
+ assert.ok(helper, `${relative}: no ${fn}`);
+ assert.doesNotMatch(
+ helper[0],
+ /(?<!Gi)B["'`]/,
+ `${relative}: ${fn} labels a binary value with a decimal unit`,
+ );
+ assert.match(helper[0], /GiB/, `${relative}: ${fn} does not suffix GiB`);
+ }
+});