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.

Tighten the comments this PR added (#9825)

Daniel Han69067812020b
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.py
index 7b760f16768..fa48992e14b 100644
--- a/studio/backend/core/inference/llama_cpp.py
+++ b/studio/backend/core/inference/llama_cpp.py
@@ -5000,20 +5000,16 @@ class LlamaCppBackend:
def __init__(self, *, manages_processes: bool = True):
"""``manages_processes = False`` builds an INERT probe.
- The constructor is not free. It reaps orphaned llama-servers, which walks
- every entry in /proc, resolves each candidate's exe and signals the ones it
- recognises, and it registers an atexit handler that holds this instance for
- the life of the process. Both are right for the backend that owns the child.
-
- Neither is right for a probe. The sizing helpers build one only to read a GGUF
- header and evaluate arithmetic, and since the memory-estimate route those
- helpers run on every settings change rather than once per load. Measured on one
- estimate: five constructions, five /proc scans, five atexit handlers -- and the
- handlers are never released, so fifty estimates left 250 of them holding 250
- backends. A panel that prices a load must not be able to kill a server, and a
- slider drag must not leak.
-
- Default is True, so every existing caller keeps the behaviour it has today.
+ The constructor is not free: it reaps orphaned llama-servers, walking /proc,
+ resolving each candidate's exe and signalling the ones it recognises, then
+ registers an atexit handler holding this instance for the life of the process.
+ Both are right for the backend that owns a child, neither for a probe that only
+ reads a header -- and since the memory-estimate route those helpers run on every
+ settings change. Measured on one estimate: five constructions, five /proc scans,
+ five atexit handlers, never released, so fifty estimates left 250 of them
+ holding 250 backends.
+
+ Default True, so every existing caller keeps today's behaviour.
"""
self._process: Optional[subprocess.Popen] = None
self._port: Optional[int] = None
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index a00c46500cf..a3140d65212 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -8145,16 +8145,13 @@ def _gguf_runtime_bytes(
# the heavier scalar hides a paired q4_0 behind an f16.
cache_type_for_budget = max(planned_cache_types, key = _kv_bytes_per_elem)
cache_type_for_scratch = _planned_scratch_cache_type(cache_type_kv, llama_extra_args)
- # A quantized V cache is the one layout where flash attention is not a
- # choice: llama.cpp turns it on itself (llama-context.cpp, "enabling
- # flash_attn since it is required for quantized V cache") and refuses the
- # load without it -- the same abort _tensor_quant_kv_unsupported_binary
- # already documents as "V cache quantization requires flash_attn". Charging
- # flash_attn = False there is not conservative, it prices a launch that
- # cannot happen: the False arm pads V to f16, so the whole quantized saving
- # on the V axis is charged back. Measured against llama-server b10632,
- # Qwen3-0.6B at 32k with -ctk/-ctv q4_0: 2296 MiB reserved against 1008 MiB
- # allocated, identical on the CPU and Vulkan builds.
+ # A quantized V cache is the one layout where flash attention is not a choice:
+ # llama.cpp turns it on itself ("enabling flash_attn since it is required for
+ # quantized V cache") and refuses the load without it. flash_attn = False there
+ # is not conservative, it prices a launch that cannot happen -- the False arm
+ # pads V to f16 and charges the whole quantized saving back. Measured on
+ # llama-server b10632, Qwen3-0.6B at 32k with -ctk/-ctv q4_0: 2296 MiB reserved
+ # against 1008 MiB allocated, identical on the CPU and Vulkan builds.
planned_v_type = planned_cache_types[1]
v_forces_flash_attn = planned_v_type not in {"f16", "bf16", "f32"}
# the loader raises --batch-size to max(slots, 2) before launch, and llama.cpp
@@ -8443,12 +8440,11 @@ def _remote_gguf_compute_reserve_gb(
budget_ctx = ctx if ctx > 0 else effective_ubatch
devices = max(1, int(n_devices))
# A multi-device layer split materialises the KQ mask _CTX_COMPUTE_SPLIT_MULT
- # times, the same step _compute_buffer_ctx_bytes applies locally; charging
- # the single-copy rate under-reserved 4x. Tensor mode is already correct
- # (measured at the single-device rate, replicated per device). n_layers is
- # None here: the header is unread, so -ngl cannot be resolved, but -ot /
- # -ncmoe / --no-kv-offload / -sm none still register. Without this gate the
- # same model 409s while remote and loads once cached.
+ # times, as _compute_buffer_ctx_bytes applies locally; the single-copy rate
+ # under-reserved 4x. Tensor mode is already correct. n_layers is None here --
+ # the header is unread, so -ngl cannot be resolved -- but -ot / -ncmoe /
+ # --no-kv-offload / -sm none still register. Without this gate the same model
+ # 409s while remote and loads once cached.
from core.inference.llama_cpp import _pipeline_parallel_disabled_by_args
split_mult = (
@@ -8466,18 +8462,15 @@ def _remote_gguf_compute_reserve_gb(
* devices
* split_mult
)
- # The mask is only the context-linear half. The flat half needs the dims,
- # which are unreadable remotely, but its dominant term needs just a vocab
- # ceiling: llama.cpp reserves n_vocab * ubatch * 4 per slot past the first
- # (every slot under tensor mode), so n_batch = n_ubatch = 32768 on two
- # slots is ~32 GiB the mask does not cover. Omitting it let the guard admit
- # an uncached load that then OOMs the training job it exists to protect.
- # The activation scratch needs embedding_length and stays uncharged: it is
- # the small half, and over-reserving here denies the load outright.
- # Scaled per device only in tensor mode, mirroring the local branch: a
- # layer split folds the flat buffer in once (_flat_buffer(False)), and
- # only tensor mode replicates it on every card.
- # The remote header is unknown, so reserve as if it enables embeddings.
+ # The mask is only the context-linear half. The flat half needs dims that are
+ # unreadable remotely, but its dominant term needs only a vocab ceiling:
+ # llama.cpp reserves n_vocab * ubatch * 4 per slot past the first (every slot
+ # under tensor mode), so n_batch = n_ubatch = 32768 on two slots is ~32 GiB the
+ # mask does not cover, and omitting it let the guard admit an uncached load that
+ # then OOMs the training job. The activation scratch needs embedding_length and
+ # stays uncharged: the small half, and over-reserving denies the load outright.
+ # Scaled per device only in tensor mode, mirroring the local branch. The remote
+ # header is unknown, so reserve as if it enables embeddings.
_out_slots = max(1, n_parallel)
out_buffer_bytes = (
_ASSUMED_MAX_VOCAB
@@ -8618,15 +8611,12 @@ def _estimate_gguf_required_gb(
or (_forced_dflash and not _dflash_capable)
# Three modes return out of _build_speculative_flags before any
# --model-draft is emitted: "off" immediately, "ngram-simple" and "ngram"
- # after their --spec-type alone. A model that ships an MTP sidecar was
- # still billed for it in every one of them, so turning speculation OFF
- # could add a multi-GiB drafter to the estimate. Same reasoning the DSpark
- # and DFlash branches already apply to a binary that cannot run them.
+ # after their --spec-type. A model shipping an MTP sidecar was billed for it
+ # in all three, so turning speculation OFF could add a multi-GiB drafter --
+ # the same reasoning the DSpark and DFlash branches already apply.
#
- # Only when the extras have not taken speculation over. `--spec-type
- # draft-dspark` in Advanced Arguments opens the sidecar whatever the panel
- # field says, so reading the field alone here stopped charging a drafter
- # the launch does load.
+ # Only where the extras have not taken speculation over: `--spec-type
+ # draft-dspark` opens the sidecar whatever the panel field says.
or (_spec_mode in _SPEC_MODES_WITHOUT_A_DRAFTER and not _extra_args_own_spec)
)
@@ -8649,13 +8639,12 @@ def _estimate_gguf_required_gb(
# Only the drafter the launch will load: the modes are exclusive, and a
# 10 GB DSpark sidecar merely sitting on disk must not inflate the guard
# for a load that never opens it.
- # Vision off means llama_cpp.py resolves no projector, so the guard must not
+ # Vision off means llama_cpp.py resolves no projector, and the guard must not
# refuse a chat load over bytes it provably does not take -- a constrained
- # machine is where the switch gets used and where this guard bites. But the
- # loader keeps an AUDIO-ONLY projector despite the switch, and dropping the
- # bytes of one that does get opened would admit a load the running training job
- # cannot afford. So ask the loader's own question of the same file, which is on
- # disk here. Same gate as the remote branch's include_mmproj below.
+ # machine is where the switch gets used. But the loader keeps an AUDIO-ONLY
+ # projector despite the switch, and dropping bytes that do get opened would
+ # admit a load the running training job cannot afford, so ask the loader's own
+ # question of the file. Same gate as the remote branch's include_mmproj.
_sized_attrs = ["gguf_mmproj_file"]
# Whether the CONFIGURED projector is one this launch opens. Bound before the
# switch so the inherited-projector gate below can read it either way.
@@ -8725,31 +8714,28 @@ def _estimate_gguf_required_gb(
total_bytes += LlamaCppBackend._get_gguf_size_bytes(str(f))
_sized_keys.add(_same_file_key(str(f)))
- # A caller that owns speculation through llama_extra_args names the
- # drafter with --model-draft. load_model hands that path to llama-server,
- # so it has to be charged, but it is charged exactly once: the same file
- # is often the local sidecar discovery already put in gguf_dflash_file /
- # gguf_dspark_file / gguf_mtp_file, and adding it twice billed a 1.5 GiB
- # drafter as 3 GiB and refused loads that fit. When the drafter really is
- # outside the model directory nothing above named it and the charge lands
- # here. It is a companion either way, never evidence of a local main
- # weight, so it does not decide which branch below produces the estimate:
- # a remote repo with a local --model-draft still has to price its weights
- # through the listing, and returning the drafter alone under-estimated a
- # load by the whole target model.
- # A remote one (--spec-draft-hf / -hfd names a repo, never a file) is charged
- # from its OWN listing: the target's companion scan never sees it, so a target
- # shipping no sidecar left a multi-GB drafter billed nowhere.
+ # A caller owning speculation through llama_extra_args names the drafter with
+ # --model-draft, which load_model hands to llama-server, so it is charged --
+ # exactly once. That file is often the same one sidecar discovery already put
+ # in gguf_dflash_file / gguf_dspark_file / gguf_mtp_file, and billing it twice
+ # made a 1.5 GiB drafter 3 GiB and refused loads that fit; outside the model
+ # directory nothing above named it and the charge lands here.
+ #
+ # A companion either way, never evidence of a local main weight, so it does not
+ # decide the branch below: a remote repo with a local --model-draft still
+ # prices its weights through the listing. A remote drafter (--spec-draft-hf
+ # names a repo, never a file) is charged from its own listing, since the
+ # target's companion scan never sees it.
_extras_bytes = 0
- # The value AND which flag carried it. Draft flags are last-wins, so a repo
- # id followed by a path leaves a path as the drafter, and pricing that path
- # as a repository would charge a reserve for something that never loads.
+ # The value AND which flag carried it: draft flags are last-wins, so a repo id
+ # followed by a path leaves a path, and pricing that as a repository charges a
+ # reserve for something that never loads.
_extras_draft, _extras_draft_is_remote = _extra_args_mtp_draft_source(
llama_extra_args, env = {}
)
- # A host-memory drafter competes for RAM, not for the training job's VRAM.
- # Charging it is not a safe over-estimate, it is the wrong resource, and it
- # 409s a load that takes no VRAM for the drafter at all.
+ # A host-memory drafter competes for RAM, not the training job's VRAM. Charging
+ # it is the wrong resource, not a safe over-estimate, and 409s a load that takes
+ # no drafter VRAM at all.
if _extra_args_draft_offloaded_to_cpu(llama_extra_args, env = os.environ):
_extras_bytes = 0
elif _extras_draft and Path(_extras_draft).is_file():
@@ -8762,30 +8748,25 @@ def _estimate_gguf_required_gb(
# A projector this config never named: llama-server reads LLAMA_ARG_MMPROJ
# straight into params.mmproj.path, so an inherited one loads and takes VRAM
- # that nothing above charged. Two things stop it, and only two. Unsloth's own
- # --mmproj overrides the env, argv being applied after set_env, so exactly one
- # file loads and charging both bills one projector twice. And under the vision
- # switch the loader keeps only an audio-only file, asked through the loader's
- # own helper so the two cannot answer differently.
+ # nothing above charged. Exactly two things stop it. Unsloth's own --mmproj
+ # overrides the env (argv is applied after set_env), so one file loads and
+ # charging both bills a projector twice; and under the vision switch the loader
+ # keeps only an audio-only file, asked through the loader's own helper.
#
- # NOT the extras opt-out on its own. --no-mmproj / --no-mmproj-auto set
- # params.no_mmproj, which stops Unsloth resolving a projector of its own and
- # stops the HF auto-download, but server-context.cpp gates the load on a
- # non-empty mmproj.path and never reads that field. So an inherited path loads
- # straight through the opt-out. What the opt-out does do is empty the command
- # line, which is why it feeds _studio_mmproj_on_argv rather than this gate.
+ # NOT the extras opt-out on its own: --no-mmproj sets params.no_mmproj, which
+ # stops Unsloth resolving one and stops the HF auto-download, but
+ # server-context.cpp gates the load on a non-empty mmproj.path and never reads
+ # that field, so an inherited path loads straight through it. What it does do is
+ # empty the command line, which is why it feeds _studio_mmproj_on_argv.
#
- # Added to the return rather than to total_bytes, which decides local-vs-remote
- # above and must stay the main weight's verdict. The remote branch charges the
- # repo's own projector instead; an inherited local file alongside a remote repo
- # is charged nowhere, as before this.
+ # Added to the return, not to total_bytes, which decides local-vs-remote above
+ # and must stay the main weight's verdict. The remote branch charges the repo's
+ # own projector; an inherited local file beside a remote repo is charged
+ # nowhere, as before.
#
- # argv overrides the env, but only when there IS argv: a configured projector
- # the switch suppressed, or extras that skipped the resolve, both leave the
- # command line empty and let the inherited path load after all. So this asks
- # what Unsloth actually emits, not merely what the config names -- the same
- # answer _sized_attrs above was built from, so the two cannot disagree about
- # which single projector this launch opens.
+ # argv overrides the env only when there IS argv -- a suppressed projector or
+ # extras that skipped the resolve both leave it empty and let the inherited path
+ # load -- so this asks what Unsloth emits, not what the config names.
_studio_mmproj_on_argv = bool(
getattr(config, "gguf_mmproj_file", None) and _dv_opens_projector
)
@@ -8929,27 +8910,20 @@ def _gguf_offloaded_layer_fraction(
) -> float:
"""Share of the weights the requested offload keeps on the GPU, in [0, 1].
- Auto is 1.0: it asks llama.cpp to fit the whole model, so the useful number to
- show is what a successful load costs.
-
- A count in the extras wins in either mode, by two different routes: Auto emits
- ``-ngl -1`` and appends the extras after it, so the user's count last-wins at the
- child, and Manual translates that same count into the load field before stripping
- the raw flag. Pricing the field alone read ``--gpu-layers 0`` with ``-ngl 999``
- as a CPU-only load.
+ Auto is 1.0: it asks llama.cpp to fit the whole model. Manual scales
+ ``--gpu-layers`` over ``block_count + 1``, the ceiling the slider uses. A count in
+ the extras wins in either mode -- Auto appends them after its own ``-ngl -1`` and
+ Manual folds them into the field -- so pricing the field alone read
+ ``--gpu-layers 0 -ngl 999`` as CPU-only.
- Manual scales by ``--gpu-layers`` over ``block_count + 1``, the ceiling the
- slider uses (the extra one is the output layer). ``--n-cpu-moe`` is NOT modelled
- -- it moves individual expert tensors, not whole blocks -- so a manual MoE
- offload reads high here, which the panel says out loud.
+ ``--n-cpu-moe`` is NOT modelled: it moves expert tensors, not whole blocks, so a
+ manual MoE offload reads high here, which the panel says out loud.
"""
from core.inference.llama_cpp import _device_selection_is_cpu
from core.inference.llama_server_args import parse_gpu_layers_override
- # A --device naming no GPU beats every layer count: llama.cpp then runs on the CPU
- # whatever -ngl says, which is why the loader's own residency gate asks this first.
- # Read through the same predicate, and with the env twin the child inherits, so the
- # panel and the launch cannot disagree about where the weights land.
+ # A --device naming no GPU beats every layer count, so the loader's residency gate
+ # asks this first. Same predicate and same env twin here, or the two disagree.
if not device_pin_governs and (
_device_selection_is_cpu(extras, os.environ) or _estimate_host_has_no_gpu()
):
@@ -8963,15 +8937,12 @@ def _gguf_offloaded_layer_fraction(
if override is not None:
gpu_layers = override
elif gpu_memory_mode != "manual":
- # Auto emits no -ngl on the fitting path, so an inherited
- # LLAMA_ARG_N_GPU_LAYERS is the only layer policy the child sees, and
- # llama.cpp's fitter will not overrule it: common/fit.cpp:463 throws
- # "n_gpu_layers already set by user" on any value the user really set, and
- # the caller downgrades that to a warning, so the launch proceeds with the
- # count as given. -1 and auto are its own default and leave the fitter free,
- # which is why _env_fixes_gpu_layers excludes them. The loader has consulted
- # this since the placement gate at llama_cpp.py:9156; the panel did not, and
- # answered 1.0 for a launch running a prefix of the weights out of host RAM.
+ # Auto emits no -ngl, so an inherited LLAMA_ARG_N_GPU_LAYERS is the only layer
+ # policy the child sees and the fitter will not overrule it: fit.cpp:463 throws
+ # "n_gpu_layers already set by user", downgraded to a warning, and the launch
+ # proceeds with the count as given. -1 and auto are its own default, which is
+ # why _env_fixes_gpu_layers excludes them. The panel answered 1.0 for a launch
+ # running a prefix of the weights out of host RAM.
from core.inference.llama_cpp import _env_fixes_gpu_layers
if not _env_fixes_gpu_layers(os.environ):
return 1.0
@@ -8984,12 +8955,10 @@ def _gguf_offloaded_layer_fraction(
if gpu_layers is None or gpu_layers < 0:
return 1.0
if gpu_layers == 0:
- # Zero needs no denominator, so this answers before the layer count is
- # consulted. A header that yields no dims leaves layer_count None, and
- # falling through to the shrug below reported a manual --gpu-layers 0 as a
- # fully GPU-resident load: the exact opposite of what was asked for, and in
- # the direction that says fits. The count is a scale factor for a partial
- # offload; an explicit none is not a partial offload.
+ # Answers before the layer count, which zero does not need. An unreadable
+ # header leaves it None, and the shrug below then called a manual
+ # --gpu-layers 0 fully GPU-resident: the opposite of what was asked, in the
+ # direction that says fits. An explicit none is not a partial offload.
return 0.0
if not layer_count or layer_count <= 0:
# No dims to scale against; 1.0 keeps it consistent with Auto.
@@ -9001,23 +8970,15 @@ def _probe_backend():
"""A header-reading LlamaCppBackend that owns no child process.
``manages_processes = False`` skips the orphan reap and the atexit registration,
- which is what makes this safe to run on every settings change. See the flag's own
- docstring for the measurements.
-
- The fallback matters as much as the flag. Tests and callers substitute
- ``LlamaCppBackend`` wholesale -- two stand-ins in
- ``test_chat_load_during_training.py`` are plain classes taking no arguments -- and a
- new keyword would break every one of them at construction rather than at the
- behaviour it controls. A stand-in that predates the flag has no reaper to suppress
- anyway, so falling back to the bare constructor is both compatible and correct.
-
- Only an UNSUPPORTED KEYWORD may take that fallback, which is why the signature is
- asked rather than the exception trusted. A TypeError raised from inside a
- constructor BODY lands in the same except, and the bare constructor it would fall
- back to is the process-reaping one: a fault would be answered by walking /proc and
- signalling the llama-servers it recognises, silently, on a route the settings panel
- fires on every change. That cannot be told apart from the compatible case by the
- exception type, so it is told apart by whether the class can bind the keyword.
+ which is what makes this safe on every settings change.
+
+ The fallback is for stand-ins that predate the keyword: callers substitute
+ ``LlamaCppBackend`` wholesale, and such a stand-in has no reaper to suppress
+ anyway. Only an unsupported KEYWORD may take it, which is why the signature is
+ bound rather than the exception trusted -- a TypeError from inside the constructor
+ body lands in the same except, and the bare constructor it falls back to is the
+ process-reaping one, so a fault would be answered by silently walking /proc and
+ signalling llama-servers on a route the panel fires on every change.
"""
import inspect
try:
@@ -9122,29 +9083,21 @@ def _estimate_disk_residency(model_identifier: str) -> str:
def _estimate_target_is_on_this_disk(model_identifier: str) -> bool:
- """Whether this identifier could possibly be priced without leaving the machine.
-
- A local path always can: the resolution reads it off disk. A remote repo id can
- only if it is already in an HF cache, because a repo that is not there answers
- ``not_downloaded`` whatever the resolution finds -- so resolving it can produce
- nothing the route will use, while a full identification walks to the Hub and
- caches what it fetches.
-
- Checked across EVERY cache root Studio scans, not just the configured one. A repo
- downloaded under the legacy or default root would otherwise read as absent and the
- row would vanish for a model that is sitting right there, which is a worse failure
- than the round trip this avoids.
-
- Fail-open on any error: a cache root that cannot be established must not turn into
- a blanket ``not_downloaded``, so an unanswerable question falls through to the
- resolution that was happening before. What it must NOT fall through to is the
- network -- see ``_estimate_disk_residency``, which keeps "yes" and "cannot tell"
- apart for the caller that decides that.
-
- A root that exists but cannot be READ is not one of those errors:
- ``_iter_hf_cache_snapshots`` swallows the ``PermissionError`` and reports the repo
- absent, so that case answers False and is refused. Safe, and the opposite of what
- the paragraph above would lead a reader to expect.
+ """Whether this identifier could be priced without leaving the machine.
+
+ A local path always can. A remote repo id only if it is already in an HF cache,
+ since one that is not answers ``not_downloaded`` whatever the resolution finds,
+ while a full identification walks to the Hub and caches what it fetches.
+
+ Every cache root Studio scans, not just the configured one: a repo under the
+ legacy root would read as absent and the row would vanish for a model sitting
+ right there.
+
+ Fail-open on error, so an unanswerable question falls through to the resolution
+ that was happening before -- but never to the network; ``_estimate_disk_residency``
+ keeps "yes" and "cannot tell" apart for the caller that decides that. An
+ unreadable root is not one of those errors: ``_iter_hf_cache_snapshots`` swallows
+ the PermissionError and reports absent, so that case answers False.
"""
return _estimate_disk_residency(model_identifier) != _ESTIMATE_DISK_ABSENT
@@ -9152,16 +9105,12 @@ def _estimate_target_is_on_this_disk(model_identifier: str) -> bool:
def _estimate_hf_cache_roots() -> list:
"""Every HF cache root to look in, or [] if that cannot be established.
- Two tiers on purpose. ``hf_cache_roots`` is the authority and the same list the
- rest of Studio scans, but it reaches through ``hub.utils.paths`` into the logging
- stack, and a caller that cannot complete that import would get an empty list and,
- through the fail-open above, a check that quietly does nothing. A check that is
- silently inert is worse than one that is absent, because it still reads as present.
-
- So fall back to the two roots that can be established without leaving
- ``huggingface_hub`` and this package's own settings. That loses the legacy root,
- which is the honest cost of the degraded path, and is recorded here rather than in
- a comment somewhere else.
+ Two tiers on purpose. ``hf_cache_roots`` is the authority, but it reaches through
+ ``hub.utils.paths`` into the logging stack, and a caller that cannot complete that
+ import would get [] and, through the fail-open above, a check that is silently
+ inert -- worse than an absent one, because it still reads as present. So fall back
+ to the two roots reachable from ``huggingface_hub`` and this package's settings,
+ losing the legacy root, which is the honest cost of the degraded path.
"""
try:
from hub.utils.hf_cache_state import hf_cache_roots
@@ -9284,16 +9233,12 @@ def _gguf_resident_file_gb(
"""GB of files a launch would make resident: weights, projector, drafter.
Derived from ``_estimate_gguf_required_gb`` by subtracting the context term it
- adds, rather than re-deriving the files. Which files a launch opens is two
- hundred lines of resolution in that function; a second copy would drift from it.
-
- It has two arms that add different terms, so subtract the matching one: a local
- ``gguf_file`` gets ``_estimate_gguf_kv_gb``, a repository gets
- ``_remote_gguf_compute_reserve_gb``. Both are exact, since each arm returns files
- plus that term. Branching on the same condition is what keeps them paired.
-
- Zero-context throughout, so the same value is added and taken away. Nothing
- about the files depends on it.
+ adds, rather than re-deriving two hundred lines of file resolution that would
+ drift from it. That function has two arms adding different terms, so subtract the
+ matching one -- a local ``gguf_file`` gets ``_estimate_gguf_kv_gb``, a repository
+ ``_remote_gguf_compute_reserve_gb`` -- and branch on the same condition to keep
+ them paired. Exact, since each arm returns files plus its term. Zero-context
+ throughout, so the same value is added and taken away.
"""
main = getattr(config, "gguf_file", None)
local_arm = bool(main and Path(main).is_file())
@@ -9307,9 +9252,8 @@ def _gguf_resident_file_gb(
# A gated repo resolves per token, so entries must not cross subjects.
_estimate_token_fingerprint(hf_token),
)
- # In the key: the two callers ask different questions of the same files, and a
- # local-only answer served to the admission guard would drop a remote drafter it
- # must charge for.
+ # In the key: a local-only answer served to the admission guard would drop a
+ # remote drafter it must charge for.
key = (*key, local_only)
now = time.monotonic()
hit = _estimate_files_cache.get(key)
@@ -9342,13 +9286,11 @@ def _gguf_resident_file_gb(
)
files_gb = max(0.0, required_gb - context_term_gb)
# Under the lock: the route body runs in an asyncio.to_thread worker, so two panel
- # requests really are two threads here, and min() walks the dict through a Python
- # key function that the interpreter is free to switch out of. A concurrent pop makes
- # that walk raise KeyError, a concurrent insert makes it raise RuntimeError
- # (dictionary changed size during iteration), and nothing between here and the
- # to_thread body catches either, so it surfaces as a 500 on a slider drag. Rare --
- # reproducing it took hundreds of thousands of concurrent eviction cycles -- but the
- # window is real and a lock around evict-and-insert costs nothing at this size.
+ # requests are two threads, and min() walks the dict through a Python key function
+ # the interpreter may switch out of. A concurrent pop raises KeyError, a concurrent
+ # insert RuntimeError, and nothing catches either, so it surfaces as a 500 on a
+ # slider drag. Rare -- it took hundreds of thousands of eviction cycles to
+ # reproduce -- but the window is real and the lock costs nothing at this size.
with _ESTIMATE_CACHE_LOCK:
if len(_estimate_files_cache) >= _ESTIMATE_FILES_CACHE_MAX:
oldest = min(_estimate_files_cache, key = lambda k: _estimate_files_cache[k][0])
@@ -9416,31 +9358,24 @@ def _charged_drafter_path(
def _estimate_host_has_no_gpu() -> bool:
"""Whether this machine has POSITIVELY been shown to have no inference GPU.
- Only from a probe that ran and came back empty. A snapshot nothing has filled yet
- is not evidence of absence, and neither is the CUDA count -- it is zero on every
- Vulkan and ROCm-via-Vulkan host, which have plenty of GPU. So the unprobed case
- falls through to the placement the estimate made before, and only a real empty
- inventory moves the weights to host RAM.
-
- Without this an Auto load on a CPU-only Linux or Windows box read as fully
- GPU-resident, so the row showed a multi-gigabyte GPU figure against a capacity of
- zero. macOS is unaffected either way: unified memory shows one pool.
+ Only a probe that ran and came back empty counts. An unfilled snapshot is not
+ evidence of absence, and neither is the CUDA count: it is zero on every Vulkan and
+ ROCm-via-Vulkan host. Without this an Auto load on a CPU-only Linux or Windows box
+ read as fully GPU-resident, showing a multi-gigabyte GPU figure against a capacity
+ of zero. macOS is unaffected: unified memory shows one pool.
"""
devices = _cached_inference_devices()
return devices is not None and len(devices) == 0
def _cached_inference_devices() -> Optional[list[tuple[int, int, int]]]:
- """The inference inventory /api/system already probed, as _guard_device_count takes
- it, or None when nothing has filled that snapshot yet.
+ """The inventory /api/system already probed, shaped for _guard_device_count, or
+ None when nothing has filled that snapshot yet.
Read, never refreshed: the Vulkan inventory costs a subprocess and this endpoint
- runs on every settings change, while /api/system polls it anyway. Only the length
- is consulted downstream, but the ordinals come along so the shape is the real one.
-
- sys.modules rather than an import: this must observe the snapshot the running
- server fills, and importing the app module from a route would execute it wherever
- it is not already loaded.
+ runs on every settings change, while /api/system polls it anyway. sys.modules
+ rather than an import, so this observes the running server's snapshot instead of
+ executing the app module wherever it is not already loaded.
"""
try:
cached = getattr(sys.modules.get("main"), "_system_gpu_cache", None)
@@ -9448,12 +9383,10 @@ def _cached_inference_devices() -> Optional[list[tuple[int, int, int]]]:
return None
_, (_, inference_gpu) = cached
devices = (inference_gpu or {}).get("devices") or []
- # NOT `or None`. An empty list is a probe that ran and found no GPU, which is a
- # different answer from a snapshot nobody has filled, and callers act on the
- # difference: it is what puts an Auto load's weights in host RAM on a CPU-only
- # machine, and what stops a tensor split being priced on one that has no cards.
- # Collapsing the two made _estimate_host_has_no_gpu unreachable -- a check that
- # reads as present and does nothing.
+ # NOT `or None`. An empty list is a probe that found no GPU; None is a snapshot
+ # nobody filled, and callers act on the difference. Collapsing them made
+ # _estimate_host_has_no_gpu unreachable: a check that reads as present and does
+ # nothing.
return [(int(device.get("index", i)), 0, 0) for i, device in enumerate(devices)]
except Exception:
return None
@@ -9463,13 +9396,12 @@ def _tensor_split_possible(requested_gpu_ids: Optional[list[int]]) -> bool:
"""Whether two devices could take a tensor split at all.
load_model drops tensor mode below two usable GPUs and restores the quantized KV
- the tensor attempt stripped, so pricing tensor on one card charges f16 and
- per-device compute buffers for a layer load that runs neither.
+ the attempt stripped, so pricing tensor on one card charges f16 and per-device
+ compute buffers for a layer load that runs neither.
- A pin answers for itself. Without one the CUDA count answers, except on a Vulkan
- build, where it sees no devices at all: there the probed inventory answers, and
- only if nothing has probed it yet is the split assumed possible, rather than
- pricing a downgrade that may not happen.
+ A pin answers for itself; otherwise the CUDA count does, except on a Vulkan build
+ where it sees nothing and the probed inventory answers. Only an unprobed host
+ assumes the split is possible, rather than pricing a downgrade that may not happen.
"""
if requested_gpu_ids:
return len(requested_gpu_ids) >= 2
@@ -9594,11 +9526,10 @@ def _inherited_remote_files_unsized(extras: Optional[list[str]], disable_vision:
def _build_default_spec_draft_n_max(extras: Optional[list[str]] = None) -> int:
"""The draft depth a build runs on its own, for extras that own the spec block.
- Same order as the loader's budget: the inherited depth env first, since the child
- keeps LLAMA_ARG_SPEC_* once the extras own the spec block, then the build's own
- default out of the capability cache. Never probed for: this runs on every settings
- change. Unprobed, assume the deepest llama.cpp has shipped, which is the same
- assumption the loader makes.
+ Loader's order: the inherited LLAMA_ARG_SPEC_* depth first, then the build's own
+ default out of the capability cache. Never probed for -- this runs on every
+ settings change -- so an unprobed build assumes the deepest llama.cpp has shipped,
+ as the loader does.
"""
from core.inference.llama_cpp import _child_spec_env, _is_positive_int
@@ -9634,27 +9565,23 @@ def _estimate_spec_mode_terms(
"""Which target-side terms this speculative mode allocates.
Returns ``(mtp_keeps_target_ctx, target_rollback)`` for
- ``_estimate_mtp_overhead_bytes``, whose defaults charge both. Both defaults are
- wrong for a separate drafter: only true MTP keeps the duplicated target context
- (an MLA target's whole KV again, multi-GiB at a long context), and draft-simple
- keeps no rollback state either. Mirrors the loader's own budget, where the same
- two are derived per mode rather than defaulted.
-
- Extras that name ``--spec-type`` own the mode outright, so the accumulated types
- decide; otherwise Studio picked the sidecar, and DSpark and DFlash are separate
- drafters that pay rollback without duplicating the context.
-
- Naming a FILE is not owning the mode. ``--model-draft`` alone leaves
- ``_build_speculative_flags`` running -- it returns early on ``--spec-type``, not on
- a drafter path -- so on a target it recognises as an MTP model Studio still emits
- ``--spec-type draft-mtp`` and the user's path merely last-wins as the drafter. The
- child then does allocate the duplicated MLA context, several context-scaled
- gigabytes that reading the path as an extras-owned spec block dropped.
-
- On a target Studio does NOT recognise, the same extras really are draft-simple,
- llama.cpp's default for a bare ``--model-draft``, and allocate neither. That is why
- the caller answers ``studio_emits_mtp`` from the header rather than this deciding
- from the mode alone.
+ ``_estimate_mtp_overhead_bytes``, whose defaults charge both and are both wrong for
+ a separate drafter: only true MTP duplicates the target context (an MLA target's
+ whole KV again, multi-GiB at a long context), and draft-simple keeps no rollback
+ either. Mirrors the loader's budget, which derives the two per mode.
+
+ Extras naming ``--spec-type`` own the mode, so the accumulated types decide;
+ otherwise Studio picked the sidecar, and DSpark and DFlash pay rollback without
+ duplicating the context.
+
+ Naming a FILE is not owning the mode. ``_build_speculative_flags`` returns early on
+ ``--spec-type``, not on a drafter path, so with a bare ``--model-draft`` against a
+ target Studio recognises as MTP it still emits ``--spec-type draft-mtp`` and the
+ path merely last-wins as the drafter -- and the child allocates the duplicated MLA
+ context that reading the path as an extras-owned spec block dropped. Against a
+ target Studio does not recognise, the same extras really are draft-simple and
+ allocate neither, which is why the caller answers ``studio_emits_mtp`` from the
+ header.
"""
from core.inference.llama_cpp import (
_accumulated_spec_types,
@@ -9721,23 +9648,14 @@ def _estimate_draft_n_max(
def _embedded_mtp_engages(probe, config, speculative_type, extras) -> bool:
"""Whether the launch really turns on an embedded NextN head.
- An embedded head is a drafter with no file, so nothing about it appears in the
- weights and the only way to know it costs anything is to re-ask the question
- ``_build_speculative_flags`` asks. Every no-MTP outcome it has is mirrored here,
- through its own predicates rather than a second copy of the reasoning:
-
- * no head in the header at all (the helper then prices nothing anyway, but this
- keeps the cheap answer cheap);
- * a mode that emits no drafter -- off, ngram, ngram-simple;
- * DSpark and DFlash, which either open their own sidecar (charged as a file) or
- fall back to --spec-default and open nothing;
- * a sub-3B embedded head, which Auto drops for ngram-mod because MTP regresses
- there;
- * an MLA embedded head under Auto, where llama.cpp's MTP path is about half the
- speed of no speculation. Forced mtp overrides that, so the drop is Auto's alone;
- * extras that own --spec-type, where Studio emits no spec block of its own. That
- last one can under-charge a hand-written --spec-type draft-mtp, which is the
- side that shows a smaller number rather than refusing a load that fits.
+ An embedded head is a drafter with no file, so nothing about it reaches the weights
+ and the only way to know it costs anything is to re-ask what
+ ``_build_speculative_flags`` asks. Every no-MTP outcome it has is mirrored here
+ through its own predicates: no head in the header; a mode emitting no drafter (off,
+ ngram, ngram-simple); DSpark and DFlash, which open a sidecar charged as a file or
+ fall back to --spec-default; a sub-3B head, which Auto drops because MTP regresses
+ there; an MLA head under Auto, where llama.cpp's MTP path runs about half the speed
+ of no speculation, a drop forced mtp overrides.
"""
if not getattr(probe, "_nextn_predict_layers", None):
return False
@@ -9750,11 +9668,10 @@ def _embedded_mtp_engages(probe, config, speculative_type, extras) -> bool:
)
if _extra_args_set_spec_type(extras):
- # Studio emits no spec block of its own here, but the child still honours what
- # the extras asked for, and --spec-type draft-mtp on a NextN GGUF engages the
- # embedded head. Answered from the accumulated types rather than assumed off:
- # with no drafter file there is nothing in the weights to notice, so the whole
- # draft cache and target-side state went uncharged.
+ # Studio emits no spec block here, but the child honours the extras, and
+ # --spec-type draft-mtp on a NextN GGUF engages the head. Assumed off, the whole
+ # draft cache and target-side state went uncharged: with no drafter file there
+ # is nothing in the weights to notice.
from core.inference.llama_cpp import _accumulated_spec_types, _child_spec_env
return bool(
_accumulated_spec_types(extras, env = _child_spec_env(extras)) & {"mtp", "draft-mtp"}
@@ -9762,11 +9679,10 @@ def _embedded_mtp_engages(probe, config, speculative_type, extras) -> bool:
mode = _canonicalize_spec_mode(speculative_type) or "auto"
if mode not in ("auto", "mtp", "mtp+ngram"):
return False
- # A build that advertises no mtp_token cannot run MTP at all: the flags builder
- # emits --spec-default and launches without it, whatever the mode says. This one IS
- # a hard incompatibility, so it applies to a forced request too. Same rule as the
- # other capability gates here -- only a probe that RAN and lacks it drops the term,
- # since an unanswerable probe must not silently stop charging for the allocation.
+ # No mtp_token means the build cannot run MTP at all: the flags builder emits
+ # --spec-default whatever the mode says. A hard incompatibility, so it applies to a
+ # forced request too. Same rule as the other capability gates: only a probe that RAN
+ # and lacks it drops the term.
try:
caps = LlamaCppBackend.probe_server_capabilities()
if caps.get("found") and not caps.get("mtp_token"):
@@ -9775,10 +9691,9 @@ def _embedded_mtp_engages(probe, config, speculative_type, extras) -> bool:
logger.debug("MTP capability probe failed while pricing the draft head: %s", exc)
if mode != "auto":
- # Both remaining drops are Auto's judgement, not a hard incompatibility. Forced
- # MTP on a sub-3B model logs "Engaging anyway (user override)" and emits, and
- # the dropdown is the documented way to override the MLA drop, so an explicit
- # request is charged for what it asked for.
+ # Both remaining drops are Auto's judgement. Forced MTP on a sub-3B model logs
+ # "Engaging anyway (user override)" and emits, and the dropdown is the documented
+ # way to override the MLA drop, so an explicit request is charged as asked.
return True
size_b = _extract_model_size_b(getattr(config, "identifier", None))
if size_b is not None and size_b < _MTP_MIN_SIZE_B:
@@ -9946,14 +9861,13 @@ def _gguf_memory_breakdown(
gpu_files_bytes = int(round(files_gb * (1024**3)))
extras = list(llama_extra_args or ())
# Pass-through adapters are resident weights the files term never carried: it
- # prices the target and its companions, and llama.cpp loads every --lora /
- # --control-vector on top of the base model. They do not mmap (the file is read
- # into a staging buffer and pushed with ggml_backend_tensor_set), so the bytes are
- # resident whatever --load-mode says, and several adapters run to gigabytes. The
- # loader has charged them since _sidecar_adapter_bytes; the panel had not, so a
- # LoRA load could be shown as a fit on the base model's size alone. Placement
- # follows the base tensor's buffer type, so these scale with the layer fraction
- # exactly as the main weight does, not as a companion.
+ # prices the target and its companions, while llama.cpp loads every --lora /
+ # --control-vector on top of the base model. They do not mmap -- read into a staging
+ # buffer and pushed with ggml_backend_tensor_set -- so the bytes are resident
+ # whatever --load-mode says, and several run to gigabytes. The loader charges them;
+ # the panel did not, so a LoRA load could read as a fit on the base size alone.
+ # Placement follows the base tensor's buffer type, so they scale with the layer
+ # fraction like the main weight, not like a companion.
from core.inference.llama_cpp import _sidecar_adapter_bytes
adapter_bytes = _sidecar_adapter_bytes(extras)
@@ -9973,13 +9887,12 @@ def _gguf_memory_breakdown(
gb = _gguf_resident_file_gb(config, llama_extra_args = extras + list(extra), **files_probe)
return None if gb is None else int(round(gb * (1024**3)))
- # A CPU-pinned drafter is dropped from _estimate_gguf_required_gb, which is a VRAM
- # admission figure. This panel reports host RAM too, so those bytes belong in the
- # total even though they never reach the GPU. Recovered by re-pricing with the pin
- # overridden rather than by re-deriving which sidecar the mode picks.
- # Bound before the branch: a CPU pin on a model that ships no sidecar charges no
- # drafter either way, and reading this below raised UnboundLocalError -- a 500 that
- # took the whole row out for an otherwise ordinary load.
+ # A CPU-pinned drafter is dropped from _estimate_gguf_required_gb, a VRAM admission
+ # figure. This panel reports host RAM too, so those bytes belong in the total.
+ # Recovered by re-pricing with the pin overridden rather than by re-deriving which
+ # sidecar the mode picks. Bound before the branch: a CPU pin on a model shipping no
+ # sidecar charges no drafter either way, and reading this below raised
+ # UnboundLocalError, a 500 that took the whole row out.
host_drafter_bytes = 0
gpu_drafter_bytes = 0
if _extra_args_draft_offloaded_to_cpu(extras):
@@ -10016,18 +9929,16 @@ def _gguf_memory_breakdown(
charged_drafter = _charged_drafter_path(
config, host_drafter_bytes or gpu_drafter_bytes, extras = extras
)
- # An embedded NextN head is a drafter with no file: nothing is charged in the
- # weights, so charged_drafter is None, and the whole runtime block below used to be
- # skipped. The head still allocates a context-sized draft KV, plus an MLA target
- # copy or Hybrid-Mamba rollback state, which at long contexts is gigabytes. Priced
- # through the same helper with drafter_path = None, which is the case it documents.
+ # An embedded NextN head is a drafter with no file, so charged_drafter is None and
+ # the runtime block below used to be skipped -- while the head still allocates a
+ # context-sized draft KV plus an MLA target copy or Hybrid-Mamba rollback state,
+ # gigabytes at a long context. Priced through the same helper with
+ # drafter_path = None, the case it documents.
#
- # Safe to ask unconditionally for these modes: the helper sizes the head from
- # nextn_predict_layers, so a model whose header carries no NextN key prices nothing
- # and this costs one arithmetic pass. The mode test is what keeps it off a launch
- # that runs no speculation at all.
- # The header is needed to answer whether an embedded head exists at all, so the
- # probe is built first and handed to both questions rather than read twice.
+ # Safe to ask unconditionally: the helper sizes the head from nextn_predict_layers,
+ # so a header with no NextN key prices nothing for one arithmetic pass, and the mode
+ # test keeps it off a launch running no speculation. The probe is built first
+ # because both questions need the header.
probe = _probe_backend()
probe._read_gguf_metadata(gguf_path)
embedded_mtp = bool(
@@ -10035,29 +9946,23 @@ def _gguf_memory_breakdown(
)
# Deliberately NOT re-placed by the draft-only pins. --spec-draft-ngl 0 and
# --spec-draft-device cpu carry params.speculative.n_gpu_layers and .devices, which
- # llama.cpp copies into the model params only on the has_draft path; an embedded
- # head takes llama_init_from_model(model_tgt) and keeps the target's placement.
- # _extra_args_draft_offloaded_to_cpu says so in its own docstring and the launch
- # budget enforces it (_draft_cpu_no_embedded), so moving the head's cache to host
- # here dropped gigabytes out of gpu_bytes for a load that allocates them on the
- # card -- an under-report, and the direction that turns an overflow into a fit.
+ # llama.cpp copies in only on the has_draft path; an embedded head takes
+ # llama_init_from_model(model_tgt) and keeps the target's placement, as
+ # _extra_args_draft_offloaded_to_cpu documents and _draft_cpu_no_embedded enforces.
+ # Moving its cache to host here dropped gigabytes out of gpu_bytes for a load that
+ # allocates them on the card.
if charged_drafter or embedded_mtp:
drafter_path, drafter_kind = charged_drafter or (None, "mtp")
- # K and V are independent overrides, and extras beat the panel field the same
- # way they do at launch; passing the field for both priced a cache the load
- # will not allocate.
- # Launch order, which is not the helper's default order. The helper falls back
- # to LLAMA_ARG_SPEC_DRAFT_CACHE_TYPE_K/_V when the extras are silent, so asking
- # it once and then `or`-ing the panel field gave the ENVIRONMENT precedence
- # over the control. At launch the field goes on argv, argv beats the env twin,
- # and the extras are appended after argv and beat both. Asked twice to get
- # that: extras alone, then the env alone.
+ # K and V are independent overrides and extras beat the panel field, as at
+ # launch. Asked twice -- extras alone, then env alone -- to get launch order:
+ # the helper falls back to LLAMA_ARG_SPEC_DRAFT_CACHE_TYPE_K/_V when the extras
+ # are silent, so one call `or`-ed with the field gave the ENVIRONMENT precedence
+ # over the control, while argv beats the env twin and the extras beat both.
draft_k, draft_v = _extra_args_draft_cache_types(extras, env = {})
env_draft_k, env_draft_v = _extra_args_draft_cache_types([], env = os.environ)
- # ... and the field only reaches argv on a build that has the flag. Where it
- # does not, Studio emits nothing and the inherited value is what the child
- # uses. Same default-charge-on-an-unanswerable-probe rule as elsewhere here:
- # only a probe that RAN and lacks the flag drops the field.
+ # ... and the field only reaches argv on a build that has the flag; elsewhere
+ # the child uses the inherited value. Only a probe that RAN and lacks it drops
+ # the field.
_managed_draft_cache = True
try:
_dc_caps = LlamaCppBackend.probe_server_capabilities()
@@ -10082,14 +9987,11 @@ def _gguf_memory_breakdown(
studio_emits_mtp = embedded_mtp
or _embedded_mtp_engages(probe, config, speculative_type, extras),
)
- # The cache layout the target was priced with, not the helper's defaults: a
- # drafter with sliding-window attention under --swa-full allocates the full
- # window, and the same slot layout and micro-batch decide its cell count. The
- # loader passes all four; defaulting them here priced a smaller cache than the
- # launch allocates. flash_attn follows the draft V axis for the same reason
- # the target's does: llama.cpp turns flash attention on itself for a
- # quantized V cache and will not start without it, so the padded-to-f16 arm
- # prices a launch that cannot happen.
+ # The layout the target was priced with, not the helper's defaults: a drafter
+ # with sliding-window attention under --swa-full allocates the full window, and
+ # the same slot layout and micro-batch decide its cell count. The loader passes
+ # all four; defaulting them priced a smaller cache than the launch allocates.
+ # flash_attn follows the draft V axis for the same reason the target's does.
_draft_v_type = draft_v or _field_draft_cache or env_draft_v
layout = dict(
swa_full = runtime.swa_full,
@@ -10195,26 +10097,22 @@ def _gguf_memory_breakdown(
# And only the offloaded layers' share of it. A cache buffer is allocated on
# model.dev_layer(il) (llama-kv-cache.cpp), so a layer left on the CPU keeps its
# cache in host RAM -- the same rule the launch documents where it plans a spill.
- # Charging the whole cache to VRAM at a partial offload contradicted the weights
- # term right above, which is scaled, and at a long context the cache is the larger
- # of the two: a 10-of-40 Manual placement read as exceeding a card it fits on.
- # Linear in the layer count, like the weights, which is an approximation on a
- # model whose layers do not all cache alike but is far nearer than charging all
- # of it; --gpu-layers 0 and a full offload are both exact.
+ # Charging all of it at a partial offload contradicted the scaled weights term
+ # above, and at a long context the cache is the larger of the two: a 10-of-40
+ # Manual placement read as exceeding a card it fits on. Linear in the layer count
+ # like the weights -- an approximation where layers do not all cache alike, far
+ # nearer than charging everything, and exact at 0 and at a full offload.
gpu_bytes = gpu_weights + (int(gpu_kv_bytes * gpu_fraction) if kv_on_gpu else 0)
if gpu_fraction > 0.0:
# Compute buffers land on the devices running layers.
gpu_bytes += runtime.compute_bytes
- # The target-side spec terms are target KV allocations, so they follow the target
- # cache. The drafter's own KV follows the drafter: a separate drafter does not
- # inherit --gpu-layers (llama.cpp overwrites it with the draft placement, default
- # auto), so at --gpu-layers 0 it is still on the GPU and still holds that cache.
- # An embedded head is the exception in the other direction: it has no file, so
- # host_drafter_bytes is 0 and drafter_on_gpu answered yes even for a target the
- # user placed on the CPU. It is part of the target's own tensors and llama.cpp
- # gives it the target's context, so it goes where the target goes -- and at
- # --gpu-layers 0 that is host RAM, where charging its cache to VRAM raised a
- # multi-gigabyte warning about a card the load never touches.
+ # Target-side spec terms are target KV allocations and follow the target cache. The
+ # drafter's own KV follows the drafter: a separate one does not inherit
+ # --gpu-layers (llama.cpp overwrites it with the draft placement, default auto), so
+ # at --gpu-layers 0 it is still on the GPU holding that cache. An embedded head is
+ # the exception in the other direction -- no file means host_drafter_bytes is 0 and
+ # drafter_on_gpu said yes even for a CPU-placed target -- but it is part of the
+ # target's tensors and takes the target's context, so it goes where the target goes.
_drafter_on_gpu = (gpu_fraction > 0.0) if embedded_mtp else drafter_on_gpu
drafter_runtime_gpu_bytes = (target_spec_bytes if kv_on_gpu else 0) + (
(drafter_runtime_bytes - target_spec_bytes) if _drafter_on_gpu else 0
@@ -13799,16 +13697,14 @@ def _cached_estimate_config(
if hit is not None and now - hit[0] < _ESTIMATE_CONFIG_TTL_SECONDS:
return hit[1]
if not _estimate_target_is_on_this_disk(model_identifier):
- # Ahead of from_identifier, because from_identifier is the expensive part. It
- # runs the load path's full identification, and for an uncached REMOTE id that
- # walks to the Hub and writes: measured on one uncached safetensors repo, four
- # model_info attempts, an hf_hub_download of config.json, and 12 new paths /
- # 1828 bytes (blob, ref, snapshot, lock) in the HF cache -- for a request whose
- # answer is "not on this disk" and which needed none of it. On an endpoint the
- # settings panel fires on every change that is a Hub round trip and a disk write
- # behind a slider, which is exactly what this route's docstring promises it does
- # not do. None, not a cached None: the common reason a repo is absent is a
- # download still in flight, and the next tick is when that answer changes.
+ # Ahead of from_identifier, the expensive part: it runs the load path's full
+ # identification, and for an uncached REMOTE id that walks to the Hub and
+ # writes. Measured on one uncached safetensors repo: four model_info attempts,
+ # an hf_hub_download of config.json, and 12 new paths / 1828 bytes of HF cache,
+ # for a request whose answer is "not on this disk". Behind a slider that is a
+ # Hub round trip and a disk write, which this route's docstring promises it does
+ # not do. Not cached: a repo is usually absent because a download is in flight,
+ # and the next tick is when that changes.
return _ESTIMATE_NOT_ON_DISK
from core.inference.llama_cpp import _hf_offline_if_unreachable_for
@@ -13820,16 +13716,13 @@ def _cached_estimate_config(
drafter_accept = _native_drafter_accept if native_grant_backed else None,
)
- # Offline FIRST, not only when the Hub is unreachable. The gate above has already
- # established the repo is on this disk, and everything below prices local files, so
- # the identification needs nothing from the network -- but from_identifier still
- # runs detect_gguf_model_remote and list_gguf_variants, an hf_model_info each. On a
- # route the panel fires on every settings change, that is two Hub round trips per
- # cache miss and a rate limit waiting to happen, for an answer already on disk.
- #
- # The reachable path stays as the fallback rather than being removed: a cached repo
- # whose resolution genuinely needs remote metadata would otherwise go from a slow
- # answer to none at all, and a slow right answer beats a fast blank row.
+ # Offline FIRST, not only when the Hub is unreachable. The gate above established
+ # the repo is on this disk and everything below prices local files, so the
+ # identification needs nothing from the network -- yet from_identifier still runs
+ # detect_gguf_model_remote and list_gguf_variants, an hf_model_info each: two Hub
+ # round trips per cache miss on a route the panel fires on every change, and a rate
+ # limit waiting to happen. The reachable path stays as the fallback, because a slow
+ # right answer beats a fast blank row.
config = None
try:
from utils.utils import force_hf_offline
@@ -13841,19 +13734,16 @@ def _cached_estimate_config(
)
#
# Not taken when the gate could not be ANSWERED, as opposed to answering yes. The
- # gate is fail-open by design, and one of the things it opens onto is a host where
- # no HF cache root could be established at all -- a missing cache home, or an
- # interpreter that cannot complete the tier-1 import. On that host the gate refuses
- # nothing, so before this condition every uncached remote id reached this retry,
- # and this retry is the network: model_info attempts plus an hf_hub_download of
- # config.json, which writes blob, ref, snapshot and lock. "Nothing is downloaded"
- # is this route's promise, so an unanswerable gate stops at the OFFLINE resolution
- # above. The cost is a blank row instead of a slow one, on a host that could not
- # say where its own cache lives.
+ # gate is fail-open, and one thing it opens onto is a host where no HF cache root
+ # could be established -- a missing cache home, or a failed tier-1 import. There it
+ # refuses nothing, so every uncached remote id reached this retry, and this retry is
+ # the network. "Nothing is downloaded" is the route's promise, so an unanswerable
+ # gate stops at the offline resolution above; the cost is a blank row instead of a
+ # slow one, on a host that cannot say where its own cache lives.
#
# `unknown`, not `present`: a gate that positively said "absent" has already
- # returned, so in production these are the same test. They differ only for a caller
- # that overrode the gate, and there the override is the answer.
+ # returned, so these are the same test except for a caller that overrode the gate,
+ # and there the override is the answer.
if config is None and _estimate_disk_residency(model_identifier) != _ESTIMATE_DISK_UNKNOWN:
try:
with _hf_offline_if_unreachable_for(model_identifier):
@@ -13869,9 +13759,8 @@ def _cached_estimate_config(
# Oldest first; the panel works one model at a time, so this is housekeeping.
oldest = min(_estimate_config_cache, key = lambda k: _estimate_config_cache[k][0])
_estimate_config_cache.pop(oldest, None)
- # Stamped now, not at `now`. `now` was read before the resolution, and the
- # resolution is the slow part: a repo that took longer than the TTL to identify
- # was inserted already expired, so the next tick re-resolved it and the cache
+ # Stamped now, not at `now`, which was read before the slow part: a repo taking
+ # longer than the TTL to identify was inserted already expired, so the cache
# stopped existing on exactly the models it was added for.
_estimate_config_cache[key] = (time.monotonic(), config)
return config
@@ -13913,19 +13802,17 @@ async def estimate_memory(
# An expired lease is not worth a red error under a settings panel.
return EstimateMemoryResponse(available = False, reason = "unsupported_source")
- # Blank Parallel Slots means the server default (4 in a standard launch), not
- # one. /load resolves it the same way, so pricing 1 here underestimated the KV
- # cache and the slot-scaled compute buffers for the default configuration.
+ # Blank Parallel Slots means the server default (4 in a standard launch), not one,
+ # and /load resolves it the same way: pricing 1 underestimated the KV cache and the
+ # slot-scaled compute buffers for the default configuration.
#
- # The settings read stays on the loop: it is an attribute on the FastAPI app
- # state, and it is the one half of this that needs the request object. The CLAMP
- # goes below, into the worker -- _effective_parallel_slots asks the binary whether
- # it supports --kv-unified, which walks nine install layouts on every call and, on
- # a cold capability cache, runs `llama-server --help` with a ten second timeout.
- # _effective_default_slots already puts this exact call in a thread, for the exact
- # reason recorded in its docstring: called inline it "stalled every other request
- # on the first open of the panel after an update". The loop here is the one
- # streaming chat tokens.
+ # The settings read stays on the loop -- an app-state attribute, the one half that
+ # needs the request object. The CLAMP goes into the worker below, because
+ # _effective_parallel_slots asks the binary about --kv-unified, walking nine install
+ # layouts and, on a cold capability cache, running `llama-server --help` with a ten
+ # second timeout. _effective_default_slots threads this same call for the same
+ # reason: inline it "stalled every other request on the first open of the panel
+ # after an update", and this loop is the one streaming chat tokens.
requested_slots = _resolve_parallel_slots(request, fastapi_request)
def _estimate() -> EstimateMemoryResponse:
@@ -13971,14 +13858,13 @@ async def estimate_memory(
# matters there too, not just in tensor mode. Automatic placement
# stays at one: _guard_device_count makes the same call.
n_devices = _guard_device_count(
- # A pin names cards for a launch that puts something on them. When the
- # effective layer count resolves to zero the launch is CPU-only, and
- # the loader drops the split flags outright, so charging the pinned
- # count added per-device pipeline overhead and replicated the
- # context-linear compute term for buffers no card allocates: measured
- # on a two-card pin, 1039 -> 2105 MiB at 4k and 1417 -> 5129 MiB at
- # 262k. Asked of the same function the panel prices placement with, so
- # the two cannot disagree about whether anything lands on a GPU.
+ # A pin names cards for a launch that puts something on them. At an
+ # effective layer count of zero the launch is CPU-only and the loader
+ # drops the split flags, so charging the pinned count added per-device
+ # pipeline overhead and replicated the context-linear compute term for
+ # buffers no card allocates: on a two-card pin, 1039 -> 2105 MiB at 4k
+ # and 1417 -> 5129 MiB at 262k. Asked of the same function the panel
+ # prices placement with, so the two cannot disagree.
None
if _gguf_offloaded_layer_fraction(
request.gpu_memory_mode,
@@ -13989,21 +13875,18 @@ async def estimate_memory(
)
== 0.0
else request.selected_gpu_ids or None,
- # Tensor mode replicates its buffers on every device in the pool, and
- # on a Vulkan build _effective_gpu_count sees none of them. The probed
- # inventory is the pool; None when nothing has probed it, which falls
- # through to the CUDA count exactly as before.
+ # Tensor mode replicates its buffers over the whole pool, and on a
+ # Vulkan build _effective_gpu_count sees none of it. The probed
+ # inventory is the pool; None falls through to the CUDA count as before.
_cached_inference_devices(),
# Same resolution the breakdown prices with: an extras --split-mode
- # decides the mode, not the toggle alone, and one card cannot take a
- # tensor split whatever either of them says.
+ # decides the mode, not the toggle alone, and one card cannot split.
tensor_parallel = _effective_tensor_parallel(
request.llama_extra_args, bool(request.tensor_parallel)
)
and _tensor_split_possible(request.selected_gpu_ids or None)
- # And the Manual drops, which are about the layer count rather than the
- # pool: a tensor count here would size per-device buffers for a launch
- # that runs a layer split on the CPU.
+ # And the Manual drops, about the layer count rather than the pool: a
+ # tensor count here sizes per-device buffers for a CPU layer split.
and _manual_keeps_tensor_split(
request.gpu_memory_mode,
request.gpu_layers,
diff --git a/studio/backend/tests/test_estimator_flash_attn_parity.py b/studio/backend/tests/test_estimator_flash_attn_parity.py
index 188c4da4017..d9c32b525b2 100644
--- a/studio/backend/tests/test_estimator_flash_attn_parity.py
+++ b/studio/backend/tests/test_estimator_flash_attn_parity.py
@@ -4,19 +4,19 @@
"""A quantized V cache is priced with flash attention on, because llama.cpp will
not run it any other way.
-The estimator used to pass ``flash_attn = False`` to ``_estimate_kv_cache_bytes``
-unconditionally, as the conservative arm. It is conservative for a *choice*; for a
-quantized V cache it is not a choice. llama.cpp turns flash attention on itself --
+``flash_attn = False`` used to be passed unconditionally as the conservative arm. It is
+conservative for a *choice*; for a quantized V cache it is not one. llama.cpp turns
+flash attention on itself --
enabling flash_attn since it is required for quantized V cache
--- and aborts the load without it, which ``_tensor_quant_kv_unsupported_binary``
-already documents as "V cache quantization requires flash_attn". The False arm sets
-``bpe_v = max(bpe_k, f16)``, so the entire quantized saving on the V axis was charged
-straight back and the panel reported a launch that cannot happen.
+-- and aborts without it, which ``_tensor_quant_kv_unsupported_binary`` documents as
+"V cache quantization requires flash_attn". The False arm sets
+``bpe_v = max(bpe_k, f16)``, charging the entire quantized saving on the V axis back
+and reporting a launch that cannot happen.
-Measured against llama-server b10632 (``version: 0.3.0-dev (build 10632, commit
-11cd98842)``), Qwen3-0.6B-Q4_K_M, identical on the CPU and Vulkan builds:
+Measured against llama-server b10632 (commit ``11cd98842``), Qwen3-0.6B-Q4_K_M,
+identical on the CPU and Vulkan builds:
ctx -ctk/-ctv reserved before allocated after
4096 q8_0 343 MiB 238 MiB 238 MiB
diff --git a/studio/backend/tests/test_memory_estimate.py b/studio/backend/tests/test_memory_estimate.py
index 8faafd84bf1..17c758b52c1 100644
--- a/studio/backend/tests/test_memory_estimate.py
+++ b/studio/backend/tests/test_memory_estimate.py
@@ -3,28 +3,26 @@
"""Tests for the Load-Model memory estimate (POST /api/inference/estimate-memory).
-Guards the pieces the estimate is assembled from, and the properties that make it
-safe to put a number in front of a user:
-
-* ``_gguf_runtime_bytes`` -- KV + compute buffers, itemized. The load-bearing case
- is a header without the attention dims: it must report ``kv_estimable = False``
- with ``kv_bytes == 0``, since a UI reading that zero as "no cache" is worse than
- showing nothing.
-* ``_estimate_gguf_kv_gb`` -- now a thin wrapper over the above. The training guard
- still calls it, so its value must stay the old sum exactly.
+Guards the pieces the estimate is assembled from and the properties that make it safe
+to put a number in front of a user:
+
+* ``_gguf_runtime_bytes`` -- KV + compute, itemized. The load-bearing case is a header
+ without the attention dims: ``kv_estimable = False`` with ``kv_bytes == 0``, since a
+ UI reading that zero as "no cache" is worse than showing nothing.
+* ``_estimate_gguf_kv_gb`` -- a thin wrapper over it now, and still the training
+ guard's input, so its value must stay the old sum exactly.
* ``_gguf_offloaded_layer_fraction`` -- Auto is deliberately 1.0, not a guess.
-* ``_gguf_resident_file_gb`` / ``_gguf_memory_breakdown`` -- weights are derived by
- subtracting the context term out of ``_estimate_gguf_required_gb``. The observable
- proving the arms are paired is that weights do not move with the context slider.
+* ``_gguf_resident_file_gb`` / ``_gguf_memory_breakdown`` -- weights come from
+ subtracting the context term out of ``_estimate_gguf_required_gb``; the observable
+ that the arms are paired is that weights do not move with the context slider.
* ``_localized_estimate_config`` -- without it a cached repo priced itself through a
- ``paths-info`` call. Pins both halves: the copy takes the local arm, and the cached
- original is never mutated.
+ ``paths-info`` call. Both halves pinned: the copy takes the local arm, the cached
+ original is not mutated.
* ``_estimate_token_fingerprint`` -- both TTL caches are keyed per token.
-* the route -- the "cannot size this" answers, and that an Ollama manifest ref is
- refused before anything is materialized.
+* the route -- the "cannot size this" answers, and an Ollama manifest ref refused
+ before anything is materialized.
-No GPU, no network, no model load: every GGUF here is a synthetic header on
-tmp_path. Cross-platform.
+No GPU, no network, no model load: every GGUF here is a synthetic header on tmp_path.
"""
import inspect
@@ -288,12 +286,11 @@ class TestGgufRuntimeBytes:
def test_a_recurrent_model_keeps_its_layer_count(self, tmp_path):
"""The unsizable-KV path is reached by whole model families, not just stubs.
- llama.cpp reads the attention head counts with ``required = false``
- (llama-model.cpp:1177) while block_count and embedding_length are required
- (:1111, :1116), so every pure SSM model -- Mamba, Mamba2, RWKV -- loads with a
- layer count and no attention dimensions, which is exactly what
- ``_can_estimate_kv`` rejects. Dropping the count there would report a manual
- --gpu-layers 0 as a fully GPU-resident load on all of them.
+ llama.cpp reads the attention head counts with ``required = false`` while
+ block_count and embedding_length are required, so every pure SSM model --
+ Mamba, Mamba2, RWKV -- loads with a layer count and no attention dims, which is
+ what ``_can_estimate_kv`` rejects. Dropping the count there reported a manual
+ --gpu-layers 0 as fully GPU-resident on all of them.
"""
mamba = _write_gguf(
tmp_path,
@@ -913,14 +910,11 @@ class TestEstimateMemoryRoute:
assert resp.reason == "not_downloaded"
def test_a_repo_not_on_this_disk_is_refused_before_it_is_resolved(self, monkeypatch):
- # The route's docstring promises "nothing is downloaded", and every other test
- # in this class asserts that while monkeypatching _cached_estimate_config --
- # the one function that can break it. Driven for real, an uncached remote id
- # walked to the Hub and cached what it fetched: on one safetensors repo, four
- # model_info attempts, an hf_hub_download of config.json, and 12 new paths /
- # 1828 bytes of blob, ref, snapshot and lock. For a request whose answer is
- # "not on this disk" and which needed none of it, on an endpoint the panel
- # fires on every change.
+ # The route promises "nothing is downloaded", and every other test in this class
+ # asserts that while monkeypatching _cached_estimate_config -- the one function
+ # that can break it. Driven for real, an uncached remote id walked to the Hub:
+ # four model_info attempts, an hf_hub_download of config.json, and 12 new paths /
+ # 1828 bytes of cache, for a request whose answer is "not on this disk".
def boom(*a, **kw):
raise AssertionError("must not resolve a model that is not on this disk")
@@ -983,18 +977,15 @@ class TestEstimateMemoryRoute:
def test_the_route_never_reaps_processes_or_leaks_an_atexit_handler(
self, monkeypatch, gqa_gguf
):
- # The sizing helpers build a LlamaCppBackend just to read a header, and
- # LlamaCppBackend.__init__ reaps orphaned llama-servers -- it walks every entry
- # in /proc, resolves each candidate's exe and SIGNALS the ones it recognises --
- # then registers an atexit handler holding the instance for the life of the
- # process. Both are right for the backend that owns a child. Neither is right
- # here, and before this became a panel endpoint they ran once per load rather
- # than once per settings change.
+ # The sizing helpers build a LlamaCppBackend just to read a header, and its
+ # __init__ reaps orphaned llama-servers -- walking /proc, resolving each
+ # candidate's exe and SIGNALLING the ones it recognises -- then registers an
+ # atexit handler holding the instance for the life of the process. Both are
+ # right for a backend that owns a child, neither for a settings panel.
#
- # Measured on this route before the probes were made inert: five constructions
- # per request, so 50 estimates were 250 /proc scans and 250 permanently
- # retained atexit handlers, at 120 ms each. A panel that prices a load must not
- # be able to kill a server, and dragging a slider must not leak.
+ # Measured before the probes were made inert: five constructions per request,
+ # so 50 estimates were 250 /proc scans and 250 retained atexit handlers at
+ # 120 ms each. Pricing a load must not be able to kill a server.
import atexit
import inspect
@@ -2224,15 +2215,12 @@ class TestManualNormalizationAndRemoteDrafters:
class TestSpeculationOffChargesNoDrafter:
"""Modes whose launch never emits ``--model-draft`` must not be billed for one.
- ``_build_speculative_flags`` returns out of three of them before it reaches the
- flag: "off" immediately, "ngram-simple" and "ngram" after their ``--spec-type``
- alone. The resident-file resolution appended ``gguf_mtp_file`` for every mode that
- was not DSpark or DFlash, so a model shipping an MTP sidecar was charged for it
- even with speculation turned OFF -- selecting OFF could ADD gigabytes to the
- figure, which is the opposite of what the control does.
-
- Exercised against the real resolution rather than through the breakdown, because
- the breakdown's own tests stub the files term wholesale and would pass either way.
+ ``_build_speculative_flags`` returns out of three before reaching the flag: "off"
+ immediately, "ngram-simple" and "ngram" after their ``--spec-type``. The resident-
+ file resolution appended ``gguf_mtp_file`` for every mode that was not DSpark or
+ DFlash, so selecting OFF could ADD gigabytes -- the opposite of what the control
+ does. Driven through the real resolution: the breakdown's own tests stub the files
+ term wholesale and would pass either way.
"""
@pytest.fixture
@@ -2384,15 +2372,12 @@ class TestAnEmbeddedMtpHeadIsPriced:
"""--spec-draft-ngl 0 does not switch the head off, and does not move it either.
Both flags carry ``params.speculative.n_gpu_layers`` / ``.devices``, which
- llama.cpp copies into the model params only on the ``has_draft`` path. An
- embedded head has no draft model to load: ``llama_init_from_model(model_tgt)``
- builds its context against the target and it keeps the target's placement.
- ``_extra_args_draft_offloaded_to_cpu`` documents that, and the launch budget
- enforces it through ``_draft_cpu_no_embedded``.
-
- So the allocation is still made AND still on the card. Gating the sizing on the
- pin dropped it from both figures; placing it in host RAM dropped it from the
- GPU one. Both are the direction that turns a multi-gigabyte load into a fit.
+ llama.cpp copies in only on the ``has_draft`` path; an embedded head has no
+ draft model to load and takes ``llama_init_from_model(model_tgt)``, keeping the
+ target's placement, as ``_extra_args_draft_offloaded_to_cpu`` documents and
+ ``_draft_cpu_no_embedded`` enforces. So it is still allocated AND still on the
+ card: gating the sizing on the pin dropped it from both figures, placing it in
+ host RAM dropped it from the GPU one, and both turn an overflow into a fit.
"""
gguf, config = nextn_model
unpinned = ri._gguf_memory_breakdown(config, gguf, n_ctx = 131072)
diff --git a/studio/backend/tests/test_memory_estimate_platforms.py b/studio/backend/tests/test_memory_estimate_platforms.py
index 2e7793beff0..1dc5e01d4db 100644
--- a/studio/backend/tests/test_memory_estimate_platforms.py
+++ b/studio/backend/tests/test_memory_estimate_platforms.py
@@ -3,47 +3,39 @@
"""The Load-Model memory estimate across every platform and accelerator Unsloth ships on.
-``tests/test_memory_estimate.py`` proves the arithmetic on one host. This file asks the
-other question: does the SAME number come out, and does it stay internally consistent,
-when the host underneath changes? The estimate reads three host-shaped seams --
-``sys.platform``, the probed inference inventory, and whether the llama.cpp build is
-Vulkan -- and each of them moves a different arm of the placement split.
-
-The matrix is the Cartesian product of the four platforms and six accelerators, run
-through the real ``POST /api/inference/estimate-memory`` handler on synthetic GGUF
-headers. Nothing here downloads, loads, allocates or launches anything.
-
-What is asserted per cell is deliberately not "the number equals N". A wrong estimator
-that is self-consistent still passes that. These are the properties a wrong-but-
-self-consistent estimator cannot satisfy:
-
-* the itemization SUMS to the total, exactly, in integers -- see ``_itemized_sum``, and
- read its comment before trusting the PR body's "four items";
-* ``gpu_bytes <= total_bytes``, on every cell, always;
-* ``weights_bytes`` does not move when the context slider does. This is the load-bearing
- one: the weights term is obtained by SUBTRACTING the context term out of
- ``_estimate_gguf_required_gb``, so any drift here means the two arms of that
- subtraction stopped naming the same bytes;
-* ``kv_bytes`` is non-decreasing in ``n_ctx``;
+``test_memory_estimate.py`` proves the arithmetic on one host; this file asks whether
+the same number comes out, and stays internally consistent, when the host changes. The
+estimate reads three host-shaped seams -- ``sys.platform``, the probed inference
+inventory, and whether the llama.cpp build is Vulkan -- and each moves a different arm
+of the placement split. The matrix is the four platforms by six accelerators, driven
+through the real route on synthetic headers; nothing downloads, loads or launches.
+
+Not "the number equals N", which a self-consistent wrong estimator also passes. The
+properties such an estimator cannot satisfy:
+
+* the itemization SUMS to the total exactly, in integers (see ``_itemized_sum``);
+* ``gpu_bytes <= total_bytes``, every cell;
+* ``weights_bytes`` does not move with the context slider. The load-bearing one: the
+ weights term is the context term SUBTRACTED out of ``_estimate_gguf_required_gb``, so
+ drift here means the two arms stopped naming the same bytes;
+* ``kv_bytes`` non-decreasing in ``n_ctx``;
* ``drafter_runtime_gpu_bytes <= drafter_runtime_bytes``;
-* no field is ever negative;
+* no negative field;
* a probed-empty inventory reports ``gpu_bytes == 0``;
-* moving bytes off the GPU never shrinks the TOTAL. On unified memory that is the whole
- claim: an offloaded byte is not a freed byte;
-* ``layer_count`` survives an unsizable KV, or ``--gpu-layers 0`` reads as a fully
- GPU-resident load.
-
-And one tripwire, asserted on every cell: nothing in this path may reach
-``LlamaCppBackend._apple_metal_memory_budget_bytes``. It contains a bare
-``import mlx.core``, which on macOS after torch has been imported aborts the process at
-the C level -- an abort no surrounding ``try``/``except`` can catch. A settings panel
-that fires on every slider tick must never be able to take the server down, so this is
-checked per cell rather than reasoned about.
-
-The honest limit of this file: it runs on Linux. ``sys.platform``, ``platform.system()``
-and ``platform.machine()`` are moved; the kernel, the filesystem semantics, the real
-Metal/HIP/Vulkan runtimes and the real device probes are not. It is branch coverage of
-the estimator's host-shaped decisions, not a substitute for the per-OS CI matrix.
+* moving bytes off the GPU never shrinks the TOTAL -- on unified memory that is the
+ whole claim, since an offloaded byte is not a freed byte;
+* ``layer_count`` survives an unsizable KV, or ``--gpu-layers 0`` reads fully resident.
+
+Plus one tripwire per cell: nothing here may reach
+``LlamaCppBackend._apple_metal_memory_budget_bytes``, whose bare ``import mlx.core``
+aborts the process at the C level on macOS once torch is imported -- an abort no
+``try``/``except`` catches. A panel firing on every slider tick must not be able to
+take the server down, so it is checked rather than reasoned about.
+
+The honest limit: this runs on Linux. ``sys.platform``, ``platform.system()`` and
+``platform.machine()`` are moved; the kernel, filesystem semantics, the real
+Metal/HIP/Vulkan runtimes and the real device probes are not. Branch coverage of the
+estimator's host-shaped decisions, not a substitute for the per-OS CI matrix.
"""
from __future__ import annotations
@@ -168,13 +160,12 @@ _UPSTREAM_ACCELERATORS = {
#
# amd-rocm -- a HIP build. NOT Vulkan: the ROCm prebuilt carries a hipBLAS ggml
# lib, so _is_vulkan_backend is False and the devices enumerate
-# through the torch/CUDA-shaped path exactly as NVIDIA's do.
-# apple-unified -- Metal. One device, because that is what the /api/system probe
-# reports on Apple Silicon: get_backend_visible_gpu_info's MLX arm
-# (utils/hardware/hardware.py:4526) emits a single index-0 device
-# whose "VRAM" is the machine's unified RAM. Modelling Apple as an
-# empty inventory would have quietly turned this into a second
-# cpu-only cell and asserted nothing about unified memory at all.
+# through the torch/CUDA-shaped path as NVIDIA's do.
+# apple-unified -- Metal, one device, which is what /api/system reports on Apple
+# Silicon: get_backend_visible_gpu_info's MLX arm emits a single
+# index-0 device whose "VRAM" is the machine's unified RAM. An empty
+# inventory here would be a second cpu-only cell asserting nothing
+# about unified memory.
ACCELERATORS = [
("nvidia-single", *_UPSTREAM_ACCELERATORS["nvidia-single"]),
("nvidia-multi", *_UPSTREAM_ACCELERATORS["nvidia-multi"]),
@@ -191,17 +182,15 @@ _CPU_ONLY = "cpu-only"
def _reachable(platform_label: str, accelerator_label: str) -> bool:
"""Whether this (platform, accelerator) pair can physically exist.
- Exactly one exclusion, and it is stated rather than dropped: apple-unified means
- Apple Silicon's Metal unified memory, which only exists under Darwin. There is no
- Apple-unified Windows, Linux or WSL2 host. (Asahi Linux does run on Apple Silicon,
- but Studio's own is_apple_silicon() is `platform.system() == "Darwin"`, so on Asahi
- the estimate takes the Linux arm -- which is the linux/cpu-only cell already here.)
-
- Everything else is kept, including the three discrete-vendor cells on macOS. Those
- are legacy shapes (Intel Mac with an eGPU, or a CUDA build predating macOS 10.14),
- and the reason to keep them is that the estimator contains NO code that forbids
- them: what those cells really assert is "Darwin plus a non-empty probed inventory",
- which is the shape a Mac reports, and dropping them would drop that coverage.
+ One exclusion, stated rather than dropped: apple-unified is Apple Silicon's Metal
+ unified memory, which only exists under Darwin. (Asahi Linux runs on Apple Silicon,
+ but Studio's is_apple_silicon() is `platform.system() == "Darwin"`, so there the
+ estimate takes the Linux arm, already covered by linux/cpu-only.)
+
+ Everything else is kept, including the three discrete-vendor cells on macOS --
+ legacy shapes, an Intel Mac with an eGPU or a pre-10.14 CUDA build, and the
+ estimator contains no code forbidding them. What they assert is "Darwin plus a
+ non-empty probed inventory", which is the shape a Mac reports.
"""
return accelerator_label != _UNIFIED or platform_label == "macos"
@@ -301,24 +290,20 @@ def _apply_cell(monkeypatch, platform_row, accelerator_row) -> None:
):
monkeypatch.delenv(inherited, raising = False)
- # The llama-server binary. Pinned for two reasons, and the second one is the
- # interesting one:
+ # The llama-server binary, pinned for two reasons; the second is the interesting one:
#
- # * determinism. ``_tensor_latches_allow_a_split`` resolves the binary and then
- # asks two in-process latches about it. Left unpinned, whether a cell consults
- # those latches at all depends on whether the runner happens to have llama.cpp
- # installed, which is not a property of the cell.
+ # * determinism. ``_tensor_latches_allow_a_split`` resolves the binary before asking
+ # two in-process latches about it, so unpinned, whether a cell consults them at
+ # all depends on whether the runner has llama.cpp installed.
# * the Windows cells could not reach them otherwise. ``_find_llama_server_binary``
- # ends at ``shutil.which``, and CPython's ``shutil.which`` calls
- # ``_winapi.NeedCurrentDirectoryForExePath`` under ``sys.platform == "win32"``
- # (shutil.py, ``_win_path_needs_curdir``). On a Linux interpreter ``_winapi`` is
- # None, so the lookup raises AttributeError, the caller's fail-open ``except``
- # swallows it, and every Windows cell silently skipped the latch check while
- # still reporting a pass. That is an artifact of simulating win32 on Linux, not
- # a product bug -- a real Windows host has ``_winapi`` -- but it is exactly the
- # kind of quiet hole that makes a green matrix mean nothing, so the seam is
- # moved above it. test_platform_matrix_the_tensor_latch_lookup_runs_on_every_cell
- # holds it open.
+ # ends at ``shutil.which``, which calls
+ # ``_winapi.NeedCurrentDirectoryForExePath`` under ``sys.platform == "win32"``.
+ # On a Linux interpreter ``_winapi`` is None, so it raises AttributeError, the
+ # caller's fail-open ``except`` swallows it, and every Windows cell skipped the
+ # latch check while reporting a pass. An artifact of simulating win32 on Linux
+ # rather than a product bug, but exactly the quiet hole that makes a green matrix
+ # mean nothing, so the seam is moved above it.
+ # test_platform_matrix_the_tensor_latch_lookup_runs_on_every_cell holds it open.
monkeypatch.setattr(
LlamaCppBackend,
"_find_llama_server_binary",
diff --git a/studio/backend/tests/test_memory_estimate_side_effects.py b/studio/backend/tests/test_memory_estimate_side_effects.py
index 196eb4d2c82..7c21a480e70 100644
--- a/studio/backend/tests/test_memory_estimate_side_effects.py
+++ b/studio/backend/tests/test_memory_estimate_side_effects.py
@@ -3,26 +3,23 @@
"""Side-effect contracts for POST /api/inference/estimate-memory.
-``test_memory_estimate.py`` guards the arithmetic. This file guards the four
-promises the route's docstring makes about what it does NOT do -- "no model is
-loaded, no device is touched, nothing is downloaded" -- and it guards them
-behaviourally rather than by reading the source, because the panel fires this
-endpoint on every settings change and a regression here is a Hub round trip, a
-disk write, or a reaped llama-server behind a slider drag.
+``test_memory_estimate.py`` guards the arithmetic; this file guards the promises the
+route makes about what it does NOT do -- "no model is loaded, no device is touched,
+nothing is downloaded" -- behaviourally rather than by reading the source, because the
+panel fires this endpoint on every settings change and a regression here is a Hub round
+trip, a disk write, or a reaped llama-server behind a slider drag.
Four properties, one section each:
-* the on-disk gate (``_estimate_target_is_on_this_disk``) is fail-OPEN on every
- error path, so this pins exactly which hosts fall through it into the network.
+* the on-disk gate (``_estimate_target_is_on_this_disk``) is fail-OPEN on every error
+ path, so this pins which hosts fall through it into the network;
* ``_probe_backend``'s ``except TypeError`` must not turn a fault raised INSIDE a
- constructor into a silently process-reaping backend.
-* the blocking capability probe belongs off the event loop, the way
- ``_effective_default_slots`` already puts it there.
-* both TTL caches are shared mutable module state reached from
- ``asyncio.to_thread`` workers, i.e. from real threads.
-
-No GPU, no network, no model load: every GGUF here is a synthetic header on
-tmp_path. Cross-platform.
+ constructor into a silently process-reaping backend;
+* the blocking capability probe belongs off the event loop, where
+ ``_effective_default_slots`` already puts it;
+* both TTL caches are shared mutable module state reached from real threads.
+
+No GPU, no network, no model load: every GGUF here is a synthetic header on tmp_path.
"""
import sys
@@ -238,20 +235,19 @@ class TestTheOnDiskGateAndTheNetwork:
assert ri._estimate_target_is_on_this_disk("org/definitely-not-cached") is True
def test_a_gate_that_could_not_be_answered_never_resolves_online(self, monkeypatch):
- # THE claim under test. The PR body says "no model is loaded, no device is
- # touched, nothing is downloaded", and the gate exists to keep that true by
+ # THE claim under test: "nothing is downloaded", which the gate keeps true by
# stopping from_identifier before it walks to the Hub.
#
- # But the gate fails OPEN, and what it falls through to is not merely a local
- # resolution: _cached_estimate_config tries offline first and then RETRIES
- # ONLINE. So on a host where no cache root can be established, an uncached
- # remote id gets the full identification -- model_info attempts and an
- # hf_hub_download of config.json, which writes blob, ref, snapshot and lock
- # into the HF cache -- for a request whose answer is "not on this disk".
+ # But the gate fails OPEN, and it falls through to more than a local resolution:
+ # _cached_estimate_config tries offline first and then RETRIES ONLINE. On a host
+ # where no cache root can be established, an uncached remote id therefore gets
+ # the full identification -- model_info attempts plus an hf_hub_download of
+ # config.json writing blob, ref, snapshot and lock -- for a request whose answer
+ # is "not on this disk".
#
- # The observable is the offline switch itself, not a socket: force_hf_offline
- # flips huggingface_hub's own constant, so a resolution that sees it False is
- # a resolution that was allowed to dial out.
+ # The observable is the offline switch, not a socket: force_hf_offline flips
+ # huggingface_hub's own constant, so a resolution seeing it False was allowed to
+ # dial out.
monkeypatch.setattr(ri, "_estimate_hf_cache_roots", list)
offline_at_each_call = []
@@ -400,17 +396,15 @@ class TestInertProbeFallback:
"""``_probe_backend`` must not answer a fault with a process-reaping backend."""
def test_a_fault_inside_the_constructor_is_not_answered_by_reaping(self, monkeypatch):
- # The fallback exists for stand-ins that PREDATE the keyword: two in
+ # The fallback is for stand-ins that PREDATE the keyword -- two in
# test_chat_load_during_training.py are plain classes taking no arguments, so
- # `LlamaCppBackend(manages_processes = False)` is a signature TypeError there
- # and the bare constructor is both compatible and correct.
+ # the keyword is a signature TypeError and the bare constructor is correct.
#
- # A TypeError raised from INSIDE __init__ is a different animal and lands in
- # the same except. The bare constructor it falls back to runs
- # _kill_orphaned_servers -- which walks /proc and SIGNALS the llama-servers it
- # recognises -- and registers an atexit handler holding the instance forever.
- # So a fault becomes "reap the user's running server", on a route the settings
- # panel fires on every change, and it does it silently.
+ # A TypeError raised from INSIDE __init__ lands in the same except, and the bare
+ # constructor it falls back to runs _kill_orphaned_servers, which walks /proc and
+ # SIGNALS the llama-servers it recognises, then registers an atexit handler
+ # holding the instance forever. A fault would silently become "reap the user's
+ # running server", on a route the panel fires on every change.
constructions = []
reaps = []
@@ -510,20 +504,17 @@ class TestSlotResolutionStaysOffTheEventLoop:
def test_the_capability_probe_never_runs_on_the_event_loop_thread(
self, monkeypatch, side_effect_gguf
):
- # _effective_parallel_slots asks the binary whether it supports --kv-unified.
- # _find_llama_server_binary walks nine candidate layouts on every call, before
- # the capability cache is even consulted, and retries a denied one five times
- # at 0.2s; on a cold cache the probe itself is `llama-server --help` with a ten
- # second timeout.
+ # _effective_parallel_slots asks the binary about --kv-unified, and
+ # _find_llama_server_binary walks nine layouts per call before the capability
+ # cache is consulted, retrying a denied one five times at 0.2s; on a cold cache
+ # the probe is `llama-server --help` with a ten second timeout.
#
- # This route's own sibling already knows: _effective_default_slots wraps the
- # same helper in asyncio.to_thread, and its docstring records that calling it
- # inline "stalled every other request on the first open of the panel after an
- # update". The loop this route runs on is the one streaming chat tokens.
+ # The sibling already knows: _effective_default_slots wraps the same helper in
+ # asyncio.to_thread because inline it "stalled every other request on the first
+ # open of the panel after an update". This route's loop streams chat tokens.
#
- # Asserted by thread identity rather than by a stopwatch: it is the same
- # property, it cannot flake under a loaded xdist runner, and it says which
- # thread the work belongs on instead of how slow it was allowed to be.
+ # Asserted by thread identity, not a stopwatch: same property, cannot flake
+ # under a loaded xdist runner, and it names the thread the work belongs on.
_priced_locally(monkeypatch, side_effect_gguf)
probe_threads = []
diff --git a/studio/frontend/src/features/model-picker/api/memory-estimate.ts b/studio/frontend/src/features/model-picker/api/memory-estimate.ts
index 0baf2babf23..cd30046819b 100644
--- a/studio/frontend/src/features/model-picker/api/memory-estimate.ts
+++ b/studio/frontend/src/features/model-picker/api/memory-estimate.ts
@@ -162,14 +162,11 @@ function estimateRequestBody(
/**
* A byte count the row can show, or the fallback.
*
- * `??` alone only defends against null and undefined, which is not the same as
- * defending against a value: JSON.parse turns `1e999` into Infinity without
- * complaint, a field can arrive as a string from a backend that stringified its
- * numbers, and a negative byte count is not a footprint. Each of those reaches
- * classifyMemoryFit, and NaN there used to come back "fits".
- *
- * Deliberately preserves the two skew fallbacks: an ABSENT key still falls through to
- * whatever the caller passes as the fallback, and an explicit 0 is a real answer.
+ * `??` defends against null and undefined, not against a value: JSON.parse turns
+ * `1e999` into Infinity, a field can arrive stringified, and a negative byte count is
+ * not a footprint. All three reach classifyMemoryFit, where NaN used to come back
+ * "fits". Both skew fallbacks are preserved: an ABSENT key falls through to the
+ * caller's fallback, and an explicit 0 is a real answer.
*/
function finiteBytes(value: unknown, fallback: number): number {
return typeof value === "number" && Number.isFinite(value) && value >= 0
@@ -260,14 +257,14 @@ function routeAbsentStatus(status: number): boolean {
/**
* How long a structural miss is trusted before the next qualifying change re-probes.
*
- * The memo is worth having: this route is POSTed after EVERY settings change, so a
- * new bundle against an old backend fires one debounced request per slider release
- * for the life of the tab, each landing in the API monitor as a 404.
+ * Worth memoing: this route is POSTed after EVERY settings change, so a new bundle
+ * against an old backend fires one debounced request per slider release for the life
+ * of the tab, each landing in the API monitor as a 404.
*
- * It must not be PERMANENT. Studio replaces its own backend in place -- an upgrade, a
- * server-wide reload -- and a latched miss would keep the row hidden on a backend that
- * has since gained the route until the window itself is reloaded. A window costs at
- * most one wasted POST per window and heals with no plumbing to any restart signal.
+ * Not PERMANENT, though. Studio replaces its own backend in place, and a latched miss
+ * would keep the row hidden on a backend that has since gained the route until the
+ * window reloads. A TTL costs one wasted POST per window and heals with no plumbing to
+ * a restart signal.
*/
const ROUTE_ABSENT_TTL_MS = 5 * 60 * 1000;
let routeAbsentAt: number | null = null;
diff --git a/studio/frontend/src/features/model-picker/components/model-config-page.tsx b/studio/frontend/src/features/model-picker/components/model-config-page.tsx
index 6d65d428d32..5eacf085e48 100644
--- a/studio/frontend/src/features/model-picker/components/model-config-page.tsx
+++ b/studio/frontend/src/features/model-picker/components/model-config-page.tsx
@@ -2821,21 +2821,20 @@ export function ModelConfigPage({
unsubscribe();
};
}, []);
- // What is free RIGHT NOW on the cards this load may use. _select_gpus admits on
- // free-minus-reserve, not on the cards' totals, so a training run or another process
- // holding VRAM changes what will actually happen to this load.
+ // What is free RIGHT NOW on the cards this load may use: _select_gpus admits on
+ // free-minus-reserve, not on totals, so another process holding VRAM changes what
+ // happens to this load.
//
- // Used to WARN, never to refuse. The bytes a pending load reclaims -- the resident
- // chat model's own, which Studio unloads first -- cannot be attributed per device
- // from here, so raw free memory would call a reload of the loaded model impossible.
- // Capping the free-based verdict at "tight" is honest under both readings: either
- // something else really is holding the card, or it is about to be given back.
- // A fixed Manual placement is launched verbatim: load_model empties its probed GPU
- // set (gpus = []) and emits --gpu-layers N --fit off, so the server-wide VRAM Budget
- // never reaches the planner and cannot shrink this load. Discounting capacity by it
- // there labelled placements that will load fine as exceeding -- a 16 GiB fixed
- // placement on a 24 GiB card reads as over budget at 50%. Auto is still budgeted,
- // because Auto is exactly the mode that hands the decision to the planner.
+ // WARNS, never refuses. The bytes a pending load reclaims are mostly the resident
+ // model's own, which Studio unloads first, and cannot be attributed per device from
+ // here, so raw free memory would call reloading the loaded model impossible. Capping
+ // the verdict at "tight" is honest either way.
+ //
+ // A fixed Manual placement is launched verbatim -- load_model empties its probed GPU
+ // set and emits --gpu-layers N --fit off -- so the server-wide VRAM Budget never
+ // reaches the planner. Discounting capacity by it called a 16 GiB fixed placement on
+ // a 24 GiB card over budget at 50%. Auto is still budgeted: Auto is the mode that
+ // hands the decision to the planner.
const memoryBudgetGovernsLaunch =
runtimeGpuMemoryMode !== "manual" ||
(runtimeConfig.gpuLayers ?? GPU_LAYERS_AUTO) < 0;
@@ -3107,14 +3106,13 @@ export function ModelConfigPage({
usableSystemRamGb={Math.max(
0,
// _HOST_RAM_HEADROOM_MIB: the 2 GiB the loader keeps for the rest of
- // the system before it will admit an offloaded load.
+ // the system before admitting an offloaded load.
//
- // The HOST reading, not the sum-shaped one beside it. That one is
- // zeroed whenever ANY device on the machine shares system RAM, which
- // is every dGPU + iGPU box, so this figure was permanently 0 there
- // and the host-pressure advisory could not fire even under a pin on
- // the discrete card -- exactly the case where host RAM really is a
- // separate pool.
+ // The HOST reading, not the sum-shaped one beside it, which is zeroed
+ // whenever ANY device shares system RAM -- every dGPU + iGPU box -- so
+ // this was permanently 0 there and the host-pressure advisory could not
+ // fire even under a pin on the discrete card, the one case where host
+ // RAM really is a separate pool.
(inferenceGpu.systemRamAvailableHostGb || 0) - 2,
)}
isUnifiedMemory={isUnifiedMemory}
diff --git a/studio/frontend/src/features/model-picker/hooks/use-memory-estimate.ts b/studio/frontend/src/features/model-picker/hooks/use-memory-estimate.ts
index f77b7d16258..9300f1df39a 100644
--- a/studio/frontend/src/features/model-picker/hooks/use-memory-estimate.ts
+++ b/studio/frontend/src/features/model-picker/hooks/use-memory-estimate.ts
@@ -63,11 +63,10 @@ export function useMemoryEstimate(
request: MemoryEstimateRequest | null,
): MemoryEstimateState {
const key = estimateKey(request);
- // Which source the CURRENT render is for, computed during render rather than read
- // from a ref the effect updates after paint. The effect below still clears on a
- // switch, but it runs after React has already painted this render, so a direct
- // switch between two GGUFs showed the previous model's footprint and fit colour
- // under the new name for a frame. Both helpers are pure, so this is safe here.
+ // Computed during render, not read from a ref the effect updates after paint: the
+ // effect below still clears on a switch, but it runs after React has painted, so a
+ // direct switch between two GGUFs showed the previous model's footprint and fit
+ // colour under the new name for a frame. Both helpers are pure, so this is safe.
const currentIdentity =
request == null
? null
diff --git a/studio/frontend/src/features/model-picker/model-config/estimate-context.ts b/studio/frontend/src/features/model-picker/model-config/estimate-context.ts
index e23bd38fc01..a5d1b32cc23 100644
--- a/studio/frontend/src/features/model-picker/model-config/estimate-context.ts
+++ b/studio/frontend/src/features/model-picker/model-config/estimate-context.ts
@@ -2,27 +2,24 @@
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
/**
- * The context the memory estimate should PRICE, which is not always the context
- * the Context Length control DISPLAYS.
+ * The context the memory estimate should PRICE, which is not always the one the
+ * Context Length control DISPLAYS.
*
- * The control has to show a number even before a new GGUF's header has been read,
- * and falls back to 32,768 for that. The Load button does not: an unset length is
- * sent as 0 and llama.cpp fits, or opens at the model's native context. Pricing the
- * displayed fallback therefore quotes an explicit 32k for a load that may well open
- * at 262k, and understates by the KV cache, the term that grows fastest with
- * context.
+ * The control must show a number before a new GGUF's header has been read and falls
+ * back to 32,768. The Load button does not: an unset length is sent as 0 and llama.cpp
+ * fits, or opens at the model's native context. Pricing the displayed fallback quotes
+ * an explicit 32k for a load that may open at 262k, understating the KV cache -- the
+ * term that grows fastest with context. 0 is the request's own "price the native
+ * context", resolved from the header exactly as the launch would.
*
- * 0 is the estimate request's own "price the native context", so the backend
- * resolves it from the header exactly as the launch would.
+ * The fallbacks are `resolveLoadMaxSeqLength`'s, in its order and no further: an
+ * explicit length is itself, reloading the resident GGUF keeps the context it is
+ * resident AT, every other GGUF case is 0. The native context is deliberately NOT a
+ * fallback -- --fit can land below it, so quoting it claims an outcome the load has
+ * not reached.
*
- * The fallbacks are `resolveLoadMaxSeqLength`'s, in its order and no further:
- * an explicit length is itself, reloading the GGUF that is already resident keeps
- * the context it is resident AT, and every other GGUF case is 0. The native
- * context deliberately is NOT a fallback -- llama.cpp's --fit can land below it,
- * so quoting it as a figure claims an outcome the load has not reached.
- *
- * Kept in its own module with no imports so `tests/` can load it under
- * `node --experimental-strip-types`, which does not resolve the `@/` alias.
+ * Import-free so `tests/` can load it under `node --experimental-strip-types`, which
+ * does not resolve the `@/` alias.
*/
export function resolveEstimateContext(
customContextLength: number | null,
@@ -31,15 +28,10 @@ export function resolveEstimateContext(
): number {
if (skipResidentFallback) {
// Two shapes reach here, and `resolveLoadMaxSeqLength` answers 0 for both before
- // it ever considers the resident context:
- //
- // * Manual memory mode with GPU Layers on Auto, where llama.cpp --fit owns the
- // sizing (`resolveFitMaxSeqLength`);
- // * a builtin-default preset on a GGUF load, which returns 0 outright.
- //
- // In both, pricing what is loaded RIGHT NOW quotes the OLD fit, and it does so
- // precisely when a context-sensitive setting has just changed and the next fit
- // will land somewhere else.
+ // considering the resident context: Manual mode with GPU Layers on Auto, where
+ // --fit owns the sizing, and a builtin-default preset on a GGUF load. In both,
+ // pricing what is loaded RIGHT NOW quotes the OLD fit -- precisely when a
+ // context-sensitive setting has just changed and the next fit lands elsewhere.
return customContextLength && customContextLength > 0 ? customContextLength : 0;
}
return customContextLength ?? activeLoadedContext ?? 0;
diff --git a/studio/frontend/src/features/model-picker/model-config/memory-fit.ts b/studio/frontend/src/features/model-picker/model-config/memory-fit.ts
index 0eea1e416fa..6b894b9e694 100644
--- a/studio/frontend/src/features/model-picker/model-config/memory-fit.ts
+++ b/studio/frontend/src/features/model-picker/model-config/memory-fit.ts
@@ -5,15 +5,11 @@
* How the estimated footprint sits against the memory available to hold it, and the
* single note the row prints about it.
*
- * Split out of model-config-page.tsx for the reason the sibling estimate-context.ts
- * gives: kept with NO imports so `tests/` can load it under
- * `node --experimental-strip-types`, which does not resolve the `@/` alias. Living
- * inside a 3,400-line .tsx made this chain unreachable from the test runner, and a
- * ternary arm that could never be taken survived review there for exactly that
- * reason (see the pool note on the advisory below).
- *
- * Everything here is pure and typed structurally, so a MemoryEstimate satisfies the
- * inputs without importing it.
+ * Import-free, like the sibling estimate-context.ts, so `tests/` can load it under
+ * `node --experimental-strip-types`, which does not resolve the `@/` alias. Inside a
+ * 3,400-line .tsx this chain was unreachable from the test runner, and a ternary arm
+ * that could never be taken survived review for exactly that reason. Everything is
+ * pure and typed structurally, so a MemoryEstimate satisfies the inputs.
*/
/** How an estimated footprint sits against the memory available to hold it. */
@@ -25,12 +21,10 @@ export const MEMORY_FIT_TIGHT_RATIO = 0.85;
/**
* Classify a footprint against a capacity.
*
- * Every non-finite input is "unknown". `<= 0` alone does not cover it: NaN and
- * Infinity both fail every comparison, so `NaN <= 0` is false and the ratio test
- * below then falls all the way through to "fits" -- a confident green verdict
- * printed from a number that does not exist. A malformed or hostile response gets
- * there without trying, because JSON.parse turns `1e999` into Infinity and a
- * `?? 0` default never sees it.
+ * Every non-finite input is "unknown", and `<= 0` alone does not cover it: NaN and
+ * Infinity fail every comparison, so `NaN <= 0` is false and the ratio test falls
+ * through to "fits" -- a green verdict from a number that does not exist. JSON.parse
+ * turns `1e999` into Infinity and a `?? 0` default never sees it.
*/
export function classifyMemoryFit(
bytes: number,
@@ -70,11 +64,10 @@ export function worseMemoryFit(
}
/**
- * GB, to two decimals, matching how the rest of the panel talks about memory.
+ * GB, to two decimals, as the rest of the panel talks about memory.
*
- * Clamped rather than trusted. Every figure here comes off the wire, and a negative
- * or non-finite one has no honest rendering: "-3.00 GB" and "NaN GB" both read as a
- * measurement rather than as the missing reading they are.
+ * Clamped, not trusted: these come off the wire, and "-3.00 GB" or "NaN GB" reads as
+ * a measurement rather than as the missing reading it is.
*/
export function formatMemoryGb(bytes: number): string {
const safe = Number.isFinite(bytes) && bytes > 0 ? bytes : 0;
@@ -148,11 +141,10 @@ export interface MemoryFitResult {
* Every verdict the row shows, plus the one note it prints.
*
* `_host_offload_shortfall_message` refuses a load whose offloaded weights exceed
- * psutil's AVAILABLE memory less a reserve, not the machine's physical total, so a
- * 70 GB host share read as fitting a 128 GB box with 32 GB free. The free-memory
- * verdicts here WARN rather than refuse for one reason: the bytes a pending load
- * reclaims are mostly the resident model's own, which Studio unloads first, and
- * those cannot be attributed from here.
+ * psutil's AVAILABLE memory less a reserve, not the physical total, so a 70 GB host
+ * share read as fitting a 128 GB box with 32 GB free. The free-memory verdicts here
+ * WARN instead: the bytes a pending load reclaims are mostly the resident model's
+ * own, which Studio unloads first, and cannot be attributed from here.
*/
export function resolveMemoryFit(
estimate: MemoryFitEstimate,
@@ -160,20 +152,18 @@ export function resolveMemoryFit(
): MemoryFitResult {
const { singleMemoryPool } = capacity;
const rawGpuFit = classifyMemoryFit(estimate.gpuBytes, capacity.gpuCapacityGb);
- // One pool means the WHOLE load draws on that memory, so the pressure question is
- // asked of the total there rather than of a GPU share that is not a separate
- // reservation. Same rule the host side already used; asking it of gpuBytes alone
- // let a partly CPU-offloaded load on a Vulkan iGPU look comfortable against free
- // memory that has to hold all of it.
+ // One pool means the WHOLE load draws on that memory, so the pressure question goes
+ // to the total rather than to a GPU share that is not a separate reservation. Asking
+ // it of gpuBytes alone let a partly CPU-offloaded load on a Vulkan iGPU look
+ // comfortable against free memory that has to hold all of it.
const freeGpuFit = classifyMemoryFit(
singleMemoryPool ? estimate.totalBytes : estimate.gpuBytes,
capacity.freeGpuCapacityGb,
);
const gpuPressured = freeGpuFit === "exceeds" || freeGpuFit === "tight";
- // Guarded rather than subtracted blind: a non-finite figure off the wire makes the
- // difference NaN, which `Math.max(0, ...)` propagates rather than clamps. 0 is the
- // same verdict from classifyMemoryFit ("unknown") and is a number a caller can
- // print, which NaN is not.
+ // Guarded, not subtracted blind: a non-finite figure makes the difference NaN, which
+ // `Math.max(0, ...)` propagates rather than clamps. 0 classifies the same ("unknown")
+ // and is printable, which NaN is not.
const hostShareBytes =
Number.isFinite(estimate.totalBytes) && Number.isFinite(estimate.gpuBytes)
? Math.max(0, estimate.totalBytes - estimate.gpuBytes)
@@ -185,11 +175,9 @@ export function resolveMemoryFit(
);
const hostPressured = usableHostFit === "exceeds" || usableHostFit === "tight";
const gpuFit = rawGpuFit === "fits" && gpuPressured ? "tight" : rawGpuFit;
- // The host share has to fit in host RAM on its own. Unused VRAM cannot hold bytes
- // that placement has pinned outside the GPU, so weighing only the combined ceiling
- // called a 70 GB CPU placement a fit on a 24 GB card plus 64 GB of RAM. Skipped
- // where the two are one pool, which is the case the combined figure already
- // describes exactly.
+ // The host share must fit host RAM on its own: unused VRAM cannot hold bytes pinned
+ // outside the GPU, so the combined ceiling alone called a 70 GB CPU placement a fit
+ // on a 24 GB card plus 64 GB of RAM. Skipped where the two are one pool.
const hostShareFit: MemoryFitVerdict = singleMemoryPool
? "unknown"
: classifyMemoryFit(hostShareBytes, capacity.systemRamCapacityGb);
@@ -197,11 +185,10 @@ export function resolveMemoryFit(
classifyMemoryFit(estimate.totalBytes, capacity.totalCapacityGb),
hostShareFit,
);
- // Lower bound, not an estimate. Two ways to get there, and both UNDER-count by a
- // term that grows with context: no attention dims, so the target cache is missing,
- // or a drafter that is a repository rather than a file on this disk, so its cache
- // is missing while its weights are counted. The advisory below still tells them
- // apart, because the two are not fixed the same way.
+ // Lower bound, not an estimate. Both routes here UNDER-count by a term that grows
+ // with context: no attention dims, so the target cache is missing, or a drafter that
+ // is a repository rather than a file on disk, so its cache is missing while its
+ // weights are counted. The advisory still tells them apart -- different fixes.
const bounded =
!estimate.kvEstimable || estimate.drafterKvUnsized || estimate.adaptersUnsized;
return {
@@ -242,17 +229,15 @@ interface AdvisoryVerdicts {
* At most one note, most actionable first.
*
* An unsizable cache outranks any verdict drawn from the figures, since it says they
- * are incomplete. It branches on `kvEstimable` rather than on `bounded`: both make
- * the figures a floor, but only this one is about the header, and the drafter case
- * below names its own cause.
+ * are incomplete. Branches on `kvEstimable`, not `bounded`: both make the figures a
+ * floor, but only this one is about the header.
*
- * The pool split below used to gate the whole tail, which made the shared-pool
- * pressure copy dead code -- it sat inside the `singleMemoryPool === false` arm and
- * re-tested `singleMemoryPool`, so the string could never be chosen -- and left a
- * single-pool host with exactly one reachable note, "exceeds". An Apple machine or a
- * Vulkan iGPU therefore never warned that a load fitting the machine did not fit
- * what was free. The pool question now decides the WORDING and which figures are
- * compared, not whether the pressure branch exists at all.
+ * The pool split used to gate the whole tail, which made the shared-pool pressure copy
+ * dead code -- it sat inside the `singleMemoryPool === false` arm and re-tested
+ * `singleMemoryPool` -- leaving a single-pool host one reachable note, "exceeds". An
+ * Apple machine or a Vulkan iGPU never warned that a load fitting the machine did not
+ * fit what was free. The pool question now decides the WORDING and which figures are
+ * compared, not whether the branch exists.
*/
export function resolveMemoryAdvisory(
estimate: MemoryFitEstimate,
diff --git a/studio/frontend/tests/memory-estimate-capacity.test.ts b/studio/frontend/tests/memory-estimate-capacity.test.ts
index 9690641e8d5..6c185867bd4 100644
--- a/studio/frontend/tests/memory-estimate-capacity.test.ts
+++ b/studio/frontend/tests/memory-estimate-capacity.test.ts
@@ -51,12 +51,11 @@ test("a pin on the iGPU does not offer its own RAM twice, nor throw the rest awa
});
test("pinning both keeps the discrete card as a pool beside system RAM", () => {
- // This asserted 96 and the reasoning given was that under-counting the dGPU refuses
- // a load rather than admitting one, so it was the safe direction. That was wrong,
- // and only half the effect was being looked at: the flag it also sets makes the row
- // show a lone Shared figure and drop the GPU verdict entirely, so a fixed placement
- // larger than the discrete card had nothing left to catch it. Two pools now, with
- // the ceiling counting the shared bytes once: 16 dedicated + 96 RAM, not 28 + 96.
+ // This asserted 96, on the reasoning that under-counting the dGPU refuses a load
+ // rather than admitting one. That looked at half the effect: the flag it also sets
+ // makes the row show a lone Shared figure and drop the GPU verdict, so a fixed
+ // placement larger than the discrete card had nothing to catch it. Two pools now,
+ // counting the shared bytes once: 16 dedicated + 96 RAM, not 28 + 96.
const capacity = resolveMemoryCapacityGb({
...HOST,
pinnedDevices: [DGPU, IGPU, IGPU],
diff --git a/studio/frontend/tests/memory-estimate-identity.test.ts b/studio/frontend/tests/memory-estimate-identity.test.ts
index 150e396231c..8caf0bc8618 100644
--- a/studio/frontend/tests/memory-estimate-identity.test.ts
+++ b/studio/frontend/tests/memory-estimate-identity.test.ts
@@ -3,13 +3,12 @@
// What useMemoryEstimate is allowed to leave on screen.
//
-// Two rules, and they are not the same rule. A settings change GREYS the figures and
-// keeps them up, so a slider drag does not strobe the row. A SOURCE change blanks
-// them, because one model's footprint under another model's name is worse than no
-// footprint at all. The hook decides both from `resolveEstimateSourceIdentity`, which
-// is the narrower key, and it computes it DURING RENDER rather than reading a ref its
-// effect updates after paint -- an effect runs after React has painted, so a direct
-// switch between two GGUFs showed the previous model's numbers for a frame.
+// Two different rules. A settings change GREYS the figures and keeps them up, so a
+// slider drag does not strobe the row; a SOURCE change blanks them, because one
+// model's footprint under another's name is worse than none. Both come from
+// `resolveEstimateSourceIdentity`, the narrower key, computed DURING RENDER rather than
+// read from a ref the effect updates after paint -- effects run after React paints, so
+// a direct switch between two GGUFs showed the previous model's numbers for a frame.
//
// The credential is part of the source, hashed rather than carried. That hash is 32
// bits, and the last test here is what that costs.
diff --git a/studio/frontend/tests/memory-estimate-skew.test.ts b/studio/frontend/tests/memory-estimate-skew.test.ts
index ea60ace990f..f1c96970f55 100644
--- a/studio/frontend/tests/memory-estimate-skew.test.ts
+++ b/studio/frontend/tests/memory-estimate-skew.test.ts
@@ -3,16 +3,16 @@
// Version skew in both directions across /api/inference/estimate-memory.
//
-// OLD BACKEND + NEW BUNDLE: the route is not there. Every failure shape has to reach
-// the panel as an unavailable estimate -- the row hides itself, and the Load button
-// beside it is not a party to any of this -- and the one shape that says the ROUTE is
-// missing, rather than that this request failed, is worth remembering so a slider drag
-// does not POST into the void once per settings change forever.
+// OLD BACKEND + NEW BUNDLE: the route is not there. Every failure shape must reach the
+// panel as an unavailable estimate -- the row hides, and the Load button is not a party
+// to any of it -- and the shape that says the ROUTE is missing, rather than that this
+// request failed, is worth remembering so a slider drag does not POST into the void
+// once per settings change forever.
//
// NEW BACKEND + OLD BUNDLE is not a thing (the bundle ships with the backend), but the
-// reverse of the field-level question is: a backend PREDATING the drafter split, or
-// one that never learned to report kv_estimable, must degrade to the documented
-// fallbacks rather than to a confident zero.
+// field-level reverse is: a backend predating the drafter split, or one that never
+// reported kv_estimable, must degrade to the documented fallbacks, not to a confident
+// zero.
import assert from "node:assert/strict";
import { register } from "node:module";
diff --git a/tests/studio/playwright_memory_estimate.py b/tests/studio/playwright_memory_estimate.py
index e74ee678843..b11e5587530 100644
--- a/tests/studio/playwright_memory_estimate.py
+++ b/tests/studio/playwright_memory_estimate.py
@@ -79,25 +79,22 @@ GGUF_REPO = os.environ.get("GGUF_REPO", "unsloth/gemma-3-270m-it-GGUF")
GGUF_VARIANT = os.environ.get("GGUF_VARIANT", "UD-Q4_K_XL")
# Substring of the picker row for the model whose run settings this drives.
#
-# Defaulted from GGUF_REPO rather than to a bare family name, and that is not cosmetic:
-# the row lookup takes `.first`, so a hint that also matches a NON-GGUF sibling opens
-# whichever the picker happens to order first. On a cache holding both
-# `gemma-3-270m-it-GGUF` and `gemma-3-270m-it-unsloth-bnb-4bit`, "gemma-3-270m" opened the
-# bnb-4bit safetensors panel -- which has no Context Length control and no memory row at
-# all, because the row is GGUF-only -- and the whole suite then reported the feature
-# missing. The repo's own name cannot collide that way.
+# From GGUF_REPO rather than a bare family name, and not cosmetically: the row lookup
+# takes `.first`, so a hint matching a NON-GGUF sibling opens whichever the picker orders
+# first. On a cache holding both `gemma-3-270m-it-GGUF` and
+# `gemma-3-270m-it-unsloth-bnb-4bit`, "gemma-3-270m" opened the bnb-4bit safetensors
+# panel -- no Context Length control, no memory row, the row being GGUF-only -- and the
+# suite reported the feature missing. The repo's own name cannot collide that way.
MODEL_HINT = os.environ.get("STUDIO_MODEL_HINT") or GGUF_REPO.rsplit("/", 1)[-1]
-# Context Lengths to drive the four re-prices with. Each has to be valid (>=128, a
-# multiple of 128, under the model's ceiling) and, crucially, DIFFERENT from whatever the
-# control is showing at the time.
+# Context Lengths for the four re-prices. Each must be valid (>=128, a multiple of 128,
+# under the model's ceiling) and DIFFERENT from what the control is showing at the time.
#
-# That last part is a real property of the control, not a precaution. The box reads "Auto"
-# until it has focus and then reveals the context the load would fit to -- 8192 on
-# gemma-3-270m here -- and typing the number already displayed commits no onChange, so the
-# request key never moves and no re-price happens at all. Measured: typing 8192 into a box
-# showing 8192 produced zero requests and the box fell back to "Auto"; every other value
-# produced one. So the value is chosen at the moment of typing, against what the box says,
-# from this pool rather than fixed per step.
+# That last part is a property of the control, not a precaution: the box reads "Auto"
+# until focused and then reveals the context the load would fit to (8192 here), and
+# typing the number already displayed commits no onChange, so the request key never moves
+# and no re-price happens. Measured: typing 8192 into a box showing 8192 produced zero
+# requests; every other value produced one. Hence chosen at the moment of typing, against
+# what the box says, rather than fixed per step.
CTX_CANDIDATES = [
int(part)
for part in os.environ.get("STUDIO_CTX_CANDIDATES", "6144,5120,4096,3072,2048,1536").split(",")
@@ -1030,18 +1027,17 @@ with sync_playwright() as p:
# ─────────────────────────────────────────────────────
# 6. A 404 from a backend predating the route also HIDES it (HARD).
#
- # LAST, and it has to be last. A non-OK answer stops the panel re-pricing for the rest
- # of its life: measured here, after one 404 the Context Length control keeps taking new
- # values and committing them -- 3072, 2048, 1536, each held by the box -- and NO further
- # POST /api/inference/estimate-memory is ever made, on any of them. `available: false`
- # does not do that; the panel re-prices normally after one, which is why the restore
- # gate above sits with the unavailable case and not with this one.
+ # LAST, and it has to be. A non-OK answer stops the panel re-pricing for the rest of
+ # its life: measured here, after one 404 the Context Length control keeps taking and
+ # committing values -- 3072, 2048, 1536 -- and no further POST is ever made.
+ # `available: false` does not do that, which is why the restore gate above sits with
+ # the unavailable case rather than this one.
#
- # It costs nothing in the situation this gate is about, a backend predating the route,
- # since every answer there would be a 404 anyway and the row is meant to stay hidden.
- # It is only reachable by an endpoint that fails and then recovers. Ordering around it
- # rather than asserting it: this suite is about the row, and pinning the freeze here
- # would be pinning behaviour nobody has decided on.
+ # Harmless in the situation this gate is about, since a backend predating the route
+ # answers 404 to everything and the row is meant to stay hidden; it is only reachable
+ # by an endpoint that fails and then recovers. Ordered around rather than asserted:
+ # this suite is about the row, and pinning the freeze would pin behaviour nobody has
+ # decided on.
# ─────────────────────────────────────────────────────
step("HTTP 404 hides the row")
_mode[0] = "http404"