Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Add Estimated Memory Usage to the Load Model panel (#9525)
Michael Hanb26ca1194a5f
diff --git a/.github/workflows/studio-ui-smoke.yml b/.github/workflows/studio-ui-smoke.ymlindex d9a584101e6..0f3cabac18b 100644--- a/.github/workflows/studio-ui-smoke.yml+++ b/.github/workflows/studio-ui-smoke.yml@@ -698,6 +698,32 @@ jobs:mkdir -p logs/playwright_modelcfgpython tests/studio/playwright_model_config.py+ # "Estimated Memory Usage" row in the same run-settings panel: the collapsible+ # readout that prices a prospective GGUF load before it runs.+ #+ # On the fourth Unsloth rather than a fifth, and immediately after the step above,+ # for two reasons. The row is GGUF-only, so it needs a GGUF sitting in the picker,+ # and that step has just put one there. And it needs nothing else from the server:+ # POST /api/inference/estimate-memory is intercepted in the browser, so the figures+ # under assertion are the ones the suite handed back rather than this runner's own+ # memory, which is what makes them assertable at all.+ #+ # It attaches with the password the step above minted instead of driving+ # /change-password itself: the bootstrap password on this instance has already been+ # rotated by then, so there is no first-boot flow left to drive.+ - name: Estimated Memory Usage row (Playwright)+ if: matrix.shard == 'picker'+ env:+ BASE_URL: http://127.0.0.1:18898+ STUDIO_LOGIN_PW: ${{ env.STUDIO_MODELCFG_NEW_PW }}+ PW_ART_DIR: logs/playwright_memory_estimate+ STUDIO_UI_STRICT: '1'+ GGUF_REPO: ${{ env.GGUF_REPO }}+ GGUF_VARIANT: ${{ env.GGUF_VARIANT }}+ run: |+ mkdir -p logs/playwright_memory_estimate+ python tests/studio/playwright_memory_estimate.py+- name: Stop fourth Unslothif: (always()) && (matrix.shard == 'picker')run: |@@ -786,6 +812,7 @@ jobs:logs/playwright_image_cancel_retrylogs/playwright_image_cancel_retry_coldlogs/playwright_modelcfg+ logs/playwright_memory_estimatelogs/playwright_imelogs/studio-permissions-*.log# 1 day, matching the repository-wide cap. A larger value here isdiff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.pyindex c6cba23eebf..9b3467cd909 100644--- a/studio/backend/core/inference/llama_cpp.py+++ b/studio/backend/core/inference/llama_cpp.py@@ -4981,7 +4981,24 @@ class LlamaCppBackend:3. unload_model(): terminate the subprocess"""- def __init__(self):+ 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.+ """self._process: Optional[subprocess.Popen] = Noneself._port: Optional[int] = Noneself._model_identifier: Optional[str] = None@@ -5271,12 +5288,13 @@ class LlamaCppBackend:# to decide whether to wait for the VRAM reclaim to finish.self._last_kill_monotonic: float = 0.0- _reaped = self._kill_orphaned_servers()- if _reaped:- # Reaped VRAM frees lazily; arm the settle wait so the first load- # waits before ranking GPUs by free memory.- self._last_kill_monotonic = time.monotonic()- atexit.register(self._cleanup)+ if manages_processes:+ _reaped = self._kill_orphaned_servers()+ if _reaped:+ # Reaped VRAM frees lazily; arm the settle wait so the first load+ # waits before ranking GPUs by free memory.+ self._last_kill_monotonic = time.monotonic()+ atexit.register(self._cleanup)# ── Properties ────────────────────────────────────────────────diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.pyindex 2e87db0d6e5..4dbe3bb2cdd 100644--- a/studio/backend/models/inference.py+++ b/studio/backend/models/inference.py@@ -712,6 +712,164 @@ class ValidateModelResponse(BaseModel):)+class EstimateMemoryRequest(BaseModel):+ """Settings a Load-Model panel is about to submit, priced before it submits them.++ Every field mirrors the load request it previews, so the estimate answers for the+ command that would actually run. Header-only: nothing is read, touched or loaded.+ """++ model_path: str = Field(..., description = "Model identifier or local path")+ gguf_variant: Optional[str] = Field(+ None, description = "GGUF quantization to price (e.g. Q4_K_M); the picked variant."+ )+ hf_token: Optional[str] = Field(None, description = "Token for gated repositories")+ native_path_lease: Optional[str] = Field(+ None,+ description = "Lease for a picked / drag-dropped .gguf, as /validate takes one.",+ )+ n_ctx: Optional[int] = Field(+ None,+ ge = 0,+ description = "Context length to price (--ctx-size). 0 or omitted prices the "+ "model's native context, which is what an Auto load asks for.",+ )+ cache_type_kv: Optional[str] = Field(+ None,+ description = "KV cache dtype to price. The biggest lever on this estimate at "+ "long contexts, so omitting it prices a load nobody asked for.",+ )+ n_parallel: Optional[int] = Field(+ None,+ ge = PARALLEL_MIN,+ le = PARALLEL_MAX,+ description = "Serving slots (--parallel); scales both the cache and the buffers.",+ )+ n_batch: Optional[int] = Field(None, ge = BATCH_MIN, le = BATCH_MAX)+ n_ubatch: Optional[int] = Field(None, ge = BATCH_MIN, le = BATCH_MAX)+ ctx_checkpoints: Optional[int] = Field(None, ge = 0, le = CTX_CHECKPOINTS_MAX)+ speculative_type: Optional[str] = Field(+ None, description = "Speculative mode; decides which drafter's weights are charged."+ )+ spec_draft_n_max: Optional[int] = Field(+ None,+ ge = 1,+ le = 16,+ description = "Draft depth. Sizes the drafter's rollback state, so it moves the "+ "estimate for every mode that loads a separate drafter.",+ )+ spec_draft_cache_type: Optional[str] = Field(+ None,+ description = "Draft KV cache dtype. The drafter keeps its own cache, and at a "+ "long context that is GB, not a rounding error.",+ )+ tensor_parallel: bool = Field(False, description = "Whether tensor mode is requested")+ disable_vision: bool = Field(+ False, description = "Vision off, so an image projector's bytes are not charged."+ )+ gpu_memory_mode: Optional[str] = Field(+ None, description = "'auto' or 'manual'; manual splits the weights by gpu_layers."+ )+ gpu_layers: Optional[int] = Field(+ None, ge = 0, description = "Layers pinned to the GPU under manual placement."+ )+ n_cpu_moe: Optional[int] = Field(+ None,+ ge = 0,+ description = "Expert layers held on the CPU (--n-cpu-moe). Not priced; echoed "+ "back so the panel can say the GPU figure reads high.",+ )+ selected_gpu_ids: Optional[List[int]] = Field(+ None,+ description = "GPUs the load is pinned to. Tensor mode replicates its compute "+ "buffers per device, so the pinned count changes the footprint.",+ )+ llama_extra_args: Optional[List[str]] = Field(+ None,+ description = "Pass-through llama-server flags. Read, not just carried: -c, "+ "-nkvo, --swa-full and the cache-type flags all move this estimate.",+ )++ _no_booleans = field_validator(+ "n_batch", "n_ubatch", "ctx_checkpoints", "n_ctx", mode = "before"+ )(LoadRequest._no_booleans.__func__)+++class EstimateMemoryResponse(BaseModel):+ """Itemized memory an inference load would occupy, or why it could not be sized."""++ available: bool = Field(..., description = "Whether a breakdown could be produced at all.")+ reason: Optional[str] = Field(+ None,+ description = "Cause when available is false: 'not_gguf', 'not_downloaded', "+ "'unsupported_source' or 'unsizable'.",+ )+ weights_bytes: int = Field(0, description = "Resident model files: weights, projector, drafter")+ kv_bytes: int = Field(0, description = "KV cache at the requested context and slots")+ compute_bytes: int = Field(0, description = "Compute / graph buffers, flat plus context-linear")+ drafter_runtime_bytes: int = Field(+ 0,+ description = "A separate drafter's own KV cache and rollback state, on top of "+ "its file in weights_bytes. Included in total_bytes, and in gpu_bytes unless the "+ "drafter is CPU-pinned. Reported separately so the itemization accounts for it.",+ )+ drafter_runtime_gpu_bytes: int = Field(+ 0,+ description = "The share of drafter_runtime_bytes that lands on the GPU. Not a "+ "placement flag, because the term is not placed as one piece: under MTP the "+ "target-side verification state follows the TARGET cache (so --no-kv-offload "+ "moves it) while the draft cache follows the drafter (so --spec-draft-ngl 0 "+ "moves that instead), and the two can go different ways in the same load.",+ )+ projector_runtime_bytes: int = Field(+ 0,+ description = "The vision encoder's buffers, about 0.4x the projector file on top "+ "of it. Included in total_bytes, and in gpu_bytes unless --no-mmproj-offload "+ "keeps the projector in host RAM.",+ )+ drafter_kv_unsized: bool = Field(+ False,+ description = "True when a drafter is charged whose cache could not be sized: "+ "--spec-draft-hf names a repository whose header is not on this disk. Its weights "+ "are in weights_bytes but its context-scaled cache is missing, so total_bytes is a "+ "lower bound.",+ )+ adapters_unsized: bool = Field(+ False,+ description = "True when a pass-through --lora / --lora-scaled / --control-vector / "+ "--control-vector-scaled names a file that could not be stat'd. llama.cpp loads every "+ "one of them into resident tensors on top of the base model, so those bytes are "+ "missing from total_bytes and it is a lower bound.",+ )+ total_bytes: int = Field(0, description = "Weights + KV + compute, wherever they land")+ gpu_bytes: int = Field(+ 0, description = "The share of total_bytes that lands on the GPU under this offload"+ )+ kv_estimable: bool = Field(+ True,+ description = "False when the GGUF header lacks the attention dims needed to "+ "size the cache. kv_bytes is then 0 meaning UNKNOWN and total_bytes is a lower "+ "bound; rendering it as a confident total is what this flag exists to prevent.",+ )+ kv_on_gpu: bool = Field(+ True, description = "False under --no-kv-offload, which moves the cache to host RAM"+ )+ n_ctx: int = Field(0, description = "Context length the estimate actually priced")+ cache_type_kv: Optional[str] = Field(+ None, description = "KV dtype the estimate priced, after flags and fallbacks resolve"+ )+ n_parallel: int = Field(1, description = "Slots the estimate priced, after the launch clamps")+ layer_count: Optional[int] = Field(None, description = "GGUF block_count, when readable")+ gpu_layers: Optional[int] = Field(+ None, description = "Layers charged to the GPU; null under automatic placement"+ )+ moe_offload_unmodelled: bool = Field(+ False,+ description = "True when --n-cpu-moe is set: experts move per-tensor, not "+ "per-block, so the GPU/host split above ignores it and reads high.",+ )++class InstallLatestTransformersRequest(BaseModel):"""Consented request to install the latest transformers release into a sidecar."""diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex b93950acb71..90b2b6e632c 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -1392,6 +1392,7 @@ try:_emitted_n_batch,_extra_args_draft_device_pin,_extra_args_n_ubatch,+ _flash_attn_enabled_from_args,_hf_offline_if_unreachable,_hf_offline_if_unreachable_for,_kv_bytes_per_elem,@@ -1447,6 +1448,7 @@ except ImportError:_emitted_n_batch,_extra_args_draft_device_pin,_extra_args_n_ubatch,+ _flash_attn_enabled_from_args,_hf_offline_if_unreachable,_hf_offline_if_unreachable_for,_kv_bytes_per_elem,@@ -2522,6 +2524,8 @@ from models.inference import (CompletionUsage,ValidateModelRequest,ValidateModelResponse,+ EstimateMemoryRequest,+ EstimateMemoryResponse,TransformersUpgradeInfo,TransformersUpgradeCheckRequest,TransformersUpgradeCheckResponse,@@ -7937,8 +7941,66 @@ def _cached_repo_gguf_bytes(repo: str, hint: str = "") -> int:# truncated header drops the token array. Above Llama 4 / Gemma 3 (256k), the widest shipping._ASSUMED_MAX_VOCAB = 262144+# Canonical speculative modes whose launch opens no drafter file at all:+# _build_speculative_flags returns out of each before it reaches --model-draft.+_SPEC_MODES_WITHOUT_A_DRAFTER = frozenset({"off", "ngram", "ngram-simple"})-def _estimate_gguf_kv_gb(++class _GgufRuntimeBytes(NamedTuple):+ """The context-dependent half of a GGUF's footprint, itemized.++ ``_estimate_gguf_kv_gb`` sums this into the single number the training guard+ needs; the Load-Model estimate shows the items separately.+ """++ kv_bytes: int+ compute_bytes: int+ # False when the header lacks the dims _can_estimate_kv() needs: kv_bytes is+ # then "unknown", not "none". The guard treats them alike; the UI must not.+ kv_estimable: bool+ # What was actually priced, after the ctx override and the slot/cache clamps.+ n_ctx: int+ cache_type_kv: Optional[str]+ n_parallel: int+ # GGUF block_count, carried out of the header walk this already paid for.+ layer_count: Optional[int] = None+ # The cache layout this was priced with, for a caller sizing a second cache that+ # the same launch allocates (a separate drafter's). Resolving them twice is how+ # the two drift apart.+ swa_full: bool = False+ kv_unified: bool = True+ n_ubatch: Optional[int] = None+ # The part of kv_bytes that is per-slot context checkpoints. Inside kv_bytes, not+ # beside it, so the training guard's total is unchanged; carried separately because+ # it is the one part of the cache that never reaches the GPU. llama.cpp keeps a+ # checkpoint in common_prompt_checkpoint's std::vector<uint8_t> buffers, host heap,+ # bounded by --cache-ram; Studio's own load schema says "Each costs host memory".+ kv_checkpoint_bytes: int = 0+++_GGUF_RUNTIME_UNKNOWN = _GgufRuntimeBytes(0, 0, False, 0, None, 1)+++def _inherited_ctx_size() -> int:+ """A positive inherited ``LLAMA_ARG_CTX_SIZE``, or 0.++ The launch keeps one: it drops the inherited context only when it is ZERO and the+ auto-layers path needs --fit to run, and says so outright -- "a positive inherited+ context stays the legitimate way to set one". So with no -c anywhere and no panel+ value, the child runs at the environment's length, not the header's native one.+ Falling straight through to native priced a 4k load at 262k, which is the KV cache+ off by two orders of magnitude in the direction that refuses the load.+ """+ raw = (os.environ.get("LLAMA_ARG_CTX_SIZE") or "").strip()+ if not raw:+ return 0+ try:+ return max(0, int(raw))+ except ValueError:+ return 0+++def _gguf_runtime_bytes(gguf_path: str,max_seq_length: int,llama_extra_args: Optional[list[str]] = None,@@ -7950,33 +8012,74 @@ def _estimate_gguf_kv_gb(ctx_checkpoints: Optional[int] = None,n_devices: int = 1,is_diffusion: bool = False,+ ctx_last_wins: bool = False,model_identifier: Optional[str] = None,-) -> float:- """KV-cache plus compute-buffer VRAM (GB) at the larger of max_seq_length and+) -> _GgufRuntimeBytes:+ """KV-cache and compute-buffer VRAM (bytes) at the larger of max_seq_length andany `--ctx-size`/`-c` override, over n_parallel slots at the effectivemicro-batch, using the effective cache settings and managed launcherdefaults. Compute buffers scale with the split the loader budgets: tensormode reserves them on every device, a multi-GPU layer split replicates thecontext-linear term; ``is_diffusion`` skips them, since the diffusion- runner ignores the llama-server batch flags. 0 if metadata is unreadable."""+ runner ignores the llama-server batch flags. All-zero and not estimable if+ metadata is unreadable.++ ``ctx_last_wins`` swaps that maximum for what the launch will really run+ (``resolve_requested_ctx``). The default is the coexistence guard's rule, which+ over-reserves on purpose; a panel quoting a number to a user wants the other+ one, since a smaller ``-c`` in the extras is the context the user gets."""try:from core.inference.llama_server_args import (parse_ctx_override,resolve_ctx_checkpoints,+ resolve_requested_ctx,)- probe = LlamaCppBackend()+ probe = _probe_backend()probe._model_identifier = model_identifierprobe._read_gguf_metadata(gguf_path)+ # Carried out even when the cache cannot be sized: block_count is a separate+ # key and is usually there, and a caller that loses it prices a manual offload+ # split as fully GPU-resident (_gguf_offloaded_layer_fraction has nothing to+ # scale against and answers 1.0), which is the wrong answer at --gpu-layers 0.+ unknown = _GGUF_RUNTIME_UNKNOWN._replace(+ layer_count = getattr(probe, "_n_layers", None) or None+ )if not probe._can_estimate_kv():- return 0.0+ return unknowntry:- ctx_override = parse_ctx_override(llama_extra_args) or 0+ _raw_ctx_override = parse_ctx_override(llama_extra_args)except Exception:- ctx_override = 0 # malformed extras are rejected upstream; fall back- ctx = max(max_seq_length or 0, ctx_override) or (probe._context_length or 0)+ _raw_ctx_override = None # malformed extras are rejected upstream; fall back+ ctx_override = _raw_ctx_override or 0+ # An explicit "-c 0" is a REQUEST for the native context, not the absence of+ # one, and llama.cpp reads argv after the environment so the zero wins at the+ # child. Folding the two together let an inherited LLAMA_ARG_CTX_SIZE=4096+ # answer for a launch that opens at the header's 262k, which is the KV cache+ # understated by two orders of magnitude in the direction that says "fits".+ _extras_ask_for_native_ctx = _raw_ctx_override == 0+ if ctx_last_wins:+ # What the launch runs, through load_model's own resolver: the extras+ # value wins whichever way it moves. The maximum below is the coexistence+ # guard's conservative rule, and quoting it to a user prices a context a+ # smaller -c means they will never get.+ try:+ ctx = resolve_requested_ctx(llama_extra_args, max_seq_length or 0)+ except Exception:+ ctx = max_seq_length or 0+ ctx = (+ ctx+ or (0 if _extras_ask_for_native_ctx else _inherited_ctx_size())+ or (probe._context_length or 0)+ )+ else:+ ctx = (+ max(max_seq_length or 0, ctx_override)+ or (0 if _extras_ask_for_native_ctx else _inherited_ctx_size())+ or (probe._context_length or 0)+ )if ctx <= 0:- return 0.0+ return unknownslots = max(1, n_parallel or 1)planned_cache_types = _planned_main_cache_types(cache_type_kv, llama_extra_args)# KV bytes take the heavier axis (conservative for storage); the dequant@@ -7984,6 +8087,18 @@ def _estimate_gguf_kv_gb(# 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.+ 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# caps the micro-batch against it, so budget from the emitted value. Diffusion# takes neither flag, and SWA metadata prices the KV against the micro-batch,@@ -8014,30 +8129,112 @@ def _estimate_gguf_kv_gb(n_batch = _emitted_n_batch(n_batch, slots),n_ubatch = n_ubatch,)- managed_kv_unified = bool(- slots > 1- and LlamaCppBackend.probe_server_capabilities().get("supports_kv_unified", False)+ # Only when it can change an answer. The probe shells out to llama-server, and+ # the previous expression short-circuited it away at one slot; calling it+ # unconditionally put a failure-prone call on every single-slot estimate, and+ # a raise here loses the whole runtime to the unknown fallback.+ _kv_caps = LlamaCppBackend.probe_server_capabilities() if slots > 1 else {}+ _supports_kv_unified = bool(_kv_caps.get("supports_kv_unified", False))+ if slots > 1 and _kv_caps.get("found") and not _supports_kv_unified:+ # load_model drops to one slot on a build without --kv-unified, because an+ # explicit --parallel N there splits -c into N windows and would quarter+ # every context for a feature the build cannot serve. It does that BEFORE+ # sizing, so keeping the requested count here scaled the compute buffers,+ # the SWA layout and the reported slot count to a process that will not+ # launch.+ slots = 1+ managed_kv_unified = bool(slots > 1 and _supports_kv_unified)+ swa_full = _swa_full_from_args_or_env(llama_extra_args)+ kv_unified = _kv_unified_from_args(+ llama_extra_args,+ default = managed_kv_unified,+ )+ _resolved_checkpoints = resolve_ctx_checkpoints(llama_extra_args, ctx_checkpoints)+ if _resolved_checkpoints:+ # A build predating both --ctx-checkpoints aliases has the request skipped+ # by the command builder, which logs and moves on, so charging for the+ # snapshots reserves memory the process never allocates. Same capability+ # probe the builder itself asks, and the same default-deny on an+ # unanswerable one: this figure also guards a running training job, so an+ # unreadable probe keeps the charge rather than dropping it.+ try:+ _cc_caps = LlamaCppBackend.probe_server_capabilities()+ # ``found`` is what separates "this build lacks the flag" from "no+ # binary was read": the defaults dict reports every capability False,+ # so keying on the flag alone would drop the charge whenever the probe+ # simply could not run.+ if _cc_caps.get("found") and not _cc_caps.get("ctx_checkpoints_flag"):+ _resolved_checkpoints = 0+ except Exception as _cc_exc:+ logger.debug("ctx-checkpoints capability probe failed: %s", _cc_exc)+ # load_model appends --flash-attn on to every launch whose build has the flag,+ # so the default here is ON, not off. The false arm pads variable-width V+ # tensors to the model-wide maximum (_max_kv_value_width), which on an+ # architecture whose global and SWA layers disagree about n_embd_v_gqa+ # inflates the whole cache and can call a load that fits an overflow. Resolved+ # the way the launch resolves it: the managed default, narrowed by the+ # capability probe, then llama.cpp's own env-then-last-wins-argv rule. A+ # quantized V still forces it on top of all that, because llama-context.cpp+ # turns it on itself rather than refusing the load.+ _fa_default = True+ try:+ _fa_caps = LlamaCppBackend.probe_server_capabilities()+ # Same ``found`` test as the checkpoint probe above: the defaults dict+ # reports nothing supported, so keying on the flag alone would size every+ # unprobed host as flash-attention-less.+ if _fa_caps.get("found") and not _fa_caps.get("supports_flash_attn", True):+ _fa_default = False+ except Exception as _fa_exc:+ logger.debug("flash-attention capability probe failed: %s", _fa_exc)+ flash_attn = (+ _flash_attn_enabled_from_args(llama_extra_args, default = _fa_default, env = os.environ)+ or v_forces_flash_attn)kv = probe._estimate_kv_cache_bytes(ctx,cache_type_for_budget,n_parallel = slots,- swa_full = _swa_full_from_args_or_env(llama_extra_args),- kv_unified = _kv_unified_from_args(- llama_extra_args,- default = managed_kv_unified,- ),+ swa_full = swa_full,+ kv_unified = kv_unified,n_ubatch = effective_ubatch,# Extras beat the field, as at launch: the control emits its flag# before them. Per-slot SWA snapshots scale with the slot's context, so# a load asking for them needs materially more memory than one that# does not.- ctx_checkpoints = resolve_ctx_checkpoints(llama_extra_args, ctx_checkpoints),- flash_attn = False,+ ctx_checkpoints = _resolved_checkpoints,+ flash_attn = flash_attn,+ )+ # The checkpoint share of that cache, by difference rather than by re-deriving+ # the SWA layer walk: the snapshots are the only term that separates the two+ # calls, and asking the same function twice cannot drift from it. Skipped+ # entirely when none were asked for, which is the common case.+ kv_checkpoint_bytes = 0+ if _resolved_checkpoints:+ _kv_without = probe._estimate_kv_cache_bytes(+ ctx,+ cache_type_for_budget,+ n_parallel = slots,+ swa_full = swa_full,+ kv_unified = kv_unified,+ n_ubatch = effective_ubatch,+ ctx_checkpoints = 0,+ flash_attn = flash_attn,+ )+ kv_checkpoint_bytes = max(0, int(kv) - int(_kv_without))+ _resolved = dict(+ kv_checkpoint_bytes = kv_checkpoint_bytes,+ kv_estimable = True,+ n_ctx = ctx,+ cache_type_kv = cache_type_for_budget,+ n_parallel = slots,+ layer_count = getattr(probe, "_n_layers", None) or None,+ swa_full = swa_full,+ kv_unified = kv_unified,+ n_ubatch = effective_ubatch,)# the load reserves ubatch-scaled compute buffers, so they count against training tooif is_diffusion:- return kv / (1024**3)+ return _GgufRuntimeBytes(kv_bytes = int(kv), compute_bytes = 0, **_resolved)devices = max(1, int(n_devices))def _flat_buffer(per_device_tensor: bool) -> int:@@ -8104,10 +8301,46 @@ def _estimate_gguf_kv_gb(# reserves buffers. Floor at the loader's flat reserve, charged once: it is an# invented number, and scaling an invention per device has no basis.compute = int(getattr(probe, "_TENSOR_PARALLEL_BUFFER_RESERVE_MIB", 0)) * 1024**2- return (kv + compute) / (1024**3)+ return _GgufRuntimeBytes(kv_bytes = int(kv), compute_bytes = int(compute), **_resolved)except Exception as e:logger.warning(f"Could not size GGUF KV cache for training guard: {e}")- return 0.0+ return _GGUF_RUNTIME_UNKNOWN+++def _estimate_gguf_kv_gb(+ gguf_path: str,+ max_seq_length: int,+ llama_extra_args: Optional[list[str]] = None,+ n_parallel: int = 1,+ cache_type_kv: Optional[str] = None,+ tensor_parallel: bool = False,+ n_batch: Optional[int] = None,+ n_ubatch: Optional[int] = None,+ ctx_checkpoints: Optional[int] = None,+ n_devices: int = 1,+ is_diffusion: bool = False,+ model_identifier: Optional[str] = None,+) -> float:+ """``_gguf_runtime_bytes`` summed into GB, for the training guard.++ An unreadable header is 0 GB, as it always was: a cache the guard cannot size+ must not become a refusal on its own.+ """+ runtime = _gguf_runtime_bytes(+ gguf_path,+ max_seq_length,+ llama_extra_args,+ n_parallel,+ cache_type_kv,+ tensor_parallel,+ n_batch,+ n_ubatch,+ ctx_checkpoints = ctx_checkpoints,+ n_devices = n_devices,+ is_diffusion = is_diffusion,+ model_identifier = model_identifier,+ )+ return (runtime.kv_bytes + runtime.compute_bytes) / (1024**3)def _remote_gguf_compute_reserve_gb(@@ -8215,6 +8448,12 @@ def _estimate_gguf_required_gb(n_devices: int = 1,is_diffusion: bool = False,disable_vision: bool = False,+ # The panel prices from disk and headers only. A --spec-draft-hf repo is otherwise+ # sized by LISTING it over the network, which is right for the admission guard (a+ # running training job is worth one request) and wrong for a row that re-prices on+ # every settings change. This skips that listing; the caller marks the total a+ # floor instead, exactly as it already does for a drafter it cannot weigh.+ local_only: bool = False,) -> Optional[float]:"""Approximate GGUF VRAM (GB): quantized weights + companions, plus the KVcache for local files (unreadable pre-download for remote). None when nothing@@ -8222,6 +8461,7 @@ def _estimate_gguf_required_gb(try:from core.inference.llama_cpp import (_canonicalize_spec_mode,+ _extra_args_device,_extra_args_draft_offloaded_to_cpu,_extra_args_mtp_draft_path,_extra_args_mtp_draft_source,@@ -8318,6 +8558,18 @@ def _estimate_gguf_required_gb(or _extras_own_drafteror (_forced_dspark and not _dspark_capable)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.+ #+ # 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.+ or (_spec_mode in _SPEC_MODES_WITHOUT_A_DRAFTER and not _extra_args_own_spec))def _same_file_key(p: str) -> str:@@ -8371,6 +8623,18 @@ def _estimate_gguf_required_gb(logger.debug(f"mmproj capability read failed: {_dv_exc}")if not _dv_opens_projector:_sized_attrs = []+ # A --mmproj in the extras last-wins at the child: the launch emits Studio's+ # projector and appends the extras after it. So the override is the file that+ # opens, and it is the one to charge -- the configured one was billed while a+ # possibly much larger custom projector went free.+ _mmproj_override_bytes = 0+ if _sized_attrs == ["gguf_mmproj_file"]:+ _mmproj_override = _extra_args_device(llama_extra_args, {"--mmproj", "-mm"})+ if _mmproj_override and Path(_mmproj_override).is_file():+ _sized_attrs = []+ _mmproj_override_bytes = LlamaCppBackend._get_gguf_size_bytes(_mmproj_override)+ total_bytes += _mmproj_override_bytes+ _sized_keys.add(_same_file_key(_mmproj_override))if not _charge_no_drafter:if dspark_requested:_sized_attrs.append("gguf_dspark_file")@@ -8433,7 +8697,7 @@ def _estimate_gguf_required_gb(elif _extras_draft and Path(_extras_draft).is_file():if _same_file_key(str(_extras_draft)) not in _sized_keys:_extras_bytes = LlamaCppBackend._get_gguf_size_bytes(str(_extras_draft))- elif _extras_draft and _extras_draft_is_remote:+ elif _extras_draft and _extras_draft_is_remote and not local_only:_extras_bytes = _remote_drafter_repo_bytes(str(_extras_draft), hf_token = hf_token)# else: a local --model-draft that is not on disk, so no drafter loads and# none is charged. A repository reserve there 409s a load over a typo.@@ -8556,6 +8820,1384 @@ def _estimate_gguf_required_gb(return None+class _GgufMemoryBreakdown(NamedTuple):+ """What a prospective GGUF load would occupy, itemized for the Load-Model panel.++ ``weights_bytes`` is the files that become resident (weights plus whichever+ projector and drafter this launch opens) and is the one term that does not move+ with the settings above it.+ """++ weights_bytes: int+ kv_bytes: int+ compute_bytes: int+ # A separate drafter's KV and rollback state, kept out of compute_bytes so each+ # line names one thing.+ drafter_runtime_bytes: int+ # How much of that lands on the GPU. Its own figure rather than a placement flag,+ # because the term is not placed as one piece: under MTP the target-side+ # verification state follows the TARGET cache while the draft cache follows the+ # drafter, so --no-kv-offload with a GPU drafter splits it. A boolean would have to+ # answer for both and would be wrong for one of them.+ drafter_runtime_gpu_bytes: int+ # The vision encoder's buffers, about 0.4x the projector file on top of it.+ projector_runtime_bytes: int+ # A drafter was charged whose cache could not be sized: --spec-draft-hf names a+ # repository, whose header is not on this disk to read.+ drafter_kv_unsized: bool+ # A pass-through --lora / --control-vector naming a file that could not be stat'd,+ # so its resident bytes are missing from the total. Same floor marker, same reason.+ adapters_unsized: bool+ # Weights + KV + compute, wherever they sit: GPU, host RAM, or a unified pool.+ total_bytes: int+ # The part that lands on the GPU under the requested offload.+ gpu_bytes: int+ kv_estimable: bool+ kv_on_gpu: bool+ n_ctx: int+ cache_type_kv: Optional[str]+ n_parallel: int+ layer_count: Optional[int]+ gpu_layers: Optional[int]+++def _gguf_offloaded_layer_fraction(+ gpu_memory_mode: Optional[str],+ gpu_layers: Optional[int],+ layer_count: Optional[int],+ extras: Optional[list[str]] = None,+ *,+ device_pin_governs: bool = False,+) -> 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.++ 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.+ """+ 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.+ if not device_pin_governs and (+ _device_selection_is_cpu(extras, os.environ) or _estimate_host_has_no_gpu()+ ):+ return 0.0++ try:+ override = parse_gpu_layers_override(extras)+ except ValueError:+ # Malformed value: llama-server names it better than a guess here would.+ override = None+ 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.+ from core.inference.llama_cpp import _env_fixes_gpu_layers+ if not _env_fixes_gpu_layers(os.environ):+ return 1.0+ try:+ gpu_layers = int(str(os.environ.get("LLAMA_ARG_N_GPU_LAYERS", "")).strip())+ except ValueError:+ # llama.cpp's own std::stoi would throw on it and the child would never+ # start, so there is no placement to model.+ return 1.0+ 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.+ return 0.0+ if not layer_count or layer_count <= 0:+ # No dims to scale against; 1.0 keeps it consistent with Auto.+ return 1.0+ return max(0.0, min(1.0, gpu_layers / float(layer_count + 1)))+++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.+ """+ import inspect+ try:+ return LlamaCppBackend(manages_processes = False)+ except TypeError:+ try:+ inspect.signature(LlamaCppBackend).bind(manages_processes = False)+ except (TypeError, ValueError):+ # Genuinely does not accept the keyword -- or has no introspectable+ # signature, where today's behaviour is the safe answer.+ return LlamaCppBackend()+ # It bound fine, so the fault came from the body. Let it surface.+ raise+++def _manual_keeps_tensor_split(+ gpu_memory_mode: Optional[str],+ gpu_layers: Optional[int],+ extras: Optional[list[str]] = None,+) -> bool:+ """Whether a Manual offload still reaches a tensor launch.++ load_model drops the tensor split twice in Manual mode before anything is+ budgeted, and neither drop is about how many cards are present:++ * ``gpu_layers == 0`` leaves nothing on the GPU to split, and under the CPU-only+ mask a ``--split-mode tensor`` survivor aborts the server rather than loading.+ * Auto layers (the field arrives ``None``, the loader sees ``-1``) hand memory+ management to llama.cpp ``--fit``, which is incompatible with tensor mode.++ A ``-ngl`` in the extras last-wins into the count first, the way /load translates+ it into the field before its own drop -- so ``--gpu-layers 0`` with ``-ngl 40``+ keeps the split, and the field alone would have dropped it. Resolved here rather+ than by the caller so the panel and the device count cannot disagree: one has+ already stripped the offload flags by the time it asks, the other has not.++ Auto mode is not ours to downgrade; the planner decides there.+ """+ if gpu_memory_mode != "manual":+ return True+ from core.inference.llama_server_args import parse_gpu_layers_override++ try:+ override = parse_gpu_layers_override(extras)+ except ValueError:+ # Malformed value: same shrug as _gguf_offloaded_layer_fraction, llama-server+ # names it better than a guess here would.+ override = None+ if override is not None:+ gpu_layers = override+ return gpu_layers is not None and gpu_layers >= 1+++# The gate's three answers. ``_estimate_target_is_on_this_disk`` collapses the last+# two into True and keeps its old bool contract; the caller that decides whether a+# resolution may go ONLINE needs them apart, because "yes, it is here" and "I could not+# tell" are the same fall-through but very different permissions.+_ESTIMATE_DISK_PRESENT = "present"+_ESTIMATE_DISK_ABSENT = "absent"+_ESTIMATE_DISK_UNKNOWN = "unknown"+++def _estimate_disk_residency(model_identifier: str) -> str:+ """``present`` / ``absent`` / ``unknown`` for the identifier's local weights.++ Same walk as ``_estimate_target_is_on_this_disk``, which is a thin wrapper over+ this. Split out only so the unanswerable case stays distinguishable: it is the one+ the route must not answer with a Hub round trip.+ """+ try:+ from utils.paths import is_local_path+ except Exception:+ return _ESTIMATE_DISK_UNKNOWN+ if not model_identifier or not model_identifier.strip():+ return _ESTIMATE_DISK_UNKNOWN+ identifier = model_identifier.strip()+ try:+ if is_local_path(identifier):+ return _ESTIMATE_DISK_PRESENT+ except Exception:+ return _ESTIMATE_DISK_UNKNOWN++ # from_identifier prefixes a bare name, so ask about the id it will actually use.+ candidates = [identifier]+ if "/" not in identifier:+ candidates.append(f"unsloth/{identifier}")+ try:+ from utils.models.model_config import _iter_hf_cache_snapshots+ roots = _estimate_hf_cache_roots()+ except Exception:+ return _ESTIMATE_DISK_UNKNOWN+ if not roots:+ return _ESTIMATE_DISK_UNKNOWN+ try:+ for root in roots:+ for candidate in candidates:+ for _snapshot in _iter_hf_cache_snapshots(candidate, cache_dir = root):+ return _ESTIMATE_DISK_PRESENT+ except Exception:+ return _ESTIMATE_DISK_UNKNOWN+ return _ESTIMATE_DISK_ABSENT+++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.+ """+ return _estimate_disk_residency(model_identifier) != _ESTIMATE_DISK_ABSENT+++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.+ """+ try:+ from hub.utils.hf_cache_state import hf_cache_roots+ roots = [Path(r) for r in hf_cache_roots()]+ if roots:+ return roots+ except Exception:+ pass++ roots = []+ seen = set()++ def _add(value) -> None:+ if not value:+ return+ try:+ path = Path(value)+ key = str(path.resolve())+ except OSError:+ return+ if key not in seen and path.is_dir():+ seen.add(key)+ roots.append(path)++ try:+ from utils.hf_cache_settings import known_hf_hub_caches+ for configured in known_hf_hub_caches():+ _add(configured)+ except Exception:+ pass+ try:+ from huggingface_hub import constants as _hf_constants+ _add(getattr(_hf_constants, "HF_HUB_CACHE", None))+ except Exception:+ pass+ return roots+++def _estimate_token_fingerprint(hf_token: Optional[str]) -> str:+ """Short non-reversible stand-in for an HF token, for cache keys only.++ A token is a credential; it does not belong in a dict key verbatim.+ """+ if not hf_token:+ return ""+ return _hashlib.sha256(hf_token.encode("utf-8")).hexdigest()[:16]+++# Resident-file totals, keyed by what decides WHICH files a launch opens. Not by+# context or cache type: dragging the slider must not re-list a repository.+_ESTIMATE_FILES_TTL_SECONDS = 30.0+_ESTIMATE_FILES_CACHE_MAX = 16+_estimate_files_cache: "dict[tuple, tuple[float, Optional[float]]]" = {}+# Shared by both estimate caches. Held only across evict-and-insert, never across a+# header walk or a resolution, so a slow request cannot block a fast one behind it.+_ESTIMATE_CACHE_LOCK = threading.Lock()+# Told apart from None on purpose. Both mean "no config", but they are different+# answers to the user: None is a resolution that was attempted and failed, which is+# `unsizable`; this one is a model that is not on this disk, which is `not_downloaded`+# and was the reason that case reported before the resolution was skipped.+_ESTIMATE_NOT_ON_DISK = object()+++def _localized_estimate_config(config: ModelConfig, gguf_path: str) -> ModelConfig:+ """A copy of ``config`` whose GGUF paths name the files already on this disk.++ ``from_identifier`` leaves ``gguf_file`` unset for anything it resolved as a+ repository, even when the weights are in the HF cache. ``_estimate_gguf_required_gb``+ branches on that field, so a cached repo was priced from a ``paths-info`` call:+ a network round trip behind a slider, and nothing at all offline.++ Copied, never mutated: the original lives in a TTL cache.++ Returned unchanged when ``gguf_file`` already names a real file (local-folder and+ native-pick configs), which keeps a native grant's directory boundary intact.+ """+ main = getattr(config, "gguf_file", None)+ if main and Path(main).is_file():+ return config+ from utils.models.model_config import (+ _local_gguf_companion_search_root,+ detect_dflash_file,+ detect_dspark_file,+ detect_mmproj_file,+ detect_mtp_file,+ )++ local = replace(config, gguf_file = gguf_path)+ # Companions sit beside the weight, or one level up in the quant-subdir layout.+ # Derived by the load path's own helper rather than by taking the weight's parent:+ # a cached repo that files each quant under its own directory (snapshot/UD-Q4_K_XL/+ # model-00001-of-00002.gguf) keeps the projector and the drafter at the snapshot+ # root, and a search_root equal to start_dir gives the detectors nothing to walk up+ # to, so the estimate silently dropped a 1-2 GB projector and the drafter's runtime.+ search_root = _local_gguf_companion_search_root(gguf_path, gguf_path)+ try:+ if getattr(local, "is_vision", False) and not local.gguf_mmproj_file:+ local.gguf_mmproj_file = detect_mmproj_file(gguf_path, search_root)+ if not local.gguf_mtp_file:+ local.gguf_mtp_file = detect_mtp_file(gguf_path, search_root)+ if not local.gguf_dspark_file:+ local.gguf_dspark_file = detect_dspark_file(gguf_path, search_root)+ if not local.gguf_dflash_file:+ local.gguf_dflash_file = detect_dflash_file(gguf_path, search_root)+ except Exception as exc:+ # An uncounted sidecar is a smaller error than no estimate at all.+ logger.debug("Companion detection failed for the memory estimate: %s", exc)+ return local+++def _gguf_resident_file_gb(+ config: ModelConfig,+ *,+ hf_token: Optional[str] = None,+ llama_extra_args: Optional[list[str]] = None,+ speculative_type: Optional[str] = None,+ disable_vision: bool = False,+ local_only: bool = False,+) -> Optional[float]:+ """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.+ """+ main = getattr(config, "gguf_file", None)+ local_arm = bool(main and Path(main).is_file())+ key = (+ getattr(config, "identifier", None),+ getattr(config, "gguf_variant", None),+ str(main or ""),+ bool(disable_vision),+ speculative_type or "",+ tuple(llama_extra_args or ()),+ # 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.+ key = (*key, local_only)+ now = time.monotonic()+ hit = _estimate_files_cache.get(key)+ if hit is not None and now - hit[0] < _ESTIMATE_FILES_TTL_SECONDS:+ return hit[1]++ priced = dict(+ llama_extra_args = llama_extra_args,+ speculative_type = speculative_type,+ disable_vision = disable_vision,+ hf_token = hf_token,+ local_only = local_only,+ )+ required_gb = _estimate_gguf_required_gb(config, max_seq_length = 0, **priced)+ if required_gb is None:+ return None # deliberately not cached: usually a download still in flight+ if local_arm:+ # Same identifier the required-GB arm classifies with, or the two halves of the+ # subtraction below stop being paired and the weights figure moves with context.+ context_term_gb = _estimate_gguf_kv_gb(+ str(main),+ 0,+ llama_extra_args,+ model_identifier = getattr(config, "identifier", None),+ )+ else:+ context_term_gb = _remote_gguf_compute_reserve_gb(+ llama_extra_args = llama_extra_args,+ max_seq_length = 0,+ )+ 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.+ 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])+ _estimate_files_cache.pop(oldest, None)+ # Stamped now, not at `now`: same reason as the config cache. A multi-shard+ # repo whose header walk outlasts the TTL must not be inserted pre-expired.+ _estimate_files_cache[key] = (time.monotonic(), files_gb)+ return files_gb+++# Appended to a probe's argument list to force the drafter charge one way or the+# other. Both flags are last-wins in llama.cpp's parsers, so an appended value+# overrides anything earlier in the list AND the environment fallback, which only+# applies when no argument carries the flag at all.+_DRAFT_FORCE_GPU_ARGS = ("--spec-draft-ngl", "999", "--spec-draft-device", "gpu")+_DRAFT_FORCE_CPU_ARGS = ("--spec-draft-ngl", "0")+++def _charged_drafter_path(+ config: ModelConfig,+ drafter_bytes: int,+ *,+ extras: Optional[list[str]] = None,+) -> Optional[tuple[str, str]]:+ """Which drafter file accounts for ``drafter_bytes``, and by which route.++ Returns ``(path, kind)`` with kind one of ``extras``, ``dspark``, ``dflash``,+ ``mtp``, or None when no drafter was charged. The kind decides which target-side+ terms the reserve carries, so it has to come from the same match as the path.++ Identified by size rather than by re-deriving the mode precedence. That+ precedence lives in ``_estimate_gguf_required_gb`` and depends on capability+ probes and Auto-mode rules; a second copy of it would pick a different sidecar+ from the one that was actually charged, which is worse than not pricing the KV+ at all. Matching on the bytes it added cannot disagree with it.++ An extras ``--model-draft`` is taken first and without the size match: it is the+ drafter the launch opens whatever discovery found, and it need not be one of the+ sidecars below. A remote ``--spec-draft-hf`` is not a local file, so it stays+ unsized either way. The env is read through ``_child_spec_env``, which is empty+ unless the extras own ``--spec-type`` and is ``os.environ`` when they do: the same+ view the child gets, so an inherited ``LLAMA_ARG_SPEC_DRAFT_MODEL`` is seen exactly+ when the launch would honour it.+ """+ if drafter_bytes <= 0:+ return None+ from core.inference.llama_cpp import _child_spec_env, _extra_args_mtp_draft_path++ named = _extra_args_mtp_draft_path(extras, env = _child_spec_env(extras)) if extras else None+ if named and Path(named).is_file():+ return str(named), "extras"+ for attr, kind in (+ ("gguf_dspark_file", "dspark"),+ ("gguf_dflash_file", "dflash"),+ ("gguf_mtp_file", "mtp"),+ ):+ candidate = getattr(config, attr, None)+ if not candidate or not Path(candidate).is_file():+ continue+ if LlamaCppBackend._get_gguf_size_bytes(str(candidate)) == drafter_bytes:+ return str(candidate), kind+ return None+++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.+ """+ 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.++ 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.+ """+ try:+ cached = getattr(sys.modules.get("main"), "_system_gpu_cache", None)+ if not cached:+ 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.+ return [(int(device.get("index", i)), 0, 0) for i, device in enumerate(devices)]+ except Exception:+ return None+++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.++ 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.+ """+ if requested_gpu_ids:+ return len(requested_gpu_ids) >= 2+ try:+ if LlamaCppBackend._is_vulkan_backend():+ devices = _cached_inference_devices()+ return len(devices) >= 2 if devices is not None else True+ except Exception:+ pass+ try:+ return LlamaCppBackend._effective_gpu_count(None) >= 2+ except Exception:+ return True+++def _charged_projector_bytes(+ config: ModelConfig, extras: Optional[list[str]], disable_vision: bool+) -> int:+ """Size of the single projector this launch opens, or 0.++ Same precedence ``_estimate_gguf_required_gb`` charges: Studio's own resolved+ projector goes on argv and wins, since argv is applied after set_env; otherwise an+ inherited ``LLAMA_ARG_MMPROJ`` loads straight through, including through+ ``--no-mmproj``, which empties the command line without clearing ``mmproj.path``.+ Under the vision switch only an audio-only projector survives, asked through the+ loader's own helpers so the two cannot answer differently.+ """+ from core.inference.llama_cpp import (+ _extra_args_device,+ _mmproj_env_is_audio_only,+ extra_args_disable_mmproj,+ )++ # A --mmproj in Advanced Arguments last-wins: the launch emits Studio's projector+ # first and appends the extras after it, so the child opens the user's. Charging+ # the configured one instead priced a file the load never opens and left a+ # possibly much larger one free.+ override = _extra_args_device(extras, {"--mmproj", "-mm"})+ if override and Path(override).is_file() and not extra_args_disable_mmproj(extras):+ if not disable_vision:+ return LlamaCppBackend._get_gguf_size_bytes(override)+ try:+ from utils.models.gguf_metadata import mmproj_accepts_image+ if not mmproj_accepts_image(override):+ return LlamaCppBackend._get_gguf_size_bytes(override)+ except Exception:+ pass+ # Unreadable under the vision switch reads as image-capable, hence dropped:+ # the same call the configured branch below makes, and what the loader does.+ return 0++ studio_mmproj = getattr(config, "gguf_mmproj_file", None)+ on_argv = bool(studio_mmproj) and not extra_args_disable_mmproj(extras)+ if on_argv and disable_vision:+ try:+ from utils.models.gguf_metadata import mmproj_accepts_image+ on_argv = not mmproj_accepts_image(str(studio_mmproj))+ except Exception:+ on_argv = False+ if on_argv and Path(str(studio_mmproj)).is_file():+ return LlamaCppBackend._get_gguf_size_bytes(str(studio_mmproj))+ if on_argv:+ return 0+ inherited = (os.environ.get("LLAMA_ARG_MMPROJ") or "").strip()+ if (+ inherited+ and (not disable_vision or _mmproj_env_is_audio_only(inherited))+ and Path(inherited).is_file()+ ):+ return LlamaCppBackend._get_gguf_size_bytes(inherited)+ return 0+++def _inherited_drafter_bytes(extras: Optional[list[str]]) -> int:+ """Size of a drafter that arrives only through the inherited environment.++ ``_estimate_gguf_required_gb`` reads ``--model-draft`` with an empty env, so a+ launch whose extras own ``--spec-type`` and whose drafter comes from+ ``LLAMA_ARG_SPEC_DRAFT_MODEL`` has no drafter in the files term at all. 0 when the+ extras name one themselves (already counted), when nothing is inherited, or when+ the path is not a local file.+ """+ from core.inference.llama_cpp import _child_spec_env, _extra_args_mtp_draft_path++ if _extra_args_mtp_draft_path(extras, env = {}):+ return 0+ inherited = _extra_args_mtp_draft_path(extras, env = _child_spec_env(extras))+ if not inherited or not Path(str(inherited)).is_file():+ return 0+ try:+ return LlamaCppBackend._get_gguf_size_bytes(str(inherited))+ except Exception:+ return 0+++def _inherited_remote_files_unsized(extras: Optional[list[str]], disable_vision: bool) -> bool:+ """Whether the child inherits a file it will fetch and this cannot weigh.++ Two of them, and both are real launch inputs the environment carries through:++ * ``LLAMA_ARG_SPEC_DRAFT_HF_REPO`` (or the legacy ``LLAMA_ARG_HFD_REPO``), which+ ``_child_spec_env`` preserves once the extras own the spec block. llama-server+ downloads that drafter and gives it a context-sized cache;+ * ``LLAMA_ARG_MMPROJ_URL``, which llama.cpp fetches and uses as the projector even+ when Studio resolved a local one.++ Neither can be sized from here without a network call, which this route is+ documented not to make. So the total is a floor and says so, rather than quietly+ omitting a multi-gigabyte file.+ """+ from core.inference.llama_cpp import _child_spec_env++ spec_env = _child_spec_env(extras)+ for key in ("LLAMA_ARG_SPEC_DRAFT_HF_REPO", "LLAMA_ARG_HFD_REPO"):+ if (spec_env.get(key) or "").strip():+ return True+ if not disable_vision and (os.environ.get("LLAMA_ARG_MMPROJ_URL") or "").strip():+ return True+ return False+++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.+ """+ from core.inference.llama_cpp import _child_spec_env, _is_positive_int++ spec_env = _child_spec_env(extras)+ inherited = next(+ (+ value+ for value in (+ spec_env.get("LLAMA_ARG_SPEC_DRAFT_N_MAX"),+ spec_env.get("LLAMA_ARG_DRAFT_MAX"),+ )+ if _is_positive_int(value)+ ),+ None,+ )+ if inherited is not None:+ return int(str(inherited).strip())+ try:+ binary = LlamaCppBackend._exec_path_for_launch(LlamaCppBackend._find_llama_server_binary())+ stat = os.stat(str(binary))+ caps = LlamaCppBackend._capability_cache.get((str(binary), stat.st_mtime_ns, stat.st_size))+ default = (caps or {}).get("spec_draft_n_max_default")+ return int(default) if default else LlamaCppBackend._UNKNOWN_SPEC_DRAFT_N_MAX+ except Exception:+ return LlamaCppBackend._UNKNOWN_SPEC_DRAFT_N_MAX+++def _estimate_spec_mode_terms(+ drafter_kind: str,+ extras: list[str],+ studio_emits_mtp: bool = False,+) -> tuple[bool, bool]:+ """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.+ """+ from core.inference.llama_cpp import (+ _accumulated_spec_types,+ _child_spec_env,+ _extra_args_set_spec_type,+ _TARGET_ROLLBACK_SPEC_TYPES,+ )++ # The env the CHILD sees: scrubbed of LLAMA_ARG_SPEC_* unless the extras own the+ # spec block, in which case an inherited type accumulates with theirs.+ spec_types = _accumulated_spec_types(extras, env = _child_spec_env(extras))+ if spec_types:+ return (+ bool(spec_types & {"mtp", "draft-mtp"}),+ bool(spec_types & _TARGET_ROLLBACK_SPEC_TYPES),+ )+ if drafter_kind == "extras" and _extra_args_set_spec_type(extras):+ # A --spec-type whose value named no flavour we recognise. Theirs either way.+ return False, False+ if drafter_kind == "extras":+ # Studio still emits the mode; only the file came from the extras.+ return (studio_emits_mtp, True) if studio_emits_mtp else (False, False)+ return drafter_kind == "mtp", True+++def _estimate_draft_n_max(+ config: ModelConfig, drafter_path: str, *, requested: Optional[int], extras: list[str]+) -> int:+ """The draft depth the launch would really run at, for a blank Draft Tokens field.++ Blank is not zero. ``_build_speculative_flags`` emits its own default when the+ field is unset (3 for DSpark, else 2 with a GPU and 3 without), and+ ``_estimate_mtp_overhead_bytes`` multiplies the Hybrid-Mamba rollback state by+ this number, so pricing zero dropped that whole allocation -- the dominant hidden+ cost on a hybrid target at several parallel slots -- from both total and GPU bytes.++ Same precedence as the launch and as the loader's own budget: an extras depth wins+ (last-wins at launch), then the build's own default where the extras own the spec+ block, then the request field, then the platform default. An explicit 0 is+ honoured, since that is a real request to draft nothing.+ """+ from core.inference.llama_cpp import _extra_args_set_spec_type, _extra_args_spec_draft_n_max++ depth = _extra_args_spec_draft_n_max(extras)+ if depth is None and _extra_args_set_spec_type(extras):+ # _build_speculative_flags returns without emitting a depth here, so neither+ # the field below nor the platform default reaches the child: it drafts at the+ # build's number, and the rollback state scales by it.+ depth = _build_default_spec_draft_n_max(extras)+ if depth is None:+ depth = requested+ if depth is not None:+ return max(0, int(depth))+ dspark = getattr(config, "gguf_dspark_file", None)+ if dspark and str(dspark) == drafter_path:+ return 3+ try:+ gpus = LlamaCppBackend._effective_gpu_count() > 0+ except Exception:+ gpus = False+ return 2 if gpus else 3+++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.+ """+ if not getattr(probe, "_nextn_predict_layers", None):+ return False+ from core.inference.llama_cpp import (+ _MTP_MIN_SIZE_B,+ _canonicalize_spec_mode,+ _extra_args_set_spec_type,+ _extract_model_size_b,+ _mla_mtp_auto_enabled,+ )++ 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.+ 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"}+ )+ 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.+ try:+ caps = LlamaCppBackend.probe_server_capabilities()+ if caps.get("found") and not caps.get("mtp_token"):+ return False+ except Exception as exc:+ 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.+ 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:+ return False+ if getattr(probe, "_kv_lora_rank", None) is not None and not _mla_mtp_auto_enabled():+ return False+ return True+++def _tensor_latches_allow_a_split(+ gguf_path: str,+ config: ModelConfig,+ cache_type_kv: Optional[str],+ llama_extra_args: Optional[list[str]],+) -> bool:+ """Whether this process has already learned that a tensor split will not happen.++ ``load_model`` checks two in-process latches before it plans, and both silently+ turn the launch into a layer split: a binary that refused a quantized KV cache+ under ``--split-mode tensor``, and a (binary, model, cache pair) that aborted on+ one earlier this session. Pricing tensor after either has been set charges+ per-device flat buffers for a launch that will not use them.++ Fail-open: an unresolvable binary or an unreadable latch answers "allowed", which+ is what this priced before the check existed.+ """+ from core.inference.llama_cpp import _planned_main_cache_types+ try:+ binary = LlamaCppBackend._find_llama_server_binary()+ if not binary:+ return True+ pair = _planned_main_cache_types(cache_type_kv, llama_extra_args)+ model = getattr(config, "identifier", None) or gguf_path+ if LlamaCppBackend._tensor_quant_kv_unsupported_binary(binary, pair):+ return False+ return not LlamaCppBackend._tensor_split_aborts(binary, model, pair)+ except Exception as exc:+ logger.debug("Tensor-split latch lookup failed while pricing: %s", exc)+ return True+++def _gguf_memory_breakdown(+ config: ModelConfig,+ gguf_path: str,+ *,+ hf_token: Optional[str] = None,+ n_ctx: int = 0,+ llama_extra_args: Optional[list[str]] = None,+ speculative_type: Optional[str] = None,+ n_parallel: int = 1,+ cache_type_kv: Optional[str] = None,+ tensor_parallel: bool = False,+ n_batch: Optional[int] = None,+ n_ubatch: Optional[int] = None,+ ctx_checkpoints: Optional[int] = None,+ n_devices: int = 1,+ is_diffusion: bool = False,+ disable_vision: bool = False,+ gpu_memory_mode: Optional[str] = None,+ gpu_layers: Optional[int] = None,+ spec_draft_n_max: Optional[int] = None,+ spec_draft_cache_type: Optional[str] = None,+ tensor_split_possible: bool = True,+ # An explicit GPU pin owns placement: load_model strips the device flags from the+ # extras and clears the device environment before it launches, because the pin is+ # the more specific instruction. Without that, a stale "--device none" in the box+ # made a pinned load read as CPU-only and reported no GPU footprint at all.+ device_pin_governs: bool = False,+) -> Optional[_GgufMemoryBreakdown]:+ """Itemize what loading this GGUF at ``n_ctx`` would cost. None if nothing sizes.++ Two terms, both from functions the training guard already uses: the files, cached+ since they do not move while the panel is open, and the KV cache plus compute+ buffers, re-derived every call because that is the half that does.+ """+ from core.inference.llama_server_args import (+ _effective_tensor_parallel,+ parse_gpu_layers_override,+ strip_shadowing_flags,+ )++ # Manual owns the offload flags: /load translates the last -ngl into the field and+ # then strips the raw flags, so the launch carries neither. Price that same list,+ # or a stale -ncmoe here reads as pipeline parallelism off and charges one context+ # buffer where the launch replicates them per device.+ if gpu_memory_mode == "manual" and llama_extra_args:+ try:+ _manual_ngl = parse_gpu_layers_override(llama_extra_args)+ except ValueError:+ _manual_ngl = None+ if _manual_ngl is not None:+ gpu_layers = _manual_ngl+ llama_extra_args = strip_shadowing_flags(+ llama_extra_args,+ strip_context = False,+ strip_cache = False,+ strip_spec = False,+ strip_template = False,+ strip_split_mode = False,+ # _should_strip_tensor_split's rule, from the same two values it reads.+ strip_tensor_split = gpu_layers is not None and gpu_layers >= 0,+ strip_offload = True,+ )++ # A --split-mode in the extras last-wins over the toggle, and an inherited tensor+ # LLAMA_ARG_SPLIT_MODE turns it on: the same helper load_model budgets with, so a+ # launch that runs tensor is not priced as a layer split. Then the downgrades the+ # loader applies on the way in, so a single card is not priced as one either, and+ # neither are the two Manual shapes that never reach a tensor launch at all.+ tensor_parallel = (+ _effective_tensor_parallel(llama_extra_args, tensor_parallel)+ and tensor_split_possible+ # And the two latches load_model consults before it plans: a build that already+ # refused a quantized KV cache under a tensor split, and a (build, model, cache+ # pair) that aborted on one this session. Both send the launch straight to a+ # layer split, whose context buffers are multiplied per device where tensor's+ # flat buffers are replicated -- gigabytes apart on two cards, and enough to+ # move the verdict. Asked of the same classmethods rather than re-derived.+ and _tensor_latches_allow_a_split(gguf_path, config, cache_type_kv, llama_extra_args)+ # The extras are already stripped of -ngl here and the count already carries it,+ # so the override lookup inside is a no-op and the field is what decides.+ and _manual_keeps_tensor_split(gpu_memory_mode, gpu_layers, llama_extra_args)+ )+ runtime = _gguf_runtime_bytes(+ gguf_path,+ n_ctx,+ llama_extra_args = llama_extra_args,+ n_parallel = n_parallel,+ cache_type_kv = cache_type_kv,+ tensor_parallel = tensor_parallel,+ n_batch = n_batch,+ n_ubatch = n_ubatch,+ ctx_checkpoints = ctx_checkpoints,+ n_devices = n_devices,+ is_diffusion = is_diffusion,+ # The panel prices the launch, not the admission guard: a smaller -c in the+ # extras is the context the user gets, not one to over-reserve against.+ ctx_last_wins = True,+ # An embedding model is recognised from its identifier, not its header, so the+ # panel has to hand over the same one /load does or it prices a generation model.+ model_identifier = getattr(config, "identifier", None),+ )+ files_gb = _gguf_resident_file_gb(+ config,+ hf_token = hf_token,+ llama_extra_args = llama_extra_args,+ speculative_type = speculative_type,+ disable_vision = disable_vision,+ # No Hub listing behind a slider: a --spec-draft-hf repo is left uncharged here+ # and marked below, rather than costing a model_info per settings change.+ local_only = True,+ )+ if files_gb is None:+ return None+ from core.inference.llama_cpp import (+ _canonicalize_spec_mode,+ _device_selection_is_cpu,+ _extra_args_draft_cache_types,+ _extra_args_draft_offloaded_to_cpu,+ _extra_args_mtp_draft_source,+ _kv_offload_from_args,+ _resolved_mmproj_offload,+ )++ 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.+ from core.inference.llama_cpp import _sidecar_adapter_bytes++ adapter_bytes = _sidecar_adapter_bytes(extras)+ # None is "engaged but unsized": a named file we cannot stat. The loader abstains+ # from the whole figure there, which for a panel would hide the row; a floor with+ # the marker on says more than silence does.+ adapters_unsized = adapter_bytes is None+ adapter_bytes = adapter_bytes or 0+ files_probe = dict(+ hf_token = hf_token,+ speculative_type = speculative_type,+ disable_vision = disable_vision,+ local_only = True,+ )++ def _files_bytes_with(extra: tuple[str, ...]) -> Optional[int]:+ 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.+ host_drafter_bytes = 0+ gpu_drafter_bytes = 0+ if _extra_args_draft_offloaded_to_cpu(extras):+ unpinned = _files_bytes_with(_DRAFT_FORCE_GPU_ARGS)+ if unpinned is not None and unpinned > gpu_files_bytes:+ host_drafter_bytes = unpinned - gpu_files_bytes+ else:+ no_drafter = _files_bytes_with(_DRAFT_FORCE_CPU_ARGS)+ if no_drafter is not None:+ gpu_drafter_bytes = max(0, gpu_files_bytes - no_drafter)+ if not (host_drafter_bytes or gpu_drafter_bytes):+ # A drafter the files term cannot see. It resolves --model-draft against an+ # empty env, which is the admission guard's conservative rule, while the child+ # does inherit LLAMA_ARG_SPEC_DRAFT_MODEL once the extras own --spec-type. That+ # leaves the panel quoting a load with no drafter at all, file or cache.+ inherited = _inherited_drafter_bytes(extras)+ if inherited:+ if _extra_args_draft_offloaded_to_cpu(extras):+ host_drafter_bytes = inherited+ else:+ gpu_drafter_bytes = inherited+ gpu_files_bytes += inherited+ weights_bytes = gpu_files_bytes + host_drafter_bytes + adapter_bytes++ # The drafter keeps its own KV cache and rollback state on top of its file, which+ # the loader budgets separately and the files term says nothing about. Priced+ # wherever the drafter itself lives: a CPU-pinned one still holds that state, in+ # host RAM, so it belongs in the total even though it never reaches the GPU.+ drafter_runtime_bytes = 0+ # The part of that reserve allocated in the TARGET's context rather than the+ # drafter's, so it stays with the target when the two are placed apart.+ target_spec_bytes = 0+ drafter_on_gpu = host_drafter_bytes == 0+ 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.+ #+ # 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.+ probe = _probe_backend()+ probe._read_gguf_metadata(gguf_path)+ embedded_mtp = bool(+ not charged_drafter and _embedded_mtp_engages(probe, config, speculative_type, extras)+ )+ # 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.+ 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.+ 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.+ _managed_draft_cache = True+ try:+ _dc_caps = LlamaCppBackend.probe_server_capabilities()+ # BOTH, matching the launcher: it emits the pair or neither, so a build+ # exposing only one still allocates its inherited or default cache.+ if _dc_caps.get("found") and not (+ _dc_caps.get("spec_draft_cache_k_flag") and _dc_caps.get("spec_draft_cache_v_flag")+ ):+ _managed_draft_cache = False+ except Exception as _dc_exc:+ logger.debug("draft cache-type capability probe failed: %s", _dc_exc)+ _field_draft_cache = spec_draft_cache_type if _managed_draft_cache else None+ draft_n_max = _estimate_draft_n_max(+ config, drafter_path, requested = spec_draft_n_max, extras = extras+ )+ keeps_target_ctx, target_rollback = _estimate_spec_mode_terms(+ drafter_kind,+ extras,+ # Asked of the header, not the mode: the same predicate that decides+ # whether an embedded head engages decides whether Studio emits draft-mtp+ # over an extras-supplied drafter path.+ 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.+ _draft_v_type = draft_v or _field_draft_cache or env_draft_v+ layout = dict(+ swa_full = runtime.swa_full,+ kv_unified = runtime.kv_unified,+ n_ubatch = runtime.n_ubatch,+ flash_attn = bool(_draft_v_type) and _draft_v_type not in {"f16", "bf16", "f32"},+ )+ drafter_runtime_bytes = (+ probe._estimate_mtp_overhead_bytes(+ runtime.n_ctx,+ spec_draft_n_max = draft_n_max,+ draft_cache_type_k = draft_k or _field_draft_cache or env_draft_k,+ draft_cache_type_v = draft_v or _field_draft_cache or env_draft_v,+ drafter_path = drafter_path,+ # The file is already in weights_bytes; this term is runtime only.+ draft_weights_bytes = 0,+ n_parallel = runtime.n_parallel,+ mtp_keeps_target_ctx = keeps_target_ctx,+ target_rollback = target_rollback,+ **layout,+ )+ or 0+ )+ # Same two terms the helper added above, recomputed here to say where they+ # sit. An MLA target under MTP duplicates its own KV context, and a hybrid+ # target keeps one rollback copy per drafted token: both are allocated in the+ # target's context, which is why pinning the drafter to the CPU does not move+ # them and offloading no target layer does not put them on the GPU.+ if keeps_target_ctx and probe._kv_lora_rank is not None:+ # Same layout the helper charged it at, or the subtraction below stops+ # naming the same bytes.+ target_spec_bytes += probe._estimate_kv_cache_bytes(+ runtime.n_ctx, "f16", n_parallel = runtime.n_parallel, **layout+ )+ if target_rollback and draft_n_max > 0:+ target_spec_bytes += (+ probe._mamba_recurrent_state_bytes(runtime.n_parallel) * draft_n_max+ )+ target_spec_bytes = min(target_spec_bytes, drafter_runtime_bytes)++ layer_count = runtime.layer_count+ gpu_fraction = _gguf_offloaded_layer_fraction(+ gpu_memory_mode, gpu_layers, layer_count, extras, device_pin_governs = device_pin_governs+ )++ # Only the main weight is split by --gpu-layers. A projector and a drafter are+ # placed by their own flags, so scaling them by the model's layer fraction let+ # --gpu-layers 0 report zero GPU bytes while both sat in VRAM.+ main_bytes = min(gpu_files_bytes, LlamaCppBackend._get_gguf_size_bytes(gguf_path))+ companion_bytes = max(0, gpu_files_bytes - main_bytes)+ # A drafter is only charged when it lands on the GPU (a CPU-pinned one is dropped+ # from the total upstream), so the projector is the single companion that can be+ # charged and off-GPU: --no-mmproj-offload keeps it in host RAM. Priced by itself+ # rather than by moving every companion, which would strand a resident drafter.+ host_companion_bytes = 0+ # The projector costs more than its file: the encoder's buffers run about 1.3x it,+ # which the placement path budgets as _MMPROJ_VRAM_SAFETY - 1. Charged whenever the+ # projector is in the resident set, and it is in the total wherever it sits, so a+ # near-capacity multimodal load is not called a fit on the file size alone.+ projector_runtime_bytes = 0+ mmproj_bytes = _charged_projector_bytes(config, extras, disable_vision)+ if mmproj_bytes and mmproj_bytes <= companion_bytes:+ # <= companion_bytes is the second half of the test: the files term charges an+ # inherited projector as readily as a configured one, so its bytes have to be+ # in there for this launch to be the one opening it.+ projector_runtime_bytes = int(mmproj_bytes * (LlamaCppBackend._MMPROJ_VRAM_SAFETY - 1.0))+ if _resolved_mmproj_offload(llama_extra_args) is False:+ host_companion_bytes = min(companion_bytes, mmproj_bytes)+ gpu_weights = (+ int(main_bytes * gpu_fraction)+ + int(adapter_bytes * gpu_fraction)+ + companion_bytes+ - host_companion_bytes+ )+ # Charged bytes with no local file behind them: a --spec-draft-hf repository. Its+ # weights are in the files term, but its cache grows with context like any other+ # and cannot be read off a header that is not here, so the total is a floor.+ drafter_kv_unsized = bool(+ ((host_drafter_bytes or gpu_drafter_bytes) and not charged_drafter)+ # An inherited remote drafter repo or projector URL is a file the child fetches+ # and this cannot weigh without leaving the machine. Same marker: the total is+ # a floor, and saying so beats omitting gigabytes in silence.+ or _inherited_remote_files_unsized(extras, disable_vision)+ # A --spec-draft-hf repository in the extras. Its weights are no longer charged+ # here, because charging them means listing the repo over the network on every+ # settings change; the marker is what keeps that honest.+ or bool(_extra_args_mtp_draft_source(extras)[1])+ )+ runtime_bytes = (+ runtime.kv_bytes + runtime.compute_bytes + drafter_runtime_bytes + projector_runtime_bytes+ )++ # -nkvo puts the cache in host RAM. At a long context that is most of the+ # footprint, so ignoring it would report VRAM pressure the load never creates.+ kv_on_gpu = _kv_offload_from_args(llama_extra_args) and gpu_fraction > 0.0+ # Context checkpoints ride inside kv_bytes but never reach the GPU: a checkpoint is+ # a host-heap std::vector<uint8_t> in llama.cpp's common_prompt_checkpoint, capped+ # by --cache-ram, and Studio's own load schema documents it as host memory. They+ # stay in the total, which is aggregate memory, and come out of the GPU figure,+ # which is not: 32 snapshots per slot is the default, so charging them to VRAM+ # warned about GPU pressure an SWA load never creates.+ gpu_kv_bytes = max(0, runtime.kv_bytes - runtime.kv_checkpoint_bytes)+ # 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.+ 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.+ _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+ )+ gpu_bytes += drafter_runtime_gpu_bytes+ # The encoder's buffers sit with the projector, so --no-mmproj-offload takes them+ # to host RAM along with the file.+ if not host_companion_bytes:+ gpu_bytes += projector_runtime_bytes+ if not device_pin_governs and (+ _device_selection_is_cpu(extras, os.environ) or _estimate_host_has_no_gpu()+ ):+ # Nothing is on a GPU because the process was given none, or because this+ # machine has none. A pin overrides both readings: it names cards, and the+ # launch strips whatever contradicted it. Applied here rather+ # than only through the layer fraction because a companion does not follow+ # --gpu-layers: a drafter and a projector are placed by their own flags, and+ # neither of those can name a device that this selection has removed.+ gpu_bytes = 0+ drafter_runtime_gpu_bytes = 0+ return _GgufMemoryBreakdown(+ weights_bytes = weights_bytes,+ kv_bytes = runtime.kv_bytes,+ compute_bytes = runtime.compute_bytes,+ drafter_runtime_bytes = drafter_runtime_bytes,+ drafter_runtime_gpu_bytes = drafter_runtime_gpu_bytes,+ projector_runtime_bytes = projector_runtime_bytes,+ drafter_kv_unsized = drafter_kv_unsized,+ adapters_unsized = adapters_unsized,+ total_bytes = weights_bytes + runtime_bytes,+ gpu_bytes = gpu_bytes,+ kv_estimable = runtime.kv_estimable,+ kv_on_gpu = kv_on_gpu,+ n_ctx = runtime.n_ctx,+ cache_type_kv = runtime.cache_type_kv,+ n_parallel = runtime.n_parallel,+ layer_count = layer_count,+ gpu_layers = gpu_layers if gpu_memory_mode == "manual" else None,+ )++def _guard_device_count(requested_gpu_ids: Optional[list[int]],vulkan_gpu_memory: Optional[list[tuple[int, int, int]]] = None,@@ -8593,7 +10235,7 @@ def _gguf_layer_count(config: ModelConfig) -> Optional[int]:from hub.utils.gguf import resolve_local_gguf_pathmain = resolve_local_gguf_path(repo, variant)if main and Path(main).is_file():- probe = LlamaCppBackend()+ probe = _probe_backend()probe._read_gguf_metadata(str(main))return getattr(probe, "_n_layers", None) or Noneexcept Exception as e:@@ -8633,7 +10275,7 @@ def _is_embedding_gguf(config: ModelConfig) -> bool:main = _local_gguf_main_path(config)if not main:return False- probe = LlamaCppBackend()+ probe = _probe_backend()probe._model_identifier = config.identifierprobe._gguf_path = mainprobe._read_gguf_metadata(main)@@ -8729,7 +10371,7 @@ def _classify_diffusion_gguf(config: ModelConfig) -> Optional[bool]:try:main = _local_gguf_main_path(config)if main:- probe = LlamaCppBackend()+ probe = _probe_backend()probe._read_gguf_metadata(main)if probe.is_diffusion:return True@@ -12066,6 +13708,299 @@ async def install_latest_transformers_route(return InstallLatestTransformersResponse(**result, model_unloaded = unloaded_chat["v"])+# A resolved ModelConfig, kept briefly so dragging the context slider re-runs only the+# arithmetic. from_identifier builds the detection registry and can reach Hugging Face;+# at one call per slider tick that is the whole cost of this endpoint. Short TTL because+# the thing it caches goes stale for a real reason -- a download finishing mid-panel --+# and 30s is under the time it takes to notice.+_ESTIMATE_CONFIG_TTL_SECONDS = 30.0+_ESTIMATE_CONFIG_CACHE_MAX = 8+_estimate_config_cache: "dict[tuple, tuple[float, Any]]" = {}+++def _cached_estimate_config(+ model_identifier: str,+ gguf_variant: Optional[str],+ hf_token: Optional[str],+ native_grant_backed: bool,+):+ """``ModelConfig.from_identifier`` behind a small TTL cache. None if it fails.++ A failure is not cached: the common one is a download still in flight, and the+ next tick of the slider is when that answer changes.+ """+ key = (+ model_identifier,+ gguf_variant,+ native_grant_backed,+ # Same reason as the file cache: a gated repo resolves per token.+ _estimate_token_fingerprint(hf_token),+ )+ now = time.monotonic()+ hit = _estimate_config_cache.get(key)+ 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.+ return _ESTIMATE_NOT_ON_DISK+ from core.inference.llama_cpp import _hf_offline_if_unreachable_for++ def _resolve():+ return ModelConfig.from_identifier(+ model_id = model_identifier,+ hf_token = hf_token,+ gguf_variant = gguf_variant,+ 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.+ config = None+ try:+ from utils.utils import force_hf_offline+ with force_hf_offline():+ config = _resolve()+ except Exception as exc:+ logger.debug(+ "Offline resolve of %s did not answer, retrying online: %s", model_identifier, exc+ )+ #+ # 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.+ #+ # `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.+ if config is None and _estimate_disk_residency(model_identifier) != _ESTIMATE_DISK_UNKNOWN:+ try:+ with _hf_offline_if_unreachable_for(model_identifier):+ config = _resolve()+ except Exception as exc:+ logger.debug("Memory estimate could not resolve %s: %s", model_identifier, exc)+ return None+ if config is None:+ return None+ # Same lock, same reason as the files cache: see the note at its eviction.+ with _ESTIMATE_CACHE_LOCK:+ if len(_estimate_config_cache) >= _ESTIMATE_CONFIG_CACHE_MAX:+ # 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+ # stopped existing on exactly the models it was added for.+ _estimate_config_cache[key] = (time.monotonic(), config)+ return config++[email protected]("/estimate-memory", response_model = EstimateMemoryResponse)+async def estimate_memory(+ request: EstimateMemoryRequest,+ fastapi_request: Request = None,+ current_subject: str = Depends(get_current_subject),+):+ """Price a prospective GGUF load from its header, before anything is allocated.++ Reads only GGUF metadata and file sizes, so it is safe to call on every settings+ change: no model is loaded, no device is touched, nothing is downloaded. A model+ that is not on this disk answers ``not_downloaded``.++ The arithmetic is the loader's own KV, compute-buffer and companion sizing, which+ is the point. Weights times a constant is fine until the KV cache stops being a+ rounding error: at 262k tokens the cache can outweigh the weights, and it swings+ fourfold on the cache dtype alone. Where the header cannot supply the dims this+ answers ``kv_estimable = false`` rather than quoting an assumed total.+ """+ from core.inference.llama_cpp import _args_place_tensors_on_cpu+ from core.inference.llama_server_args import _effective_tensor_parallel++ if is_ollama_manifest_ref(request.model_path):+ # Resolving one writes a .gguf link to disk; that belongs to the load path.+ return EstimateMemoryResponse(available = False, reason = "unsupported_source")+ try:+ model_identifier, _model_log_label, native_grant_backed = (+ # "validate-model", not an operation of this route's own: leases are+ # verified against the exact operation they were signed for, and+ # "estimate-memory" is not one a client can mint. This is the same+ # read-only header probe /validate performs, so it is the right grant.+ _resolve_model_identifier_for_request(request, operation = "validate-model")+ )+ except HTTPException:+ # 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.+ #+ # 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.+ requested_slots = _resolve_parallel_slots(request, fastapi_request)++ def _estimate() -> EstimateMemoryResponse:+ resolved_slots = _effective_parallel_slots(+ requested_slots,+ diffusion_kind = False,+ )+ config = _cached_estimate_config(+ model_identifier,+ request.gguf_variant,+ request.hf_token,+ native_grant_backed,+ )+ if config is _ESTIMATE_NOT_ON_DISK:+ return EstimateMemoryResponse(available = False, reason = "not_downloaded")+ if config is None:+ return EstimateMemoryResponse(available = False, reason = "unsizable")+ if not getattr(config, "is_gguf", False):+ # Safetensors / MLX allocate on a different plan; the GGUF arithmetic+ # would be a made-up number in a confident box.+ return EstimateMemoryResponse(available = False, reason = "not_gguf")+ gguf_path = _local_gguf_main_path(config)+ if not gguf_path:+ return EstimateMemoryResponse(available = False, reason = "not_downloaded")+ # Price the files on this disk, not the repository they came from.+ config = _localized_estimate_config(config, gguf_path)++ breakdown = _gguf_memory_breakdown(+ config,+ gguf_path,+ hf_token = request.hf_token,+ n_ctx = request.n_ctx or 0,+ llama_extra_args = request.llama_extra_args,+ speculative_type = request.speculative_type,+ n_parallel = resolved_slots,+ cache_type_kv = request.cache_type_kv,+ tensor_parallel = bool(request.tensor_parallel),+ n_batch = request.n_batch,+ n_ubatch = request.n_ubatch,+ ctx_checkpoints = request.ctx_checkpoints,+ # A layer split across pinned cards replicates the context-linear+ # compute term and adds per-device pipeline overhead, so the count+ # matters there too, not just in tensor mode. Automatic placement+ # stays at one: _guard_device_count makes the same call.+ n_devices = _guard_device_count(+ # A pin names cards for a launch that puts something on them. 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.+ None+ if _gguf_offloaded_layer_fraction(+ request.gpu_memory_mode,+ request.gpu_layers,+ None,+ request.llama_extra_args,+ device_pin_governs = bool(request.selected_gpu_ids),+ )+ == 0.0+ else request.selected_gpu_ids or None,+ # Tensor mode replicates its buffers 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.+ _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.+ 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 _manual_keeps_tensor_split(+ request.gpu_memory_mode,+ request.gpu_layers,+ request.llama_extra_args,+ ),+ ),+ disable_vision = bool(request.disable_vision),+ gpu_memory_mode = request.gpu_memory_mode,+ gpu_layers = request.gpu_layers,+ spec_draft_n_max = request.spec_draft_n_max,+ spec_draft_cache_type = request.spec_draft_cache_type,+ tensor_split_possible = _tensor_split_possible(request.selected_gpu_ids or None),+ # A pin names the cards, so the launch strips any device flag that says+ # otherwise and this must read the same way.+ device_pin_governs = bool(request.selected_gpu_ids),+ )+ if breakdown is None:+ return EstimateMemoryResponse(available = False, reason = "unsizable")+ return EstimateMemoryResponse(+ available = True,+ weights_bytes = breakdown.weights_bytes,+ kv_bytes = breakdown.kv_bytes,+ compute_bytes = breakdown.compute_bytes,+ drafter_runtime_bytes = breakdown.drafter_runtime_bytes,+ drafter_runtime_gpu_bytes = breakdown.drafter_runtime_gpu_bytes,+ projector_runtime_bytes = breakdown.projector_runtime_bytes,+ drafter_kv_unsized = breakdown.drafter_kv_unsized,+ adapters_unsized = breakdown.adapters_unsized,+ total_bytes = breakdown.total_bytes,+ gpu_bytes = breakdown.gpu_bytes,+ kv_estimable = breakdown.kv_estimable,+ kv_on_gpu = breakdown.kv_on_gpu,+ n_ctx = breakdown.n_ctx,+ cache_type_kv = breakdown.cache_type_kv,+ n_parallel = breakdown.n_parallel,+ layer_count = breakdown.layer_count,+ gpu_layers = breakdown.gpu_layers,+ moe_offload_unmodelled = bool(+ (request.gpu_memory_mode == "manual" and (request.n_cpu_moe or 0) > 0)+ # Outside Manual the extras keep their expert-placement flags: /load+ # strips those only on the Manual branch, where the field owns them.+ # Same predicate the loader's own host-residency gate uses, so -ncmoe,+ # -cmoe and an -ot pattern all say it out loud.+ or (+ request.gpu_memory_mode != "manual"+ and _args_place_tensors_on_cpu(request.llama_extra_args)+ )+ ),+ )++ # Header walks and file stats are blocking; keep them off the event loop so a+ # slider drag cannot stall streaming chats.+ return await asyncio.to_thread(_estimate)++@router.post("/unload", response_model = UnloadResponse)async def unload_model(request: UnloadRequest, current_subject: str = Depends(get_current_subject)):"""Unload a model from memory.diff --git a/studio/backend/tests/test_chat_load_during_training.py b/studio/backend/tests/test_chat_load_during_training.pyindex 973e2853e68..247b2e5980e 100644--- a/studio/backend/tests/test_chat_load_during_training.py+++ b/studio/backend/tests/test_chat_load_during_training.py@@ -2817,7 +2817,10 @@ class TestEstimateGgufRequiredGb(unittest.TestCase):self.assertEqual(seen["ctx"], 131072)self.assertEqual(seen["n_parallel"], 1) # default single slotself.assertFalse(seen["swa_full"])- self.assertFalse(seen["flash_attn"])+ # load_model appends --flash-attn on to every launch whose build has the+ # flag, so the guard sizes the cache the launch will actually allocate.+ # False here padded variable-width V tensors to the model-wide maximum.+ self.assertTrue(seen["flash_attn"])# override below max_seq_length -> larger (max_seq_length) winsself.assertAlmostEqual(r._estimate_gguf_kv_gb("m", 4096, ["--ctx-size", "1024"]), 4.0)self.assertEqual(seen["ctx"], 4096)diff --git a/studio/backend/tests/test_estimator_flash_attn_parity.py b/studio/backend/tests/test_estimator_flash_attn_parity.pynew file mode 100644index 00000000000..188c4da4017--- /dev/null+++ b/studio/backend/tests/test_estimator_flash_attn_parity.py@@ -0,0 +1,338 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""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 --++ 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.++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:++ ctx -ctk/-ctv reserved before allocated after+ 4096 q8_0 343 MiB 238 MiB 238 MiB+ 4096 q4_0 287 MiB 126 MiB 126 MiB+ 32768 q8_0 2744 MiB 1904 MiB 1904 MiB+ 32768 q4_0 2296 MiB 1008 MiB 1008 MiB++The tests below do not need a binary: they assert the arithmetic identity that+produced those numbers, which is that BOTH axes shrink with the cache type, not just+K. A regression puts the f16 V back and the ratio jumps.+"""++import sys+import types as _types+from pathlib import Path++# Stub heavy / unavailable deps before importing the module under test.+# Same block, same reasons, as tests/test_memory_estimate.py.++_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)+if _BACKEND_DIR not in sys.path:+ sys.path.insert(0, _BACKEND_DIR)++_loggers_stub = _types.ModuleType("loggers")+_loggers_stub.get_logger = lambda name: __import__("logging").getLogger(name)+sys.modules.setdefault("loggers", _loggers_stub)++_structlog_stub = _types.ModuleType("structlog")+_structlog_stub.get_logger = lambda *a, **k: __import__("logging").getLogger("stub")+sys.modules.setdefault("structlog", _structlog_stub)++import importlib.util as _ilu # noqa: E402++import pytest # noqa: E402++import asyncio # noqa: E402+from types import SimpleNamespace # noqa: E402++import routes.inference as ri # noqa: E402+from models.inference import EstimateMemoryRequest # noqa: E402+from core.inference.llama_cpp import _kv_bytes_per_elem # noqa: E402++# Reuse the GGUF blob builder rather than copying it, for the reason its first+# borrower gives: a second copy of the writer would drift from the parser.+_kv_spec = _ilu.spec_from_file_location(+ "_kv_cache_estimation_for_flash_attn_parity",+ Path(__file__).resolve().parent / "test_kv_cache_estimation.py",+)+_kv_mod = _ilu.module_from_spec(_kv_spec)+_kv_spec.loader.exec_module(_kv_mod)+_make_gguf_bytes = _kv_mod._make_gguf_bytes++# Qwen3-0.6B's real shape, so the ratios below are the ones that were measured.+_QWEN3_FIELDS = {+ "context_length": 40960,+ "block_count": 28,+ "embedding_length": 1024,+ "attention.head_count": 16,+ "attention.head_count_kv": 8,+ "attention.key_length": 128,+ "attention.value_length": 128,+}++[email protected](autouse = True)+def _clear_flash_attn_parity_caches():+ ri._estimate_files_cache.clear()+ ri._estimate_config_cache.clear()+ yield+ ri._estimate_files_cache.clear()+ ri._estimate_config_cache.clear()+++def qwen3_shaped_gguf(tmp_path):+ # general.architecture goes in FIRST. The reader takes it before it knows which+ # prefix the rest of the keys carry, so a blob that writes it last parses as a+ # header with no dimensions and every figure below silently becomes zero.+ fields = {"general.architecture": "qwen3"}+ fields.update({f"qwen3.{k}": v for k, v in _QWEN3_FIELDS.items()})+ path = tmp_path / "qwen3-shaped.gguf"+ path.write_bytes(_make_gguf_bytes("qwen3", fields))+ return str(path)+++def _estimate_through_route(**kwargs):+ """Drive the real route far enough to capture what it hands the sizing call."""+ try:+ asyncio.run(+ ri.estimate_memory(+ EstimateMemoryRequest(**kwargs),+ fastapi_request = None,+ current_subject = "test",+ )+ )+ except RuntimeError:+ pass+++def _kv_bytes(+ path,+ ctx,+ cache_type,+ slots = 1,+):+ return ri._gguf_runtime_bytes(path, ctx, None, slots, cache_type, False).kv_bytes++[email protected]("cache_type", ["q8_0", "q4_0", "q5_1", "iq4_nl"])[email protected]("n_ctx", [4096, 32768])+def test_a_quantized_cache_shrinks_both_axes_not_only_k(qwen3_shaped_gguf, cache_type, n_ctx):+ """The load-bearing one. K and V are the same width in this model, so a correct+ price is exactly ``bpe(type) / bpe(f16)`` of the f16 price. The old behaviour+ shrank K and pinned V at f16, landing halfway."""+ f16 = _kv_bytes(qwen3_shaped_gguf, n_ctx, "f16")+ quantized = _kv_bytes(qwen3_shaped_gguf, n_ctx, cache_type)+ expected_ratio = _kv_bytes_per_elem(cache_type) / _kv_bytes_per_elem("f16")++ assert quantized == pytest.approx(f16 * expected_ratio, rel = 1e-6), (+ f"{cache_type} at {n_ctx} priced {quantized} bytes against an f16 price of "+ f"{f16}: ratio {quantized / f16:.4f}, expected {expected_ratio:.4f}. A ratio "+ f"near the midpoint means V is still being charged at f16, which is the "+ f"flash_attn = False arm on a cache llama.cpp will not start without it."+ )+++def test_the_measured_llama_cpp_reservations_are_reproduced(qwen3_shaped_gguf):+ """The four cells from the docstring, as figures rather than as a ratio. These+ are what llama-server b10632 actually allocated for this model shape."""+ mib = 1024 * 1024+ for n_ctx, cache_type, allocated_mib in (+ (4096, "q8_0", 238.0),+ (4096, "q4_0", 126.0),+ (32768, "q8_0", 1904.0),+ (32768, "q4_0", 1008.0),+ ):+ priced = _kv_bytes(qwen3_shaped_gguf, n_ctx, cache_type) / mib+ assert priced == pytest.approx(allocated_mib, rel = 1e-6), (+ f"{cache_type} at {n_ctx}: priced {priced:.1f} MiB, llama-server b10632 "+ f"allocated {allocated_mib} MiB"+ )+++def test_an_f16_cache_is_unchanged_by_the_flash_attn_rule(qwen3_shaped_gguf):+ """The fix must not move the unquantized path. f16 leaves flash attention to+ llama.cpp's own auto-detection, so the padded-V arm still applies and these+ figures are the ones the guard has always used."""+ mib = 1024 * 1024+ assert _kv_bytes(qwen3_shaped_gguf, 4096, "f16") / mib == pytest.approx(448.0)+ assert _kv_bytes(qwen3_shaped_gguf, 32768, "f16") / mib == pytest.approx(3584.0)+ assert _kv_bytes(qwen3_shaped_gguf, 4096, None) == _kv_bytes(qwen3_shaped_gguf, 4096, "f16")++[email protected]("wide_type", ["bf16", "f32"])+def test_a_cache_wider_than_f16_does_not_force_flash_attention(qwen3_shaped_gguf, wide_type):+ """The rule keys on "quantized", not on "not f16". bf16 and f32 are neither+ quantized nor eligible for the forced-FA path, so they keep the conservative+ padding."""+ f16 = _kv_bytes(qwen3_shaped_gguf, 4096, "f16")+ wide = _kv_bytes(qwen3_shaped_gguf, 4096, wide_type)+ assert wide >= f16, f"{wide_type} priced {wide} below the f16 price {f16}"+++def test_a_quantized_v_in_the_extra_arguments_is_read_the_same_way(qwen3_shaped_gguf):+ """The panel field is not the only way to ask for one. An extras-supplied+ --cache-type-v must reach the same rule, because it reaches the same child."""+ field = ri._gguf_runtime_bytes(qwen3_shaped_gguf, 4096, None, 1, "q4_0", False).kv_bytes+ extras = ri._gguf_runtime_bytes(+ qwen3_shaped_gguf,+ 4096,+ ["--cache-type-k", "q4_0", "--cache-type-v", "q4_0"],+ 1,+ None,+ False,+ ).kv_bytes+ assert extras == field, (+ f"extras priced {extras} where the field priced {field}; the launch cannot "+ f"tell the two apart, so neither should the estimate"+ )+++# The round that followed: four placement inputs the estimate was reading wrong.+# Each of these fails on the parent commit.+++def test_a_cpu_only_manual_launch_is_not_charged_for_a_pinned_card(monkeypatch, qwen3_shaped_gguf):+ """Manual with zero layers is a CPU-only launch, and the loader drops the split+ flags for it. Charging the pinned card 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.++ Driven through the route, because the defect was in what the route HANDS the+ device count, not in the device count itself. Asserting the two helpers in+ isolation passes on the unfixed tree."""+ one = ri._gguf_runtime_bytes(+ qwen3_shaped_gguf, 32768, None, 4, "f16", False, None, None, n_devices = 1+ )+ two = ri._gguf_runtime_bytes(+ qwen3_shaped_gguf, 32768, None, 4, "f16", False, None, None, n_devices = 2+ )+ assert (+ two.compute_bytes > one.compute_bytes+ ), "a second device has to cost something, or this test proves nothing"++ seen = {}++ def _spy(*args, **kwargs):+ seen["n_devices"] = kwargs.get("n_devices")+ raise RuntimeError("stop here; the argument is the whole assertion")++ monkeypatch.setattr(ri, "_gguf_memory_breakdown", _spy)+ monkeypatch.setattr(+ ri,+ "_cached_estimate_config",+ lambda *a, **kw: SimpleNamespace(+ identifier = "local",+ gguf_file = qwen3_shaped_gguf,+ is_gguf = True,+ gguf_variant = None,+ gguf_mmproj_file = None,+ gguf_mtp_file = None,+ gguf_dspark_file = None,+ gguf_dflash_file = None,+ ),+ )+ for layers, expected in ((0, 1), (40, 2)):+ seen.clear()+ _estimate_through_route(+ model_path = qwen3_shaped_gguf,+ gpu_memory_mode = "manual",+ gpu_layers = layers,+ selected_gpu_ids = [0, 1],+ )+ assert seen.get("n_devices") == expected, (+ f"--gpu-layers {layers} with a two-card pin priced "+ f"{seen.get('n_devices')} devices, expected {expected}"+ )+++def test_an_inherited_gpu_layer_count_is_read_in_auto(monkeypatch, qwen3_shaped_gguf):+ """Auto emits no -ngl on the fitting path, so 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, "n_gpu_layers already set by user")."""+ monkeypatch.delenv("LLAMA_ARG_N_GPU_LAYERS", raising = False)+ assert ri._gguf_offloaded_layer_fraction("auto", None, 27, None) == 1.0++ monkeypatch.setenv("LLAMA_ARG_N_GPU_LAYERS", "0")+ assert ri._gguf_offloaded_layer_fraction("auto", None, 27, None) == 0.0++ monkeypatch.setenv("LLAMA_ARG_N_GPU_LAYERS", "14")+ half = ri._gguf_offloaded_layer_fraction("auto", None, 27, None)+ assert 0.0 < half < 1.0, f"a partial inherited count priced {half}"++ # -1 and auto are llama.cpp's own default, so they leave the fitter free to choose+ # and are not an override.+ for auto_value in ("-1", "auto", ""):+ monkeypatch.setenv("LLAMA_ARG_N_GPU_LAYERS", auto_value)+ assert ri._gguf_offloaded_layer_fraction("auto", None, 27, None) == 1.0+++def test_an_explicit_ngl_in_the_extras_still_beats_the_inherited_count(+ monkeypatch, qwen3_shaped_gguf+):+ """argv is parsed after the environment and wins, so an extras -ngl is the answer+ whatever the env says."""+ monkeypatch.setenv("LLAMA_ARG_N_GPU_LAYERS", "0")+ assert ri._gguf_offloaded_layer_fraction("auto", None, 27, ["-ngl", "999"]) == 1.0+++def test_pass_through_adapters_are_charged_and_follow_the_base_placement(+ tmp_path, qwen3_shaped_gguf+):+ """llama.cpp loads every --lora / --control-vector into resident tensors on top of+ the base model, on the base tensor's buffer type. The files term prices only the+ target and its companions, so without this an adapter load was a fit on the base+ model's size alone."""+ from core.inference.llama_cpp import _sidecar_adapter_bytes++ lora = tmp_path / "adapter.gguf"+ size = 7 * 1024 * 1024+ lora.write_bytes(b"\0" * size)+ assert _sidecar_adapter_bytes(["--lora", str(lora)]) == size+ # A named file that cannot be stat'd is the "engaged but unsized" case.+ assert _sidecar_adapter_bytes(["--lora", str(tmp_path / "missing.gguf")]) is None+ # And no adapters is zero, not None, so the marker stays off for every ordinary load.+ assert _sidecar_adapter_bytes([]) == 0++ # The helper pre-dates this; what is new is that the panel asks it. Driven through+ # the breakdown so the test fails on a tree where the term is computed and dropped.+ config = SimpleNamespace(+ identifier = "local",+ gguf_file = qwen3_shaped_gguf,+ is_gguf = True,+ gguf_variant = None,+ gguf_mmproj_file = None,+ gguf_mtp_file = None,+ gguf_dspark_file = None,+ gguf_dflash_file = None,+ )+ bare = ri._gguf_memory_breakdown(config, qwen3_shaped_gguf, n_ctx = 4096)+ with_lora = ri._gguf_memory_breakdown(+ config, qwen3_shaped_gguf, n_ctx = 4096, llama_extra_args = ["--lora", str(lora)]+ )+ assert bare is not None and with_lora is not None+ assert with_lora.weights_bytes - bare.weights_bytes == size, (+ f"a {size}-byte adapter moved weights by " f"{with_lora.weights_bytes - bare.weights_bytes}"+ )+ assert with_lora.total_bytes - bare.total_bytes == size+ assert not with_lora.adapters_unsized++ missing = ri._gguf_memory_breakdown(+ config,+ qwen3_shaped_gguf,+ n_ctx = 4096,+ llama_extra_args = ["--lora", str(tmp_path / "missing.gguf")],+ )+ assert (+ missing is not None and missing.adapters_unsized+ ), "an unsizable adapter has to mark the total a floor rather than vanish"diff --git a/studio/backend/tests/test_memory_estimate.py b/studio/backend/tests/test_memory_estimate.pynew file mode 100644index 00000000000..8faafd84bf1--- /dev/null+++ b/studio/backend/tests/test_memory_estimate.py@@ -0,0 +1,3180 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""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.+* ``_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.+* ``_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.+* ``_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.++No GPU, no network, no model load: every GGUF here is a synthetic header on+tmp_path. Cross-platform.+"""++import inspect+import os+import sys+import types as _types+from pathlib import Path++import pytest++# Stub heavy / unavailable deps before importing the module under test.+# Copied verbatim from tests/test_kv_cache_estimation.py -- same reasons.++_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)+if _BACKEND_DIR not in sys.path:+ sys.path.insert(0, _BACKEND_DIR)++# loggers+_loggers_stub = _types.ModuleType("loggers")+_loggers_stub.get_logger = lambda name: __import__("logging").getLogger(name)+sys.modules.setdefault("loggers", _loggers_stub)++# structlog. Carries get_logger because this stub is process-wide: whichever test+# module is imported first wins the setdefault, and utils/prebuilt/freshness_flow+# calls structlog.get_logger at import time. A bare module here fails that import+# for every later module on a runner without the real package.+_structlog_stub = _types.ModuleType("structlog")+_structlog_stub.get_logger = lambda *a, **k: __import__("logging").getLogger("stub")+sys.modules.setdefault("structlog", _structlog_stub)++# httpx -- only stub when the real library is missing. Unconditional stubbing+# shadows HTTPError/Response that huggingface_hub.errors imports at load time,+# silently breaking the transformers introspection tier.+try:+ import httpx as _httpx_real # noqa: F401+except ImportError:+ _httpx_stub = _types.ModuleType("httpx")+ for _exc_name in (+ "ConnectError",+ "TimeoutException",+ "ReadTimeout",+ "ReadError",+ "RemoteProtocolError",+ "CloseError",+ "HTTPError",+ "RequestError",+ ):+ setattr(_httpx_stub, _exc_name, type(_exc_name, (Exception,), {}))++ class _FakeTimeout:+ def __init__(self, *a, **kw):+ pass++ _httpx_stub.Timeout = _FakeTimeout+ _httpx_stub.Response = type("Response", (), {})+ _httpx_stub.Client = type(+ "Client",+ (),+ {+ "__init__": lambda self, **kw: None,+ "__enter__": lambda self: self,+ "__exit__": lambda self, *a: None,+ },+ )+ sys.modules["httpx"] = _httpx_stub++import asyncio # noqa: E402+from types import SimpleNamespace # noqa: E402++import routes.inference as ri # noqa: E402+from models.inference import EstimateMemoryRequest # noqa: E402+from utils.models.model_config import ModelConfig # noqa: E402++# Reuse the GGUF blob builder rather than copying it: these tests are only worth+# anything if the bytes they parse are the bytes the real parser was written for,+# and a second copy of the writer would drift from the first. Loaded by path+# because `tests` is not importable as a package name from every runner layout.+import importlib.util as _ilu # noqa: E402++_kv_spec = _ilu.spec_from_file_location(+ "_kv_cache_estimation_for_memory_estimate",+ Path(__file__).resolve().parent / "test_kv_cache_estimation.py",+)+_kv_mod = _ilu.module_from_spec(_kv_spec)+_kv_spec.loader.exec_module(_kv_mod)+_make_gguf_bytes = _kv_mod._make_gguf_bytes++_GIB = 1024**3++[email protected](autouse = True)+def _clear_estimate_caches():+ """Both module caches are TTL'd, not per-request, so they leak across tests.++ ``_estimate_files_cache`` is keyed on the config identity and NOT on the+ context, which is exactly the behaviour under test -- so a stale entry from+ an earlier test would silently satisfy an assertion here.+ """+ ri._estimate_files_cache.clear()+ ri._estimate_config_cache.clear()+ yield+ ri._estimate_files_cache.clear()+ ri._estimate_config_cache.clear()+++# Fixtures: synthetic GGUF headers+++# Pure-GQA geometry with no sliding window, so the estimator takes the standard+# Path-4 branch and -- more importantly -- the dynamic SWA resolver never fires,+# which is the only thing in this code path that could reach Hugging Face.+_GQA_FIELDS = {+ "context_length": 8192,+ "block_count": 12,+ "attention.head_count": 8,+ "attention.head_count_kv": 4,+ "attention.key_length": 64,+ "attention.value_length": 64,+ "embedding_length": 512,+}+++def _write_gguf(+ tmp_path: Path,+ arch: str,+ fields: dict,+ name: str = "model.gguf",+) -> str:+ kv = {"general.architecture": arch}+ kv.update({f"{arch}.{k}": v for k, v in fields.items()})+ path = tmp_path / name+ path.write_bytes(_make_gguf_bytes(arch, kv))+ return str(path)+++def gqa_gguf(tmp_path) -> str:+ return _write_gguf(tmp_path, "qwen3", _GQA_FIELDS)+++def dimless_gguf(tmp_path) -> str:+ """A header carrying a layer count and nothing the KV formula can use.++ Real GGUFs like this exist (truncated / minimal metadata), and they are the+ whole reason ``kv_estimable`` is a separate field.+ """+ return _write_gguf(tmp_path, "qwen3", {"block_count": 12}, name = "dimless.gguf")+++# A. _gguf_offloaded_layer_fraction+++class TestOffloadedLayerFraction:+ """Share of the weights the requested offload keeps on the GPU."""++ def test_auto_is_full(self):+ # Auto asks llama.cpp to fit everything and only spills when it cannot,+ # so 1.0 is the cost of the load succeeding -- not an approximation.+ assert ri._gguf_offloaded_layer_fraction("auto", None, 12) == 1.0+ assert ri._gguf_offloaded_layer_fraction(None, 4, 12) == 1.0++ @pytest.mark.parametrize("gpu_layers", [None, -1])+ def test_manual_without_a_layer_count_is_full(self, gpu_layers):+ # "manual" with no usable -ngl is the slider's own unset state; it must+ # read like Auto rather than dividing by a number nobody chose.+ assert ri._gguf_offloaded_layer_fraction("manual", gpu_layers, 12) == 1.0++ @pytest.mark.parametrize("layer_count", [None, 0])+ def test_unknown_layer_count_is_full(self, layer_count):+ # Remote / unreadable header: there is no denominator, and inventing one+ # would put a fabricated split in front of the user.+ assert ri._gguf_offloaded_layer_fraction("manual", 20, layer_count) == 1.0++ def test_manual_split_uses_block_count_plus_one(self):+ # +1 is the output layer, matching the ceiling the UI slider uses; a bare+ # gpu_layers/layer_count would read 100% one layer early.+ assert ri._gguf_offloaded_layer_fraction("manual", 20, 65) == pytest.approx(20 / 66)++ def test_over_large_gpu_layers_clamps(self):+ # -ngl 999 is the idiomatic "all of it"; it must not exceed the weights.+ assert ri._gguf_offloaded_layer_fraction("manual", 999, 65) == 1.0++ def test_zero_layers_is_cpu_only(self):+ assert ri._gguf_offloaded_layer_fraction("manual", 0, 65) == 0.0++ def test_a_layer_count_in_the_extras_wins_in_either_mode(self):+ # Auto emits -ngl -1 and the extras are appended after it, so a user count+ # last-wins at the child; the loader reads it back with the same parser+ # (llama_cpp.py:6841, the non-manual arm). Treating Auto as always fully+ # resident put a GPU-exceeds warning on a load running on the CPU.+ assert ri._gguf_offloaded_layer_fraction("auto", None, 12, ["-ngl", "0"]) == 0.0+ assert ri._gguf_offloaded_layer_fraction(+ "auto", None, 12, ["--gpu-layers", "6"]+ ) == pytest.approx(6 / 13)+ # -1 is "all layers", and above the count clamps rather than exceeding.+ assert ri._gguf_offloaded_layer_fraction("auto", None, 12, ["-ngl", "-1"]) == 1.0+ assert ri._gguf_offloaded_layer_fraction("auto", None, 12, ["-ngl", "999"]) == 1.0+ # Malformed is llama-server's to reject; it names it better than a guess here.+ assert ri._gguf_offloaded_layer_fraction("auto", None, 12, ["-ngl", "abc"]) == 1.0+ # Manual does strip the flag, but only after translating its last-wins value+ # into the load field (routes/inference.py, the manual branch of /load and of+ # the validate path), so the extras count is what the child runs there too.+ assert ri._gguf_offloaded_layer_fraction("manual", 0, 12, ["-ngl", "999"]) == 1.0+ assert ri._gguf_offloaded_layer_fraction("manual", 12, 12, ["-ngl", "0"]) == 0.0+ # And with nothing in the extras the field still owns it.+ assert ri._gguf_offloaded_layer_fraction("manual", 0, 12, ["--top-k", "40"]) == 0.0+++# B. _gguf_runtime_bytes against real GGUF headers+++class TestGgufRuntimeBytes:+ """The context-dependent half, priced off a real (synthetic) header."""++ def test_kv_grows_with_context(self, gqa_gguf):+ sizes = [ri._gguf_runtime_bytes(gqa_gguf, ctx).kv_bytes for ctx in (1024, 4096, 16384)]+ assert all(a < b for a, b in zip(sizes, sizes[1:])), sizes+ assert sizes[0] > 0++ def test_quantized_cache_is_smaller_than_f16(self, gqa_gguf):+ # 4x on the cache dtype alone at the same context is the single biggest+ # lever the panel exposes, so the estimate has to actually follow it.+ f16 = ri._gguf_runtime_bytes(gqa_gguf, 8192, cache_type_kv = "f16")+ q4 = ri._gguf_runtime_bytes(gqa_gguf, 8192, cache_type_kv = "q4_0")+ assert q4.kv_bytes < f16.kv_bytes+ assert q4.n_ctx == f16.n_ctx == 8192++ def test_reports_what_it_priced(self, gqa_gguf):+ # These fields exist so a reader can judge the estimate instead of+ # trusting it; they must describe the arithmetic that actually ran.+ runtime = ri._gguf_runtime_bytes(gqa_gguf, 4096, cache_type_kv = "q8_0", n_parallel = 1)+ assert runtime.kv_estimable is True+ assert runtime.n_ctx == 4096+ assert runtime.cache_type_kv == "q8_0"+ assert runtime.n_parallel == 1+ assert runtime.layer_count == _GQA_FIELDS["block_count"]++ def test_zero_context_prices_the_native_one(self, gqa_gguf):+ # n_ctx = 0 is the panel's "Auto"; it prices the header's context_length,+ # which is what an Auto load would ask llama-server for.+ runtime = ri._gguf_runtime_bytes(gqa_gguf, 0)+ assert runtime.n_ctx == _GQA_FIELDS["context_length"]+ assert runtime.kv_bytes > 0++ def test_missing_dims_are_unknown_not_zero(self, dimless_gguf):+ # THE case this NamedTuple exists for. kv_bytes == 0 here means "could not+ # size", and the only thing separating it from a genuine zero is the flag.+ runtime = ri._gguf_runtime_bytes(dimless_gguf, 32768)+ assert runtime.kv_estimable is False+ assert runtime.kv_bytes == 0+ assert runtime.compute_bytes == 0+ # It also stops describing a priced load, since none was priced.+ assert runtime.n_ctx == 0+ # block_count is a separate key and survives: a caller sizing a manual offload+ # split needs it, and without it _gguf_offloaded_layer_fraction answers 1.0 and+ # calls --gpu-layers 0 a fully GPU-resident load.+ assert runtime.layer_count == 12+ assert ri._gguf_offloaded_layer_fraction("manual", 0, runtime.layer_count) == 0.0++ 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.+ """+ mamba = _write_gguf(+ tmp_path,+ "mamba",+ {+ "block_count": 24,+ "embedding_length": 2048,+ "context_length": 8192,+ "ssm.conv_kernel": 4,+ "ssm.inner_size": 4096,+ "ssm.state_size": 16,+ "ssm.time_step_rank": 128,+ },+ name = "mamba.gguf",+ )+ runtime = ri._gguf_runtime_bytes(mamba, 32768)+ assert runtime.kv_estimable is False+ assert runtime.layer_count == 24+ assert ri._gguf_offloaded_layer_fraction("manual", 0, runtime.layer_count) == 0.0++ def test_unreadable_file_is_unknown(self, tmp_path):+ # Not a GGUF at all: the header walk raises and the caller must still get+ # a well-formed "unknown", never a partial number.+ junk = tmp_path / "not-a-gguf.gguf"+ junk.write_bytes(b"not a gguf header")+ assert ri._gguf_runtime_bytes(str(junk), 4096) == ri._GGUF_RUNTIME_UNKNOWN+++# C. Training-guard compatibility+++class TestKvGbWrapperCompatibility:+ """``_estimate_gguf_kv_gb`` is the training admission guard's entry point.++ It is now a wrapper, so the refactor is only correct if it still returns+ exactly the old scalar: (KV + compute) in GB. Anything else silently moves+ the threshold at which chat is refused during a training run.+ """++ @pytest.mark.parametrize(+ "kwargs",+ [+ dict(),+ dict(cache_type_kv = "q8_0"),+ dict(n_parallel = 4),+ dict(n_batch = 2048, n_ubatch = 512),+ dict(ctx_checkpoints = 4),+ dict(n_devices = 2),+ dict(is_diffusion = True),+ dict(llama_extra_args = ["-c", "16384"]),+ ],+ )+ def test_wrapper_equals_summed_tuple(self, gqa_gguf, kwargs):+ runtime = ri._gguf_runtime_bytes(gqa_gguf, 4096, **kwargs)+ assert ri._estimate_gguf_kv_gb(gqa_gguf, 4096, **kwargs) == pytest.approx(+ (runtime.kv_bytes + runtime.compute_bytes) / _GIB+ )++ def test_unsizable_header_is_zero_gb(self, dimless_gguf):+ # Unchanged legacy behaviour: a cache the guard cannot size must not+ # become a refusal on its own, so it contributes nothing.+ assert ri._estimate_gguf_kv_gb(dimless_gguf, 32768) == 0.0++ def test_the_guard_keeps_the_larger_context_the_panel_does_not(self, gqa_gguf):+ """A smaller ``-c`` in the extras is what the launch runs, not what the+ guard reserves against. The guard deliberately takes the maximum, since a+ request that later drops the flag must not have been admitted against the+ smaller cache; the panel is quoting a number to a user and takes the launch+ value (``resolve_requested_ctx``, load_model's own resolver).+ """+ smaller = ["-c", "8192"]+ guard = ri._gguf_runtime_bytes(gqa_gguf, 131072, smaller)+ panel = ri._gguf_runtime_bytes(gqa_gguf, 131072, smaller, ctx_last_wins = True)+ assert guard.n_ctx == 131072+ assert panel.n_ctx == 8192+ assert panel.kv_bytes < guard.kv_bytes+ # The wrapper the guard calls must still be the maximum arm, unchanged.+ assert ri._estimate_gguf_kv_gb(gqa_gguf, 131072, llama_extra_args = smaller) == pytest.approx(+ (guard.kv_bytes + guard.compute_bytes) / _GIB+ )+ # A larger override is the same either way, and -c 0 means the model's own+ # trained context in llama.cpp rather than the panel's number.+ larger = ["-c", "262144"]+ assert (+ ri._gguf_runtime_bytes(gqa_gguf, 131072, larger, ctx_last_wins = True).n_ctx+ == ri._gguf_runtime_bytes(gqa_gguf, 131072, larger).n_ctx+ == 262144+ )+ assert (+ ri._gguf_runtime_bytes(gqa_gguf, 131072, ["-c", "0"], ctx_last_wins = True).n_ctx+ == _GQA_FIELDS["context_length"]+ )+++# D. _gguf_resident_file_gb and _gguf_memory_breakdown+++class TestResidentFileGb:+ """The weights term, obtained by subtracting the context term back out."""++ def test_subtracts_the_local_arm_context_term(self, gqa_gguf, monkeypatch):+ # Prove the pairing rather than the plumbing: a config with a local+ # gguf_file takes the _estimate_gguf_kv_gb arm, so feeding+ # _estimate_gguf_required_gb a known "files + that term" must leave+ # exactly the files behind.+ ctx_term = ri._estimate_gguf_kv_gb(gqa_gguf, 0, None)+ assert ctx_term > 0, "fixture must have a non-trivial context term to subtract"+ config = SimpleNamespace(identifier = "local/model", gguf_file = gqa_gguf, is_gguf = True)+ monkeypatch.setattr(ri, "_estimate_gguf_required_gb", lambda cfg, **kw: 3.0 + ctx_term)+ assert ri._gguf_resident_file_gb(config) == pytest.approx(3.0)++ def test_unresolvable_size_is_not_cached(self, gqa_gguf, monkeypatch):+ # A None is usually a download still in flight, so the next slider tick+ # is precisely when the answer changes; caching it would freeze the panel+ # on "unsizable" for the whole TTL.+ config = SimpleNamespace(identifier = "local/model", gguf_file = gqa_gguf, is_gguf = True)+ monkeypatch.setattr(ri, "_estimate_gguf_required_gb", lambda cfg, **kw: None)+ assert ri._gguf_resident_file_gb(config) is None+ assert ri._estimate_files_cache == {}+++class TestMemoryBreakdown:+ """Composition of files + runtime into the panel's itemization."""++ WEIGHTS_GB = 4.0+ # Of that files total, the main weight and everything beside it. Pinned because+ # the synthetic header on tmp_path is a few hundred bytes, which would leave the+ # whole 4 GB looking like companions and make the offload split meaningless.+ MAIN_BYTES = 3 * 1024**3+ COMPANION_BYTES = int(WEIGHTS_GB * 1024**3) - MAIN_BYTES++ @pytest.fixture+ def config(self, gqa_gguf):+ return SimpleNamespace(+ identifier = "local/model",+ gguf_file = gqa_gguf,+ is_gguf = True,+ gguf_mmproj_file = None,+ )++ @pytest.fixture(autouse = True)+ def _fixed_files(self, monkeypatch):+ # Pin the files term so every assertion below is about the composition,+ # not about repository listing (which would want the network).+ monkeypatch.setattr(ri, "_gguf_resident_file_gb", lambda cfg, **kw: self.WEIGHTS_GB)+ real_size = ri.LlamaCppBackend._get_gguf_size_bytes++ def _size(path):+ name = os.path.basename(str(path))+ return self.MAIN_BYTES if name == "model.gguf" else real_size(path)++ monkeypatch.setattr(ri.LlamaCppBackend, "_get_gguf_size_bytes", staticmethod(_size))++ def test_weights_do_not_move_with_context(self, config, gqa_gguf):+ # THE invariant the subtraction approach exists to keep. If the context+ # term ever leaked into the files term, this is where it shows up -- and+ # the runtime terms must still be moving, or the test proves nothing.+ small = ri._gguf_memory_breakdown(config, gqa_gguf, n_ctx = 2048)+ large = ri._gguf_memory_breakdown(config, gqa_gguf, n_ctx = 32768)+ assert small.weights_bytes == large.weights_bytes+ assert large.kv_bytes > small.kv_bytes+ assert large.total_bytes > small.total_bytes++ def test_total_is_the_sum_of_its_parts(self, config, gqa_gguf):+ b = ri._gguf_memory_breakdown(config, gqa_gguf, n_ctx = 8192)+ assert b.weights_bytes == int(round(self.WEIGHTS_GB * _GIB))+ assert b.total_bytes == b.weights_bytes + b.kv_bytes + b.compute_bytes++ def test_auto_placement_puts_everything_on_the_gpu(self, config, gqa_gguf):+ # Auto's estimate is the cost of the load succeeding, so nothing is+ # attributed to host RAM and gpu_layers is reported as unset.+ b = ri._gguf_memory_breakdown(config, gqa_gguf, n_ctx = 8192, gpu_memory_mode = "auto")+ assert b.gpu_bytes == b.total_bytes+ assert b.kv_on_gpu is True+ assert b.gpu_layers is None++ def test_an_auto_load_with_an_extras_ngl_is_not_fully_resident(self, config, gqa_gguf):+ # The one thing that overrides Auto: the child takes the last -ngl, so+ # -ngl 0 runs on the CPU however the panel's own mode reads.+ full = ri._gguf_memory_breakdown(config, gqa_gguf, n_ctx = 8192, gpu_memory_mode = "auto")+ on_cpu = ri._gguf_memory_breakdown(+ config,+ gqa_gguf,+ n_ctx = 8192,+ gpu_memory_mode = "auto",+ llama_extra_args = ["-ngl", "0"],+ )+ assert on_cpu.total_bytes == full.total_bytes+ assert on_cpu.kv_on_gpu is False+ # The main weight, its cache and its compute all leave the GPU; whatever is+ # placed by its own flag (a projector here would be) does not.+ assert on_cpu.gpu_bytes == full.gpu_bytes - (+ self.MAIN_BYTES + full.kv_bytes + full.compute_bytes+ )++ def test_a_smaller_ctx_override_is_the_context_priced(self, config, gqa_gguf):+ # The panel reports what the launch runs, so a -c below the Context Length+ # control prices the smaller cache and says so in n_ctx.+ b = ri._gguf_memory_breakdown(+ config, gqa_gguf, n_ctx = 131072, llama_extra_args = ["-c", "8192"]+ )+ bigger = ri._gguf_memory_breakdown(config, gqa_gguf, n_ctx = 131072)+ assert b.n_ctx == 8192+ assert b.kv_bytes < bigger.kv_bytes++ def test_a_manual_layer_count_in_the_extras_is_priced(self, config, gqa_gguf):+ # /load translates the last -ngl into the manual field before stripping the+ # flag, so the field alone was the wrong thing to price.+ manual = dict(gpu_memory_mode = "manual", gpu_layers = 0, n_ctx = 8192)+ field_only = ri._gguf_memory_breakdown(config, gqa_gguf, **manual)+ overridden = ri._gguf_memory_breakdown(+ config, gqa_gguf, llama_extra_args = ["-ngl", "999"], **manual+ )+ assert field_only.gpu_bytes < overridden.gpu_bytes+ assert overridden.gpu_bytes == overridden.total_bytes++ def test_an_extras_split_mode_decides_the_priced_mode(self, config, gqa_gguf):+ # A --split-mode in the extras last-wins over the toggle at launch, and the+ # compute buffers differ by mode, so pricing the toggle priced a launch that+ # does not happen. Two devices, since one device splits nothing.+ def priced(extras, toggle):+ return ri._gguf_memory_breakdown(+ config,+ gqa_gguf,+ n_ctx = 32768,+ llama_extra_args = extras,+ tensor_parallel = toggle,+ n_devices = 2,+ ).compute_bytes++ layer, tensor = priced(None, False), priced(None, True)+ assert layer != tensor, "fixture must separate the two modes for this to prove anything"+ assert priced(["--split-mode", "tensor"], False) == tensor+ # And the reverse: the extras can turn it off as well as on.+ assert priced(["--split-mode", "layer"], True) == layer++ def test_manual_split_divides_the_cache_with_the_weights(self, config, gqa_gguf):+ # A cache buffer is allocated on model.dev_layer(il) whenever offload_kqv is+ # on (llama-kv-cache.cpp), so a layer left on the CPU keeps its cache in host+ # RAM: --no-kv-offload moves ALL of it, and a partial --gpu-layers moves the+ # rest with the layers. Charging the whole cache to VRAM here contradicted the+ # weights term beside it, and at a long context the cache is the larger of the+ # two, so a small Manual offload read as exceeding a card it fits on.+ b = ri._gguf_memory_breakdown(+ config, gqa_gguf, n_ctx = 8192, gpu_memory_mode = "manual", gpu_layers = 6+ )+ fraction = 6 / float(_GQA_FIELDS["block_count"] + 1)+ assert b.layer_count == _GQA_FIELDS["block_count"]+ assert b.gpu_layers == 6+ assert b.gpu_bytes == (+ int(self.MAIN_BYTES * fraction)+ + self.COMPANION_BYTES+ + int(b.kv_bytes * fraction)+ + b.compute_bytes+ )+ # The cache is still counted in full in the aggregate figure: the host holds+ # the other share, it does not vanish.+ assert b.gpu_bytes < b.total_bytes+ assert b.kv_bytes > int(b.kv_bytes * fraction)++ def test_a_partial_offload_splits_only_the_main_weight(self, config, gqa_gguf):+ # --gpu-layers splits the model, not the companions beside it: a projector+ # and a drafter are placed by their own flags. Scaling the whole files term+ # let --gpu-layers 0 report an empty GPU while both sat in VRAM.+ zero = ri._gguf_memory_breakdown(+ config, gqa_gguf, n_ctx = 8192, gpu_memory_mode = "manual", gpu_layers = 0+ )+ assert zero.gpu_bytes == self.COMPANION_BYTES+ # KV and compute do follow the layers, so nothing else survives ngl 0.+ assert zero.kv_on_gpu is False+ full = ri._gguf_memory_breakdown(+ config,+ gqa_gguf,+ n_ctx = 8192,+ gpu_memory_mode = "manual",+ gpu_layers = _GQA_FIELDS["block_count"] + 1,+ )+ assert full.gpu_bytes == full.total_bytes++ def test_no_mmproj_offload_moves_the_projector_and_only_it(self, config, gqa_gguf, tmp_path):+ # The drafter is the other companion, and it is only ever charged when it+ # lands on the GPU, so this flag must not sweep it off with the projector.+ projector = tmp_path / "mmproj-model.gguf"+ projector.write_bytes(b"\0" * 1024)+ config.gguf_mmproj_file = str(projector)+ expected = self.COMPANION_BYTES - projector.stat().st_size+ pinned = ri._gguf_memory_breakdown(+ config,+ gqa_gguf,+ n_ctx = 8192,+ gpu_memory_mode = "manual",+ gpu_layers = 0,+ llama_extra_args = ["--no-mmproj-offload"],+ )+ # Exactly the projector leaves; the rest of the companion bytes stay.+ assert pinned.gpu_bytes == expected++ def test_no_kv_offload_moves_the_cache_off_the_gpu(self, config, gqa_gguf):+ # At a long context the cache is most of the footprint, so ignoring+ # -nkvo would report VRAM pressure the load does not create.+ b = ri._gguf_memory_breakdown(+ config, gqa_gguf, n_ctx = 8192, llama_extra_args = ["--no-kv-offload"]+ )+ assert b.kv_on_gpu is False+ assert b.kv_bytes > 0 # still counted in the total, just not in VRAM+ assert b.gpu_bytes == b.weights_bytes + b.compute_bytes+ assert b.total_bytes == b.weights_bytes + b.kv_bytes + b.compute_bytes++ def test_unsizable_files_produce_no_breakdown(self, config, gqa_gguf, monkeypatch):+ # None here means the caller default-denies with "unsizable" rather than+ # rendering a total whose largest term is missing.+ monkeypatch.setattr(ri, "_gguf_resident_file_gb", lambda cfg, **kw: None)+ assert ri._gguf_memory_breakdown(config, gqa_gguf, n_ctx = 8192) is None+++# E. _localized_estimate_config+++def _repo_config(**overrides) -> ModelConfig:+ """A config shaped the way ``from_identifier`` leaves a REPOSITORY GGUF.++ ``gguf_file`` is None even when the weights are already in the HF cache --+ that field is filled in by the download path, not by resolution -- which is+ precisely the state that used to send the estimate to the network.+ """+ fields = dict(+ identifier = "org/model-GGUF",+ display_name = "model (Q4_K_M)",+ path = "org/model-GGUF",+ is_local = False,+ is_cached = False,+ is_vision = False,+ is_lora = False,+ is_gguf = True,+ gguf_file = None,+ gguf_hf_repo = "org/model-GGUF",+ gguf_variant = "Q4_K_M",+ )+ fields.update(overrides)+ return ModelConfig(**fields)+++def _local_config(gguf_path: str, **overrides) -> ModelConfig:+ """A config that already names a real file: the local-folder / native-pick shape."""+ fields = dict(+ identifier = str(Path(gguf_path).parent),+ display_name = Path(gguf_path).name,+ path = str(Path(gguf_path).parent),+ is_local = True,+ is_cached = True,+ is_vision = False,+ is_lora = False,+ is_gguf = True,+ gguf_file = gguf_path,+ )+ fields.update(overrides)+ return ModelConfig(**fields)+++class TestLocalizedEstimateConfig:+ """Point a repository-shaped config at the weights already on this disk."""++ def test_config_naming_a_real_file_is_returned_unchanged(self, gqa_gguf):+ # Identity, not equality: a config that already names a file has been+ # through the local-folder or native-pick path, and re-running companion+ # detection on it would scan outside a native grant's directory boundary.+ config = _local_config(gqa_gguf)+ assert ri._localized_estimate_config(config, gqa_gguf) is config++ def test_repo_config_is_copied_never_mutated(self, gqa_gguf):+ # The original is sitting in _estimate_config_cache for the TTL, shared by+ # every later tick of the slider. A half-localized config escaping into+ # that cache is the genuinely nasty version of this bug.+ config = _repo_config()+ localized = ri._localized_estimate_config(config, gqa_gguf)+ assert localized is not config+ assert localized.gguf_file == gqa_gguf+ assert config.gguf_file is None+ # Everything else carries over, so the files arithmetic still knows which+ # repository and variant it is pricing.+ assert localized.identifier == config.identifier+ assert localized.gguf_hf_repo == config.gguf_hf_repo+ assert localized.gguf_variant == config.gguf_variant++ def test_real_sibling_projector_is_detected(self, tmp_path):+ # Real files, real detection: this is the test that proves search_root is+ # wired to the weight's own directory rather than to the repo id.+ weight = _write_gguf(tmp_path, "qwen3", _GQA_FIELDS, name = "model-Q4_K_M.gguf")+ projector = _write_gguf(tmp_path, "clip", {"block_count": 2}, name = "mmproj-model.gguf")+ localized = ri._localized_estimate_config(_repo_config(is_vision = True), weight)+ assert localized.gguf_mmproj_file == projector+ # No mtp-/dspark-/dflash- siblings exist, so those stay unset rather than+ # latching onto the weight or the projector.+ assert localized.gguf_mtp_file is None+ assert localized.gguf_dspark_file is None+ assert localized.gguf_dflash_file is None++ def test_non_vision_config_skips_the_projector(self, tmp_path):+ # A projector sitting in the directory must not be charged to a config the+ # loader will not open one for; that is bytes billed to nobody's load.+ weight = _write_gguf(tmp_path, "qwen3", _GQA_FIELDS, name = "model-Q4_K_M.gguf")+ _write_gguf(tmp_path, "clip", {"block_count": 2}, name = "mmproj-model.gguf")+ localized = ri._localized_estimate_config(_repo_config(is_vision = False), weight)+ assert localized.gguf_mmproj_file is None++ def test_drafter_detectors_receive_the_weight_and_its_directory(self, gqa_gguf, monkeypatch):+ # The three sidecar kinds, stubbed: real dspark/dflash detection wants a+ # family-name match against the target, which is a lot of fixture for what+ # is being checked here -- that each detector is called with the resolved+ # weight and the directory holding it.+ from utils.models import model_config as mc++ seen = {}++ def _stub(name, result):+ def _detect(+ path,+ search_root = None,+ *a,+ **kw,+ ):+ seen[name] = (path, search_root)+ return result++ return _detect++ monkeypatch.setattr(mc, "detect_mtp_file", _stub("mtp", "/tmp/mtp.gguf"))+ monkeypatch.setattr(mc, "detect_dspark_file", _stub("dspark", "/tmp/dspark.gguf"))+ monkeypatch.setattr(mc, "detect_dflash_file", _stub("dflash", "/tmp/dflash.gguf"))++ localized = ri._localized_estimate_config(_repo_config(), gqa_gguf)+ assert localized.gguf_mtp_file == "/tmp/mtp.gguf"+ assert localized.gguf_dspark_file == "/tmp/dspark.gguf"+ assert localized.gguf_dflash_file == "/tmp/dflash.gguf"+ expected = (gqa_gguf, str(Path(gqa_gguf).parent))+ assert seen == {"mtp": expected, "dspark": expected, "dflash": expected}++ def test_a_raising_detector_still_yields_a_usable_config(self, gqa_gguf, monkeypatch):+ # A companion scan that fails leaves the sidecar uncounted, which is a much+ # smaller error than the endpoint returning no estimate at all.+ from utils.models import model_config as mc++ monkeypatch.setattr(mc, "detect_mtp_file", lambda *a, **kw: "/tmp/mtp.gguf")++ def _boom(*a, **kw):+ raise OSError("permission denied walking the snapshot")++ monkeypatch.setattr(mc, "detect_dspark_file", _boom)++ localized = ri._localized_estimate_config(_repo_config(), gqa_gguf)+ assert localized.gguf_file == gqa_gguf # the main weight is still priced+ assert localized.gguf_mtp_file == "/tmp/mtp.gguf" # detected before the raise+ assert localized.gguf_dspark_file is None++ def test_localized_config_takes_the_local_files_arm(self, gqa_gguf, monkeypatch):+ # THE regression. Pre-fix, a repo-shaped config sent _gguf_resident_file_gb+ # down the repository arm, which prices from a paths-info listing and+ # subtracts _remote_gguf_compute_reserve_gb. Making that reserve raise turns+ # "took the remote arm" from a silent numeric difference into a failure.+ def _remote_arm_taken(*a, **kw):+ raise AssertionError("a localized config must not be priced as a repository")++ monkeypatch.setattr(ri, "_remote_gguf_compute_reserve_gb", _remote_arm_taken)+ ctx_term = ri._estimate_gguf_kv_gb(gqa_gguf, 0, None)+ monkeypatch.setattr(ri, "_estimate_gguf_required_gb", lambda cfg, **kw: 5.0 + ctx_term)++ raw = _repo_config()+ localized = ri._localized_estimate_config(raw, gqa_gguf)+ assert ri._gguf_resident_file_gb(localized) == pytest.approx(5.0)++ # And the un-localized original still goes the other way, so the assertion+ # above is about the localization rather than about the patched arm.+ ri._estimate_files_cache.clear()+ with pytest.raises(AssertionError, match = "must not be priced as a repository"):+ ri._gguf_resident_file_gb(raw)+++# F. Token-scoped caches+++class TestTokenFingerprint:+ """Both TTL caches are keyed per token, since a gated repo resolves per token."""++ def test_absent_token_is_empty(self):+ assert ri._estimate_token_fingerprint(None) == ""+ assert ri._estimate_token_fingerprint("") == ""++ def test_stable_and_distinct(self):+ a = ri._estimate_token_fingerprint("hf_aaaaaaaaaaaaaaaaaaaa")+ assert a == ri._estimate_token_fingerprint("hf_aaaaaaaaaaaaaaaaaaaa")+ assert a != ri._estimate_token_fingerprint("hf_bbbbbbbbbbbbbbbbbbbb")++ def test_does_not_carry_the_token(self):+ # The keys live in memory for the TTL and are never logged, but a token is+ # a credential and the literal string has no business in a dict key.+ token = "hf_supersecretvalue123"+ fingerprint = ri._estimate_token_fingerprint(token)+ assert token not in fingerprint+ assert fingerprint and len(fingerprint) == 16++ def test_config_cache_is_not_shared_across_tokens(self, monkeypatch):+ # One subject's gated-repo resolution must not be served to another within+ # the 30s TTL. Distinguishable return values make a shared entry visible.+ calls = []++ def _from_identifier(+ model_id,+ hf_token = None,+ **kw,+ ):+ calls.append(hf_token)+ return SimpleNamespace(identifier = model_id, resolved_with = hf_token)++ monkeypatch.setattr(ri.ModelConfig, "from_identifier", staticmethod(_from_identifier))+ # "org/gated" is in no cache root on this box, so the on-disk gate would refuse+ # it before from_identifier is reached and this test would be asserting the+ # gate rather than the token scoping. Answer the gate; the scoping is the+ # subject here, and it has its own test above.+ monkeypatch.setattr(ri, "_estimate_target_is_on_this_disk", lambda _id: True)++ first = ri._cached_estimate_config("org/gated", "Q4_K_M", "token-a", False)+ second = ri._cached_estimate_config("org/gated", "Q4_K_M", "token-b", False)+ assert first.resolved_with == "token-a"+ assert second.resolved_with == "token-b"+ assert calls == ["token-a", "token-b"]++ # Same token still hits the cache -- the scoping must not defeat it, or the+ # endpoint resolves a config on every tick of the slider.+ assert ri._cached_estimate_config("org/gated", "Q4_K_M", "token-a", False) is first+ assert calls == ["token-a", "token-b"]++ def test_files_cache_is_not_shared_across_tokens(self, gqa_gguf, monkeypatch):+ config = _local_config(gqa_gguf)+ ctx_term = ri._estimate_gguf_kv_gb(gqa_gguf, 0, None)+ by_token = {"token-a": 1.0 + ctx_term, "token-b": 7.0 + ctx_term}+ calls = []++ def _required(cfg, **kw):+ calls.append(kw.get("hf_token"))+ return by_token[kw["hf_token"]]++ monkeypatch.setattr(ri, "_estimate_gguf_required_gb", _required)++ assert ri._gguf_resident_file_gb(config, hf_token = "token-a") == pytest.approx(1.0)+ assert ri._gguf_resident_file_gb(config, hf_token = "token-b") == pytest.approx(7.0)+ assert calls == ["token-a", "token-b"]+ # ...and the first token is still cached rather than re-listed.+ assert ri._gguf_resident_file_gb(config, hf_token = "token-a") == pytest.approx(1.0)+ assert calls == ["token-a", "token-b"]+++# G. The route+++def _estimate(fastapi_request = None, **kwargs):+ """Call the route directly, bypassing the auth dependency."""+ return asyncio.run(+ ri.estimate_memory(+ EstimateMemoryRequest(**kwargs),+ fastapi_request = fastapi_request,+ current_subject = "test",+ )+ )+++def _request_with_slots(slots: int):+ """A stand-in for the FastAPI request carrying the server's slot default."""+ return SimpleNamespace(+ app = SimpleNamespace(+ state = SimpleNamespace(+ llama_parallel_slots = slots,+ )+ )+ )+++class TestEstimateMemoryRoute:+ """The three "cannot size this" answers, and what they must not do first."""++ def test_ollama_manifest_ref_is_refused_before_materializing(self, monkeypatch):+ # Resolving one writes a .gguf link to disk. This endpoint fires on every+ # slider tick, so it must bail on the prefix alone -- no filesystem write,+ # and not even a config resolution.+ def boom(*a, **kw):+ raise AssertionError("estimate-memory must not materialize an Ollama ref")++ monkeypatch.setattr(ri, "materialize_ollama_model_ref", boom)+ monkeypatch.setattr(ri, "acquire_ollama_model_ref", boom)+ monkeypatch.setattr(ri, "_cached_estimate_config", boom)++ resp = _estimate(model_path = "ollama-manifest:sha256-deadbeef")+ assert resp.available is False+ assert resp.reason == "unsupported_source"++ def test_non_gguf_model_is_not_priced(self, monkeypatch):+ # Safetensors / MLX size their memory through a different allocator;+ # quoting the GGUF arithmetic for them is a made-up number in a box.+ monkeypatch.setattr(+ ri,+ "_cached_estimate_config",+ lambda *a, **kw: SimpleNamespace(is_gguf = False, identifier = "org/model"),+ )+ resp = _estimate(model_path = "org/model")+ assert resp.available is False+ assert resp.reason == "not_gguf"++ def test_gguf_not_on_disk_is_not_downloaded(self, monkeypatch):+ # No header to read and no reaching for the network on a slider drag.+ monkeypatch.setattr(+ ri,+ "_cached_estimate_config",+ lambda *a, **kw: SimpleNamespace(is_gguf = True, identifier = "org/model"),+ )+ monkeypatch.setattr(ri, "_local_gguf_main_path", lambda config: None)+ resp = _estimate(model_path = "org/model", gguf_variant = "Q4_K_M")+ assert resp.available is False+ 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.+ def boom(*a, **kw):+ raise AssertionError("must not resolve a model that is not on this disk")++ monkeypatch.setattr(ri.ModelConfig, "from_identifier", staticmethod(boom))+ monkeypatch.setattr(ri, "_estimate_hf_cache_roots", lambda: [Path(os.devnull).parent])+ resp = _estimate(model_path = "org/definitely-not-cached")+ assert resp.available is False+ # not_downloaded, not unsizable: the sentinel keeps the two apart, because+ # "absent" and "resolution failed" are different answers about the same model.+ assert resp.reason == "not_downloaded"++ def test_the_on_disk_check_reads_every_cache_root(self, tmp_path, monkeypatch):+ # The fix's own worst case, and worse than the bug it fixes: a row that+ # vanishes for a model sitting on the disk. Studio scans configured, legacy and+ # default roots, while the snapshot helper the load path uses takes only the+ # configured one, so the check has to iterate all of them.+ primary, secondary = tmp_path / "a", tmp_path / "b"+ for d in (primary, secondary):+ d.mkdir()+ snap = secondary / "models--org--Model-GGUF" / "snapshots" / "rev1"+ snap.mkdir(parents = True)+ (snap / "model.gguf").write_bytes(b"\0" * 8)+ monkeypatch.setattr(ri, "_estimate_hf_cache_roots", lambda: [primary, secondary])+ assert ri._estimate_target_is_on_this_disk("org/Model-GGUF") is True+ # Casing drifts between download and lookup; the helper is case-insensitive.+ assert ri._estimate_target_is_on_this_disk("ORG/model-gguf") is True+ assert ri._estimate_target_is_on_this_disk("org/Other-GGUF") is False++ def test_the_on_disk_check_fails_open(self, monkeypatch, gqa_gguf):+ # An unanswerable question must not become a blanket refusal. A local path is+ # read off disk and never consults the cache at all.+ def boom(*a, **kw):+ raise OSError("cache root unreadable")++ monkeypatch.setattr(ri, "_estimate_hf_cache_roots", boom)+ assert ri._estimate_target_is_on_this_disk("org/anything") is True+ monkeypatch.setattr(ri, "_estimate_hf_cache_roots", lambda: [])+ assert ri._estimate_target_is_on_this_disk("org/anything") is True+ assert ri._estimate_target_is_on_this_disk(gqa_gguf) is True++ def test_the_cache_evictions_are_serialised(self):+ # The route body runs in an asyncio.to_thread worker, so two panel requests are+ # two real threads in the eviction. min() walks the dict through a Python key+ # function the interpreter can switch out of: a concurrent pop makes it raise+ # KeyError, a concurrent insert RuntimeError, and neither is caught between+ # there and the worker, so it surfaces as a 500 on a slider drag.+ import inspect+ for source in (+ inspect.getsource(ri._gguf_resident_file_gb),+ inspect.getsource(ri._cached_estimate_config),+ ):+ evict = source[source.index("_CACHE_MAX") :]+ assert "_ESTIMATE_CACHE_LOCK" in source+ assert source.index("_ESTIMATE_CACHE_LOCK") < source.index("_CACHE_MAX"), (+ "the lock must be taken BEFORE the length check, or the check-then-"+ "insert it protects is still torn"+ )+ assert "min(" in evict++ 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.+ #+ # 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.+ import atexit+ import inspect++ from core.inference.llama_cpp import LlamaCppBackend++ reaps = []+ raw = inspect.getattr_static(LlamaCppBackend, "_kill_orphaned_servers").__func__+ monkeypatch.setattr(+ LlamaCppBackend,+ "_kill_orphaned_servers",+ staticmethod(lambda: reaps.append(1)),+ )+ assert callable(raw)++ config = SimpleNamespace(+ identifier = "local/model",+ gguf_file = gqa_gguf,+ is_gguf = True,+ gguf_mmproj_file = None,+ gguf_mtp_file = None,+ gguf_dspark_file = None,+ gguf_dflash_file = None,+ )+ monkeypatch.setattr(ri, "_cached_estimate_config", lambda *a, **kw: config)+ monkeypatch.setattr(ri, "_gguf_resident_file_gb", lambda cfg, **kw: 2.0)++ before = atexit._ncallbacks()+ for i in range(5):+ ri._estimate_files_cache.clear()+ ri._estimate_config_cache.clear()+ assert _estimate(model_path = gqa_gguf, n_ctx = 4096 + i).available is True+ assert reaps == [], f"the estimate reaped orphaned servers {len(reaps)}x"+ assert atexit._ncallbacks() == before, (+ f"the estimate leaked {atexit._ncallbacks() - before} atexit handlers over "+ f"five requests; each one retains a whole backend"+ )++ def test_the_inert_probe_mode_is_opt_in(self):+ # Default True, so every existing caller -- above all the real backend that+ # owns the llama-server child -- keeps exactly the behaviour it has today.+ import inspect++ from core.inference.llama_cpp import LlamaCppBackend++ sig = inspect.signature(LlamaCppBackend.__init__)+ param = sig.parameters["manages_processes"]+ assert param.default is True+ assert param.kind is inspect.Parameter.KEYWORD_ONLY++ def test_expert_offload_from_the_extras_is_declared_unmodelled(self, monkeypatch, gqa_gguf):+ # --n-cpu-moe moves individual expert tensors, which the layer fraction+ # cannot express, so the row has to say so. /load strips those flags only on+ # the Manual branch, where the field owns them; anywhere else they reach the+ # child and the estimate reads high without qualification.+ config = SimpleNamespace(identifier = "local/model", gguf_file = gqa_gguf, is_gguf = True)+ monkeypatch.setattr(ri, "_cached_estimate_config", lambda *a, **kw: config)+ monkeypatch.setattr(ri, "_gguf_resident_file_gb", lambda cfg, **kw: 2.0)++ def flagged(**kw):+ return _estimate(model_path = gqa_gguf, n_ctx = 8192, **kw).moe_offload_unmodelled++ assert flagged(gpu_memory_mode = "auto", llama_extra_args = ["--n-cpu-moe", "8"]) is True+ assert flagged(gpu_memory_mode = "auto", llama_extra_args = ["-cmoe"]) is True+ assert flagged(gpu_memory_mode = "auto", llama_extra_args = ["-ot", "exps=CPU"]) is True+ # Zero places nothing, and an unrelated flag is not an offload.+ assert flagged(gpu_memory_mode = "auto", llama_extra_args = ["-ncmoe", "0"]) is False+ assert flagged(gpu_memory_mode = "auto", llama_extra_args = ["--top-k", "40"]) is False+ # Manual strips them, so only its own field speaks there.+ assert flagged(gpu_memory_mode = "manual", llama_extra_args = ["-ncmoe", "8"]) is False+ assert flagged(gpu_memory_mode = "manual", n_cpu_moe = 8) is True++ def test_the_device_count_uses_the_effective_split_mode(self, monkeypatch, gqa_gguf):+ # A layer split across pinned cards is counted differently from a tensor+ # split, so the device count has to be asked the same question the pricing+ # is: the toggle alone is not the mode the launch runs.+ config = SimpleNamespace(identifier = "local/model", gguf_file = gqa_gguf, is_gguf = True)+ monkeypatch.setattr(ri, "_cached_estimate_config", lambda *a, **kw: config)+ monkeypatch.setattr(ri, "_gguf_resident_file_gb", lambda cfg, **kw: 2.0)+ asked: list[bool] = []++ def _count(+ gpu_ids,+ _unused,+ *,+ tensor_parallel = False,+ ):+ asked.append(tensor_parallel)+ return 2++ monkeypatch.setattr(ri, "_guard_device_count", _count)+ _estimate(+ model_path = gqa_gguf,+ n_ctx = 8192,+ tensor_parallel = False,+ llama_extra_args = ["--split-mode", "tensor"],+ selected_gpu_ids = [0, 1],+ )+ assert asked == [True]+ # And one card cannot take a tensor split, whatever the extras ask for, so+ # the count is asked the question load_model will answer.+ _estimate(+ model_path = gqa_gguf,+ n_ctx = 8192,+ tensor_parallel = True,+ llama_extra_args = ["--split-mode", "tensor"],+ selected_gpu_ids = [0],+ )+ assert asked == [True, False]++ def test_unresolvable_config_is_unsizable(self, monkeypatch):+ monkeypatch.setattr(ri, "_cached_estimate_config", lambda *a, **kw: None)+ resp = _estimate(model_path = "org/does-not-exist")+ assert resp.available is False+ assert resp.reason == "unsizable"++ def test_local_gguf_is_priced_end_to_end(self, monkeypatch, gqa_gguf):+ # The success path, with only the two network-capable steps replaced:+ # config resolution and the repository-listing half of the files term.+ config = SimpleNamespace(identifier = "local/model", gguf_file = gqa_gguf, is_gguf = True)+ monkeypatch.setattr(ri, "_cached_estimate_config", lambda *a, **kw: config)+ monkeypatch.setattr(ri, "_gguf_resident_file_gb", lambda cfg, **kw: 2.0)++ resp = _estimate(+ model_path = gqa_gguf,+ n_ctx = 8192,+ cache_type_kv = "q8_0",+ gpu_memory_mode = "manual",+ gpu_layers = 6,+ n_cpu_moe = 2,+ )+ assert resp.available is True+ assert resp.reason is None+ assert resp.weights_bytes == int(round(2.0 * _GIB))+ assert resp.total_bytes == resp.weights_bytes + resp.kv_bytes + resp.compute_bytes+ assert resp.kv_estimable is True+ assert resp.n_ctx == 8192+ assert resp.cache_type_kv == "q8_0"+ assert resp.layer_count == _GQA_FIELDS["block_count"]+ assert resp.gpu_layers == 6+ # --n-cpu-moe moves individual expert tensors, which no layer-count+ # arithmetic models; the panel is told to say so rather than guess.+ assert resp.moe_offload_unmodelled is True++ def test_cached_repo_is_priced_from_disk_not_from_a_listing(self, monkeypatch, gqa_gguf):+ # The glue for the localization: a repo-shaped config whose weights ARE on+ # this disk must be priced locally. _remote_gguf_compute_reserve_gb only+ # runs on the repository arm, and list_gguf_variants is the paths-info call+ # that arm makes -- both raise here, so either one being reached fails.+ def _network(*a, **kw):+ raise AssertionError("estimate-memory must not price a cached repo remotely")++ monkeypatch.setattr(ri, "_cached_estimate_config", lambda *a, **kw: _repo_config())+ monkeypatch.setattr(ri, "_local_gguf_main_path", lambda config: gqa_gguf)+ monkeypatch.setattr(ri, "_remote_gguf_compute_reserve_gb", _network)++ resp = _estimate(model_path = "org/model-GGUF", gguf_variant = "Q4_K_M", n_ctx = 4096)+ assert resp.available is True+ # Priced off the real header on disk, which is the whole point of localizing.+ assert resp.kv_estimable is True+ assert resp.layer_count == _GQA_FIELDS["block_count"]+ assert resp.weights_bytes > 0+ assert resp.n_ctx == 4096+++class TestParallelSlotResolution:+ """Blank Parallel Slots means the server default, not one.++ /load resolves the field through ``_resolve_parallel_slots`` and normally+ inherits ``app.state.llama_parallel_slots`` (four in a standard launch). Pricing+ one slot for the default UI state underestimated both the KV cache and the+ slot-scaled compute buffers, which is the configuration most people load.+ """++ @pytest.fixture(autouse = True)+ def _local_model(self, monkeypatch, gqa_gguf):+ config = SimpleNamespace(+ identifier = "local/model",+ gguf_file = gqa_gguf,+ is_gguf = True,+ gguf_mmproj_file = None,+ )+ monkeypatch.setattr(ri, "_cached_estimate_config", lambda *a, **kw: config)+ monkeypatch.setattr(ri, "_local_gguf_main_path", lambda cfg: gqa_gguf)+ monkeypatch.setattr(ri, "_gguf_resident_file_gb", lambda cfg, **kw: 1.0)++ def test_omitted_slots_inherit_the_server_default(self):+ resp = _estimate(+ model_path = "local/model",+ n_ctx = 8192,+ fastapi_request = _request_with_slots(4),+ )+ assert resp.n_parallel == 4++ def test_an_explicit_count_still_wins(self):+ resp = _estimate(+ model_path = "local/model",+ n_ctx = 8192,+ n_parallel = 1,+ fastapi_request = _request_with_slots(4),+ )+ assert resp.n_parallel == 1++ def test_more_slots_cost_more(self):+ one = _estimate(+ model_path = "local/model",+ n_ctx = 8192,+ fastapi_request = _request_with_slots(1),+ )+ four = _estimate(+ model_path = "local/model",+ n_ctx = 8192,+ fastapi_request = _request_with_slots(4),+ )+ # The compute buffer takes an output buffer per extra slot, so it always+ # grows. The cache only does on architectures whose slots get their own+ # cells: under unified KV a plain GQA model shares one set, which is why+ # this asserts >= there rather than pretending otherwise.+ assert four.compute_bytes > one.compute_bytes+ assert four.kv_bytes >= one.kv_bytes+ assert four.total_bytes > one.total_bytes++ def test_a_missing_app_state_falls_back_to_one(self):+ # No FastAPI request at all (the shape older test doubles pass) must not+ # raise; it just loses the default, as _resolve_parallel_slots specifies.+ resp = _estimate(model_path = "local/model", n_ctx = 8192)+ assert resp.n_parallel == 1+++class TestNativeLeaseOperation:+ """The route must verify leases under the operation the client can mint.++ Leases are signed for one operation and ``_validate_payload`` compares it+ exactly. "estimate-memory" is not a mintable ``NativePathOperation``, so+ verifying under that name rejected every picked or drag-dropped GGUF and the+ row never appeared for them.+ """++ def test_the_route_verifies_the_validate_model_grant(self, monkeypatch):+ seen = {}++ def _resolve(+ request,+ *,+ operation,+ resolved_ollama_path = None,+ ):+ seen["operation"] = operation+ return ("/tmp/dropped.gguf", "dropped.gguf", True)++ monkeypatch.setattr(ri, "_resolve_model_identifier_for_request", _resolve)+ monkeypatch.setattr(ri, "_cached_estimate_config", lambda *a, **kw: None)+ _estimate(model_path = "dropped.gguf", native_path_lease = "signed")+ assert seen["operation"] == "validate-model"++ def test_the_operation_is_one_the_client_can_mint(self):+ # Guards the pairing rather than the string: the frontend mints through+ # consumeNativePathToken(token, "validate-model"), and this is the list+ # that call is typed against.+ types_ts = (+ Path(__file__).resolve().parents[2] / "frontend/src/features/native-intents/types.ts"+ ).read_text(encoding = "utf-8")+ assert '"validate-model"' in types_ts+ assert "estimate-memory" not in types_ts+++from core.inference.llama_cpp import ( # noqa: E402+ _extra_args_draft_offloaded_to_cpu as _draft_on_cpu,+)+++class TestDrafterAccounting:+ """A separate drafter costs more than its file.++ The loader budgets its KV cache and rollback state through+ ``_estimate_mtp_overhead_bytes``, which grows with context exactly as the target's+ cache does. Charging only the file made speculation look nearly free.+ """++ @pytest.fixture+ def config(self, gqa_gguf, tmp_path):+ drafter = tmp_path / "mtp-model.gguf"+ drafter.write_bytes(+ _make_gguf_bytes(+ "qwen3",+ {+ "general.architecture": "qwen3",+ **{f"qwen3.{k}": v for k, v in _GQA_FIELDS.items()},+ },+ )+ )+ return SimpleNamespace(+ identifier = "local/model",+ gguf_file = gqa_gguf,+ is_gguf = True,+ gguf_mmproj_file = None,+ gguf_mtp_file = str(drafter),+ gguf_dspark_file = None,+ gguf_dflash_file = None,+ )++ def test_the_charged_drafter_is_found_by_the_bytes_it_added(self, config, tmp_path):+ size = os.path.getsize(config.gguf_mtp_file)+ # The kind rides along with the path: it decides which target-side terms the+ # reserve carries, and deriving it separately could name another mode.+ assert ri._charged_drafter_path(config, size) == (config.gguf_mtp_file, "mtp")+ # A figure matching no candidate must not pick one at random.+ assert ri._charged_drafter_path(config, size + 1) is None+ assert ri._charged_drafter_path(config, 0) is None++ def test_drafter_runtime_grows_with_context(self, config, gqa_gguf, monkeypatch):+ drafter_bytes = os.path.getsize(config.gguf_mtp_file)+ main_gb = 1.0++ # Mimic the files term: the drafter is charged unless the probe forces it off.+ def _files(+ cfg,+ *,+ llama_extra_args = None,+ **kw,+ ):+ pinned = _draft_on_cpu(list(llama_extra_args or ()))+ return main_gb + (0.0 if pinned else drafter_bytes / 1024**3)++ monkeypatch.setattr(ri, "_gguf_resident_file_gb", _files)+ small = ri._gguf_memory_breakdown(config, gqa_gguf, n_ctx = 2048)+ large = ri._gguf_memory_breakdown(config, gqa_gguf, n_ctx = 32768)+ # Weights are the same files at both contexts; only the drafter's cache moved.+ assert small.weights_bytes == large.weights_bytes+ drafter_runtime_small = small.total_bytes - small.weights_bytes - small.kv_bytes+ drafter_runtime_large = large.total_bytes - large.weights_bytes - large.kv_bytes+ assert drafter_runtime_large > drafter_runtime_small++ def test_a_cpu_pinned_drafter_stays_in_the_total(self, config, gqa_gguf, monkeypatch):+ drafter_bytes = os.path.getsize(config.gguf_mtp_file)+ main_gb = 1.0++ def _files(+ cfg,+ *,+ llama_extra_args = None,+ **kw,+ ):+ pinned = _draft_on_cpu(list(llama_extra_args or ()))+ return main_gb + (0.0 if pinned else drafter_bytes / 1024**3)++ monkeypatch.setattr(ri, "_gguf_resident_file_gb", _files)+ on_gpu = ri._gguf_memory_breakdown(config, gqa_gguf, n_ctx = 8192)+ on_cpu = ri._gguf_memory_breakdown(+ config, gqa_gguf, n_ctx = 8192, llama_extra_args = ["--spec-draft-ngl", "0"]+ )+ # _estimate_gguf_required_gb drops a CPU-pinned drafter because it is a VRAM+ # admission figure. This panel reports host RAM too, so the bytes stay in the+ # total and leave only the GPU column.+ assert on_cpu.total_bytes == on_gpu.total_bytes+ assert on_cpu.weights_bytes == on_gpu.weights_bytes+ assert on_cpu.gpu_bytes < on_gpu.gpu_bytes++ def test_the_drafter_runtime_reports_its_own_gpu_share(self, config, gqa_gguf, monkeypatch):+ # The panel used to label this line from kv_on_gpu, the TARGET cache's+ # placement, which is set by a different flag. Wrong in both directions: silent+ # about a genuinely host-resident draft cache, and claiming host RAM for one+ # this same call had just charged to gpu_bytes. So the share is reported.+ drafter_bytes = os.path.getsize(config.gguf_mtp_file)++ def _files(+ cfg,+ *,+ llama_extra_args = None,+ **kw,+ ):+ pinned = _draft_on_cpu(list(llama_extra_args or ()))+ return 1.0 + (0.0 if pinned else drafter_bytes / 1024**3)++ monkeypatch.setattr(ri, "_gguf_resident_file_gb", _files)+ on_gpu = ri._gguf_memory_breakdown(config, gqa_gguf, n_ctx = 8192)+ assert on_gpu.drafter_runtime_bytes > 0+ # Default placement: all of it, so the row says nothing rather than guessing.+ assert on_gpu.drafter_runtime_gpu_bytes == on_gpu.drafter_runtime_bytes++ on_cpu = ri._gguf_memory_breakdown(+ config, gqa_gguf, n_ctx = 8192, llama_extra_args = ["--spec-draft-ngl", "0"]+ )+ assert on_cpu.drafter_runtime_gpu_bytes == 0++ # --no-kv-offload moves the TARGET cache and leaves the drafter alone. A+ # boolean read off kv_on_gpu would call the whole term host-resident here,+ # while gpu_bytes still carries the draft cache.+ nkvo = ri._gguf_memory_breakdown(+ config, gqa_gguf, n_ctx = 8192, llama_extra_args = ["--no-kv-offload"]+ )+ assert nkvo.kv_on_gpu is False+ assert nkvo.drafter_runtime_gpu_bytes > 0++ # Whatever the placement, the share is never more than the term it is a share+ # of, and never negative.+ for b in (on_gpu, on_cpu, nkvo):+ assert 0 <= b.drafter_runtime_gpu_bytes <= b.drafter_runtime_bytes+++class TestDeviceCount:+ """A pinned layer split pays per-device overhead, not just tensor mode."""++ def test_a_pinned_layer_split_counts_its_cards(self):+ # _gguf_runtime_bytes adds pipeline overhead per extra device and replicates+ # the context-linear compute term, so forcing 1 here underestimated both.+ assert ri._guard_device_count([0, 1], None, tensor_parallel = False) == 2+ assert ri._guard_device_count([0, 1, 2], None, tensor_parallel = False) == 3+ # Automatic placement lands on one card until the fit says otherwise.+ assert ri._guard_device_count(None, None, tensor_parallel = False) == 1+++# A hybrid-Mamba target: the recurrent state the verification rollback copies, and the+# only shape where the draft depth changes the number the panel prints.+_HYBRID_FIELDS = {+ **_GQA_FIELDS,+ "block_count": 24,+ "full_attention_interval": 4,+ "ssm.inner_size": 4096,+ "ssm.state_size": 128,+ "ssm.group_count": 8,+ "ssm.conv_kernel": 4,+}+++class TestBlankDraftDepth:+ """Draft Tokens left blank is the launcher's default, not zero.++ ``_build_speculative_flags`` emits its own depth when the field is unset, and+ ``_estimate_mtp_overhead_bytes`` scales the Hybrid-Mamba rollback state by it, so+ pricing zero dropped that allocation from both the total and the GPU figure.+ """++ @pytest.fixture+ def hybrid(self, tmp_path) -> str:+ return _write_gguf(tmp_path, "qwen3next", _HYBRID_FIELDS, name = "hybrid.gguf")++ @pytest.fixture+ def config(self, hybrid, tmp_path):+ drafter = tmp_path / "mtp-hybrid.gguf"+ drafter.write_bytes(+ _make_gguf_bytes(+ "qwen3",+ {+ "general.architecture": "qwen3",+ **{f"qwen3.{k}": v for k, v in _GQA_FIELDS.items()},+ },+ )+ )+ return SimpleNamespace(+ identifier = "local/hybrid",+ gguf_file = hybrid,+ is_gguf = True,+ gguf_mmproj_file = None,+ gguf_mtp_file = str(drafter),+ gguf_dspark_file = None,+ gguf_dflash_file = None,+ )++ @pytest.fixture(autouse = True)+ def _fixed_files(self, config, monkeypatch):+ drafter_bytes = os.path.getsize(config.gguf_mtp_file)++ def _files(+ cfg,+ *,+ llama_extra_args = None,+ **kw,+ ):+ pinned = _draft_on_cpu(list(llama_extra_args or ()))+ return 1.0 + (0.0 if pinned else drafter_bytes / 1024**3)++ monkeypatch.setattr(ri, "_gguf_resident_file_gb", _files)++ def _priced(self, config, hybrid, **kw):+ return ri._gguf_memory_breakdown(config, hybrid, n_ctx = 8192, n_parallel = 4, **kw)++ def test_blank_prices_the_launch_default_not_zero(self, config, hybrid):+ # THE regression: the UI sends null for a blank field, which used to reach+ # _estimate_mtp_overhead_bytes as a depth of 0 and cost the rollback copies.+ zero = self._priced(config, hybrid, spec_draft_n_max = 0)+ one = self._priced(config, hybrid, spec_draft_n_max = 1)+ blank = self._priced(config, hybrid, spec_draft_n_max = None)+ per_copy = one.total_bytes - zero.total_bytes+ assert per_copy > 0, "fixture is not hybrid-Mamba; the test would prove nothing"+ assert blank.total_bytes > zero.total_bytes+ # 2 on a GPU box, 3 without: the two platform defaults _build_speculative_flags+ # emits. Not pinned to one, so this passes on a runner with or without a card.+ assert (blank.total_bytes - zero.total_bytes) // per_copy in (2, 3)+ # The drafter sits on the GPU here, so the fit verdict moves with it too.+ assert blank.gpu_bytes > zero.gpu_bytes++ def test_an_explicit_depth_still_wins(self, config, hybrid):+ zero = self._priced(config, hybrid, spec_draft_n_max = 0)+ one = self._priced(config, hybrid, spec_draft_n_max = 1)+ per_copy = one.total_bytes - zero.total_bytes+ five = self._priced(config, hybrid, spec_draft_n_max = 5)+ assert five.total_bytes - zero.total_bytes == 5 * per_copy++ def test_an_extras_depth_wins_over_a_blank_field(self, config, hybrid):+ # Last-wins at launch, so the extras flag is what the child really drafts at.+ zero = self._priced(config, hybrid, spec_draft_n_max = 0)+ one = self._priced(config, hybrid, spec_draft_n_max = 1)+ per_copy = one.total_bytes - zero.total_bytes+ pinned = self._priced(+ config,+ hybrid,+ spec_draft_n_max = None,+ llama_extra_args = ["--spec-draft-n-max", "5"],+ )+ assert pinned.total_bytes - zero.total_bytes == 5 * per_copy++ def test_depth_resolution_follows_the_launch_precedence(self, config):+ drafter = config.gguf_mtp_file+ assert ri._estimate_draft_n_max(config, drafter, requested = 7, extras = []) == 7+ # Extras beat the field, and an explicit zero is honoured as "draft nothing".+ assert (+ ri._estimate_draft_n_max(config, drafter, requested = 7, extras = ["--draft-max", "4"]) == 4+ )+ assert ri._estimate_draft_n_max(config, drafter, requested = 0, extras = []) == 0+ assert ri._estimate_draft_n_max(config, drafter, requested = None, extras = []) in (2, 3)+ # DSpark launches at 3 regardless of the card, so it is priced at 3.+ dspark = SimpleNamespace(gguf_dspark_file = "/tmp/dspark-model.gguf")+ assert (+ ri._estimate_draft_n_max(dspark, "/tmp/dspark-model.gguf", requested = None, extras = [])+ == 3+ )+++class TestQuantSubdirCompanions:+ """A cached repo that files each quant under its own directory.++ ``snapshot/UD-Q4_K_XL/model-00001-of-00002.gguf`` with ``mmproj-*.gguf`` and the+ drafter at ``snapshot/`` is the standard Hugging Face layout for any quant over the+ per-file limit. Passing the weight's own parent as ``search_root`` gave the+ detectors nothing to walk up to, so the projector went uncounted.+ """++ def test_a_projector_at_the_snapshot_root_is_found(self, tmp_path):+ quant_dir = tmp_path / "UD-Q4_K_XL"+ quant_dir.mkdir()+ weight = _write_gguf(+ quant_dir, "qwen3", _GQA_FIELDS, name = "model-UD-Q4_K_XL-00001-of-00002.gguf"+ )+ projector = _write_gguf(tmp_path, "clip", {"block_count": 2}, name = "mmproj-F16.gguf")+ localized = ri._localized_estimate_config(_repo_config(is_vision = True), weight)+ assert localized.gguf_mmproj_file == projector++ def test_a_drafter_at_the_snapshot_root_is_found(self, tmp_path):+ quant_dir = tmp_path / "Q4_K_M"+ quant_dir.mkdir()+ weight = _write_gguf(quant_dir, "qwen3", _GQA_FIELDS, name = "model-Q4_K_M.gguf")+ drafter = _write_gguf(tmp_path, "qwen3", _GQA_FIELDS, name = "mtp-model.gguf")+ localized = ri._localized_estimate_config(_repo_config(), weight)+ assert localized.gguf_mtp_file == drafter++ def test_a_flat_layout_still_scans_only_the_weights_directory(self, tmp_path):+ # The widened root must not reach a sibling model's projector: the quant check+ # is what keeps a non-quant directory name from being walked out of.+ model_dir = tmp_path / "some-model"+ model_dir.mkdir()+ weight = _write_gguf(model_dir, "qwen3", _GQA_FIELDS, name = "model-Q4_K_M.gguf")+ _write_gguf(tmp_path, "clip", {"block_count": 2}, name = "mmproj-F16.gguf")+ localized = ri._localized_estimate_config(_repo_config(is_vision = True), weight)+ assert localized.gguf_mmproj_file is None+++class TestDrafterEdgeCases:+ """The narrow drafter paths, each of which produced a wrong answer or a 500."""++ @pytest.fixture+ def bare_config(self, gqa_gguf):+ """A model shipping no sidecar of any kind."""+ return SimpleNamespace(+ identifier = "local/model",+ gguf_file = gqa_gguf,+ is_gguf = True,+ gguf_mmproj_file = None,+ gguf_mtp_file = None,+ gguf_dspark_file = None,+ gguf_dflash_file = None,+ )++ def test_a_cpu_pin_without_a_drafter_does_not_crash(self, bare_config, gqa_gguf, monkeypatch):+ # Only the else branch bound gpu_drafter_bytes, so a CPU pin on a model with+ # nothing to pin raised UnboundLocalError and answered 500 for an ordinary load.+ monkeypatch.setattr(ri, "_gguf_resident_file_gb", lambda cfg, **kw: 1.0)+ breakdown = ri._gguf_memory_breakdown(+ bare_config, gqa_gguf, n_ctx = 4096, llama_extra_args = ["--spec-draft-ngl", "0"]+ )+ assert breakdown is not None+ assert breakdown.drafter_runtime_bytes == 0+ assert breakdown.total_bytes > 0++ def test_a_custom_model_draft_is_carried_into_runtime_sizing(+ self, bare_config, gqa_gguf, tmp_path+ ):+ # The launch opens whatever --model-draft names, which need not be one of the+ # discovered sidecars; matching only those dropped its cache entirely.+ custom = tmp_path / "my-drafter.gguf"+ custom.write_bytes(Path(gqa_gguf).read_bytes())+ found = ri._charged_drafter_path(bare_config, 4096, extras = ["--model-draft", str(custom)])+ assert found == (str(custom), "extras")+ # A remote repo is not a local file, so it stays unsized rather than guessed.+ assert (+ ri._charged_drafter_path(+ bare_config, 4096, extras = ["--spec-draft-hf", "org/drafter-GGUF"]+ )+ is None+ )+ # And nothing is resolved when no drafter was charged in the first place.+ assert (+ ri._charged_drafter_path(bare_config, 0, extras = ["--model-draft", str(custom)]) is None+ )++ def test_draft_cache_overrides_come_from_the_extras(self):+ # K and V are independent at launch, so passing the panel field for both+ # priced a cache the load will not allocate.+ from core.inference.llama_cpp import _extra_args_draft_cache_types+ assert _extra_args_draft_cache_types(["--cache-type-k-draft", "f32"]) == ("f32", None)+ assert _extra_args_draft_cache_types(["--cache-type-v-draft", "q8_0"]) == (None, "q8_0")+ # Asserted on the source before, which meant it could only ever restate the+ # implementation. The precedence itself is checked by behaviour below, where a+ # wrong order changes the number instead of the spelling.+++class TestSpeculativeModeTerms:+ """A separate drafter is not an MTP head, and the two are not placed together.++ ``_estimate_mtp_overhead_bytes`` defaults to charging both target-side terms+ because an unsure caller should over-reserve. The loader does not stay unsure: it+ derives them from the engaged mode. Defaulting here charged DSpark and DFlash a+ second full copy of an MLA target's KV, which the mode never allocates.+ """++ @pytest.fixture+ def mla(self, tmp_path) -> str:+ # kv_lora_rank is what makes the duplicated target context real.+ return _write_gguf(+ tmp_path,+ "deepseek2",+ {**_GQA_FIELDS, "attention.kv_lora_rank": 512},+ name = "mla.gguf",+ )++ def _config(self, mla, tmp_path, kind: str):+ drafter = tmp_path / f"{kind}-drafter.gguf"+ drafter.write_bytes(Path(mla).read_bytes())+ return SimpleNamespace(+ identifier = "local/mla",+ gguf_file = mla,+ is_gguf = True,+ gguf_mmproj_file = None,+ gguf_mtp_file = str(drafter) if kind == "mtp" else None,+ gguf_dspark_file = str(drafter) if kind == "dspark" else None,+ gguf_dflash_file = None,+ )++ @pytest.fixture+ def priced_files(self, mla, tmp_path, monkeypatch):+ """The files term as the real one behaves: drafter charged unless pinned."""+ drafter_bytes = os.path.getsize(mla)++ def _files(+ cfg,+ *,+ llama_extra_args = None,+ **kw,+ ):+ pinned = _draft_on_cpu(list(llama_extra_args or ()))+ return 1.0 + (0.0 if pinned else drafter_bytes / 1024**3)++ monkeypatch.setattr(ri, "_gguf_resident_file_gb", _files)++ def _target_ctx_copy(self, mla, n_ctx: int) -> int:+ probe = ri.LlamaCppBackend()+ probe._read_gguf_metadata(mla)+ return probe._estimate_kv_cache_bytes(n_ctx, "f16")++ def test_a_dspark_drafter_is_not_charged_the_targets_context(self, mla, tmp_path, priced_files):+ ctx = 131072+ mtp = ri._gguf_memory_breakdown(self._config(mla, tmp_path, "mtp"), mla, n_ctx = ctx)+ dspark = ri._gguf_memory_breakdown(self._config(mla, tmp_path, "dspark"), mla, n_ctx = ctx)+ # DSpark loads its own drafter with its own cache and keeps no copy of the+ # target's, so the difference is exactly that copy, priced at f16.+ assert mtp.drafter_runtime_bytes - dspark.drafter_runtime_bytes == self._target_ctx_copy(+ mla, ctx+ )+ assert dspark.total_bytes < mtp.total_bytes++ def test_a_gpu_drafter_is_charged_when_the_target_keeps_no_layers(+ self, mla, tmp_path, priced_files+ ):+ # A separate drafter does not inherit --gpu-layers: llama.cpp overwrites it+ # with the draft placement, whose default is auto. At --gpu-layers 0 the+ # drafter is still on the GPU and still holds its cache there.+ config = self._config(mla, tmp_path, "dspark")+ manual = dict(gpu_memory_mode = "manual", gpu_layers = 0, n_ctx = 131072)+ on_gpu = ri._gguf_memory_breakdown(config, mla, **manual)+ pinned = ri._gguf_memory_breakdown(+ config, mla, llama_extra_args = ["--spec-draft-ngl", "0"], **manual+ )+ assert on_gpu.drafter_runtime_bytes > 0+ # The drafter's file and its cache both leave the GPU when it is pinned, and+ # DSpark on this target keeps nothing in the target's context.+ assert (+ on_gpu.gpu_bytes - pinned.gpu_bytes+ == on_gpu.drafter_runtime_bytes + os.path.getsize(mla)+ )++ def test_the_target_side_of_the_reserve_stays_with_the_target(+ self, mla, tmp_path, priced_files+ ):+ ctx = 131072+ config = self._config(mla, tmp_path, "mtp")+ copy_bytes = self._target_ctx_copy(mla, ctx)+ # Target on the CPU, drafter on the GPU: the draft cache is charged, the+ # duplicated target context is not.+ manual = dict(gpu_memory_mode = "manual", gpu_layers = 0, n_ctx = ctx)+ no_layers = ri._gguf_memory_breakdown(config, mla, **manual)+ no_layers_pinned = ri._gguf_memory_breakdown(+ config, mla, llama_extra_args = ["--spec-draft-ngl", "0"], **manual+ )+ assert copy_bytes > 0+ # What pinning the drafter takes off the GPU is its own cache and file, never+ # the target's copy, which was not on the GPU here in the first place.+ assert no_layers.gpu_bytes - no_layers_pinned.gpu_bytes == (+ no_layers.drafter_runtime_bytes - copy_bytes + os.path.getsize(mla)+ )+ # The mirror image: drafter pinned to the CPU, target fully offloaded. The+ # copy lives in the target's context, so pinning does not move it.+ pinned = ri._gguf_memory_breakdown(+ config, mla, n_ctx = ctx, llama_extra_args = ["--spec-draft-ngl", "0"]+ )+ unpinned = ri._gguf_memory_breakdown(config, mla, n_ctx = ctx)+ assert unpinned.gpu_bytes - pinned.gpu_bytes == (+ unpinned.drafter_runtime_bytes - copy_bytes + os.path.getsize(mla)+ )+ # And the copy is still charged with the drafter pinned away, which is what+ # the loader reserves for the same launch.+ assert pinned.gpu_bytes - no_layers_pinned.gpu_bytes > copy_bytes++ def test_extras_owning_the_spec_block_price_the_builds_depth(self, mla):+ # _build_speculative_flags returns without emitting a depth once the extras+ # name --spec-type, so neither the panel field nor Studio's 2/3 platform+ # default reaches the child: it drafts at the build's own number.+ config = SimpleNamespace(gguf_dspark_file = None)+ owned = ["--spec-type", "draft-mtp"]+ assert ri._estimate_draft_n_max(config, mla, requested = None, extras = owned) == 16+ assert ri._estimate_draft_n_max(config, mla, requested = 2, extras = owned) == 16+ # An explicit depth still wins, and without --spec-type the field does.+ assert (+ ri._estimate_draft_n_max(+ config, mla, requested = 2, extras = [*owned, "--spec-draft-n-max", "5"]+ )+ == 5+ )+ assert ri._estimate_draft_n_max(config, mla, requested = 2, extras = []) == 2++ def test_each_mode_charges_only_the_terms_it_allocates(self):+ # Studio's own sidecars: only MTP duplicates the target context, and all three+ # pay rollback. Extras that name a type own the answer, and a bare+ # --model-draft is draft-simple, which allocates neither.+ assert ri._estimate_spec_mode_terms("mtp", []) == (True, True)+ assert ri._estimate_spec_mode_terms("dspark", []) == (False, True)+ assert ri._estimate_spec_mode_terms("dflash", []) == (False, True)+ # A bare --model-draft on a target Studio does not recognise as MTP really is+ # draft-simple, llama.cpp's default, and allocates neither.+ assert ri._estimate_spec_mode_terms("extras", []) == (False, False)+ # But on a target Studio DOES recognise, it still emits --spec-type draft-mtp+ # and the extras path merely last-wins as the drafter, so the duplicated MLA+ # context and the rollback state are both really allocated.+ assert ri._estimate_spec_mode_terms("extras", [], studio_emits_mtp = True) == (True, True)+ # A --spec-type in the extras still owns the answer outright either way.+ assert ri._estimate_spec_mode_terms(+ "extras", ["--spec-type", "draft-simple"], studio_emits_mtp = True+ ) == (False, False)+ assert ri._estimate_spec_mode_terms("extras", ["--spec-type", "draft-simple"]) == (+ False,+ False,+ )+ assert ri._estimate_spec_mode_terms("extras", ["--spec-type", "draft-mtp"]) == (True, True)+ assert ri._estimate_spec_mode_terms("extras", ["--spec-type", "draft-eagle3"]) == (+ False,+ True,+ )+++class TestLaunchShapedPricing:+ """Three places the panel priced a launch the loader would not perform.++ Each is the same shape: a setting resolved one way in ``load_model`` and another+ way here, where the difference is large enough to flip the verdict.+ """++ @pytest.fixture+ def swa(self, tmp_path) -> str:+ # Sliding-window attention, so --swa-full has something to change: without it+ # the cache holds the window, with it the whole context.+ return _write_gguf(+ tmp_path,+ "gemma3",+ {**_GQA_FIELDS, "attention.sliding_window": 4096, "context_length": 262144},+ name = "swa.gguf",+ )++ @pytest.fixture+ def spec_config(self, swa, tmp_path, monkeypatch):+ drafter = tmp_path / "mtp-swa.gguf"+ drafter.write_bytes(Path(swa).read_bytes())+ drafter_bytes = drafter.stat().st_size++ def _files(+ cfg,+ *,+ llama_extra_args = None,+ **kw,+ ):+ pinned = _draft_on_cpu(list(llama_extra_args or ()))+ return 1.0 + (0.0 if pinned else drafter_bytes / 1024**3)++ monkeypatch.setattr(ri, "_gguf_resident_file_gb", _files)+ return SimpleNamespace(+ identifier = "local/swa",+ gguf_file = swa,+ is_gguf = True,+ gguf_mmproj_file = None,+ gguf_mtp_file = str(drafter),+ gguf_dspark_file = None,+ gguf_dflash_file = None,+ )++ def test_the_drafter_cache_is_priced_at_the_targets_layout(self, spec_config, swa):+ # --swa-full reached the target cache and stopped there, so a drafter with the+ # same geometry was priced holding a window while the launch gives it the whole+ # context. The loader passes all four layout settings; so does this now.+ windowed = ri._gguf_memory_breakdown(spec_config, swa, n_ctx = 131072)+ full = ri._gguf_memory_breakdown(+ spec_config, swa, n_ctx = 131072, llama_extra_args = ["--swa-full"]+ )+ assert full.kv_bytes > windowed.kv_bytes+ # Same header on both sides, so the drafter's cache moves exactly as the+ # target's does rather than staying at the windowed figure.+ assert full.drafter_runtime_bytes == full.kv_bytes+ assert windowed.drafter_runtime_bytes == windowed.kv_bytes++ def test_a_cpu_device_selection_takes_the_weights_off_the_gpu(self, spec_config, swa):+ """``--device none`` runs on the CPU whatever the layer count says.++ The loader's residency gate asks ``_device_selection_is_cpu`` before it looks at+ -ngl for exactly this reason. The estimate read Auto as fully GPU-resident and+ charged the whole footprint to VRAM, which is a GPU-exceeds warning for a load+ that touches no GPU at all.+ """+ priced = dict(n_ctx = 32768, cache_type_kv = "f16")+ on_gpu = ri._gguf_memory_breakdown(spec_config, swa, **priced)+ for flag in (["--device", "none"], ["--device", "cpu"], ["-dev", "none"]):+ cpu_only = ri._gguf_memory_breakdown(spec_config, swa, llama_extra_args = flag, **priced)+ assert cpu_only.gpu_bytes == 0, flag+ # The memory is still spent, just not on the card.+ assert cpu_only.total_bytes > 0+ assert on_gpu.gpu_bytes > 0++ def test_context_checkpoints_are_charged_to_the_host_not_the_gpu(self, spec_config, swa):+ """Checkpoints are host RAM, so they belong in the total and not in gpu_bytes.++ llama.cpp holds each one in ``common_prompt_checkpoint``'s+ ``std::vector<uint8_t>`` buffers, on the host heap and bounded by+ ``--cache-ram``; Studio's own load schema says "Each costs host memory". They+ are inside ``kv_bytes`` because that is what the training guard budgets, so the+ GPU figure has to take them back out. Priced into VRAM, the default 32 per slot+ warned about GPU pressure the launch never creates.+ """+ priced = dict(n_ctx = 131072, cache_type_kv = "f16")+ none = ri._gguf_memory_breakdown(spec_config, swa, ctx_checkpoints = 0, **priced)+ many = ri._gguf_memory_breakdown(spec_config, swa, ctx_checkpoints = 8, **priced)++ # The snapshots are real and substantial, or the rest of this proves nothing.+ assert many.kv_bytes > none.kv_bytes+ # ... and they are in the aggregate total, which is what the host pays.+ assert many.total_bytes > none.total_bytes+ # But the GPU figure does not move: that is the whole finding.+ assert many.gpu_bytes == none.gpu_bytes++ def test_one_card_is_priced_as_the_layer_load_it_launches(self, spec_config, swa):+ # Tensor mode needs two usable GPUs. Below that load_model drops it, so pricing+ # tensor charged per-device compute buffers for a launch that runs neither.+ #+ # The cache type is no longer part of this: #8939 removed the gate that rewrote+ # both axes to f16 on a tensor split, so a quantized KV now survives one and the+ # downgrade cannot move it. Asserted equal rather than dropped, since a+ # reintroduced gate would put an f16 cache back on the tensor side.+ priced = dict(n_ctx = 32768, cache_type_kv = "q4_0", tensor_parallel = True, n_devices = 1)+ downgraded = ri._gguf_memory_breakdown(+ spec_config, swa, tensor_split_possible = False, **priced+ )+ as_tensor = ri._gguf_memory_breakdown(+ spec_config, swa, tensor_split_possible = True, **priced+ )+ assert downgraded.cache_type_kv == "q4_0"+ assert as_tensor.cache_type_kv == "q4_0"+ assert downgraded.kv_bytes == as_tensor.kv_bytes+ assert downgraded.compute_bytes < as_tensor.compute_bytes+ assert downgraded.total_bytes < as_tensor.total_bytes++ def test_manual_auto_layers_is_priced_as_the_layer_load_it_launches(self, spec_config, swa):+ # Manual with Auto layers hands the budget to llama.cpp --fit, which load_model+ # says outright is incompatible with tensor parallelism and drops the split for.+ # Two cards are visible and pinned, so nothing else downgrades it: only the+ # layer count does. Priced as tensor, the per-device buffers are charged for a+ # launch that runs a layer split.+ priced = dict(+ n_ctx = 32768,+ cache_type_kv = "q4_0",+ tensor_parallel = True,+ n_devices = 2,+ gpu_memory_mode = "manual",+ tensor_split_possible = True,+ )+ auto_layers = ri._gguf_memory_breakdown(spec_config, swa, gpu_layers = None, **priced)+ explicit = ri._gguf_memory_breakdown(spec_config, swa, gpu_layers = 40, **priced)+ assert auto_layers.compute_bytes != explicit.compute_bytes+ # The layer-split arm, which is what /load runs here.+ as_layers = ri._gguf_memory_breakdown(+ spec_config, swa, gpu_layers = None, **{**priced, "tensor_parallel": False}+ )+ assert auto_layers.compute_bytes == as_layers.compute_bytes++ def test_manual_zero_layers_is_priced_as_the_cpu_load_it_launches(self, spec_config, swa):+ # gpu_layers=0 leaves nothing on the GPU to split. load_model drops the split+ # rather than let --split-mode tensor abort the server under the CPU-only mask,+ # so a tensor price here is per-device buffers for a load that takes no VRAM.+ priced = dict(+ n_ctx = 32768,+ cache_type_kv = "q4_0",+ n_devices = 2,+ gpu_memory_mode = "manual",+ gpu_layers = 0,+ tensor_split_possible = True,+ )+ as_tensor = ri._gguf_memory_breakdown(spec_config, swa, tensor_parallel = True, **priced)+ as_layers = ri._gguf_memory_breakdown(spec_config, swa, tensor_parallel = False, **priced)+ assert as_tensor.compute_bytes == as_layers.compute_bytes+ assert as_tensor.total_bytes == as_layers.total_bytes++ def test_an_ngl_in_the_extras_keeps_the_manual_split(self, spec_config, swa):+ # /load translates the last -ngl into the field before deciding, so a slider at+ # 0 with -ngl 40 in the extras is a 40-layer load and does reach a tensor+ # launch. Dropping on the field alone would price it as a layer split.+ assert ri._manual_keeps_tensor_split("manual", 0, ["-ngl", "40"]) is True+ assert ri._manual_keeps_tensor_split("manual", 40, ["-ngl", "0"]) is False+ assert ri._manual_keeps_tensor_split("manual", None, None) is False+ assert ri._manual_keeps_tensor_split("manual", 0, None) is False+ assert ri._manual_keeps_tensor_split("manual", 1, None) is True+ # Auto is the planner's call, not ours, whatever the count says.+ assert ri._manual_keeps_tensor_split("auto", 0, None) is True+ assert ri._manual_keeps_tensor_split(None, None, None) is True+ # A malformed override is shrugged off rather than raised, same as the layer+ # fraction does with it.+ assert ri._manual_keeps_tensor_split("manual", 8, ["-ngl", "banana"]) is True++ def test_a_one_card_pin_cannot_tensor_split(self):+ # A pin answers for itself and needs no probe, which is the deterministic half+ # of the rule. Without a pin the host answers, and that must not raise here+ # whatever this machine has.+ assert ri._tensor_split_possible([0]) is False+ assert ri._tensor_split_possible([0, 1]) is True+ assert ri._tensor_split_possible([2, 3, 5]) is True+ assert isinstance(ri._tensor_split_possible(None), bool)++ def test_the_vision_encoder_costs_more_than_its_projector_file(+ self, swa, tmp_path, monkeypatch+ ):+ # The encoder's buffers run about 1.3x the file, which the placement path+ # budgets as _MMPROJ_VRAM_SAFETY - 1. Counting only the file called a+ # near-capacity multimodal load a fit.+ projector = tmp_path / "mmproj-swa.gguf"+ projector.write_bytes(b"\0" * 1024)+ config = SimpleNamespace(+ identifier = "local/vision",+ gguf_file = swa,+ is_gguf = True,+ gguf_mmproj_file = str(projector),+ gguf_mtp_file = None,+ gguf_dspark_file = None,+ gguf_dflash_file = None,+ )+ monkeypatch.setattr(ri, "_gguf_resident_file_gb", lambda cfg, **kw: 4.0)+ real_size = ri.LlamaCppBackend._get_gguf_size_bytes+ monkeypatch.setattr(+ ri.LlamaCppBackend,+ "_get_gguf_size_bytes",+ staticmethod(+ lambda path: 3 * _GIB+ if os.path.basename(str(path)) == "swa.gguf"+ else real_size(path)+ ),+ )+ expected = int(1024 * (ri.LlamaCppBackend._MMPROJ_VRAM_SAFETY - 1.0))+ resident = ri._gguf_memory_breakdown(config, swa, n_ctx = 8192)+ assert resident.projector_runtime_bytes == expected+ assert resident.total_bytes == (+ resident.weights_bytes + resident.kv_bytes + resident.compute_bytes + expected+ )+ # The buffers sit with the projector, so pinning it takes them off the GPU+ # while leaving them in the total.+ pinned = ri._gguf_memory_breakdown(+ config, swa, n_ctx = 8192, llama_extra_args = ["--no-mmproj-offload"]+ )+ assert pinned.total_bytes == resident.total_bytes+ assert resident.gpu_bytes - pinned.gpu_bytes == expected + 1024++ def test_a_model_with_no_projector_is_charged_nothing_for_one(self, spec_config, swa):+ assert ri._gguf_memory_breakdown(spec_config, swa, n_ctx = 8192).projector_runtime_bytes == 0+++class TestInheritedEnvironment:+ """What the CHILD inherits, which is not always what the panel was told.++ ``_child_spec_env`` is the rule: the launch scrubs LLAMA_ARG_SPEC_* whenever+ Unsloth owns the spec block, and keeps it when the extras do. The projector has no+ such scrub at all, so an inherited one loads even through --no-mmproj.+ """++ @pytest.fixture+ def bare(self, gqa_gguf):+ # No sidecars: anything charged here arrived through the environment.+ return SimpleNamespace(+ identifier = "local/bare",+ gguf_file = gqa_gguf,+ is_gguf = True,+ gguf_mmproj_file = None,+ gguf_mtp_file = None,+ gguf_dspark_file = None,+ gguf_dflash_file = None,+ )++ @pytest.fixture+ def fixed_files(self, monkeypatch):+ monkeypatch.setattr(ri, "_gguf_resident_file_gb", lambda cfg, **kw: 1.0)++ def test_an_inherited_drafter_is_charged_when_the_extras_own_speculation(+ self, bare, gqa_gguf, tmp_path, monkeypatch, fixed_files+ ):+ drafter = _write_gguf(tmp_path, "qwen3", _GQA_FIELDS, name = "inherited-draft.gguf")+ monkeypatch.setenv("LLAMA_ARG_SPEC_DRAFT_MODEL", drafter)+ # The files term resolves --model-draft against an empty env, so this drafter+ # is in neither its bytes nor, before this, the cache priced on top of them.+ owned = ri._gguf_memory_breakdown(+ bare, gqa_gguf, n_ctx = 32768, llama_extra_args = ["--spec-type", "draft-mtp"]+ )+ assert owned.drafter_runtime_bytes > 0+ assert owned.weights_bytes == _GIB + os.path.getsize(drafter)+ # Without an extras --spec-type the launch scrubs LLAMA_ARG_SPEC_*, so the+ # child never sees it and neither does the estimate.+ scrubbed = ri._gguf_memory_breakdown(bare, gqa_gguf, n_ctx = 32768)+ assert scrubbed.drafter_runtime_bytes == 0+ assert scrubbed.weights_bytes == _GIB++ def test_an_inherited_draft_depth_is_honoured_only_when_the_child_keeps_it(+ self, bare, gqa_gguf, monkeypatch+ ):+ monkeypatch.setenv("LLAMA_ARG_SPEC_DRAFT_N_MAX", "7")+ owned = ["--spec-type", "draft-mtp"]+ # The loader reads the env twin before falling back to the build's default.+ assert ri._estimate_draft_n_max(bare, gqa_gguf, requested = None, extras = owned) == 7+ # Scrubbed when Unsloth owns the block, so the platform default stands.+ assert ri._estimate_draft_n_max(bare, gqa_gguf, requested = None, extras = []) in (2, 3)+ # A flag still beats the environment, as it does at launch.+ assert (+ ri._estimate_draft_n_max(+ bare, gqa_gguf, requested = None, extras = [*owned, "--spec-draft-n-max", "5"]+ )+ == 5+ )++ def test_an_inherited_projector_is_charged_like_a_configured_one(+ self, bare, gqa_gguf, tmp_path, monkeypatch+ ):+ projector = tmp_path / "inherited-mmproj.gguf"+ projector.write_bytes(b"\0" * 4096)+ monkeypatch.setenv("LLAMA_ARG_MMPROJ", str(projector))+ monkeypatch.setattr(ri, "_gguf_resident_file_gb", lambda cfg, **kw: 4.0)+ real_size = ri.LlamaCppBackend._get_gguf_size_bytes+ monkeypatch.setattr(+ ri.LlamaCppBackend,+ "_get_gguf_size_bytes",+ staticmethod(+ lambda path: 3 * _GIB+ if os.path.basename(str(path)) == "model.gguf"+ else real_size(path)+ ),+ )+ expected = int(4096 * (ri.LlamaCppBackend._MMPROJ_VRAM_SAFETY - 1.0))+ resident = ri._gguf_memory_breakdown(bare, gqa_gguf, n_ctx = 8192)+ assert resident.projector_runtime_bytes == expected+ # Placement too: the flag and the inherited variable move file and buffers+ # alike, since _resolved_mmproj_offload reads both.+ by_flag = ri._gguf_memory_breakdown(+ bare, gqa_gguf, n_ctx = 8192, llama_extra_args = ["--no-mmproj-offload"]+ )+ assert resident.gpu_bytes - by_flag.gpu_bytes == expected + 4096+ monkeypatch.setenv("LLAMA_ARG_MMPROJ_OFFLOAD", "0")+ assert ri._gguf_memory_breakdown(bare, gqa_gguf, n_ctx = 8192).gpu_bytes == by_flag.gpu_bytes++ def test_the_vulkan_pool_comes_from_the_probed_snapshot(self, monkeypatch):+ # _effective_gpu_count counts CUDA devices, so on a Vulkan build it sees none+ # and a multi-GPU tensor launch was priced with one device's buffers. The+ # inventory /api/system already probed answers instead, read and never+ # refreshed: probing it costs a subprocess and this runs on every keystroke.+ fake_main = _types.ModuleType("main")+ monkeypatch.setitem(sys.modules, "main", fake_main)+ monkeypatch.setattr(ri.LlamaCppBackend, "_is_vulkan_backend", staticmethod(lambda *a: True))++ def snapshot(count: int):+ fake_main._system_gpu_cache = (+ 0.0,+ ({}, {"devices": [{"index": i} for i in range(count)]}),+ )++ snapshot(3)+ assert len(ri._cached_inference_devices()) == 3+ assert (+ ri._guard_device_count(None, ri._cached_inference_devices(), tensor_parallel = True) == 3+ )+ assert ri._tensor_split_possible(None) is True+ snapshot(1)+ assert (+ ri._guard_device_count(None, ri._cached_inference_devices(), tensor_parallel = True) == 1+ )+ # One Vulkan device is a downgrade at launch, so it is one here too.+ assert ri._tensor_split_possible(None) is False+ # Nothing probed yet: unknown, and unknown must not become a downgrade.+ fake_main._system_gpu_cache = None+ assert ri._cached_inference_devices() is None+ assert ri._tensor_split_possible(None) is True+++class TestManualNormalizationAndRemoteDrafters:+ """Two more places the panel described a command the loader would not send."""++ @pytest.fixture+ def bare(self, gqa_gguf):+ return SimpleNamespace(+ identifier = "local/bare",+ gguf_file = gqa_gguf,+ is_gguf = True,+ gguf_mmproj_file = None,+ gguf_mtp_file = None,+ gguf_dspark_file = None,+ gguf_dflash_file = None,+ )++ def test_manual_prices_the_stripped_extras(self, bare, gqa_gguf, monkeypatch):+ # -ncmoe pushes into tensor_buft_overrides, which turns pipeline parallelism+ # off and drops the context-buffer multiplier. Manual strips the flag before+ # launch, so the multiplier survives and the panel has to say so; Auto keeps+ # the flag, so there it does not.+ monkeypatch.setattr(ri, "_gguf_resident_file_gb", lambda cfg, **kw: 1.0)+ priced = dict(n_ctx = 32768, gpu_layers = 99, n_devices = 2)++ def compute(mode: str, extras):+ return ri._gguf_memory_breakdown(+ bare, gqa_gguf, gpu_memory_mode = mode, llama_extra_args = extras, **priced+ ).compute_bytes++ moe = ["--n-cpu-moe", "8"]+ assert compute("manual", moe) == compute("manual", None)+ assert compute("auto", moe) < compute("auto", None)++ def test_a_remote_drafter_is_declared_unsized_rather_than_priced_at_zero(+ self, bare, gqa_gguf, monkeypatch+ ):+ # --spec-draft-hf names a repository. Its weights are charged by the files term,+ # but its cache cannot be read off a header that is not on this disk, and a+ # confident total missing a context-scaled cache is the one answer this row+ # must never give.+ from core.inference.llama_cpp import _extra_args_draft_offloaded_to_cpu as pinned++ def _files(+ cfg,+ *,+ llama_extra_args = None,+ **kw,+ ):+ args = list(llama_extra_args or ())+ remote = "--spec-draft-hf" in args+ return 1.0 + (2.0 if remote and not pinned(args) else 0.0)++ monkeypatch.setattr(ri, "_gguf_resident_file_gb", _files)+ remote = ri._gguf_memory_breakdown(+ bare, gqa_gguf, n_ctx = 32768, llama_extra_args = ["--spec-draft-hf", "org/drafter-GGUF"]+ )+ assert remote.drafter_kv_unsized is True+ # The weights are still counted, so the floor is as high as it can be made.+ assert remote.weights_bytes == 3 * _GIB+ assert remote.drafter_runtime_bytes == 0+ # And a load with no drafter at all is not flagged.+ assert ri._gguf_memory_breakdown(bare, gqa_gguf, n_ctx = 32768).drafter_kv_unsized is False++ def test_the_route_carries_the_unsized_flag(self, bare, gqa_gguf, monkeypatch):+ from core.inference.llama_cpp import _extra_args_draft_offloaded_to_cpu as pinned++ monkeypatch.setattr(ri, "_cached_estimate_config", lambda *a, **kw: bare)++ def _files(+ cfg,+ *,+ llama_extra_args = None,+ **kw,+ ):+ # Mirrors the real term, including that a CPU-pinned drafter is dropped:+ # the breakdown identifies the drafter's bytes by re-pricing with that pin.+ args = list(llama_extra_args or ())+ return 1.0 + (2.0 if "--spec-draft-hf" in args and not pinned(args) else 0.0)++ monkeypatch.setattr(ri, "_gguf_resident_file_gb", _files)+ resp = _estimate(+ model_path = gqa_gguf,+ n_ctx = 8192,+ llama_extra_args = ["--spec-draft-hf", "org/drafter-GGUF"],+ )+ assert resp.available is True+ # available, but not silent about what is missing from the total.+ assert resp.drafter_kv_unsized is True+++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.+ """++ @pytest.fixture+ def config_with_a_sidecar(self, tmp_path):+ target = _write_gguf(tmp_path, "qwen3", _GQA_FIELDS, name = "target.gguf")+ sidecar = tmp_path / "mtp.gguf"+ sidecar.write_bytes(Path(target).read_bytes())+ return SimpleNamespace(+ identifier = "local/target",+ gguf_file = target,+ is_gguf = True,+ gguf_variant = None,+ gguf_mmproj_file = None,+ gguf_mtp_file = str(sidecar),+ gguf_dspark_file = None,+ gguf_dflash_file = None,+ )++ @pytest.mark.parametrize("mode", ["off", "ngram", "ngram-simple"])+ def test_a_drafterless_mode_is_not_charged_for_the_sidecar(self, config_with_a_sidecar, mode):+ charged = ri._gguf_resident_file_gb(config_with_a_sidecar, speculative_type = "mtp")+ quiet = ri._gguf_resident_file_gb(config_with_a_sidecar, speculative_type = mode)+ assert charged is not None and quiet is not None+ # The sidecar is a copy of the target, so its absence is unmissable.+ assert quiet < charged+ assert quiet == pytest.approx(charged / 2, rel = 0.05)++ def test_a_drafting_mode_still_charges_it(self, config_with_a_sidecar):+ """The guard against over-correcting: MTP must keep paying for its drafter."""+ with_mtp = ri._gguf_resident_file_gb(config_with_a_sidecar, speculative_type = "mtp")+ auto = ri._gguf_resident_file_gb(config_with_a_sidecar, speculative_type = "auto")+ assert with_mtp is not None and auto is not None+ assert with_mtp == auto+++class TestAProjectorOverrideIsTheOneCharged:+ """``--mmproj`` in Advanced Arguments last-wins, so it is the file that opens.++ ``load_model`` emits Studio's resolved projector and appends the extras after it,+ so the child opens the user's. Both the resident-file total and the encoder's+ runtime allowance read only the configured projector, which billed a file the+ launch never opens and let a possibly much larger custom one through free.+ """++ @pytest.fixture+ def vision_config(self, tmp_path):+ target = _write_gguf(tmp_path, "qwen3", _GQA_FIELDS, name = "target.gguf")+ small = tmp_path / "mmproj-small.gguf"+ small.write_bytes(b"s" * 4096)+ big = tmp_path / "mmproj-big.gguf"+ big.write_bytes(b"b" * (4096 * 8))+ config = SimpleNamespace(+ identifier = "local/vision",+ gguf_file = target,+ is_gguf = True,+ gguf_variant = None,+ gguf_mmproj_file = str(small),+ gguf_mtp_file = None,+ gguf_dspark_file = None,+ gguf_dflash_file = None,+ )+ return config, str(small), str(big)++ def test_the_override_replaces_the_configured_projector_in_the_files(self, vision_config):+ config, small, big = vision_config+ configured = ri._gguf_resident_file_gb(config)+ overridden = ri._gguf_resident_file_gb(config, llama_extra_args = ["--mmproj", big])+ assert configured is not None and overridden is not None+ # The override is 8x the configured one, so the total has to move with it.+ assert overridden > configured+ delta = (overridden - configured) * 1024**3+ assert delta == pytest.approx(Path(big).stat().st_size - Path(small).stat().st_size, abs = 8)++ def test_the_overrides_encoder_runtime_is_charged_too(self, vision_config):+ config, _small, big = vision_config+ charged = ri._charged_projector_bytes(config, ["--mmproj", big], False)+ assert charged == Path(big).stat().st_size++ def test_the_short_flag_is_read_the_same_way(self, vision_config):+ config, _small, big = vision_config+ assert ri._charged_projector_bytes(config, ["-mm", big], False) == Path(big).stat().st_size++ def test_no_override_still_charges_the_configured_projector(self, vision_config):+ config, small, _big = vision_config+ assert ri._charged_projector_bytes(config, [], False) == Path(small).stat().st_size+++class TestAnEmbeddedMtpHeadIsPriced:+ """A NextN head is a drafter with no file, and it still allocates a draft cache.++ Nothing is charged in the weights for it, so `_charged_drafter_path` returns None+ and the entire runtime-sizing block was skipped. `_estimate_mtp_overhead_bytes`+ documents this case explicitly (``drafter_path=None``, ``draft_weights_bytes=0``)+ and sizes the head from ``nextn_predict_layers``, so the allocation was knowable+ and simply not asked for.+ """++ @pytest.fixture+ def nextn_model(self, tmp_path):+ gguf = _write_gguf(+ tmp_path,+ "qwen3",+ {**_GQA_FIELDS, "context_length": 262144, "nextn_predict_layers": 2},+ name = "nextn.gguf",+ )+ return gguf, SimpleNamespace(+ identifier = "local/nextn",+ gguf_file = gguf,+ is_gguf = True,+ gguf_variant = None,+ gguf_mmproj_file = None,+ gguf_mtp_file = None,+ gguf_dspark_file = None,+ gguf_dflash_file = None,+ )++ def test_the_head_is_charged_when_speculation_can_engage(self, nextn_model):+ gguf, config = nextn_model+ priced = ri._gguf_memory_breakdown(config, gguf, n_ctx = 131072)+ assert priced is not None+ assert priced.drafter_runtime_bytes > 0+ # And it is inside the total, which is the figure the fit verdict reads.+ assert priced.total_bytes > priced.weights_bytes + priced.kv_bytes++ def test_turning_speculation_off_charges_no_head(self, nextn_model):+ gguf, config = nextn_model+ off = ri._gguf_memory_breakdown(config, gguf, n_ctx = 131072, speculative_type = "off")+ assert off is not None+ assert off.drafter_runtime_bytes == 0++ def test_a_model_without_a_head_is_unaffected(self, tmp_path):+ """The guard against charging every model: no NextN key, nothing priced."""+ plain = _write_gguf(tmp_path, "qwen3", {**_GQA_FIELDS, "context_length": 262144})+ config = SimpleNamespace(+ identifier = "local/plain",+ gguf_file = plain,+ is_gguf = True,+ gguf_variant = None,+ gguf_mmproj_file = None,+ gguf_mtp_file = None,+ gguf_dspark_file = None,+ gguf_dflash_file = None,+ )+ priced = ri._gguf_memory_breakdown(config, plain, n_ctx = 131072)+ assert priced is not None+ assert priced.drafter_runtime_bytes == 0++ def test_a_draft_pin_does_not_move_the_embedded_head(self, nextn_model):+ """--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.+ """+ gguf, config = nextn_model+ unpinned = ri._gguf_memory_breakdown(config, gguf, n_ctx = 131072)+ assert unpinned is not None+ assert unpinned.drafter_runtime_gpu_bytes > 0+ for pin in (["--spec-draft-ngl", "0"], ["--spec-draft-device", "cpu"]):+ pinned = ri._gguf_memory_breakdown(config, gguf, n_ctx = 131072, llama_extra_args = pin)+ assert pinned is not None, pin+ assert pinned.drafter_runtime_bytes > 0, pin+ # Unmoved: the same bytes on the same device as with no pin at all.+ assert pinned.drafter_runtime_gpu_bytes == unpinned.drafter_runtime_gpu_bytes, pin+ assert pinned.drafter_runtime_bytes == unpinned.drafter_runtime_bytes, pin++ def test_a_cpu_placed_target_takes_the_embedded_head_with_it(self, nextn_model):+ """The other half of the same rule: it follows the target DOWN as well as up.++ An embedded head has no file, so host_drafter_bytes is 0 and the drafter is+ GPU-resident by default. That default is only right while the target is: the+ head is part of the target's tensors and llama.cpp gives it the target's+ context, so at --gpu-layers 0 its cache is in host RAM. Charging it to VRAM+ there raised a multi-gigabyte warning about a card the load never touches.+ """+ gguf, config = nextn_model+ on_cpu = ri._gguf_memory_breakdown(+ config, gguf, n_ctx = 131072, gpu_memory_mode = "manual", gpu_layers = 0+ )+ assert on_cpu is not None+ # Still allocated, and still in the aggregate figure -- just not on the card.+ assert on_cpu.drafter_runtime_bytes > 0+ assert on_cpu.drafter_runtime_gpu_bytes == 0+++class TestACpuOnlyHostShowsNoGpuFootprint:+ """An Auto load on a machine with no GPU runs in host RAM, and must read that way.++ CPU placement was detected only from an explicit --device or its env twin, so a+ plain Auto request on a CPU-only Linux or Windows box was priced fully GPU-resident+ -- a multi-gigabyte GPU figure against a capacity of zero.++ The evidence has to be a probe that RAN. An unfilled snapshot is not absence, and+ the CUDA count is zero on every Vulkan host, so neither may move the weights.+ """++ @pytest.fixture+ def priced(self, tmp_path):+ gguf = _write_gguf(tmp_path, "qwen3", {**_GQA_FIELDS, "context_length": 262144})+ return gguf, SimpleNamespace(+ identifier = "local/cpu",+ gguf_file = gguf,+ is_gguf = True,+ gguf_variant = None,+ gguf_mmproj_file = None,+ gguf_mtp_file = None,+ gguf_dspark_file = None,+ gguf_dflash_file = None,+ )++ def test_a_probed_empty_inventory_puts_everything_in_host_ram(self, priced, monkeypatch):+ gguf, config = priced+ monkeypatch.setattr(ri, "_cached_inference_devices", lambda: [])+ out = ri._gguf_memory_breakdown(config, gguf, n_ctx = 32768)+ assert out is not None+ assert out.gpu_bytes == 0+ # Still a real load, just not on a card.+ assert out.total_bytes > 0+ assert out.kv_on_gpu is False++ def test_an_unprobed_snapshot_is_not_evidence_of_absence(self, priced, monkeypatch):+ gguf, config = priced+ monkeypatch.setattr(ri, "_cached_inference_devices", lambda: None)+ out = ri._gguf_memory_breakdown(config, gguf, n_ctx = 32768)+ assert out is not None+ assert out.gpu_bytes > 0++ def test_a_probed_inventory_with_a_card_is_unaffected(self, priced, monkeypatch):+ gguf, config = priced+ monkeypatch.setattr(ri, "_cached_inference_devices", lambda: [(0, 0, 0)])+ out = ri._gguf_memory_breakdown(config, gguf, n_ctx = 32768)+ assert out is not None+ assert out.gpu_bytes > 0+++class TestAnInheritedContextIsPriced:+ """``LLAMA_ARG_CTX_SIZE`` is what the child runs at when nothing else sets a length.++ The launch drops an inherited context only when it is ZERO and the auto-layers path+ needs --fit to run; a positive one is left alone as a legitimate way to set the+ length. The estimate fell straight through to the header's native context, so a 4k+ environment on a 262k model priced the KV cache 64x too large and refused loads that+ run comfortably.+ """++ @pytest.fixture+ def wide(self, tmp_path):+ gguf = _write_gguf(tmp_path, "qwen3", {**_GQA_FIELDS, "context_length": 262144})+ return gguf, SimpleNamespace(+ identifier = "local/wide",+ gguf_file = gguf,+ is_gguf = True,+ gguf_variant = None,+ gguf_mmproj_file = None,+ gguf_mtp_file = None,+ gguf_dspark_file = None,+ gguf_dflash_file = None,+ )++ def test_the_environment_length_is_priced_when_nothing_else_sets_one(self, wide, monkeypatch):+ gguf, config = wide+ monkeypatch.setenv("LLAMA_ARG_CTX_SIZE", "4096")+ out = ri._gguf_memory_breakdown(config, gguf, n_ctx = 0)+ assert out is not None+ assert out.n_ctx == 4096++ def test_the_native_context_is_still_the_last_resort(self, wide, monkeypatch):+ gguf, config = wide+ monkeypatch.delenv("LLAMA_ARG_CTX_SIZE", raising = False)+ out = ri._gguf_memory_breakdown(config, gguf, n_ctx = 0)+ assert out is not None+ assert out.n_ctx == 262144++ @pytest.mark.parametrize("value", ["0", "", "not-a-number", "-5"])+ def test_a_useless_environment_value_falls_through(self, wide, monkeypatch, value):+ """Zero is the one the launch itself drops, and the rest are not lengths."""+ gguf, config = wide+ monkeypatch.setenv("LLAMA_ARG_CTX_SIZE", value)+ out = ri._gguf_memory_breakdown(config, gguf, n_ctx = 0)+ assert out is not None+ assert out.n_ctx == 262144++ @pytest.mark.parametrize("flag", [["-c", "0"], ["--ctx-size", "0"], ["--ctx-size=0"]])+ def test_an_explicit_zero_asks_for_native_and_beats_the_environment(+ self, wide, monkeypatch, flag+ ):+ """ "-c 0" REQUESTS the native context; it is not the absence of a request.++ llama.cpp parses the environment before argv, so the explicit zero wins at the+ child. Folding it in with "nothing was set" let an inherited 4k answer for a+ launch that opens at the header's 262k -- the KV cache understated 64x, in the+ direction that says "fits".+ """+ gguf, config = wide+ monkeypatch.setenv("LLAMA_ARG_CTX_SIZE", "4096")+ out = ri._gguf_memory_breakdown(config, gguf, n_ctx = 0, llama_extra_args = flag)+ assert out is not None+ assert out.n_ctx == 262144, flag++ def test_without_that_zero_the_environment_still_answers(self, wide, monkeypatch):+ """The guard against over-correcting: only an explicit zero bypasses it."""+ gguf, config = wide+ monkeypatch.setenv("LLAMA_ARG_CTX_SIZE", "4096")+ assert ri._gguf_memory_breakdown(config, gguf, n_ctx = 0).n_ctx == 4096++ def test_an_explicit_panel_length_still_wins(self, wide, monkeypatch):+ gguf, config = wide+ monkeypatch.setenv("LLAMA_ARG_CTX_SIZE", "4096")+ out = ri._gguf_memory_breakdown(config, gguf, n_ctx = 8192)+ assert out is not None+ assert out.n_ctx == 8192+++class TestTheResolutionTriesOfflineFirst:+ """A repo already on this disk is priced without asking the Hub.++ The on-disk gate has established the files are here and everything downstream reads+ local files, but `from_identifier` still ran `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.+ """++ def test_the_first_attempt_runs_under_forced_offline(self, tmp_path, monkeypatch):+ gguf = _write_gguf(tmp_path, "qwen3", _GQA_FIELDS)+ seen = []++ import contextlib++ @contextlib.contextmanager+ def _forced():+ seen.append("offline")+ yield True++ monkeypatch.setattr(ri, "_estimate_target_is_on_this_disk", lambda ident: True)+ monkeypatch.setitem(+ __import__("sys").modules,+ "utils.utils",+ SimpleNamespace(force_hf_offline = _forced),+ )+ cfg = SimpleNamespace(identifier = "org/cached", gguf_file = gguf, is_gguf = True)+ monkeypatch.setattr(ri.ModelConfig, "from_identifier", staticmethod(lambda **kw: cfg))+ ri._estimate_config_cache.clear()+ out = ri._cached_estimate_config("org/cached", None, None, False)+ assert out is cfg+ assert seen == ["offline"], "the offline window was not entered"++ def test_an_offline_failure_falls_back_rather_than_blanking_the_row(+ self, tmp_path, monkeypatch+ ):+ """A slow right answer beats a fast blank row."""+ gguf = _write_gguf(tmp_path, "qwen3", _GQA_FIELDS)+ calls = []+ cfg = SimpleNamespace(identifier = "org/cached", gguf_file = gguf, is_gguf = True)++ def _from_identifier(**kw):+ calls.append(1)+ if len(calls) == 1:+ raise RuntimeError("needs the hub")+ return cfg++ import contextlib++ @contextlib.contextmanager+ def _forced():+ yield True++ monkeypatch.setattr(ri, "_estimate_target_is_on_this_disk", lambda ident: True)+ monkeypatch.setitem(+ __import__("sys").modules,+ "utils.utils",+ SimpleNamespace(force_hf_offline = _forced),+ )+ monkeypatch.setattr(ri.ModelConfig, "from_identifier", staticmethod(_from_identifier))+ ri._estimate_config_cache.clear()+ out = ri._cached_estimate_config("org/cached", None, None, False)+ assert out is cfg+ assert len(calls) == 2, "the online retry did not run"+++class TestTheEmbeddedHeadIsChargedOnlyWhenItEngages:+ """Every no-MTP outcome ``_build_speculative_flags`` has, asked of the estimate.++ An embedded head has no file, so nothing about it is visible in the weights and an+ over-charge is invisible too: it just makes the row read several GB high and can+ refuse a load that runs. These are the launches that allocate no head at all.+ """++ def _config(self, gguf, identifier):+ return SimpleNamespace(+ identifier = identifier,+ gguf_file = gguf,+ is_gguf = True,+ gguf_variant = None,+ gguf_mmproj_file = None,+ gguf_mtp_file = None,+ gguf_dspark_file = None,+ gguf_dflash_file = None,+ )++ @pytest.fixture+ def head(self, tmp_path):+ return _write_gguf(+ tmp_path,+ "qwen3",+ {**_GQA_FIELDS, "context_length": 262144, "nextn_predict_layers": 2},+ name = "head.gguf",+ )++ def test_a_sub_3b_head_is_dropped_by_auto(self, head):+ """Auto falls back to ngram-mod there, because MTP regresses below 3B."""+ big = ri._gguf_memory_breakdown(self._config(head, "org/Qwen3-8B"), head, n_ctx = 131072)+ small = ri._gguf_memory_breakdown(self._config(head, "org/Qwen3-1.7B"), head, n_ctx = 131072)+ assert big.drafter_runtime_bytes > 0+ assert small.drafter_runtime_bytes == 0++ def test_forcing_mtp_overrides_the_size_drop(self, head):+ """The drop is Auto's judgement; an explicit request is not overruled."""+ forced = ri._gguf_memory_breakdown(+ self._config(head, "org/Qwen3-1.7B"), head, n_ctx = 131072, speculative_type = "mtp"+ )+ assert forced.drafter_runtime_bytes > 0++ @pytest.mark.parametrize("mode", ["dspark", "dflash"])+ def test_a_sidecar_mode_never_charges_the_embedded_head(self, head, mode):+ """Those either open their own sidecar, charged as a file, or --spec-default."""+ out = ri._gguf_memory_breakdown(+ self._config(head, "org/Qwen3-8B"), head, n_ctx = 131072, speculative_type = mode+ )+ assert out.drafter_runtime_bytes == 0++ @pytest.mark.parametrize("mode", [None, "mtp"])+ def test_a_binary_that_cannot_run_mtp_is_not_charged_for_it(self, head, monkeypatch, mode):+ """No mtp_token means --spec-default launches, whatever the mode asked for.++ Unlike the size and MLA drops this is a hard incompatibility, so it applies to+ a forced request too.+ """+ monkeypatch.setattr(+ ri.LlamaCppBackend,+ "probe_server_capabilities",+ classmethod(lambda cls, *a, **k: {"found": True, "mtp_token": None}),+ )+ out = ri._gguf_memory_breakdown(+ self._config(head, "org/Qwen3-8B"), head, n_ctx = 131072, speculative_type = mode+ )+ assert out.drafter_runtime_bytes == 0++ def test_an_unanswerable_probe_keeps_the_charge(self, head, monkeypatch):+ """A probe that could not run is not evidence the build lacks the flag."""+ monkeypatch.setattr(+ ri.LlamaCppBackend,+ "probe_server_capabilities",+ classmethod(lambda cls, *a, **k: {"found": False, "mtp_token": None}),+ )+ out = ri._gguf_memory_breakdown(self._config(head, "org/Qwen3-8B"), head, n_ctx = 131072)+ assert out.drafter_runtime_bytes > 0++ def test_extras_asking_for_another_mode_are_left_alone(self, head):+ """Studio emits no spec block of its own once --spec-type is in the extras."""+ out = ri._gguf_memory_breakdown(+ self._config(head, "org/Qwen3-8B"),+ head,+ n_ctx = 131072,+ llama_extra_args = ["--spec-type", "ngram-mod"],+ )+ assert out.drafter_runtime_bytes == 0++ @pytest.mark.parametrize("spec", ["draft-mtp", "mtp"])+ def test_extras_asking_for_mtp_engage_the_embedded_head(self, head, spec):+ """The child honours the extras, and on a NextN GGUF that IS the embedded head.++ There is no drafter file, so nothing in the weights would ever hint at it: the+ draft cache and the target-side state were simply absent from the total.+ """+ out = ri._gguf_memory_breakdown(+ self._config(head, "org/Qwen3-8B"),+ head,+ n_ctx = 131072,+ llama_extra_args = ["--spec-type", spec],+ )+ assert out.drafter_runtime_bytes > 0++ def test_extras_asking_for_mtp_on_a_sub_3b_model_still_engage_it(self, head):+ """An explicit request is not second-guessed by Auto's size rule."""+ out = ri._gguf_memory_breakdown(+ self._config(head, "org/Qwen3-1.7B"),+ head,+ n_ctx = 131072,+ llama_extra_args = ["--spec-type", "draft-mtp"],+ )+ assert out.drafter_runtime_bytes > 0+++class TestTheCpuOnlyCheckIsActuallyReachable:+ """Driven through the real snapshot, not through a stubbed helper.++ The first version of the CPU-only fix was inert: `_cached_inference_devices` ended+ in `or None`, so the empty list a probed CPU-only host produces arrived as the same+ value as a snapshot nobody had filled, and the check for it could never fire. Its+ unit tests passed because they replaced `_cached_inference_devices` itself, which+ is the one thing that could not be wrong. These stub the snapshot instead.+ """++ @pytest.fixture+ def snapshot(self, monkeypatch):+ import sys as _sys+ def _set(devices):+ main = SimpleNamespace(_system_gpu_cache = (0.0, (None, {"devices": devices})))+ monkeypatch.setitem(_sys.modules, "main", main)++ return _set++ def test_a_probed_cpu_only_host_reads_as_empty_not_unknown(self, snapshot):+ snapshot([])+ assert ri._cached_inference_devices() == []+ assert ri._estimate_host_has_no_gpu() is True++ def test_a_probed_host_with_cards_reads_as_those_cards(self, snapshot):+ snapshot([{"index": 0}, {"index": 1}])+ assert len(ri._cached_inference_devices()) == 2+ assert ri._estimate_host_has_no_gpu() is False++ def test_an_unfilled_snapshot_is_still_unknown(self, monkeypatch):+ import sys as _sys++ monkeypatch.setitem(_sys.modules, "main", SimpleNamespace())+ assert ri._cached_inference_devices() is None+ assert ri._estimate_host_has_no_gpu() is False++ def test_a_cpu_only_host_cannot_take_a_tensor_split(self, snapshot, monkeypatch):+ """The other caller of the same snapshot, which was also reading True here."""+ snapshot([])+ monkeypatch.setattr(ri.LlamaCppBackend, "_is_vulkan_backend", staticmethod(lambda *a: True))+ assert ri._tensor_split_possible(None) is False++ def test_the_whole_footprint_lands_in_host_ram_end_to_end(self, snapshot, tmp_path):+ gguf = _write_gguf(tmp_path, "qwen3", {**_GQA_FIELDS, "context_length": 262144})+ config = SimpleNamespace(+ identifier = "local/cpu",+ gguf_file = gguf,+ is_gguf = True,+ gguf_variant = None,+ gguf_mmproj_file = None,+ gguf_mtp_file = None,+ gguf_dspark_file = None,+ gguf_dflash_file = None,+ )+ snapshot([])+ out = ri._gguf_memory_breakdown(config, gguf, n_ctx = 32768)+ assert out is not None+ assert out.gpu_bytes == 0+ assert out.total_bytes > 0+++class TestDraftCacheTypePrecedence:+ """extras beat the panel field beat the inherited environment.++ That is launch order: the field goes on argv, argv beats the LLAMA_ARG_* twin, and+ the extras are appended after argv and beat both. `_extra_args_draft_cache_types`+ falls back to the env by DEFAULT, so asking it once and then `or`-ing the field on+ gave the environment precedence over the control -- an inherited q4 priced against+ an f16 the child would really allocate, undercounting a context-scaled cache.+ """++ @pytest.fixture+ def spec(self, tmp_path, monkeypatch):+ target = _write_gguf(+ tmp_path, "qwen3", {**_GQA_FIELDS, "context_length": 262144}, name = "t.gguf"+ )+ drafter = tmp_path / "mtp.gguf"+ drafter.write_bytes(Path(target).read_bytes())+ drafter_bytes = drafter.stat().st_size++ # Varies with the draft pin, like the real one: the breakdown recovers the+ # drafter's size by re-pricing with the pin flipped, so a constant stub charges+ # no drafter at all and every assertion below would compare 0 with 0.+ def _files(+ cfg,+ *,+ llama_extra_args = None,+ **kw,+ ):+ pinned = _draft_on_cpu(list(llama_extra_args or ()))+ return 1.0 + (0.0 if pinned else drafter_bytes / 1024**3)++ monkeypatch.setattr(ri, "_gguf_resident_file_gb", _files)+ return target, SimpleNamespace(+ identifier = "org/Qwen3-8B",+ gguf_file = target,+ is_gguf = True,+ gguf_variant = None,+ gguf_mmproj_file = None,+ gguf_mtp_file = str(drafter),+ gguf_dspark_file = None,+ gguf_dflash_file = None,+ )++ def _bytes(+ self,+ spec,+ monkeypatch,+ *,+ env = None,+ field = None,+ extras = None,+ ):+ target, config = spec+ for key in ("LLAMA_ARG_SPEC_DRAFT_CACHE_TYPE_K", "LLAMA_ARG_SPEC_DRAFT_CACHE_TYPE_V"):+ monkeypatch.delenv(key, raising = False)+ if env:+ monkeypatch.setenv("LLAMA_ARG_SPEC_DRAFT_CACHE_TYPE_K", env)+ monkeypatch.setenv("LLAMA_ARG_SPEC_DRAFT_CACHE_TYPE_V", env)+ out = ri._gguf_memory_breakdown(+ config,+ target,+ n_ctx = 131072,+ spec_draft_cache_type = field,+ llama_extra_args = extras,+ )+ assert out is not None+ return out.drafter_runtime_bytes++ def test_the_panel_field_beats_an_inherited_value(self, spec, monkeypatch):+ # q4_0 is a quarter of f16, so the wrong precedence is unmissable.+ inherited_only = self._bytes(spec, monkeypatch, env = "q4_0")+ field_wins = self._bytes(spec, monkeypatch, env = "q4_0", field = "f16")+ assert field_wins > inherited_only++ def test_the_inherited_value_is_used_when_the_field_is_blank(self, spec, monkeypatch):+ plain = self._bytes(spec, monkeypatch)+ inherited = self._bytes(spec, monkeypatch, env = "q4_0")+ assert inherited < plain++ def test_the_extras_beat_both(self, spec, monkeypatch):+ field_only = self._bytes(spec, monkeypatch, env = "q4_0", field = "f16")+ extras_win = self._bytes(+ spec,+ monkeypatch,+ env = "q4_0",+ field = "f16",+ extras = ["--cache-type-k-draft", "q4_0", "--cache-type-v-draft", "q4_0"],+ )+ assert extras_win < field_only+++class TestTheTensorSplitLatchesAreHonoured:+ """load_model consults two in-process latches before it plans; so must the price.++ Both silently turn the launch into a layer split, and the two shapes cost different+ amounts: tensor replicates a flat buffer per device, a layer split multiplies the+ context-linear term instead. On two cards that is gigabytes apart, which is enough+ to move the verdict, so pricing tensor after a latch is set is a wrong number for a+ launch that will not happen.+ """++ @pytest.fixture+ def two_card(self, tmp_path, monkeypatch):+ gguf = _write_gguf(tmp_path, "qwen3", {**_GQA_FIELDS, "context_length": 262144})+ config = SimpleNamespace(+ identifier = "local/tensor",+ gguf_file = gguf,+ is_gguf = True,+ gguf_variant = None,+ gguf_mmproj_file = None,+ gguf_mtp_file = None,+ gguf_dspark_file = None,+ gguf_dflash_file = None,+ )+ monkeypatch.setattr(+ ri.LlamaCppBackend,+ "_find_llama_server_binary",+ staticmethod(lambda **kw: "/opt/llama/llama-server"),+ )+ return gguf, config++ def _priced(self, two_card, **kw):+ gguf, config = two_card+ return ri._gguf_memory_breakdown(+ config,+ gguf,+ n_ctx = 32768,+ tensor_parallel = True,+ n_devices = 2,+ tensor_split_possible = True,+ **kw,+ )++ def test_a_binary_that_refused_a_quantized_tensor_cache_is_priced_as_layer(+ self, two_card, monkeypatch+ ):+ as_tensor = self._priced(two_card, cache_type_kv = "q4_0")+ monkeypatch.setattr(+ ri.LlamaCppBackend,+ "_tensor_quant_kv_unsupported_binary",+ classmethod(lambda cls, *a, **k: True),+ )+ downgraded = self._priced(two_card, cache_type_kv = "q4_0")+ assert downgraded.compute_bytes != as_tensor.compute_bytes++ def test_a_model_that_aborted_on_tensor_this_session_is_priced_as_layer(+ self, two_card, monkeypatch+ ):+ as_tensor = self._priced(two_card, cache_type_kv = "f16")+ monkeypatch.setattr(+ ri.LlamaCppBackend,+ "_tensor_split_aborts",+ classmethod(lambda cls, *a, **k: True),+ )+ downgraded = self._priced(two_card, cache_type_kv = "f16")+ assert downgraded.compute_bytes != as_tensor.compute_bytes++ def test_no_latch_leaves_tensor_pricing_alone(self, two_card, monkeypatch):+ """The guard against the check firing on every load."""+ monkeypatch.setattr(+ ri.LlamaCppBackend,+ "_tensor_quant_kv_unsupported_binary",+ classmethod(lambda cls, *a, **k: False),+ )+ monkeypatch.setattr(+ ri.LlamaCppBackend,+ "_tensor_split_aborts",+ classmethod(lambda cls, *a, **k: False),+ )+ assert ri._tensor_latches_allow_a_split(two_card[0], two_card[1], "f16", None) is True++ def test_an_unresolvable_binary_fails_open(self, two_card, monkeypatch):+ monkeypatch.setattr(+ ri.LlamaCppBackend, "_find_llama_server_binary", staticmethod(lambda **kw: None)+ )+ assert ri._tensor_latches_allow_a_split(two_card[0], two_card[1], "f16", None) is True+++class TestInheritedRemoteFilesAreMarkedUnsized:+ """A file the child fetches, that this route may not fetch to weigh, is a floor.++ Both arrive through the environment and both are preserved for the launch:+ LLAMA_ARG_SPEC_DRAFT_HF_REPO (kept by _child_spec_env once the extras own the spec+ block) and LLAMA_ARG_MMPROJ_URL. Sizing either needs a network call this route is+ documented not to make, so the honest answer is a marked lower bound rather than a+ silently missing multi-gigabyte file.+ """++ @pytest.fixture+ def plain(self, tmp_path, monkeypatch):+ for key in (+ "LLAMA_ARG_SPEC_DRAFT_HF_REPO",+ "LLAMA_ARG_HFD_REPO",+ "LLAMA_ARG_MMPROJ_URL",+ ):+ monkeypatch.delenv(key, raising = False)+ gguf = _write_gguf(tmp_path, "qwen3", {**_GQA_FIELDS, "context_length": 262144})+ return gguf, SimpleNamespace(+ identifier = "local/plain",+ gguf_file = gguf,+ is_gguf = True,+ gguf_variant = None,+ gguf_mmproj_file = None,+ gguf_mtp_file = None,+ gguf_dspark_file = None,+ gguf_dflash_file = None,+ )++ def test_nothing_inherited_is_not_marked(self, plain):+ gguf, config = plain+ assert ri._gguf_memory_breakdown(config, gguf, n_ctx = 8192).drafter_kv_unsized is False++ @pytest.mark.parametrize("key", ["LLAMA_ARG_SPEC_DRAFT_HF_REPO", "LLAMA_ARG_HFD_REPO"])+ def test_an_inherited_remote_drafter_repo_is_marked(self, plain, monkeypatch, key):+ gguf, config = plain+ monkeypatch.setenv(key, "org/drafter-GGUF")+ out = ri._gguf_memory_breakdown(+ config, gguf, n_ctx = 8192, llama_extra_args = ["--spec-type", "draft-mtp"]+ )+ assert out.drafter_kv_unsized is True+ # Still an answer, not a refusal: a floor beats a blank row.+ assert out.total_bytes > 0++ def test_an_inherited_projector_url_is_marked(self, plain, monkeypatch):+ gguf, config = plain+ monkeypatch.setenv("LLAMA_ARG_MMPROJ_URL", "https://example.invalid/mmproj.gguf")+ assert ri._gguf_memory_breakdown(config, gguf, n_ctx = 8192).drafter_kv_unsized is True++ def test_a_projector_url_is_irrelevant_with_vision_off(self, plain, monkeypatch):+ gguf, config = plain+ monkeypatch.setenv("LLAMA_ARG_MMPROJ_URL", "https://example.invalid/mmproj.gguf")+ out = ri._gguf_memory_breakdown(config, gguf, n_ctx = 8192, disable_vision = True)+ assert out.drafter_kv_unsized is False+++class TestFourMoreLaunchNormalizations:+ """Each is a rule load_model applies before it sizes anything."""++ @pytest.fixture+ def basic(self, tmp_path):+ gguf = _write_gguf(tmp_path, "qwen3", {**_GQA_FIELDS, "context_length": 262144})+ return gguf, SimpleNamespace(+ identifier = "local/basic",+ gguf_file = gguf,+ is_gguf = True,+ gguf_variant = None,+ gguf_mmproj_file = None,+ gguf_mtp_file = None,+ gguf_dspark_file = None,+ gguf_dflash_file = None,+ )++ def test_a_gpu_pin_beats_a_stale_device_flag(self, basic):+ """The pin names cards; the launch strips whatever contradicted it.++ Without this, a --device none left in Advanced Arguments made a pinned load+ report no GPU footprint at all, which is the fit verdict inverted.+ """+ gguf, config = basic+ cpu_flag = ["--device", "none"]+ unpinned = ri._gguf_memory_breakdown(config, gguf, n_ctx = 8192, llama_extra_args = cpu_flag)+ pinned = ri._gguf_memory_breakdown(+ config, gguf, n_ctx = 8192, llama_extra_args = cpu_flag, device_pin_governs = True+ )+ assert unpinned.gpu_bytes == 0+ assert pinned.gpu_bytes > 0++ def test_a_remote_drafter_repo_is_not_listed_over_the_network(self, basic, monkeypatch):+ """Sizing it means an hf_model_info per settings change; the marker replaces it."""+ gguf, config = basic+ called = []+ monkeypatch.setattr(+ ri,+ "_remote_drafter_repo_bytes",+ lambda *a, **k: (called.append(1), 1 << 30)[1],+ )+ out = ri._gguf_memory_breakdown(+ config,+ gguf,+ n_ctx = 8192,+ llama_extra_args = ["--spec-draft-hf", "org/drafter-GGUF"],+ )+ assert called == [], "the Hub listing ran behind the panel"+ # Uncharged, but not unmentioned.+ assert out.drafter_kv_unsized is True++ @pytest.mark.parametrize(+ "caps,managed",+ [+ (+ {+ "found": True,+ "spec_draft_cache_k_flag": "-ctkd",+ "spec_draft_cache_v_flag": "-ctvd",+ },+ True,+ ),+ (+ {+ "found": True,+ "spec_draft_cache_k_flag": "-ctkd",+ "spec_draft_cache_v_flag": None,+ },+ False,+ ),+ (+ {+ "found": True,+ "spec_draft_cache_k_flag": None,+ "spec_draft_cache_v_flag": "-ctvd",+ },+ False,+ ),+ (+ {"found": False, "spec_draft_cache_k_flag": None, "spec_draft_cache_v_flag": None},+ True,+ ),+ ],+ )+ def test_the_draft_cache_field_needs_both_flags(self, tmp_path, monkeypatch, caps, managed):+ """The launcher emits the pair or neither, so one flag is not enough."""+ target = _write_gguf(+ tmp_path, "qwen3", {**_GQA_FIELDS, "context_length": 262144}, name = "t2.gguf"+ )+ drafter = tmp_path / "mtp2.gguf"+ drafter.write_bytes(Path(target).read_bytes())+ drafter_bytes = drafter.stat().st_size++ def _files(+ cfg,+ *,+ llama_extra_args = None,+ **kw,+ ):+ pinned = _draft_on_cpu(list(llama_extra_args or ()))+ return 1.0 + (0.0 if pinned else drafter_bytes / 1024**3)++ monkeypatch.setattr(ri, "_gguf_resident_file_gb", _files)+ monkeypatch.setattr(+ ri.LlamaCppBackend,+ "probe_server_capabilities",+ classmethod(lambda cls, *a, **k: {**caps, "mtp_token": "draft-mtp"}),+ )+ config = SimpleNamespace(+ identifier = "org/Qwen3-8B",+ gguf_file = target,+ is_gguf = True,+ gguf_variant = None,+ gguf_mmproj_file = None,+ gguf_mtp_file = str(drafter),+ gguf_dspark_file = None,+ gguf_dflash_file = None,+ )+ priced = ri._gguf_memory_breakdown(+ config, target, n_ctx = 131072, spec_draft_cache_type = "q4_0"+ )+ default = ri._gguf_memory_breakdown(config, target, n_ctx = 131072)+ # q4_0 is a quarter of the default f16, so "managed" is visible in the bytes.+ if managed:+ assert priced.drafter_runtime_bytes < default.drafter_runtime_bytes+ else:+ assert priced.drafter_runtime_bytes == default.drafter_runtime_bytes++ def test_slots_are_clamped_on_a_build_without_kv_unified(self, basic, monkeypatch):+ """load_model drops to one slot there, before it sizes anything."""+ gguf, config = basic+ monkeypatch.setattr(+ ri.LlamaCppBackend,+ "probe_server_capabilities",+ classmethod(lambda cls, *a, **k: {"found": True, "supports_kv_unified": False}),+ )+ out = ri._gguf_memory_breakdown(config, gguf, n_ctx = 8192, n_parallel = 4)+ assert out.n_parallel == 1++ def test_an_unprobed_build_keeps_the_requested_slots(self, basic, monkeypatch):+ """A probe that could not run is not evidence the flag is missing."""+ gguf, config = basic+ monkeypatch.setattr(+ ri.LlamaCppBackend,+ "probe_server_capabilities",+ classmethod(lambda cls, *a, **k: {"found": False, "supports_kv_unified": False}),+ )+ out = ri._gguf_memory_breakdown(config, gguf, n_ctx = 8192, n_parallel = 4)+ assert out.n_parallel == 4diff --git a/studio/backend/tests/test_memory_estimate_platforms.py b/studio/backend/tests/test_memory_estimate_platforms.pynew file mode 100644index 00000000000..2e7793beff0--- /dev/null+++ b/studio/backend/tests/test_memory_estimate_platforms.py@@ -0,0 +1,1239 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""The 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``;+* ``drafter_runtime_gpu_bytes <= drafter_runtime_bytes``;+* no field is ever negative;+* 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.+"""++from __future__ import annotations++import importlib.util as _ilu+import os+import platform as _platform+import sys+import types as _types+from pathlib import Path++import pytest++# Stub heavy / unavailable deps before importing the module under test.+# Copied from tests/test_memory_estimate.py -- same reasons, and+# tests/test_backend_tests_stub_heavy_imports.py enforces that it is here.++_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)+if _BACKEND_DIR not in sys.path:+ sys.path.insert(0, _BACKEND_DIR)++# loggers+_loggers_stub = _types.ModuleType("loggers")+_loggers_stub.get_logger = lambda name: __import__("logging").getLogger(name)+sys.modules.setdefault("loggers", _loggers_stub)++# structlog. Carries get_logger because this stub is process-wide: whichever test+# module is imported first wins the setdefault, and utils/prebuilt/freshness_flow+# calls structlog.get_logger at import time.+_structlog_stub = _types.ModuleType("structlog")+_structlog_stub.get_logger = lambda *a, **k: __import__("logging").getLogger("stub")+sys.modules.setdefault("structlog", _structlog_stub)++# httpx -- only stub when the real library is missing. Unconditional stubbing shadows+# HTTPError/Response that huggingface_hub.errors imports at load time.+try:+ import httpx as _httpx_real # noqa: F401+except ImportError:+ _httpx_stub = _types.ModuleType("httpx")+ for _exc_name in (+ "ConnectError",+ "TimeoutException",+ "ReadTimeout",+ "ReadError",+ "RemoteProtocolError",+ "CloseError",+ "HTTPError",+ "RequestError",+ ):+ setattr(_httpx_stub, _exc_name, type(_exc_name, (Exception,), {}))++ class _FakeTimeout:+ def __init__(self, *a, **kw):+ pass++ _httpx_stub.Timeout = _FakeTimeout+ _httpx_stub.Response = type("Response", (), {})+ _httpx_stub.Client = type(+ "Client",+ (),+ {+ "__init__": lambda self, **kw: None,+ "__enter__": lambda self: self,+ "__exit__": lambda self, *a: None,+ },+ )+ sys.modules["httpx"] = _httpx_stub++import asyncio # noqa: E402+from types import SimpleNamespace # noqa: E402++import core.inference.llama_cpp as llama_mod # noqa: E402+import routes.inference as ri # noqa: E402+from core.inference.llama_cpp import LlamaCppBackend # noqa: E402+from models.inference import EstimateMemoryRequest # noqa: E402++# The GGUF blob writer and the platform/accelerator tables are LOADED, not copied: a+# second copy of either drifts from the first, and then this file is asserting about+# bytes and hosts that no other test in the tree recognises. By path, because+# `tests` is not importable as a package name from every runner layout -- the idiom is+# test_llama_extra_args_platforms.py:26-33.+_TESTS_DIR = Path(__file__).resolve().parent++_kv_spec = _ilu.spec_from_file_location(+ "_kv_cache_estimation_for_platform_matrix", _TESTS_DIR / "test_kv_cache_estimation.py"+)+_kv_mod = _ilu.module_from_spec(_kv_spec)+_kv_spec.loader.exec_module(_kv_mod)+_make_gguf_bytes = _kv_mod._make_gguf_bytes++_plat_spec = _ilu.spec_from_file_location(+ "_llama_extra_args_platforms_for_memory_estimate",+ _TESTS_DIR / "test_llama_extra_args_platforms.py",+)+_plat_mod = _ilu.module_from_spec(_plat_spec)+_plat_spec.loader.exec_module(_plat_mod)++# (label, sys.platform, os.name, WSL-shaped release or None) -- linux / wsl2 / windows / macos.+PLATFORMS = _plat_mod.PLATFORMS+# Moves sys.platform and the WSL markers, and deliberately NOT os.name; see its docstring+# and the note on _apply_cell below.+_apply_platform = _plat_mod._apply_platform++_GIB = 1024**3++# platform.system() per platform label. The estimate reaches it through+# utils.hardware.is_apple_silicon, which is `system() == "Darwin" and machine() == "arm64"`.+_SYSTEM = {"linux": "Linux", "wsl2": "Linux", "windows": "Windows", "macos": "Darwin"}+++# A. The accelerator table+++# The upstream table by label, so a rename there fails here loudly instead of silently+# re-pointing a cell at the wrong hardware.+_UPSTREAM_ACCELERATORS = {+ label: (vulkan, memory) for label, vulkan, memory in _plat_mod.ACCELERATORS+}++# (label, vulkan, [(index, free_mib, total_mib)]). The four upstream entries reused+# verbatim, plus the two this file adds:+#+# 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.+ACCELERATORS = [+ ("nvidia-single", *_UPSTREAM_ACCELERATORS["nvidia-single"]),+ ("nvidia-multi", *_UPSTREAM_ACCELERATORS["nvidia-multi"]),+ ("amd-rocm", False, [(0, 12_000, 16_000)]),+ ("amd-vulkan", *_UPSTREAM_ACCELERATORS["amd-vulkan"]),+ ("apple-unified", False, [(0, 40_000, 65_536)]),+ ("cpu-only", *_UPSTREAM_ACCELERATORS["cpu-only"]),+]++_UNIFIED = "apple-unified"+_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.+ """+ return accelerator_label != _UNIFIED or platform_label == "macos"+++MATRIX = [+ pytest.param(p, a, id = f"{p[0]}-{a[0]}")+ for p in PLATFORMS+ for a in ACCELERATORS+ if _reachable(p[0], a[0])+]++# 4 platforms x 6 accelerators, minus apple-unified on the three non-Darwin platforms.+assert len(MATRIX) == 4 * 6 - 3 == 21+++# B. Applying a cell+++def _snapshot(memory) -> tuple:+ """A ``main._system_gpu_cache`` shaped exactly as main.py fills it.++ Patched at the SOURCE rather than over ``_cached_inference_devices``, so the cell+ exercises the real reader -- including the "not `or None`" rule that keeps an empty+ probed list distinct from an unfilled snapshot, which is the whole mechanism behind+ the CPU-only placement.+ """+ devices = [+ {"index": index, "memory_total_gb": round(total / 1024, 2), "vram_free_gb": free / 1024}+ for index, free, total in memory+ ]+ inference_gpu = {"available": bool(devices), "devices": devices}+ return (0.0, ({"available": bool(devices), "devices": devices}, inference_gpu))+++def _apply_cell(monkeypatch, platform_row, accelerator_row) -> None:+ """Move every host-shaped seam this endpoint reads, and nothing else.++ NEVER ``os.name``: it swaps pathlib's flavour mid-run, the synthetic GGUFs on+ tmp_path stop resolving, and every byte asserted below becomes a claim about a file+ that was never opened. Documented at test_llama_extra_args_platforms.py:59-63 and+ test_slot_refit_platform_matrix.py:107. ``sys.platform``, ``platform.system()``,+ ``platform.machine()`` and WSL_DISTRO_NAME are the whole toolkit.+ """+ platform_label = platform_row[0]+ accelerator_label, vulkan, memory = accelerator_row++ # sys.platform + the WSL markers, through the harness that already owns them.+ _apply_platform(monkeypatch, platform_row)+ # The modules under test alias `sys` by `import sys`, so the object patched above is+ # the object they read. Asserted rather than assumed: a future `from sys import+ # platform` in either module would silently take this whole matrix off the branch it+ # believes it is testing, and nothing else would notice.+ assert ri.sys is sys and llama_mod.sys is sys++ apple = accelerator_label == _UNIFIED+ monkeypatch.setattr(_platform, "system", lambda: _SYSTEM[platform_label], raising = False)+ monkeypatch.setattr(+ _platform,+ "machine",+ lambda: "arm64" if apple else ("AMD64" if platform_label == "windows" else "x86_64"),+ raising = False,+ )++ # The probed inference inventory, through main.py's own snapshot shape.+ monkeypatch.setitem(sys.modules, "main", SimpleNamespace(_system_gpu_cache = _snapshot(memory)))++ # The llama.cpp build flavour and the CUDA-visible count.+ monkeypatch.setattr(+ LlamaCppBackend, "_is_vulkan_backend", staticmethod(lambda binary = None: vulkan)+ )+ monkeypatch.setattr(+ LlamaCppBackend,+ "_effective_gpu_count",+ staticmethod(+ lambda gpu_indices = None: len(gpu_indices) if gpu_indices is not None else len(memory)+ ),+ )++ # ROCm's own marker. Nothing on the estimate path branches on it today -- the+ # estimator sees a HIP host and a CUDA host identically, and only `vulkan` and the+ # device count move it -- so the amd-rocm cell's real job is to hold that true.+ monkeypatch.setattr(+ "utils.hardware.hardware.IS_ROCM", accelerator_label == "amd-rocm", raising = False+ )+ for mask in ("HIP_VISIBLE_DEVICES", "ROCR_VISIBLE_DEVICES", "CUDA_VISIBLE_DEVICES"):+ monkeypatch.delenv(mask, raising = False)+ # A GGML/LLAMA_ARG_* value inherited from the runner's shell would be read as the+ # user's own setting and price a load nobody configured.+ for inherited in (+ "LLAMA_ARG_CTX_SIZE",+ "LLAMA_ARG_MMPROJ",+ "LLAMA_ARG_SPEC_DRAFT_MODEL",+ "LLAMA_ARG_SPEC_DRAFT_CACHE_TYPE_K",+ "LLAMA_ARG_SPEC_DRAFT_CACHE_TYPE_V",+ "LLAMA_ARG_SPLIT_MODE",+ "LLAMA_ARG_DEVICE",+ ):+ monkeypatch.delenv(inherited, raising = False)++ # The llama-server binary. Pinned for two reasons, and the second one 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.+ # * 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.+ monkeypatch.setattr(+ LlamaCppBackend,+ "_find_llama_server_binary",+ staticmethod(+ lambda **kw: (+ "C:\\llama.cpp\\llama-server.exe"+ if platform_label == "windows"+ else "/opt/llama.cpp/llama-server"+ )+ ),+ )++ # The capability probe shells out to llama-server --help. Pinned so a cell's numbers+ # come from the header and the flags, not from whichever binary this runner has.+ monkeypatch.setattr(+ LlamaCppBackend,+ "probe_server_capabilities",+ classmethod(+ lambda cls, binary = None: {+ "found": True,+ "supports_mtp": True,+ "spec_draft_cache_k_flag": True,+ "spec_draft_cache_v_flag": True,+ "spec_draft_n_max_flag": "--spec-draft-n-max",+ }+ ),+ )++[email protected](autouse = True)+def _clear_estimate_caches():+ """Both module caches are TTL'd, not per-request, so they leak across cells.++ ``_estimate_files_cache`` is keyed on the config and NOT on the context, which is+ the behaviour under test elsewhere -- so an entry left by another cell would satisfy+ an assertion here that the cell never actually computed.+ """+ ri._estimate_files_cache.clear()+ ri._estimate_config_cache.clear()+ yield+ ri._estimate_files_cache.clear()+ ri._estimate_config_cache.clear()++[email protected](autouse = True)+def _metal_budget_tripwire(monkeypatch):+ """NOTHING on this path may call ``_apple_metal_memory_budget_bytes``.++ Its body is a bare ``import mlx.core`` (core/inference/llama_cpp.py:7816). On macOS,+ importing MLX after torch has been imported aborts the process at the C level, and a+ C-level abort is not an exception: no ``try``/``except`` anywhere up the stack can+ catch it. ``/api/inference/estimate-memory`` fires on every tick of the context+ slider, so one reachable call there is a settings panel that kills the server.++ Recorded rather than raised, because a raise would be swallowed by one of the broad+ ``except Exception`` handlers on this path and the tripwire would report nothing.+ The recorder returns 0, which is the off-Apple-Silicon answer, so a cell that DOES+ reach it still completes and is still reported.+ """+ calls: list[str] = []++ def _tripwire() -> int:+ calls.append("reached")+ return 0++ monkeypatch.setattr(+ LlamaCppBackend, "_apple_metal_memory_budget_bytes", staticmethod(_tripwire)+ )+ yield calls+ assert calls == [], (+ "the memory estimate reached LlamaCppBackend._apple_metal_memory_budget_bytes "+ f"{len(calls)} time(s). That function imports mlx.core, which aborts the process "+ "at the C level on macOS once torch is loaded, and this endpoint runs on every "+ "settings change."+ )+++# C. The model shapes+++# Realistic geometry. The numbers matter: at 32k the KV cache here is larger than the+# weights, which is the regime the whole feature exists for and the one where a paired+# subtraction that has come unpaired is visible rather than lost in rounding.+_GQA_FIELDS = {+ "context_length": 262144,+ "block_count": 32,+ "attention.head_count": 32,+ "attention.head_count_kv": 8,+ "attention.key_length": 128,+ "attention.value_length": 128,+ "embedding_length": 4096,+ "feed_forward_length": 12288,+ "vocab_size": 152064,+}++# Sparse padding. _get_gguf_size_bytes is a stat(), so truncate() gives a 3 GiB weights+# file that costs no disk. Without it every file is a few hundred bytes, the GB-scale+# float in the files term rounds them to noise, and "weights do not move with the+# context" would pass on numbers too small to have moved.+_WEIGHTS_BYTES = 3 * _GIB+_PROJECTOR_BYTES = 600 * 1024 * 1024+_DRAFTER_BYTES = 400 * 1024 * 1024+# What "costs no disk" is worth on the runner that does not agree. POSIX gives a hole+# for free; NTFS allocates and zero-fills every byte unless the file is marked sparse+# FIRST, so twelve of these filled a Windows runner's disk and every cell in this file+# errored with ENOSPC. The flag is asked for below; this is what the fixture falls back+# to when it cannot be set, which keeps the shapes GB-scale without the 34 GB.+_DENSE_PAD_DIVISOR = 12+++def _try_make_sparse(handle) -> bool:+ """Mark an open file sparse. True on any filesystem that needs no marking.++ Windows only: FSCTL_SET_SPARSE has to be issued before the file is extended, or+ the extension is already committed. Everything else holes-punches on truncate().+ """+ # FORCE_DENSE_PAD is how the fallback below gets exercised at all: it is the arm+ # only Windows takes, and a POSIX box would otherwise never run the code that this+ # file's own ENOSPC on a Windows runner is the reason for.+ if os.name != "nt" and not os.environ.get("FORCE_DENSE_PAD"):+ return True+ try:+ import ctypes+ import msvcrt++ _FSCTL_SET_SPARSE = 0x000900C4+ returned = ctypes.c_ulong(0)+ return bool(+ ctypes.windll.kernel32.DeviceIoControl(+ ctypes.c_void_p(msvcrt.get_osfhandle(handle.fileno())),+ _FSCTL_SET_SPARSE,+ None,+ 0,+ None,+ 0,+ ctypes.byref(returned),+ None,+ )+ )+ except Exception:+ return False+++def _pad_to(path: Path, pad: int) -> None:+ """Extend `path` to `pad` bytes without paying for them where that is possible."""+ with open(path, "r+b") as handle:+ if not _try_make_sparse(handle):+ pad = max(len(handle.read()), pad // _DENSE_PAD_DIVISOR)+ handle.truncate(pad)+++def _write_gguf(directory: Path, name: str, arch: str, fields: dict, *, pad: int) -> str:+ kv = {"general.architecture": arch}+ kv.update({f"{arch}.{k}": v for k, v in fields.items()})+ path = directory / name+ path.write_bytes(_make_gguf_bytes(arch, kv))+ if pad:+ _pad_to(path, pad)+ return str(path)+++def _config(gguf_path: str, **overrides) -> SimpleNamespace:+ fields = dict(+ identifier = "local/model",+ gguf_file = gguf_path,+ is_gguf = True,+ gguf_variant = None,+ gguf_mmproj_file = None,+ gguf_mtp_file = None,+ gguf_dspark_file = None,+ gguf_dflash_file = None,+ is_vision = False,+ )+ fields.update(overrides)+ return SimpleNamespace(**fields)++[email protected](scope = "module")+def shapes(tmp_path_factory):+ """Every model shape the estimator has a distinct arm for, built once.++ Module scope because these are ten sparse files and twenty-one cells; per-test+ rebuild is pure overhead, and nothing below mutates them.+ """+ root = tmp_path_factory.mktemp("platform-matrix-shapes")+ built: dict[str, tuple[str, SimpleNamespace]] = {}++ gqa = _write_gguf(root, "gqa.gguf", "qwen3", _GQA_FIELDS, pad = _WEIGHTS_BYTES)+ built["gqa"] = (gqa, _config(gqa))++ # MLA: a compressed latent cache, priced off kv_lora_rank rather than the head dims.+ mla = _write_gguf(+ root,+ "mla.gguf",+ "deepseek2",+ {+ **_GQA_FIELDS,+ "attention.kv_lora_rank": 512,+ "attention.key_length_mla": 576,+ "attention.value_length_mla": 512,+ },+ pad = _WEIGHTS_BYTES,+ )+ built["mla"] = (mla, _config(mla))++ # SWA: the cache is capped by the window, so kv_bytes plateaus in n_ctx instead of+ # growing -- which is why the monotonicity invariant below is non-decreasing.+ swa = _write_gguf(+ root,+ "swa.gguf",+ "gemma3",+ {**_GQA_FIELDS, "attention.sliding_window": 1024},+ pad = _WEIGHTS_BYTES,+ )+ built["swa"] = (swa, _config(swa))++ # Hybrid Mamba: attention every full_attention_interval layers, recurrent state on+ # the rest. Both terms are charged, from different formulas.+ hybrid = _write_gguf(+ root,+ "hybrid.gguf",+ "granitehybrid",+ {+ **_GQA_FIELDS,+ "ssm.inner_size": 8192,+ "ssm.state_size": 128,+ "ssm.group_count": 8,+ "ssm.conv_kernel": 4,+ "full_attention_interval": 4,+ },+ pad = _WEIGHTS_BYTES,+ )+ built["hybrid_mamba"] = (hybrid, _config(hybrid))++ # Pure SSM: block_count and embedding_length, no attention dims. NOT a degenerate+ # stub -- llama.cpp reads the attention head counts with required=false+ # (src/llama-model.cpp:1306 region) while block_count is required, so every Mamba,+ # Mamba2 and RWKV model loads exactly like this. It is the kv_estimable=False path+ # for a whole family of real models.+ ssm = _write_gguf(+ root,+ "pure-ssm.gguf",+ "mamba",+ {+ "block_count": 48,+ "embedding_length": 2048,+ "context_length": 8192,+ "ssm.conv_kernel": 4,+ "ssm.inner_size": 4096,+ "ssm.state_size": 16,+ "ssm.time_step_rank": 128,+ },+ pad = _WEIGHTS_BYTES,+ )+ built["pure_ssm"] = (ssm, _config(ssm))++ # NextN / embedded MTP: a drafter with no file, whose draft cache is still allocated.+ nextn = _write_gguf(+ root,+ "nextn.gguf",+ "qwen3",+ {**_GQA_FIELDS, "nextn_predict_layers": 2},+ pad = _WEIGHTS_BYTES,+ )+ built["nextn_mtp"] = (nextn, _config(nextn))++ # Embedding model: a pooling type llama-server launches with --embedding, which caps+ # the batch at the micro-batch and gives every slot an output buffer.+ embedding = _write_gguf(+ root,+ "embedding.gguf",+ "bert",+ {**_GQA_FIELDS, "context_length": 8192, "pooling_type": 2},+ pad = _WEIGHTS_BYTES,+ )+ built["embedding"] = (embedding, _config(embedding, identifier = "local/embed-model"))++ # Vision: a target plus a projector file, which is charged AND carries encoder+ # buffers of its own on top of the file.+ vision = _write_gguf(root, "vision.gguf", "qwen3", _GQA_FIELDS, pad = _WEIGHTS_BYTES)+ projector = _write_gguf(+ root, "mmproj-vision.gguf", "clip", {"has_vision_encoder": 1}, pad = _PROJECTOR_BYTES+ )+ built["vision_projector"] = (+ vision,+ _config(vision, gguf_mmproj_file = projector, is_vision = True),+ )++ # A separate drafter sidecar: its own file in the weights AND its own KV on top.+ target = _write_gguf(root, "spec-target.gguf", "qwen3", _GQA_FIELDS, pad = _WEIGHTS_BYTES)+ drafter = _write_gguf(+ root,+ "mtp-draft.gguf",+ "qwen3",+ {**_GQA_FIELDS, "block_count": 2},+ pad = _DRAFTER_BYTES,+ )+ built["mtp_drafter"] = (target, _config(target, gguf_mtp_file = drafter))++ # Truncated: a real file with an unreadable header. The parser raises, and the+ # caller must still produce a well-formed answer rather than a partial number.+ truncated = root / "truncated.gguf"+ truncated.write_bytes(b"GGUF\x03\x00\x00\x00 truncated, nothing further is readable")+ _pad_to(truncated, _WEIGHTS_BYTES)+ built["truncated_header"] = (str(truncated), _config(str(truncated)))++ return built+++# Shapes that carry a drafter the mode has to be told about; everything else prices the+# same under the default (auto) mode.+_SPEC_SHAPES = {"mtp_drafter": "mtp"}++SHAPE_NAMES = [+ "gqa",+ "mla",+ "swa",+ "hybrid_mamba",+ "pure_ssm",+ "nextn_mtp",+ "embedding",+ "vision_projector",+ "mtp_drafter",+ "truncated_header",+]++# 4k / 32k / 128k. Three points, because two cannot distinguish "grew" from "grew then+# fell back", and the weights term has to hold still across all of them.+CONTEXTS = (4096, 32768, 131072)+++# D. Driving the real route+++def _price(shapes, shape_name: str, **kwargs):+ """The real ``POST /api/inference/estimate-memory`` handler, auth dependency aside.++ The route, not ``_gguf_memory_breakdown``, because the invariants below are claims+ about the RESPONSE: a breakdown that sums correctly and a route that drops one of+ its terms on the way into the model are different bugs, and only this call sees the+ second one.+ """+ gguf_path, config = shapes[shape_name]+ spec = _SPEC_SHAPES.get(shape_name)+ if spec is not None:+ kwargs.setdefault("speculative_type", spec)+ request = EstimateMemoryRequest(model_path = gguf_path, **kwargs)++ # Only the config resolution is replaced: it is the one step that can reach the+ # network, and it is not what any of this is about.+ original = ri._cached_estimate_config+ ri._cached_estimate_config = lambda *a, **kw: config+ try:+ return asyncio.run(+ ri.estimate_memory(request, fastapi_request = None, current_subject = "test")+ )+ finally:+ ri._cached_estimate_config = original+++_ITEMS = (+ "weights_bytes",+ "kv_bytes",+ "compute_bytes",+ "drafter_runtime_bytes",+ "projector_runtime_bytes",+)++_NON_NEGATIVE = (*_ITEMS, "drafter_runtime_gpu_bytes", "total_bytes", "gpu_bytes", "n_ctx")+++def _itemized_sum(response) -> int:+ """The itemization, summed. FIVE terms, not four.++ The PR body says "the four items now sum to Total exactly". That is true of every+ shape without a vision projector and false of every shape with one:+ ``projector_runtime_bytes`` is a fifth line, it is inside ``total_bytes``+ (routes/inference.py, ``runtime_bytes``), and the panel renders it as its own row+ (model-config-page.tsx:1103). Summing four here would have made the vision cell+ fail by exactly the projector's buffers, which is a wrong test rather than a found+ bug -- so the sum is five, and the four-term claim is checked separately, once, in+ test_platform_matrix_the_itemization_is_five_terms_not_four.+ """+ return sum(getattr(response, item) for item in _ITEMS)+++def _assert_core_invariants(+ response,+ *,+ cell: str,+ shape: str,+ note: str = "",+) -> None:+ """Everything that must hold of any answer, on any host, for any model."""+ where = f"[{cell}] {shape}{' ' + note if note else ''}"++ assert response.available is True, f"{where}: {response.reason}"++ for field in _NON_NEGATIVE:+ assert getattr(response, field) >= 0, f"{where}: {field} is {getattr(response, field)}"++ assert _itemized_sum(response) == response.total_bytes, (+ f"{where}: the itemization does not sum to the total. "+ f"weights={response.weights_bytes} kv={response.kv_bytes} "+ f"compute={response.compute_bytes} drafter={response.drafter_runtime_bytes} "+ f"projector={response.projector_runtime_bytes} "+ f"sum={_itemized_sum(response)} total={response.total_bytes} "+ f"(delta {response.total_bytes - _itemized_sum(response)})"+ )++ assert response.gpu_bytes <= response.total_bytes, (+ f"{where}: gpu_bytes {response.gpu_bytes} exceeds total_bytes "+ f"{response.total_bytes} -- the GPU share cannot be more than everything"+ )++ assert response.drafter_runtime_gpu_bytes <= response.drafter_runtime_bytes, (+ f"{where}: drafter_runtime_gpu_bytes {response.drafter_runtime_gpu_bytes} exceeds "+ f"drafter_runtime_bytes {response.drafter_runtime_bytes}"+ )++ if not response.kv_estimable:+ # kv_bytes == 0 here means UNKNOWN, and the flag is the only thing separating it+ # from a genuine zero.+ assert response.kv_bytes == 0, f"{where}: unsizable KV reported {response.kv_bytes} bytes"+ assert response.compute_bytes == 0, f"{where}: unsizable KV priced compute buffers"+++# E. The matrix++[email protected]("platform,accelerator", MATRIX)+def test_platform_matrix_every_shape_is_internally_consistent(+ monkeypatch, shapes, platform, accelerator+):+ """One cell, every model shape, every context: the answer holds together.++ This is the bulk of the matrix -- 10 shapes x 3 contexts per cell -- and it asserts+ only properties, never magnitudes. A sum that is off by one byte, a GPU share above+ the total, or a negative field is caught here on whichever host produced it.+ """+ _apply_cell(monkeypatch, platform, accelerator)+ cell = f"{platform[0]}-{accelerator[0]}"++ for shape in SHAPE_NAMES:+ for n_ctx in CONTEXTS:+ ri._estimate_files_cache.clear()+ response = _price(shapes, shape, n_ctx = n_ctx)+ _assert_core_invariants(response, cell = cell, shape = shape, note = f"n_ctx={n_ctx}")++[email protected]("platform,accelerator", MATRIX)+def test_platform_matrix_weights_do_not_move_with_the_context_slider(+ monkeypatch, shapes, platform, accelerator+):+ """The load-bearing one.++ ``weights_bytes`` is not measured. It is derived by subtracting the context term+ back out of ``_estimate_gguf_required_gb``, so it is only correct while the term+ subtracted is the same term that was added. Any drift as ``n_ctx`` moves means the+ two arms have come unpaired, and the weights row silently absorbs part of the KV+ cache -- in either direction, on any host.+ """+ _apply_cell(monkeypatch, platform, accelerator)+ cell = f"{platform[0]}-{accelerator[0]}"++ for shape in SHAPE_NAMES:+ weights: list[int] = []+ kv: list[int] = []+ for n_ctx in CONTEXTS:+ ri._estimate_files_cache.clear()+ response = _price(shapes, shape, n_ctx = n_ctx)+ weights.append(response.weights_bytes)+ kv.append(response.kv_bytes)++ assert len(set(weights)) == 1, (+ f"[{cell}] {shape}: weights_bytes moved with the context slider: "+ f"{dict(zip(CONTEXTS, weights))}. The weights term is a subtraction; if it "+ f"moves, the term added and the term removed are no longer the same bytes."+ )+ # Non-decreasing, not strictly increasing: a sliding-window cache is capped by+ # its window and legitimately plateaus, and an unsizable one stays at 0.+ assert kv == sorted(+ kv+ ), f"[{cell}] {shape}: kv_bytes is not non-decreasing in n_ctx: {dict(zip(CONTEXTS, kv))}"++[email protected]("platform,accelerator", MATRIX)+def test_platform_matrix_settings_do_not_break_the_itemization(+ monkeypatch, shapes, platform, accelerator+):+ """The settings a user actually moves, on every host.++ Each of these reaches a different arm: the cache dtype rescales the KV term, slots+ rescale both KV and the compute buffers, ``--no-kv-offload`` moves the cache out of+ the GPU figure without leaving the total, manual layers rescale only the main+ weight, and a tensor split replicates the flat buffers per device. The invariants+ are the same ones; the point is that no setting breaks them.+ """+ _apply_cell(monkeypatch, platform, accelerator)+ cell = f"{platform[0]}-{accelerator[0]}"++ settings = [+ ("f16 cache", dict(cache_type_kv = "f16")),+ ("q4_0 cache", dict(cache_type_kv = "q4_0")),+ ("4 slots", dict(n_parallel = 4)),+ ("no-kv-offload", dict(llama_extra_args = ["-nkvo"])),+ ("manual 0 layers", dict(gpu_memory_mode = "manual", gpu_layers = 0)),+ ("manual all layers", dict(gpu_memory_mode = "manual", gpu_layers = 999)),+ ("tensor split", dict(tensor_parallel = True, selected_gpu_ids = [0, 1])),+ ("checkpoints", dict(ctx_checkpoints = 8)),+ ("draft depth", dict(spec_draft_n_max = 8, spec_draft_cache_type = "q8_0")),+ ("vision off", dict(disable_vision = True)),+ ("native context", dict(n_ctx = 0)),+ ]++ for shape in ("gqa", "swa", "pure_ssm", "vision_projector", "mtp_drafter"):+ for note, kwargs in settings:+ ri._estimate_files_cache.clear()+ kwargs = {"n_ctx": 32768, **kwargs}+ response = _price(shapes, shape, **kwargs)+ _assert_core_invariants(response, cell = cell, shape = shape, note = note)++[email protected]("platform,accelerator", MATRIX)+def test_platform_matrix_an_offloaded_byte_is_never_a_freed_byte(+ monkeypatch, shapes, platform, accelerator+):+ """Moving bytes off the GPU changes where they are, never how many there are.++ ``total_bytes`` is aggregate memory: GPU, host RAM or a unified pool. So+ ``--gpu-layers 0`` and ``--no-kv-offload`` may only ever move bytes out of+ ``gpu_bytes``; a total that shrinks with them is the panel telling a user that+ offloading made memory disappear.++ On the apple-unified cell this is the entire claim rather than a nicety: there is+ one pool, so a byte moved off the GPU is still occupying the same RAM. A row that+ reported a smaller total under an offload would be advertising headroom that does+ not exist on the machine that has the least of it.+ """+ _apply_cell(monkeypatch, platform, accelerator)+ cell = f"{platform[0]}-{accelerator[0]}"++ for shape in ("gqa", "vision_projector", "mtp_drafter", "nextn_mtp"):+ ri._estimate_files_cache.clear()+ resident = _price(shapes, shape, n_ctx = 32768)++ for note, kwargs in (+ ("manual 0 layers", dict(gpu_memory_mode = "manual", gpu_layers = 0)),+ ("no-kv-offload", dict(llama_extra_args = ["-nkvo"])),+ ("no-mmproj-offload", dict(llama_extra_args = ["--no-mmproj-offload"])),+ ("cpu device", dict(llama_extra_args = ["--device", "none"])),+ ):+ ri._estimate_files_cache.clear()+ offloaded = _price(shapes, shape, n_ctx = 32768, **kwargs)+ _assert_core_invariants(offloaded, cell = cell, shape = shape, note = note)++ assert offloaded.total_bytes == resident.total_bytes, (+ f"[{cell}] {shape} under {note}: total_bytes fell from "+ f"{resident.total_bytes} to {offloaded.total_bytes}. Offloading moves "+ f"bytes between pools; it does not free them, and on unified memory "+ f"there is only one pool to move them within."+ )+ assert offloaded.gpu_bytes <= resident.gpu_bytes, (+ f"[{cell}] {shape} under {note}: gpu_bytes ROSE from "+ f"{resident.gpu_bytes} to {offloaded.gpu_bytes}"+ )++[email protected]("platform,accelerator", MATRIX)+def test_platform_matrix_a_probed_empty_inventory_shows_no_gpu_footprint(+ monkeypatch, shapes, platform, accelerator+):+ """``gpu_bytes == 0`` exactly on the cells that have no GPU, and only those.++ A probe that RAN and found nothing is the evidence; an unfilled snapshot is not+ absence, and the CUDA count is zero on every Vulkan and ROCm-via-Vulkan host that+ has plenty of GPU. Getting this wrong put a multi-gigabyte GPU figure against a+ capacity of zero on CPU-only Linux and Windows boxes.+ """+ _apply_cell(monkeypatch, platform, accelerator)+ cell = f"{platform[0]}-{accelerator[0]}"+ cpu_only = accelerator[0] == _CPU_ONLY++ for shape in ("gqa", "pure_ssm", "vision_projector"):+ ri._estimate_files_cache.clear()+ response = _price(shapes, shape, n_ctx = 32768)+ _assert_core_invariants(response, cell = cell, shape = shape)++ if cpu_only:+ assert response.gpu_bytes == 0, (+ f"[{cell}] {shape}: a probed-empty inventory still reported "+ f"{response.gpu_bytes} GPU bytes"+ )+ assert response.drafter_runtime_gpu_bytes == 0, f"[{cell}] {shape}"+ # Still a real load, just not one on a card.+ assert response.total_bytes > 0, f"[{cell}] {shape}"+ else:+ assert response.gpu_bytes > 0, (+ f"[{cell}] {shape}: a probed inventory with {len(accelerator[2])} "+ f"device(s) reported no GPU footprint at all"+ )++[email protected]("platform,accelerator", MATRIX)+def test_platform_matrix_an_unsizable_kv_still_carries_its_layer_count(+ monkeypatch, shapes, platform, accelerator+):+ """A pure-SSM header sizes no cache and must still report ``block_count``.++ llama.cpp reads the attention head counts with ``required = false`` while+ ``block_count`` is required, so every Mamba, Mamba2 and RWKV model reaches this path+ legitimately. Without the layer count ``_gguf_offloaded_layer_fraction`` has no+ denominator, answers 1.0, and a manual ``--gpu-layers 0`` on that whole family reads+ as a fully GPU-resident load -- the direction that calls an impossible load a fit.+ """+ _apply_cell(monkeypatch, platform, accelerator)+ cell = f"{platform[0]}-{accelerator[0]}"++ ri._estimate_files_cache.clear()+ response = _price(shapes, "pure_ssm", n_ctx = 131072)+ assert response.kv_estimable is False, f"[{cell}]"+ assert response.layer_count == 48, (+ f"[{cell}] pure_ssm: kv_estimable is False and layer_count is "+ f"{response.layer_count}; without it the offload split has no denominator"+ )++ # And the count is load-bearing, not decorative: it is what makes -ngl 0 read as a+ # CPU load rather than a GPU-resident one.+ ri._estimate_files_cache.clear()+ pinned = _price(shapes, "pure_ssm", n_ctx = 131072, gpu_memory_mode = "manual", gpu_layers = 0)+ _assert_core_invariants(pinned, cell = cell, shape = "pure_ssm", note = "-ngl 0")+ assert (+ pinned.gpu_bytes == 0+ ), f"[{cell}] pure_ssm at --gpu-layers 0 reported {pinned.gpu_bytes} GPU bytes"++[email protected]("platform,accelerator", MATRIX)+def test_platform_matrix_an_unreadable_header_answers_without_inventing_a_cache(+ monkeypatch, shapes, platform, accelerator+):+ """A truncated GGUF: a well-formed "cannot size this", never a partial number."""+ _apply_cell(monkeypatch, platform, accelerator)+ cell = f"{platform[0]}-{accelerator[0]}"++ ri._estimate_files_cache.clear()+ response = _price(shapes, "truncated_header", n_ctx = 131072)+ _assert_core_invariants(response, cell = cell, shape = "truncated_header")+ assert response.kv_estimable is False, f"[{cell}]"+ assert response.n_ctx == 0, f"[{cell}]: priced a context off a header it could not read"+ # No block_count to recover: unlike the pure-SSM case above, this header carries+ # nothing at all. See the pinned gap below for what that costs.+ assert response.layer_count is None, f"[{cell}]"+++# F. The claims this file exists to check independently+++def test_platform_matrix_the_itemization_is_five_terms_not_four(monkeypatch, shapes):+ """The PR body's "the four items now sum to Total exactly" is one term short.++ Four terms do sum to the total on every shape without a vision projector. With one,+ ``projector_runtime_bytes`` is a fifth line -- inside ``total_bytes``, rendered as+ its own row by the panel -- and the four-term sum misses it by exactly the encoder's+ buffers. Pinned here so the wording and the arithmetic cannot drift apart again:+ the arithmetic is right, the sentence is stale.+ """+ _apply_cell(monkeypatch, PLATFORMS[0], ACCELERATORS[0])++ ri._estimate_files_cache.clear()+ plain = _price(shapes, "gqa", n_ctx = 32768)+ four = plain.weights_bytes + plain.kv_bytes + plain.compute_bytes + plain.drafter_runtime_bytes+ assert plain.projector_runtime_bytes == 0+ assert four == plain.total_bytes++ ri._estimate_files_cache.clear()+ vision = _price(shapes, "vision_projector", n_ctx = 32768)+ four = (+ vision.weights_bytes + vision.kv_bytes + vision.compute_bytes + vision.drafter_runtime_bytes+ )+ assert vision.projector_runtime_bytes > 0+ assert four + vision.projector_runtime_bytes == vision.total_bytes+ assert four != vision.total_bytes, (+ "the projector term is no longer outside the four-item sum; if it has been "+ "folded into another line, this test and the PR body should both say four"+ )++[email protected]("platform,accelerator", MATRIX)+def test_platform_matrix_the_metal_budget_is_never_reached(+ monkeypatch, shapes, platform, accelerator, _metal_budget_tripwire+):+ """The tripwire, asserted per cell rather than reasoned about.++ Driven hard on purpose: every shape, the Apple-shaped context settings, and the+ paravirtual detector deliberately RESTORED. The backend conftest pins+ ``_metal_device_is_paravirtual`` to False on both ``core.inference.llama_cpp`` and+ ``routes.inference`` (tests/conftest.py:296-314) so the suite is host independent,+ which also masks whichever Apple arms consult it. On the apple-unified cell that+ would be assuming the answer, so it is put back -- both values -- and the tripwire+ is asked again with it live.+ """+ _apply_cell(monkeypatch, platform, accelerator)+ apple = accelerator[0] == _UNIFIED++ if apple:+ # is_apple_silicon() is already True on this cell (Darwin + arm64), which is the+ # ONLY gate in front of the mlx import. If any arm of the estimate consults the+ # budget, this cell is where it fires.+ from utils.hardware import is_apple_silicon+ assert is_apple_silicon() is True++ for paravirtual in (False, True):+ if apple:+ monkeypatch.setattr(+ llama_mod, "_metal_device_is_paravirtual", lambda: paravirtual, raising = False+ )+ monkeypatch.setattr(+ ri, "_metal_device_is_paravirtual", lambda: paravirtual, raising = False+ )+ for shape in SHAPE_NAMES:+ for kwargs in (+ dict(n_ctx = 0),+ dict(n_ctx = 131072),+ dict(n_ctx = 0, llama_extra_args = ["-c", "0"]),+ dict(n_ctx = 131072, gpu_memory_mode = "manual", gpu_layers = 0),+ ):+ ri._estimate_files_cache.clear()+ _price(shapes, shape, **kwargs)+ if not apple:+ break++ # The autouse fixture asserts the recorder is empty at teardown; assert it here too+ # so the failure names this cell rather than a teardown error.+ assert (+ _metal_budget_tripwire == []+ ), f"[{platform[0]}-{accelerator[0]}] reached _apple_metal_memory_budget_bytes"+++def test_platform_matrix_the_platform_label_alone_changes_nothing(monkeypatch, shapes):+ """Linux, WSL2, Windows and macOS price an identical load identically.++ Worth asserting rather than assuming, because it is the finding this matrix+ actually produced: the estimate reads the HOST, not the operating system. Sweeping+ all 21 cells collapses them to three behaviours -- one device, two devices, and no+ device -- and ``sys.platform`` is in none of them.++ That is the right design (bytes are bytes, and a GGUF header does not change shape+ on Windows), so this test is the net under it: the day someone adds a per-OS arm to+ this endpoint, it fails here and has to be justified, rather than shipping to three+ platforms that nobody could test.+ """+ answers = {}+ for platform_row in PLATFORMS:+ for accelerator_row in ACCELERATORS:+ if not _reachable(platform_row[0], accelerator_row[0]):+ continue+ with pytest.MonkeyPatch.context() as patcher:+ _apply_cell(patcher, platform_row, accelerator_row)+ ri._estimate_files_cache.clear()+ response = _price(shapes, "gqa", n_ctx = 32768)+ answers[(platform_row[0], accelerator_row[0])] = (+ response.total_bytes,+ response.gpu_bytes,+ response.kv_bytes,+ response.weights_bytes,+ )++ for accelerator_label in ("nvidia-single", "nvidia-multi", "amd-rocm", "amd-vulkan", _CPU_ONLY):+ by_platform = {+ platform_label: answer+ for (platform_label, acc), answer in answers.items()+ if acc == accelerator_label+ }+ assert (+ len(set(by_platform.values())) == 1+ ), f"{accelerator_label} priced differently per platform: {by_platform}"++ # And macOS on Apple Silicon prices the same load as any other single-device host.+ # One pool is a CAPACITY fact, not a footprint one: the same bytes are allocated+ # either way, and which pool they come out of is the panel's question, answered+ # frontend-side from `singleMemoryPool` (memory-fit.ts). Nothing in the response+ # distinguishes them, which is why the row cannot be read without that flag.+ assert answers[("macos", _UNIFIED)] == answers[("linux", "nvidia-single")]++[email protected]("platform,accelerator", MATRIX)+def test_platform_matrix_the_probed_inventory_owns_the_split_on_a_vulkan_build(+ monkeypatch, shapes, platform, accelerator+):+ """A Vulkan build enumerates no CUDA devices, and that is not evidence of no GPU.++ This is the one seam where vendor genuinely changes the answer, and it only shows+ up in the combination a real Vulkan host produces: two devices in the probed+ inventory and a CUDA count of ZERO, because torch cannot see a Vulkan card. If+ ``_tensor_split_possible`` asked the CUDA count there it would refuse the split on a+ machine with two cards, and price per-device compute buffers for a launch that+ replicates them -- gigabytes apart on the figure the fit verdict reads.++ Asserted on every cell, including the non-Vulkan ones, where the CUDA count is the+ right thing to ask and a zero really does mean no split.+ """+ _apply_cell(monkeypatch, platform, accelerator)+ cell = f"{platform[0]}-{accelerator[0]}"+ vulkan = accelerator[1]++ # Two devices in the probed inventory, nothing visible to torch: the Vulkan shape.+ monkeypatch.setitem(+ sys.modules,+ "main",+ SimpleNamespace(_system_gpu_cache = _snapshot([(0, 12_000, 16_000), (1, 12_000, 16_000)])),+ )+ monkeypatch.setattr(+ LlamaCppBackend,+ "_effective_gpu_count",+ staticmethod(lambda gpu_indices = None: len(gpu_indices) if gpu_indices is not None else 0),+ )++ ri._estimate_files_cache.clear()+ unpinned = _price(shapes, "gqa", n_ctx = 32768, tensor_parallel = True)+ _assert_core_invariants(unpinned, cell = cell, shape = "gqa", note = "unpinned tensor")++ # The same request with the cards named explicitly. A pin answers for itself on+ # every build, so it is the reference the probe-driven answer has to match on+ # Vulkan and to differ from where the CUDA count legitimately says "one card".+ ri._estimate_files_cache.clear()+ pinned = _price(shapes, "gqa", n_ctx = 32768, tensor_parallel = True, selected_gpu_ids = [0, 1])+ _assert_core_invariants(pinned, cell = cell, shape = "gqa", note = "pinned tensor")++ if vulkan:+ assert unpinned.compute_bytes == pinned.compute_bytes, (+ f"[{cell}] a Vulkan build with two probed devices priced a single-device "+ f"load ({unpinned.compute_bytes}) where the same pinned request prices "+ f"{pinned.compute_bytes}; the CUDA count answered instead of the inventory"+ )+ else:+ # torch sees nothing, so there is no split to price, and the pin is the only+ # thing that can say otherwise.+ assert (+ unpinned.compute_bytes < pinned.compute_bytes+ ), f"[{cell}] a CUDA-shaped build reporting zero devices still priced a two-device split"++[email protected]("platform,accelerator", MATRIX)+def test_platform_matrix_the_tensor_latch_lookup_runs_on_every_cell(+ monkeypatch, shapes, platform, accelerator+):+ """Every cell really asks the tensor latches, rather than failing open past them.++ ``_tensor_latches_allow_a_split`` is wrapped in a fail-open ``except Exception``:+ anything that raises inside it answers "a split is allowed" and logs at debug. That+ is the right behaviour in production and a trap in a matrix, because a cell where+ the lookup EXPLODES is indistinguishable from a cell where it ran and said yes --+ both are green, and only one of them tested anything.++ It is not hypothetical. Before the binary was pinned in ``_apply_cell``, all six+ Windows cells took the exception arm on every single request, because a simulated+ ``sys.platform == "win32"`` sends ``shutil.which`` into ``_winapi`` and there is no+ ``_winapi`` on Linux. This test is what noticed, and it is what keeps it noticed.+ """+ _apply_cell(monkeypatch, platform, accelerator)+ cell = f"{platform[0]}-{accelerator[0]}"++ asked: list[tuple] = []+ real = LlamaCppBackend._tensor_quant_kv_unsupported_binary++ def _spy(+ cls,+ binary,+ cache_types = ("f16", "f16"),+ ):+ asked.append((binary, cache_types))+ return real.__func__(cls, binary, cache_types)++ monkeypatch.setattr(LlamaCppBackend, "_tensor_quant_kv_unsupported_binary", classmethod(_spy))++ ri._estimate_files_cache.clear()+ response = _price(+ shapes,+ "gqa",+ n_ctx = 32768,+ cache_type_kv = "q8_0",+ tensor_parallel = True,+ selected_gpu_ids = [0, 1],+ )+ _assert_core_invariants(response, cell = cell, shape = "gqa", note = "tensor + q8_0")++ assert asked, (+ f"[{cell}] the tensor-split latch lookup never reached the latches. Something "+ f"inside _tensor_latches_allow_a_split raised and its fail-open except arm "+ f"answered instead, so this cell priced a tensor split it never checked."+ )+ # And it asked about the cache pair this launch actually plans, not the default.+ assert asked[0][1] == ("q8_0", "q8_0"), f"[{cell}]: latch asked about {asked[0][1]}"+++# G. Regressions this matrix found+#+# This one was a strict xfail when the matrix first ran: a header that yields no dims+# left layer_count None, and _gguf_offloaded_layer_fraction answered 1.0 for every such+# request, so an explicit --gpu-layers 0 was reported as a fully GPU-resident load. The+# pure-SSM case was fixed by keeping block_count out of the header walk; this one has no+# count to keep. It does not need one -- zero layers on the GPU is knowable without+# knowing how many layers there are, and the fraction is a scale factor for a PARTIAL+# offload, which an explicit none is not.+++def test_platform_matrix_a_manual_zero_offload_is_honoured_on_an_unreadable_header(+ monkeypatch, shapes+):+ _apply_cell(monkeypatch, PLATFORMS[0], ACCELERATORS[0])+ ri._estimate_files_cache.clear()+ manual = dict(gpu_memory_mode = "manual", gpu_layers = 0)+ pinned = _price(shapes, "truncated_header", n_ctx = 32768, **manual)+ assert pinned.layer_count is None+ assert pinned.gpu_bytes == 0, (+ f"--gpu-layers 0 on an unreadable header still reports {pinned.gpu_bytes} GPU "+ f"bytes out of a {pinned.total_bytes}-byte total"+ )diff --git a/studio/backend/tests/test_memory_estimate_side_effects.py b/studio/backend/tests/test_memory_estimate_side_effects.pynew file mode 100644index 00000000000..196eb4d2c82--- /dev/null+++ b/studio/backend/tests/test_memory_estimate_side_effects.py@@ -0,0 +1,999 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""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.++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.+* ``_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.+"""++import sys+import threading+import time+import types as _types+from pathlib import Path++import pytest++# Stub heavy / unavailable deps before importing the module under test.+# Copied verbatim from tests/test_memory_estimate.py -- same reasons.++_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)+if _BACKEND_DIR not in sys.path:+ sys.path.insert(0, _BACKEND_DIR)++# loggers+_loggers_stub = _types.ModuleType("loggers")+_loggers_stub.get_logger = lambda name: __import__("logging").getLogger(name)+sys.modules.setdefault("loggers", _loggers_stub)++# structlog. Carries get_logger because this stub is process-wide: whichever test+# module is imported first wins the setdefault, and utils/prebuilt/freshness_flow+# calls structlog.get_logger at import time. A bare module here fails that import+# for every later module on a runner without the real package.+_structlog_stub = _types.ModuleType("structlog")+_structlog_stub.get_logger = lambda *a, **k: __import__("logging").getLogger("stub")+sys.modules.setdefault("structlog", _structlog_stub)++# httpx -- only stub when the real library is missing. Unconditional stubbing+# shadows HTTPError/Response that huggingface_hub.errors imports at load time,+# silently breaking the transformers introspection tier.+try:+ import httpx as _httpx_real # noqa: F401+except ImportError:+ _httpx_stub = _types.ModuleType("httpx")+ for _exc_name in (+ "ConnectError",+ "TimeoutException",+ "ReadTimeout",+ "ReadError",+ "RemoteProtocolError",+ "CloseError",+ "HTTPError",+ "RequestError",+ ):+ setattr(_httpx_stub, _exc_name, type(_exc_name, (Exception,), {}))++ class _FakeTimeout:+ def __init__(self, *a, **kw):+ pass++ _httpx_stub.Timeout = _FakeTimeout+ _httpx_stub.Response = type("Response", (), {})+ _httpx_stub.Client = type(+ "Client",+ (),+ {+ "__init__": lambda self, **kw: None,+ "__enter__": lambda self: self,+ "__exit__": lambda self, *a: None,+ },+ )+ sys.modules["httpx"] = _httpx_stub++import asyncio # noqa: E402+from types import SimpleNamespace # noqa: E402++import routes.inference as ri # noqa: E402+from models.inference import EstimateMemoryRequest # noqa: E402++# Reuse the GGUF blob builder rather than copying it: these tests are only worth+# anything if the bytes they parse are the bytes the real parser was written for.+# Loaded by path because `tests` is not importable as a package name from every+# runner layout.+import importlib.util as _ilu # noqa: E402++_kv_spec = _ilu.spec_from_file_location(+ "_kv_cache_estimation_for_estimate_side_effects",+ Path(__file__).resolve().parent / "test_kv_cache_estimation.py",+)+_kv_mod = _ilu.module_from_spec(_kv_spec)+_kv_spec.loader.exec_module(_kv_mod)+_make_gguf_bytes = _kv_mod._make_gguf_bytes++[email protected](autouse = True)+def _side_effect_caches_are_clean():+ """Both module caches are TTL'd, not per-request, so they leak across tests."""+ ri._estimate_files_cache.clear()+ ri._estimate_config_cache.clear()+ yield+ ri._estimate_files_cache.clear()+ ri._estimate_config_cache.clear()+++_SIDE_EFFECT_GQA_FIELDS = {+ "context_length": 8192,+ "block_count": 12,+ "attention.head_count": 8,+ "attention.head_count_kv": 4,+ "attention.key_length": 64,+ "attention.value_length": 64,+ "embedding_length": 512,+}+++def side_effect_gguf(tmp_path) -> str:+ """A pure-GQA header: standard branch, and the SWA resolver never fires."""+ arch = "qwen3"+ kv = {"general.architecture": arch}+ kv.update({f"{arch}.{k}": v for k, v in _SIDE_EFFECT_GQA_FIELDS.items()})+ path = tmp_path / "side_effects.gguf"+ path.write_bytes(_make_gguf_bytes(arch, kv))+ return str(path)+++def _run_estimate(fastapi_request = None, **kwargs):+ """Call the route directly, bypassing the auth dependency."""+ return asyncio.run(+ ri.estimate_memory(+ EstimateMemoryRequest(**kwargs),+ fastapi_request = fastapi_request,+ current_subject = "test",+ )+ )+++def _request_carrying_slots(slots: int):+ """A stand-in for the FastAPI request carrying the server's slot default."""+ return SimpleNamespace(app = SimpleNamespace(state = SimpleNamespace(llama_parallel_slots = slots)))+++def _priced_locally(monkeypatch, gguf_path: str):+ """Pin the route onto a local header so only the property under test moves."""+ config = SimpleNamespace(+ identifier = "local/model",+ gguf_file = gguf_path,+ is_gguf = True,+ gguf_mmproj_file = None,+ gguf_mtp_file = None,+ gguf_dspark_file = None,+ gguf_dflash_file = None,+ )+ monkeypatch.setattr(ri, "_cached_estimate_config", lambda *a, **kw: config)+ monkeypatch.setattr(ri, "_gguf_resident_file_gb", lambda cfg, **kw: 2.0)+ return config+++def _pin_on_disk(monkeypatch):+ """Answer the on-disk gate positively, however this revision asks it.++ The gate is consulted through a bool wrapper and, for the narrower question of+ whether a resolution may go online, through a tri-state. Both are pinned so these+ tests measure the property they name rather than the gate, and so the same file+ runs against a revision that has only the first.+ """+ monkeypatch.setattr(ri, "_estimate_target_is_on_this_disk", lambda _id: True)+ monkeypatch.setattr(+ ri,+ "_estimate_disk_residency",+ lambda _id: getattr(ri, "_ESTIMATE_DISK_PRESENT", "present"),+ raising = False,+ )+++def _hub_offline_now() -> bool:+ """Whether the in-process HF offline switch is currently thrown.++ ``force_hf_offline`` flips ``huggingface_hub.constants.HF_HUB_OFFLINE`` rather than+ only the env var, because the env var is read once at import. So the constant is+ the honest observable for "would this call have gone to the network".+ """+ import huggingface_hub.constants as _hf_constants+ return bool(_hf_constants.HF_HUB_OFFLINE)+++# D6. The on-disk gate and the network+++class TestTheOnDiskGateAndTheNetwork:+ """The gate is fail-OPEN, and what it opens onto is a Hub round trip."""++ def test_a_host_with_no_establishable_cache_root_yields_no_roots(self, monkeypatch):+ # The premise the rest of this class rests on: `roots == []` is a real host+ # state, not a hypothetical. Both tiers are driven to fail the way they fail in+ # the field -- tier 1's import reaches through hub.utils.paths into the logging+ # stack (a lean interpreter without structlog raises exactly here), and tier 2+ # keeps only roots that `is_dir()`, which drops a path that does not exist.+ def _tier_one_import_fails():+ raise ModuleNotFoundError("No module named 'structlog'")++ monkeypatch.setattr(+ ri, "_estimate_hf_cache_roots", ri._estimate_hf_cache_roots, raising = False+ )+ import hub.utils.hf_cache_state as _state+ import utils.hf_cache_settings as _settings++ monkeypatch.setattr(_state, "hf_cache_roots", _tier_one_import_fails)+ monkeypatch.setattr(_settings, "known_hf_hub_caches", lambda: [])+ import huggingface_hub.constants as _hf_constants++ monkeypatch.setattr(_hf_constants, "HF_HUB_CACHE", "/nonexistent/hf/hub")++ assert ri._estimate_hf_cache_roots() == []++ def test_no_cache_root_means_the_gate_cannot_refuse_anything(self, monkeypatch):+ # Fail-open, stated as behaviour. Every error path in the gate returns True,+ # and `roots == []` is the one that is live in the field.+ monkeypatch.setattr(ri, "_estimate_hf_cache_roots", list)+ 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+ # 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".+ #+ # 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.+ monkeypatch.setattr(ri, "_estimate_hf_cache_roots", list)+ offline_at_each_call = []++ def _fake_from_identifier(**kwargs):+ offline_at_each_call.append(_hub_offline_now())+ return None++ monkeypatch.setattr(ri.ModelConfig, "from_identifier", staticmethod(_fake_from_identifier))++ resp = _run_estimate(model_path = "org/definitely-not-cached")+ assert resp.available is False+ assert offline_at_each_call, "the resolution never ran at all"+ assert False not in offline_at_each_call, (+ "the on-disk gate could not be answered and the resolution was allowed "+ "online anyway: that is a Hub round trip and an HF-cache write behind a "+ f"slider, offline flag per attempt was {offline_at_each_call}"+ )++ def test_the_fail_open_path_dials_no_socket_and_writes_no_cache_file(self, monkeypatch):+ # The end-to-end form of the same claim, driven through the real+ # ModelConfig.from_identifier with the session socket guard counting. The guard+ # is reused rather than HF_HUB_OFFLINE being set, so the ONLINE branch is the+ # one under test -- setting the env var would select the branch that trivially+ # passes.+ import socket++ attempts = []+ guarded_connect = socket.socket.connect+ guarded_connect_ex = socket.socket.connect_ex+ guarded_resolve = socket.getaddrinfo++ def _record_connect(self, address, *a, **kw):+ attempts.append(("connect", address))+ return guarded_connect(self, address, *a, **kw)++ def _record_connect_ex(self, address, *a, **kw):+ attempts.append(("connect_ex", address))+ return guarded_connect_ex(self, address, *a, **kw)++ def _record_resolve(host, port, *a, **kw):+ attempts.append(("getaddrinfo", host))+ return guarded_resolve(host, port, *a, **kw)++ monkeypatch.setattr(socket.socket, "connect", _record_connect)+ monkeypatch.setattr(socket.socket, "connect_ex", _record_connect_ex)+ monkeypatch.setattr(socket, "getaddrinfo", _record_resolve)++ # A host where the gate cannot answer.+ monkeypatch.setattr(ri, "_estimate_hf_cache_roots", list)++ from utils.hf_cache_settings import get_hf_cache_paths++ hub_cache = Path(get_hf_cache_paths().hub_cache)++ def _snapshot():+ if not hub_cache.is_dir():+ return []+ return sorted(str(p.relative_to(hub_cache)) for p in hub_cache.rglob("*"))++ before = _snapshot()+ resp = _run_estimate(model_path = "org/definitely-not-cached-side-effects")+ assert resp.available is False++ after = _snapshot()+ assert after == before, (+ "the estimate wrote into the HF cache: " f"{sorted(set(after) - set(before))[:12]}"+ )+ _LOCAL = {"localhost", "127.0.0.1", "::1", "0.0.0.0"}+ outbound = [+ a+ for a in attempts+ if not (isinstance(a[1], str) and a[1] in _LOCAL)+ and not (isinstance(a[1], tuple) and a[1] and str(a[1][0]) in _LOCAL)+ ]+ assert (+ outbound == []+ ), f"the estimate tried to leave the machine {len(outbound)}x: {outbound[:5]}"++ def test_an_unreadable_cache_root_answers_not_downloaded(self, tmp_path, monkeypatch):+ # Recorded because the gate's docstring promises the opposite: "an unreadable+ # cache root must not turn into a blanket not_downloaded". It does.+ # _iter_hf_cache_snapshots swallows every OSError, PermissionError included,+ # and reports the repo as absent -- so the gate's own except never fires and+ # the answer is a refusal, not a fall-through. Safer than the docstring says,+ # but the docstring is what a reader will believe.+ if sys.platform == "win32":+ pytest.skip("POSIX permission bits")+ import os++ if os.geteuid() == 0:+ pytest.skip("root reads through any mode")++ root = tmp_path / "locked"+ (root / "models--org--Model-GGUF" / "snapshots" / "rev1").mkdir(parents = True)+ root.chmod(0o000)+ try:+ monkeypatch.setattr(ri, "_estimate_hf_cache_roots", lambda: [root])+ answered = ri._estimate_target_is_on_this_disk("org/Model-GGUF")+ finally:+ root.chmod(0o755)+ assert (+ answered is False+ ), "behaviour changed to match the docstring; update the docstring too"++ def test_passing_the_gate_does_not_mean_the_resolution_can_stay_local(+ self, tmp_path, monkeypatch+ ):+ # The asymmetry that survives every fix above. The gate scans EVERY cache root+ # Studio knows; from_identifier's offline readers take only the CONFIGURED one.+ # So a repo sitting in the legacy or a historical root passes the gate, the+ # offline resolve then finds nothing where it looks, and the online retry runs+ # with the gate having said yes. "On this disk" does not imply "resolvable+ # without the network", and only the first of those is what the gate checks.+ from utils.models.model_config import _iter_hf_cache_snapshots++ other_root = tmp_path / "legacy"+ snap = other_root / "models--org--Model-GGUF" / "snapshots" / "rev1"+ snap.mkdir(parents = True)+ (snap / "model.gguf").write_bytes(b"\0" * 8)++ monkeypatch.setattr(ri, "_estimate_hf_cache_roots", lambda: [other_root])+ assert ri._estimate_target_is_on_this_disk("org/Model-GGUF") is True+ # ...while the reader the resolution actually uses, on its default root, does+ # not see it.+ assert list(_iter_hf_cache_snapshots("org/Model-GGUF")) == []++ offline_at_each_call = []++ def _fake_from_identifier(**kwargs):+ offline_at_each_call.append(_hub_offline_now())+ return None++ monkeypatch.setattr(ri.ModelConfig, "from_identifier", staticmethod(_fake_from_identifier))+ _run_estimate(model_path = "org/Model-GGUF")+ assert offline_at_each_call, "the resolution never ran"+ # Deliberately NOT asserted as a fix: a repo that is genuinely present but+ # whose metadata lives elsewhere is the one case the online retry exists for.+ # This pins the shape so the trade-off is visible if it is ever revisited.+ assert offline_at_each_call[0] is True, "the first attempt must still be offline"+++# D4. The inert-probe fallback+++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+ # 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.+ #+ # 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.+ constructions = []+ reaps = []++ class _FaultyBackend:+ def __init__(self, *, manages_processes: bool = True):+ constructions.append(manages_processes)+ if not manages_processes:+ # NOT a signature rejection: the keyword bound fine. This stands+ # for any TypeError from the constructor body.+ raise TypeError("'NoneType' object is not subscriptable")+ reaps.append("_kill_orphaned_servers")++ monkeypatch.setattr(ri, "LlamaCppBackend", _FaultyBackend)++ raised = None+ try:+ ri._probe_backend()+ except TypeError as exc:+ raised = exc++ assert reaps == [], (+ "a TypeError from inside __init__ was answered by constructing the "+ "process-reaping backend; an estimate must never be able to kill a server"+ )+ assert constructions == [False], (+ "the constructor ran twice for one probe: the fallback must only fire when "+ f"the keyword itself is unsupported, saw {constructions}"+ )+ assert raised is not None, "a fault inside the constructor must surface, not be masked"++ def test_a_stand_in_that_predates_the_keyword_still_gets_the_bare_constructor(+ self, monkeypatch+ ):+ # The compatibility the narrowed except must not cost. Modelled on the real+ # stand-ins: plain classes, no __init__ at all.+ class _PlainStandIn:+ is_diffusion = False+ _architecture = None++ monkeypatch.setattr(ri, "LlamaCppBackend", _PlainStandIn)+ assert isinstance(ri._probe_backend(), _PlainStandIn)++ class _NoKeywordStandIn:+ def __init__(self):+ self.built = True++ monkeypatch.setattr(ri, "LlamaCppBackend", _NoKeywordStandIn)+ assert ri._probe_backend().built is True++ def test_the_real_constructor_cannot_raise_the_typeerror_the_except_catches(self):+ # The honest scope of the fix. Under `manages_processes = False` the real+ # __init__ body is attribute assignment and threading primitives only: every+ # call it makes -- _kill_orphaned_servers, atexit.register, time.monotonic --+ # sits inside the `if manages_processes:` branch that is not taken. So the+ # broad except was unreachable for the real class, and the narrowing matters+ # for substituted and subclassed backends, which is the population it serves.+ import ast+ import inspect++ from core.inference.llama_cpp import LlamaCppBackend++ tree = ast.parse(inspect.getsource(inspect.getmodule(LlamaCppBackend)))+ init = next(+ f+ for node in ast.walk(tree)+ if isinstance(node, ast.ClassDef) and node.name == "LlamaCppBackend"+ for f in node.body+ if isinstance(f, ast.FunctionDef) and f.name == "__init__"+ )+ guarded = {+ getattr(n, "lineno", None)+ for st in init.body+ if isinstance(st, ast.If)+ for n in ast.walk(st)+ }+ unguarded_calls = [+ ast.unparse(n)+ for n in ast.walk(init)+ if isinstance(n, ast.Call) and n.lineno not in guarded+ ]+ assert set(unguarded_calls) <= {+ "threading.Lock()",+ "threading.RLock()",+ "threading.Event()",+ }, (+ "the inert branch of LlamaCppBackend.__init__ grew a call that could "+ f"raise: {sorted(set(unguarded_calls))}"+ )+++# D5. The blocking capability probe+++class TestSlotResolutionStaysOffTheEventLoop:+ """``_effective_parallel_slots`` shells out to ``llama-server --help``."""++ 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.+ #+ # 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.+ #+ # 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.+ _priced_locally(monkeypatch, side_effect_gguf)++ probe_threads = []++ def _caps(*a, **kw):+ probe_threads.append(threading.get_ident())+ return {"found": True, "supports_kv_unified": True}++ monkeypatch.setattr(ri.LlamaCppBackend, "probe_server_capabilities", staticmethod(_caps))++ async def _drive():+ loop_thread = threading.get_ident()+ resp = await ri.estimate_memory(+ EstimateMemoryRequest(model_path = side_effect_gguf, n_ctx = 4096),+ fastapi_request = _request_carrying_slots(4),+ current_subject = "test",+ )+ return loop_thread, resp++ loop_thread, resp = asyncio.run(_drive())+ assert resp.available is True+ assert probe_threads, "the slot clamp never asked the binary; the probe moved"+ assert loop_thread not in probe_threads, (+ "the capability probe ran on the event loop thread; on a cold cache that is "+ "`llama-server --help` with a ten second timeout, in front of chat streaming"+ )++ def test_the_slot_default_is_still_read_from_the_app_state(self, monkeypatch, side_effect_gguf):+ # Moving the probe off the loop must not take the settings read with it: the+ # published default lives on the FastAPI app state, which belongs to the loop+ # side, and pricing 1 there underestimates the KV cache and the slot-scaled+ # compute buffers for the default configuration.+ _priced_locally(monkeypatch, side_effect_gguf)+ monkeypatch.setattr(+ ri.LlamaCppBackend,+ "probe_server_capabilities",+ staticmethod(lambda *a, **kw: {"found": True, "supports_kv_unified": True}),+ )+ resp = _run_estimate(+ fastapi_request = _request_carrying_slots(4),+ model_path = side_effect_gguf,+ n_ctx = 4096,+ )+ assert resp.n_parallel == 4, (+ "the server's published slot default was lost; blank Parallel Slots must "+ "price the 4 slots a standard launch serves, not 1"+ )++ def test_a_single_slot_never_reaches_the_probe(self, monkeypatch):+ # One slot cannot be clamped below one, so the binary is not asked at all.+ # Pins the cheap path so the fix cannot start paying for a probe nobody needs.+ def boom(*a, **kw):+ raise AssertionError("a single slot must not probe the binary")++ monkeypatch.setattr(ri.LlamaCppBackend, "probe_server_capabilities", staticmethod(boom))+ assert ri._effective_parallel_slots(1) == 1+ assert ri._effective_parallel_slots(0) == 1+++# D7. The FastAPI request parameter+++class TestTheRequestParameterAnnotation:+ """``fastapi_request: Request = None`` is the form that works, not a slip."""++ def test_the_route_registers_and_receives_a_real_request(self):+ # Through the app the default is never used: FastAPI special-cases a bare+ # `Request` annotation and always injects the live object. The None default is+ # what lets a unit test await the coroutine directly.+ from fastapi import FastAPI, Request+ from fastapi.testclient import TestClient++ app = FastAPI()++ @app.post("/probe")+ async def _probe(request: EstimateMemoryRequest, fastapi_request: Request = None):+ return {"injected": type(fastapi_request).__name__}++ with TestClient(app) as client:+ body = client.post("/probe", json = {"model_path": "x"}).json()+ assert body["injected"] == "Request"++ def test_optional_request_would_break_route_registration(self):+ # The obvious "correction" is not one. FastAPI recognises the Request type by+ # the bare annotation; Optional[Request] falls through to pydantic field+ # creation and raises at decoration time, so the module would not import.+ from typing import Optional++ import fastapi+ from fastapi import FastAPI, Request++ app = FastAPI()+ with pytest.raises(fastapi.exceptions.FastAPIError):++ @app.post("/broken")+ async def _broken(+ request: EstimateMemoryRequest, fastapi_request: Optional[Request] = None+ ):+ return {}++ def test_the_route_signature_matches_the_convention_in_this_module(self):+ import inspect++ from fastapi import Request++ param = inspect.signature(ri.estimate_memory).parameters["fastapi_request"]+ assert param.annotation is Request+ assert param.default is None+++# Contract: cache eviction under concurrency+++class TestEstimateCachesUnderConcurrency:+ """Both caches are module state reached from ``asyncio.to_thread`` workers."""++ def test_evicting_and_inserting_from_many_threads_never_raises(self, monkeypatch):+ # min() walks the dict through a Python key function the interpreter is free to+ # switch out of: a concurrent pop makes that walk raise KeyError, a concurrent+ # insert RuntimeError ("dictionary changed size during iteration"). Nothing+ # between here and the to_thread body catches either, so it surfaces as a 500+ # on a slider drag. This is the behavioural form of that guarantee -- the+ # source-reading assertion in test_memory_estimate.py cannot see a torn walk.+ threads = 64+ keys = ri._ESTIMATE_CONFIG_CACHE_MAX * 4 # well past the eviction threshold+ _pin_on_disk(monkeypatch)++ class _FakeModelConfig:+ @staticmethod+ def from_identifier(*, model_id, **kw):+ return SimpleNamespace(identifier = model_id, is_gguf = True)++ monkeypatch.setattr(ri, "ModelConfig", _FakeModelConfig)++ start = threading.Barrier(threads)+ errors = []+ sizes = []++ def _worker(n: int):+ start.wait()+ try:+ for i in range(40):+ ri._cached_estimate_config(f"org/model-{(n + i) % keys}", None, None, False)+ sizes.append(len(ri._estimate_config_cache))+ except Exception as exc: # noqa: BLE001 - the point is that none escape+ errors.append(exc)++ workers = [threading.Thread(target = _worker, args = (n,)) for n in range(threads)]+ for w in workers:+ w.start()+ for w in workers:+ w.join()++ assert errors == [], f"concurrent eviction raised {errors[:3]}"+ # The lock covers evict-and-insert, not check-then-insert across threads, so+ # the ceiling is MAX + (concurrent inserters). Bounded is the contract; exact+ # is not, and asserting exact would be asserting a race.+ assert max(sizes) <= ri._ESTIMATE_CONFIG_CACHE_MAX + threads+ assert len(ri._estimate_config_cache) <= ri._ESTIMATE_CONFIG_CACHE_MAX + threads++ def test_the_files_cache_evicts_under_the_same_pressure(self, monkeypatch):+ threads = 64+ keys = ri._ESTIMATE_FILES_CACHE_MAX * 4+ monkeypatch.setattr(ri, "_estimate_gguf_required_gb", lambda *a, **kw: 3.0)+ monkeypatch.setattr(ri, "_remote_gguf_compute_reserve_gb", lambda **kw: 0.5)++ start = threading.Barrier(threads)+ errors = []+ sizes = []++ def _worker(n: int):+ start.wait()+ try:+ for i in range(40):+ ri._gguf_resident_file_gb(+ SimpleNamespace(+ identifier = f"org/files-{(n + i) % keys}",+ gguf_file = None,+ gguf_variant = None,+ ),+ )+ sizes.append(len(ri._estimate_files_cache))+ except Exception as exc: # noqa: BLE001+ errors.append(exc)++ workers = [threading.Thread(target = _worker, args = (n,)) for n in range(threads)]+ for w in workers:+ w.start()+ for w in workers:+ w.join()++ assert errors == [], f"concurrent files-cache eviction raised {errors[:3]}"+ assert max(sizes) <= ri._ESTIMATE_FILES_CACHE_MAX + threads++ def test_a_cold_key_is_resolved_once_per_caller_not_once(self, monkeypatch):+ # Documented, not celebrated. There is no in-flight dedup, so a thundering herd+ # on one cold key runs the expensive resolution once per caller. Harmless for a+ # panel that prices one model at a time; the assertion exists so that if a+ # single-flight is ever added, this test is the thing that has to change.+ threads = 32+ _pin_on_disk(monkeypatch)+ resolutions = []+ lock = threading.Lock()+ start = threading.Barrier(threads)+ # Inside the resolution, so the count is decided by the code and not by the+ # scheduler: every caller that gets here must arrive before any of them may+ # leave. If a single-flight is ever added, fewer than `threads` arrive and this+ # breaks rather than passing by luck.+ inside = threading.Barrier(threads, timeout = 30)++ class _CountingModelConfig:+ @staticmethod+ def from_identifier(*, model_id, **kw):+ with lock:+ resolutions.append(model_id)+ inside.wait()+ return SimpleNamespace(identifier = model_id, is_gguf = True)++ monkeypatch.setattr(ri, "ModelConfig", _CountingModelConfig)++ errors = []++ def _worker():+ start.wait()+ try:+ ri._cached_estimate_config("org/one-cold-key", None, None, False)+ except Exception as exc: # noqa: BLE001+ errors.append(exc)++ workers = [threading.Thread(target = _worker) for _ in range(threads)]+ for w in workers:+ w.start()+ for w in workers:+ w.join()++ assert errors == []+ assert (+ len(resolutions) == threads+ ), "the stampede shape changed; if a single-flight was added, say so here"+ assert len(ri._estimate_config_cache) == 1++ def test_an_entry_is_not_born_already_expired(self, monkeypatch):+ # The TTL stamp is the observable. Taken BEFORE the resolution, an entry that+ # took longer than the TTL to produce is inserted already stale, so the very+ # next request re-resolves and the cache stops existing on exactly the slow+ # models it was added for.+ clock = {"t": 1000.0}+ _pin_on_disk(monkeypatch)+ monkeypatch.setattr(+ ri,+ "time",+ SimpleNamespace(monotonic = lambda: clock["t"], time = time.time),+ )++ resolutions = []+ slow = ri._ESTIMATE_CONFIG_TTL_SECONDS + 10.0++ class _SlowModelConfig:+ @staticmethod+ def from_identifier(*, model_id, **kw):+ resolutions.append(model_id)+ clock["t"] += slow # the resolution really did take this long+ return SimpleNamespace(identifier = model_id, is_gguf = True)++ monkeypatch.setattr(ri, "ModelConfig", _SlowModelConfig)++ ri._cached_estimate_config("org/slow", None, None, False)+ assert len(resolutions) == 1+ # No clock advance at all between the two calls: the second request is+ # immediate, and must be a hit.+ ri._cached_estimate_config("org/slow", None, None, False)+ assert len(resolutions) == 1, (+ "the entry was born expired: its TTL stamp was taken before a "+ f"{slow:.0f}s resolution, so an immediate repeat re-resolved"+ )++ def test_the_files_entry_is_not_born_already_expired_either(self, monkeypatch):+ # Same stamp, same cache, other half. A multi-shard repo whose header walk and+ # file stats outlast the TTL must not be inserted pre-expired, or the slider+ # re-walks it on every tick.+ clock = {"t": 5000.0}+ monkeypatch.setattr(+ ri, "time", SimpleNamespace(monotonic = lambda: clock["t"], time = time.time)+ )+ walks = []+ slow = ri._ESTIMATE_FILES_TTL_SECONDS + 10.0++ def _slow_required(cfg, **kw):+ walks.append(1)+ clock["t"] += slow+ return 3.0++ monkeypatch.setattr(ri, "_estimate_gguf_required_gb", _slow_required)+ monkeypatch.setattr(ri, "_remote_gguf_compute_reserve_gb", lambda **kw: 0.5)++ config = SimpleNamespace(identifier = "org/many-shards", gguf_file = None, gguf_variant = None)+ ri._gguf_resident_file_gb(config)+ assert len(walks) == 1+ ri._gguf_resident_file_gb(config)+ assert len(walks) == 1, (+ "the files entry was born expired: its TTL stamp was taken before a "+ f"{slow:.0f}s walk"+ )+++# Contract: token and subject isolation+++class TestTokenAndSubjectIsolation:+ """A gated repo resolves per credential; entries must not cross."""++ def test_two_tokens_never_receive_each_others_config(self, monkeypatch):+ _pin_on_disk(monkeypatch)++ class _PerTokenModelConfig:+ @staticmethod+ def from_identifier(+ *,+ model_id,+ hf_token = None,+ **kw,+ ):+ if hf_token is None:+ raise PermissionError("gated repo needs a token")+ return SimpleNamespace(identifier = model_id, is_gguf = True, resolved_with = hf_token)++ monkeypatch.setattr(ri, "ModelConfig", _PerTokenModelConfig)++ for _round in range(3): # interleaved, not one subject then the other+ alice = ri._cached_estimate_config("org/gated", None, "token-alice", False)+ bob = ri._cached_estimate_config("org/gated", None, "token-bob", False)+ assert alice.resolved_with == "token-alice"+ assert bob.resolved_with == "token-bob"++ # And the tokenless caller gets neither -- it gets the failure it earned.+ assert ri._cached_estimate_config("org/gated", None, None, False) is None++ def test_the_token_is_fingerprinted_not_stored_in_the_key(self):+ # A token is a credential; it does not belong in a dict key verbatim, because+ # module state is dumped by every debugger and every heap snapshot.+ secret = "hf_thisIsASecretToken"+ fingerprint = ri._estimate_token_fingerprint(secret)+ assert secret not in fingerprint+ assert len(fingerprint) == 16+ assert ri._estimate_token_fingerprint(secret) == fingerprint+ assert ri._estimate_token_fingerprint("hf_other") != fingerprint+ assert ri._estimate_token_fingerprint(None) == ""+ assert ri._estimate_token_fingerprint("") == ""++ def test_the_subject_is_absent_from_the_key_and_the_token_is_what_isolates(self, monkeypatch):+ # Recorded deliberately. current_subject is NOT part of the cache key: the+ # credential is, and two subjects presenting the same token are entitled to the+ # same answer. What this pins is that nothing else about a subject leaks in --+ # so if per-subject state is ever added to the resolution, the key must grow+ # with it and this test is where that shows up.+ _pin_on_disk(monkeypatch)+ monkeypatch.setattr(+ ri,+ "ModelConfig",+ SimpleNamespace(+ from_identifier = staticmethod(+ lambda *, model_id, **kw: SimpleNamespace(identifier = model_id, is_gguf = True)+ )+ ),+ )+ ri._cached_estimate_config("org/model", "Q4_K_M", "tok", True)+ (key,) = list(ri._estimate_config_cache)+ assert key == ("org/model", "Q4_K_M", True, ri._estimate_token_fingerprint("tok"))++ def test_the_native_grant_is_keyed_as_a_flag_not_as_an_identity(self, monkeypatch):+ # The grant changes the resolution: it passes _native_drafter_accept into+ # from_identifier. So it has to be in the key, and it is -- but as a boolean.+ # Two DIFFERENT subjects each holding a valid lease share one entry. That is+ # sound only because the lease is verified before the key is built, never+ # after; this test is the record of that reasoning.+ _pin_on_disk(monkeypatch)+ seen = []++ class _GrantAwareModelConfig:+ @staticmethod+ def from_identifier(+ *,+ model_id,+ drafter_accept = None,+ **kw,+ ):+ seen.append(drafter_accept is not None)+ return SimpleNamespace(identifier = model_id, is_gguf = True)++ monkeypatch.setattr(ri, "ModelConfig", _GrantAwareModelConfig)++ ri._cached_estimate_config("org/model", None, "tok", False)+ ri._cached_estimate_config("org/model", None, "tok", True)+ assert seen == [False, True], "the grant flag must reach the resolution"+ assert len(ri._estimate_config_cache) == 2, "a grant-backed resolve must not "+ "overwrite the ungranted one"+++# Contract: no GPU is touched+++class TestNoDeviceIsTouched:+ """ "no device is touched" -- the third clause of the route's docstring."""++ def test_a_full_request_allocates_nothing_and_launches_nothing(+ self, monkeypatch, side_effect_gguf+ ):+ # The route reaches _guard_device_count -> _tensor_split_possible ->+ # LlamaCppBackend._effective_gpu_count, which imports torch and asks CUDA how+ # many devices it can see. That is driver ENUMERATION, and it is as far as this+ # is allowed to go: no context creation, no property read, no free-memory+ # probe, no nvidia-smi, no llama-server. Each of those is a real cost on a box+ # where a training run owns the cards, and this endpoint fires on every+ # settings change.+ import subprocess++ import torch++ touched = []++ def _forbid(name):+ def _hit(*a, **kw):+ touched.append(name)+ raise AssertionError(f"the estimate touched the GPU via {name}")++ return _hit++ # Enumeration: permitted, but recorded so the boundary is visible.+ enumerated = []+ real_is_available = torch.cuda.is_available+ monkeypatch.setattr(+ torch.cuda,+ "is_available",+ lambda: (enumerated.append("is_available"), real_is_available())[1],+ )+ real_device_count = torch.cuda.device_count+ monkeypatch.setattr(+ torch.cuda,+ "device_count",+ lambda: (enumerated.append("device_count"), real_device_count())[1],+ )++ # Everything past enumeration: forbidden.+ for attr in (+ "init",+ "set_device",+ "mem_get_info",+ "get_device_properties",+ "synchronize",+ "empty_cache",+ ):+ if hasattr(torch.cuda, attr):+ monkeypatch.setattr(torch.cuda, attr, _forbid(f"torch.cuda.{attr}"))+ monkeypatch.setattr(subprocess, "run", _forbid("subprocess.run"))+ monkeypatch.setattr(subprocess, "Popen", _forbid("subprocess.Popen"))+ monkeypatch.setattr(subprocess, "check_output", _forbid("subprocess.check_output"))++ _priced_locally(monkeypatch, side_effect_gguf)+ resp = _run_estimate(+ fastapi_request = _request_carrying_slots(1),+ model_path = side_effect_gguf,+ n_ctx = 8192,+ )+ assert resp.available is True+ assert touched == [], f"the estimate touched the GPU: {touched}"+ # Recorded, not forbidden, and this is the honest edge of the claim: the+ # device-count path really does ask the CUDA driver how many cards are+ # visible: measured on this box, is_available() and device_count() both fire.+ # No context is created and no property is read, but "no device is touched" is+ # a slight overstatement of that, and this is where it shows. Subset, not+ # equality: a CPU-only runner answers is_available() False and never reaches+ # device_count, and a Vulkan build short-circuits before either.+ assert set(enumerated) <= {"is_available", "device_count"}, enumerateddiff --git a/studio/backend/tests/test_server_tuning_flags.py b/studio/backend/tests/test_server_tuning_flags.pyindex e188a91436d..3c29eb38ec7 100644--- a/studio/backend/tests/test_server_tuning_flags.py+++ b/studio/backend/tests/test_server_tuning_flags.py@@ -420,9 +420,16 @@ def test_the_coexistence_estimate_charges_the_requested_checkpoints():in inspect.signature(inference_routes._estimate_gguf_required_gb).parameters)assert "ctx_checkpoints" in inspect.signature(inference_routes._estimate_gguf_kv_gb).parameters+ assert "ctx_checkpoints" in inspect.signature(inference_routes._gguf_runtime_bytes).parameterssource = inspect.getsource(inference_routes._guard_chat_load_against_training)assert 'ctx_checkpoints = getattr(request, "ctx_checkpoints", None)' in source- kv_source = inspect.getsource(inference_routes._estimate_gguf_kv_gb)+ # _estimate_gguf_kv_gb is the guard's summing wrapper; the arithmetic lives in+ # _gguf_runtime_bytes, which the memory-estimate endpoint reads itemized. Both+ # links are asserted, so dropping the field in either place still fails here.+ assert "ctx_checkpoints = ctx_checkpoints" in inspect.getsource(+ inference_routes._estimate_gguf_kv_gb+ )+ kv_source = inspect.getsource(inference_routes._gguf_runtime_bytes)# priced on what the launch runs, so a typed --ctx-checkpoints wins here tooassert "resolve_ctx_checkpoints(llama_extra_args, ctx_checkpoints)" in kv_sourcediff --git a/studio/frontend/src/features/model-picker/api/memory-estimate.ts b/studio/frontend/src/features/model-picker/api/memory-estimate.tsnew file mode 100644index 00000000000..0baf2babf23--- /dev/null+++ b/studio/frontend/src/features/model-picker/api/memory-estimate.ts@@ -0,0 +1,337 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import { authFetch } from "@/features/auth";+import { consumeNativePathToken } from "@/features/native-intents/api";++/** GB, to two decimals. Lives in the import-free module beside the fit rules so the+ * node test runner can reach it; re-exported here because every caller of the row's+ * figures already imports from this file. */+export { formatMemoryGb } from "../model-config/memory-fit";++/** Why no breakdown came back. The panel maps these to its own copy. */+export type MemoryEstimateReason =+ | "not_gguf"+ | "not_downloaded"+ | "unsupported_source"+ | "unsizable";++export interface MemoryEstimate {+ available: boolean;+ reason: MemoryEstimateReason | null;+ /** Files that become resident: weights, projector, drafter. */+ weightsBytes: number;+ /** KV cache at the priced context and slot count. Meaningless unless `kvEstimable`. */+ kvBytes: number;+ /** Compute / graph buffers, flat plus the context-linear growth. */+ computeBytes: number;+ /** A separate drafter's own cache and rollback state, on top of its file. */+ drafterRuntimeBytes: number;+ /** The share of the above that lands on the GPU. A figure rather than a flag: under+ * MTP the target-side verification state follows the TARGET cache and the draft+ * cache follows the drafter, so the two halves can be placed differently. */+ drafterRuntimeGpuBytes: number;+ /** The vision encoder's buffers, about 0.4x the projector file on top of it. */+ projectorRuntimeBytes: number;+ /** A charged drafter whose cache could not be sized: `--spec-draft-hf` names a+ * repository, so its header is not on this disk. The total is a floor. */+ drafterKvUnsized: boolean;+ /** A pass-through adapter file that could not be sized, so the total is a floor. */+ adaptersUnsized: boolean;+ /** Weights + KV + compute, wherever they land (VRAM, host RAM, or one unified pool). */+ totalBytes: number;+ /** The share of `totalBytes` that lands on the GPU under the requested offload. */+ gpuBytes: number;+ /**+ * False when the GGUF header lacks the attention dims needed to size the cache. The+ * numbers above are then a lower bound, not an estimate: at a long context the cache+ * is most of the footprint.+ */+ kvEstimable: boolean;+ /** False under `--no-kv-offload`, which moves the cache to host RAM. */+ kvOnGpu: boolean;+ /** What was actually priced, after overrides and clamps resolve. */+ nCtx: number;+ cacheTypeKv: string | null;+ nParallel: number;+ layerCount: number | null;+ /** Layers charged to the GPU; null under automatic placement. */+ gpuLayers: number | null;+ /** `--n-cpu-moe` is set, so the GPU figure ignores it and reads high. */+ moeOffloadUnmodelled: boolean;+}++/** The load settings that move the estimate. Mirrors the fields /load takes. */+export interface MemoryEstimateRequest {+ modelPath: string;+ ggufVariant?: string | null;+ hfToken?: string | null;+ nativePathToken?: string | null;+ nCtx?: number | null;+ cacheTypeKv?: string | null;+ nParallel?: number | null;+ nBatch?: number | null;+ nUbatch?: number | null;+ ctxCheckpoints?: number | null;+ speculativeType?: string | null;+ specDraftNMax?: number | null;+ specDraftCacheType?: string | null;+ tensorParallel?: boolean;+ disableVision?: boolean;+ gpuMemoryMode?: string | null;+ gpuLayers?: number | null;+ nCpuMoe?: number | null;+ selectedGpuIds?: number[] | null;+ llamaExtraArgs?: string[] | null;+}++const UNAVAILABLE: MemoryEstimate = {+ available: false,+ reason: "unsizable",+ weightsBytes: 0,+ kvBytes: 0,+ computeBytes: 0,+ drafterRuntimeBytes: 0,+ drafterRuntimeGpuBytes: 0,+ projectorRuntimeBytes: 0,+ drafterKvUnsized: false,+ adaptersUnsized: false,+ totalBytes: 0,+ gpuBytes: 0,+ kvEstimable: false,+ kvOnGpu: true,+ nCtx: 0,+ cacheTypeKv: null,+ nParallel: 1,+ layerCount: null,+ gpuLayers: null,+ moeOffloadUnmodelled: false,+};++interface ApiEstimateResponse {+ available: boolean;+ reason: MemoryEstimateReason | null;+ weights_bytes: number;+ kv_bytes: number;+ compute_bytes: number;+ drafter_runtime_bytes: number;+ drafter_runtime_gpu_bytes: number;+ projector_runtime_bytes: number;+ drafter_kv_unsized: boolean;+ adapters_unsized?: boolean;+ total_bytes: number;+ gpu_bytes: number;+ kv_estimable: boolean;+ kv_on_gpu: boolean;+ n_ctx: number;+ cache_type_kv: string | null;+ n_parallel: number;+ layer_count: number | null;+ gpu_layers: number | null;+ moe_offload_unmodelled: boolean;+}++function estimateRequestBody(+ payload: MemoryEstimateRequest,+ nativePathLease: string | null,+): string {+ return JSON.stringify({+ model_path: payload.modelPath,+ gguf_variant: payload.ggufVariant ?? null,+ hf_token: payload.hfToken ?? null,+ native_path_lease: nativePathLease,+ n_ctx: payload.nCtx ?? null,+ cache_type_kv: payload.cacheTypeKv ?? null,+ n_parallel: payload.nParallel ?? null,+ n_batch: payload.nBatch ?? null,+ n_ubatch: payload.nUbatch ?? null,+ ctx_checkpoints: payload.ctxCheckpoints ?? null,+ speculative_type: payload.speculativeType ?? null,+ spec_draft_n_max: payload.specDraftNMax ?? null,+ spec_draft_cache_type: payload.specDraftCacheType ?? null,+ tensor_parallel: payload.tensorParallel ?? false,+ disable_vision: payload.disableVision ?? false,+ gpu_memory_mode: payload.gpuMemoryMode ?? null,+ gpu_layers: payload.gpuLayers ?? null,+ n_cpu_moe: payload.nCpuMoe ?? null,+ selected_gpu_ids: payload.selectedGpuIds ?? null,+ llama_extra_args: payload.llamaExtraArgs ?? null,+ });+}++/**+ * 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.+ */+function finiteBytes(value: unknown, fallback: number): number {+ return typeof value === "number" && Number.isFinite(value) && value >= 0+ ? value+ : fallback;+}++/** A count (context, slots, layers) rather than a byte size: same guard, no fallback+ * chain, and null stays null where null is the "unknown" the row prints. */+function finiteCount(value: unknown, fallback: number): number {+ return typeof value === "number" && Number.isFinite(value) && value >= 0+ ? Math.trunc(value)+ : fallback;+}++function nullableCount(value: unknown): number | null {+ return typeof value === "number" && Number.isFinite(value) && value >= 0+ ? Math.trunc(value)+ : null;+}++/** A flag whose ABSENCE is meaningful, so a non-boolean is treated as absent rather+ * than coerced: `Boolean("false")` is true, and these decide what the row claims. */+function flag(value: unknown, fallback: boolean): boolean {+ return typeof value === "boolean" ? value : fallback;+}++const ESTIMATE_REASONS: readonly MemoryEstimateReason[] = [+ "not_gguf",+ "not_downloaded",+ "unsupported_source",+ "unsizable",+];++function toMemoryEstimate(body: ApiEstimateResponse): MemoryEstimate {+ const drafterRuntimeBytes = finiteBytes(body.drafter_runtime_bytes, 0);+ return {+ available: flag(body.available, false),+ // A reason the panel has no copy for is not a reason. An unknown string would+ // reach the copy map and render nothing at all.+ reason: ESTIMATE_REASONS.includes(body.reason as MemoryEstimateReason)+ ? (body.reason as MemoryEstimateReason)+ : null,+ weightsBytes: finiteBytes(body.weights_bytes, 0),+ kvBytes: finiteBytes(body.kv_bytes, 0),+ computeBytes: finiteBytes(body.compute_bytes, 0),+ drafterRuntimeBytes,+ // Absent on a backend predating the split: fall back to the whole term, which+ // keeps the old "all of it is on the GPU" reading rather than inventing a zero+ // that would silently drop a real VRAM charge off the row.+ drafterRuntimeGpuBytes: finiteBytes(+ body.drafter_runtime_gpu_bytes,+ drafterRuntimeBytes,+ ),+ projectorRuntimeBytes: finiteBytes(body.projector_runtime_bytes, 0),+ drafterKvUnsized: flag(body.drafter_kv_unsized, false),+ // Absent on a backend that predates the adapter term, and false is the right+ // reading there: it charged no adapters, so it claimed no floor.+ adaptersUnsized: flag(body.adapters_unsized, false),+ totalBytes: finiteBytes(body.total_bytes, 0),+ gpuBytes: finiteBytes(body.gpu_bytes, 0),+ // Absent on an older backend: treat the KV figure as unverified, the safe+ // direction for the one number that can dwarf all the others.+ kvEstimable: flag(body.kv_estimable, false),+ kvOnGpu: flag(body.kv_on_gpu, true),+ nCtx: finiteCount(body.n_ctx, 0),+ cacheTypeKv:+ typeof body.cache_type_kv === "string" ? body.cache_type_kv : null,+ nParallel: finiteCount(body.n_parallel, 1),+ layerCount: nullableCount(body.layer_count),+ gpuLayers: nullableCount(body.gpu_layers),+ moeOffloadUnmodelled: flag(body.moe_offload_unmodelled, false),+ };+}++/**+ * Statuses that say the ROUTE is not there, as distinct from this request failing.+ *+ * 404 and 405 are a backend predating it (405 because a router that owns the path for+ * another method answers that instead), 501 one that answers but declines. Everything+ * else -- 401, 422, 500, a gateway error, a body that is not JSON -- is about this+ * request or this moment, and says nothing about whether the route exists.+ */+function routeAbsentStatus(status: number): boolean {+ return status === 404 || status === 405 || status === 501;+}++/**+ * 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.+ *+ * 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.+ */+const ROUTE_ABSENT_TTL_MS = 5 * 60 * 1000;+let routeAbsentAt: number | null = null;++/** Forget a recorded miss. For tests, and for any caller that learns the backend+ * changed underneath it before the window is up. */+export function resetMemoryEstimateRouteMemo(): void {+ routeAbsentAt = null;+}++/**+ * Price a prospective GGUF load from its header. Allocates nothing, loads nothing.+ *+ * Never throws for a backend answer: every failure -- an absent route, an auth+ * expiry, a 500, a proxy's HTML error page served as 200, a truncated body -- comes+ * back as an unavailable estimate, so the panel hides the row and the Load button+ * beside it is untouched. The statuses are told apart only to decide whether the miss+ * is worth remembering; the row's own reading of them is identical.+ */+export async function fetchMemoryEstimate(+ payload: MemoryEstimateRequest,+ signal?: AbortSignal,+): Promise<MemoryEstimate> {+ if (+ routeAbsentAt !== null &&+ Date.now() - routeAbsentAt < ROUTE_ABSENT_TTL_MS+ ) {+ return UNAVAILABLE;+ }+ let nativePathLease: string | null = null;+ if (payload.nativePathToken) {+ try {+ nativePathLease = (+ await consumeNativePathToken(payload.nativePathToken, "validate-model")+ ).nativePathLease;+ } catch {+ // Lease expired / revoked. Nothing was read, so there is no estimate to give.+ return { ...UNAVAILABLE, reason: "unsupported_source" };+ }+ }+ const response = await authFetch("/api/inference/estimate-memory", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ signal,+ body: estimateRequestBody(payload, nativePathLease),+ });+ if (!response.ok) {+ // Only a structural miss latches. A transient 500 explicitly CLEARS the memo+ // rather than leaving an older one standing: a backend that is answering at all,+ // however badly, is not one that is missing the route.+ routeAbsentAt = routeAbsentStatus(response.status) ? Date.now() : null;+ return UNAVAILABLE;+ }+ routeAbsentAt = null;+ let body: unknown;+ try {+ body = await response.json();+ } catch {+ // A 200 that is not JSON: a captive portal or a dev proxy serving its own HTML,+ // or a body cut short. Nothing was measured, so there is nothing to show.+ return UNAVAILABLE;+ }+ if (typeof body !== "object" || body === null) {+ return UNAVAILABLE;+ }+ return toMemoryEstimate(body as ApiEstimateResponse);+}diff --git a/studio/frontend/src/features/model-picker/components/model-config-page.tsx b/studio/frontend/src/features/model-picker/components/model-config-page.tsxindex 3db093c12f6..46ba3e6a9eb 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@@ -17,6 +17,7 @@ import { usePlatformStore } from "@/config/env";import {GPU_LAYERS_AUTO,fetchGgufStagedMetadata,+ readPersistedGpuMemoryMode,readPersistedSpeculativeType,resolveStagedDiffusionClassification,useChatRuntimeStore,@@ -42,7 +43,13 @@ import {pinnableGpuContext,reconcileGpuSelection,useGpuDevices,+ useInferenceGpuInfo,} from "@/hooks/use-gpu-info";+import {+ DEFAULT_VRAM_FRACTION,+ aggregateUsableFreeVramGb,+ resolveMemoryCapacityGb,+} from "@/hooks/gpu-vram";import { ChevronDownStandardIcon } from "@/lib/chevron-icons";import { toast } from "@/lib/toast";import { ArrowLeft01Icon } from "@hugeicons/core-free-icons";@@ -52,6 +59,7 @@ import {type Ref,useEffect,useId,+ useMemo,useRef,useState,useSyncExternalStore,@@ -67,6 +75,16 @@ import {loadManagedLlamaFlags,subscribeLlamaFlagCatalog,} from "../api/llama-flags";+import { type MemoryEstimate } from "../api/memory-estimate";+import { resolveEstimateContext } from "../model-config/estimate-context";+import {+ type MemoryFitVerdict,+ formatMemoryGb,+ resolveDraftCacheNote,+ resolveKvNote,+ resolveMemoryFit,+} from "../model-config/memory-fit";+import { useMemoryEstimate } from "../hooks/use-memory-estimate";import {fetchLoadModelOverride,fromApiOverride,@@ -890,6 +908,226 @@ function AdvancedSettingsToggle({);}+const MEMORY_VALUE_TONE: Record<MemoryFitVerdict, string> = {+ fits: "text-nav-fg",+ tight: "text-amber-500",+ exceeds: "text-red-500",+ unknown: "text-nav-fg",+};++/** One "GPU 29.41 GB" pill: dim caption, figure on the shared control surface. */+function MemoryFigure({+ label,+ value,+ tone,+}: {+ label: string;+ value: string;+ tone?: string;+}) {+ return (+ <div className="flex shrink-0 items-center gap-1.5">+ <span className="text-ui-11 font-medium leading-none tracking-nav text-muted-foreground">+ {label}+ </span>+ <span+ className={`inline-flex h-6 items-center ${CONTROL_SURFACE} px-2 text-ui-12 font-medium tabular-nums ${tone ?? "text-nav-fg"}`}+ >+ {value}+ </span>+ </div>+ );+}++function MemoryBreakdownLine({+ label,+ value,+ note,+ muted,+}: {+ label: string;+ value: string;+ note?: string;+ muted?: boolean;+}) {+ return (+ <div className="flex items-baseline justify-between gap-3">+ <span className="min-w-0 text-ui-11 leading-relaxed text-muted-foreground">+ {label}+ {note ? (+ <span className="ml-1 text-muted-foreground/70">{note}</span>+ ) : null}+ </span>+ <span+ className={`shrink-0 text-ui-11 tabular-nums ${muted ? "text-muted-foreground" : "text-nav-fg"}`}+ >+ {value}+ </span>+ </div>+ );+}++/**+ * "Estimated Memory Usage": what the settings above would cost, before they are run.+ *+ * Figures come from the loader's own sizing, not a weights-times-a-constant rule of+ * thumb, which stops working the moment the KV cache is no longer a rounding error.+ * So KV gets its own line, and when the header cannot size it the row quotes a floor+ * instead of a confident total.+ */+function MemoryEstimateRow({+ estimate,+ loading,+ stale,+ gpuCapacityGb,+ totalCapacityGb,+ systemRamCapacityGb,+ freeGpuCapacityGb,+ usableSystemRamGb,+ isUnifiedMemory,+ singleMemoryPool,+ expanded,+ onExpandedChange,+}: {+ estimate: MemoryEstimate | null;+ loading: boolean;+ stale: boolean;+ /** VRAM available, or the shared pool where there is only one. 0 when unknown. */+ gpuCapacityGb: number;+ /** GPU plus host RAM, the ceiling an offloaded load works against. 0 when unknown. */+ totalCapacityGb: number;+ /** Host RAM alone. The bytes a load pins OUTSIDE the GPU have to fit in this, and+ * unused VRAM cannot help them, so it is a separate question from the total. */+ systemRamCapacityGb: number;+ /** VRAM free on the usable cards right now. Warns only: see the note at the call+ * site for why this may not refuse a load. 0 when nothing was probed. */+ freeGpuCapacityGb: number;+ /** Host RAM the machine can hand out right now, less the reserve the loader keeps.+ * Warns only, for the same reason the free-VRAM figure does. 0 when unknown. */+ usableSystemRamGb: number;+ isUnifiedMemory: boolean;+ /** GPU and host draw on the same memory, so an offloaded byte is not a freed one. */+ singleMemoryPool: boolean;+ expanded: boolean;+ onExpandedChange: (next: boolean) => void;+}) {+ const contentId = useId();+ if (!estimate?.available) {+ // Nothing honest to show. Silent while loading too, so the row does not flicker.+ return null;+ }+ // Every verdict and the one advisory paragraph, resolved in ../model-config/memory-fit.+ // Kept out of this file so the node test runner can reach it: the chain is long, the+ // cases it distinguishes are all hardware shapes nobody has on the desk, and while it+ // lived here an arm that could never be taken shipped unnoticed.+ const { gpuFit, totalFit, prefix, advisory } = resolveMemoryFit(estimate, {+ gpuCapacityGb,+ totalCapacityGb,+ systemRamCapacityGb,+ freeGpuCapacityGb,+ usableSystemRamGb,+ singleMemoryPool,+ });+ const kvNote = resolveKvNote(estimate);+ const draftCacheNote = resolveDraftCacheNote(+ estimate.drafterRuntimeGpuBytes,+ estimate.drafterRuntimeBytes,+ );+ return (+ <div className="space-y-2">+ <div className={ROW_CLASS}>+ <button+ type="button"+ onClick={() => onExpandedChange(!expanded)}+ aria-expanded={expanded}+ aria-controls={contentId}+ className="flex min-w-0 items-center gap-1.5 rounded-sm text-left focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"+ >+ <span className={LABEL_CLASS}>Estimated Memory Usage</span>+ <span className="shrink-0 rounded-full bg-black/[0.06] px-1.5 py-px text-ui-10 font-medium uppercase leading-[1.4] tracking-wider text-muted-foreground dark:bg-white/[0.08]">+ Beta+ </span>+ <HugeiconsIcon+ icon={ChevronDownStandardIcon}+ className={`size-3 shrink-0 text-muted-foreground transition-transform ${expanded ? "rotate-180" : ""}`}+ strokeWidth={1.75}+ />+ </button>+ <div+ className={`flex shrink-0 items-center gap-3 transition-opacity ${stale || loading ? "opacity-50" : ""}`}+ >+ {/* One pool: offloading a layer moves it within the same memory rather+ than out of it, so the honest single figure is the total. Reporting+ the GPU share here let a zero-layer load read as almost free. */}+ <MemoryFigure+ label={singleMemoryPool ? (isUnifiedMemory ? "Unified" : "Shared") : "GPU"}+ value={`${prefix}${formatMemoryGb(+ singleMemoryPool ? estimate.totalBytes : estimate.gpuBytes,+ )}`}+ tone={MEMORY_VALUE_TONE[singleMemoryPool ? totalFit : gpuFit]}+ />+ {singleMemoryPool ? null : (+ <MemoryFigure+ label="Total"+ value={`${prefix}${formatMemoryGb(estimate.totalBytes)}`}+ tone={MEMORY_VALUE_TONE[totalFit]}+ />+ )}+ </div>+ </div>+ {expanded && (+ <div id={contentId} className="space-y-1 pl-0.5">+ <MemoryBreakdownLine+ label="Weights"+ value={formatMemoryGb(estimate.weightsBytes)}+ note={+ estimate.gpuLayers != null && estimate.layerCount != null+ ? `${estimate.gpuLayers} of ${estimate.layerCount + 1} layers on GPU`+ : undefined+ }+ />+ <MemoryBreakdownLine+ label="KV cache"+ value={+ estimate.kvEstimable ? formatMemoryGb(estimate.kvBytes) : "unknown"+ }+ note={estimate.kvEstimable ? kvNote : undefined}+ muted={!estimate.kvEstimable}+ />+ <MemoryBreakdownLine+ label="Compute buffers"+ value={formatMemoryGb(estimate.computeBytes)}+ />+ {/* The encoder's buffers, which run about 1.3x the projector file. Only on a+ vision load, and named separately since the file is already in Weights. */}+ {estimate.projectorRuntimeBytes > 0 && (+ <MemoryBreakdownLine+ label="Vision encoder"+ value={formatMemoryGb(estimate.projectorRuntimeBytes)}+ />+ )}+ {/* Only when speculation loads a separate drafter, and it is the term most+ likely to surprise: its cache grows with context like the target's. */}+ {estimate.drafterRuntimeBytes > 0 && (+ <MemoryBreakdownLine+ label="Draft cache"+ value={formatMemoryGb(estimate.drafterRuntimeBytes)}+ note={draftCacheNote}+ />+ )}+ </div>+ )}+ {advisory && (+ <p+ className={`text-ui-11 leading-relaxed ${advisory.tone === "warn" ? "text-amber-500" : "text-muted-foreground"}`}+ >+ {advisory.text}+ </p>+ )}+ </div>+ );+}+function MlxAdvancedSettings({config,update,@@ -1815,6 +2053,11 @@ export function ModelConfigPage({const rememberRef = useRef(remember);rememberRef.current = remember;const [speculativeFallback] = useState(readPersistedSpeculativeType);+ // Same substitution as speculativeFallback, for the same reason: only "manual" is+ // persisted per model, so an absent mode means "follow the standing preference"+ // rather than Auto. applyPerModelConfigToRuntime resolves it that way at load, so+ // pricing the absence as Auto rated a Manual launch against the wrong plan.+ const [gpuMemoryModeFallback] = useState(readPersistedGpuMemoryMode);const [templateOpen, setTemplateOpen] = useState(false);// Raised by the extra-arguments row when what is typed is something// validate_extra_args would refuse, so the load is not started to fail. Held by@@ -2397,6 +2640,9 @@ export function ModelConfigPage({target.meta.contextLength ?? stagedDims?.contextLength ?? null;const activeLoadedContext =isActiveModel && target.isGguf ? loadedContextLength : null;+ // resolveLoadMaxSeqLength returns 0 for a builtin-default GGUF load before it looks+ // at the resident context, so the estimate must not fall back to it either.+ const activePresetSource = useChatRuntimeStore((s) => s.activePresetSource);const minContext = CONTEXT_LENGTH_MIN;const maxContext = Math.max(minContext,@@ -2483,6 +2729,153 @@ export function ModelConfigPage({? { ...loadableConfig, customContextLength: activeLoadedContext }: loadableConfig: loadableConfig;+ const runtimeGpuMemoryMode =+ runtimeConfig.gpuMemoryMode ?? gpuMemoryModeFallback;+ // Priced against the config that would actually load, at the context on screen, so+ // the figures answer for what the Load button will do. Diffusion stands down: its+ // runner allocates on a different plan than llama-server's.+ //+ // The tri-state is read as a tri-state here, not through resolvedIsDiffusion, which+ // folds "not yet classified" in with "not diffusion". A GGUF whose classification is+ // still in flight may be DiffusionGemma, and starting the llama-server estimate on+ // that guess paints a footprint from the wrong allocation plan -- one that stays on+ // screen indefinitely if the classifying probe never answers, since the tri-state+ // then never leaves undefined. Waiting costs a moment of no row; guessing costs a+ // confident wrong number, which is the trade this whole panel is written around.+ const memoryEstimateRequest =+ target.isGguf && classifiedIsDiffusion === false+ ? {+ modelPath: target.id,+ ggufVariant: target.ggufVariant ?? null,+ hfToken: hfToken || null,+ nativePathToken,+ // The context the Load button sends, not the one the control displays: an+ // unset length with no header yet shows 32,768 and loads at native.+ nCtx: resolveEstimateContext(+ runtimeConfig.customContextLength ?? null,+ activeLoadedContext,+ // The two shapes where resolveLoadMaxSeqLength answers 0 before it+ // reaches the resident context: --fit owns the sizing, or a+ // builtin-default preset on a GGUF load.+ (target.isGguf === true &&+ runtimeGpuMemoryMode === "manual" &&+ (runtimeConfig.gpuLayers ?? GPU_LAYERS_AUTO) < 0) ||+ (target.isGguf === true && activePresetSource === "builtin-default"),+ ),+ cacheTypeKv: runtimeConfig.kvCacheDtype,+ nParallel: runtimeConfig.nParallel,+ nBatch: runtimeConfig.nBatch,+ nUbatch: runtimeConfig.nUbatch,+ ctxCheckpoints: runtimeConfig.ctxCheckpoints ?? null,+ // The same substitution applyPerModelConfigToRuntime makes at load: a model+ // with no per-model override sends null, which the backend reads as Auto,+ // while the selector has been showing the global fallback all along. With+ // the global set to Off and an 11 GB DSpark sidecar in the repo, the row+ // charged the sidecar for a load that disables it.+ speculativeType: runtimeConfig.speculativeType ?? speculativeFallback ?? null,+ specDraftNMax: runtimeConfig.specDraftNMax,+ specDraftCacheType: runtimeConfig.specDraftCacheDtype ?? null,+ tensorParallel: runtimeConfig.tensorParallel,+ disableVision: runtimeConfig.disableVision,+ gpuMemoryMode: runtimeGpuMemoryMode,+ gpuLayers:+ runtimeConfig.gpuLayers != null &&+ runtimeConfig.gpuLayers !== GPU_LAYERS_AUTO+ ? runtimeConfig.gpuLayers+ : null,+ nCpuMoe: runtimeConfig.nCpuMoe ?? null,+ selectedGpuIds: runtimeConfig.selectedGpuIds ?? null,+ llamaExtraArgs: runtimeConfig.llamaExtraArgs ?? null,+ }+ : null;+ const memoryEstimate = useMemoryEstimate(memoryEstimateRequest);+ const [memoryBreakdownOpen, setMemoryBreakdownOpen] = useState(false);+ const inferenceGpu = useInferenceGpuInfo();+ // A pin can only draw on the cards it names, so the verdict is measured against+ // those. Judging a one-card pin against a two-card total called an 8 GB load a fit+ // on 16 GB of VRAM it could not reach.+ const pinnedGpuIds = runtimeConfig.selectedGpuIds;+ // The VRAM Budget slider sits in this same panel and caps what the next load may+ // claim per GPU, so the verdict has to be measured against the capped figure or the+ // row contradicts the control directly above it. Subscribed as well as read once:+ // dragging that slider must re-classify without a remount.+ // Seeded with the loader's own default rather than a full card. The read is async+ // and returns null on failure -- an older backend has no such route -- and in both+ // windows the launch still applies VRAM_FRACTION_DEFAULT. Starting at 1 claimed a+ // reserve no setting of that slider ever gives back, so the row read a hair+ // optimistic until the answer arrived and stayed there if it never did.+ const [memoryVramBudgetFraction, setMemoryVramBudgetFraction] =+ useState(DEFAULT_VRAM_FRACTION);+ useEffect(() => {+ let cancelled = false;+ loadVramBudgetSettings().then((loaded) => {+ if (!cancelled && loaded) {+ setMemoryVramBudgetFraction(loaded.fraction);+ }+ });+ const unsubscribe = subscribeVramBudgetSettings((next) => {+ setMemoryVramBudgetFraction(next.fraction);+ });+ return () => {+ cancelled = true;+ 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.+ //+ // 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.+ const memoryBudgetGovernsLaunch =+ runtimeGpuMemoryMode !== "manual" ||+ (runtimeConfig.gpuLayers ?? GPU_LAYERS_AUTO) < 0;+ const memoryEffectiveBudgetFraction = memoryBudgetGovernsLaunch+ ? memoryVramBudgetFraction+ : 1;+ const memoryFreeGpuCapacityGb = useMemo(() => {+ const pinned =+ pinnedGpuIds && pinnedGpuIds.length > 0+ ? gpuDevices.filter((device) => pinnedGpuIds.includes(device.index))+ : gpuDevices;+ // Per device, and by the loader's absolute-reserve rule rather than a+ // multiplication: the budget is subtracted from the card, not applied to what+ // happens to be free, and the two agree only on an idle one.+ //+ // Aggregated with the same count-the-shared-pool-once rule the TOTALS use. A+ // plain sum over a mixed inventory counted the iGPU's share of host RAM a second+ // time, and this figure is what freeGpuFit -- and through it the fit verdict --+ // is measured against.+ // The reserve keeps its budget-derived floor even for a fixed Manual placement:+ // what is free right now still constrains the launch, whatever set the number.+ return aggregateUsableFreeVramGb(pinned, memoryEffectiveBudgetFraction);+ }, [gpuDevices, pinnedGpuIds, memoryEffectiveBudgetFraction]);+ const {+ gpuCapacityGb: memoryGpuCapacityGb,+ totalCapacityGb: memoryTotalCapacityGb,+ singleMemoryPool,+ } = resolveMemoryCapacityGb({+ gpuBudgetFraction: memoryEffectiveBudgetFraction,+ pinnedDevices:+ pinnedGpuIds && pinnedGpuIds.length > 0+ ? gpuDevices.filter((device) => pinnedGpuIds.includes(device.index))+ : [],+ hostGpuTotalGb: inferenceGpu.memoryTotalGb,+ hostDedicatedGpuTotalGb: inferenceGpu.dedicatedMemoryTotalGb,+ hostSharesSystemRam: inferenceGpu.sharedMemory,+ systemRamTotalGb: inferenceGpu.systemRamTotalGb,+ unifiedMemory: isUnifiedMemory,+ });+const rememberChanged = remember !== savedRemember;const persistenceOnly = isActiveModel && atBaseline && rememberChanged;const primaryActionLabel = persistenceOnly@@ -2700,6 +3093,34 @@ export function ModelConfigPage({<div className="space-y-3.5">{target.isGguf && (<>+ {/* Above Context Length on purpose: that is the control moving this+ number most, and a readout below it is one you go looking for. */}+ <MemoryEstimateRow+ estimate={memoryEstimate.estimate}+ loading={memoryEstimate.loading}+ stale={memoryEstimate.stale}+ gpuCapacityGb={memoryGpuCapacityGb}+ totalCapacityGb={memoryTotalCapacityGb}+ systemRamCapacityGb={inferenceGpu.systemRamTotalGb}+ freeGpuCapacityGb={memoryFreeGpuCapacityGb}+ 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 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.+ (inferenceGpu.systemRamAvailableHostGb || 0) - 2,+ )}+ isUnifiedMemory={isUnifiedMemory}+ singleMemoryPool={singleMemoryPool}+ expanded={memoryBreakdownOpen}+ onExpandedChange={setMemoryBreakdownOpen}+ /><div className="space-y-3"><div className={ROW_CLASS}><div className="flex min-w-0 items-center gap-1.5">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.tsnew file mode 100644index 00000000000..f77b7d16258--- /dev/null+++ b/studio/frontend/src/features/model-picker/hooks/use-memory-estimate.ts@@ -0,0 +1,142 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import { useEffect, useRef, useState } from "react";+import {+ type MemoryEstimate,+ type MemoryEstimateRequest,+ fetchMemoryEstimate,+} from "../api/memory-estimate";+import {+ resolveEstimateSourceIdentity,+ resolveTokenIdentity as tokenIdentity,+} from "../model-config/estimate-context";++/** Long enough that a slider drag lands one request, not sixty; short enough that+ * letting go feels immediate. The fetch itself is a header walk, tens of ms. */+const ESTIMATE_DEBOUNCE_MS = 250;++export interface MemoryEstimateState {+ estimate: MemoryEstimate | null;+ /** First fetch for this model, nothing to show yet. A re-price keeps the old+ * numbers up and sets `stale` instead, so the row never blinks on a slider step. */+ loading: boolean;+ /** The numbers shown are for older settings; a fresh answer is on its way. */+ stale: boolean;+}++/** Everything that changes the answer. Settings the backend ignores stay out, or+ * the row re-fetches for nothing. */+function estimateKey(request: MemoryEstimateRequest | null): string | null {+ if (!request) return null;+ return JSON.stringify([+ request.modelPath,+ request.ggufVariant ?? null,+ tokenIdentity(request.hfToken),+ request.nativePathToken ?? null,+ request.nCtx ?? null,+ request.cacheTypeKv ?? null,+ request.nParallel ?? null,+ request.nBatch ?? null,+ request.nUbatch ?? null,+ request.ctxCheckpoints ?? null,+ request.speculativeType ?? null,+ request.specDraftNMax ?? null,+ request.specDraftCacheType ?? null,+ request.tensorParallel ?? false,+ request.disableVision ?? false,+ request.gpuMemoryMode ?? null,+ request.gpuLayers ?? null,+ request.nCpuMoe ?? null,+ request.selectedGpuIds ?? null,+ request.llamaExtraArgs ?? null,+ ]);+}++/**+ * Debounced memory estimate for a prospective load. Pass null to stand down.+ *+ * In-flight requests abort when the settings move again, so a slow answer for a+ * context already dragged past cannot overwrite a newer one.+ */+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.+ const currentIdentity =+ request == null+ ? null+ : resolveEstimateSourceIdentity(+ request.modelPath,+ request.ggufVariant,+ tokenIdentity(request.hfToken),+ request.nativePathToken,+ );+ const [state, setState] = useState<MemoryEstimateState & { identity: string | null }>({+ estimate: null,+ loading: false,+ stale: false,+ identity: null,+ });+ // Read inside the effect so it depends on the key alone: `request` is a fresh+ // object every render and would restart the debounce on any keystroke.+ const latestRequest = useRef(request);+ latestRequest.current = request;+ // Which model the numbers belong to. A switch must clear them: one model's+ // footprint under another's name is worse than none. The quantization counts as a+ // switch -- Q4_K_M to F16 on one repository leaves modelPath alone while the+ // weights quadruple -- so this is the source identity, not the path.+ const shownModel = useRef<string | null>(null);++ useEffect(() => {+ const pending = latestRequest.current;+ if (key == null || pending == null) {+ shownModel.current = null;+ setState({ estimate: null, loading: false, stale: false, identity: null });+ return;+ }+ const identity = resolveEstimateSourceIdentity(+ pending.modelPath,+ pending.ggufVariant,+ tokenIdentity(pending.hfToken),+ pending.nativePathToken,+ );+ const modelChanged = shownModel.current !== identity;+ setState((current) =>+ modelChanged+ ? { estimate: null, loading: true, stale: false, identity }+ : { ...current, loading: current.estimate == null, stale: true, identity },+ );+ const controller = new AbortController();+ const timer = setTimeout(() => {+ fetchMemoryEstimate(pending, controller.signal)+ .then((estimate) => {+ if (controller.signal.aborted) return;+ shownModel.current = identity;+ setState({ estimate, loading: false, stale: false, identity });+ })+ .catch(() => {+ if (controller.signal.aborted) return;+ // A failed estimate is not a failed panel; drop the row.+ shownModel.current = identity;+ setState({ estimate: null, loading: false, stale: false, identity });+ });+ }, ESTIMATE_DEBOUNCE_MS);+ return () => {+ clearTimeout(timer);+ controller.abort();+ };+ }, [key]);++ // State that belongs to a different source is not shown at all, not even for the+ // frame before the effect clears it.+ if (state.identity !== currentIdentity) {+ return { estimate: null, loading: currentIdentity != null, stale: false };+ }+ return { estimate: state.estimate, loading: state.loading, stale: state.stale };+}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.tsnew file mode 100644index 00000000000..e23bd38fc01--- /dev/null+++ b/studio/frontend/src/features/model-picker/model-config/estimate-context.ts@@ -0,0 +1,102 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++/**+ * The context the memory estimate should PRICE, which is not always the context+ * 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.+ *+ * 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 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.+ */+export function resolveEstimateContext(+ customContextLength: number | null,+ activeLoadedContext: number | null,+ skipResidentFallback = false,+): 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.+ return customContextLength && customContextLength > 0 ? customContextLength : 0;+ }+ return customContextLength ?? activeLoadedContext ?? 0;+}++/**+ * Which MODEL an estimate belongs to, for deciding whether shown numbers still do.+ *+ * Not the same question as "did anything change" -- that is the full request key,+ * and a slider step must keep the old figures up and mark them stale rather than+ * blank the row. This is the narrower one: a change here means the numbers on+ * screen describe a DIFFERENT file, so they have to go, not go grey.+ *+ * The quantization is part of it, which is the whole reason this exists. Switching+ * Q4_K_M to F16 on the same repository leaves `modelPath` untouched while the+ * weights roughly quadruple, so keying on the path alone left one quant's footprint+ * displayed under another's name -- the exact thing the caller says must not happen.+ * The token identity and the native path token are here for the same reason: both+ * select which file the backend resolves.+ */+/**+ * Identity of a token without the token.+ *+ * The backend resolves and caches gated repositories per token, so swapping one for+ * another has to re-fetch, but the credential itself has no business sitting in a+ * React dependency key.+ *+ * djb2, because this only has to separate two strings held in this tab, never to+ * resist anyone, and it has to be synchronous (SubtleCrypto is not). It is 32 bits, so+ * a collision is constructible: two colliding credentials would leave one's estimate+ * on screen under the other, because the same value keys both the refetch and the+ * blank-the-row check. The bound is the number of tokens compared IN ONE TAB, which is+ * two -- the one that was set and the one that replaced it -- so the odds are ~2^-32+ * per swap and the consequence is a stale byte count on a row already labelled Beta,+ * not an incorrect load. Widening it is not worth a second hash; noting it is.+ */+export function resolveTokenIdentity(+ token: string | null | undefined,+): string {+ if (!token) return "";+ let hash = 5381;+ for (let i = 0; i < token.length; i++) {+ hash = ((hash << 5) + hash + token.charCodeAt(i)) | 0;+ }+ return (hash >>> 0).toString(36);+}++export function resolveEstimateSourceIdentity(+ modelPath: string,+ ggufVariant: string | null | undefined,+ tokenIdentity: string,+ nativePathToken: string | null | undefined,+): string {+ return JSON.stringify([+ modelPath,+ ggufVariant ?? null,+ tokenIdentity,+ nativePathToken ?? null,+ ]);+}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.tsnew file mode 100644index 00000000000..0eea1e416fa--- /dev/null+++ b/studio/frontend/src/features/model-picker/model-config/memory-fit.ts@@ -0,0 +1,377 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++/**+ * 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.+ */++/** How an estimated footprint sits against the memory available to hold it. */+export type MemoryFitVerdict = "fits" | "tight" | "exceeds" | "unknown";++/** Above this share of the capacity the fit is reported as tight rather than clean. */+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.+ */+export function classifyMemoryFit(+ bytes: number,+ capacityGb: number,+): MemoryFitVerdict {+ // Nothing probed or nothing to weigh: no verdict rather than a false "fits".+ if (!Number.isFinite(bytes) || !Number.isFinite(capacityGb)) {+ return "unknown";+ }+ if (capacityGb <= 0 || bytes <= 0) {+ return "unknown";+ }+ const ratio = bytes / (capacityGb * 1024 ** 3);+ if (ratio > 1) {+ return "exceeds";+ }+ if (ratio > MEMORY_FIT_TIGHT_RATIO) {+ return "tight";+ }+ return "fits";+}++/** The worse of two verdicts, for a load that has to satisfy both at once. */+export function worseMemoryFit(+ a: MemoryFitVerdict,+ b: MemoryFitVerdict,+): MemoryFitVerdict {+ const rank: Record<MemoryFitVerdict, number> = {+ unknown: 0,+ fits: 1,+ tight: 2,+ exceeds: 3,+ };+ // unknown loses to any real verdict: one half being unmeasurable must not erase the+ // other half's answer.+ return rank[a] >= rank[b] ? a : b;+}++/**+ * GB, to two decimals, matching how 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.+ */+export function formatMemoryGb(bytes: number): string {+ const safe = Number.isFinite(bytes) && bytes > 0 ? bytes : 0;+ return `${(safe / 1024 ** 3).toFixed(2)} GB`;+}++/** At most one note under the figures, most actionable first. */+export interface MemoryAdvisory {+ /** `warn` is amber; `muted` is body text. */+ tone: "warn" | "muted";+ text: string;+}++/** The estimate fields the verdicts read, structurally. */+export interface MemoryFitEstimate {+ /** The share of the total that lands on the GPU under the requested offload. */+ gpuBytes: number;+ /** Weights + KV + compute, wherever they land. */+ totalBytes: number;+ /** False when the GGUF header could not size the cache, so the figures are a floor. */+ kvEstimable: boolean;+ /** A charged drafter whose cache could not be sized, so the figures are a floor. */+ drafterKvUnsized: boolean;+ adaptersUnsized: boolean;+ /** `--n-cpu-moe` is set, so the GPU figure ignores it and reads high. */+ moeOffloadUnmodelled: boolean;+}++/** What the load may draw on, as resolved by resolveMemoryCapacityGb and the host. */+export interface MemoryFitCapacity {+ /** VRAM available, or the shared pool where there is only one. 0 when unknown. */+ gpuCapacityGb: number;+ /** GPU plus host RAM, the ceiling an offloaded load works against. 0 when unknown. */+ totalCapacityGb: number;+ /** Host RAM alone. Bytes pinned OUTSIDE the GPU have to fit in this, and unused+ * VRAM cannot help them, so it is a separate question from the total. */+ systemRamCapacityGb: number;+ /** VRAM free on the usable cards right now. Warns only. 0 when nothing was probed. */+ freeGpuCapacityGb: number;+ /** Host RAM the machine can hand out right now, less the loader's reserve. Warns+ * only. 0 when unknown. */+ usableSystemRamGb: number;+ /** GPU and host draw on the same memory, so an offloaded byte is not a freed one. */+ singleMemoryPool: boolean;+}++export interface MemoryFitResult {+ /** The GPU verdict before the free-memory warning is folded in. */+ rawGpuFit: MemoryFitVerdict;+ /** What the GPU figure is coloured with: rawGpuFit, nudged to tight under pressure. */+ gpuFit: MemoryFitVerdict;+ /** The pool against what is free right now, capped at a warning by its caller. */+ freeGpuFit: MemoryFitVerdict;+ gpuPressured: boolean;+ /** Bytes this placement pins outside the GPU. */+ hostShareBytes: number;+ usableHostFit: MemoryFitVerdict;+ hostPressured: boolean;+ /** The host share against physical RAM. "unknown" where there is only one pool. */+ hostShareFit: MemoryFitVerdict;+ /** What the total figure is coloured with. */+ totalFit: MemoryFitVerdict;+ /** The figures are a lower bound, so they are printed with a leading marker. */+ bounded: boolean;+ /** The marker itself, empty when the figures are a real estimate. */+ prefix: string;+ advisory: MemoryAdvisory | null;+}++/**+ * 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.+ */+export function resolveMemoryFit(+ estimate: MemoryFitEstimate,+ capacity: MemoryFitCapacity,+): 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.+ 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.+ const hostShareBytes =+ Number.isFinite(estimate.totalBytes) && Number.isFinite(estimate.gpuBytes)+ ? Math.max(0, estimate.totalBytes - estimate.gpuBytes)+ : 0;+ // Same question for the other pool. See the note above on why this warns.+ const usableHostFit = classifyMemoryFit(+ singleMemoryPool ? estimate.totalBytes : hostShareBytes,+ capacity.usableSystemRamGb,+ );+ 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.+ const hostShareFit: MemoryFitVerdict = singleMemoryPool+ ? "unknown"+ : classifyMemoryFit(hostShareBytes, capacity.systemRamCapacityGb);+ const totalFit = worseMemoryFit(+ 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.+ const bounded =+ !estimate.kvEstimable || estimate.drafterKvUnsized || estimate.adaptersUnsized;+ return {+ rawGpuFit,+ gpuFit,+ freeGpuFit,+ gpuPressured,+ hostShareBytes,+ usableHostFit,+ hostPressured,+ hostShareFit,+ totalFit,+ bounded,+ prefix: bounded ? "≥ " : "",+ advisory: resolveMemoryAdvisory(estimate, {+ singleMemoryPool,+ totalFit,+ hostShareFit,+ gpuFit,+ rawGpuFit,+ gpuPressured,+ hostPressured,+ }),+ };+}++interface AdvisoryVerdicts {+ singleMemoryPool: boolean;+ totalFit: MemoryFitVerdict;+ hostShareFit: MemoryFitVerdict;+ gpuFit: MemoryFitVerdict;+ rawGpuFit: MemoryFitVerdict;+ gpuPressured: boolean;+ hostPressured: boolean;+}++/**+ * 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.+ *+ * 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.+ */+export function resolveMemoryAdvisory(+ estimate: MemoryFitEstimate,+ verdicts: AdvisoryVerdicts,+): MemoryAdvisory | null {+ if (!estimate.kvEstimable) {+ return {+ tone: "warn",+ text: "This GGUF's header doesn't carry the attention dimensions, so the KV cache can't be sized. The figures above are a floor, and the cache is usually the term that grows fastest with context.",+ };+ }+ if (estimate.drafterKvUnsized) {+ return {+ tone: "warn",+ text: "Part of this load is a file the server will fetch rather than one on this disk, so it can't be sized from here. The figures above are a floor.",+ };+ }+ if (estimate.moeOffloadUnmodelled) {+ return {+ tone: "muted",+ text: "Expert layers held on the CPU aren't modelled here, so the GPU figure reads high.",+ };+ }+ if (verdicts.singleMemoryPool) {+ if (verdicts.totalFit === "exceeds") {+ return {+ tone: "warn",+ text: "More than this machine's memory. The GPU and the rest of the system share one pool here, so there is nothing to offload to.",+ };+ }+ // One pool, so one pressure question however it was measured: the GPU's free+ // reading and the host's available reading are two views of the same bytes, and+ // either seeing pressure is the same news.+ if (verdicts.hostPressured || verdicts.gpuPressured) {+ return {+ tone: "muted",+ text: "This fits the machine, but not what is free right now. If that memory is not the model being replaced, the context will be fitted down or the load refused.",+ };+ }+ return null;+ }+ // Discrete memory, so the two verdicts are separate questions and the aggregate one+ // is asked FIRST. Reading gpuFit alone offered spilling to system RAM as the remedy+ // for a load that does not fit in GPU and RAM combined, which is advice to do+ // something that cannot work.+ if (verdicts.hostShareFit === "exceeds") {+ return {+ tone: "warn",+ text: "More than system RAM holds. This placement keeps most of the load outside the GPU, and spare VRAM cannot take those bytes.",+ };+ }+ if (verdicts.totalFit === "exceeds") {+ return {+ tone: "warn",+ text: "More than this machine holds. The GPU and system RAM together are not enough for this load, so spilling layers or fitting the context down will not recover it.",+ };+ }+ if (verdicts.gpuFit === "exceeds") {+ return {+ tone: "warn",+ text: "More than this GPU holds. Layers will spill to system RAM, or the context will be fitted down to what fits.",+ };+ }+ if (verdicts.hostPressured) {+ return {+ tone: "muted",+ text: "The part of this load that runs from system RAM fits the machine, but not what is free right now. If that memory is not the model being replaced, the load will be refused.",+ };+ }+ if (verdicts.rawGpuFit === "fits" && verdicts.gpuPressured) {+ return {+ tone: "muted",+ text: "This fits the card, but something is using it right now. If that memory is not the model being replaced, layers will spill or the context will be fitted down.",+ };+ }+ return null;+}++/** The KV line's caption: dtype, what was priced, and where it lives. */+export function resolveKvNote(estimate: {+ cacheTypeKv: string | null;+ nCtx: number;+ nParallel: number;+ kvOnGpu: boolean;+}): string {+ return [+ estimate.cacheTypeKv ?? "f16",+ // Off the wire, so it is not trusted to be a number: `.toLocaleString()` on a+ // null throws, and one bad field must not take the whole panel down.+ `${Number.isFinite(estimate.nCtx) ? Math.max(0, estimate.nCtx).toLocaleString() : "0"} tokens`,+ Number.isFinite(estimate.nParallel) && estimate.nParallel > 1+ ? `${estimate.nParallel} slots`+ : null,+ estimate.kvOnGpu ? null : "host RAM",+ ]+ .filter(Boolean)+ .join(" · ");+}++/**+ * Where the draft cache actually sits, read from its own GPU share rather than from+ * kvOnGpu.+ *+ * kvOnGpu is the TARGET cache's placement, and the two are set by different flags:+ * `--no-kv-offload` moves the target, `--spec-draft-ngl 0` moves the drafter. Off the+ * target flag this line was wrong in both directions -- silent about a genuinely+ * host-resident draft cache, and claiming "host RAM" for one the same response had+ * just charged to gpu_bytes. Under MTP the term is split across both placements, so+ * there is a third case that no boolean could have expressed.+ */+export function resolveDraftCacheNote(+ drafterRuntimeGpuBytes: number,+ drafterRuntimeBytes: number,+): string | undefined {+ if (!(drafterRuntimeGpuBytes > 0)) {+ return "host RAM";+ }+ if (drafterRuntimeGpuBytes < drafterRuntimeBytes) {+ return `${formatMemoryGb(drafterRuntimeGpuBytes)} on GPU`;+ }+ return undefined;+}diff --git a/studio/frontend/src/hooks/gpu-selection.ts b/studio/frontend/src/hooks/gpu-selection.tsindex add5e1bfb04..c9aa7a9f5cd 100644--- a/studio/frontend/src/hooks/gpu-selection.ts+++ b/studio/frontend/src/hooks/gpu-selection.ts@@ -10,6 +10,11 @@ export interface SystemGpuDevice {memoryTotalGb: number;/** Free VRAM at fetch time, or total VRAM when usage is unavailable. */memoryFreeGb: number;+ /** A Vulkan iGPU: memoryTotalGb is a capped view of system RAM rather than a+ * pool beside it. Per device, not per host: a mixed inventory pairs one of+ * these with a discrete card, and a pin naming only the discrete card can+ * still spill to host RAM. */+ sharedMemory: boolean;/** Whether `index` is safe to send as gpu_ids. */pinnable: boolean;/** Whether the separate DiffusionGemma runner can use this physical ID. */diff --git a/studio/frontend/src/hooks/gpu-vram.ts b/studio/frontend/src/hooks/gpu-vram.tsindex 9e9994fbd2f..a7d956ab458 100644--- a/studio/frontend/src/hooks/gpu-vram.ts+++ b/studio/frontend/src/hooks/gpu-vram.ts@@ -30,18 +30,149 @@ export interface VramReportingGpu {export function aggregateGpuMemoryTotalGb(devices: MemoryTotalDevice[],): number {+ // A probe reading, so it is not trusted to be a usable number: `?? 0` only defends+ // against null and undefined, and one NaN or Infinity in the list poisons the sum+ // and every fit verdict measured against it.+ const size = (device: MemoryTotalDevice) => {+ const total = device.memory_total_gb ?? 0;+ return Number.isFinite(total) && total > 0 ? total : 0;+ };const dedicated = devices.filter((device) => !device.shared_memory)- .reduce((sum, device) => sum + (device.memory_total_gb ?? 0), 0);+ .reduce((sum, device) => sum + size(device), 0);const shared = Math.max(0,- ...devices- .filter((device) => device.shared_memory)- .map((device) => device.memory_total_gb ?? 0),+ ...devices.filter((device) => device.shared_memory).map(size),);return Math.round((dedicated + shared) * 100) / 100;}+export interface MemoryCapacityInput {+ /** The devices a pin names, or empty when the load may use the whole host. */+ pinnedDevices: { memoryTotalGb: number; sharedMemory: boolean }[];+ /** Aggregate GPU budget of the whole inventory, for the unpinned case. */+ hostGpuTotalGb: number;+ /** The same aggregate with shared-memory devices left out, for the unpinned case.+ * Only the dedicated cards are memory BESIDE system RAM; an iGPU's budget is a+ * capped view of that same RAM, so adding both to reach a machine-wide ceiling+ * counts the shared bytes twice. Absent means "no shared device", i.e. the same+ * figure as `hostGpuTotalGb`. */+ hostDedicatedGpuTotalGb?: number;+ /** Whether ANY device on the host reports a shared pool. Only consulted when+ * nothing is pinned; a pin answers for itself. */+ hostSharesSystemRam: boolean;+ systemRamTotalGb: number;+ /** Apple Silicon: one pool for everything, whatever the devices say. */+ unifiedMemory: boolean;+ /** VRAM Budget: the fraction of each GPU a load may claim, from the setting beside+ * this row. 1 (or absent) means the whole card. Applied to the GPU figure only --+ * it caps what llama.cpp is allowed to take, not how much RAM the host has. */+ gpuBudgetFraction?: number;+}++/** What a prospective load may draw on: the GPU pool, and the ceiling once layers+ * spill to host RAM.+ *+ * System RAM is added only where it is a pool BESIDE the GPU budget. A Vulkan+ * iGPU's reported budget is already a capped view of that same RAM, so adding it+ * would count the bytes twice. That question is per device, not per host: a mixed+ * inventory pairs a discrete card with an iGPU, and a pin naming only the discrete+ * card can still spill into RAM the iGPU would have been sharing.+ *+ * Both figures are 0 when nothing was probed, which callers read as "no verdict"+ * rather than as a fit. */+export function resolveMemoryCapacityGb(input: MemoryCapacityInput): {+ gpuCapacityGb: number;+ totalCapacityGb: number;+ /** One pool for both figures, so a caller shows one number rather than two. */+ singleMemoryPool: boolean;+} {+ const pinnedGpuCapacityGb = aggregateGpuMemoryTotalGb(+ input.pinnedDevices.map((device) => ({+ memory_total_gb: device.memoryTotalGb,+ shared_memory: device.sharedMemory,+ })),+ );+ // One flag for both answers, so the capacity and the pool question cannot+ // disagree about which devices they are describing.+ const pinGoverns = pinnedGpuCapacityGb > 0;+ // The host figure comes from aggregateGpuMemoryTotalGb on the caller's side, which+ // guards itself, but this is a plain number on a public interface and a non-finite+ // one here would make every figure below NaN.+ const hostGpuTotalGb =+ Number.isFinite(input.hostGpuTotalGb) && input.hostGpuTotalGb > 0+ ? input.hostGpuTotalGb+ : 0;+ const rawGpuCapacityGb = pinGoverns ? pinnedGpuCapacityGb : hostGpuTotalGb;+ // The dedicated-only figure for the same governing set. A pin answers for itself;+ // unpinned takes the caller's, falling back to the full aggregate, which is the+ // right answer on every host that has no shared device at all.+ const rawDedicatedCapacityGb = pinGoverns+ ? aggregateGpuMemoryTotalGb(+ input.pinnedDevices+ .filter((device) => !device.sharedMemory)+ .map((device) => ({+ memory_total_gb: device.memoryTotalGb,+ shared_memory: false,+ })),+ )+ : Number.isFinite(input.hostDedicatedGpuTotalGb) &&+ (input.hostDedicatedGpuTotalGb as number) >= 0+ ? (input.hostDedicatedGpuTotalGb as number)+ : hostGpuTotalGb;+ // The budget is what the next load is ALLOWED to claim, so it is the capacity a+ // verdict should be measured against: at 80% a 20 GB footprint on a 24 GB card is+ // over the line the slider draws, and reading the raw total called it comfortable.+ // Guarded rather than trusted: a 0 or a missing value would silently zero the+ // capacity, which every caller reads as "nothing probed".+ const budget =+ typeof input.gpuBudgetFraction === "number" &&+ input.gpuBudgetFraction > 0 &&+ input.gpuBudgetFraction <= 1+ ? input.gpuBudgetFraction+ : 1;+ const gpuCapacityGb = Math.round(rawGpuCapacityGb * budget * 100) / 100;+ const dedicatedCapacityGb =+ Math.round(rawDedicatedCapacityGb * budget * 100) / 100;+ // Same guard as the device totals: psutil's figure arrives over the wire too, and a+ // non-finite one would turn the ceiling below into NaN, which classifyMemoryFit+ // reads as no verdict at all rather than as the RAM the machine plainly has.+ const systemRamTotalGb =+ Number.isFinite(input.systemRamTotalGb) && input.systemRamTotalGb > 0+ ? input.systemRamTotalGb+ : 0;+ // Every, for the same reason the host-level flag uses every: a pin naming a+ // discrete card alongside an iGPU still has dedicated VRAM beside system RAM, and+ // calling that one pool hides the GPU verdict on the only figure that would catch+ // a fixed placement too large for the card.+ const sharesSystemRam = pinGoverns+ ? input.pinnedDevices.length > 0 &&+ input.pinnedDevices.every((device) => device.sharedMemory)+ : input.hostSharesSystemRam;+ const singleMemoryPool = input.unifiedMemory || sharesSystemRam;+ return {+ gpuCapacityGb,+ totalCapacityGb: singleMemoryPool+ ? input.unifiedMemory+ // Apple reports the one pool as the GPU budget already.+ ? gpuCapacityGb+ // A Vulkan iGPU's budget is a CAPPED view of system RAM, so RAM must not be+ // added to it -- but it must not replace it either. The pool's real size is+ // the RAM, and taking the capped figure as the machine's whole capacity+ // called a 20 GB CPU-offloaded load impossible on a 91 GiB host because the+ // iGPU was allowed 12. The larger of the two is the pool; on a mixed+ // inventory that under-counts a discrete card sitting beside it, which is+ // the side that refuses a load rather than admitting one that cannot run.+ : Math.max(gpuCapacityGb, systemRamTotalGb)+ // Dedicated VRAM, not the whole GPU figure: on a mixed inventory the iGPU's+ // budget is already inside systemRamTotalGb, and adding it again inflated the+ // ceiling in the direction that admits a load. Identical to gpuCapacityGb on+ // any host without a shared device, which is every discrete-only machine.+ : dedicatedCapacityGb + systemRamTotalGb,+ singleMemoryPool,+ };+}+/** Whether every device reports its own usage, so each row and their sum are real. */export function gpuVramUsedIsPerDevice(devices: VramReportingDevice[],@@ -72,3 +203,85 @@ export function resolveGpuVramUsedGb(const aggregate = gpu?.vram_used_gb_aggregate;return Number.isFinite(aggregate) ? (aggregate as number) : null;}++/** The loader's default VRAM fraction (`_CTX_FIT_VRAM_FRACTION`). */+export const DEFAULT_VRAM_FRACTION = 0.97;+/** The loader's floor reserve (`_VRAM_FLOOR_RESERVE_MIB`), in GB. */+const VRAM_FLOOR_RESERVE_GB = 512 / 1024;++/**+ * Free VRAM a load may actually claim on one card, by the loader's own rule.+ *+ * `_vram_usable_mib` subtracts an ABSOLUTE reserve from what is free -- it does not+ * scale free memory by the fraction. The two agree only on an idle card. On a 24 GB+ * card with 10 GB free at an 80% budget the loader offers 5.2 GB while a+ * multiplication says 8, so a 7 GB load looked comfortable and will be fitted down.+ *+ * The floor keeps the budget monotonic: capped at the default's own reserve so that+ * nudging the slider up never hands back less, which a flat 512 MiB would do on any+ * card under about 17 GB.+ */+export function usableFreeVramGb(+ freeGb: number,+ totalGb: number,+ fraction: number,+): number {+ // Every argument is a probe reading off the wire. A NaN or an Infinity propagates+ // through the arithmetic below into a figure a fit verdict is drawn from, so it is+ // rejected here rather than at each of the four call sites.+ if (!Number.isFinite(freeGb) || freeGb <= 0) {+ return 0;+ }+ const total = Number.isFinite(totalGb) ? totalGb : 0;+ const frac =+ Number.isFinite(fraction) && fraction > 0 && fraction <= 1 ? fraction : 1;+ if (!(total > 0)) {+ // No total to take a percentage of; the free reading is the only scale there is,+ // and the loader falls back the same way.+ return Math.max(0, freeGb * frac);+ }+ const floor = Math.min(VRAM_FLOOR_RESERVE_GB, (1 - DEFAULT_VRAM_FRACTION) * total);+ const reserve = Math.max((1 - frac) * total, floor);+ return Math.max(0, freeGb - reserve);+}++/** A device as the free-VRAM aggregate sees it. Structural, so a SystemGpuDevice fits. */+export interface FreeVramDevice {+ memoryFreeGb?: number;+ memoryTotalGb?: number;+ /** True when this device's budget is a capped view of the host's own RAM. */+ sharedMemory?: boolean;+}++/**+ * Free memory a prospective load may claim across an inventory, counting a shared+ * host-memory pool only once.+ *+ * The same rule `aggregateGpuMemoryTotalGb` applies to totals, and for the same+ * reason: on a discrete-plus-iGPU host the iGPU's free reading IS the host's free RAM+ * seen through a cap, so adding it to the discrete card's free VRAM counts those+ * bytes twice and hands the free-memory verdict a capacity the machine does not have.+ * Summing blindly is worse here than for totals, because a shared device can report a+ * total of 0 (`hardware.py` zeroes it for an iGPU on one path), and `usableFreeVramGb`+ * then falls back to the raw free reading with no reserve subtracted at all.+ *+ * Several shared devices are several views of one pool, so the largest is taken+ * rather than their sum -- two iGPUs on one host do not have two pools.+ */+export function aggregateUsableFreeVramGb(+ devices: FreeVramDevice[],+ fraction: number,+): number {+ const usable = (device: FreeVramDevice) =>+ usableFreeVramGb(device.memoryFreeGb ?? 0, device.memoryTotalGb ?? 0, fraction);+ const dedicated = devices+ .filter((device) => !device.sharedMemory)+ .reduce((sum, device) => sum + usable(device), 0);+ const shared = Math.max(+ 0,+ ...devices.filter((device) => device.sharedMemory).map(usable),+ );+ // Devices arrive rounded to 2dp and the reserve is a fraction of them, so the sum+ // reintroduces float error the same way the totals aggregate does.+ return Math.round((dedicated + shared) * 100) / 100;+}diff --git a/studio/frontend/src/hooks/use-gpu-info.ts b/studio/frontend/src/hooks/use-gpu-info.tsindex 123891711b0..bb5671a0d63 100644--- a/studio/frontend/src/hooks/use-gpu-info.ts+++ b/studio/frontend/src/hooks/use-gpu-info.ts@@ -32,33 +32,54 @@ export {export interface GpuInfo {available: boolean;budgetKnown: boolean;+ /** A Vulkan iGPU: memoryTotalGb is a capped view of system RAM, not a pool+ * beside it, so callers must not add systemRamTotalGb on top of it. */+ sharedMemory: boolean;/** The backend torch resolved: cuda, rocm, xpu, mlx, cpu. Carried on every path, including the* GPU-less one, because "which runtimes can this host place" is exactly the question a host* with no usable GPU has to answer. Empty until system info arrives. */backend: string;name: string;memoryTotalGb: number;+ /** The same aggregate with shared-memory devices left out: the VRAM that is a pool+ * BESIDE system RAM rather than a capped view of it. */+ dedicatedMemoryTotalGb: number;/** Largest single device's VRAM. Image/video loads live on ONE device (no tensor split), so their fit math must use a single device, not the multi-GPU sum. */maxDeviceMemoryGb: number;/** VRAM of the device an image/video load actually lands on: the lowest visible ordinal, since resolve_diffusion_device_target() returns a bare "cuda" and torch places on the current device. On a heterogeneous host this is NOT maxDeviceMemoryGb, and sizing a pick against the larger card would recommend a checkpoint that OOMs the smaller one. */loadDeviceMemoryGb: number;cpuCore: number;cpuThread: number;+ /** Host RAM free right now, ZEROED on a host where any device shares that RAM.+ * The zero belongs to the SUM: every reader of this field adds it to the GPU+ * budget, and on a shared-memory host that would offer the same bytes twice. */systemRamAvailableGb: number;+ /** Host RAM free right now as the probe reported it, whatever the devices share.+ *+ * The field above cannot answer "is host RAM under pressure", because on a+ * dGPU + iGPU box it is permanently 0 -- `devices.some(...)` is a host-level OR, so+ * ONE Vulkan iGPU in the inventory zeroes the reading for the whole machine, and it+ * stays 0 even when the user has pinned the discrete card and host RAM is genuinely+ * a separate pool. `sharesSystemRam` in gpu-vram.ts already answers the pool+ * question per pin, which is the half that is right; this is the reading it needs. */+ systemRamAvailableHostGb: number;systemRamTotalGb: number;}const DEFAULT_GPU: GpuInfo = {available: false,budgetKnown: false,+ sharedMemory: false,backend: "",name: "Unknown",memoryTotalGb: 0,+ dedicatedMemoryTotalGb: 0,maxDeviceMemoryGb: 0,loadDeviceMemoryGb: 0,cpuCore: 0,cpuThread: 0,systemRamAvailableGb: 0,+ systemRamAvailableHostGb: 0,systemRamTotalGb: 0,};@@ -73,6 +94,7 @@ function toGpuInfo(cpuCore: data?.cpu?.physical_count ?? 0,cpuThread: data?.cpu?.logical_count ?? 0,systemRamAvailableGb: data?.memory?.available_gb ?? 0,+ systemRamAvailableHostGb: data?.memory?.available_gb ?? 0,systemRamTotalGb: data?.memory?.total_gb ?? 0,};const gpuData =@@ -85,14 +107,32 @@ function toGpuInfo(...base,// A Vulkan iGPU's reported budget is capped shared system RAM, not an// independent VRAM pool. Do not offer the same RAM again for CPU offload.+ // `systemRamAvailableHostGb` deliberately keeps `base`'s reading through this+ // spread: the zero is about not double-counting a SUM, not a claim that the+ // machine has no free RAM, and a caller asking about host pressure needs the+ // number itself.systemRamAvailableGb: devices.some((device) => device.shared_memory)? 0: base.systemRamAvailableGb,+ // EVERY, not some, and deliberately different from the zeroing above. That one+ // is about a SUM: one shared device is enough to make "GPU total + system RAM"+ // count the same bytes twice. This one answers "is there only one pool", which a+ // discrete card sitting beside an iGPU makes false. Reading it as some() marked a+ // mixed inventory single-pool, and the row shows a lone Shared figure there and+ // drops the GPU verdict, so a fixed Manual placement larger than the discrete+ // card read as a fit against a combined ceiling it will never spill into.+ // Length-guarded because every() on an empty list is true, and a host with+ // nothing probed has no pool to be single.+ sharedMemory:+ devices.length > 0 && devices.every((device) => device.shared_memory),available: true,budgetKnown: true,name: devices[0]?.name ?? "Unknown",// Shared-memory (Vulkan iGPU) devices report the same system RAM pool, so they are counted once rather than summed.memoryTotalGb: aggregateGpuMemoryTotalGb(devices),+ dedicatedMemoryTotalGb: aggregateGpuMemoryTotalGb(+ devices.filter((device) => !device.shared_memory),+ ),maxDeviceMemoryGb: devices.reduce((max, d) => Math.max(max, d.memory_total_gb ?? 0), 0),// Lowest visible ordinal = torch's current device = where the pipeline lands.loadDeviceMemoryGb: pickLoadDevice(devices)?.memory_total_gb ?? 0,@@ -129,6 +169,7 @@ function toGpuDevices(name: d.name ?? `GPU ${d.index}`,memoryTotalGb: d.memory_total_gb ?? 0,memoryFreeGb: d.vram_free_gb ?? 0,+ sharedMemory: d.shared_memory === true,pinnable: picksAccepted && d.index_kind === "vulkan",// The DiffusionGemma runner is torch-side and never speaks ggml// ordinals, so a Vulkan pick is not usable there.@@ -154,6 +195,7 @@ function toGpuDevices(name: d.name ?? `GPU ${d.index}`,memoryTotalGb: d.memory_total_gb ?? 0,memoryFreeGb: d.vram_free_gb ?? 0,+ sharedMemory: d.shared_memory === true,// The XPU ban is about torch-xpu ordinals no applicator speaks, so /load// and /validate 400 them. A Vulkan ordinal is not one of those, so it// stays pickable even when this list arrives from an XPU host.diff --git a/studio/frontend/tests/diffusion-gpu-choices.test.ts b/studio/frontend/tests/diffusion-gpu-choices.test.tsindex 2c2dbe8757b..4f9afd92395 100644--- a/studio/frontend/tests/diffusion-gpu-choices.test.ts+++ b/studio/frontend/tests/diffusion-gpu-choices.test.ts@@ -24,6 +24,7 @@ function device(name: `GPU ${index}`,memoryTotalGb: 24,memoryFreeGb: 20,+ sharedMemory: false,pinnable: true,diffusionPinnable: true,...overrides,diff --git a/studio/frontend/tests/helpers/memory-estimate-resolver.mjs b/studio/frontend/tests/helpers/memory-estimate-resolver.mjsnew file mode 100644index 00000000000..397aabccc0e--- /dev/null+++ b/studio/frontend/tests/helpers/memory-estimate-resolver.mjs@@ -0,0 +1,19 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// Bare Node needs stubs for the two Vite-only dependencies the memory-estimate API+// module pulls in: authFetch, and the native path lease, which reaches @tauri-apps.+import { resolve as resolveBundler } from "../bundler-resolver.mjs";++const STUBS = new Map([+ ["@/features/auth", "./store-stubs/auth.ts"],+ ["@/features/native-intents/api", "./native-path-stub.ts"],+]);++export function resolve(specifier, context, next) {+ const stub = STUBS.get(specifier);+ if (stub) {+ return next(new URL(stub, import.meta.url).href, context);+ }+ return resolveBundler(specifier, context, next);+}diff --git a/studio/frontend/tests/helpers/native-path-stub.ts b/studio/frontend/tests/helpers/native-path-stub.tsnew file mode 100644index 00000000000..3f817d81810--- /dev/null+++ b/studio/frontend/tests/helpers/native-path-stub.ts@@ -0,0 +1,33 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// The one native-intents export the memory-estimate API module imports. The real one+// reaches @tauri-apps/api, which bare Node cannot load and which would answer nothing+// useful outside the desktop shell anyway.++export interface NativePathLeaseResponse {+ nativePathLease: string;+}++type Handler = (+ token: string,+ operation: string,+) => NativePathLeaseResponse | Promise<NativePathLeaseResponse>;++let handler: Handler | null = null;++/** Answer the next lease exchange from `next`. Pass null to restore the default,+ * which rejects the way an expired or revoked lease does. */+export function setNativePathHandler(next: Handler | null): void {+ handler = next;+}++export async function consumeNativePathToken(+ token: string,+ operation: string,+): Promise<NativePathLeaseResponse> {+ if (!handler) {+ throw new Error("consumeNativePathToken: no native shell in tests");+ }+ return handler(token, operation);+}diff --git a/studio/frontend/tests/memory-estimate-capacity.test.ts b/studio/frontend/tests/memory-estimate-capacity.test.tsnew file mode 100644index 00000000000..a10f1c6e002--- /dev/null+++ b/studio/frontend/tests/memory-estimate-capacity.test.ts@@ -0,0 +1,324 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// What the Load-Model memory row measures its verdict against. The load-bearing+// case is a mixed Vulkan host: a discrete card beside an iGPU whose reported budget+// is a capped view of system RAM. Whether RAM counts as a pool beside the GPU is a+// question about the devices the load can reach, not about the host, and pinning+// changes which devices those are.++import assert from "node:assert/strict";+import test from "node:test";++import { resolveMemoryCapacityGb, usableFreeVramGb } from "../src/hooks/gpu-vram.ts";++// The inventory in studio/backend/tests/test_system_vulkan_gpu_info.py: an RX 9070 XT+// with its own 16 GB, and an 8060S iGPU whose 91 GiB raw total is reported as the+// 12 GB capped budget.+const DGPU = { memoryTotalGb: 16, sharedMemory: false };+const IGPU = { memoryTotalGb: 12, sharedMemory: true };+const HOST = {+ // What toGpuInfo aggregates for that pair: dedicated summed, shared counted once.+ hostGpuTotalGb: 28,+ // devices.some(...), so the whole host reads as shared while only one card is.+ hostSharesSystemRam: true,+ systemRamTotalGb: 96,+ unifiedMemory: false,+};++test("a pin on the discrete card keeps system RAM as a pool beside it", () => {+ // The iGPU is not in the load, so nothing is sharing that RAM with it and layers+ // that do not fit on the 16 GB card spill into the 96 GB host pool. Reading the+ // host-level shared flag here capped the total at 16 GB and called an 18 GB load+ // impossible with 96 GB of RAM standing free.+ const capacity = resolveMemoryCapacityGb({ ...HOST, pinnedDevices: [DGPU] });+ assert.equal(capacity.gpuCapacityGb, 16);+ assert.equal(capacity.totalCapacityGb, 112);+ assert.equal(capacity.singleMemoryPool, false);+});++test("a pin on the iGPU does not offer its own RAM twice, nor throw the rest away", () => {+ // Its 12 GB IS system RAM, already capped, so the 96 GB must not be ADDED on top --+ // that counts the same bytes twice and calls an oversized load a fit.+ //+ // It must not REPLACE it either, which is what this asserted before: the machine+ // genuinely has 96 GB, and capping its total at the iGPU's 12 GB allowance called a+ // 20 GB CPU-offloaded load impossible on a host with 76 GB to spare.+ const capacity = resolveMemoryCapacityGb({ ...HOST, pinnedDevices: [IGPU] });+ assert.equal(capacity.gpuCapacityGb, 12);+ assert.equal(capacity.totalCapacityGb, 96);+ assert.equal(capacity.singleMemoryPool, true);+});++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.+ const capacity = resolveMemoryCapacityGb({+ ...HOST,+ pinnedDevices: [DGPU, IGPU, IGPU],+ });+ assert.equal(capacity.singleMemoryPool, false);+ assert.equal(capacity.gpuCapacityGb, 28);+ assert.equal(capacity.totalCapacityGb, 112);+});++test("with no pin the host answers, and it says shared", () => {+ // Same correction as the iGPU pin: shared means RAM is not added on top, not that+ // the machine shrinks to the iGPU's allowance.+ const capacity = resolveMemoryCapacityGb({ ...HOST, pinnedDevices: [] });+ assert.equal(capacity.gpuCapacityGb, 28);+ assert.equal(capacity.totalCapacityGb, 96);+});++test("a shared pool smaller than the GPU budget keeps the GPU budget", () => {+ // The guard against the correction going the other way: whatever the RAM figure is,+ // the pool is never reported as less than what the GPU is already allowed.+ const capacity = resolveMemoryCapacityGb({+ hostGpuTotalGb: 32,+ hostSharesSystemRam: true,+ systemRamTotalGb: 8,+ unifiedMemory: false,+ pinnedDevices: [],+ });+ assert.equal(capacity.totalCapacityGb, 32);+});++test("Apple's unified pool is still reported as the GPU budget alone", () => {+ // Unified memory is not the capped-view case: the GPU budget already IS the pool,+ // so the max() above must not start preferring a separately reported RAM figure.+ const capacity = resolveMemoryCapacityGb({+ hostGpuTotalGb: 36,+ hostSharesSystemRam: false,+ systemRamTotalGb: 36,+ unifiedMemory: true,+ pinnedDevices: [],+ });+ assert.equal(capacity.totalCapacityGb, 36);+ assert.equal(capacity.singleMemoryPool, true);+});++test("a plain multi-GPU host adds its RAM whether or not a card is pinned", () => {+ const plain = {+ hostGpuTotalGb: 48,+ hostSharesSystemRam: false,+ systemRamTotalGb: 64,+ unifiedMemory: false,+ };+ assert.equal(+ resolveMemoryCapacityGb({ ...plain, pinnedDevices: [] }).totalCapacityGb,+ 112,+ );+ const pinned = resolveMemoryCapacityGb({+ ...plain,+ pinnedDevices: [{ memoryTotalGb: 24, sharedMemory: false }],+ });+ // The pin is the pool a split spreads over, and RAM is still beside it.+ assert.equal(pinned.gpuCapacityGb, 24);+ assert.equal(pinned.totalCapacityGb, 88);+});++test("Apple Silicon is one pool however the devices are described", () => {+ const capacity = resolveMemoryCapacityGb({+ pinnedDevices: [],+ hostGpuTotalGb: 128,+ hostSharesSystemRam: false,+ systemRamTotalGb: 128,+ unifiedMemory: true,+ });+ assert.equal(capacity.totalCapacityGb, 128);+ assert.equal(capacity.singleMemoryPool, true);+});++test("an unprobed host gives no verdict rather than a fit", () => {+ // 0 capacity is what classifyMemoryFit reads as "unknown". A pin whose devices+ // report nothing must fall back to the host rather than answer 0 on its own.+ const nothing = resolveMemoryCapacityGb({+ pinnedDevices: [],+ hostGpuTotalGb: 0,+ hostSharesSystemRam: false,+ systemRamTotalGb: 0,+ unifiedMemory: false,+ });+ assert.equal(nothing.gpuCapacityGb, 0);+ assert.equal(nothing.totalCapacityGb, 0);+ const unsized = resolveMemoryCapacityGb({+ ...HOST,+ pinnedDevices: [{ memoryTotalGb: 0, sharedMemory: false }],+ });+ assert.equal(unsized.gpuCapacityGb, HOST.hostGpuTotalGb);+});++// The VRAM Budget slider sits in the same panel and caps what the next load may claim+// per GPU. Measuring the verdict against the raw total contradicted the control+// directly above the row: at 80% a 20 GiB footprint on a 24 GiB card is over the line+// the slider draws, and the row called it comfortable.+test("the configured budget caps the GPU capacity a verdict is measured against", () => {+ const capacity = resolveMemoryCapacityGb({+ hostGpuTotalGb: 24,+ hostSharesSystemRam: false,+ systemRamTotalGb: 64,+ unifiedMemory: false,+ pinnedDevices: [],+ gpuBudgetFraction: 0.8,+ });+ assert.equal(capacity.gpuCapacityGb, 19.2);+ // Host RAM is not the GPU's allowance, so the total follows the capped GPU figure+ // plus the whole of RAM.+ assert.equal(capacity.totalCapacityGb, 83.2);+});++test("the budget applies to a pinned subset too", () => {+ const capacity = resolveMemoryCapacityGb({+ ...HOST,+ pinnedDevices: [DGPU],+ gpuBudgetFraction: 0.5,+ });+ assert.equal(capacity.gpuCapacityGb, 8);+});++test("an absent or nonsensical budget leaves the capacity alone", () => {+ const base = {+ hostGpuTotalGb: 24,+ hostSharesSystemRam: false,+ systemRamTotalGb: 64,+ unifiedMemory: false,+ pinnedDevices: [],+ };+ // A 0 or a missing value must not zero the capacity: every caller reads 0 as+ // "nothing probed" and would stop showing a verdict at all.+ assert.equal(resolveMemoryCapacityGb(base).gpuCapacityGb, 24);+ assert.equal(resolveMemoryCapacityGb({ ...base, gpuBudgetFraction: 0 }).gpuCapacityGb, 24);+ assert.equal(resolveMemoryCapacityGb({ ...base, gpuBudgetFraction: 1.5 }).gpuCapacityGb, 24);+ assert.equal(resolveMemoryCapacityGb({ ...base, gpuBudgetFraction: -1 }).gpuCapacityGb, 24);+});++// The loader subtracts an ABSOLUTE reserve from what is free; it does not scale free+// memory by the fraction. The two agree only on an idle card, and the gap is what+// decides whether a busy-card warning appears at all.+test("the budget is an absolute reserve, not a multiplier, on a busy card", () => {+ // _select_gpus' own example: 24 GB card, 10 GB free, 80% budget.+ // free - (1 - 0.8) * 24 = 10 - 4.8 = 5.2, where a multiplication says 8.+ assert.ok(Math.abs(usableFreeVramGb(10, 24, 0.8) - 5.2) < 1e-9);+});++test("an idle card is where the two rules agree", () => {+ assert.ok(Math.abs(usableFreeVramGb(24, 24, 0.8) - 19.2) < 1e-9);+});++test("the floor keeps the budget monotonic on a small card", () => {+ // Capped at the default's own reserve, so nudging the slider up never hands back+ // less. A flat 512 MiB would do exactly that on any card under about 17 GB.+ const atDefault = usableFreeVramGb(8, 8, 0.97);+ const justAbove = usableFreeVramGb(8, 8, 0.971);+ assert.ok(justAbove >= atDefault);+});++test("a probe with no total falls back to the fraction, as the loader does", () => {+ assert.ok(Math.abs(usableFreeVramGb(10, 0, 0.8) - 8) < 1e-9);+});++test("the usable figure never goes negative", () => {+ assert.equal(usableFreeVramGb(0.1, 24, 0.5), 0);+});++test("a mixed dedicated and shared inventory is two pools, not one", () => {+ // devices.some(shared) marked a discrete card sitting beside a Vulkan iGPU as one+ // pool. The row shows a lone Shared figure there and drops the GPU verdict+ // entirely, so a fixed Manual placement larger than the discrete card read as a fit+ // against a ceiling it can never spill into.+ const mixed = resolveMemoryCapacityGb({+ pinnedDevices: [],+ hostGpuTotalGb: 28, // 16 GB card + a 12 GB iGPU budget, counted once+ hostDedicatedGpuTotalGb: 16,+ hostSharesSystemRam: false, // every(), so a mixed host is no longer flagged+ systemRamTotalGb: 91,+ unifiedMemory: false,+ });+ assert.equal(mixed.singleMemoryPool, false);+ assert.equal(mixed.gpuCapacityGb, 28);+ // 16 + 91, NOT 28 + 91: the iGPU's 12 GB budget is already inside the 91.+ assert.equal(mixed.totalCapacityGb, 107);++ // An all-shared host is still one pool, and still takes the max rather than a sum.+ const allShared = resolveMemoryCapacityGb({+ pinnedDevices: [],+ hostGpuTotalGb: 12,+ hostDedicatedGpuTotalGb: 0,+ hostSharesSystemRam: true,+ systemRamTotalGb: 91,+ unifiedMemory: false,+ });+ assert.equal(allShared.singleMemoryPool, true);+ assert.equal(allShared.totalCapacityGb, 91);+});++test("a pin decides the pool question for the cards it names", () => {+ const dedicated = { memoryTotalGb: 16, sharedMemory: false };+ const igpu = { memoryTotalGb: 12, sharedMemory: true };++ // Only the discrete card: two pools, and RAM is genuinely beside it.+ const onCard = resolveMemoryCapacityGb({+ pinnedDevices: [dedicated],+ hostGpuTotalGb: 28,+ hostDedicatedGpuTotalGb: 16,+ hostSharesSystemRam: false,+ systemRamTotalGb: 91,+ unifiedMemory: false,+ });+ assert.equal(onCard.singleMemoryPool, false);+ assert.equal(onCard.totalCapacityGb, 107);++ // Only the iGPU: one pool.+ const onIgpu = resolveMemoryCapacityGb({+ pinnedDevices: [igpu],+ hostGpuTotalGb: 28,+ hostDedicatedGpuTotalGb: 16,+ hostSharesSystemRam: false,+ systemRamTotalGb: 91,+ unifiedMemory: false,+ });+ assert.equal(onIgpu.singleMemoryPool, true);+ assert.equal(onIgpu.totalCapacityGb, 91);++ // Both pinned: still two pools, because the discrete VRAM is still there.+ const onBoth = resolveMemoryCapacityGb({+ pinnedDevices: [dedicated, igpu],+ hostGpuTotalGb: 28,+ hostDedicatedGpuTotalGb: 16,+ hostSharesSystemRam: false,+ systemRamTotalGb: 91,+ unifiedMemory: false,+ });+ assert.equal(onBoth.singleMemoryPool, false);+ assert.equal(onBoth.gpuCapacityGb, 28);+ assert.equal(onBoth.totalCapacityGb, 107);+});++test("a discrete-only host is unchanged by the dedicated-only ceiling", () => {+ // The regression guard: with no shared device the two figures are equal, so every+ // ordinary machine keeps exactly the ceiling it had.+ const discrete = resolveMemoryCapacityGb({+ pinnedDevices: [],+ hostGpuTotalGb: 24,+ hostSharesSystemRam: false,+ systemRamTotalGb: 64,+ unifiedMemory: false,+ });+ assert.equal(discrete.singleMemoryPool, false);+ assert.equal(discrete.totalCapacityGb, 88);++ // Apple keeps its own branch, whatever the devices say.+ const apple = resolveMemoryCapacityGb({+ pinnedDevices: [],+ hostGpuTotalGb: 64,+ hostSharesSystemRam: false,+ systemRamTotalGb: 64,+ unifiedMemory: true,+ });+ assert.equal(apple.singleMemoryPool, true);+ assert.equal(apple.totalCapacityGb, 64);+});diff --git a/studio/frontend/tests/memory-estimate-context.test.ts b/studio/frontend/tests/memory-estimate-context.test.tsnew file mode 100644index 00000000000..9e9c55405bb--- /dev/null+++ b/studio/frontend/tests/memory-estimate-context.test.ts@@ -0,0 +1,121 @@+import assert from "node:assert/strict";+import { test } from "node:test";++import {+ resolveEstimateContext,+ resolveEstimateSourceIdentity,+} from "../src/features/model-picker/model-config/estimate-context.ts";++// The regression this file exists for: the Context Length control needs a number to+// display before a new GGUF's header has been read and falls back to 32,768, but the+// Load button sends 0 for the same state and llama.cpp fits or opens at the model's+// native context. Pricing the displayed fallback quoted an explicit 32k for a load+// that could open far wider, and the KV cache is the term that grows fastest with+// context, so the panel understated exactly where it mattered most.+test("Auto with no metadata yet prices the native context, not the displayed 32k", () => {+ assert.equal(resolveEstimateContext(null, null), 0);+});++test("an explicit length is priced as itself", () => {+ assert.equal(resolveEstimateContext(8192, null), 8192);+ // Even when it is larger than the header's native context: the user asked for it,+ // and llama.cpp is the one that refuses or fits it down.+ assert.equal(resolveEstimateContext(524288, null), 524288);+});++test("the resident load's context is kept when reloading it", () => {+ // resolveLoadMaxSeqLength's isReloadingCurrentGguf branch: a fitted load got less+ // than native, and that is what it will be resident at again.+ assert.equal(resolveEstimateContext(null, 40223), 40223);+});++test("a known native context is NOT quoted as the figure", () => {+ // The one that would undo the fix if it were written the obvious way. Auto sends 0+ // and llama.cpp's --fit can land well below native, so pricing native claims an+ // outcome the load has not reached; 0 lets the estimate resolve it the way the+ // launch does. There is no native argument any more, and that is the point.+ assert.equal(resolveEstimateContext(null, null), 0);+});++test("an explicit length outranks the resident one", () => {+ assert.equal(resolveEstimateContext(4096, 40223), 4096);+});++test("zero is not mistaken for unset", () => {+ // 0 already means "price the native context" on the wire, so an explicit 0 and an+ // unset length agree rather than one of them falling through to a display bound.+ assert.equal(resolveEstimateContext(0, 40223), 0);+});++// Which MODEL the shown numbers belong to. The hook blanks the row when this changes+// and merely greys it when anything else does, so anything that selects a different+// FILE has to be in here. It keyed on modelPath alone, which is identical across a+// quantization switch while the weights roughly quadruple: Q4_K_M's footprint stayed+// on screen under F16's name until the new answer landed.+const sourceId = (+ path: string,+ variant: string | null = null,+ token = "",+ native: string | null = null,+) => resolveEstimateSourceIdentity(path, variant, token, native);++test("two quantizations of one repository are different sources", () => {+ assert.notEqual(+ sourceId("unsloth/Qwen3-8B-GGUF", "Q4_K_M"),+ sourceId("unsloth/Qwen3-8B-GGUF", "F16"),+ );+});++test("the same source is the same identity, so a slider step does not blank the row", () => {+ assert.equal(+ sourceId("unsloth/Qwen3-8B-GGUF", "Q4_K_M"),+ sourceId("unsloth/Qwen3-8B-GGUF", "Q4_K_M"),+ );+});++test("two repositories are different sources", () => {+ assert.notEqual(sourceId("org/a", "Q4_K_M"), sourceId("org/b", "Q4_K_M"));+});++test("two credentials are different sources: they resolve different files", () => {+ assert.notEqual(sourceId("org/gated", "Q4_K_M", "aaa"), sourceId("org/gated", "Q4_K_M", "bbb"));+});++test("two native picks of the same file name are different sources", () => {+ assert.notEqual(sourceId("model.gguf", null, "", "tok-1"), sourceId("model.gguf", null, "", "tok-2"));+});++test("absent and null are the same, so an unset variant does not thrash the row", () => {+ assert.equal(sourceId("org/a", null), sourceId("org/a", undefined as unknown as null));+});++// Manual memory mode with GPU Layers on Auto hands context sizing to llama.cpp --fit.+// `resolveFitMaxSeqLength` sends a positive pin or 0 there, never the resident length,+// so falling back to what is loaded right now priced the OLD fit after a change that+// moves it -- a KV dtype or a batch size, which is exactly when the two diverge.+test("when the fit or a builtin-default owns the context, the resident length is not sent", () => {+ assert.equal(resolveEstimateContext(null, 40960, true), 0);+});++test("a positive pin survives the fit path, because Load sends it", () => {+ assert.equal(resolveEstimateContext(8192, 40960, true), 8192);+});++test("a non-positive pin is still 0 under the fit path", () => {+ assert.equal(resolveEstimateContext(0, 40960, true), 0);+ assert.equal(resolveEstimateContext(-1, 40960, true), 0);+});++test("every other shape keeps the resident fallback", () => {+ assert.equal(resolveEstimateContext(null, 40960, false), 40960);+ // And the flag defaults off, so no caller gains the fit rule by accident.+ assert.equal(resolveEstimateContext(null, 40960), 40960);+});++// resolveLoadMaxSeqLength answers 0 for a builtin-default GGUF load too, before it+// reaches the reloading-current-GGUF branch that returns the resident context. Same+// flag, because the consequence is identical: pricing what is loaded right now quotes+// the OLD fit at exactly the moment a setting has moved the next one.+test("a builtin-default GGUF load prices the fit, not the resident context", () => {+ assert.equal(resolveEstimateContext(null, 131072, true), 0);+});diff --git a/studio/frontend/tests/memory-estimate-free-vram.test.ts b/studio/frontend/tests/memory-estimate-free-vram.test.tsnew file mode 100644index 00000000000..b38ceb841f4--- /dev/null+++ b/studio/frontend/tests/memory-estimate-free-vram.test.ts@@ -0,0 +1,350 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// What the Load-Model memory row measures FREE memory against, and how both the free+// and the total aggregate behave on inventories nobody has on the desk.+//+// The row's sibling file memory-estimate-capacity.test.ts covers the totals. This one+// covers the free figure that feeds `freeGpuFit`, plus the readings that arrive+// missing, null, negative or non-finite from a probe that failed halfway.++import assert from "node:assert/strict";+import test from "node:test";++import { classifyMemoryFit } from "../src/features/model-picker/model-config/memory-fit.ts";+import {+ aggregateGpuMemoryTotalGb,+ aggregateUsableFreeVramGb,+ resolveMemoryCapacityGb,+ usableFreeVramGb,+} from "../src/hooks/gpu-vram.ts";++const GB = 1024 ** 3;++// studio/backend/tests/test_system_vulkan_gpu_info.py: an RX 9070 XT with its own+// 16 GB beside an 8060S iGPU. get_vulkan_inference_gpu_info forces the iGPU's+// total_mib to 0 and reports `budget_mib = total_mib or free_mib`, so an iGPU's+// memory_total_gb and vram_free_gb are the SAME number: the host's free RAM, less the+// iGPU host reserve.+const DGPU = { memoryFreeGb: 15, memoryTotalGb: 16, sharedMemory: false };+const IGPU = { memoryFreeGb: 11, memoryTotalGb: 11, sharedMemory: true };++// ---------------------------------------------------------------------------+// D3: the shared pool, counted once++test("one discrete card and one iGPU are added, exactly as their totals are", () => {+ // Recorded deliberately: this pairing is NOT the double-count case.+ // aggregateGpuMemoryTotalGb adds these two as well, so the free figure and the+ // total it is weighed against agree. Taking max() over a single shared device is+ // that device.+ assert.equal(+ aggregateGpuMemoryTotalGb([+ { memory_total_gb: 16, shared_memory: false },+ { memory_total_gb: 11, shared_memory: true },+ ]),+ 27,+ );+ const free = aggregateUsableFreeVramGb([DGPU, IGPU], 1);+ const summedBlindly =+ usableFreeVramGb(15, 16, 1) + usableFreeVramGb(11, 11, 1);+ assert.ok(Math.abs(free - summedBlindly) < 0.01);+});++test("the SAME pool reported twice does not double the free figure", () => {+ // ggml-vulkan enumerates one device per installed ICD, and _run_vulkan_probe does+ // not dedup, so a box with both Mesa RADV and AMDVLK present lists one physical+ // iGPU at two ordinals, each reporting the same host RAM. The totals aggregate+ // already takes max() over shared devices; a plain sum of the free readings did+ // not, and invented a pool the machine does not have.+ const once = aggregateUsableFreeVramGb([DGPU, IGPU], 1);+ const twice = aggregateUsableFreeVramGb([DGPU, IGPU, IGPU], 1);+ assert.equal(twice, once);+ // Four ICDs would have quadrupled it.+ assert.equal(aggregateUsableFreeVramGb([DGPU, IGPU, IGPU, IGPU, IGPU], 1), once);+ // And the total says the same thing, so the two figures cannot disagree.+ assert.equal(+ aggregateGpuMemoryTotalGb([+ { memory_total_gb: 16, shared_memory: false },+ { memory_total_gb: 11, shared_memory: true },+ { memory_total_gb: 11, shared_memory: true },+ ]),+ 27,+ );+});++test("the phantom capacity was enough to flip the verdict", () => {+ const blind = [DGPU, IGPU, IGPU].reduce(+ (sum, d) => sum + usableFreeVramGb(d.memoryFreeGb, d.memoryTotalGb, 1),+ 0,+ );+ const correct = aggregateUsableFreeVramGb([DGPU, IGPU, IGPU], 1);+ assert.ok(blind - correct > 10, `phantom was ${(blind - correct).toFixed(2)} GB`);+ assert.equal(classifyMemoryFit(30 * GB, blind), "fits");+ assert.equal(classifyMemoryFit(30 * GB, correct), "exceeds");+});++test("several discrete cards still sum, because they are separate pools", () => {+ const pair = aggregateUsableFreeVramGb(+ [+ { memoryFreeGb: 24, memoryTotalGb: 24, sharedMemory: false },+ { memoryFreeGb: 24, memoryTotalGb: 24, sharedMemory: false },+ ],+ 1,+ );+ assert.ok(Math.abs(pair - 2 * usableFreeVramGb(24, 24, 1)) < 0.01);+});++test("two shared devices of different sizes report the larger, not their sum", () => {+ // Two views of one pool, one of which had a reserve applied and one of which did+ // not. The pool is at least the larger; it is certainly not both added together.+ const mixed = aggregateUsableFreeVramGb(+ [+ { memoryFreeGb: 40, memoryTotalGb: 40, sharedMemory: true },+ { memoryFreeGb: 11, memoryTotalGb: 11, sharedMemory: true },+ ],+ 1,+ );+ assert.ok(Math.abs(mixed - usableFreeVramGb(40, 40, 1)) < 0.01);+});++test("the VRAM Budget reserve is applied per device inside the aggregate", () => {+ // _select_gpus' own example: a 24 GB card with 10 GB free at an 80% budget offers+ // 10 - (1 - 0.8) * 24 = 5.2, not 8.+ const busy = aggregateUsableFreeVramGb(+ [{ memoryFreeGb: 10, memoryTotalGb: 24, sharedMemory: false }],+ 0.8,+ );+ assert.ok(Math.abs(busy - 5.2) < 0.01, `${busy}`);+});++test("an empty inventory is no verdict, not a fit", () => {+ assert.equal(aggregateUsableFreeVramGb([], 1), 0);+ assert.equal(classifyMemoryFit(8 * GB, aggregateUsableFreeVramGb([], 1)), "unknown");+});++// ---------------------------------------------------------------------------+// PART 3: readings that arrive broken++test("missing fields on a device read as nothing probed, and do not throw", () => {+ assert.doesNotThrow(() => aggregateUsableFreeVramGb([{}, {}], 1));+ assert.equal(aggregateUsableFreeVramGb([{}, {}], 1), 0);+ assert.equal(aggregateGpuMemoryTotalGb([{}, {}]), 0);+});++test("null, string, negative, NaN and Infinity readings never become capacity", () => {+ const bad = [null, "16", -8, Number.NaN, Number.POSITIVE_INFINITY, undefined];+ for (const value of bad) {+ const devices = [+ { memoryFreeGb: value as number, memoryTotalGb: value as number, sharedMemory: false },+ { memoryFreeGb: value as number, memoryTotalGb: value as number, sharedMemory: true },+ ];+ const free = aggregateUsableFreeVramGb(devices, 1);+ assert.ok(+ Number.isFinite(free) && free >= 0,+ `free from ${String(value)} was ${free}`,+ );+ assert.equal(free, 0, `free from ${String(value)}`);+ const total = aggregateGpuMemoryTotalGb([+ { memory_total_gb: value as number, shared_memory: false },+ { memory_total_gb: value as number, shared_memory: true },+ ]);+ assert.ok(Number.isFinite(total) && total >= 0, `total from ${String(value)}`);+ assert.equal(total, 0);+ // And no verdict is drawn from any of them.+ assert.equal(classifyMemoryFit(8 * GB, free), "unknown");+ assert.equal(classifyMemoryFit(8 * GB, total), "unknown");+ }+});++test("one broken device does not poison the readings beside it", () => {+ const free = aggregateUsableFreeVramGb(+ [DGPU, { memoryFreeGb: Number.NaN, memoryTotalGb: Number.NaN, sharedMemory: false }],+ 1,+ );+ assert.ok(Math.abs(free - usableFreeVramGb(15, 16, 1)) < 0.01, `${free}`);+});++test("a non-finite budget fraction leaves the reading alone", () => {+ for (const fraction of [Number.NaN, Number.POSITIVE_INFINITY, 0, -1, 2]) {+ const free = aggregateUsableFreeVramGb([DGPU], fraction);+ assert.ok(Number.isFinite(free) && free >= 0, `fraction=${fraction} -> ${free}`);+ assert.ok(Math.abs(free - usableFreeVramGb(15, 16, 1)) < 0.01);+ }+});++// ---------------------------------------------------------------------------+// PART 3: the capacity resolver on the same shapes++const HOST = {+ hostGpuTotalGb: 27,+ hostSharesSystemRam: true,+ systemRamTotalGb: 96,+ unifiedMemory: false,+};++test("Apple's 64 GB pool is not discounted twice by a stale server budget", () => {+ // Apple reports the one pool as the GPU budget already, so the VRAM Budget slider+ // caps it once. The total must follow that capped figure and must NOT then prefer a+ // separately reported RAM number, which would hand back the very memory the slider+ // just took away.+ const capacity = resolveMemoryCapacityGb({+ pinnedDevices: [],+ hostGpuTotalGb: 64,+ hostSharesSystemRam: false,+ systemRamTotalGb: 64,+ unifiedMemory: true,+ gpuBudgetFraction: 0.5,+ });+ assert.equal(capacity.gpuCapacityGb, 32);+ assert.equal(capacity.totalCapacityGb, 32);+ assert.equal(capacity.singleMemoryPool, true);+});++test("one Vulkan iGPU with a 12 GB allowance on a 64 GB system", () => {+ // The allowance is a capped view of the RAM, so the RAM is not added on top -- and+ // the machine is not shrunk to the allowance either. The pool is the RAM.+ const capacity = resolveMemoryCapacityGb({+ pinnedDevices: [{ memoryTotalGb: 12, sharedMemory: true }],+ hostGpuTotalGb: 12,+ hostSharesSystemRam: true,+ systemRamTotalGb: 64,+ unifiedMemory: false,+ });+ assert.equal(capacity.gpuCapacityGb, 12);+ assert.equal(capacity.totalCapacityGb, 64);+ assert.equal(capacity.singleMemoryPool, true);+});++test("16 GB discrete plus a shared iGPU: each pin, and no pin", () => {+ const discretePin = resolveMemoryCapacityGb({+ ...HOST,+ pinnedDevices: [{ memoryTotalGb: 16, sharedMemory: false }],+ });+ // Nothing is sharing that RAM with the pinned card, so RAM is a pool beside it.+ assert.equal(discretePin.gpuCapacityGb, 16);+ assert.equal(discretePin.totalCapacityGb, 112);+ assert.equal(discretePin.singleMemoryPool, false);++ const igpuPin = resolveMemoryCapacityGb({+ ...HOST,+ pinnedDevices: [{ memoryTotalGb: 11, sharedMemory: true }],+ });+ assert.equal(igpuPin.gpuCapacityGb, 11);+ assert.equal(igpuPin.totalCapacityGb, 96);+ assert.equal(igpuPin.singleMemoryPool, true);++ const unpinned = resolveMemoryCapacityGb({ ...HOST, pinnedDevices: [] });+ // devices.some(...) makes the host read as shared, so RAM is not added on top.+ assert.equal(unpinned.gpuCapacityGb, 27);+ assert.equal(unpinned.totalCapacityGb, 96);+ assert.equal(unpinned.singleMemoryPool, true);+});++test("a pin whose devices all report 0 falls back to the host aggregate", () => {+ const unsized = resolveMemoryCapacityGb({+ ...HOST,+ pinnedDevices: [+ { memoryTotalGb: 0, sharedMemory: false },+ { memoryTotalGb: 0, sharedMemory: false },+ ],+ });+ assert.equal(unsized.gpuCapacityGb, HOST.hostGpuTotalGb);+ // And the pool question falls back with it, rather than being answered by devices+ // that reported nothing.+ assert.equal(unsized.singleMemoryPool, true);+});++test("a capacity resolver handed nothing gives no verdict rather than a fit", () => {+ const nothing = resolveMemoryCapacityGb({+ pinnedDevices: [],+ hostGpuTotalGb: 0,+ hostSharesSystemRam: false,+ systemRamTotalGb: 0,+ unifiedMemory: false,+ });+ assert.equal(classifyMemoryFit(8 * GB, nothing.gpuCapacityGb), "unknown");+ assert.equal(classifyMemoryFit(8 * GB, nothing.totalCapacityGb), "unknown");+});++test("non-finite capacity inputs never produce a fit", () => {+ for (const value of [Number.NaN, Number.POSITIVE_INFINITY, -1]) {+ const capacity = resolveMemoryCapacityGb({+ pinnedDevices: [{ memoryTotalGb: value, sharedMemory: false }],+ hostGpuTotalGb: value,+ hostSharesSystemRam: false,+ systemRamTotalGb: value,+ unifiedMemory: false,+ });+ assert.ok(+ Number.isFinite(capacity.gpuCapacityGb) && capacity.gpuCapacityGb >= 0,+ `gpu ${capacity.gpuCapacityGb} from ${value}`,+ );+ assert.ok(+ Number.isFinite(capacity.totalCapacityGb) && capacity.totalCapacityGb >= 0,+ `total ${capacity.totalCapacityGb} from ${value}`,+ );+ assert.notEqual(classifyMemoryFit(8 * GB, capacity.gpuCapacityGb), "fits");+ assert.notEqual(classifyMemoryFit(8 * GB, capacity.totalCapacityGb), "fits");+ }+});++// ---------------------------------------------------------------------------+// PART 3: a persisted pin that no longer matches the hardware+//+// selectedGpuIds is remembered per model and survives a driver change, a card being+// removed, and a switch between the torch and the Vulkan index namespaces. The page+// resolves it with `gpuDevices.filter((d) => pinnedIds.includes(d.index))`, so this+// is that filter against a malformed list.++const INVENTORY = [+ { index: 0, memoryFreeGb: 15, memoryTotalGb: 16, sharedMemory: false },+ { index: 1, memoryFreeGb: 11, memoryTotalGb: 11, sharedMemory: true },+];++const pinned = (ids: number[]) =>+ ids.length > 0 ? INVENTORY.filter((d) => ids.includes(d.index)) : INVENTORY;++test("a pin naming indices that no longer exist falls back to the host", () => {+ const devices = pinned([7, 9]);+ assert.equal(devices.length, 0);+ const capacity = resolveMemoryCapacityGb({+ ...HOST,+ pinnedDevices: devices.map((d) => ({+ memoryTotalGb: d.memoryTotalGb,+ sharedMemory: d.sharedMemory,+ })),+ });+ // pinGoverns is false, so the whole-host answer stands rather than a 0 that would+ // hide the verdict entirely.+ assert.equal(capacity.gpuCapacityGb, HOST.hostGpuTotalGb);+ assert.equal(aggregateUsableFreeVramGb(devices, 1), 0);+});++test("a duplicated index selects its device once, not twice", () => {+ const devices = pinned([0, 0, 0]);+ assert.equal(devices.length, 1);+ assert.equal(+ aggregateUsableFreeVramGb(devices, 1),+ aggregateUsableFreeVramGb(pinned([0]), 1),+ );+});++test("negative and non-integer indices match nothing and do not throw", () => {+ assert.doesNotThrow(() => pinned([-1, -2, 1.5]));+ assert.equal(pinned([-1, -2, 1.5]).length, 0);+});++test("a pin mixing one real index with junk keeps only the real one", () => {+ const devices = pinned([1, -3, 42]);+ assert.equal(devices.length, 1);+ const capacity = resolveMemoryCapacityGb({+ ...HOST,+ pinnedDevices: devices.map((d) => ({+ memoryTotalGb: d.memoryTotalGb,+ sharedMemory: d.sharedMemory,+ })),+ });+ // The iGPU alone, so one pool, and RAM is not offered a second time.+ assert.equal(capacity.gpuCapacityGb, 11);+ assert.equal(capacity.singleMemoryPool, true);+});diff --git a/studio/frontend/tests/memory-estimate-identity.test.ts b/studio/frontend/tests/memory-estimate-identity.test.tsnew file mode 100644index 00000000000..150e396231c--- /dev/null+++ b/studio/frontend/tests/memory-estimate-identity.test.ts@@ -0,0 +1,151 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// 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.+//+// 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.++import assert from "node:assert/strict";+import test from "node:test";++import {+ resolveEstimateSourceIdentity,+ resolveTokenIdentity,+} from "../src/features/model-picker/model-config/estimate-context.ts";++const identity = (+ path: string,+ variant: string | null = null,+ token: string | null = null,+ nativeToken: string | null = null,+) =>+ resolveEstimateSourceIdentity(+ path,+ variant,+ resolveTokenIdentity(token),+ nativeToken,+ );++/** The guard the hook runs during render: state belonging to another source is not+ * returned at all, not even for the frame before the effect clears it. */+function shown(stateIdentity: string | null, currentIdentity: string | null) {+ return stateIdentity === currentIdentity;+}++test("switching GGUF never paints the previous model's numbers", () => {+ const before = identity("unsloth/Qwen3-8B-GGUF", "Q4_K_M");+ const after = identity("unsloth/Llama-3.1-8B-GGUF", "Q4_K_M");+ // The render that first names the new model still holds the old model's state.+ assert.equal(shown(before, after), false);+});++test("switching quantization on ONE repository is also a switch", () => {+ // modelPath is identical across this change while the weights roughly quadruple.+ const q4 = identity("unsloth/Qwen3-8B-GGUF", "Q4_K_M");+ const f16 = identity("unsloth/Qwen3-8B-GGUF", "F16");+ assert.notEqual(q4, f16);+ assert.equal(shown(q4, f16), false);+});++test("a settings change is NOT a switch, so the figures stay up and go grey", () => {+ // Context, KV dtype, slots, pins: none of them select a different file, so the+ // source identity is unchanged and the hook keeps the numbers with `stale` set.+ const before = identity("unsloth/Qwen3-8B-GGUF", "Q4_K_M");+ const after = identity("unsloth/Qwen3-8B-GGUF", "Q4_K_M");+ assert.equal(shown(before, after), true);+});++test("standing down blanks the row rather than freezing the last answer", () => {+ const held = identity("unsloth/Qwen3-8B-GGUF", "Q4_K_M");+ assert.equal(shown(held, null), false);+});++test("two credentials are two sources: they resolve different files", () => {+ assert.notEqual(+ identity("org/gated", "Q4_K_M", "hf_aaa"),+ identity("org/gated", "Q4_K_M", "hf_bbb"),+ );+ // And clearing the credential is a switch too.+ assert.notEqual(+ identity("org/gated", "Q4_K_M", "hf_aaa"),+ identity("org/gated", "Q4_K_M", null),+ );+});++test("two native picks of the same filename are two sources", () => {+ assert.notEqual(+ identity("model.gguf", null, null, "tok-1"),+ identity("model.gguf", null, null, "tok-2"),+ );+});++// ---------------------------------------------------------------------------+// The token hash++test("the credential itself never appears in the identity", () => {+ const secret = "hf_ThisIsASecretAndMustNotBeInAReactKey";+ const key = identity("org/gated", "Q4_K_M", secret);+ assert.equal(key.includes(secret), false);+ assert.equal(key.includes("Secret"), false);+});++test("no credential and an empty credential agree", () => {+ assert.equal(resolveTokenIdentity(null), "");+ assert.equal(resolveTokenIdentity(undefined), "");+ assert.equal(resolveTokenIdentity(""), "");+});++test("the same credential is the same identity, so it does not thrash the row", () => {+ assert.equal(resolveTokenIdentity("hf_abc"), resolveTokenIdentity("hf_abc"));+});++// The 32-bit question, answered rather than assumed. These two are both well-formed+// HF tokens ("hf_" plus 34 base62 characters) found by a birthday search over djb2;+// the point is that a collision is CONSTRUCTIBLE, not that one is likely.+const COLLIDING_A = "hf_7MqSwsKw8ci6CSUGQE2iUWyQqC4Wc8KoAi";+const COLLIDING_B = "hf_He6AyGWm4OKk0SmY4O2mAMWeUAGCWIKAK8";++test("a djb2 collision is real, and it suppresses BOTH the refetch and the blank", () => {+ assert.notEqual(COLLIDING_A, COLLIDING_B);+ assert.equal(resolveTokenIdentity(COLLIDING_A), resolveTokenIdentity(COLLIDING_B));+ // Same hash, so the source identity matches: the render-time guard cannot tell the+ // two apart, and the effect key does not change either, so nothing re-fetches.+ const a = identity("org/gated", "Q4_K_M", COLLIDING_A);+ const b = identity("org/gated", "Q4_K_M", COLLIDING_B);+ assert.equal(a, b);+ assert.equal(shown(a, b), true);+});++test("the collision costs a stale byte count, not a wrong load", () => {+ // Worth stating in a test because it is the reason this is documented rather than+ // fixed. The hash keys the ROW only. The load itself, and the estimate REQUEST when+ // one is made, both carry the real credential, so a collision can leave last+ // token's figures on screen and can never send the wrong token anywhere.+ const a = identity("org/gated", "Q4_K_M", COLLIDING_A);+ assert.equal(a.includes(COLLIDING_A), false);+ assert.equal(a.includes(COLLIDING_B), false);+ // The bound is two tokens compared per tab, so ~2^-32 per swap.+ assert.equal(resolveTokenIdentity(COLLIDING_A).length <= 7, true);+});++test("the hash is stable across the shapes a credential arrives in", () => {+ // Whitespace and case are meaningful in a credential, so they must be meaningful+ // here: a trimmed and an untrimmed paste resolve different files on the backend.+ assert.notEqual(resolveTokenIdentity("hf_abc"), resolveTokenIdentity("hf_abc "));+ assert.notEqual(resolveTokenIdentity("hf_abc"), resolveTokenIdentity("HF_ABC"));+});++test("a long or non-ASCII credential still hashes without throwing", () => {+ assert.doesNotThrow(() => resolveTokenIdentity("x".repeat(100_000)));+ assert.doesNotThrow(() => resolveTokenIdentity("héllo-\u{1F600}-token"));+ assert.equal(typeof resolveTokenIdentity("héllo"), "string");+});diff --git a/studio/frontend/tests/memory-estimate-skew.test.ts b/studio/frontend/tests/memory-estimate-skew.test.tsnew file mode 100644index 00000000000..ea60ace990f--- /dev/null+++ b/studio/frontend/tests/memory-estimate-skew.test.ts@@ -0,0 +1,394 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// 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.+//+// 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.++import assert from "node:assert/strict";+import { register } from "node:module";+import test from "node:test";++register("./helpers/memory-estimate-resolver.mjs", import.meta.url);++const auth = await import("./helpers/store-stubs/auth.ts");+const native = await import("./helpers/native-path-stub.ts");+const {+ fetchMemoryEstimate,+ resetMemoryEstimateRouteMemo,+} = await import("../src/features/model-picker/api/memory-estimate.ts");++const REQUEST = { modelPath: "unsloth/Qwen3-8B-GGUF", ggufVariant: "Q4_K_M" };++/** A complete, current response. The skew cases below delete fields from it. */+const FULL = {+ available: true,+ reason: null,+ weights_bytes: 4 * 1024 ** 3,+ kv_bytes: 2 * 1024 ** 3,+ compute_bytes: 1024 ** 3,+ drafter_runtime_bytes: 3 * 1024 ** 3,+ drafter_runtime_gpu_bytes: 1024 ** 3,+ projector_runtime_bytes: 0,+ drafter_kv_unsized: false,+ total_bytes: 7 * 1024 ** 3,+ gpu_bytes: 6 * 1024 ** 3,+ kv_estimable: true,+ kv_on_gpu: true,+ n_ctx: 32768,+ cache_type_kv: "f16",+ n_parallel: 1,+ layer_count: 36,+ gpu_layers: 37,+ moe_offload_unmodelled: false,+};++let requests: { url: string; body: unknown }[] = [];++function answer(+ make: (url: string, init?: RequestInit) => Response,+): void {+ requests = [];+ auth.setAuthFetchHandler((url, init) => {+ requests.push({+ url,+ body: init?.body ? JSON.parse(String(init.body)) : null,+ });+ return make(url, init);+ });+}++const json = (body: unknown, status = 200) =>+ new Response(JSON.stringify(body), {+ status,+ headers: { "Content-Type": "application/json" },+ });++const status = (code: number) =>+ new Response(code === 204 ? null : `error ${code}`, { status: code });++test.beforeEach(() => {+ resetMemoryEstimateRouteMemo();+ auth.setAuthFetchHandler(null);+ native.setNativePathHandler(null);+ requests = [];+});++test.after(() => {+ resetMemoryEstimateRouteMemo();+ auth.setAuthFetchHandler(null);+ native.setNativePathHandler(null);+});++// ---------------------------------------------------------------------------+// OLD BACKEND + NEW BUNDLE: every failure shape hides the row and nothing else++test("every non-OK status comes back unavailable rather than throwing", async () => {+ for (const code of [400, 401, 403, 404, 405, 409, 422, 429, 500, 501, 502, 503]) {+ resetMemoryEstimateRouteMemo();+ answer(() => status(code));+ const estimate = await fetchMemoryEstimate(REQUEST);+ assert.equal(estimate.available, false, `status ${code}`);+ // The row reads `!estimate?.available` and returns null, so it hides. Nothing+ // here can reject, so nothing reaches the panel's own error path.+ assert.equal(estimate.totalBytes, 0, `status ${code}`);+ assert.equal(estimate.gpuBytes, 0, `status ${code}`);+ }+});++test("an HTML 200 from a proxy is unavailable, not a crash", async () => {+ // A captive portal or a dev proxy serving its own page with a 200. `response.json()`+ // rejects on this, and an unhandled rejection here is a rejected promise inside the+ // panel's effect rather than a hidden row.+ answer(+ () =>+ new Response("<!doctype html><html><body>Sign in</body></html>", {+ status: 200,+ headers: { "Content-Type": "text/html" },+ }),+ );+ const estimate = await fetchMemoryEstimate(REQUEST);+ assert.equal(estimate.available, false);+});++test("a truncated JSON body is unavailable, not a crash", async () => {+ answer(+ () =>+ new Response('{"available": true, "total_byt', {+ status: 200,+ headers: { "Content-Type": "application/json" },+ }),+ );+ const estimate = await fetchMemoryEstimate(REQUEST);+ assert.equal(estimate.available, false);+});++test("a 200 whose body is not an object at all is unavailable", async () => {+ for (const body of [null, 7, "ok", [1, 2, 3], true]) {+ resetMemoryEstimateRouteMemo();+ answer(() => json(body));+ const estimate = await fetchMemoryEstimate(REQUEST);+ assert.equal(estimate.available, false, JSON.stringify(body));+ }+});++test("a 200 with an empty object degrades to every documented default", async () => {+ answer(() => json({}));+ const estimate = await fetchMemoryEstimate(REQUEST);+ assert.equal(estimate.available, false);+ assert.equal(estimate.kvEstimable, false);+ assert.equal(estimate.kvOnGpu, true);+ assert.equal(estimate.nParallel, 1);+ assert.equal(estimate.layerCount, null);+ assert.equal(estimate.gpuLayers, null);+});++// ---------------------------------------------------------------------------+// THE MEMO++test("a 404 is remembered, so the next settings change does not POST again", async () => {+ answer(() => status(404));+ assert.equal((await fetchMemoryEstimate(REQUEST)).available, false);+ assert.equal(requests.length, 1);+ // A drag of the context slider, a KV dtype change, a new pin: all of them re-key the+ // hook and would each have fired their own request at a route that is not there.+ for (let i = 0; i < 20; i++) {+ assert.equal((await fetchMemoryEstimate(REQUEST)).available, false);+ }+ assert.equal(requests.length, 1);+});++test("405 and 501 are remembered for the same reason", async () => {+ for (const code of [405, 501]) {+ resetMemoryEstimateRouteMemo();+ answer(() => status(code));+ await fetchMemoryEstimate(REQUEST);+ await fetchMemoryEstimate(REQUEST);+ assert.equal(requests.length, 1, `status ${code}`);+ }+});++test("a transient 500 CANNOT latch the memo", async () => {+ // The requirement this test exists for. A backend that is answering at all, however+ // badly, is not one that is missing the route, and a 500 during a restart would+ // otherwise blank the row for the rest of the session.+ answer(() => status(500));+ await fetchMemoryEstimate(REQUEST);+ await fetchMemoryEstimate(REQUEST);+ await fetchMemoryEstimate(REQUEST);+ assert.equal(requests.length, 3);+});++test("no other failing status latches either", async () => {+ for (const code of [400, 401, 403, 408, 409, 422, 429, 502, 503, 504]) {+ resetMemoryEstimateRouteMemo();+ answer(() => status(code));+ await fetchMemoryEstimate(REQUEST);+ await fetchMemoryEstimate(REQUEST);+ assert.equal(requests.length, 2, `status ${code} must not latch`);+ }+});++test("a 500 arriving after a 404 clears the memo rather than leaving it standing", async () => {+ // The backend was replaced under us: the new one is up but unhealthy. That is+ // evidence the OLD answer no longer applies, so the memo must not survive it.+ let code = 404;+ answer(() => status(code));+ await fetchMemoryEstimate(REQUEST);+ assert.equal(requests.length, 1);+ // Still memoized: this call is suppressed.+ await fetchMemoryEstimate(REQUEST);+ assert.equal(requests.length, 1);+ resetMemoryEstimateRouteMemo();+ code = 500;+ await fetchMemoryEstimate(REQUEST);+ await fetchMemoryEstimate(REQUEST);+ assert.equal(requests.length, 3);+});++test("a success clears the memo, so an upgraded backend is believed at once", async () => {+ answer(() => json(FULL));+ const estimate = await fetchMemoryEstimate(REQUEST);+ assert.equal(estimate.available, true);+ await fetchMemoryEstimate(REQUEST);+ assert.equal(requests.length, 2);+});++test("resetting the memo re-probes", async () => {+ answer(() => status(404));+ await fetchMemoryEstimate(REQUEST);+ await fetchMemoryEstimate(REQUEST);+ assert.equal(requests.length, 1);+ resetMemoryEstimateRouteMemo();+ await fetchMemoryEstimate(REQUEST);+ assert.equal(requests.length, 2);+});++// ---------------------------------------------------------------------------+// FIELD-LEVEL SKEW: a backend predating parts of the response++test("a pre-split backend keeps the 'all of it is on the GPU' reading", async () => {+ // drafter_runtime_gpu_bytes did not exist before the placement split. Defaulting it+ // to 0 would silently drop a real VRAM charge off the row and paint a load that does+ // not fit as one that does.+ const { drafter_runtime_gpu_bytes, ...preSplit } = FULL;+ void drafter_runtime_gpu_bytes;+ answer(() => json(preSplit));+ const estimate = await fetchMemoryEstimate(REQUEST);+ assert.equal(estimate.drafterRuntimeGpuBytes, FULL.drafter_runtime_bytes);+ assert.equal(estimate.drafterRuntimeBytes, FULL.drafter_runtime_bytes);+});++test("an explicit zero GPU share is a real answer, not an absent field", async () => {+ // --spec-draft-ngl 0 puts the whole drafter in host RAM, and the row says so. The+ // fallback must not fire here and claim it is on the card.+ answer(() => json({ ...FULL, drafter_runtime_gpu_bytes: 0 }));+ const estimate = await fetchMemoryEstimate(REQUEST);+ assert.equal(estimate.drafterRuntimeGpuBytes, 0);+});++test("a missing kv_estimable degrades to the floor path, not a confident total", async () => {+ // The KV cache is the one term that can dwarf all the others, so an older backend+ // that cannot vouch for it must produce the amber, prefixed, "unknown" reading+ // rather than a total the row would print in plain text.+ const { kv_estimable, ...older } = FULL;+ void kv_estimable;+ answer(() => json(older));+ const estimate = await fetchMemoryEstimate(REQUEST);+ assert.equal(estimate.kvEstimable, false);+ const { resolveMemoryFit } = await import(+ "../src/features/model-picker/model-config/memory-fit.ts"+ );+ const result = resolveMemoryFit(estimate, {+ gpuCapacityGb: 24,+ totalCapacityGb: 88,+ systemRamCapacityGb: 64,+ freeGpuCapacityGb: 23,+ usableSystemRamGb: 60,+ singleMemoryPool: false,+ });+ assert.equal(result.bounded, true);+ assert.equal(result.prefix, "≥ ");+ assert.equal(result.advisory?.tone, "warn");+ assert.match(result.advisory?.text ?? "", /attention dimensions/);+});++test("a missing kv_on_gpu keeps the pre-flag assumption", async () => {+ const { kv_on_gpu, ...older } = FULL;+ void kv_on_gpu;+ answer(() => json(older));+ assert.equal((await fetchMemoryEstimate(REQUEST)).kvOnGpu, true);+});++test("a field arriving as a string or a non-finite number does not become a figure", async () => {+ // JSON.parse turns 1e999 into Infinity without complaint, and a backend that+ // stringified its numbers is a real skew shape. `?? 0` sees neither.+ answer(() =>+ new Response(+ '{"available": true, "kv_estimable": true, "total_bytes": 1e999, "gpu_bytes": "6442450944", "weights_bytes": -1, "n_ctx": null, "n_parallel": "4", "layer_count": 1e999}',+ { status: 200, headers: { "Content-Type": "application/json" } },+ ),+ );+ const estimate = await fetchMemoryEstimate(REQUEST);+ for (const value of [+ estimate.totalBytes, estimate.gpuBytes, estimate.weightsBytes,+ estimate.kvBytes, estimate.computeBytes, estimate.nCtx, estimate.nParallel,+ ]) {+ assert.ok(Number.isFinite(value) && value >= 0, `${value}`);+ }+ assert.equal(estimate.layerCount, null);+ const { classifyMemoryFit } = await import(+ "../src/features/model-picker/model-config/memory-fit.ts"+ );+ // And nothing drawn from them claims a fit.+ assert.equal(classifyMemoryFit(estimate.totalBytes, 24), "unknown");+});++test("a reason the panel has no copy for is dropped rather than rendered blank", async () => {+ answer(() => json({ ...FULL, available: false, reason: "brand_new_reason" }));+ assert.equal((await fetchMemoryEstimate(REQUEST)).reason, null);+ answer(() => json({ ...FULL, available: false, reason: "not_downloaded" }));+ assert.equal((await fetchMemoryEstimate(REQUEST)).reason, "not_downloaded");+});++test("a boolean sent as the string 'false' is not read as true", async () => {+ answer(() =>+ new Response('{"available": "false", "kv_estimable": "false", "kv_on_gpu": "false"}', {+ status: 200,+ headers: { "Content-Type": "application/json" },+ }),+ );+ const estimate = await fetchMemoryEstimate(REQUEST);+ assert.equal(estimate.available, false);+ assert.equal(estimate.kvEstimable, false);+ // Absent-shaped, so the documented default stands rather than a coerced true.+ assert.equal(estimate.kvOnGpu, true);+});++// ---------------------------------------------------------------------------+// The request itself++test("the settings that move the answer are all on the wire", async () => {+ answer(() => json(FULL));+ await fetchMemoryEstimate({+ ...REQUEST,+ nCtx: 8192,+ cacheTypeKv: "q8_0",+ nParallel: 4,+ selectedGpuIds: [0, 1],+ llamaExtraArgs: ["--foo"],+ });+ const body = requests[0]?.body as Record<string, unknown>;+ assert.equal(requests[0]?.url, "/api/inference/estimate-memory");+ assert.equal(body.model_path, REQUEST.modelPath);+ assert.equal(body.gguf_variant, "Q4_K_M");+ assert.equal(body.n_ctx, 8192);+ assert.equal(body.cache_type_kv, "q8_0");+ assert.equal(body.n_parallel, 4);+ assert.deepEqual(body.selected_gpu_ids, [0, 1]);+ assert.deepEqual(body.llama_extra_args, ["--foo"]);+ // The credential is sent, but the panel never keys on it: see estimate-context.+ assert.equal(body.hf_token, null);+});++test("an expired native path lease is its own reason and never reaches the network", async () => {+ answer(() => json(FULL));+ native.setNativePathHandler(() => {+ throw new Error("lease revoked");+ });+ const estimate = await fetchMemoryEstimate({+ ...REQUEST,+ nativePathToken: "tok-1",+ });+ assert.equal(estimate.available, false);+ assert.equal(estimate.reason, "unsupported_source");+ assert.equal(requests.length, 0);+});++test("a live native lease is exchanged and forwarded", async () => {+ answer(() => json(FULL));+ native.setNativePathHandler(() => ({ nativePathLease: "lease-9" }));+ await fetchMemoryEstimate({ ...REQUEST, nativePathToken: "tok-1" });+ const body = requests[0]?.body as Record<string, unknown>;+ assert.equal(body.native_path_lease, "lease-9");+});++test("an abort signal is passed through to the transport", async () => {+ const controller = new AbortController();+ let seen: AbortSignal | null | undefined;+ auth.setAuthFetchHandler((_url, init) => {+ seen = init?.signal;+ return json(FULL);+ });+ await fetchMemoryEstimate(REQUEST, controller.signal);+ assert.equal(seen, controller.signal);+});diff --git a/studio/frontend/tests/memory-estimate-standing-defaults.test.ts b/studio/frontend/tests/memory-estimate-standing-defaults.test.tsnew file mode 100644index 00000000000..cbb93cf694d--- /dev/null+++ b/studio/frontend/tests/memory-estimate-standing-defaults.test.ts@@ -0,0 +1,87 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// Two values the Estimated Memory Usage row has to resolve the way the launch does,+// because both are absent from the per-model record in the ordinary case rather than+// in an edge one: the GPU memory mode (only "manual" is ever persisted per model) and+// the VRAM budget fraction (read asynchronously, and null on an older backend). Read+// as "unset means the default" they price a different launch than the one the Load+// button starts. Asserted against the source, the idiom tensor-parallel-row-gating+// already uses for logic that lives inside the component.++import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import path from "node:path";+import test from "node:test";+import { fileURLToPath } from "node:url";++import { DEFAULT_VRAM_FRACTION } from "../src/hooks/gpu-vram.ts";++const HERE = path.dirname(fileURLToPath(import.meta.url));+const read = (relative: string) =>+ readFileSync(path.join(HERE, "..", relative), "utf8");++const CONFIG_PAGE = read(+ "src/features/model-picker/components/model-config-page.tsx",+);+const APPLY_CONFIG = read(+ "src/features/model-picker/model-config/apply-per-model-config.ts",+);+const NORMALIZE_CONFIG = read(+ "src/features/model-picker/model-config/per-model-config.ts",+);+const BUDGET_SETTINGS = read("../backend/utils/vram_budget_settings.py");++test("only Manual is persisted per model, so an absent mode is not Auto", () => {+ // The premise of the whole fix. If this stopped holding, reading the absence as+ // Auto would be right and the resolution below would be the wrong thing to keep.+ assert.match(NORMALIZE_CONFIG, /if \(partial\.gpuMemoryMode === "manual"\)/);+});++test("the load path resolves an absent mode from the standing preference", () => {+ assert.match(+ APPLY_CONFIG,+ /gpuMemoryMode:[\s\S]{0,200}config\.gpuMemoryMode \?\? readPersistedGpuMemoryMode\(\)/,+ );+});++test("the panel resolves the same absence the same way", () => {+ assert.match(+ CONFIG_PAGE,+ /const runtimeGpuMemoryMode =\s*\n?\s*runtimeConfig\.gpuMemoryMode \?\? gpuMemoryModeFallback;/,+ );+ assert.match(+ CONFIG_PAGE,+ /const \[gpuMemoryModeFallback\] = useState\(readPersistedGpuMemoryMode\);/,+ );+});++test("the estimate request sends the resolved mode, not the raw record", () => {+ assert.match(CONFIG_PAGE, /gpuMemoryMode: runtimeGpuMemoryMode,/);+ assert.doesNotMatch(+ CONFIG_PAGE,+ /gpuMemoryMode: runtimeConfig\.gpuMemoryMode \?\? null,/,+ );+});++test("the two verdicts drawn from the mode read the resolved one too", () => {+ // A Manual placement with fixed layers is launched verbatim, so the VRAM budget+ // must not be applied to it, and its context comes from the resident load rather+ // than the control. Both branches turn on the mode.+ assert.match(CONFIG_PAGE, /runtimeGpuMemoryMode !== "manual" \|\|/);+ assert.match(CONFIG_PAGE, /runtimeGpuMemoryMode === "manual" &&/);+ assert.doesNotMatch(CONFIG_PAGE, /\(runtimeConfig\.gpuMemoryMode \?\? "auto"\)/);+});++test("the budget fraction starts at the loader's default, not a full card", () => {+ assert.match(+ CONFIG_PAGE,+ /const \[memoryVramBudgetFraction, setMemoryVramBudgetFraction\] =\s*\n?\s*useState\(DEFAULT_VRAM_FRACTION\);/,+ );+});++test("that default is the fraction the backend actually applies", () => {+ const declared = BUDGET_SETTINGS.match(/^VRAM_FRACTION_DEFAULT = ([0-9.]+)$/m);+ assert.ok(declared, "backend no longer declares VRAM_FRACTION_DEFAULT");+ assert.equal(Number(declared[1]), DEFAULT_VRAM_FRACTION);+});diff --git a/studio/frontend/tests/memory-fit.test.ts b/studio/frontend/tests/memory-fit.test.tsnew file mode 100644index 00000000000..97c6aa46b17--- /dev/null+++ b/studio/frontend/tests/memory-fit.test.ts@@ -0,0 +1,494 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// The Load-Model memory row's verdicts and the single note it prints.+//+// This file exists because the chain used to live inside model-config-page.tsx, where+// the node runner cannot reach it: a 3,400-line .tsx that imports React, the router+// and thirty component barrels. An arm that could never be taken shipped in it, and+// nothing could have caught that except reading the ternary carefully enough.++import assert from "node:assert/strict";+import test from "node:test";++import {+ type MemoryFitCapacity,+ type MemoryFitEstimate,+ type MemoryFitVerdict,+ classifyMemoryFit,+ formatMemoryGb,+ resolveDraftCacheNote,+ resolveKvNote,+ resolveMemoryFit,+ worseMemoryFit,+} from "../src/features/model-picker/model-config/memory-fit.ts";++const GB = 1024 ** 3;++const SIZED: MemoryFitEstimate = {+ gpuBytes: 0,+ totalBytes: 0,+ kvEstimable: true,+ drafterKvUnsized: false,+ adaptersUnsized: false,+ moeOffloadUnmodelled: false,+};++/** A roomy discrete host: 24 GB card, 64 GB of RAM, nothing else running. */+const IDLE_DISCRETE: MemoryFitCapacity = {+ gpuCapacityGb: 24,+ totalCapacityGb: 88,+ systemRamCapacityGb: 64,+ freeGpuCapacityGb: 23,+ usableSystemRamGb: 60,+ singleMemoryPool: false,+};++/** Apple, 64 GB unified. One pool for everything. */+const APPLE: MemoryFitCapacity = {+ gpuCapacityGb: 64,+ totalCapacityGb: 64,+ systemRamCapacityGb: 64,+ freeGpuCapacityGb: 60,+ usableSystemRamGb: 60,+ singleMemoryPool: true,+};++const fit = (+ estimate: Partial<MemoryFitEstimate>,+ capacity: Partial<MemoryFitCapacity>,+ base: MemoryFitCapacity = IDLE_DISCRETE,+) => resolveMemoryFit({ ...SIZED, ...estimate }, { ...base, ...capacity });++// ---------------------------------------------------------------------------+// classifyMemoryFit++test("a footprint well inside the capacity fits", () => {+ assert.equal(classifyMemoryFit(8 * GB, 24), "fits");+});++test("above 85% of the capacity is tight, above 100% exceeds", () => {+ assert.equal(classifyMemoryFit(20.5 * GB, 24), "tight");+ assert.equal(classifyMemoryFit(25 * GB, 24), "exceeds");+ // The boundary itself is not tight: 85% exactly is still a fit.+ assert.equal(classifyMemoryFit(0.85 * 24 * GB, 24), "fits");+ // And a footprint exactly filling the capacity has not exceeded it.+ assert.equal(classifyMemoryFit(24 * GB, 24), "tight");+});++test("nothing probed and nothing to weigh are both no verdict", () => {+ assert.equal(classifyMemoryFit(8 * GB, 0), "unknown");+ assert.equal(classifyMemoryFit(0, 24), "unknown");+ assert.equal(classifyMemoryFit(8 * GB, -4), "unknown");+ assert.equal(classifyMemoryFit(-8 * GB, 24), "unknown");+});++// The regression this guard exists for. Every one of these came back "fits" before:+// NaN and Infinity fail `<= 0` and every ratio comparison, so control fell all the way+// through to the confident green answer at the bottom.+test("a non-finite reading is never a fit", () => {+ for (const bytes of [Number.NaN, Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY]) {+ assert.equal(classifyMemoryFit(bytes, 24), "unknown", `bytes=${bytes}`);+ }+ for (const capacity of [Number.NaN, Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY]) {+ assert.equal(classifyMemoryFit(8 * GB, capacity), "unknown", `capacity=${capacity}`);+ }+});++test("a value that is not a number at all is not a fit either", () => {+ const bad = [null, undefined, "24", "", {}, []] as unknown as number[];+ for (const value of bad) {+ assert.equal(classifyMemoryFit(value, 24), "unknown", `bytes=${String(value)}`);+ assert.equal(classifyMemoryFit(8 * GB, value), "unknown", `capacity=${String(value)}`);+ }+});++// ---------------------------------------------------------------------------+// worseMemoryFit++test("the worse of two verdicts wins, and unknown loses to any real one", () => {+ assert.equal(worseMemoryFit("fits", "exceeds"), "exceeds");+ assert.equal(worseMemoryFit("exceeds", "fits"), "exceeds");+ assert.equal(worseMemoryFit("tight", "fits"), "tight");+ assert.equal(worseMemoryFit("unknown", "fits"), "fits");+ assert.equal(worseMemoryFit("fits", "unknown"), "fits");+ assert.equal(worseMemoryFit("unknown", "unknown"), "unknown");+});++test("worseMemoryFit is symmetric for every pair", () => {+ const all: MemoryFitVerdict[] = ["unknown", "fits", "tight", "exceeds"];+ for (const a of all) {+ for (const b of all) {+ assert.equal(worseMemoryFit(a, b), worseMemoryFit(b, a), `${a} vs ${b}`);+ }+ }+});++// ---------------------------------------------------------------------------+// D1: the advisory chain+//+// The defect: the pool ternary gated the WHOLE tail. Inside its+// `singleMemoryPool === false` arm, the host-pressure branch chose its wording by+// re-testing `singleMemoryPool` -- which is false there by construction -- so the+// single-pool string could not be selected by any input. The visible half of the same+// bug is that a single-pool host had exactly one reachable note.++const ADVISORY_TEXTS = {+ singlePoolExceeds:+ "More than this machine's memory. The GPU and the rest of the system share one pool here, so there is nothing to offload to.",+ singlePoolPressure:+ "This fits the machine, but not what is free right now. If that memory is not the model being replaced, the context will be fitted down or the load refused.",+ hostShareExceeds:+ "More than system RAM holds. This placement keeps most of the load outside the GPU, and spare VRAM cannot take those bytes.",+ totalExceeds:+ "More than this machine holds. The GPU and system RAM together are not enough for this load, so spilling layers or fitting the context down will not recover it.",+ gpuExceeds:+ "More than this GPU holds. Layers will spill to system RAM, or the context will be fitted down to what fits.",+ hostPressure:+ "The part of this load that runs from system RAM fits the machine, but not what is free right now. If that memory is not the model being replaced, the load will be refused.",+ gpuPressure:+ "This fits the card, but something is using it right now. If that memory is not the model being replaced, layers will spill or the context will be fitted down.",+};++test("D1: a single-pool host under memory pressure now says so", () => {+ // Apple, 64 GB unified, a 30 GB load, 6 GB actually free. The machine holds it;+ // what is free does not. Before the fix this produced no note whatsoever, because+ // the only branch a single pool could reach was "exceeds".+ const result = fit(+ { gpuBytes: 30 * GB, totalBytes: 30 * GB },+ { freeGpuCapacityGb: 6, usableSystemRamGb: 6 },+ APPLE,+ );+ assert.equal(result.totalFit, "fits");+ assert.ok(result.gpuPressured || result.hostPressured);+ assert.deepEqual(result.advisory, {+ tone: "muted",+ text: ADVISORY_TEXTS.singlePoolPressure,+ });+});++test("D1: the single-pool pressure text is reachable from EITHER free reading", () => {+ // Free VRAM sees it, host RAM does not.+ const gpuSide = fit(+ { gpuBytes: 30 * GB, totalBytes: 30 * GB },+ { freeGpuCapacityGb: 6, usableSystemRamGb: 60 },+ APPLE,+ );+ assert.equal(gpuSide.advisory?.text, ADVISORY_TEXTS.singlePoolPressure);+ // Host RAM sees it, free VRAM does not.+ const hostSide = fit(+ { gpuBytes: 30 * GB, totalBytes: 30 * GB },+ { freeGpuCapacityGb: 60, usableSystemRamGb: 6 },+ APPLE,+ );+ assert.equal(hostSide.advisory?.text, ADVISORY_TEXTS.singlePoolPressure);+});++test("D1: no discrete-host string can be chosen on a single-pool host", () => {+ // The other half of the dead branch: the two discrete pressure strings talk about+ // "the card" and "the part of this load that runs from system RAM", neither of+ // which means anything where there is one pool.+ const sweep = new Set<string>();+ for (const gpuBytes of [0, 4 * GB, 30 * GB, 90 * GB]) {+ for (const totalBytes of [0, 4 * GB, 30 * GB, 90 * GB]) {+ for (const freeGpuCapacityGb of [0, 2, 6, 60]) {+ for (const usableSystemRamGb of [0, 2, 6, 60]) {+ const note = fit(+ { gpuBytes, totalBytes },+ { freeGpuCapacityGb, usableSystemRamGb },+ APPLE,+ ).advisory?.text;+ if (note) sweep.add(note);+ }+ }+ }+ }+ assert.deepEqual(+ [...sweep].sort(),+ [ADVISORY_TEXTS.singlePoolExceeds, ADVISORY_TEXTS.singlePoolPressure].sort(),+ );+});++test("D1: the discrete host keeps its own wording, and never the single-pool one", () => {+ const sweep = new Set<string>();+ for (const gpuBytes of [0, 4 * GB, 20 * GB, 30 * GB]) {+ for (const totalBytes of [0, 4 * GB, 30 * GB, 200 * GB]) {+ for (const freeGpuCapacityGb of [0, 2, 23]) {+ for (const usableSystemRamGb of [0, 2, 60]) {+ const note = fit(+ { gpuBytes, totalBytes },+ { freeGpuCapacityGb, usableSystemRamGb },+ ).advisory?.text;+ if (note) sweep.add(note);+ }+ }+ }+ }+ assert.equal(sweep.has(ADVISORY_TEXTS.singlePoolPressure), false);+ assert.equal(sweep.has(ADVISORY_TEXTS.singlePoolExceeds), false);+});++test("the floor notes outrank every verdict, in their own order", () => {+ // An unsizable cache says the figures are incomplete, which beats any reading of+ // them. The header case outranks the drafter case, and both outrank the MoE note.+ const both = fit(+ { kvEstimable: false, drafterKvUnsized: true, moeOffloadUnmodelled: true, totalBytes: 900 * GB },+ {},+ );+ assert.equal(both.advisory?.tone, "warn");+ assert.match(both.advisory?.text ?? "", /attention dimensions/);+ const drafter = fit(+ { drafterKvUnsized: true, moeOffloadUnmodelled: true, totalBytes: 900 * GB },+ {},+ );+ assert.match(drafter.advisory?.text ?? "", /fetch rather than one on this disk/);+ const moe = fit({ moeOffloadUnmodelled: true, totalBytes: 900 * GB }, {});+ assert.equal(moe.advisory?.tone, "muted");+ assert.match(moe.advisory?.text ?? "", /Expert layers/);+});++test("the floor marker follows either unsizable case", () => {+ assert.equal(fit({ kvEstimable: false }, {}).prefix, "≥ ");+ assert.equal(fit({ drafterKvUnsized: true }, {}).prefix, "≥ ");+ assert.equal(fit({}, {}).prefix, "");+ assert.equal(fit({ kvEstimable: false }, {}).bounded, true);+ assert.equal(fit({}, {}).bounded, false);+});++test("the aggregate verdict is asked before the GPU one", () => {+ // A 200 GB load on a 24 GB card and 64 GB of RAM. Reading gpuFit alone offered+ // spilling to system RAM as the remedy, which is advice to do something that cannot+ // work.+ const result = fit({ gpuBytes: 20 * GB, totalBytes: 200 * GB }, {});+ assert.equal(result.advisory?.text, ADVISORY_TEXTS.hostShareExceeds);+});++test("a load beyond GPU and RAM combined, with a host share that fits RAM", () => {+ const result = fit(+ { gpuBytes: 80 * GB, totalBytes: 120 * GB },+ { gpuCapacityGb: 24, totalCapacityGb: 88, systemRamCapacityGb: 64 },+ );+ assert.equal(result.advisory?.text, ADVISORY_TEXTS.totalExceeds);+});++test("a load that only overflows the card is told it will spill", () => {+ const result = fit({ gpuBytes: 30 * GB, totalBytes: 30 * GB }, {});+ assert.equal(result.advisory?.text, ADVISORY_TEXTS.gpuExceeds);+});++test("a discrete host under host-RAM pressure keeps the system-RAM wording", () => {+ const result = fit(+ { gpuBytes: 10 * GB, totalBytes: 50 * GB },+ { usableSystemRamGb: 38 },+ );+ assert.equal(result.advisory?.text, ADVISORY_TEXTS.hostPressure);+});++test("a discrete host under VRAM pressure alone gets the card wording", () => {+ const result = fit(+ { gpuBytes: 20 * GB, totalBytes: 20 * GB },+ { freeGpuCapacityGb: 8 },+ );+ assert.equal(result.advisory?.text, ADVISORY_TEXTS.gpuPressure);+ // And the GPU figure is coloured amber rather than left green.+ assert.equal(result.rawGpuFit, "fits");+ assert.equal(result.gpuFit, "tight");+});++test("a comfortable load says nothing at all", () => {+ assert.equal(fit({ gpuBytes: 6 * GB, totalBytes: 6 * GB }, {}).advisory, null);+ assert.equal(+ fit({ gpuBytes: 6 * GB, totalBytes: 6 * GB }, {}, APPLE).advisory,+ null,+ );+});++// ---------------------------------------------------------------------------+// The pool-aware free reading++test("one pool weighs the WHOLE load against what is free, not the GPU share", () => {+ // A shared iGPU with half the load CPU-offloaded. Those bytes come out of the same+ // memory, so measuring only the GPU share against free memory called a load that+ // cannot fit comfortable.+ const pooled = fit(+ { gpuBytes: 6 * GB, totalBytes: 30 * GB },+ { freeGpuCapacityGb: 10, usableSystemRamGb: 10 },+ { ...APPLE, singleMemoryPool: true },+ );+ assert.equal(pooled.freeGpuFit, "exceeds");+ assert.equal(pooled.gpuPressured, true);+ // The discrete host asks the same question of the GPU share alone, which is right+ // there: the host bytes are a different pool.+ const discrete = fit(+ { gpuBytes: 6 * GB, totalBytes: 30 * GB },+ { freeGpuCapacityGb: 10 },+ );+ assert.equal(discrete.freeGpuFit, "fits");+});++test("the host share is the bytes outside the GPU, floored at zero", () => {+ assert.equal(fit({ gpuBytes: 10 * GB, totalBytes: 30 * GB }, {}).hostShareBytes, 20 * GB);+ // gpu_bytes above total_bytes is nonsense off the wire, not a negative footprint.+ assert.equal(fit({ gpuBytes: 30 * GB, totalBytes: 10 * GB }, {}).hostShareBytes, 0);+});++test("one pool asks no separate host-share question", () => {+ // The combined figure already describes that case exactly, so a second verdict+ // drawn from the same bytes would only be able to disagree with it.+ assert.equal(fit({ gpuBytes: 6 * GB, totalBytes: 30 * GB }, {}, APPLE).hostShareFit, "unknown");+});++// ---------------------------------------------------------------------------+// Garbage in++test("a non-finite footprint produces no verdict and no advisory, and does not throw", () => {+ for (const bad of [Number.NaN, Number.POSITIVE_INFINITY]) {+ const result = fit({ gpuBytes: bad, totalBytes: bad }, {});+ assert.equal(result.gpuFit, "unknown");+ assert.equal(result.totalFit, "unknown");+ assert.equal(result.advisory, null);+ // A number the caller can print. Math.max(0, NaN) is NaN, not 0.+ assert.equal(result.hostShareBytes, 0);+ }+});++test("a non-finite capacity never yields a fit", () => {+ const result = fit(+ { gpuBytes: 8 * GB, totalBytes: 8 * GB },+ {+ gpuCapacityGb: Number.NaN,+ totalCapacityGb: Number.POSITIVE_INFINITY,+ systemRamCapacityGb: Number.NaN,+ freeGpuCapacityGb: Number.NaN,+ usableSystemRamGb: Number.POSITIVE_INFINITY,+ },+ );+ assert.equal(result.gpuFit, "unknown");+ assert.equal(result.totalFit, "unknown");+ assert.equal(result.gpuPressured, false);+ assert.equal(result.hostPressured, false);+});++test("no combination of garbage throws or produces a verdict outside the four", () => {+ const values = [+ 0, -1, 1, Number.NaN, Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY,+ null, undefined, "12", {},+ ] as unknown as number[];+ const allowed = new Set(["fits", "tight", "exceeds", "unknown"]);+ for (const a of values) {+ for (const b of values) {+ const result = fit(+ { gpuBytes: a, totalBytes: b },+ {+ gpuCapacityGb: a,+ totalCapacityGb: b,+ systemRamCapacityGb: a,+ freeGpuCapacityGb: b,+ usableSystemRamGb: a,+ },+ );+ for (const verdict of [+ result.gpuFit, result.rawGpuFit, result.totalFit,+ result.hostShareFit, result.freeGpuFit, result.usableHostFit,+ ]) {+ assert.ok(allowed.has(verdict), `${String(a)}/${String(b)} -> ${verdict}`);+ }+ // Never a confident green from a number that does not exist. `a` drives both+ // gpuBytes and gpuCapacityGb, so it is the one this verdict depends on; a bad+ // `b` only reaches the free reading, and losing that warning is not a false fit.+ if (!Number.isFinite(a)) {+ assert.notEqual(result.gpuFit, "fits", `gpuBytes=${String(a)}`);+ }+ if (!Number.isFinite(b)) {+ assert.notEqual(result.totalFit, "fits", `totalBytes=${String(b)}`);+ }+ // And every figure the row prints stays printable.+ assert.ok(+ Number.isFinite(result.hostShareBytes) && result.hostShareBytes >= 0,+ `hostShareBytes=${result.hostShareBytes}`,+ );+ }+ }+});++// ---------------------------------------------------------------------------+// formatMemoryGb++test("a figure is always finite and never negative", () => {+ assert.equal(formatMemoryGb(24 * GB), "24.00 GB");+ assert.equal(formatMemoryGb(0), "0.00 GB");+ assert.equal(formatMemoryGb(-5 * GB), "0.00 GB");+ assert.equal(formatMemoryGb(Number.NaN), "0.00 GB");+ assert.equal(formatMemoryGb(Number.POSITIVE_INFINITY), "0.00 GB");+ assert.equal(formatMemoryGb(undefined as unknown as number), "0.00 GB");+});++// ---------------------------------------------------------------------------+// The two captions++test("the KV caption names the dtype, what was priced, and where it lives", () => {+ assert.equal(+ resolveKvNote({ cacheTypeKv: "q8_0", nCtx: 32768, nParallel: 1, kvOnGpu: true }),+ "q8_0 · 32,768 tokens",+ );+ // No dtype reported falls back to f16, several slots are named, and a cache the+ // loader moved off the GPU says where it went.+ assert.equal(+ resolveKvNote({ cacheTypeKv: null, nCtx: 4096, nParallel: 4, kvOnGpu: false }),+ "f16 · 4,096 tokens · 4 slots · host RAM",+ );+ // A single slot is the unremarkable case and is not named.+ assert.equal(+ resolveKvNote({ cacheTypeKv: "f16", nCtx: 4096, nParallel: 1, kvOnGpu: false }),+ "f16 · 4,096 tokens · host RAM",+ );+});++test("the KV caption survives a field that is not a number", () => {+ // `.toLocaleString()` on a null throws, and one bad field must not take the panel+ // down with it.+ assert.doesNotThrow(() =>+ resolveKvNote({+ cacheTypeKv: null,+ nCtx: null as unknown as number,+ nParallel: Number.NaN,+ kvOnGpu: true,+ }),+ );+ assert.equal(+ resolveKvNote({+ cacheTypeKv: null,+ nCtx: Number.NaN,+ nParallel: 1,+ kvOnGpu: true,+ }),+ "f16 · 0 tokens",+ );+});++test("the draft cache note reads its OWN placement, not the target cache's", () => {+ // --spec-draft-ngl 0 moves the drafter while --no-kv-offload moves the target, so a+ // boolean read off the target was wrong in both directions.+ assert.equal(resolveDraftCacheNote(0, 4 * GB), "host RAM");+ // Under MTP the term is split across both placements: a third case.+ assert.equal(resolveDraftCacheNote(1 * GB, 4 * GB), "1.00 GB on GPU");+ // Entirely on the GPU is the unremarkable case and gets no caption.+ assert.equal(resolveDraftCacheNote(4 * GB, 4 * GB), undefined);+ assert.equal(resolveDraftCacheNote(Number.NaN, 4 * GB), "host RAM");+});++test("an unsizable pass-through adapter marks the total a floor", () => {+ // llama.cpp loads every --lora / --control-vector into resident tensors on top of+ // the base model. When one is named but cannot be stat'd its bytes are missing, so+ // the figure is a lower bound and has to say so, exactly as an unsized drafter does.+ const bounded = resolveMemoryFit(+ { ...SIZED, adaptersUnsized: true, totalBytes: 8 * GB, gpuBytes: 8 * GB },+ IDLE_DISCRETE,+ );+ assert.equal(bounded.bounded, true);+ const sized = resolveMemoryFit(+ { ...SIZED, totalBytes: 8 * GB, gpuBytes: 8 * GB },+ IDLE_DISCRETE,+ );+ assert.equal(sized.bounded, false);+});diff --git a/tests/studio/playwright_memory_estimate.py b/tests/studio/playwright_memory_estimate.pynew file mode 100644index 00000000000..e74ee678843--- /dev/null+++ b/tests/studio/playwright_memory_estimate.py@@ -0,0 +1,1076 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++""" "Estimated Memory Usage" row Playwright regression test (GPU-free, no model load).++The row lives in the model-picker's run-settings panel (MemoryEstimateRow in+features/model-picker/components/model-config-page.tsx) and it renders ONLY when the+selected target is a GGUF and POST /api/inference/estimate-memory answers+`available: true`. When it cannot answer it returns `null` -- the row HIDES rather+than erroring -- which is why a screenshot of this panel proves nothing on its own:+an unavailable estimate, a 404 from a backend predating the route, and a row that+was never implemented all look identical on screen.++So this drives the row against a RECORDED API exchange. Every+/api/inference/estimate-memory call is intercepted with `context.route`, its POST body+is captured, and the response this test hands back is the one the row is then asserted+to be displaying. What that buys, gate by gate:++ - Request carries the settings: typing a distinctive Context Length must produce a+ NEW estimate POST whose `n_ctx` is that number, and whose body still carries the+ rest of the load settings the panel is supposed to price (model_path, cache_type_kv,+ n_parallel, gpu_memory_mode). A row that re-renders without re-pricing, or one wired+ to a stale request object, fails here (HARD).+ - Response reaches the screen: the figures shown are the ones the stub returned, to+ the byte -- `formatMemoryGb` of the stubbed totals, and, once the row is expanded,+ the breakdown lines plus the KV note built from the echoed context and cache dtype+ (HARD).+ - The row hides rather than errors: `available: false` hides it, restoring the+ available response brings it BACK -- without that half, "hidden" is satisfied by a+ panel that simply died -- and an HTTP 404, the answer from a backend predating the+ route, hides it too, with no page error (HARD).++Stubbing is deliberate. The real endpoint needs a GGUF whose header is on this disk and+answers with whatever that machine's memory happens to be, so a test asserting real+figures would either assert nothing specific or be a hardware report. The request half+is not stubbed: it is the panel's own, unmodified.++Runs as a plain script (not via pytest), mirroring tests/studio/playwright_model_config.py:+accumulate failures in `_failed`, exit non-zero if any HARD gate failed. With+STUDIO_UI_STRICT=1 (as CI sets), soft_fail also gates; genuinely-optional checks use+runtime_warn so they never flake the merge gate.++Honours STUDIO_PLAYWRIGHT_BROWSER in {chromium, firefox, webkit}, like every sibling+scene. The locale is pinned to en-US because one assertion reads a number the app+formatted with `toLocaleString`.+"""++import json+import re+import sys+import os+import time+from pathlib import Path++from playwright.sync_api import sync_playwright++# Run as a plain script (not via pytest), so prepend the dir to sys.path.+sys.path.insert(0, str(Path(__file__).resolve().parent))+from _playwright_robust import ( # noqa: E402+ chromium_launch_args,+ click_and_wait_for_response,+ dump_diagnostics,+ install_view_transition_killer,+ install_wall_clock_watchdog,+ is_benign_page_error,+ recover_or_replace_page,+ wait_for_health,+)++BASE = os.environ["BASE_URL"]+NEW = os.environ.get("STUDIO_NEW_PW", "MemEst-NEW-2026!")+# Attach mode: log into an already-provisioned Unsloth with an existing password instead+# of the first-boot change-password dance. The CI step runs this after the model-config+# scene against the SAME server, whose bootstrap password that scene has already rotated,+# so there is no change-password flow left to drive there.+LOGIN_PW = os.environ.get("STUDIO_LOGIN_PW")+LOGIN_USER = os.environ.get("STUDIO_LOGIN_USER", "unsloth")+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.+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.+#+# 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.+CTX_CANDIDATES = [+ int(part)+ for part in os.environ.get("STUDIO_CTX_CANDIDATES", "6144,5120,4096,3072,2048,1536").split(",")+ if part.strip()+]+ART_DIR = os.environ.get("PW_ART_DIR", "logs/playwright_memory_estimate")+# Settle window after run-settings opens, before staging an edit. Same reason as+# playwright_model_config.py: an edit made in the panel's first moments is discarded when+# the panel re-derives its baseline once mount-time work lands.+CONFIG_SETTLE_MS = int(os.environ.get("STUDIO_CONFIG_SETTLE_MS", "1000"))+ART = Path(ART_DIR)+ART.mkdir(parents = True, exist_ok = True)+STRICT = os.environ.get("STUDIO_UI_STRICT", "0") == "1"+PLAYWRIGHT_BROWSER = os.environ.get("STUDIO_PLAYWRIGHT_BROWSER", "chromium").lower()+PLAYWRIGHT_CHANNEL = os.environ.get("STUDIO_PLAYWRIGHT_CHANNEL") or None+WALL_TIMEOUT_S = float(os.environ.get("STUDIO_UI_WALL_TIMEOUT_S", "600"))+# The hook debounces at 250ms and the fetch is intercepted in-process, so a re-price+# lands in well under a second; this is the "it is never coming" bound.+ESTIMATE_WAIT_MS = int(os.environ.get("STUDIO_UI_ESTIMATE_WAIT_MS", "20000"))++TRANSCRIPT_NAME = "memory-estimate-exchanges.json"++GIB = 1024**3+# Exact quarter-GiB figures on purpose: `formatMemoryGb` is `(bytes / 1024**3).toFixed(2)`,+# and a quarter of a GiB is exactly representable, so the string the app renders is+# predictable to the last digit on every engine rather than a rounding argument.+STUB_WEIGHTS_BYTES = int(3.25 * GIB)+STUB_KV_BYTES = int(1.50 * GIB)+STUB_COMPUTE_BYTES = int(0.75 * GIB)+STUB_TOTAL_BYTES = STUB_WEIGHTS_BYTES + STUB_KV_BYTES + STUB_COMPUTE_BYTES # 5.50 GiB+STUB_GPU_BYTES = int(4.75 * GIB)+STUB_LAYER_COUNT = 27+STUB_GPU_LAYERS = 12+++def _gb(num_bytes: int) -> str:+ """Python-side mirror of formatMemoryGb in api/memory-estimate.ts."""+ return f"{num_bytes / GIB:.2f} GB"+++_n = [0]+_failed: list[str] = []+++def step(s: str) -> None:+ print(f"[ui-memest] STEP {s}", flush = True)+++def info(s: str) -> None:+ print(f"[ui-memest] {s}", flush = True)+++def fail(m: str) -> None:+ print(f"[ui-memest] FAIL: {m}", flush = True)+ _failed.append(m)+++def soft_fail(m: str) -> None:+ if STRICT:+ fail(m)+ else:+ info(f"WARN (strict-off): {m}")+++def runtime_warn(m: str) -> None:+ """Warn about a genuinely-optional check that STRICT does not gate."""+ info(f"WARN (runtime): {m}")+++def _count(loc) -> int:+ """Number of matches, or 0.++ A raise here is not the same as no match: a closed page or a lost execution context+ also throws, and reporting that as "selector missing" sends the reader after the+ markup instead of the crash. Say so, then still return 0.+ """+ try:+ return loc.count()+ except Exception as exc:+ info(f"WARN: locator raised (not a missing element): {type(exc).__name__}: {exc}")+ return 0+++def _login_token_via_api(base: str, user: str, pw: str) -> str:+ """POST /api/auth/login -> access_token (attach-mode helper, stdlib only)."""+ import urllib.request++ req = urllib.request.Request(+ f"{base}/api/auth/login",+ data = json.dumps({"username": user, "password": pw}).encode(),+ headers = {"Content-Type": "application/json"},+ method = "POST",+ )+ with urllib.request.urlopen(req, timeout = 15) as r:+ return json.loads(r.read().decode())["access_token"]+++# ─────────────────────────────────────────────────────+# The stubbed endpoint. `_mode` decides what the NEXT call answers; every call is+# recorded, request and response, and the whole transcript is written to the artifact+# directory so a failure can be read after the fact.+# ─────────────────────────────────────────────────────+_mode = ["available"]+exchanges: list[dict] = []++UNAVAILABLE_BODY = {+ "available": False,+ # The reason a real backend gives for a GGUF whose file is not on this disk, which+ # is the commonest way a user meets the hidden row.+ "reason": "not_downloaded",+ "weights_bytes": 0,+ "kv_bytes": 0,+ "compute_bytes": 0,+ "drafter_runtime_bytes": 0,+ "drafter_runtime_gpu_bytes": 0,+ "projector_runtime_bytes": 0,+ "drafter_kv_unsized": False,+ "total_bytes": 0,+ "gpu_bytes": 0,+ "kv_estimable": False,+ "kv_on_gpu": True,+ "n_ctx": 0,+ "cache_type_kv": None,+ "n_parallel": 1,+ "layer_count": None,+ "gpu_layers": None,+ "moe_offload_unmodelled": False,+}+++def _available_body(request_payload: dict) -> dict:+ """An available estimate whose context / cache dtype / slot count ECHO the request.++ Echoing is what turns the KV note into a round-trip assertion: the note is built+ from `nCtx` and `cacheTypeKv` off the RESPONSE, so seeing the context that was typed+ into the control appear there proves the value travelled control -> request ->+ response -> DOM, not merely that a number rendered.+ """+ raw_ctx = request_payload.get("n_ctx")+ n_ctx = int(raw_ctx) if isinstance(raw_ctx, (int, float)) and raw_ctx else 0+ raw_parallel = request_payload.get("n_parallel")+ n_parallel = int(raw_parallel) if isinstance(raw_parallel, (int, float)) and raw_parallel else 1+ return {+ "available": True,+ "reason": None,+ "weights_bytes": STUB_WEIGHTS_BYTES,+ "kv_bytes": STUB_KV_BYTES,+ "compute_bytes": STUB_COMPUTE_BYTES,+ "drafter_runtime_bytes": 0,+ "drafter_runtime_gpu_bytes": 0,+ "projector_runtime_bytes": 0,+ "drafter_kv_unsized": False,+ "total_bytes": STUB_TOTAL_BYTES,+ "gpu_bytes": STUB_GPU_BYTES,+ "kv_estimable": True,+ "kv_on_gpu": True,+ "n_ctx": n_ctx,+ "cache_type_kv": request_payload.get("cache_type_kv") or "f16",+ "n_parallel": n_parallel,+ "layer_count": STUB_LAYER_COUNT,+ "gpu_layers": STUB_GPU_LAYERS,+ "moe_offload_unmodelled": False,+ }+++def _handle_estimate(route) -> None:+ request = route.request+ raw = ""+ try:+ raw = request.post_data or ""+ except Exception:+ raw = ""+ try:+ payload = json.loads(raw) if raw else {}+ except Exception:+ payload = {}+ if not isinstance(payload, dict):+ payload = {}+ mode = _mode[0]+ record: dict = {+ "ts": time.time(),+ "mode": mode,+ "method": request.method,+ "url": request.url,+ "request": payload,+ "raw_request": raw[:2000],+ }+ exchanges.append(record)+ if mode == "http404":+ body = {"detail": "Not Found"}+ record["response_status"] = 404+ record["response"] = body+ route.fulfill(+ status = 404,+ content_type = "application/json",+ body = json.dumps(body),+ )+ return+ body = dict(UNAVAILABLE_BODY) if mode == "unavailable" else _available_body(payload)+ record["response_status"] = 200+ record["response"] = body+ route.fulfill(status = 200, content_type = "application/json", body = json.dumps(body))+++def write_transcript() -> None:+ """The recorded API exchange, in the artifact directory the sibling scenes use."""+ try:+ (ART / TRANSCRIPT_NAME).write_text(+ json.dumps(+ {+ "base_url": BASE,+ "browser": PLAYWRIGHT_BROWSER,+ "model": {"repo": GGUF_REPO, "variant": GGUF_VARIANT},+ "stub": {+ "weights_bytes": STUB_WEIGHTS_BYTES,+ "kv_bytes": STUB_KV_BYTES,+ "compute_bytes": STUB_COMPUTE_BYTES,+ "total_bytes": STUB_TOTAL_BYTES,+ "gpu_bytes": STUB_GPU_BYTES,+ },+ "exchanges": exchanges,+ },+ indent = 2,+ default = str,+ ),+ encoding = "utf-8",+ )+ info(f"wrote {len(exchanges)} estimate exchange(s) to {ART / TRANSCRIPT_NAME}")+ except Exception as exc:+ info(f"WARN: could not write the exchange transcript: {exc}")+++with sync_playwright() as p:+ _watchdog = install_wall_clock_watchdog(WALL_TIMEOUT_S, label = "ui-memest", info = info)+ # Health pre-flight: a bash-side health wait can pass before the auth DB migrates.+ wait_for_health(BASE, timeout = 30.0, info = info)+ if PLAYWRIGHT_BROWSER not in ("chromium", "firefox", "webkit"):+ fail(f"unsupported STUDIO_PLAYWRIGHT_BROWSER={PLAYWRIGHT_BROWSER!r}")+ sys.exit(1)+ browser_type = getattr(p, PLAYWRIGHT_BROWSER)+ launch_kwargs = {"headless": True}+ if PLAYWRIGHT_BROWSER == "chromium":+ launch_kwargs["args"] = chromium_launch_args()+ if PLAYWRIGHT_CHANNEL:+ launch_kwargs["channel"] = PLAYWRIGHT_CHANNEL+ elif PLAYWRIGHT_CHANNEL:+ fail("STUDIO_PLAYWRIGHT_CHANNEL requires chromium")+ sys.exit(1)+ browser = browser_type.launch(**launch_kwargs)+ ctx = browser.new_context(+ viewport = {"width": 1280, "height": 900},+ reduced_motion = "reduce",+ # One assertion reads a number the app formatted with `toLocaleString`, whose+ # group separator is a property of the locale. Left to the engine's default,+ # 8192 renders "8,192" on one runner and "8 192" on another, and the gate would+ # be measuring the runner.+ locale = "en-US",+ )+ install_view_transition_killer(ctx)+ # On the CONTEXT, not the page: a page replaced by the recovery helper below would+ # otherwise lose the interception and reach the real endpoint, which on a runner with+ # no GGUF answers unavailable -- so the row would hide and this would read as the+ # feature being broken.+ ctx.route("**/api/inference/estimate-memory*", _handle_estimate)+ page = ctx.new_page()+ page.set_default_timeout(60_000)+ page_errors: list[str] = []++ def _on_pageerror(e):+ msg = str(e)+ if is_benign_page_error(msg):+ info(f"WARN ignoring benign pageerror: {msg!r}")+ return+ page_errors.append(msg)++ page.on("pageerror", _on_pageerror)++ def shoot(name: str) -> None:+ _n[0] += 1+ try:+ page.screenshot(+ path = str(ART / f"{_n[0]:02d}-{name}.png"),+ full_page = True,+ timeout = 90_000,+ animations = "disabled",+ )+ except Exception as exc:+ info(f"WARN: screenshot {name} failed: {exc}")++ def diagnose(name: str, missed: str) -> None:+ rows = []+ try:+ opts = page.locator("[data-model-picker-option]")+ rows = [+ (opts.nth(i).inner_text() or "").strip()[:60] for i in range(min(opts.count(), 12))+ ]+ except Exception:+ pass+ dump_diagnostics(+ page,+ ART,+ name,+ info = info,+ extra = {+ "missed_selector": missed,+ "option_rows": rows,+ "estimate_exchanges": exchanges[-4:],+ "mode": _mode[0],+ },+ )++ # ─────────────────────────────────────────────────────+ # Setup: authenticate.+ # ─────────────────────────────────────────────────────+ if LOGIN_PW:+ step("setup: API login + token seed (attach to running Unsloth)")+ _tok = _login_token_via_api(BASE, LOGIN_USER, LOGIN_PW)+ ctx.add_init_script(+ f"try{{localStorage.setItem('unsloth_auth_token', {json.dumps(_tok)});}}catch(e){{}}"+ )+ page.goto(BASE, wait_until = "domcontentloaded", timeout = 60_000)+ else:+ step("setup: change-password")+ form_err: Exception | None = None+ for _attempt in range(3):+ try:+ page.goto(f"{BASE}/change-password", wait_until = "domcontentloaded", timeout = 60_000)+ try:+ page.wait_for_load_state("networkidle", timeout = 30_000)+ except Exception:+ pass+ pw_field = page.locator("#new-password")+ pw_field.wait_for(state = "visible", timeout = 60_000)+ pw_field.fill(NEW, timeout = 60_000)+ page.fill("#confirm-password", NEW, timeout = 60_000)+ status, _ = click_and_wait_for_response(+ page,+ url_substr = "/api/auth/change-password",+ method = "POST",+ do_click = lambda: page.locator('button[type="submit"]').click(),+ timeout_ms = 30_000,+ info = lambda m: print(f"[ui-memest] {m}", flush = True),+ )+ if status is not None and status >= 400:+ raise AssertionError(+ f"change-password POST returned {status}; page_errors={page_errors[:1]!r}"+ )+ form_err = None+ break+ except Exception as e:+ form_err = e+ try:+ cur_url = page.url+ except Exception:+ cur_url = "<page closed>"+ print(+ f"[ui-memest] change-password attempt {_attempt + 1} failed: "+ f"{type(e).__name__}: {str(e)[:200]}; page.url={cur_url}",+ flush = True,+ )+ if _attempt < 2:+ page = recover_or_replace_page(+ page,+ ctx,+ default_timeout_ms = 60_000,+ info = lambda m: print(f"[ui-memest] recovery: {m}", flush = True),+ )+ page.on("pageerror", _on_pageerror)+ if form_err is not None:+ raise form_err++ try:+ page.wait_for_load_state("networkidle", timeout = 30_000)+ except Exception:+ pass+ composer = page.locator('textarea[aria-label="Message input"]')+ last_err: Exception | None = None+ for _attempt in range(2):+ try:+ composer.wait_for(state = "visible", timeout = 60_000)+ last_err = None+ break+ except Exception as e:+ last_err = e+ shoot(f"00-composer-wait-attempt-{_attempt + 1}-fail")+ if _attempt == 0:+ page = recover_or_replace_page(+ page,+ ctx,+ default_timeout_ms = 60_000,+ goto_url = BASE,+ settle_networkidle = True,+ info = lambda m: print(f"[ui-memest] recovery: {m}", flush = True),+ )+ page.on("pageerror", _on_pageerror)+ composer = page.locator('textarea[aria-label="Message input"]')+ if last_err is not None:+ raise last_err+ shoot("01-chat-loaded")++ # ─────────────────────────────────────────────────────+ # Picker helpers (same proven selectors as playwright_model_config.py).+ # ─────────────────────────────────────────────────────+ POPOVER = '[data-tour="chat-model-selector-popover"]'+ TRIGGER = '[data-tour="chat-model-selector"]'+ SOLE_QUANT_SETTLE_MS = 30_000+ QUANT_GEAR_MS = 2_000++ def open_picker():+ popover = page.locator(POPOVER).first+ if _count(popover) == 0 or not popover.is_visible():+ page.locator(TRIGGER).first.click()+ page.wait_for_timeout(900)+ popover = page.locator(POPOVER).first+ popover.wait_for(state = "visible", timeout = 30_000)+ return popover++ def close_picker():+ try:+ page.keyboard.press("Escape")+ page.wait_for_timeout(400)+ except Exception:+ pass++ def reveal_on_device_row(popover, hint):+ """Bring the row into view without clicking it: a single-quant row loads its+ quant on click and closes the picker, taking the gear with it."""+ od = page.get_by_role("tab", name = "On Device").first+ if _count(od):+ od.click()+ page.wait_for_timeout(700)+ try:+ popover.locator("[data-model-picker-option]").first.wait_for(+ state = "attached", timeout = 20_000+ )+ except Exception:+ pass+ row = popover.locator("[data-model-picker-option]", has_text = hint).first+ if _count(row) == 0:+ search = popover.locator("[data-model-picker-search-input]").first+ if _count(search):+ search.click()+ search.fill(hint)+ page.wait_for_timeout(700)+ row = popover.locator("[data-model-picker-option]", has_text = hint).first+ return row if _count(row) else None++ def select_on_device_row(popover, hint):+ row = reveal_on_device_row(popover, hint)+ if row is None:+ return None+ row.click()+ page.wait_for_timeout(800)+ return row++ def row_gear(+ popover,+ hint,+ quant = None,+ timeout_ms = SOLE_QUANT_SETTLE_MS,+ ):+ # The gear is a sibling of the row, not inside [data-model-picker-option]. The+ # quant is anchored to the end: every label is "<repo> <quant>", so an unanchored+ # match lets F16 find BF16 and `.first` then opens a variant this test never named.+ pattern = f"^Inference settings for .*{re.escape(hint)}"+ if quant:+ pattern += f".* {re.escape(quant)}$"+ gear = popover.get_by_role("button", name = re.compile(pattern, re.IGNORECASE)).first+ try:+ gear.wait_for(state = "visible", timeout = timeout_ms)+ except Exception:+ return None+ return gear++ def config_is_open(popover):+ """Back is unique to the config page and always rendered inside the picker."""+ return _count(popover.get_by_role("button", name = "Back to model list")) > 0++ def open_config(popover, hint):+ if reveal_on_device_row(popover, hint) is None:+ diagnose("no-picker-row", f"[data-model-picker-option] has_text={hint!r}")+ return None+ # The quant first: with "Expand quantizations" on, a repo-only lookup finds some+ # gear straight away and which one is arbitrary. Repo-only stays as the fallback,+ # for the collapsed sole-quant row whose label carries its own quant.+ gear = row_gear(popover, hint, quant = GGUF_VARIANT, timeout_ms = QUANT_GEAR_MS)+ if gear is None:+ gear = row_gear(popover, hint)+ if gear is None:+ # A multi-quant repo shows gears only once the row is expanded, and clicking+ # a collapsed sole-quant row loads it and closes the picker -- so reopen and+ # look again rather than treating a closed picker as a missing gear.+ if select_on_device_row(popover, hint) is None:+ diagnose("no-row-gear", f"Inference settings for ...{hint}")+ return None+ if not popover.is_visible():+ popover = open_picker()+ if reveal_on_device_row(popover, hint) is None:+ diagnose("no-row-gear-after-reopen", f"[data-model-picker-option] {hint!r}")+ return None+ gear = row_gear(popover, hint, quant = GGUF_VARIANT, timeout_ms = QUANT_GEAR_MS) or (+ row_gear(popover, hint)+ )+ if gear is None:+ diagnose("no-row-gear", f"Inference settings for ...{hint}")+ return None+ gear.click()+ for _ in range(40):+ if config_is_open(popover):+ page.wait_for_timeout(CONFIG_SETTLE_MS)+ return popover+ page.wait_for_timeout(250)+ diagnose("config-not-open", 'button[name="Back to model list"]')+ return None++ def context_input(popover):+ for role in ("textbox", "spinbutton"):+ loc = popover.get_by_role(role, name = "Context Length").first+ if _count(loc):+ return loc+ loc = popover.locator('input[aria-label="Context Length"]').first+ return loc if _count(loc) else None++ # ─────────────────────────────────────────────────────+ # Row helpers. The toggle button is the anchor for everything: the header row is its+ # parent, and the breakdown is whatever its aria-controls names -- both stated by the+ # component itself, so neither depends on a class name that a restyle can move.+ # ─────────────────────────────────────────────────────+ ESTIMATE_LABEL = re.compile(r"Estimated Memory Usage", re.I)+ # The run-settings panel exists more than once in this document -- the picker keeps+ # its own copy mounted behind the one on screen -- so a bare `.first` is a coin+ # toss, and the copy it landed on in CI was one the user cannot see: the row was+ # painted, screenshotted, and reported missing for twenty seconds. Take the first+ # match that is actually on screen, and say which strategy found it, because "the+ # row is not there" and "the row is there twice" are the same failure otherwise.+ _match_note: list[str] = []++ def _first_visible(loc, label: str):+ """The first on-screen match of `loc`, or None. Never raises."""+ try:+ total = loc.count()+ except Exception:+ return None+ for i in range(total):+ candidate = loc.nth(i)+ try:+ if candidate.is_visible():+ if label not in _match_note:+ _match_note.append(label)+ info(f"row located by {label} ({total} match(es) in the document)")+ return candidate+ except Exception:+ continue+ return None++ def estimate_button():+ """The visible toggle, by role first and by markup second.++ The role query is the one that carries a claim worth making -- a row a screen+ reader cannot announce is a row that is not there for some users -- so it is+ tried first and its success is recorded. The structural fallback exists because+ this scene must be able to tell "the panel never rendered the row" from "the+ row is unreachable by role", and a single locator that answers no to both+ cannot.+ """+ found = _first_visible(page.get_by_role("button", name = ESTIMATE_LABEL), "role=button")+ if found is not None:+ return found+ return _first_visible(page.locator("button").filter(has_text = ESTIMATE_LABEL), "button+text")++ def estimate_visible() -> bool:+ return estimate_button() is not None++ def wait_for_row(present: bool, timeout_ms: int = ESTIMATE_WAIT_MS) -> bool:+ deadline = time.monotonic() + timeout_ms / 1000+ while time.monotonic() < deadline:+ if estimate_visible() == present:+ return True+ page.wait_for_timeout(200)+ return estimate_visible() == present++ def header_text() -> str:+ button = estimate_button()+ if button is None:+ return ""+ try:+ return (button.locator("xpath=..").inner_text() or "").strip()+ except Exception:+ return ""++ def breakdown_text() -> str:+ button = estimate_button()+ if button is None:+ return ""+ try:+ content_id = button.get_attribute("aria-controls")+ except Exception:+ content_id = None+ if not content_id:+ return ""+ # Attribute selector, not `#id`: React's useId mints ids containing ':', which is+ # not a valid CSS id selector.+ panel = page.locator(f'[id="{content_id}"]').first+ if _count(panel) == 0:+ return ""+ try:+ return (panel.inner_text() or "").strip()+ except Exception:+ return ""++ def wait_for_estimate_post(+ predicate,+ *,+ since: int,+ timeout_ms: int = ESTIMATE_WAIT_MS,+ ):+ """The first recorded exchange at or after `since` matching `predicate`, or None.++ Driven off the recorded transcript rather than `expect_request`, because these+ gates are about WHAT was asked as well as that something was.+ """+ deadline = time.monotonic() + timeout_ms / 1000+ while time.monotonic() < deadline:+ for record in exchanges[since:]:+ if predicate(record):+ return record+ page.wait_for_timeout(200)+ for record in exchanges[since:]:+ if predicate(record):+ return record+ return None++ _used_contexts: set[int] = set()++ def reprice(popover, label: str):+ """Move the Context Length and return `(value, record)` once it has been priced.++ `value` is picked here rather than fixed per step, against what the box is showing+ at this moment: typing the number already displayed is a no-op the panel does not+ re-price (see the note on CTX_CANDIDATES), and the box reveals its number only once+ it has focus, so the choice cannot be made before the click.++ `record` is None when nothing was priced, which every caller reports as its own+ failure rather than carrying on against a stale row.+ """+ box = context_input(popover)+ if box is None:+ fail(f"{label}: the Context Length control is not in the run-settings panel")+ return None, None+ attempted: list[int] = []+ for _try in range(3):+ try:+ box.click()+ page.wait_for_timeout(200)+ shown = box.input_value()+ except Exception as exc:+ fail(f"{label}: could not focus the Context Length control: {exc}")+ return None, None+ try:+ shown_int = int(str(shown).replace(",", "").strip())+ except Exception:+ shown_int = None+ value = next(+ (+ candidate+ for candidate in CTX_CANDIDATES+ if candidate != shown_int+ and candidate not in _used_contexts+ and candidate not in attempted+ ),+ None,+ )+ if value is None:+ fail(+ f"{label}: ran out of Context Length values to type; the control shows "+ f"{shown!r} and {sorted(_used_contexts)} are spent"+ )+ return None, None+ attempted.append(value)+ before = len(exchanges)+ try:+ box.fill(str(value))+ # Commit the draft: a value left focused mid-edit has been seen to stay a+ # draft on the slower engines.+ box.press("Tab")+ except Exception as exc:+ fail(f"{label}: could not type {value} into the Context Length control: {exc}")+ return None, None+ record = wait_for_estimate_post(+ lambda rec: rec["request"].get("n_ctx") == value, since = before+ )+ if record is not None:+ _used_contexts.add(value)+ info(f"{label}: Context Length {shown!r} -> {value}, priced")+ return value, record+ info(+ f"{label}: typing {value} over {shown!r} produced no estimate request; "+ f"retrying with another value"+ )+ fail(+ f"{label}: the panel never re-priced after the Context Length was changed "+ f"(tried {attempted}); every n_ctx asked for so far="+ f"{[r['request'].get('n_ctx') for r in exchanges]!r}"+ )+ return None, None++ # ─────────────────────────────────────────────────────+ # 1. Open the run-settings panel for the GGUF and prove the row is there (HARD).+ # ─────────────────────────────────────────────────────+ step("open run-settings for the GGUF target")+ popover = open_picker()+ shoot("02-picker-open")+ if open_config(popover, MODEL_HINT) is None:+ fail(f"could not open run-settings for a model matching {MODEL_HINT!r}")+ write_transcript()+ shoot("03-config-failed")+ browser.close()+ print(f"[ui-memest] RESULT: FAIL ({len(_failed)} issue(s))", flush = True)+ for m in _failed:+ print(f"[ui-memest] - {m}", flush = True)+ sys.exit(1)+ shoot("03-config-open")++ if not wait_for_row(True):+ fail(+ "the Estimated Memory Usage row never appeared for a GGUF target whose "+ f"estimate was stubbed available (exchanges={len(exchanges)}, "+ f"last={exchanges[-1:]!r})"+ )+ diagnose("row-missing", "button[name=/Estimated Memory Usage/]")+ else:+ info("OK row: Estimated Memory Usage rendered for the GGUF target")+ if "role=button" not in _match_note:+ # Only the structural locator found it, so the toggle is not reachable by+ # role -- an ancestor is hiding it from the accessibility tree, or its+ # accessible name is not what it reads as. Reported rather than gated+ # while it is unproven which; the line above names the strategy that won.+ runtime_warn(+ "the row was found only by markup, not by role=button: a screen "+ "reader would not announce this toggle"+ )++ if not exchanges:+ fail(+ "the panel never called POST /api/inference/estimate-memory, so nothing on "+ "screen can be attributed to the estimate at all"+ )++ # ─────────────────────────────────────────────────────+ # 2. The request carries the load settings, and a changed control re-prices (HARD).+ # ─────────────────────────────────────────────────────+ step("the Context Length on screen reaches the estimate request")+ priced_ctx, priced = reprice(popover, "context reaches the request")+ if priced is not None:+ info(f"OK request: estimate re-priced at n_ctx={priced_ctx}")+ body = priced["request"]+ # The rest of what the panel is supposed to price. Presence, not value: the+ # values are the machine's and the user's, but a request that stopped carrying+ # a field means the estimate has silently stopped answering for that setting.+ required = ("model_path", "n_ctx", "cache_type_kv", "n_parallel", "gpu_memory_mode")+ missing = [key for key in required if key not in body]+ if missing:+ fail(f"the estimate request no longer carries {missing}; body keys={sorted(body)}")+ else:+ info(f"OK request: carries {list(required)}")+ model_path = str(body.get("model_path") or "")+ if MODEL_HINT.lower() not in model_path.lower():+ fail(+ f"the estimate priced {model_path!r}, which is not the model whose run "+ f"settings are open ({MODEL_HINT!r})"+ )+ else:+ info(f"OK request: priced model_path={model_path!r}")+ variant = body.get("gguf_variant")+ if (+ variant is not None+ and GGUF_VARIANT+ and str(variant).strip().lower() != (GGUF_VARIANT.strip().lower())+ ):+ runtime_warn(+ f"the estimate priced quant {variant!r}, not {GGUF_VARIANT!r}; the picker row "+ f"may have collapsed onto a different variant"+ )++ # ─────────────────────────────────────────────────────+ # 3. The stubbed numbers are the ones on screen (HARD).+ # ─────────────────────────────────────────────────────+ step("the row displays the numbers the endpoint returned")+ if not wait_for_row(True):+ fail("the row is gone after the re-price, so its figures cannot be read")+ else:+ head = header_text()+ info(f"row header text: {head!r}")+ # Case-insensitively: the pill is written "Beta" in the source and rendered+ # "BETA" by a CSS `uppercase`, so `inner_text` returns the transformed string and+ # an exact-case check fails on a pill that is right there on screen.+ if not re.search(r"\bbeta\b", head, re.I):+ soft_fail(f"the row lost its Beta pill (header text={head!r})")+ total_gb = _gb(STUB_TOTAL_BYTES)+ gpu_gb = _gb(STUB_GPU_BYTES)+ # The total is shown in BOTH memory topologies: as the sole figure where the GPU+ # and the host share one pool, and beside the GPU share where they do not. The GPU+ # figure only exists in the second, so it is asserted only when its label is there+ # -- a CPU-only runner and an Apple machine legitimately show neither.+ if total_gb not in head:+ fail(+ f"the row does not show the returned total {total_gb!r} "+ f"(total_bytes={STUB_TOTAL_BYTES}); header text={head!r}"+ )+ else:+ info(f"OK figures: total {total_gb} is on screen")+ if re.search(r"\bGPU\b", head):+ if gpu_gb not in head:+ fail(+ f"the row shows a GPU figure but not the returned gpu_bytes {gpu_gb!r}; "+ f"header text={head!r}"+ )+ else:+ info(f"OK figures: GPU {gpu_gb} is on screen")+ else:+ info("single-pool layout: no separate GPU figure to check")+ shoot("04-row-collapsed")++ # Expand: the breakdown is where the per-term figures and the KV note live.+ try:+ expander = estimate_button()+ if expander is None:+ raise RuntimeError("the row is no longer on screen")+ expander.click()+ page.wait_for_timeout(400)+ except Exception as exc:+ fail(f"could not expand the Estimated Memory Usage row: {exc}")+ detail = breakdown_text()+ info(f"row breakdown text: {detail!r}")+ if not detail:+ fail(+ "expanding the row produced no breakdown panel (the button's aria-controls "+ "names nothing on the page)"+ )+ else:+ for label, value in (+ ("Weights", _gb(STUB_WEIGHTS_BYTES)),+ ("KV cache", _gb(STUB_KV_BYTES)),+ ("Compute buffers", _gb(STUB_COMPUTE_BYTES)),+ ):+ if label not in detail:+ fail(f"the breakdown has no {label!r} line; text={detail!r}")+ elif value not in detail:+ fail(+ f"the {label!r} line does not show the returned {value!r}; "+ f"text={detail!r}"+ )+ else:+ info(f"OK breakdown: {label} = {value}")+ # The KV note is assembled from the RESPONSE's context and cache dtype, and the+ # stub echoes the request's. So this one string closes the loop: the number+ # typed into the control reached the request, came back in the response, and+ # was rendered.+ if priced is not None and priced_ctx is not None:+ echoed = f"{priced_ctx:,} tokens"+ if echoed not in detail:+ fail(+ f"the KV note does not quote the priced context {echoed!r}, so the "+ f"response's n_ctx is not what the row is displaying; text={detail!r}"+ )+ else:+ info(f"OK round trip: the KV note quotes {echoed}")+ layers_note = f"{STUB_GPU_LAYERS} of {STUB_LAYER_COUNT + 1} layers on GPU"+ if layers_note not in detail:+ runtime_warn(+ f"the Weights line does not carry the placement note {layers_note!r}; "+ f"text={detail!r}"+ )+ else:+ info(f"OK breakdown: placement note {layers_note!r}")+ shoot("05-row-expanded")++ # ─────────────────────────────────────────────────────+ # 4. An unavailable estimate HIDES the row (HARD).+ # ─────────────────────────────────────────────────────+ step("available:false hides the row")+ _mode[0] = "unavailable"+ _unavailable_ctx, unavailable_record = reprice(popover, "available:false hides the row")+ if unavailable_record is not None and unavailable_record["mode"] != "unavailable":+ fail(+ "the re-price was served before the endpoint was switched to unavailable, so "+ "the hide below would be measuring the wrong response"+ )+ if wait_for_row(False):+ info("OK hide: available:false removed the row")+ else:+ fail(+ "the row is still on screen after the estimate came back available:false; "+ f"header={header_text()!r}"+ )+ shoot("06-unavailable")++ # ─────────────────────────────────────────────────────+ # 5. Restoring the available response brings the row BACK (HARD).+ # Without this the hide gate above is satisfied by a panel that simply died.+ # ─────────────────────────────────────────────────────+ step("restoring an available estimate brings the row back")+ _mode[0] = "available"+ restored_ctx, restored = reprice(popover, "restoring brings the row back")+ if restored is not None and restored["mode"] != "available":+ fail(+ "the restoring re-price was served before the endpoint was switched back, so "+ "the row coming back below would not be attributable to it"+ )+ if wait_for_row(True):+ head = header_text()+ if _gb(STUB_TOTAL_BYTES) in head:+ info("OK restore: the row came back with the returned total")+ else:+ fail(f"the row came back without the returned total; header={head!r}")+ detail = breakdown_text()+ echoed = f"{restored_ctx:,} tokens" if restored_ctx is not None else ""+ if detail and echoed and echoed not in detail:+ soft_fail(+ f"the restored row still quotes an older context; expected {echoed!r} in "+ f"{detail!r}"+ )+ else:+ fail(+ "the row did not come back once the estimate was available again, so the hide "+ "gate above proves nothing about the response and everything about the panel"+ )+ shoot("07-restored")++ # ─────────────────────────────────────────────────────+ # 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.+ #+ # 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.+ # ─────────────────────────────────────────────────────+ step("HTTP 404 hides the row")+ _mode[0] = "http404"+ _not_found_ctx, not_found_record = reprice(popover, "404 hides the row")+ if not_found_record is not None and not_found_record["mode"] != "http404":+ fail(+ "the re-price was served before the endpoint was switched to 404, so the hide "+ "below would be measuring the wrong response"+ )+ if wait_for_row(False):+ info("OK hide: a 404 removed the row rather than surfacing an error")+ else:+ fail(f"the row survived a 404 from the estimate endpoint; header={header_text()!r}")+ if page_errors:+ fail(f"a 404 estimate produced page errors instead of a hidden row: {page_errors[:3]!r}")+ shoot("08-http404")++ close_picker()++ if page_errors:+ fail(f"page errors during run: {page_errors[:3]!r}")++ write_transcript()+ browser.close()++if _failed:+ print(f"[ui-memest] RESULT: FAIL ({len(_failed)} issue(s))", flush = True)+ for m in _failed:+ print(f"[ui-memest] - {m}", flush = True)+ sys.exit(1)+print(f"[ui-memest] RESULT: PASS ({len(exchanges)} estimate exchange(s) recorded)", flush = True)+sys.exit(0)diff --git a/tests/studio/test_pip_cache_naming.py b/tests/studio/test_pip_cache_naming.pyindex a4c1d2bcaa2..c1f5482ca18 100644--- a/tests/studio/test_pip_cache_naming.py+++ b/tests/studio/test_pip_cache_naming.py@@ -32,7 +32,7 @@ SAVE_SUFFIX = "actions/pip-cache-save"def _jobs(path):- doc = yaml.safe_load(path.read_text()) or {}+ doc = yaml.safe_load(path.read_text(encoding = "utf-8")) or {}for name, job in (doc.get("jobs") or {}).items():yield name, (job.get("steps") or [])@@ -107,7 +107,7 @@ def test_jobs_sharing_key_files_still_have_distinct_names():def test_key_is_versioned_and_carries_the_name():- action = (REPO / ".github/actions/pip-cache-restore/action.yml").read_text()+ action = (REPO / ".github/actions/pip-cache-restore/action.yml").read_text(encoding = "utf-8")assert 'prefix="pip-v2-${name}-' in action, ("the key must stay pip-v2-<name>-... . The v2 segment is what lets ""cache-janitor.yml match only post-rename keys: 'Linux' is a valid name, so "@@ -116,7 +116,7 @@ def test_key_is_versioned_and_carries_the_name():def test_janitor_matches_v2_keys_only():- janitor = (REPO / ".github/workflows/cache-janitor.yml").read_text()+ janitor = (REPO / ".github/workflows/cache-janitor.yml").read_text(encoding = "utf-8")assert ("pip-v2-*|uv-*|fe-dist-*)" in janitor), "janitor no longer ranks the pip/uv/fe-dist families"@@ -127,7 +127,9 @@ def test_janitor_matches_v2_keys_only():def test_save_runs_on_the_default_branch_only():- action = yaml.safe_load((REPO / ".github/actions/pip-cache-save/action.yml").read_text())+ action = yaml.safe_load(+ (REPO / ".github/actions/pip-cache-save/action.yml").read_text(encoding = "utf-8")+ )condition = " ".join(str(action["runs"]["steps"][0].get("if", "")).split())assert "github.ref == 'refs/heads/main'" in conditionassert "always()" in condition