Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: consolidate the two memory-estimate stacks (#9830)
Daniel Han14d4fb3c174e
diff --git a/studio/backend/core/inference/memory_contract.py b/studio/backend/core/inference/memory_contract.pynew file mode 100644index 00000000000..7a6d4a7ea10--- /dev/null+++ b/studio/backend/core/inference/memory_contract.py@@ -0,0 +1,259 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""One canonical memory estimate, and the two legacy shapes projected from it.++Studio answers "how much memory would this load take" on two routes:++* ``POST /api/inference/estimate-memory`` -- the Load Model panel+* ``GET /api/models/kv-cache-estimate`` -- the Hub memory bar++They already share the ``_gguf_memory_breakdown`` planner, so the arithmetic+cannot drift. What used to drift is everything around it, and the sharp edge is+that ``weights_bytes`` exists on both, is an ``int`` on both, and means+different things: every resident file on the inference route, the quant file+alone on the models route. Nothing in the type system separates those, so a+caller reading the wrong one is simply wrong, quietly.++This module is the fix. :func:`build_memory_estimate` turns a planner breakdown+into the canonical :class:`MemoryEstimate`, whose two unambiguous fields replace+that one ambiguous one. The two ``project_*`` functions then map the canonical+model back onto each route's existing wire shape, byte for byte, so no client+sees a change. The legacy meaning of ``weights_bytes`` is applied in exactly one+place per route, right here, where the two sit next to each other and the+difference is impossible to miss.++Everything here is pure: no I/O, no probing, no network. The planner does that+work; this only renames and reshapes what it returned.+"""++from __future__ import annotations++from typing import Any, Optional++from models.inference import MemoryEstimate++__all__ = [+ "EMPTY_BREAKDOWN",+ "build_memory_estimate",+ "project_estimate_memory_response",+ "project_kv_cache_estimate",+]+++class _EmptyBreakdown:+ """Stands in for a planner run that did not happen.++ Every attribute is absent, so :func:`build_memory_estimate`'s ``getattr``+ defaults apply and the planner-derived fields come back at their "not+ computed" values. ``gpu_bytes`` in particular resolves to ``None`` rather+ than ``0``, which is the distinction that matters: never ran, as opposed to+ ran and found nothing on the card.++ A class rather than ``None`` so callers have one object to pass and the+ projection stays total, instead of every call site growing its own branch.+ """++ __slots__ = ()++ def __repr__(self) -> str: # pragma: no cover - debugging aid+ return "<EMPTY_BREAKDOWN>"+++EMPTY_BREAKDOWN = _EmptyBreakdown()+++class _Unset:+ """Distinguishes "not overridden" from an override whose value is None.++ ``gpu_bytes`` needs all three states -- a number, a real ``None`` meaning the+ planner never ran, and "take whatever the breakdown had" -- and ``None``+ cannot carry the third.+ """++ __slots__ = ()++ def __bool__(self) -> bool: # pragma: no cover - defensive+ return False+++_UNSET = _Unset()+++def build_memory_estimate(+ breakdown: Any,+ *,+ quant_file_bytes: int,+ native_context: Optional[int] = None,+ gpu_floor_bytes: Optional[int] = None,+ context_is_pinned: bool = True,+ inherited_device_pin: bool = False,+ spec_unpriced: bool = False,+ moe_offload_unmodelled: bool = False,+ gpu_bytes: Any = _UNSET,+ compute_bytes: Any = _UNSET,+ total_bytes: Any = _UNSET,+ n_ctx: Any = _UNSET,+) -> MemoryEstimate:+ """Normalize a planner breakdown into the canonical estimate.++ *breakdown* is a ``_GgufMemoryBreakdown``, taken structurally rather than by+ import so this module does not depend on a route module. Its own+ ``weights_bytes`` field carries the RESIDENT-FILES meaning, which is why it+ lands in ``resident_files_bytes`` and never in ``quant_file_bytes``.++ *quant_file_bytes* has to be supplied by the caller because the planner does+ not carry it: the planner is given a resolved config and reports what the+ launch would hold, while the size of the one file the user picked is known+ only to whatever resolved that file. Callers that genuinely do not know it+ should pass 0 rather than the resident total, since a wrong number here is+ exactly the confusion this module exists to end.++ The four trailing overrides exist because ``/kv-cache-estimate`` derives those+ figures from its own planner calls, with its own None handling, and they are+ not the breakdown's. They are passed IN rather than assigned onto the returned+ model afterwards: Pydantic does not validate assignment by default, so+ mutating the model post-construction puts whatever it is handed straight onto+ the wire. Measured, not assumed -- ``m.gpu_bytes = "not an int"`` succeeds on+ pydantic 2.13, and so does setting a declared ``int`` field to ``None``.+ """+ resident = int(getattr(breakdown, "weights_bytes", 0) or 0)+ quant = int(quant_file_bytes or 0)+ # Deliberately NOT clamped against `resident`, though the quant file is by+ # definition one of the resident files and so cannot really be larger.+ #+ # The two figures do not come from the same place. `resident` is what the+ # planner measured from the files it opened; `quant` is what resolved the+ # user's chosen file, which may be a listing size or a stat of a different+ # path. They agree in production and diverge whenever anything stubs one+ # side, and a clamp there does not catch a bug -- it silently replaces the+ # caller's real number with an unrelated one. The first draft of this+ # function clamped, and the contract-freeze suite caught it truncating a+ # 4.1 GB quant to 373 bytes.+ return MemoryEstimate(+ available = True,+ reason = None,+ quant_file_bytes = quant,+ resident_files_bytes = resident,+ kv_bytes = int(getattr(breakdown, "kv_bytes", 0) or 0),+ compute_bytes = (+ int(getattr(breakdown, "compute_bytes", 0) or 0)+ if isinstance(compute_bytes, _Unset)+ else int(compute_bytes or 0)+ ),+ drafter_runtime_bytes = int(getattr(breakdown, "drafter_runtime_bytes", 0) or 0),+ drafter_runtime_gpu_bytes = int(getattr(breakdown, "drafter_runtime_gpu_bytes", 0) or 0),+ projector_runtime_bytes = int(getattr(breakdown, "projector_runtime_bytes", 0) or 0),+ drafter_kv_unsized = bool(getattr(breakdown, "drafter_kv_unsized", False)),+ adapters_unsized = bool(getattr(breakdown, "adapters_unsized", False)),+ total_bytes = (+ int(getattr(breakdown, "total_bytes", 0) or 0)+ if isinstance(total_bytes, _Unset)+ else int(total_bytes or 0)+ ),+ # Not `or 0`: zero is a real answer (an all-CPU launch) and must survive+ # distinct from None. See the field's own description.+ gpu_bytes = (+ (None if getattr(breakdown, "gpu_bytes", None) is None else int(breakdown.gpu_bytes))+ if isinstance(gpu_bytes, _Unset)+ else (None if gpu_bytes is None else int(gpu_bytes))+ ),+ gpu_floor_bytes = None if gpu_floor_bytes is None else int(gpu_floor_bytes),+ kv_estimable = bool(getattr(breakdown, "kv_estimable", True)),+ kv_on_gpu = bool(getattr(breakdown, "kv_on_gpu", True)),+ n_ctx = (+ int(getattr(breakdown, "n_ctx", 0) or 0)+ if isinstance(n_ctx, _Unset)+ else int(n_ctx or 0)+ ),+ native_context = native_context,+ cache_type_kv = getattr(breakdown, "cache_type_kv", None),+ n_parallel = int(getattr(breakdown, "n_parallel", 1) or 1),+ layer_count = getattr(breakdown, "layer_count", None),+ gpu_layers = getattr(breakdown, "gpu_layers", None),+ moe_offload_unmodelled = bool(moe_offload_unmodelled),+ context_is_pinned = bool(context_is_pinned),+ inherited_device_pin = bool(inherited_device_pin),+ spec_unpriced = bool(spec_unpriced),+ )+++def project_estimate_memory_response(estimate: MemoryEstimate) -> dict:+ """The ``EstimateMemoryResponse`` shape, for ``POST /estimate-memory``.++ ``weights_bytes`` here is the RESIDENT-FILES total, which is what this route+ has always meant by it and what the Load Model panel itemizes against.+ """+ return {+ "available": estimate.available,+ "reason": estimate.reason,+ # The aggregate meaning. See the module docstring.+ "weights_bytes": estimate.resident_files_bytes,+ "kv_bytes": estimate.kv_bytes,+ "compute_bytes": estimate.compute_bytes,+ "drafter_runtime_bytes": estimate.drafter_runtime_bytes,+ "drafter_runtime_gpu_bytes": estimate.drafter_runtime_gpu_bytes,+ "projector_runtime_bytes": estimate.projector_runtime_bytes,+ "drafter_kv_unsized": estimate.drafter_kv_unsized,+ "adapters_unsized": estimate.adapters_unsized,+ "total_bytes": estimate.total_bytes,+ "gpu_bytes": estimate.gpu_bytes or 0,+ "kv_estimable": estimate.kv_estimable,+ "kv_on_gpu": estimate.kv_on_gpu,+ "n_ctx": estimate.n_ctx,+ "cache_type_kv": estimate.cache_type_kv,+ "n_parallel": estimate.n_parallel,+ "layer_count": estimate.layer_count,+ "gpu_layers": estimate.gpu_layers,+ "moe_offload_unmodelled": estimate.moe_offload_unmodelled,+ }+++def project_kv_cache_estimate(+ estimate: MemoryEstimate,+ *,+ kv_bytes: Optional[int] = None,+ spec_bytes: Optional[int] = None,+ spec_fixed_bytes: Optional[int] = None,+ projector_bytes: Optional[int] = None,+ kv_checkpoint_bytes: Optional[int] = None,+) -> dict:+ """The ``GET /kv-cache-estimate`` shape, for the Hub memory bar.++ ``weights_bytes`` here is the QUANT FILE ALONE, which is what this route has+ always meant by it: the bar draws its weights segment from this and prints it+ beside the download size on the same row, so folding the projector or a+ drafter in would make the two disagree on screen.++ The keyword terms are this route's OWN itemization, computed by the route+ rather than by the planner, so they are passed through instead of derived+ here. ``kv_bytes`` is among them deliberately: this route prices the target+ cache itself and its figure is not interchangeable with the planner's.+ Reaching into the estimate for it would silently swap one for the other.++ ``None`` is meaningful throughout and is preserved -- this route uses ``None``+ for "no such term", never ``0``, and the frontend's ``estimateIsUnsized()``+ distinguishes them.++ The one field where ``None`` and ``0`` differ in the OTHER direction is+ ``gpu_bytes``, which is passed straight through: see its field description.+ """+ return {+ # The quant-file meaning. See the module docstring.+ "weights_bytes": estimate.quant_file_bytes or None,+ "kv_bytes": kv_bytes or None,+ "native_context": estimate.native_context,+ "spec_bytes": spec_bytes,+ "n_ctx": estimate.n_ctx,+ "projector_bytes": projector_bytes,+ "kv_checkpoint_bytes": kv_checkpoint_bytes,+ "spec_fixed_bytes": spec_fixed_bytes,+ # Deliberately NOT `or None`. Zero means an all-CPU launch.+ "gpu_bytes": estimate.gpu_bytes,+ "compute_bytes": estimate.compute_bytes or None,+ "total_bytes": estimate.total_bytes or None,+ "gpu_floor_bytes": estimate.gpu_floor_bytes,+ "context_is_pinned": estimate.context_is_pinned,+ "inherited_device_pin": estimate.inherited_device_pin,+ "spec_unpriced": estimate.spec_unpriced,+ }diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.pyindex 4dbe3bb2cdd..2b1d1bf0239 100644--- a/studio/backend/models/inference.py+++ b/studio/backend/models/inference.py@@ -870,6 +870,111 @@ class EstimateMemoryResponse(BaseModel):)+class MemoryEstimate(BaseModel):+ """The canonical answer to "what would this load occupy".++ Studio grew two routes that answer this -- ``POST /inference/estimate-memory``+ for the Load Model panel and ``GET /models/kv-cache-estimate`` for the Hub+ memory bar. They share the ``_gguf_memory_breakdown`` planner, so their+ arithmetic already agrees; this is the shared CONTRACT, so their vocabulary+ agrees too. Both legacy routes are projections of this model and keep their+ own shapes exactly.++ The one thing this model deliberately does not have is a field called+ ``weights_bytes``. That name means different things on the two legacy routes+ -- every resident file on one, the quant file alone on the other -- and it is+ the same type on both, so nothing catches a caller reading the wrong one.+ It is replaced here by two fields that each say which they are, and it is+ absent rather than redefined so that no future reader can pick it up and+ guess. See ``core/inference/memory_contract.py`` for the projections.+ """++ 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'.",+ )++ # --- the two meanings that used to collide under `weights_bytes` ---+ quant_file_bytes: int = Field(+ 0,+ description = "The selected GGUF quant file ALONE, as it sits on disk. This is "+ "the figure a download size or a weights segment should be drawn from, because "+ "it is the number the user already saw beside the model.",+ )+ resident_files_bytes: int = Field(+ 0,+ description = "Every file this launch makes resident: the quant file PLUS "+ "whichever projector and drafter it opens. Always >= quant_file_bytes. This is "+ "the figure an itemized footprint should be drawn from.",+ )++ 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"+ )+ drafter_runtime_gpu_bytes: int = Field(+ 0, description = "The share of drafter_runtime_bytes that lands on the GPU"+ )+ projector_runtime_bytes: int = Field(+ 0, description = "The vision encoder's buffers, on top of the projector file"+ )+ drafter_kv_unsized: bool = Field(+ False, description = "A charged drafter's cache could not be sized, so totals are a floor"+ )+ adapters_unsized: bool = Field(+ False, description = "A pass-through adapter could not be stat'd, so totals are a floor"+ )++ total_bytes: int = Field(0, description = "Weights + KV + compute, wherever they land")+ gpu_bytes: Optional[int] = Field(+ None,+ description = "The share of total_bytes that lands on the GPU. Optional because "+ "None and 0 are DIFFERENT answers here: None is 'the planner did not run', while "+ "0 is 'this launch puts nothing on the card', which inherited placement such as "+ "LLAMA_ARG_DEVICE=none really does produce. Collapsing the two sends a caller "+ "back to summing segments and drawing VRAM pressure for a load that touches no "+ "card at all.",+ )+ gpu_floor_bytes: Optional[int] = Field(+ None,+ description = "What still lands on the GPU at the SHORTEST context: drafter "+ "weights, flat compute buffers, recurrent rollback state. None of it shrinks "+ "when the context does, so it separates an overage a shorter context fixes from "+ "one it cannot. None when it was not computed.",+ )++ kv_estimable: bool = Field(True, description = "False when the header could not size the cache")+ kv_on_gpu: bool = Field(True, description = "Whether the target cache sits on the GPU")+ n_ctx: int = Field(0, description = "Context length the estimate actually priced")+ native_context: Optional[int] = Field(+ None, description = "The model's own trained context length, when readable"+ )+ cache_type_kv: Optional[str] = Field(None, description = "KV cache dtype the estimate priced")+ 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 placed on the GPU, when known")+ moe_offload_unmodelled: bool = Field(+ False, description = "--n-cpu-moe is set, so the GPU figure reads high"+ )+ context_is_pinned: bool = Field(+ True,+ description = "False only when the loader is free to shrink the context. A caller "+ "that softens its verdict for an auto-fitted row has to stop softening here.",+ )+ inherited_device_pin: bool = Field(+ False,+ description = "An inherited LLAMA_ARG_DEVICE confines the launch to the cards it "+ "names, so a budget aggregated over the visible inventory describes a pool the "+ "launch will not open.",+ )+ spec_unpriced: bool = Field(+ False, description = "A speculative term was charged that could not be sized"+ )++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 a3140d65212..73eccf62a21 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -67,6 +67,10 @@ from core.inference.context_window import (estimate_messages_tokens_dense,truncate_oldest_messages as _truncate_oldest_messages,)+from core.inference.memory_contract import (+ build_memory_estimate,+ project_estimate_memory_response,+)from core.inference.stream_errors import LlamaStreamErrorfrom core.inference.orchestrator import (AUDIO_GENERATION_MAX_TOKENS,@@ -13905,25 +13909,20 @@ async def estimate_memory()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,+ # Shaped through the canonical MemoryEstimate, the same one+ # GET /models/kv-cache-estimate goes through, so the two routes cannot+ # drift apart in vocabulary. The projection is what preserves THIS+ # route's meaning of weights_bytes -- every resident file, not the quant+ # file alone. Both mappings live together in+ # core/inference/memory_contract.py.+ estimate = build_memory_estimate(+ breakdown,+ # Not known here, and 0 rather than a stand-in: this route is given a+ # resolved config and prices what the launch would hold, so nothing+ # in it measured the single file the user picked. The legacy shape+ # below does not carry the field, and inventing a value would put a+ # wrong number on the canonical route for the sake of a non-null.+ quant_file_bytes = 0,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@@ -13936,6 +13935,7 @@ async def estimate_memory()),)+ return EstimateMemoryResponse(**project_estimate_memory_response(estimate))# Header walks and file stats are blocking; keep them off the event loop so a# slider drag cannot stall streaming chats.diff --git a/studio/backend/routes/models.py b/studio/backend/routes/models.pyindex 431de8ea54e..e4434546b64 100644--- a/studio/backend/routes/models.py+++ b/studio/backend/routes/models.py@@ -20,6 +20,11 @@ from typing import List, NamedTuple, Optionalfrom loggers import get_logger# Dependency-light leaf (PEP 562 package init): no llama.cpp / torch import chain.+from core.inference.memory_contract import (+ EMPTY_BREAKDOWN,+ build_memory_estimate,+ project_kv_cache_estimate,+)from core.inference.model_ids import display_model_namefrom hub.services.models import catalog_classification as _catalog_classificationfrom utils import gguf_archs as _gguf_archs@@ -4192,6 +4197,12 @@ async def get_kv_cache_estimate(planner_total = Noneplanner_floor = Noneplanner_unsized = False+ # Bound BEFORE the try, not inside it. Every statement below can+ # raise into the surrounding `except`, and a name defined only on the+ # success path then reads as a NameError from the projection after+ # it -- which this same route has already been bitten by once, in a+ # guard that silently never ran because of it.+ _b = Nonetry:from routes.inference import (_ESTIMATE_NOT_ON_DISK,@@ -4293,34 +4304,30 @@ async def get_kv_cache_estimate(except Exception as e:logger.debug(f"planner breakdown failed for '{repo_id}' {quant}: {e}")- return {- "kv_bytes": int(kv) if kv else None,- "weights_bytes": weights_bytes or None,- "native_context": be._context_length,- "spec_bytes": int(spec) if spec else None,- "n_ctx": int(n_ctx),- "projector_bytes": projector or None,- # The part of kv_bytes that llama.cpp keeps in host heap rather than- # on the card, so a VRAM bar can subtract it. Included in kv_bytes,- # not beside it: the field shipped meaning the whole cache and an- # existing caller still reads it that way.- "kv_checkpoint_bytes": kv_checkpoint or None,- # The part of spec_bytes a shorter context cannot reduce.- "spec_fixed_bytes": spec_fixed if spec else None,- # The load planner's figures. gpu_bytes is the complete footprint- # that lands on the card and is what a fit verdict should be drawn- # against; the rest are itemized for the caller that wants them.- "gpu_bytes": planner_gpu,- "compute_bytes": planner_compute,- "total_bytes": planner_total,+ # Shaped through the canonical MemoryEstimate rather than assembled+ # here, so this route and POST /inference/estimate-memory cannot drift+ # apart in vocabulary the way they had. The projection is what keeps+ # this route's own meaning of `weights_bytes` -- the quant file ALONE+ # -- while the panel's projection keeps its aggregate meaning. The two+ # sit side by side in core/inference/memory_contract.py, which is the+ # only place either mapping is written down.+ #+ # The terms this route prices ITSELF (the target cache, the+ # speculative split, the projector, the checkpoint share) are passed+ # in rather than read off the estimate: the planner has its own+ # figures for some of them and they are not interchangeable.+ _estimate = build_memory_estimate(+ _b if _b is not None else EMPTY_BREAKDOWN,+ quant_file_bytes = weights_bytes or 0,+ native_context = be._context_length,# What remains on the card at the shortest context, so a caller# can tell a context-driven overage from one no context fixes.- "gpu_floor_bytes": planner_floor,+ gpu_floor_bytes = planner_floor,# False only when the loader is free to shrink the context. A# caller that softens its verdict for an auto-fitted row has to# stop softening here, or an inherited window over budget reads# as a fit for a launch that will OOM.- "context_is_pinned": _context_is_pinned,+ context_is_pinned = _context_is_pinned,# An inherited LLAMA_ARG_DEVICE confines the child to the cards it# names, and an automatic launch preserves it. The caller's budget# is an aggregate over the whole visible inventory, which then@@ -4329,11 +4336,34 @@ async def get_kv_cache_estimate(# caller cannot see the environment, so it is reported here.# Any pin at all is enough to say so: the route does not know the# host's inventory, and abstaining is the safe direction.- "inherited_device_pin": _inherited_device_pin,+ inherited_device_pin = _inherited_device_pin,# The planner saw a drafter whose cache it could not size, so its# own total is a floor.- "spec_unpriced": spec_unpriced or planner_unsized,- }+ spec_unpriced = spec_unpriced or planner_unsized,+ # The planner's own figures, kept exactly as this route computed+ # them above: planner_gpu preserves a real zero, the other two do+ # not. Passed in rather than assigned onto the model afterwards,+ # because Pydantic does not validate assignment by default and a+ # post-construction write puts whatever it is handed straight+ # onto the wire.+ gpu_bytes = planner_gpu,+ compute_bytes = planner_compute,+ total_bytes = planner_total,+ n_ctx = int(n_ctx),+ )+ return project_kv_cache_estimate(+ _estimate,+ kv_bytes = int(kv) if kv else None,+ spec_bytes = int(spec) if spec else None,+ # The part of spec_bytes a shorter context cannot reduce.+ spec_fixed_bytes = spec_fixed if spec else None,+ projector_bytes = projector or None,+ # The part of kv_bytes that llama.cpp keeps in host heap rather+ # than on the card, so a VRAM bar can subtract it. Included in+ # kv_bytes, not beside it: the field shipped meaning the whole+ # cache and an existing caller still reads it that way.+ kv_checkpoint_bytes = kv_checkpoint or None,+ )except Exception as e:logger.debug(f"kv-cache-estimate failed for '{repo_id}' {quant}: {e}")return nulldiff --git a/studio/backend/tests/test_memory_contract.py b/studio/backend/tests/test_memory_contract.pynew file mode 100644index 00000000000..3f24e73625c--- /dev/null+++ b/studio/backend/tests/test_memory_contract.py@@ -0,0 +1,293 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""The canonical MemoryEstimate and the two legacy shapes projected from it.++``test_memory_estimate_contract_freeze.py`` pins what the two ROUTES emit today.+This file pins the shared layer they are being moved onto: that the canonical+model separates the two meanings ``weights_bytes`` used to carry, and that each+projection puts the right one back on the wire.++The single most important assertion here is+``test_the_two_projections_disagree_about_weights_bytes``. The whole point of+routing both surfaces through one model is that their arithmetic cannot drift;+the whole point of projecting back out is that their CONTRACTS still differ+where they always did. Getting the first without the second is a silent+regression for every existing caller of one route.++Pure functions, no I/O.+"""++import sys+from pathlib import Path+from types import SimpleNamespace++_TESTS_DIR = str(Path(__file__).resolve().parent)+if _TESTS_DIR not in sys.path:+ sys.path.insert(0, _TESTS_DIR)++_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)+if _BACKEND_DIR not in sys.path:+ sys.path.insert(0, _BACKEND_DIR)++# Imported for its side effects: installs the process-wide loggers/structlog/httpx+# stubs that models.inference needs on a runner without the real packages. Same+# pattern as test_kv_cache_estimate_route.py.+import test_kv_cache_estimation # noqa: E402,F401++import pytest # noqa: E402++from core.inference.memory_contract import ( # noqa: E402+ build_memory_estimate,+ project_estimate_memory_response,+ project_kv_cache_estimate,+)++# A planner breakdown where every term is a distinct number, so a projection+# that reads the wrong field cannot coincidentally look right.+_BREAKDOWN = SimpleNamespace(+ weights_bytes = 5_000_000_000, # resident: quant + projector + drafter+ kv_bytes = 3_000_000_000,+ compute_bytes = 700_000_000,+ drafter_runtime_bytes = 400_000_000,+ drafter_runtime_gpu_bytes = 250_000_000,+ projector_runtime_bytes = 120_000_000,+ drafter_kv_unsized = False,+ adapters_unsized = False,+ total_bytes = 8_700_000_000,+ gpu_bytes = 8_100_000_000,+ kv_estimable = True,+ kv_on_gpu = True,+ n_ctx = 32768,+ cache_type_kv = "f16",+ n_parallel = 4,+ layer_count = 28,+ gpu_layers = 28,+)++# The quant file alone: strictly smaller than the resident total above, which is+# the relationship the two fields exist to express.+_QUANT_FILE_BYTES = 4_100_000_000+++def estimate():+ return build_memory_estimate(+ _BREAKDOWN,+ quant_file_bytes = _QUANT_FILE_BYTES,+ native_context = 131072,+ gpu_floor_bytes = 900_000_000,+ context_is_pinned = False,+ inherited_device_pin = True,+ spec_unpriced = True,+ )+++class TestTheCanonicalModel:+ def test_the_ambiguous_name_is_gone(self, estimate):+ # Absent rather than redefined: a field named weights_bytes on the shared+ # model would be picked up and guessed at by exactly the readers this+ # separation exists to protect.+ assert not hasattr(estimate, "weights_bytes"), (+ "MemoryEstimate has grown a weights_bytes field. That name means two "+ "different things on the two legacy routes and belongs on neither the "+ "shared model nor any new caller."+ )++ def test_the_two_meanings_are_separate_and_ordered(self, estimate):+ assert estimate.quant_file_bytes == _QUANT_FILE_BYTES+ assert estimate.resident_files_bytes == _BREAKDOWN.weights_bytes+ # The quant file is one of the resident files, so this ordering is a+ # property of the model rather than of this fixture.+ assert estimate.quant_file_bytes < estimate.resident_files_bytes++ def test_the_planner_weights_field_is_the_resident_meaning(self, estimate):+ # The planner's own field name is weights_bytes and it carries the+ # AGGREGATE. Mapping it to quant_file_bytes would be the easy mistake.+ assert estimate.resident_files_bytes == _BREAKDOWN.weights_bytes+ assert estimate.quant_file_bytes != _BREAKDOWN.weights_bytes++ def test_the_two_figures_are_reported_as_given(self):+ """Neither figure is adjusted to make the other look consistent.++ The quant file is by definition one of the resident files, so a quant+ larger than the resident total is impossible in production. It is still+ reported unchanged, because the two numbers come from different places+ and "fixing" one against the other replaces a caller's real value with+ an unrelated one rather than catching anything. An earlier draft clamped+ here and truncated a 4.1 GB quant to a 373 byte synthetic header.+ """+ out = build_memory_estimate(_BREAKDOWN, quant_file_bytes = 9_999_999_999)+ assert out.quant_file_bytes == 9_999_999_999+ assert out.resident_files_bytes == _BREAKDOWN.weights_bytes++ def test_optional_terms_default_without_being_invented(self):+ out = build_memory_estimate(_BREAKDOWN, quant_file_bytes = _QUANT_FILE_BYTES)+ # None means "not computed" and must not become 0, which is a real value+ # meaning "nothing is pinned to the card at the shortest context".+ assert out.gpu_floor_bytes is None+ assert out.native_context is None+++class TestTheRouteOverrides:+ """The figures /kv-cache-estimate computes itself, passed in not assigned on."""++ def test_gpu_bytes_carries_three_distinct_states(self):+ # A number, a real None (planner never ran), and "use the breakdown's".+ # None cannot express the third, which is why there is a sentinel.+ assert build_memory_estimate(_BREAKDOWN, quant_file_bytes = 1, gpu_bytes = 0).gpu_bytes == 0+ assert (+ build_memory_estimate(_BREAKDOWN, quant_file_bytes = 1, gpu_bytes = None).gpu_bytes is None+ )+ # Omitted entirely: falls through to whatever the breakdown had.+ assert (+ build_memory_estimate(_BREAKDOWN, quant_file_bytes = 1).gpu_bytes == _BREAKDOWN.gpu_bytes+ )++ def test_the_other_overrides_apply(self):+ out = build_memory_estimate(+ _BREAKDOWN,+ quant_file_bytes = 1,+ compute_bytes = 11,+ total_bytes = 22,+ n_ctx = 33,+ )+ assert (out.compute_bytes, out.total_bytes, out.n_ctx) == (11, 22, 33)+ # And None collapses to 0 for the three that are declared non-optional,+ # matching what the route's `or None` handling produced before.+ none_out = build_memory_estimate(+ _BREAKDOWN,+ quant_file_bytes = 1,+ compute_bytes = None,+ total_bytes = None,+ n_ctx = None,+ )+ assert (none_out.compute_bytes, none_out.total_bytes, none_out.n_ctx) == (0, 0, 0)++ def test_the_route_does_not_mutate_the_model_after_building_it(self):+ """Pydantic does not validate assignment, so a post-build write is unchecked.++ Measured rather than assumed: on pydantic 2.13,+ ``m.gpu_bytes = "not an int"`` succeeds and puts that string on the wire,+ and a declared ``int`` field accepts None the same way. The route used to+ assign these four fields after construction; this pins that it does not+ go back to doing so.+ """+ from pathlib import Path++ source = (Path(__file__).resolve().parent.parent / "routes" / "models.py").read_text()+ for field in ("gpu_bytes", "compute_bytes", "total_bytes", "n_ctx"):+ assert f"_estimate.{field} =" not in source, (+ f"routes/models.py assigns {field} onto a built MemoryEstimate. "+ "Pass it to build_memory_estimate instead; assignment skips "+ "validation entirely."+ )++ def test_assignment_really_is_unvalidated(self):+ # The premise of the guard above. If a future pydantic or a model_config+ # change makes assignment validate, this fails and the guard can relax.+ from models.inference import MemoryEstimate++ m = MemoryEstimate(available = True)+ m.gpu_bytes = "not an int"+ assert m.gpu_bytes == "not an int", (+ "assignment now validates; the no-mutation guard above is no longer "+ "load-bearing and its comment should be updated"+ )+++class TestTheLegacyProjections:+ def test_estimate_memory_gets_the_resident_total(self, estimate):+ out = project_estimate_memory_response(estimate)+ assert (+ out["weights_bytes"] == _BREAKDOWN.weights_bytes+ ), "the Load Model panel itemizes weights_bytes as every resident file"++ def test_kv_cache_estimate_gets_the_quant_file(self, estimate):+ out = project_kv_cache_estimate(estimate)+ assert out["weights_bytes"] == _QUANT_FILE_BYTES, (+ "the Hub bar draws its weights segment from weights_bytes and prints it "+ "beside the download size on the same row"+ )++ def test_the_two_projections_disagree_about_weights_bytes(self, estimate):+ """The compatibility boundary, asserted directly.++ If this fails, the two routes have been made to agree on a key whose+ meaning was never shared, and one set of callers is now silently reading+ a different number through an unchanged JSON shape.+ """+ panel = project_estimate_memory_response(estimate)+ bar = project_kv_cache_estimate(estimate)+ assert panel["weights_bytes"] != bar["weights_bytes"], (+ "both routes now report the same weights_bytes. See the module "+ "docstring: these two meanings are different by design."+ )++ def test_the_kv_projection_keeps_none_rather_than_zero(self):+ # This route uses None for "no such term" throughout, and the frontend's+ # estimateIsUnsized() distinguishes null from 0. Coercing to 0 would make+ # an unsizable model look like a free one.+ empty = SimpleNamespace(**{**_BREAKDOWN.__dict__, "kv_bytes": 0})+ out = project_kv_cache_estimate(+ build_memory_estimate(empty, quant_file_bytes = 0), kv_bytes = 0+ )+ assert out["kv_bytes"] is None+ assert out["weights_bytes"] is None++ def test_a_zero_gpu_share_survives_as_zero(self):+ """The one field where 0 must NOT become None.++ An inherited LLAMA_ARG_DEVICE=none makes the launch entirely CPU+ resident. Folding that into None sends the caller back to summing+ segments and drawing VRAM pressure for a load that touches no card --+ a bug this route already had once and fixed.+ """+ cpu_only = SimpleNamespace(**{**_BREAKDOWN.__dict__, "gpu_bytes": 0})+ out = project_kv_cache_estimate(+ build_memory_estimate(cpu_only, quant_file_bytes = _QUANT_FILE_BYTES),+ kv_bytes = _BREAKDOWN.kv_bytes,+ )+ assert out["gpu_bytes"] == 0, "a real zero GPU share was folded into 'no answer'"++ def test_a_missing_planner_leaves_the_gpu_share_null(self):+ # The other side of the same coin: never ran is not the same as ran and+ # found nothing.+ absent = SimpleNamespace(**{**_BREAKDOWN.__dict__, "gpu_bytes": None})+ out = project_kv_cache_estimate(+ build_memory_estimate(absent, quant_file_bytes = _QUANT_FILE_BYTES),+ kv_bytes = _BREAKDOWN.kv_bytes,+ )+ assert out["gpu_bytes"] is None++ def test_the_kv_projection_does_not_borrow_the_planners_kv(self, estimate):+ # This route prices the target cache itself; the planner's figure is not+ # interchangeable. Passing no kv_bytes must yield None rather than+ # silently substituting the planner's.+ assert project_kv_cache_estimate(estimate)["kv_bytes"] is None++ def test_the_kv_projection_passes_its_own_itemization_through(self, estimate):+ # These four are the models route's own terms; the planner does not model+ # them separately, so they must survive the round trip untouched.+ out = project_kv_cache_estimate(+ estimate,+ spec_bytes = 111,+ spec_fixed_bytes = 22,+ projector_bytes = 333,+ kv_checkpoint_bytes = 44,+ )+ assert (out["spec_bytes"], out["spec_fixed_bytes"]) == (111, 22)+ assert (out["projector_bytes"], out["kv_checkpoint_bytes"]) == (333, 44)++ def test_both_projections_carry_every_key_their_route_promises(self, estimate):+ # Cross-checked against the frozen key sets, so the projections and the+ # freeze cannot drift apart from each other.+ from test_memory_estimate_contract_freeze import _KV_CACHE_ESTIMATE_KEYS++ assert set(project_kv_cache_estimate(estimate)) == set(_KV_CACHE_ESTIMATE_KEYS)++ from models.inference import EstimateMemoryResponse++ assert set(project_estimate_memory_response(estimate)) == set(+ EstimateMemoryResponse.model_fields+ )diff --git a/studio/backend/tests/test_memory_contract_platforms.py b/studio/backend/tests/test_memory_contract_platforms.pynew file mode 100644index 00000000000..784ff0dc16f--- /dev/null+++ b/studio/backend/tests/test_memory_contract_platforms.py@@ -0,0 +1,198 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""The shared contract across the platform x GPU-vendor product.++The consolidation is pure arithmetic and renaming, with no platform-specific+branch anywhere in it, which is precisely the claim worth testing rather than+asserting: a contract that quietly depends on the host is the kind of thing that+is only discovered by the one user who has that host.++The matrix is the four platform keys the repo already parametrises over+(``test_diffusion_predownload_guard_platforms.py``) crossed with the placements+a GGUF load can end up in: everything on one card, split across two, partly on+the host, entirely on the host, and nothing probed at all.++Two properties hold in every cell:++* the WIRE SHAPE of both legacy routes is identical everywhere, so no client+ needs a per-platform branch+* ``weights_bytes`` keeps its own meaning on each route in every cell, which is+ the compatibility boundary the whole consolidation rests on++No GPU, no network, no model load. Pure functions.+"""++import sys+from pathlib import Path+from types import SimpleNamespace++_TESTS_DIR = str(Path(__file__).resolve().parent)+if _TESTS_DIR not in sys.path:+ sys.path.insert(0, _TESTS_DIR)++_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)+if _BACKEND_DIR not in sys.path:+ sys.path.insert(0, _BACKEND_DIR)++import test_kv_cache_estimation # noqa: E402,F401 -- process-wide stubs++import pytest # noqa: E402++from core.inference.memory_contract import ( # noqa: E402+ EMPTY_BREAKDOWN,+ build_memory_estimate,+ project_estimate_memory_response,+ project_kv_cache_estimate,+)+from models.inference import EstimateMemoryResponse # noqa: E402+from test_memory_estimate_contract_freeze import _KV_CACHE_ESTIMATE_KEYS # noqa: E402++PLATFORMS = ("linux", "wsl", "win32", "darwin")++# The vendor decides where bytes LAND, which is the only thing that varies here.+# Named for the host they model so a failure says which machine it is about.+PLACEMENTS = {+ "nvidia-single": {"gpu": 8_100_000_000, "total": 8_700_000_000},+ "nvidia-dual": {"gpu": 8_700_000_000, "total": 8_700_000_000},+ "amd-rocm-discrete": {"gpu": 6_000_000_000, "total": 8_700_000_000},+ # An APU or Apple part: one pool, so everything is "on the GPU" and also all+ # of it is host memory. The route reports the placement, not the topology.+ "unified-apu": {"gpu": 8_700_000_000, "total": 8_700_000_000},+ # --n-cpu-moe or a layer split: some of it is off the card.+ "partial-offload": {"gpu": 3_000_000_000, "total": 8_700_000_000},+ # LLAMA_ARG_DEVICE=none. Zero is a REAL answer here, not a missing one.+ "cpu-only": {"gpu": 0, "total": 8_700_000_000},+}++_QUANT_FILE_BYTES = 4_100_000_000+_RESIDENT_FILES_BYTES = 5_000_000_000+++def _breakdown(gpu: int, total: int) -> SimpleNamespace:+ return SimpleNamespace(+ weights_bytes = _RESIDENT_FILES_BYTES,+ kv_bytes = 3_000_000_000,+ compute_bytes = 700_000_000,+ drafter_runtime_bytes = 0,+ drafter_runtime_gpu_bytes = 0,+ projector_runtime_bytes = 0,+ drafter_kv_unsized = False,+ adapters_unsized = False,+ total_bytes = total,+ gpu_bytes = gpu,+ kv_estimable = True,+ kv_on_gpu = gpu > 0,+ n_ctx = 32768,+ cache_type_kv = "f16",+ n_parallel = 1,+ layer_count = 28,+ gpu_layers = 28 if gpu > 0 else 0,+ )++[email protected]("platform", PLATFORMS)[email protected]("placement", sorted(PLACEMENTS))+class TestTheContractIsPlatformIndependent:+ def test_both_wire_shapes_are_identical_everywhere(self, platform, placement, monkeypatch):+ monkeypatch.setattr(sys, "platform", platform, raising = False)+ p = PLACEMENTS[placement]+ est = build_memory_estimate(+ _breakdown(p["gpu"], p["total"]), quant_file_bytes = _QUANT_FILE_BYTES+ )+ assert set(project_kv_cache_estimate(est)) == set(+ _KV_CACHE_ESTIMATE_KEYS+ ), f"{platform}/{placement}: the models route's key set moved"+ assert set(project_estimate_memory_response(est)) == set(+ EstimateMemoryResponse.model_fields+ ), f"{platform}/{placement}: the inference route's field set moved"++ def test_the_two_meanings_stay_apart_everywhere(self, platform, placement, monkeypatch):+ monkeypatch.setattr(sys, "platform", platform, raising = False)+ p = PLACEMENTS[placement]+ est = build_memory_estimate(+ _breakdown(p["gpu"], p["total"]), quant_file_bytes = _QUANT_FILE_BYTES+ )+ panel = project_estimate_memory_response(est)+ bar = project_kv_cache_estimate(est)+ assert panel["weights_bytes"] == _RESIDENT_FILES_BYTES+ assert bar["weights_bytes"] == _QUANT_FILE_BYTES+ assert panel["weights_bytes"] != bar["weights_bytes"], (+ f"{platform}/{placement}: the two routes agreed on weights_bytes, which "+ "silently changes the number under one set of callers"+ )++ def test_a_cpu_only_launch_reports_zero_rather_than_nothing(+ self, platform, placement, monkeypatch+ ):+ monkeypatch.setattr(sys, "platform", platform, raising = False)+ if placement != "cpu-only":+ pytest.skip("only the CPU-only placement asserts this")+ est = build_memory_estimate(+ _breakdown(0, 8_700_000_000), quant_file_bytes = _QUANT_FILE_BYTES+ )+ bar = project_kv_cache_estimate(est)+ assert bar["gpu_bytes"] == 0, (+ f"{platform}: a launch that touches no card reported {bar['gpu_bytes']!r} "+ "instead of 0. None means 'the planner never ran', and a caller that "+ "cannot tell them apart draws VRAM pressure for a CPU load."+ )+ assert bar["gpu_bytes"] is not None++[email protected]("platform", PLATFORMS)+class TestTheAbsentPlannerIsTheSameEverywhere:+ def test_a_planner_that_never_ran_is_null_not_zero(self, platform, monkeypatch):+ monkeypatch.setattr(sys, "platform", platform, raising = False)+ est = build_memory_estimate(EMPTY_BREAKDOWN, quant_file_bytes = _QUANT_FILE_BYTES)+ bar = project_kv_cache_estimate(est)+ assert bar["gpu_bytes"] is None, (+ f"{platform}: an absent planner reported {bar['gpu_bytes']!r}. 0 would mean "+ "'measured, nothing on the card', which is a different claim."+ )+ # The quant size is known independently of the planner, so it survives.+ assert bar["weights_bytes"] == _QUANT_FILE_BYTES+ # And the shape is still complete, so a caller needs no branch for it.+ assert set(bar) == set(_KV_CACHE_ESTIMATE_KEYS)+++class TestOldClientsAreUnaffected:+ """Forwards compatibility: what a client written before this PR still sees."""++ def test_every_field_an_old_client_read_is_still_present_and_typed(self):+ # The fields #7880's frontend reads off /kv-cache-estimate, by name, as a+ # stand-in for any third-party client pinned to that shape.+ est = build_memory_estimate(+ _breakdown(8_100_000_000, 8_700_000_000), quant_file_bytes = _QUANT_FILE_BYTES+ )+ bar = project_kv_cache_estimate(+ est, kv_bytes = 3_000_000_000, spec_bytes = None, projector_bytes = None+ )+ for name in (+ "kv_bytes",+ "weights_bytes",+ "native_context",+ "spec_bytes",+ "n_ctx",+ "gpu_bytes",+ "compute_bytes",+ "total_bytes",+ "gpu_floor_bytes",+ "context_is_pinned",+ "inherited_device_pin",+ "spec_unpriced",+ ):+ assert name in bar, f"{name} disappeared from a shipped contract"+ for name in ("kv_bytes", "weights_bytes", "n_ctx"):+ assert bar[name] is None or isinstance(+ bar[name], int+ ), f"{name} changed type, which breaks a strict deserializer"+ for name in ("context_is_pinned", "inherited_device_pin", "spec_unpriced"):+ assert isinstance(bar[name], bool)++ def test_the_canonical_model_never_grows_the_ambiguous_name(self):+ from models.inference import MemoryEstimate+ assert "weights_bytes" not in MemoryEstimate.model_fields, (+ "MemoryEstimate has grown a weights_bytes field. That name means two "+ "different things on the two legacy routes and belongs on neither."+ )diff --git a/studio/backend/tests/test_memory_estimate_contract_freeze.py b/studio/backend/tests/test_memory_estimate_contract_freeze.pynew file mode 100644index 00000000000..bf5707afb90--- /dev/null+++ b/studio/backend/tests/test_memory_estimate_contract_freeze.py@@ -0,0 +1,278 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""The two public memory-estimate contracts, frozen before they are consolidated.++Studio answers "how much memory would this load take" on two routes:++* ``POST /api/inference/estimate-memory`` -- the Load Model panel (#9525)+* ``GET /api/models/kv-cache-estimate`` -- the Hub memory bar (#7880)++They already share one planner, ``_gguf_memory_breakdown``, so their arithmetic+cannot drift. Their CONTRACTS are still separate, and consolidating the two onto+one implementation is the change these tests exist to make safe.++The hazard is specific and it is not shape drift, which a typechecker would+catch. ``weights_bytes`` exists on both routes, is an ``int`` on both, and means+DIFFERENT THINGS:++* on ``/estimate-memory`` it is every resident file -- weights, projector and+ drafter together (``models/inference.py``: "Resident model files: weights,+ projector, drafter")+* on ``/kv-cache-estimate`` it is the quant file ALONE; the planner's aggregate+ is carried separately as ``gpu_bytes`` / ``total_bytes`` / ``gpu_floor_bytes``++A consolidation that picks one meaning for the shared key changes the number+under whichever caller loses, with no change to the JSON shape and therefore+nothing for a client to detect. So the collision is pinned here DELIBERATELY:+``test_the_two_routes_disagree_about_weights_bytes`` is not describing a bug to+be fixed, it is the compatibility boundary. If a refactor makes the two agree,+that test fails, and that failure is the point.++No GPU, no network, no model load: every GGUF here is a synthetic header on+tmp_path. Cross-platform.+"""++import sys+from pathlib import Path+from types import SimpleNamespace++_TESTS_DIR = str(Path(__file__).resolve().parent)+if _TESTS_DIR not in sys.path:+ sys.path.insert(0, _TESTS_DIR)++_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)+if _BACKEND_DIR not in sys.path:+ sys.path.insert(0, _BACKEND_DIR)++# Installs the process-wide loggers/structlog/httpx stubs and the GGUF builder,+# and brings the route harness with it. Same import-for-side-effects pattern as+# test_kv_cache_estimate_route.py.+from test_kv_cache_estimate_route import _call_route, _write_gguf # noqa: E402++import routes.inference as ri # noqa: E402+import routes.models as models_routes # noqa: E402+from models.inference import EstimateMemoryResponse # noqa: E402+++def _reach_the_planner(monkeypatch, gguf: Path) -> None:+ """Make the route's planner delegation actually run.++ Worth spelling out, because the first draft of this file did NOT do it and+ was worthless as a result. The delegation is gated on+ ``_cached_estimate_config`` resolving the repo to something on this disk;+ for a synthetic repo id it returns ``None``, the whole block is skipped, and+ ``gpu_bytes`` / ``total_bytes`` / ``gpu_floor_bytes`` / ``compute_bytes``+ all come back ``None``.++ A freeze test written over that fixture passes while asserting nothing: the+ planner fields are present-and-null, so swapping ``weights_bytes`` for the+ planner's aggregate still passes, which is the exact silent change this file+ exists to catch. Pin the config so the planner produces real figures.+ """+ config = SimpleNamespace(+ identifier = "local/model",+ gguf_file = str(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)+++# An ordinary GQA model. Nothing exotic: this is about the envelope, not the+# arithmetic, and test_memory_estimate.py already owns the arithmetic.+_PLAIN_GQA = {+ "context_length": 32768,+ "block_count": 28,+ "attention.head_count": 16,+ "attention.head_count_kv": 8,+ "embedding_length": 3072,+ "attention.key_length": 128,+ "attention.value_length": 128,+}++# Every key GET /kv-cache-estimate has ever promised, as of the #7880 merge+# (54367e59). The route returns a bare dict with no response_model, so nothing+# in the framework enforces this and only this test does.+_KV_CACHE_ESTIMATE_KEYS = frozenset(+ {+ "kv_bytes",+ "weights_bytes",+ "native_context",+ "spec_bytes",+ "n_ctx",+ "projector_bytes",+ "kv_checkpoint_bytes",+ "spec_fixed_bytes",+ "gpu_bytes",+ "compute_bytes",+ "total_bytes",+ "gpu_floor_bytes",+ "context_is_pinned",+ "inherited_device_pin",+ "spec_unpriced",+ }+)+++class TestTheKvCacheEstimateEnvelope:+ """GET /kv-cache-estimate, key for key."""++ def test_the_key_set_is_exactly_what_shipped(self, monkeypatch, tmp_path):+ gguf = _write_gguf(tmp_path / "model-Q4_K_M.gguf", _PLAIN_GQA)+ out = _call_route(+ monkeypatch,+ path = gguf,+ weights_bytes = 4_000_000_000,+ repo_id = "unsloth/contract-freeze-GGUF",+ speculative_type = None,+ )+ assert out is not None, "the route answered None for a sizable local GGUF"+ got = set(out)+ # Named both ways round so a failure says which direction moved rather+ # than printing two sets and leaving the reader to diff them.+ assert not got - _KV_CACHE_ESTIMATE_KEYS, (+ f"new keys on a route with no response_model: {sorted(got - _KV_CACHE_ESTIMATE_KEYS)}. "+ "Additive is safe for permissive clients and NOT safe for strict ones; "+ "add it here deliberately."+ )+ assert not _KV_CACHE_ESTIMATE_KEYS - got, (+ f"keys removed from a shipped contract: {sorted(_KV_CACHE_ESTIMATE_KEYS - got)}. "+ "This is a narrowing and it breaks callers."+ )++ def test_weights_bytes_is_the_quant_file_alone(self, monkeypatch, tmp_path):+ # The anchor for the whole consolidation. The figure handed to the route+ # as the resolved quant size must come back out unchanged: not the+ # planner's aggregate, not the aggregate minus something.+ #+ # Driven with the planner REACHED, so that the aggregate is a real and+ # different number sitting right beside this field. Without that, this+ # assertion holds vacuously.+ quant_size = 4_123_456_789+ gguf = _write_gguf(tmp_path / "model-Q4_K_M.gguf", _PLAIN_GQA)+ _reach_the_planner(monkeypatch, gguf)+ out = _call_route(+ monkeypatch,+ path = gguf,+ weights_bytes = quant_size,+ repo_id = "unsloth/contract-freeze-GGUF",+ speculative_type = None,+ )+ assert out[+ "gpu_bytes"+ ], "the planner did not run, so this test would pass vacuously; see _reach_the_planner"+ assert out["gpu_bytes"] != quant_size, (+ "the planner's aggregate happens to equal the quant size in this fixture, "+ "so the two meanings are indistinguishable here; change the fixture"+ )+ assert out["weights_bytes"] == quant_size, (+ "weights_bytes on /kv-cache-estimate is the quant file alone. The Hub bar "+ "draws its weights segment from this and labels it with the file size the "+ "row advertises; folding the projector or a drafter in makes the segment "+ "disagree with the download size beside it."+ )++ def test_the_planner_aggregate_travels_in_its_own_fields(self, monkeypatch, tmp_path):+ # The corollary: the planner's numbers arrive, they are POPULATED, and+ # they are not weights_bytes. Presence alone is not the assertion -- the+ # fields are present-and-null whenever the delegation is skipped, which+ # is most of this suite's sibling fixtures.+ gguf = _write_gguf(tmp_path / "model-Q4_K_M.gguf", _PLAIN_GQA)+ _reach_the_planner(monkeypatch, gguf)+ out = _call_route(+ monkeypatch,+ path = gguf,+ weights_bytes = 4_000_000_000,+ repo_id = "unsloth/contract-freeze-GGUF",+ speculative_type = None,+ )+ for field in ("gpu_bytes", "total_bytes", "gpu_floor_bytes", "compute_bytes"):+ assert out.get(field), (+ f"{field} is how the planner's figures reach the bar, and it is "+ f"{out.get(field)!r}. A null here means the delegation added during "+ "#7880's review stopped running."+ )+ # The floor is what survives any context reduction, so it must be a+ # strict fraction of the full GPU figure rather than a copy of it.+ assert out["gpu_floor_bytes"] < out["gpu_bytes"]+++class TestTheEstimateMemoryEnvelope:+ """POST /estimate-memory, field for field."""++ def test_weights_bytes_is_documented_as_the_aggregate(self):+ # Read off the model rather than a live call: this is a statement about+ # the CONTRACT, and the description is the contract for a field whose+ # type says nothing useful. If someone narrows the meaning to match the+ # sibling route, this is the tripwire.+ field = EstimateMemoryResponse.model_fields["weights_bytes"]+ description = (field.description or "").lower()+ assert "projector" in description and "drafter" in description, (+ "weights_bytes on /estimate-memory is weights PLUS projector PLUS drafter. "+ f"Its description now reads {field.description!r}, which no longer says so. "+ "The Load Model panel itemizes against this meaning."+ )++ def test_the_response_model_still_carries_the_itemization(self):+ # The panel prints one row per term. Losing any of these silently blanks+ # a row rather than failing, so they are pinned by name.+ expected = {+ "available",+ "reason",+ "weights_bytes",+ "kv_bytes",+ "compute_bytes",+ "drafter_runtime_bytes",+ "drafter_runtime_gpu_bytes",+ "projector_runtime_bytes",+ "drafter_kv_unsized",+ "adapters_unsized",+ "total_bytes",+ "gpu_bytes",+ "kv_estimable",+ "kv_on_gpu",+ "n_ctx",+ "cache_type_kv",+ "n_parallel",+ "layer_count",+ "gpu_layers",+ "moe_offload_unmodelled",+ }+ got = set(EstimateMemoryResponse.model_fields)+ assert (+ not expected - got+ ), f"fields removed from a shipped response model: {sorted(expected - got)}"+++class TestTheCollisionItself:+ """The one thing the consolidation must not quietly resolve."""++ def test_the_two_routes_disagree_about_weights_bytes(self, monkeypatch, tmp_path):+ """Same key, same type, different meaning. Pinned on purpose.++ This test failing means someone made the two routes agree on+ ``weights_bytes``. That is not automatically wrong, but it IS a silent+ semantic change for one set of callers, so it has to be a decision+ someone wrote down rather than a side effect of sharing an+ implementation. Read the module docstring before changing it.+ """+ kv_route_meaning = models_routes.get_kv_cache_estimate.__doc__ or ""+ inference_meaning = EstimateMemoryResponse.model_fields["weights_bytes"].description or ""+ # The inference route says so in its own words.+ assert (+ "projector" in inference_meaning.lower()+ ), "the aggregate meaning is no longer documented on /estimate-memory"+ # And the models route hands back exactly what it resolved, which the+ # sibling test above proves numerically. Here we only assert the two+ # descriptions are not the same claim, so that a future merge onto one+ # shared field cannot pass both suites unnoticed.+ assert "weights, projector, drafter" not in kv_route_meaning, (+ "/kv-cache-estimate has started describing weights_bytes as the "+ "aggregate. If that is intended, the Hub bar's weights segment and "+ "the download size beside it now disagree, and older clients reading "+ "this field as the file size are silently wrong."+ )diff --git a/studio/frontend/src/features/hub/catalog/gguf-download-card.tsx b/studio/frontend/src/features/hub/catalog/gguf-download-card.tsxindex 6f7762012c0..3f1ce494424 100644--- a/studio/frontend/src/features/hub/catalog/gguf-download-card.tsx+++ b/studio/frontend/src/features/hub/catalog/gguf-download-card.tsx@@ -26,6 +26,7 @@ import { pinKey, usePinnedModelsStore } from "@/features/model-picker";import { ChevronDownStandardIcon } from "@/lib/chevron-icons";import { copyToClipboard } from "@/lib/copy-to-clipboard";import { type GgufFitClass, classifyGgufFit } from "@/lib/gguf-fit";+import { useVramBudgetFraction } from "@/hooks/use-vram-budget-fraction";import { toast } from "@/lib/toast";import { cn } from "@/lib/utils";import {@@ -249,7 +250,7 @@ interface GgufVariantMenuItem {function createGgufVariantMenuItems(variants: readonly GgufVariantDetail[] | null,- resources: { gpuGb?: number; systemRamGb?: number },+ resources: { gpuGb?: number; systemRamGb?: number; budgetFraction?: number },): GgufVariantMenuItem[] {if (!variants) return [];return variants.map((variant) => ({@@ -625,10 +626,19 @@ export function GgufDownloadCard({ReadonlySet<string>>(() => new Set<string>());+ // The live VRAM Budget, so the badge and the sort score against the line the+ // loader will actually admit at. The memory bar on this same row already reads+ // it; without this the two disagreed for every saved fraction below the default.+ const budgetFraction = useVramBudgetFraction() ?? undefined;+const rawSortedVariants = useMemo(() => {if (!variants) return null;- return sortDownloadableGgufVariants(variants, { gpuGb, systemRamGb });- }, [variants, gpuGb, systemRamGb]);+ return sortDownloadableGgufVariants(variants, {+ gpuGb,+ systemRamGb,+ budgetFraction,+ });+ }, [variants, gpuGb, systemRamGb, budgetFraction]);const selectLiveGgufVariantStates = useMemo(() => createLiveGgufVariantStatesSelector(repoId),[repoId],@@ -650,8 +660,13 @@ export function GgufDownloadCard({);}, [completedVariantKeys, liveVariantStates, rawSortedVariants]);const variantMenuItems = useMemo(- () => createGgufVariantMenuItems(sortedVariants, { gpuGb, systemRamGb }),- [gpuGb, sortedVariants, systemRamGb],+ () =>+ createGgufVariantMenuItems(sortedVariants, {+ gpuGb,+ systemRamGb,+ budgetFraction,+ }),+ [gpuGb, sortedVariants, systemRamGb, budgetFraction],);const selectedQuant =@@ -747,9 +762,13 @@ export function GgufDownloadCard({const selectedFit = useMemo(() =>selected- ? classifyGgufFit(selected.size_bytes, { gpuGb, systemRamGb })+ ? classifyGgufFit(selected.size_bytes, {+ gpuGb,+ systemRamGb,+ budgetFraction,+ }): null,- [gpuGb, selected?.size_bytes, systemRamGb],+ [gpuGb, selected?.size_bytes, systemRamGb, budgetFraction],);const selectedDownloadSizeLabel = selected? ggufVariantTransferLabel(selected)diff --git a/studio/frontend/src/features/hub/catalog/local-on-device-card.tsx b/studio/frontend/src/features/hub/catalog/local-on-device-card.tsxindex 16fc595b277..6e21ed59d90 100644--- a/studio/frontend/src/features/hub/catalog/local-on-device-card.tsx+++ b/studio/frontend/src/features/hub/catalog/local-on-device-card.tsx@@ -2,6 +2,7 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import { ModelMemoryBarFor } from "@/components/model-memory-bar";+import { useVramBudgetFraction } from "@/hooks/use-vram-budget-fraction";import {Popover,PopoverContent,@@ -343,6 +344,11 @@ export function LocalOnDeviceCard({};});}, [currentVariantState.variants, remoteVariantState.variants]);+ // The same live VRAM Budget the memory bar on this card reads. Without it the+ // quant menu ranked against the 0.97 default while the bar beside it used the+ // saved fraction, so an over-budget variant could sit above a smaller one that+ // actually fits.+ const budgetFraction = useVramBudgetFraction() ?? undefined;const sortedVariants = useMemo(() =>variants@@ -351,6 +357,7 @@ export function LocalOnDeviceCard({activeGgufVariant: isActive ? activeGgufVariant : null,gpuGb,systemRamGb,+ budgetFraction,}): null,[@@ -360,6 +367,7 @@ export function LocalOnDeviceCard({activeGgufVariant,gpuGb,systemRamGb,+ budgetFraction,],);const preferredQuant = preferredFilediff --git a/studio/frontend/src/features/hub/lib/gguf-variant-sort.ts b/studio/frontend/src/features/hub/lib/gguf-variant-sort.tsindex 350586fe1b5..c26f0263671 100644--- a/studio/frontend/src/features/hub/lib/gguf-variant-sort.ts+++ b/studio/frontend/src/features/hub/lib/gguf-variant-sort.ts@@ -9,6 +9,9 @@ import { ggufVariantsMatch } from "@/features/hub/lib/model-identity";type GgufVariantResources = {gpuGb?: number;systemRamGb?: number;+ /** The saved VRAM Budget, so the sort ranks against the line the loader will+ * actually admit at rather than against the default. */+ budgetFraction?: number;};export function ggufVariantDisplayLabel(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 12df88fb312..bb025aef006 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@@ -2006,8 +2006,12 @@ export function ModelConfigPage({}: ModelConfigPageProps) {const rememberId = useId();const platformDeviceType = usePlatformStore((s) => s.deviceType);+ // Apple Silicon specifically, and used ONLY for wording: "Unified" is what+ // Apple calls its pool, where an AMD APU's is a "Shared" one. It is NOT the+ // right signal for the capacity question below -- see hasUnifiedMemory.+ //// Unified memory, not just Darwin: an Intel Mac spills to system RAM like a PC.- const isUnifiedMemory = usePlatformStore((s) => s.appleSilicon);+ const isAppleUnifiedMemory = usePlatformStore((s) => s.appleSilicon);const platformChatOnlyReason = usePlatformStore((s) => s.chatOnlyReason);const mlxKvQuantReason = useChatRuntimeStore((s) => s.mlxKvQuantReason);const chatTemplateOverrideReason = useChatRuntimeStore(@@ -2804,6 +2808,46 @@ export function ModelConfigPage({// 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;+ // Whether the devices THIS LOAD will use draw on one pool with the rest of the+ // system, from the backend's per-device unified_memory flag rather than from+ // the platform. Apple Silicon is the obvious case and a ROCm APU is the one+ // that was being missed: both share the pool, so adding VRAM to system RAM to+ // reach a machine-wide ceiling counts the same bytes twice.+ //+ // Scoped to the devices this load will actually use, and true only when EVERY+ // one of them is unified.+ //+ // Two separate mistakes were made here, so both are written down. Reading the+ // host-wide flag was the first: an APU beside a discrete card makes it true,+ // and a pin on the discrete card then collapsed totalCapacityGb from 143.5 GiB+ // to 15.5 GiB. Narrowing to the pin but keeping `.some()` was the second: an+ // unpinned load, or a pin naming BOTH, still marked the whole set unified and+ // reported 62.1 GiB instead of 143.5 GiB. Both produce false "more than this+ // machine holds" warnings for loads that fit comfortably.+ //+ // `.every()` is the right question for CAPACITY: one independent-memory device+ // in the set means there is real VRAM beside system RAM, so the two are not+ // one pool. Note use-gpu-info.ts deliberately uses `.some()` for its own flag,+ // and that is not an inconsistency -- it answers a different question, whether+ // the aggregate is still a VRAM ceiling a verdict can be measured against, and+ // one unified part is enough to spoil that.+ //+ // The empty set is excluded explicitly, because `[].every()` is true and a+ // host with no devices at all is not a unified-memory machine.+ //+ // The Apple fallback stays host-wide and unconditional: there every device is+ // the one pool whatever is pinned, and it also covers the window before the+ // per-device probe lands, so this is never a weaker answer than the platform+ // check it replaced.+ const hasUnifiedMemory = useMemo(() => {+ if (isAppleUnifiedMemory) return true;+ const governing =+ pinnedGpuIds && pinnedGpuIds.length > 0+ ? gpuDevices.filter((device) => pinnedGpuIds.includes(device.index))+ : gpuDevices;+ if (governing.length === 0) return false;+ return governing.every((device) => device.unifiedMemory === true);+ }, [gpuDevices, pinnedGpuIds, isAppleUnifiedMemory]);// 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:@@ -2850,6 +2894,22 @@ export function ModelConfigPage({const memoryEffectiveBudgetFraction = memoryBudgetGovernsLaunch? memoryVramBudgetFraction: 1;+ // _HOST_RAM_HEADROOM_MIB: the 2 GiB the loader keeps for the rest of the system+ // before admitting an offloaded load.+ //+ // The HOST reading, not the sum-shaped one beside it, which is zeroed whenever+ // ANY device shares system RAM -- every dGPU + iGPU box -- so that was+ // permanently 0 there and the host-pressure advisory could not fire even under+ // a pin on the discrete card, the one case where host RAM really is a separate+ // pool.+ //+ // Hoisted because the free-capacity memo below needs the same figure: a ROCm+ // APU's free pool IS this, and two copies of the subtraction is how they would+ // drift apart.+ const memoryUsableSystemRamGb = Math.max(+ 0,+ (inferenceGpu.systemRamAvailableHostGb || 0) - 2,+ );const memoryFreeGpuCapacityGb = useMemo(() => {const pinned =pinnedGpuIds && pinnedGpuIds.length > 0@@ -2865,8 +2925,31 @@ export function ModelConfigPage({// 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 freeVram = aggregateUsableFreeVramGb(+ pinned,+ memoryEffectiveBudgetFraction,+ );+ // On a ROCm APU this figure is the free space inside a BIOS-carved window,+ // and resolveMemoryFit asks it the WHOLE-LOAD question as soon as the pool is+ // single. Those two together warned that a 60 GiB load does not fit a 96 GiB+ // machine with 60+ GiB free, purely because it exceeds a 48 GiB window.+ //+ // The pool's real free memory is the host's, exactly as its real CAPACITY is+ // the host's RAM rather than the window. Same discriminator as the capacity+ // side, so the two cannot answer differently: Apple's GPU figure already IS+ // the pool and is left alone.+ if (hasUnifiedMemory && !isAppleUnifiedMemory) {+ return Math.max(freeVram, memoryUsableSystemRamGb);+ }+ return freeVram;+ }, [+ gpuDevices,+ pinnedGpuIds,+ memoryEffectiveBudgetFraction,+ hasUnifiedMemory,+ isAppleUnifiedMemory,+ memoryUsableSystemRamGb,+ ]);const {gpuCapacityGb: memoryGpuCapacityGb,totalCapacityGb: memoryTotalCapacityGb,@@ -2882,7 +2965,20 @@ export function ModelConfigPage({hostDedicatedGpuTotalGb: inferenceGpu.dedicatedMemoryTotalGb,hostSharesSystemRam: inferenceGpu.sharedMemory,systemRamTotalGb: inferenceGpu.systemRamTotalGb,- unifiedMemory: isUnifiedMemory,+ // The GENERAL signal, not the Apple-only one. A ROCm APU reports+ // unified_memory per device and shares one pool exactly as Apple does, but+ // reading appleSilicon here charged it as discrete VRAM PLUS host RAM --+ // the same bytes counted twice, so the panel could report a fit that+ // cannot happen. The Hub bar gets this right and abstains on this very+ // flag; this is the panel catching up.+ unifiedMemory: hasUnifiedMemory,+ // ...but "one pool" and "how big is the pool" are different questions, and+ // the two platforms answer the second differently. Apple's memory_total_gb+ // IS the machine's unified memory; a ROCm APU's is a BIOS-carved window+ // onto system RAM, so taking it as the ceiling reported 46.56 GiB on a+ // 96 GiB machine and warned that a 60 GiB load exceeds the host. Only the+ // Apple half may be read as the whole pool.+ unifiedPoolReportedAsGpuMemory: isAppleUnifiedMemory,});const rememberChanged = remember !== savedRemember;@@ -3112,19 +3208,8 @@ export function ModelConfigPage({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 admitting an offloaded load.- //- // The HOST reading, not the sum-shaped one beside it, which is zeroed- // whenever ANY device shares system RAM -- every dGPU + iGPU box -- so- // this was permanently 0 there and the host-pressure advisory could not- // fire even under a pin on the discrete card, the one case where host- // RAM really is a separate pool.- (inferenceGpu.systemRamAvailableHostGb || 0) - 2,- )}- isUnifiedMemory={isUnifiedMemory}+ usableSystemRamGb={memoryUsableSystemRamGb}+ isUnifiedMemory={isAppleUnifiedMemory}singleMemoryPool={singleMemoryPool}expanded={memoryBreakdownOpen}onExpandedChange={setMemoryBreakdownOpen}@@ -3193,7 +3278,7 @@ export function ModelConfigPage({loadedMaxContextLength != null &&contextValue > loadedMaxContextLength && (<p className="text-ui-11 text-amber-500">- {isUnifiedMemory ? (+ {isAppleUnifiedMemory ? (<>Exceeds what fits in unified memory ({loadedMaxContextLength.toLocaleString()} tokens). Thediff --git a/studio/frontend/src/features/model-picker/model-config/memory-fit.ts b/studio/frontend/src/features/model-picker/model-config/memory-fit.tsindex 37fe141121b..c268e4a9dae 100644--- a/studio/frontend/src/features/model-picker/model-config/memory-fit.ts+++ b/studio/frontend/src/features/model-picker/model-config/memory-fit.ts@@ -5,74 +5,54 @@* How the estimated footprint sits against the memory available to hold it, and the* single note the row prints about it.*- * Import-free, like the sibling estimate-context.ts, so `tests/` can load it under- * `node --experimental-strip-types`, which does not resolve the `@/` alias. Inside a- * 3,400-line .tsx this chain was unreachable from the test runner, and a ternary arm- * that could never be taken survived review for exactly that reason. Everything is- * pure and typed structurally, so a MemoryEstimate satisfies the inputs.+ * Split out of model-config-page.tsx for the reason the sibling estimate-context.ts+ * gives: kept free of `@/` ALIAS imports so `tests/` can load it under+ * `node --experimental-strip-types`, which does not resolve that 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).+ *+ * The imports below are RELATIVE and with explicit extensions, which the strip-types+ * loader does resolve, so the three tests that load this module directly+ * (memory-fit, memory-estimate-skew, memory-estimate-free-vram) still work without+ * registering a bundler resolver. An `@/` spelling here breaks all three.+ *+ * 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";+// The fit vocabulary and the unit formatting now live in src/lib/memory/, shared+// with the Hub memory bar so the two surfaces cannot describe one load+// differently while being fed identical bytes. Re-exported here rather than+// moved out of reach, because this module is the panel's entry point and its+// call sites are unchanged.+export {+ classifyMemoryFit,+ worseMemoryFit,+ type MemoryFitVerdict,+} from "../../../lib/memory/verdict.ts";+export { MEMORY_FIT_TIGHT_RATIO } from "../../../lib/memory/thresholds.ts";-/** Above this share of the capacity the fit is reported as tight rather than clean. */-export const MEMORY_FIT_TIGHT_RATIO = 0.85;+import { classifyMemoryFit, worseMemoryFit } from "../../../lib/memory/verdict.ts";+import type { MemoryFitVerdict } from "../../../lib/memory/verdict.ts";+import { formatBytesGiB } from "../../../lib/memory/format.ts";/**- * Classify a footprint against a capacity.+ * A memory figure in bytes, to two decimals.*- * Every non-finite input is "unknown", and `<= 0` alone does not cover it: NaN and- * Infinity fail every comparison, so `NaN <= 0` is false and the ratio test falls- * through to "fits" -- a green verdict from a number that does not exist. JSON.parse- * turns `1e999` into Infinity and a `?? 0` default never sees it.- */-export function classifyMemoryFit(- bytes: number,- 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, as the rest of the panel talks about memory.+ * @deprecated Prefer `formatBytesGiB` from `@/lib/memory/format`, whose name+ * says which unit it takes. This alias exists because there used to be a SECOND+ * exported `formatMemoryGb`, in `lib/model-memory.ts`, which took gigabytes+ * rather than bytes and printed a different label -- the same name and the same+ * `(number) => string` signature for two incompatible things.*- * Clamped, not trusted: these come off the wire, and "-3.00 GB" or "NaN GB" reads as- * a measurement rather than as the missing reading it is.+ * Note the label has changed from "GB" to "GiB". The divide was always by+ * 1024^3, so every figure this printed was a gibibyte value labelled as a+ * gigabyte, overstating each by 7.4%. That is the defect #9570 fixed elsewhere;+ * it reached seven figures on the Load Model panel and the guard test could not+ * see it, because its regex only matches interpolations naming a `*TotalGb`.*/-export function formatMemoryGb(bytes: number): string {- const safe = Number.isFinite(bytes) && bytes > 0 ? bytes : 0;- return `${(safe / 1024 ** 3).toFixed(2)} GB`;-}+export const formatMemoryGb = formatBytesGiB;/** At most one note under the figures, most actionable first. */export interface MemoryAdvisory {diff --git a/studio/frontend/src/hooks/gpu-selection.ts b/studio/frontend/src/hooks/gpu-selection.tsindex f9e998924ae..2196ff25913 100644--- a/studio/frontend/src/hooks/gpu-selection.ts+++ b/studio/frontend/src/hooks/gpu-selection.ts@@ -17,6 +17,12 @@ export interface SystemGpuDevice {sharedMemory: boolean;/** host-backed portion of memoryTotalGb when sharedMemory is true. */sharedMemoryHostBackedGb?: number | null;+ /** This device and the host are ONE pool (Apple Silicon, a ROCm APU), so its+ * VRAM is not memory beside system RAM. Per device for the same reason+ * sharedMemory is: a pin naming only a discrete card on a mixed machine does+ * not share anything, and judging it against a host-wide flag threw away the+ * system RAM that pin can really spill into. */+ unifiedMemory?: 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 05e130682fe..3925cc6b04d 100644--- a/studio/frontend/src/hooks/gpu-vram.ts+++ b/studio/frontend/src/hooks/gpu-vram.ts@@ -111,6 +111,28 @@ export interface MemoryCapacityDevice {memoryTotalGb: number;sharedMemory: boolean;sharedMemoryHostBackedGb?: number | null;+ /** The backend's per-device `unified_memory`, for a ROCm APU.+ *+ * Separate from `sharedMemory` because the backend reports them separately and+ * they do not coincide: `hardware.py` sets `shared_memory` only on Windows, so+ * on Linux the very same APU arrives as `unified_memory: true,+ * shared_memory: false`. Reading only `sharedMemory` there counts the APU's+ * carved window as VRAM standing BESIDE system RAM, when it is a view INTO it.+ *+ * Both flags mean the same thing for capacity, which is why+ * `sharesHostMemory` below folds them together rather than either one being+ * taught about the other. */+ unifiedMemory?: boolean;+}++/** Whether this device's memory is a view into host RAM rather than beside it.+ * The one question capacity cares about; the two flags are how the backend+ * happens to report it on two platforms. */+function sharesHostMemory(device: {+ sharedMemory?: boolean;+ unifiedMemory?: boolean;+}): boolean {+ return device.sharedMemory === true || device.unifiedMemory === true;}function budgetedGpuMemoryGb(@@ -128,7 +150,7 @@ function budgetedGpuMemoryGb(? device.memoryTotalGb: 0;const deviceCapacity = total * budget;- if (!device.sharedMemory) {+ if (!sharesHostMemory(device)) {dedicated += deviceCapacity;continue;}@@ -175,8 +197,24 @@ export interface MemoryCapacityInput {* nothing is pinned; a pin answers for itself. */hostSharesSystemRam: boolean;systemRamTotalGb: number;- /** Apple Silicon: one pool for everything, whatever the devices say. */+ /** One pool for everything, whatever the shared-memory flags say. True on Apple+ * Silicon and on a ROCm APU, which is why the pool's SIZE is a separate question+ * below: the two report it differently. */unifiedMemory: boolean;+ /** Whether the GPU figure already describes the whole pool.+ *+ * True on Apple, where `memory_total_gb` IS the machine's unified memory, so the+ * budgeted GPU capacity is the ceiling and adding RAM would double count.+ *+ * False on a ROCm APU, where the GPU figure is a BIOS-carved window onto system+ * RAM -- 48 GiB of a 96 GiB machine is typical -- and taking it as the ceiling+ * discards the rest of the pool the weights actually load into. The backend says+ * so in as many words (`llama_cpp.py::_available_system_memory_mib`: "On a+ * unified-memory APU this, not the ROCm-reported VRAM, is the real ceiling").+ *+ * Defaults to true, which is the answer for every caller that predates the ROCm+ * case and passed `unifiedMemory` meaning Apple. */+ unifiedPoolReportedAsGpuMemory?: 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. */@@ -203,7 +241,10 @@ export function resolveMemoryCapacityGb(input: MemoryCapacityInput): {const pinnedTotals = gpuMemoryTotalsGb(input.pinnedDevices.map((device) => ({memory_total_gb: device.memoryTotalGb,- shared_memory: device.sharedMemory,+ // Folded, not passed through: a Linux ROCm APU reports shared_memory false+ // and unified_memory true, and counting its carved window as dedicated VRAM+ // added 46.56 GiB of capacity that is already inside system RAM.+ shared_memory: sharesHostMemory(device),shared_memory_host_backed_gb: device.sharedMemoryHostBackedGb,})),);@@ -244,7 +285,10 @@ export function resolveMemoryCapacityGb(input: MemoryCapacityInput): {const capacityDeviceTotals = gpuMemoryTotalsGb(capacityDevices.map((device) => ({memory_total_gb: device.memoryTotalGb,- shared_memory: device.sharedMemory,+ // Folded, not passed through: a Linux ROCm APU reports shared_memory false+ // and unified_memory true, and counting its carved window as dedicated VRAM+ // added 46.56 GiB of capacity that is already inside system RAM.+ shared_memory: sharesHostMemory(device),shared_memory_host_backed_gb: device.sharedMemoryHostBackedGb,})),);@@ -278,16 +322,17 @@ export function resolveMemoryCapacityGb(input: MemoryCapacityInput): {return {gpuCapacityGb,totalCapacityGb: singleMemoryPool- ? input.unifiedMemory+ ? input.unifiedMemory && input.unifiedPoolReportedAsGpuMemory !== false// 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.+ // A Vulkan iGPU's budget, and a ROCm APU's, are both 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@@ -378,6 +423,11 @@ export interface FreeVramDevice {sharedMemory?: boolean;/** Host-backed portion of memoryTotalGb when sharedMemory is true. */sharedMemoryHostBackedGb?: number | null;+ /** The backend's per-device `unified_memory`. Same reason it exists on+ * MemoryCapacityDevice: a Linux ROCm APU reports `unified_memory: true,+ * shared_memory: false`, and summing its window into the DEDICATED free total+ * counts memory that is already inside the host's RAM. */+ unifiedMemory?: boolean;}/**@@ -410,7 +460,7 @@ export function aggregateUsableFreeVramGb(let fullySharedFree = 0;for (const device of devices) {const deviceUsable = usable(device);- if (!device.sharedMemory) {+ if (!sharesHostMemory(device)) {dedicated += deviceUsable;continue;}diff --git a/studio/frontend/src/hooks/use-gpu-info.ts b/studio/frontend/src/hooks/use-gpu-info.tsindex 83705420e3d..6c96b490cfe 100644--- a/studio/frontend/src/hooks/use-gpu-info.ts+++ b/studio/frontend/src/hooks/use-gpu-info.ts@@ -168,6 +168,7 @@ function toGpuDevices(memoryFreeGb: d.vram_free_gb ?? 0,sharedMemory: d.shared_memory === true,sharedMemoryHostBackedGb: d.shared_memory_host_backed_gb,+ unifiedMemory: d.unified_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.@@ -195,6 +196,7 @@ function toGpuDevices(memoryFreeGb: d.vram_free_gb ?? 0,sharedMemory: d.shared_memory === true,sharedMemoryHostBackedGb: d.shared_memory_host_backed_gb,+ unifiedMemory: d.unified_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/src/hooks/use-vram-budget-fraction.ts b/studio/frontend/src/hooks/use-vram-budget-fraction.tsnew file mode 100644index 00000000000..beafd016288--- /dev/null+++ b/studio/frontend/src/hooks/use-vram-budget-fraction.ts@@ -0,0 +1,100 @@+// 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 user's saved VRAM Budget fraction, live, and read ONCE per session.+ *+ * Several places already did this by hand -- `use-model-memory.ts`, and three+ * effects in `model-config-page.tsx` -- each with its own `useState` plus a+ * subscribe-and-load effect. The Hub's fit badge is the next caller, and copying+ * the pattern again is how the surfaces drift apart: the badge and the memory+ * bar sit on the SAME ROW and must agree about the fraction.+ *+ * The caching here is not an optimization, it is a correctness constraint on a+ * LIST. `loadVramBudgetSettings` deliberately has no read-through cache --+ * `reloadRequired` describes the running process and goes stale on any load --+ * and it clears its shared promise once the request settles, so it only+ * coalesces callers whose requests overlap in time. A Hub catalog mounts a card+ * per repo progressively, through scrolling, filtering and pagination, so one+ * GET per card is what that adds up to, and on a backend predating the route it+ * is one 404 per card.+ *+ * So the FRACTION is cached module-wide, while the settings loader keeps its+ * always-refetch behaviour for the callers that need `reloadRequired`. The cache+ * is kept live by the same change event every other reader already subscribes+ * to, so a save still reaches every mounted card immediately.+ *+ * `null` until the first answer arrives, and `null` forever on a backend too old+ * to serve `/api/settings/vram-budget`. Callers pass it straight to+ * `classifyGgufFit`, whose `budgetFraction` treats absent as "use the shared+ * default" rather than as "the whole card".+ */++import { useEffect, useState } from "react";++import {+ loadVramBudgetSettings,+ subscribeVramBudgetSettings,+} from "@/features/settings/api/vram-budget";++/** The last fraction seen, from any reader. `null` = not answered yet. */+let cachedFraction: number | null = null;+/** In flight, so cards mounting in the same tick share one request. */+let inFlight: Promise<void> | null = null;+/** The route answered 404: there is no fraction to fetch, ever. Without this a+ * catalog on an older backend retries per card forever. */+let routeAbsent = false;++/** Reset for tests; not used by the app. */+export function __resetVramBudgetFractionCache(): void {+ cachedFraction = null;+ inFlight = null;+ routeAbsent = false;+}++function ensureLoaded(): Promise<void> {+ if (cachedFraction !== null || routeAbsent) return Promise.resolve();+ if (inFlight) return inFlight;+ inFlight = loadVramBudgetSettings()+ .then((settings) => {+ // Null is the route being absent, not a transient failure, so record it+ // rather than asking the next card to find out again.+ if (settings) cachedFraction = settings.fraction;+ else routeAbsent = true;+ })+ .catch(() => {+ // Leaves the cache empty, which is the "use the shared default" answer.+ // Not marked absent: a transient failure should not permanently pin every+ // card to the default for the rest of the session.+ })+ .finally(() => {+ inFlight = null;+ });+ return inFlight;+}++export function useVramBudgetFraction(): number | null {+ const [fraction, setFraction] = useState<number | null>(cachedFraction);++ useEffect(() => {+ let alive = true;+ // Subscribe BEFORE loading. A save committed while the GET is in the air+ // would otherwise be missed entirely, leaving the badge scoring against a+ // fraction the user has already replaced. This is also what keeps the+ // module cache honest: every writer publishes on this event.+ const unsubscribe = subscribeVramBudgetSettings((settings) => {+ cachedFraction = settings.fraction;+ routeAbsent = false;+ if (alive) setFraction(settings.fraction);+ });+ void ensureLoaded().then(() => {+ if (alive) setFraction(cachedFraction);+ });+ return () => {+ alive = false;+ unsubscribe();+ };+ }, []);++ return fraction;+}diff --git a/studio/frontend/src/lib/gguf-fit.ts b/studio/frontend/src/lib/gguf-fit.tsindex bd3374286c8..4a0819f9f76 100644--- a/studio/frontend/src/lib/gguf-fit.ts+++ b/studio/frontend/src/lib/gguf-fit.ts@@ -13,12 +13,37 @@ export type GgufFitClass = "fits" | "marginal" | "partial" | "ram" | "oom";export interface GgufFitInput {gpuGb?: number;systemRamGb?: number;+ /** The user's saved VRAM Budget, when it is known.+ *+ * Absent means "not loaded yet, or a backend too old to serve the route", and+ * falls back to the shared default. It does NOT mean "the whole card": scoring+ * against 1.0 would call a load comfortable that the loader refuses.+ *+ * This exists because the badge and the memory bar sit on the SAME ROW and the+ * bar already consumes the live fraction (`use-model-memory.ts`). With a saved+ * 0.90 on a 24 GiB card the loader admits at 21.6 GiB while this file scored+ * against the 0.97 default's 23.28 GiB, so a 18 to 19 GiB quant was badged+ * `fits` beside a bar reporting an overage. */+ budgetFraction?: number;}-/** Fraction of GPU VRAM treated as usable, matching the backend's 0.90 budget.- * Exported so the picker's memory bar draws its track against the same budget- * this classifier judges against. */-export const VRAM_HEADROOM_RATIO = 0.9;+/** Fraction of GPU VRAM treated as usable.+ *+ * Re-exported from the shared memory core so this badge and the Hub memory bar+ * on the SAME ROW cannot judge against different budgets. It was 0.90 here while+ * the bar used the loader's own 0.97, which is what admission actually applies+ * (`_CTX_FIT_VRAM_FRACTION`); `llama_cpp.py` records 0.90 as already tried and+ * reverted, "0.90 dropped 91-94% fits to CPU offload, #5106".+ *+ * Measured over 15-24 GiB on a 24 GiB card, this takes badge-vs-bar+ * disagreements from 11/19 sizes to 8/19. It does not remove them: the residual+ * 8 are the ESTIMATOR difference, since this file scores `size * 1.15 + 1 GB`+ * while the bar uses the load planner's real figures. Sharing the constant is+ * the part that belongs to this consolidation; rewiring the badge onto the+ * planner is a separate change with its own blast radius (it also drives a+ * filter). */+export { DEFAULT_VRAM_BUDGET_FRACTION as VRAM_HEADROOM_RATIO } from "./memory/thresholds.ts";+import { DEFAULT_VRAM_BUDGET_FRACTION } from "./memory/thresholds.ts";/** GGUF weights are file size; runtime activations add roughly this fraction. */const ACTIVATIONS_RATIO = 0.15;/** Flat KV/context allowance at a typical 4K window. */@@ -36,17 +61,38 @@ export function requiredGgufMemoryGb(export function classifyGgufFit(sizeBytes: number,- { gpuGb, systemRamGb }: GgufFitInput,+ { gpuGb, systemRamGb, budgetFraction }: GgufFitInput,): GgufFitClass {const required = requiredGgufMemoryGb(sizeBytes);if (!gpuGb || gpuGb <= 0) {const ramBudget = (systemRamGb ?? 0) * RAM_OFFLOAD_USABLE_RATIO;return required <= ramBudget ? "ram" : "oom";}- const budget = gpuGb * VRAM_HEADROOM_RATIO;+ // Guarded rather than trusted: this arrives from a settings route, and a 0 or a+ // non-finite value would score every quant as an overage.+ const fraction =+ typeof budgetFraction === "number" &&+ Number.isFinite(budgetFraction) &&+ budgetFraction > 0 &&+ budgetFraction <= 1+ ? budgetFraction+ : DEFAULT_VRAM_BUDGET_FRACTION;+ const budget = gpuGb * fraction;if (required <= budget) return "fits";+ // Raw card, deliberately. This band means "over your budget, still card-sized",+ // which is the only thing that distinguishes it from `fits`: scoring it against+ // `budget` too would make it unreachable, since `required <= budget` has already+ // returned above. It is a warning tier, not a claim that the load will be+ // admitted.if (required <= gpuGb) return "marginal";- const combined = gpuGb + (systemRamGb ?? 0) * RAM_OFFLOAD_USABLE_RATIO;+ // The budget, though. Once layers spill, what the GPU can still contribute is+ // what it is ALLOWED to hold, and the reserve is exactly what the model and KV+ // cache may not use ("the fit reserves a slice of every card that the model and+ // KV cache may not use", vram_budget_settings.py). Crediting the raw card here+ // invented capacity the loader will not give: on a 24 GiB card with 16 GiB of+ // RAM at the legal minimum 0.80, quants from 23 to 26 GiB were badged `partial`+ // when the budget leaves them no way to load.+ const combined = budget + (systemRamGb ?? 0) * RAM_OFFLOAD_USABLE_RATIO;if (required <= combined) return "partial";return "oom";}diff --git a/studio/frontend/src/lib/memory/format.ts b/studio/frontend/src/lib/memory/format.tsnew file mode 100644index 00000000000..f0dc3332d1b--- /dev/null+++ b/studio/frontend/src/lib/memory/format.ts@@ -0,0 +1,70 @@+// 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 Studio prints a memory figure. One implementation, for every surface.+ *+ * There used to be two, and they were both called `formatMemoryGb`:+ *+ * - `model-config/memory-fit.ts` took BYTES and printed `"24.00 GB"`+ * - `lib/model-memory.ts` took GIGABYTES and printed `"24 GiB"`+ *+ * Same name, same `(number) => string` signature, different input unit and+ * different output label. Importing the wrong one is off by 1024^3 and+ * typechecks cleanly, and the panel's variant was labelling a binary divide as+ * "GB" across seven figures, which is the defect #9570 fixed elsewhere.+ *+ * So the unit is in the NAME here. `formatGiB` takes gibibytes, `formatBytesGiB`+ * takes bytes, and neither can be confused for the other at a call site.+ *+ * Everything Studio measures in memory is a binary divide: weights and KV come+ * from `bytes / 1024**3`, and the GPU total arrives from the backend as+ * `props.total_memory / 1024**3` with nothing subtracting a budget on the way.+ * Calling any of them GB overstates each by 7.4%.+ *+ * No `@/` alias imports, deliberately. `tests/` runs under `node --experimental-strip-types`,+ * which does not resolve the `@/` alias, and the modules this replaces documented+ * the same constraint. A single import here makes the whole chain untestable.+ */++const BYTES_PER_GIB = 1024 ** 3;++/**+ * Adaptive precision, for a one-line readout: `"7.2 GiB"`, `"24 GiB"`.+ *+ * Clamped rather than trusted. Every figure here comes off the wire, and+ * `"-3.0 GiB"` or `"NaN GiB"` both read as a measurement rather than as the+ * missing reading they are.+ */+export function formatGiB(gib: number): string {+ if (!Number.isFinite(gib) || gib <= 0) return "0 GiB";+ return `${gib < 10 ? gib.toFixed(1) : Math.round(gib)} GiB`;+}++/**+ * Fixed two decimals, for an itemized column where the figures line up:+ * `"24.00 GiB"`.+ *+ * A separate function rather than a flag, because the choice is about the+ * SURFACE and not about the number. A readout that says "about 7 GiB" and a+ * table row that has to add up want different things, and threading a boolean+ * through every call site is how they end up inconsistent again.+ */+export function formatBytesGiB(bytes: number): string {+ const safe = Number.isFinite(bytes) && bytes > 0 ? bytes : 0;+ return `${(safe / BYTES_PER_GIB).toFixed(2)} GiB`;+}++/**+ * A per-token KV rate, which lands in KiB or MiB.+ *+ * Binary throughout, and labelled so. The previous version divided by 1024 and+ * printed "KB", the same mislabel as above one scale down.+ */+export function formatKvRate(bytes: number): string {+ if (!Number.isFinite(bytes) || bytes <= 0) return "0 KiB";+ const kib = bytes / 1024;+ if (kib < 1024) return `${kib < 10 ? kib.toFixed(1) : Math.round(kib)} KiB`;+ const mib = kib / 1024;+ return `${mib < 10 ? mib.toFixed(1) : Math.round(mib)} MiB`;+}diff --git a/studio/frontend/src/lib/memory/thresholds.ts b/studio/frontend/src/lib/memory/thresholds.tsnew file mode 100644index 00000000000..68f50135701--- /dev/null+++ b/studio/frontend/src/lib/memory/thresholds.ts@@ -0,0 +1,58 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++/**+ * Every number that decides how a memory figure is COLOURED or JUDGED.+ *+ * These were spread across two features that never referenced each other, so+ * the Load Model panel and the Hub memory bar could describe one load+ * differently while being fed identical bytes. Collecting them here does not+ * make them one number -- two of them measure genuinely different things -- but+ * it does mean the difference is visible in one place instead of being+ * discovered by comparing two screens.+ *+ * No `@/` alias imports: see the note in ./format.ts.+ */++/**+ * Above this share of the capacity, a fit is reported as tight rather than clean.+ *+ * This is a VERDICT threshold: it answers "will this load fit", and the answer+ * changes at 85% because the remaining headroom stops being enough for the+ * allocator's slack. Distinct from the pressure ramp below, which answers "how+ * full does this look" -- the two are different questions and it is correct for+ * them to have different numbers.+ */+export const MEMORY_FIT_TIGHT_RATIO = 0.85;++/**+ * Fill fraction (%) at which the bar leaves the accent colour.+ *+ * Studio's live meters step at 70/90 (`resources-tab.tsx`), but those show usage+ * as it happens, where a sustained 70% is worth flagging. This is a reservation+ * you can see coming, so it holds the accent until 80.+ */+export const PRESSURE_HIGH_PCT = 80;++/** Fill fraction (%) at which the bar turns destructive. */+export const PRESSURE_CRITICAL_PCT = 90;++/**+ * The share of a card a load may claim when the user's VRAM Budget setting has+ * not been read yet, or the backend is too old to serve it.+ *+ * 0.97, matching the loader's own `_CTX_FIT_VRAM_FRACTION`+ * (`core/inference/llama_cpp.py`), because a fit verdict drawn against a+ * different fraction than the one admission actually uses is wrong by+ * construction.+ *+ * Explicitly NOT 0.90. The Hub bar used that, and it is not merely a more+ * cautious guess -- it is a value this project already measured and reverted:+ *+ * "0.90 dropped 91-94% fits to CPU offload, #5106" (llama_cpp.py)+ *+ * A bar that warns at 0.90 tells users a load will not fit when the loader will+ * happily admit it, which is the same class of wrong answer as the false "fits"+ * the bar exists to prevent, pointing the other way.+ */+export const DEFAULT_VRAM_BUDGET_FRACTION = 0.97;diff --git a/studio/frontend/src/lib/memory/verdict.ts b/studio/frontend/src/lib/memory/verdict.tsnew file mode 100644index 00000000000..53286b73a35--- /dev/null+++ b/studio/frontend/src/lib/memory/verdict.ts@@ -0,0 +1,139 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++/**+ * One vocabulary for "does this load fit", shared by both memory surfaces.+ *+ * The two surfaces had disjoint answers to the same question:+ *+ * - the Load Model panel: `fits | tight | exceeds | unknown`+ * - the Hub memory bar: `fits | context-exceeds | model-exceeds | unknown`+ *+ * Neither is a subset of the other, and each carries a distinction the other+ * cannot express. The panel knows about TIGHT, which is the useful warning+ * before anything is wrong. The bar knows WHY something exceeds, which is what+ * decides the remedy: a smaller quant, or a shorter context.+ *+ * So this is a superset rather than a winner. The verdict says how bad it is;+ * the cause says what would fix it. Each surface reads the part it renders, and+ * neither loses anything it said before.+ *+ * No `@/` alias imports: see the note in ./format.ts. A relative one is fine,+ * since `node --experimental-strip-types` resolves those.+ */++import { MEMORY_FIT_TIGHT_RATIO } from "./thresholds.ts";++/** How an estimated footprint sits against the memory available to hold it. */+export type MemoryFitVerdict = "fits" | "tight" | "exceeds" | "unknown";++/**+ * What is responsible for an overage, and therefore what would fix it.+ *+ * - `context` -- the reservation grows with context, so a shorter context or a+ * quantized KV cache recovers it.+ * - `irreducible` -- the part no context reduction touches. Usually the weights,+ * but NOT only the weights: a separate drafter's own weights, the flat compute+ * buffer and a Hybrid Mamba target's recurrent rollback state all survive any+ * context change, and each can be several GiB.+ * - `null` -- nothing exceeds, or the cause was not determined.+ */+export type MemoryFitCause = "context" | "irreducible" | null;++export interface MemoryVerdict {+ verdict: MemoryFitVerdict;+ cause: MemoryFitCause;+}++/**+ * 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;+}++/**+ * The bar's status vocabulary, derived from the shared one.+ *+ * Kept as a separate string union rather than replacing it, because these are+ * the values its rendering and its translation keys already switch on.+ */+export type ModelMemoryStatus =+ | "unknown"+ | "fits"+ | "context-exceeds"+ | "model-exceeds";++/**+ * Project a shared verdict onto the bar's vocabulary.+ *+ * `tight` maps to `fits`: the bar expresses that band through its pressure+ * colour rather than through a status, so folding it into `fits` here loses+ * nothing that is actually rendered.+ */+export function toModelMemoryStatus(v: MemoryVerdict): ModelMemoryStatus {+ if (v.verdict === "unknown") return "unknown";+ if (v.verdict !== "exceeds") return "fits";+ return v.cause === "context" ? "context-exceeds" : "model-exceeds";+}++/**+ * Lift the bar's vocabulary into the shared one, for the reverse direction.+ *+ * Note the asymmetry: this cannot recover `tight`, because the bar never+ * recorded it. Round-tripping through the bar's status is lossy on purpose and+ * callers holding a real {@link MemoryVerdict} should keep it rather than+ * passing through here.+ */+export function fromModelMemoryStatus(status: ModelMemoryStatus): MemoryVerdict {+ switch (status) {+ case "unknown":+ return { verdict: "unknown", cause: null };+ case "fits":+ return { verdict: "fits", cause: null };+ case "context-exceeds":+ return { verdict: "exceeds", cause: "context" };+ case "model-exceeds":+ return { verdict: "exceeds", cause: "irreducible" };+ }+}diff --git a/studio/frontend/src/lib/model-memory.ts b/studio/frontend/src/lib/model-memory.tsindex d9cdb9e8cb8..11ba5fc6db0 100644--- a/studio/frontend/src/lib/model-memory.ts+++ b/studio/frontend/src/lib/model-memory.ts@@ -14,7 +14,11 @@* the fit badge on a row can't contradict each other.*/-import { VRAM_HEADROOM_RATIO } from "@/lib/gguf-fit";+import {+ DEFAULT_VRAM_BUDGET_FRACTION,+ PRESSURE_CRITICAL_PCT,+ PRESSURE_HIGH_PCT,+} from "./memory/thresholds.ts";const BYTES_PER_GB = 1024 ** 3;@@ -82,10 +86,12 @@ export interface ModelMemoryInput {*/export type ModelMemoryPressure = "normal" | "high" | "critical";-/** Fill fraction (%) at which the bar leaves the accent colour. */-export const PRESSURE_HIGH_PCT = 80;-/** Fill fraction (%) at which the bar turns destructive. */-export const PRESSURE_CRITICAL_PCT = 90;+// Shared with the Load Model panel's thresholds so the two surfaces colour one+// load the same way. See src/lib/memory/thresholds.ts.+export {+ PRESSURE_HIGH_PCT,+ PRESSURE_CRITICAL_PCT,+} from "./memory/thresholds.ts";export type ModelMemoryStatus =/** Not enough information to draw anything. */@@ -146,6 +152,33 @@ function toGb(bytes?: number | null): number {export function computeModelMemory(input: ModelMemoryInput,): ModelMemorySegments {+ // A figure that is not a number cannot produce a verdict, only a confident+ // looking one. `toGb` passes Infinity straight through, so an infinite+ // weightsBytes reached the status ladder and came out "model-exceeds": a full+ // red bar reading "Larger than VRAM" beside a weights figure of "0 GiB",+ // because the formatter clamps what the verdict did not. JSON.parse turns+ // 1e999 into Infinity, so a malformed response gets there without trying.+ //+ // `classifyMemoryFit` on the panel already answers "unknown" for exactly these+ // inputs, so this was also the two surfaces disagreeing about the same bytes.+ // Null and undefined are NOT covered here: those mean "has not arrived yet",+ // which is an ordinary state the segments below already handle.+ if (+ [+ input.weightsBytes,+ input.kvBytes,+ input.specBytes,+ input.computeBytes,+ input.gpuTotalBytes,+ input.gpuFloorBytes,+ input.specFixedBytes,+ input.gpuGb,+ input.nCtx,+ input.budgetFraction,+ ].some((value) => typeof value === "number" && !Number.isFinite(value))+ ) {+ return EMPTY;+ }const gpuGb = input.gpuGb ?? 0;const modelGb = toGb(input.weightsBytes);if (gpuGb <= 0 || modelGb <= 0) return EMPTY;@@ -155,13 +188,18 @@ export function computeModelMemory(if (input.gpuTotalBytes === 0) return EMPTY;// The loader's own budget when the caller knows it, so the bar warns at the- // line admission actually draws. VRAM_HEADROOM_RATIO stays the fallback: it- // is what the fit badge on the same row judges against, and it is the only- // answer available before the settings request lands.+ // line admission actually draws.+ //+ // The fallback is DEFAULT_VRAM_BUDGET_FRACTION (0.97), matching the loader's+ // _CTX_FIT_VRAM_FRACTION and the Load Model panel. It used to be+ // VRAM_HEADROOM_RATIO (0.90), which is not a safer guess but a measured wrong+ // one: llama_cpp.py records "0.90 dropped 91-94% fits to CPU offload, #5106".+ // Warning at a line admission does not draw is the same class of wrong answer+ // as a false "fits", pointing the other way.const fraction =input.budgetFraction && input.budgetFraction > 0? input.budgetFraction- : VRAM_HEADROOM_RATIO;+ : DEFAULT_VRAM_BUDGET_FRACTION;const budgetGb = gpuGb * fraction;const kvGb = toGb(input.kvBytes) + toGb(input.computeBytes);const specGb = toGb(input.specBytes);@@ -516,24 +554,23 @@ export function estimateIsUnsized(estimate: {);}-/** Compact label for a per-token KV rate, which lands in KB or MB. */-export function formatKvRate(bytes: number): string {- if (bytes <= 0) return "0 KB";- const kb = bytes / 1024;- if (kb < 1024) return `${kb < 10 ? kb.toFixed(1) : Math.round(kb)} KB`;- const mb = kb / 1024;- return `${mb < 10 ? mb.toFixed(1) : Math.round(mb)} MB`;-}+// The unit formatting now lives in src/lib/memory/format.ts, shared with the+// Load Model panel. Re-exported here because this module is the bar's entry+// point and its call sites are unchanged.+//+// formatKvRate's labels have changed from KB/MB to KiB/MiB: the divide was+// always by 1024, so the readout was printing kibibytes labelled as kilobytes,+// the same mislabel #9570 fixed one scale up.+export { formatKvRate } from "./memory/format.ts";/*** Compact label for the bar's readout ("7.2 GiB").*- * GiB, not GB: every figure here is a binary divide. Weights and KV come from- * bytes / 1024**3, and gpuGb arrives from the backend as- * props.total_memory / 1024**3 with nothing subtracting a budget on the way, so- * calling any of them GB overstates each by 7.4% (#9570).+ * @deprecated Prefer `formatGiB` from `@/lib/memory/format`, whose name says+ * which unit it takes. This alias exists because there used to be a SECOND+ * exported `formatMemoryGb`, in `model-config/memory-fit.ts`, which took BYTES+ * rather than gigabytes -- the same name and the same `(number) => string`+ * signature for two incompatible things, so importing the wrong one was off by+ * 1024^3 and still typechecked.*/-export function formatMemoryGb(gb: number): string {- if (gb <= 0) return "0 GiB";- return `${gb < 10 ? gb.toFixed(1) : Math.round(gb)} GiB`;-}+export { formatGiB as formatMemoryGb } from "./memory/format.ts";diff --git a/studio/frontend/tests/memory-cross-surface-matrix.test.ts b/studio/frontend/tests/memory-cross-surface-matrix.test.tsnew file mode 100644index 00000000000..bd12ce4abf0--- /dev/null+++ b/studio/frontend/tests/memory-cross-surface-matrix.test.ts@@ -0,0 +1,303 @@+// 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 property this PR exists to establish, checked over the whole hardware+// matrix rather than on one host: the Load Model panel and the Hub memory bar+// cannot describe one load differently.+//+// `model-memory-hardware-matrix.test.ts` already pins what the BAR does with+// each kind of budget. This file is about the two surfaces AGREEING, which is a+// different question and was not previously asked anywhere: each surface was+// self-consistent the whole time, and that was never the problem.+//+// The matrix is [linux, wsl, win32, darwin] x nine device inventories, minus the+// physically impossible cells (Apple unified memory on Windows). Every cell is+// checked against six properties, so this is ~200 assertions rather than nine+// hand-written cases.++import assert from "node:assert/strict";+import test from "node:test";++import { registerBundlerResolver } from "./helpers/kit.ts";++registerBundlerResolver();++const { computeModelMemory } = await import("../src/lib/model-memory.ts");+const { resolveMemoryCapacityGb } = await import("../src/hooks/gpu-vram.ts");+const { classifyMemoryFit } = await import("../src/lib/memory/verdict.ts");+const { formatGiB, formatBytesGiB, formatKvRate } = await import(+ "../src/lib/memory/format.ts"+);+const { DEFAULT_VRAM_BUDGET_FRACTION } = await import(+ "../src/lib/memory/thresholds.ts"+);++const GB = 1024 ** 3;++type Platform = "linux" | "wsl" | "win32" | "darwin";+const ALL: Platform[] = ["linux", "wsl", "win32", "darwin"];++// Matches MemoryCapacityDevice in src/hooks/gpu-vram.ts. sharedMemory is+// required there, so it is normalised at the call site rather than left optional+// here, which tsc -b catches even though the tests pass either way.+interface Device {+ memoryTotalGb: number;+ sharedMemory?: boolean;+}++interface Host {+ label: string;+ devices: Device[];+ systemRamTotalGb: number;+ /** Any device reports a unified pool (Apple, ROCm APU). */+ unifiedMemory: boolean;+ /** Which platforms this inventory can physically occur on. */+ platforms: Platform[];+}++// Nine inventories spanning [NVIDIA, AMD, Intel, Apple, none] and+// [discrete, integrated, unified, mixed, multi].+const HOSTS: Host[] = [+ {+ label: "NVIDIA single 24 GiB",+ devices: [{ memoryTotalGb: 24 }],+ systemRamTotalGb: 64,+ unifiedMemory: false,+ // No CUDA on Apple silicon since 10.13; treated as not occurring.+ platforms: ["linux", "wsl", "win32"],+ },+ {+ label: "NVIDIA dual 24 GiB",+ devices: [{ memoryTotalGb: 24 }, { memoryTotalGb: 24 }],+ systemRamTotalGb: 128,+ unifiedMemory: false,+ platforms: ["linux", "wsl", "win32"],+ },+ {+ label: "AMD ROCm discrete 16 GiB",+ devices: [{ memoryTotalGb: 16 }],+ systemRamTotalGb: 64,+ unifiedMemory: false,+ platforms: ["linux", "wsl", "win32"],+ },+ {+ label: "ROCm APU 48 GiB of a 96 GiB pool",+ devices: [{ memoryTotalGb: 48, sharedMemory: true }],+ systemRamTotalGb: 96,+ unifiedMemory: true,+ // Strix Halo class parts; not Apple.+ platforms: ["linux", "wsl", "win32"],+ },+ {+ label: "AMD Vulkan iGPU 12 GiB capped view of RAM",+ devices: [{ memoryTotalGb: 12, sharedMemory: true }],+ systemRamTotalGb: 32,+ unifiedMemory: false,+ platforms: ["linux", "wsl", "win32"],+ },+ {+ label: "Intel iGPU 8 GiB shared",+ devices: [{ memoryTotalGb: 8, sharedMemory: true }],+ systemRamTotalGb: 32,+ unifiedMemory: false,+ platforms: ["linux", "wsl", "win32"],+ },+ {+ label: "Apple Silicon 64 GiB unified",+ devices: [{ memoryTotalGb: 64, sharedMemory: true }],+ systemRamTotalGb: 64,+ unifiedMemory: true,+ platforms: ["darwin"],+ },+ {+ label: "mixed dGPU 16 GiB + iGPU 12 GiB",+ devices: [{ memoryTotalGb: 16 }, { memoryTotalGb: 12, sharedMemory: true }],+ systemRamTotalGb: 96,+ unifiedMemory: false,+ platforms: ["linux", "wsl", "win32"],+ },+ {+ label: "CPU only",+ devices: [],+ systemRamTotalGb: 32,+ unifiedMemory: false,+ platforms: ALL,+ },+];++// Footprints spanning comfortably-under, near the line, and hopeless. The 22/24+// case is the one that lands between 0.90 and 0.97 of a 24 GiB card, which is+// exactly the band this PR's budget change moves.+const FOOTPRINTS = [+ { label: "tiny", weightsBytes: 2 * GB, kvBytes: 1 * GB },+ { label: "half", weightsBytes: 8 * GB, kvBytes: 4 * GB },+ { label: "at the 0.90/0.97 seam", weightsBytes: 20 * GB, kvBytes: 2 * GB },+ { label: "hopeless", weightsBytes: 180 * GB, kvBytes: 40 * GB },+];++function capacityFor(host: Host) {+ return resolveMemoryCapacityGb({+ pinnedDevices: [],+ hostDevices: host.devices.map((d) => ({+ memoryTotalGb: d.memoryTotalGb,+ sharedMemory: d.sharedMemory === true,+ })),+ hostGpuTotalGb: host.devices.reduce((n, d) => n + d.memoryTotalGb, 0),+ hostSharesSystemRam: host.devices.some((d) => d.sharedMemory === true),+ systemRamTotalGb: host.systemRamTotalGb,+ unifiedMemory: host.unifiedMemory,+ gpuBudgetFraction: DEFAULT_VRAM_BUDGET_FRACTION,+ });+}++function cells() {+ const out: { host: Host; platform: Platform; fp: (typeof FOOTPRINTS)[number] }[] = [];+ for (const host of HOSTS) {+ for (const platform of host.platforms) {+ for (const fp of FOOTPRINTS) out.push({ host, platform, fp });+ }+ }+ return out;+}++test("the matrix is actually a matrix", () => {+ // A property suite that silently shrank to two cells is worse than none.+ const n = cells().length;+ assert.ok(n >= 100, `expected a full product, got ${n} cells`);+});++test("P1: no cell ever reports a fit for a footprint over its budget", () => {+ for (const { host, platform, fp } of cells()) {+ const cap = capacityFor(host);+ const bar = computeModelMemory({+ weightsBytes: fp.weightsBytes,+ kvBytes: fp.kvBytes,+ gpuGb: cap.gpuCapacityGb,+ budgetFraction: DEFAULT_VRAM_BUDGET_FRACTION,+ contextIsAutoFitted: false,+ });+ if (bar.status === "unknown") continue;+ const totalGb = (fp.weightsBytes + fp.kvBytes) / GB;+ if (totalGb > bar.budgetGb) {+ assert.notEqual(+ bar.status,+ "fits",+ `${host.label} / ${platform} / ${fp.label}: ${totalGb.toFixed(1)} GiB ` ++ `reported as fitting a ${bar.budgetGb.toFixed(1)} GiB budget`,+ );+ }+ }+});++test("P2: the bar and the panel never contradict each other", () => {+ // The property the whole PR is for. The bar's status and the panel's verdict+ // are different vocabularies over the same question, so they are compared by+ // direction: if one says the load does not fit, the other must not say it does.+ for (const { host, platform, fp } of cells()) {+ const cap = capacityFor(host);+ const bar = computeModelMemory({+ weightsBytes: fp.weightsBytes,+ kvBytes: fp.kvBytes,+ gpuGb: cap.gpuCapacityGb,+ budgetFraction: DEFAULT_VRAM_BUDGET_FRACTION,+ contextIsAutoFitted: false,+ });+ const panel = classifyMemoryFit(fp.weightsBytes + fp.kvBytes, cap.gpuCapacityGb);+ if (bar.status === "unknown" || panel === "unknown") continue;+ const barSaysNo = bar.status !== "fits";+ const panelSaysNo = panel === "exceeds";+ if (panelSaysNo) {+ assert.ok(+ barSaysNo,+ `${host.label} / ${platform} / ${fp.label}: panel says exceeds, bar says fits`,+ );+ }+ }+});++test("P3: one byte count formats identically wherever it is printed", () => {+ // Two formatters, two units in, one label out. This is the collision that used+ // to exist as two functions with the same name.+ for (const gib of [0.5, 2.33, 7.24, 24, 174, 1024]) {+ assert.equal(formatBytesGiB(gib * GB).endsWith(" GiB"), true);+ assert.equal(formatGiB(gib).endsWith(" GiB"), true);+ // The same quantity, so the numeric part must agree once rounding is undone.+ const a = Number.parseFloat(formatBytesGiB(gib * GB));+ const b = Number.parseFloat(formatGiB(gib));+ assert.ok(+ Math.abs(a - b) <= 0.55,+ `${gib} GiB formats as ${a} one way and ${b} the other`,+ );+ }+});++test("P4: a shared or unified pool is never counted twice", () => {+ for (const host of HOSTS) {+ const cap = capacityFor(host);+ if (host.devices.length === 0) continue;+ const ceiling = host.unifiedMemory+ ? host.systemRamTotalGb+ : host.systemRamTotalGb ++ host.devices.reduce((n, d) => n + (d.sharedMemory ? 0 : d.memoryTotalGb), 0);+ assert.ok(+ cap.totalCapacityGb <= ceiling + 0.01,+ `${host.label}: ceiling ${cap.totalCapacityGb} exceeds the ${ceiling} GiB ` ++ `the machine physically has, so a pool was counted twice`,+ );+ }+});++test("P5: a CPU-only host draws nothing rather than a zero-width bar", () => {+ for (const platform of ALL) {+ const host = HOSTS.find((h) => h.label === "CPU only")!;+ const cap = capacityFor(host);+ const bar = computeModelMemory({+ weightsBytes: 4 * GB,+ kvBytes: 1 * GB,+ gpuGb: cap.gpuCapacityGb,+ });+ assert.equal(bar.status, "unknown", `${platform}: CPU-only host drew a VRAM bar`);+ assert.equal(bar.budgetGb, 0);+ }+});++test("P6: no cell leaks a number that does not exist into a label", () => {+ const bad = /NaN|Infinity|undefined|-\d/;+ for (const { host, platform, fp } of cells()) {+ const cap = capacityFor(host);+ const bar = computeModelMemory({+ weightsBytes: fp.weightsBytes,+ kvBytes: fp.kvBytes,+ gpuGb: cap.gpuCapacityGb,+ budgetFraction: DEFAULT_VRAM_BUDGET_FRACTION,+ });+ for (const label of [+ formatGiB(bar.totalGb),+ formatGiB(bar.budgetGb),+ formatGiB(bar.modelGb),+ formatBytesGiB(fp.weightsBytes),+ formatKvRate(bar.kvBytesPerToken),+ ]) {+ assert.doesNotMatch(+ label,+ bad,+ `${host.label} / ${platform} / ${fp.label}: rendered "${label}"`,+ );+ }+ }+});++test("hostile and malformed figures never become a confident verdict", () => {+ // JSON.parse turns 1e999 into Infinity, and a `?? 0` default never sees it.+ for (const evil of [Number.NaN, Number.POSITIVE_INFINITY, -1, 0]) {+ const bar = computeModelMemory({+ weightsBytes: evil,+ kvBytes: evil,+ gpuGb: 24,+ budgetFraction: DEFAULT_VRAM_BUDGET_FRACTION,+ });+ assert.equal(bar.status, "unknown", `weights=${evil} produced ${bar.status}`);+ assert.equal(classifyMemoryFit(evil, 24), "unknown");+ assert.equal(classifyMemoryFit(8 * GB, evil), "unknown");+ }+});diff --git a/studio/frontend/tests/memory-fit.test.ts b/studio/frontend/tests/memory-fit.test.tsindex 97c6aa46b17..ba43f1d0500 100644--- a/studio/frontend/tests/memory-fit.test.ts+++ b/studio/frontend/tests/memory-fit.test.ts@@ -415,12 +415,17 @@ test("no combination of garbage throws or produces a verdict outside the four",// formatMemoryGbtest("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");+ // GiB, not GB. The divide was always by 1024**3, so every figure this printed+ // was a gibibyte value wearing a gigabyte label -- 7.4% high, on seven figures+ // of the Load Model panel. Same defect #9570 fixed elsewhere; the guard test+ // could not see this one because its regex only matches interpolations naming+ // a `*TotalGb`.+ assert.equal(formatMemoryGb(24 * GB), "24.00 GiB");+ assert.equal(formatMemoryGb(0), "0.00 GiB");+ assert.equal(formatMemoryGb(-5 * GB), "0.00 GiB");+ assert.equal(formatMemoryGb(Number.NaN), "0.00 GiB");+ assert.equal(formatMemoryGb(Number.POSITIVE_INFINITY), "0.00 GiB");+ assert.equal(formatMemoryGb(undefined as unknown as number), "0.00 GiB");});// ---------------------------------------------------------------------------@@ -471,7 +476,7 @@ test("the draft cache note reads its OWN placement, not the target cache's", ()// 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");+ assert.equal(resolveDraftCacheNote(1 * GB, 4 * GB), "1.00 GiB 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");diff --git a/studio/frontend/tests/memory-shared-core.test.ts b/studio/frontend/tests/memory-shared-core.test.tsnew file mode 100644index 00000000000..019627b16c0--- /dev/null+++ b/studio/frontend/tests/memory-shared-core.test.ts@@ -0,0 +1,386 @@+// 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 shared presentation core, and the property that justifies it: the Load+// Model panel and the Hub memory bar cannot describe one load differently.+//+// Before this module the two surfaces disagreed in every category that decides+// what a user reads -- unit labels, rounding, fit thresholds, the fraction of a+// card a load may claim, and the verdict vocabulary itself -- while being fed+// byte-identical figures from one backend planner. Each difference on its own+// was defensible; together they meant the same model could read as fitting on+// one screen and not on the other.+//+// These tests are written against the SHARED module rather than through either+// surface, because a test that goes through one surface only proves that+// surface is self-consistent, which was never the problem.++import assert from "node:assert/strict";+import test from "node:test";++import {+ formatBytesGiB,+ formatGiB,+ formatKvRate,+} from "../src/lib/memory/format.ts";+import {+ DEFAULT_VRAM_BUDGET_FRACTION,+ MEMORY_FIT_TIGHT_RATIO,+ PRESSURE_CRITICAL_PCT,+ PRESSURE_HIGH_PCT,+} from "../src/lib/memory/thresholds.ts";+import {+ classifyMemoryFit,+ fromModelMemoryStatus,+ toModelMemoryStatus,+ worseMemoryFit,+} from "../src/lib/memory/verdict.ts";++const GIB = 1024 ** 3;++// ---------------------------------------------------------------------------+// Units++test("every formatter names a BINARY unit, because every divide is binary", () => {+ // The whole point of the rename. Each of these divides by 1024, so each must+ // say so; the panel's old formatter divided by 1024**3 and said "GB".+ assert.equal(formatGiB(7.24), "7.2 GiB");+ assert.equal(formatGiB(24), "24 GiB");+ assert.equal(formatBytesGiB(24 * GIB), "24.00 GiB");+ assert.equal(formatKvRate(6234), "6.1 KiB");+ assert.equal(formatKvRate(1024 * 1024 * 3), "3.0 MiB");+});++test("the two size formatters take DIFFERENT units, and say so in their names", () => {+ // This is the bug the rename exists to prevent: the old pair were both called+ // formatMemoryGb, both `(number) => string`, and one took bytes while the+ // other took gibibytes. Passing the wrong one was off by 1024^3 and+ // typechecked cleanly.+ const oneGibAsBytes = GIB;+ const oneGib = 1;+ assert.equal(formatBytesGiB(oneGibAsBytes), "1.00 GiB");+ assert.equal(formatGiB(oneGib), "1.0 GiB");+ // Feeding bytes to the gibibyte formatter is the mistake, and it produces an+ // absurd number rather than a plausible one, which is the best available+ // outcome now that the names differ.+ assert.notEqual(formatGiB(oneGibAsBytes), "1.0 GiB");+});++test("no formatter renders a number that does not exist", () => {+ // Every figure here comes off the wire. "NaN GiB" and "-3.0 GiB" both read as+ // measurements rather than as the missing readings they are.+ for (const bad of [Number.NaN, Number.POSITIVE_INFINITY, -5, undefined]) {+ assert.equal(formatGiB(bad as number), "0 GiB");+ assert.equal(formatBytesGiB(bad as number), "0.00 GiB");+ assert.equal(formatKvRate(bad as number), "0 KiB");+ }+});++// ---------------------------------------------------------------------------+// Thresholds++test("the budget fraction matches what the loader admits at", () => {+ // 0.97 is _CTX_FIT_VRAM_FRACTION in core/inference/llama_cpp.py. A verdict+ // drawn against a different fraction than admission uses is wrong by+ // construction, in whichever direction it differs.+ assert.equal(DEFAULT_VRAM_BUDGET_FRACTION, 0.97);+ // Specifically NOT 0.90, which the bar used. llama_cpp.py records that value+ // as measured and reverted: "0.90 dropped 91-94% fits to CPU offload, #5106".+ assert.notEqual(DEFAULT_VRAM_BUDGET_FRACTION, 0.9);+});++test("the fit threshold and the pressure ramp stay distinct", () => {+ // These measure different things -- "will it fit" against "how full does it+ // look" -- so they are allowed to differ. What they are NOT allowed to do is+ // differ per surface, which is what collecting them here prevents.+ assert.equal(MEMORY_FIT_TIGHT_RATIO, 0.85);+ assert.equal(PRESSURE_HIGH_PCT, 80);+ assert.equal(PRESSURE_CRITICAL_PCT, 90);+ assert.ok(PRESSURE_HIGH_PCT < PRESSURE_CRITICAL_PCT);+});++// ---------------------------------------------------------------------------+// Verdicts++test("a figure that does not exist is never a confident fit", () => {+ // `<= 0` alone does not cover it: NaN fails every comparison, so `NaN <= 0` is+ // false and the ratio test falls through to "fits" -- a green verdict printed+ // from a number that is not there. JSON.parse turns 1e999 into Infinity, so a+ // malformed response reaches this without trying.+ assert.equal(classifyMemoryFit(Number.NaN, 24), "unknown");+ assert.equal(classifyMemoryFit(8 * GIB, Number.NaN), "unknown");+ assert.equal(classifyMemoryFit(Number.POSITIVE_INFINITY, 24), "unknown");+ assert.equal(classifyMemoryFit(8 * GIB, 0), "unknown");+});++test("the bands land where the thresholds say", () => {+ assert.equal(classifyMemoryFit(8 * GIB, 24), "fits");+ // Just over 85% of 24 GiB.+ assert.equal(classifyMemoryFit(21 * GIB, 24), "tight");+ assert.equal(classifyMemoryFit(25 * GIB, 24), "exceeds");+});++test("unknown never erases a real verdict", () => {+ // One half being unmeasurable must not silently improve the other half's+ // answer.+ assert.equal(worseMemoryFit("unknown", "exceeds"), "exceeds");+ assert.equal(worseMemoryFit("fits", "tight"), "tight");+ assert.equal(worseMemoryFit("tight", "exceeds"), "exceeds");+});++test("neither surface loses a distinction it used to make", () => {+ // The panel's contribution: TIGHT, the warning before anything is wrong.+ assert.equal(classifyMemoryFit(21 * GIB, 24), "tight");+ // The bar's contribution: WHY it exceeds, which decides the remedy.+ assert.equal(+ toModelMemoryStatus({ verdict: "exceeds", cause: "context" }),+ "context-exceeds",+ );+ assert.equal(+ toModelMemoryStatus({ verdict: "exceeds", cause: "irreducible" }),+ "model-exceeds",+ );+});++test("tight folds into fits for the bar, which colours that band instead", () => {+ // The bar has no "tight" status; it expresses the same band through its+ // pressure ramp. Folding it into "fits" here loses nothing that renders.+ assert.equal(toModelMemoryStatus({ verdict: "tight", cause: null }), "fits");+ assert.equal(toModelMemoryStatus({ verdict: "fits", cause: null }), "fits");+ assert.equal(toModelMemoryStatus({ verdict: "unknown", cause: null }), "unknown");+});++test("the bar's vocabulary round-trips, and is honest about what it loses", () => {+ for (const status of ["unknown", "fits", "context-exceeds", "model-exceeds"] as const) {+ assert.equal(toModelMemoryStatus(fromModelMemoryStatus(status)), status);+ }+ // The lossy direction, asserted so it is a known property rather than a+ // surprise: the bar never recorded "tight", so it cannot be recovered.+ assert.equal(fromModelMemoryStatus("fits").verdict, "fits");+});++// ---------------------------------------------------------------------------+// The fit badge draws against the same budget as the bar (Codex P2 on 9830)++test("the Hub fit badge and the memory bar share one budget constant", async () => {+ // These render on the SAME ROW, so two budgets meant two verdicts for one+ // model. gguf-fit.ts held 0.90 while the bar used the loader's 0.97, which is+ // what admission actually applies.+ const { VRAM_HEADROOM_RATIO } = await import("../src/lib/gguf-fit.ts");+ assert.equal(+ VRAM_HEADROOM_RATIO,+ DEFAULT_VRAM_BUDGET_FRACTION,+ "the badge and the bar are judging against different budgets again",+ );+});++test("aligning the constant narrows the badge/bar gap without closing it", async () => {+ // Honest about what the fix buys. Measured over 15-24 GiB on a 24 GiB card the+ // disagreement count goes 11/19 -> 8/19. The residual 8 are the ESTIMATOR+ // difference -- gguf-fit scores `size * 1.15 + 1 GB` while the bar uses the+ // planner's real figures -- so sharing a constant cannot remove them, and+ // claiming otherwise would be the wrong lesson to leave here.+ const { classifyGgufFit, requiredGgufMemoryGb } = await import(+ "../src/lib/gguf-fit.ts"+ );+ const bytes = 20 * 1024 ** 3;+ // The badge still scores a 20 GiB file at 24.0 GiB of "required" memory.+ assert.ok(+ requiredGgufMemoryGb(bytes) > 20,+ "the badge's heuristic no longer inflates, so this note is stale",+ );+ // So on a 24 GiB card it still refuses a file the bar happily fits.+ assert.notEqual(classifyGgufFit(bytes, { gpuGb: 24, systemRamGb: 64 }), "fits");+});++// ---------------------------------------------------------------------------+// The badge must score against the SAVED budget, not just the default+// (Codex P2 on 9830)++test("a saved VRAM Budget moves the badge, not only the bar", async () => {+ // Sharing the default constant fixed the loading and old-backend case. It did+ // not fix the case where the user has actually saved a fraction: the badge+ // still applied 0.97 while the bar beside it consumed the live value from+ // `use-model-memory.ts`. Measured on a 24 GiB card with a saved 0.90, where the+ // loader admits at 21.6 GiB and the default would score against 23.28 GiB.+ const { classifyGgufFit, requiredGgufMemoryGb } = await import(+ "../src/lib/gguf-fit.ts"+ );+ const bytes = 18 * 1024 ** 3;+ const required = requiredGgufMemoryGb(bytes);+ // Between the two budgets, which is the whole window in which they can differ.+ assert.ok(+ required > 24 * 0.9 && required <= 24 * DEFAULT_VRAM_BUDGET_FRACTION,+ `fixture must sit between the two budgets; required=${required}`,+ );+ assert.equal(+ classifyGgufFit(bytes, { gpuGb: 24, systemRamGb: 64, budgetFraction: 0.9 }),+ "marginal",+ "a saved 0.90 must push this over the line the loader draws",+ );+ assert.equal(+ classifyGgufFit(bytes, { gpuGb: 24, systemRamGb: 64 }),+ "fits",+ "and without a saved fraction the default still applies, unchanged",+ );+});++test("an absent or unusable budget falls back rather than refusing everything", async () => {+ // `budgetFraction` arrives from a settings route. Absent is the normal state+ // during the first paint and the permanent state on a backend predating the+ // route, so it must mean "use the default" and not "the whole card" (which+ // would admit loads the loader refuses) or "0" (which would refuse all of+ // them).+ const { classifyGgufFit } = await import("../src/lib/gguf-fit.ts");+ const bytes = 18 * 1024 ** 3;+ const withDefault = classifyGgufFit(bytes, { gpuGb: 24, systemRamGb: 64 });+ for (const bad of [undefined, 0, -1, 1.5, Number.NaN, Number.POSITIVE_INFINITY]) {+ assert.equal(+ classifyGgufFit(bytes, {+ gpuGb: 24,+ systemRamGb: 64,+ budgetFraction: bad as number,+ }),+ withDefault,+ `budgetFraction=${String(bad)} must fall back to the shared default`,+ );+ }+ // And 1.0 is a legitimate saved value, not a rejected one: it means the user+ // allowed the whole card.+ assert.equal(+ classifyGgufFit(bytes, { gpuGb: 24, systemRamGb: 64, budgetFraction: 1 }),+ "fits",+ );+});++test("the badge's call sites read the live fraction", async () => {+ // The classifier taking a fraction is worthless if nothing passes one. Asserted+ // on source because these are .tsx call sites the runner cannot render.+ const { readFileSync } = await import("node:fs");+ const card = readFileSync(+ new URL(+ "../src/features/hub/catalog/gguf-download-card.tsx",+ import.meta.url,+ ),+ "utf8",+ );+ assert.match(+ card,+ /useVramBudgetFraction\(\)/,+ "the Hub card must read the saved budget, not rely on the default",+ );+ // Every fit-scoring call on the row, not just the badge: the sort ranks with+ // the same classifier and would otherwise order rows against a different line.+ const passes = card.match(/budgetFraction,/g) ?? [];+ assert.ok(+ passes.length >= 3,+ `expected the fraction at the badge, the sort and the menu; found ${passes.length}`,+ );+});++test("the offload band credits the budget, not the whole card", async () => {+ // Once layers spill, what the GPU can still hold is what it is ALLOWED to hold.+ // The reserve is precisely what the model and KV cache may not use, so adding+ // the raw card to the RAM allowance invented capacity the loader will not give.+ //+ // Driven at 0.80, the LEGAL minimum (VRAM_FRACTION_MIN in+ // vram_budget_settings.py). The originally reported example used 0.50, which+ // the settings route rejects, so the real defect is smaller than it looked --+ // 4.8 GiB of phantom GPU on a 24 GiB card -- and still large enough to mislabel+ // four whole quant sizes.+ const { classifyGgufFit, requiredGgufMemoryGb } = await import(+ "../src/lib/gguf-fit.ts"+ );+ const input = { gpuGb: 24, systemRamGb: 16, budgetFraction: 0.8 };+ for (const sizeGb of [23, 24, 25, 26]) {+ const bytes = sizeGb * 1024 ** 3;+ const required = requiredGgufMemoryGb(bytes);+ // Beyond what budget plus offloadable RAM can hold: 19.2 + 8 = 27.2.+ assert.ok(required > 27.2, `fixture ${sizeGb} must exceed the real ceiling`);+ assert.equal(+ classifyGgufFit(bytes, input),+ "oom",+ `a ${sizeGb} GiB quant needs ${required.toFixed(2)} GiB, and 0.80 of a ` ++ "24 GiB card plus half of 16 GiB of RAM cannot hold it",+ );+ }+});++test("marginal stays on the raw card, or the band cannot be reached", async () => {+ // Deliberately NOT scored against the budget. `fits` already returns for+ // everything at or under the budget, so scoring this against the budget too+ // would make the branch dead code. The band means "over your budget, still+ // card-sized", which is a warning and not a promise of admission.+ const { classifyGgufFit } = await import("../src/lib/gguf-fit.ts");+ // 20 GiB needs 24.00 GiB: over 0.80 of the card (19.2) and exactly at the card.+ assert.equal(+ classifyGgufFit(20 * 1024 ** 3, {+ gpuGb: 24,+ systemRamGb: 16,+ budgetFraction: 0.8,+ }),+ "marginal",+ "a load between the budget and the card must still be reachable",+ );+});++test("every fit-scoring surface reads the saved budget, not just the Hub card", async () => {+ // The Hub download card got the live fraction; the On Device card did not, and+ // it renders a memory bar (which uses the saved value) directly above a quant+ // menu sorted by classifyGgufFit (which did not). One card, two budgets.+ const { readFileSync } = await import("node:fs");+ const read = (rel: string) =>+ readFileSync(new URL(rel, import.meta.url), "utf8");+ for (const rel of [+ "../src/features/hub/catalog/gguf-download-card.tsx",+ "../src/features/hub/catalog/local-on-device-card.tsx",+ ]) {+ const source = read(rel);+ assert.match(+ source,+ /useVramBudgetFraction\(\)/,+ `${rel} scores GGUF fit but does not read the saved VRAM Budget`,+ );+ assert.match(+ source,+ /budgetFraction,/,+ `${rel} reads the fraction but never passes it to the classifier`,+ );+ }+});++test("the budget read is shared, not one request per mounted card", async () => {+ // loadVramBudgetSettings deliberately has no read-through cache and clears its+ // shared promise once each request settles, so it coalesces only callers whose+ // requests overlap in time. A Hub catalog mounts a card per repo progressively+ // through scrolling and filtering, so a per-card call is a GET per card, and a+ // 404 per card on a backend predating the route.+ const source = await import("node:fs").then(({ readFileSync }) =>+ readFileSync(+ new URL("../src/hooks/use-vram-budget-fraction.ts", import.meta.url),+ "utf8",+ ),+ );+ assert.match(+ source,+ /let cachedFraction/,+ "the fraction must be cached module-wide; it is one host-wide value",+ );+ assert.match(+ source,+ /let inFlight/,+ "cards mounting in the same tick must share one request",+ );+ assert.match(+ source,+ /routeAbsent/,+ "a 404 must be remembered, or every card retries a route that does not exist",+ );+ // And the cache must still be invalidated by a save, or a shared cache is just+ // a stale one.+ assert.match(+ source,+ /subscribeVramBudgetSettings\(\([\s\S]{0,200}?cachedFraction = settings\.fraction/,+ "the change event must refresh the cache, or a save never reaches the cards",+ );+});diff --git a/studio/frontend/tests/memory-unified-apu.test.ts b/studio/frontend/tests/memory-unified-apu.test.tsnew file mode 100644index 00000000000..49819c3a330--- /dev/null+++ b/studio/frontend/tests/memory-unified-apu.test.ts@@ -0,0 +1,456 @@+// 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 ROCm APU shares one memory pool between the GPU and the rest of the system,+// exactly as Apple Silicon does. The Load Model panel decided that question from+// `usePlatformStore(s => s.appleSilicon)`, so on an APU it charged the pool as+// discrete VRAM PLUS host RAM: the same bytes counted twice, and a verdict of+// "fits" for a load that cannot open.+//+// The signal was already there. `use-gpu-info.ts` derives `unifiedMemory` from+// the backend's per-device `unified_memory` flag, which the ROCm probe sets, and+// the Hub memory bar already abstains on it. Only the panel was reading the+// platform instead of the hardware.+//+// These tests are on `resolveMemoryCapacityGb` rather than on the component,+// because that is where the double count happens and it is reachable from the+// test runner. The component's part is one line: which flag it passes.++import assert from "node:assert/strict";+import test from "node:test";+import { readFileSync } from "node:fs";++import {+ aggregateUsableFreeVramGb,+ resolveMemoryCapacityGb,+} from "../src/hooks/gpu-vram.ts";++const PANEL = new URL(+ "../src/features/model-picker/components/model-config-page.tsx",+ import.meta.url,+);++// A Strix Halo style APU: one 96 GiB pool, reported as GPU-visible memory and as+// system RAM, because it is the same silicon.+const APU = { memoryTotalGb: 48, sharedMemory: true };+const APU_HOST = {+ hostGpuTotalGb: 48,+ hostSharesSystemRam: true,+ systemRamTotalGb: 96,+ pinnedDevices: [],+ hostDevices: [APU],+};++test("an APU's pool is counted once, not as VRAM plus RAM", () => {+ const unified = resolveMemoryCapacityGb({ ...APU_HOST, unifiedMemory: true });+ assert.equal(unified.singleMemoryPool, true);+ // The ceiling is the machine's memory, not the machine's memory plus a copy of+ // the part of it the GPU can see.+ assert.ok(+ unified.totalCapacityGb <= 96,+ `one pool cannot exceed the machine's 96 GiB, got ${unified.totalCapacityGb}`,+ );+});++test("reading the platform instead of the hardware double counts the pool", () => {+ // The state the panel was in on an APU: unifiedMemory false, because the host+ // is not Apple. This is the bug, pinned as a contrast so the assertion above+ // is measuring something rather than restating a default.+ const asDiscrete = resolveMemoryCapacityGb({ ...APU_HOST, unifiedMemory: false });+ const unified = resolveMemoryCapacityGb({ ...APU_HOST, unifiedMemory: true });+ assert.notEqual(+ asDiscrete.totalCapacityGb,+ unified.totalCapacityGb,+ "the unified flag no longer changes the ceiling on an APU, so the panel " ++ "reading the wrong flag would now be undetectable",+ );+ assert.ok(+ asDiscrete.totalCapacityGb > unified.totalCapacityGb,+ `treating one pool as two must overstate the ceiling; got ` ++ `${asDiscrete.totalCapacityGb} vs ${unified.totalCapacityGb}`,+ );+});++test("the panel passes the hardware signal, not the platform one", () => {+ // The fix itself is one line in a 3,400-line .tsx that this runner cannot+ // render, so it is asserted on the source. Without this the two tests above+ // pass on a panel that still reads appleSilicon: they pin what+ // resolveMemoryCapacityGb does with each flag, not which flag it is handed.+ const source = readFileSync(PANEL, "utf8");+ const call = source.match(/resolveMemoryCapacityGb\(\{[\s\S]*?\n\s*\}\)/);+ assert.ok(call, "resolveMemoryCapacityGb is no longer called here");+ assert.match(+ call[0],+ /unifiedMemory:\s*hasUnifiedMemory/,+ "the capacity call must take the general unified-memory signal. Passing the " ++ "Apple-only one charges a ROCm APU's single pool as VRAM plus host RAM.",+ );+ // And the general signal must come from the probed DEVICES rather than being+ // aliased back to the platform check. WHICH devices, and with which quantifier,+ // are asserted separately below.+ assert.match(+ source,+ /const hasUnifiedMemory[\s\S]{0,900}?device\.unifiedMemory === true/,+ "hasUnifiedMemory must be derived from the backend's per-device flag",+ );+});++test("an old backend that never sends unified_memory keeps the old behaviour", () => {+ // Backwards compatibility for an existing install whose backend predates the+ // per-device flag. use-gpu-info derives unifiedMemory with+ // `devices.some(d => d.unified_memory === true)`, so a missing key is false,+ // and the panel's `inferenceGpu.unifiedMemory || isAppleUnifiedMemory` then+ // collapses to exactly the appleSilicon check it replaced. Neither better nor+ // worse than before, which is the requirement.+ const legacyDevices: { memory_total_gb: number; unified_memory?: boolean }[] = [+ { memory_total_gb: 24 },+ ];+ const probed = legacyDevices.some((d) => d.unified_memory === true);+ assert.equal(probed, false, "a missing key must not read as unified");+ for (const appleSilicon of [false, true]) {+ assert.equal(+ probed || appleSilicon,+ appleSilicon,+ `old backend with appleSilicon=${appleSilicon} changed answer`,+ );+ }+});++test("a real discrete card is unaffected by the change", () => {+ // The fix must not turn an ordinary NVIDIA host into a shared-pool one. Its+ // devices do not report unified_memory, so nothing here moves.+ const discrete = resolveMemoryCapacityGb({+ pinnedDevices: [],+ hostDevices: [{ memoryTotalGb: 24, sharedMemory: false }],+ hostGpuTotalGb: 24,+ hostSharesSystemRam: false,+ systemRamTotalGb: 64,+ unifiedMemory: false,+ });+ assert.equal(discrete.singleMemoryPool, false);+ assert.equal(discrete.gpuCapacityGb, 24);+ // VRAM beside RAM, which is what a discrete card actually offers.+ assert.equal(discrete.totalCapacityGb, 88);+});++// ---------------------------------------------------------------------------+// Scoping the flag to the pin (Codex P2 on 9830)++test("a discrete pin on a mixed APU host keeps system RAM as a pool beside it", () => {+ // The regression the first version of this fix introduced. A ROCm APU beside a+ // discrete card makes a HOST-WIDE `devices.some(...)` true, and passing that+ // for a pin naming only the discrete card told resolveMemoryCapacityGb the two+ // are one pool. Measured: totalCapacityGb collapsed 143.52 -> 15.52 GiB,+ // discarding 128 GiB of RAM the load can really spill into, and the panel then+ // warned "more than this machine holds" for a load that fits comfortably.+ const APU = { memoryTotalGb: 48, sharedMemory: true };+ const DGPU = { memoryTotalGb: 16, sharedMemory: false };+ const base = {+ pinnedDevices: [DGPU],+ hostDevices: [APU, DGPU],+ hostGpuTotalGb: 64,+ hostSharesSystemRam: true,+ systemRamTotalGb: 128,+ gpuBudgetFraction: 0.97,+ };+ const scoped = resolveMemoryCapacityGb({ ...base, unifiedMemory: false });+ const hostWide = resolveMemoryCapacityGb({ ...base, unifiedMemory: true });+ assert.equal(scoped.singleMemoryPool, false);+ assert.ok(+ scoped.totalCapacityGb > 100,+ `a discrete pin must keep host RAM; got ${scoped.totalCapacityGb} GiB`,+ );+ assert.ok(+ hostWide.totalCapacityGb < scoped.totalCapacityGb,+ "the host-wide flag must be the one that throws RAM away, or this test is moot",+ );+});++test("the panel scopes the unified flag to the pinned devices", () => {+ // The fix is in a .tsx this runner cannot render, so it is asserted on source.+ // Without this, the capacity test above passes on a panel that still hands the+ // host-wide flag over: it pins what the resolver does, not what it is given.+ const source = readFileSync(PANEL, "utf8");+ const decl = source.match(/const hasUnifiedMemory = useMemo\(\(\) => \{[\s\S]*?\}, \[[^\]]*\]\);/);+ assert.ok(decl, "hasUnifiedMemory is no longer a scoped useMemo");+ assert.match(+ decl[0],+ /pinnedGpuIds[\s\S]*includes\(device\.index\)/,+ "hasUnifiedMemory must narrow to the pinned devices before calling .some()",+ );+ assert.match(+ decl[0],+ /isAppleUnifiedMemory/,+ "the Apple fallback must stay, for the window before the per-device probe lands",+ );+});++test("a mixed governing set is not unified, pinned or unpinned", () => {+ // The second half of the same bug. Narrowing to the pin fixed the discrete-only+ // case but `.some()` still marked a MIXED set unified: an unpinned load, or a+ // pin naming both an APU and a discrete card, reported 62.08 GiB instead of+ // 143.52 GiB. One independent-memory device in the set means there is real VRAM+ // beside system RAM, so the two are not one pool.+ const APU = { memoryTotalGb: 48, sharedMemory: true, unifiedMemory: true };+ const DGPU = { memoryTotalGb: 16, sharedMemory: false, unifiedMemory: false };+ const mixed = [APU, DGPU];++ const unified = (governing: typeof mixed) =>+ governing.length > 0 && governing.every((d) => d.unifiedMemory === true);++ assert.equal(unified(mixed), false, "a mixed set must not read as unified");+ assert.equal(unified([APU]), true, "an APU-only set is unified");+ assert.equal(unified([DGPU]), false, "a discrete-only set is not unified");+ // `[].every()` is true, which would make a host with no devices at all read as+ // a unified-memory machine.+ assert.equal(unified([]), false, "the empty set must not read as unified");++ // And the capacity that follows from it.+ const cap = resolveMemoryCapacityGb({+ pinnedDevices: mixed,+ hostDevices: mixed,+ hostGpuTotalGb: 64,+ hostSharesSystemRam: true,+ systemRamTotalGb: 128,+ unifiedMemory: unified(mixed),+ gpuBudgetFraction: 0.97,+ });+ assert.ok(+ cap.totalCapacityGb > 100,+ `a mixed pin must keep host RAM beside the discrete card; got ${cap.totalCapacityGb} GiB`,+ );+});++test("the panel asks whether EVERY governing device is unified", () => {+ const source = readFileSync(PANEL, "utf8");+ const decl = source.match(/const hasUnifiedMemory = useMemo\(\(\) => \{[\s\S]*?\}, \[[^\]]*\]\);/);+ assert.ok(decl, "hasUnifiedMemory is no longer a scoped useMemo");+ assert.match(+ decl[0],+ /\.every\(\(device\) => device\.unifiedMemory === true\)/,+ "must be .every(): .some() marks a mixed APU-plus-discrete set unified and " ++ "throws away the system RAM beside the discrete card",+ );+ assert.match(+ decl[0],+ /governing\.length === 0/,+ "the empty set needs an explicit guard, since [].every() is true",+ );+});++// ---------------------------------------------------------------------------+// The pool's SIZE, which is a different question from whether it is one pool+// (Codex P2 on 9830)++test("a ROCm APU's ceiling is system RAM, not its GPU-visible window", () => {+ // Classifying the APU as one pool was right. Taking the GPU figure as the size+ // of that pool was not: Apple's memory_total_gb IS the machine's unified+ // memory, while a ROCm APU's is a BIOS-carved window onto system RAM. On a+ // 96 GiB machine carving 48 GiB, the ceiling came out at 46.56 GiB, so the+ // panel warned that a 60 GiB load exceeds a machine that holds 96.+ //+ // The backend already says which one is real, in+ // llama_cpp.py::_available_system_memory_mib: "On a unified-memory APU this,+ // not the ROCm-reported VRAM, is the real ceiling: the weights load into+ // shared system RAM."+ //+ // Driven with sharedMemory false, which is what a ROCm APU reports on Linux+ // (hardware.py sets shared_memory only on Windows). That matters: it is the+ // case where the unified flag is the ONLY thing classifying the pool, so the+ // capacity comes entirely from this branch.+ const APU = { memoryTotalGb: 48, sharedMemory: false };+ const base = {+ pinnedDevices: [],+ hostDevices: [APU],+ hostGpuTotalGb: 48,+ hostSharesSystemRam: false,+ systemRamTotalGb: 96,+ gpuBudgetFraction: 0.97,+ unifiedMemory: true,+ };+ const rocm = resolveMemoryCapacityGb({+ ...base,+ unifiedPoolReportedAsGpuMemory: false,+ });+ assert.equal(rocm.singleMemoryPool, true, "still one pool");+ assert.equal(+ rocm.totalCapacityGb,+ 96,+ "the pool is the machine's RAM, not the window the BIOS carved out of it",+ );+ // The GPU figure is still the budgeted window: what may sit on the GPU and how+ // much the machine holds are different numbers even when they share silicon.+ assert.equal(rocm.gpuCapacityGb, 46.56);+});++test("Apple is unchanged, since its GPU figure already is the whole pool", () => {+ // The guard on the fix. Apple must keep the budgeted GPU figure as its ceiling;+ // routing it through the RAM branch would hand back the raw 96 and quietly drop+ // the VRAM Budget the user set.+ const MAC = { memoryTotalGb: 96, sharedMemory: false };+ const base = {+ pinnedDevices: [],+ hostDevices: [MAC],+ hostGpuTotalGb: 96,+ hostSharesSystemRam: false,+ systemRamTotalGb: 96,+ gpuBudgetFraction: 0.97,+ unifiedMemory: true,+ };+ const explicit = resolveMemoryCapacityGb({+ ...base,+ unifiedPoolReportedAsGpuMemory: true,+ });+ // Absent must behave as Apple, so every caller written before the ROCm case+ // keeps its answer without being updated.+ const byDefault = resolveMemoryCapacityGb(base);+ assert.equal(explicit.totalCapacityGb, 93.12);+ assert.equal(+ byDefault.totalCapacityGb,+ explicit.totalCapacityGb,+ "omitting the new flag must mean Apple, or existing callers silently move",+ );+ assert.notEqual(+ explicit.totalCapacityGb,+ 96,+ "Apple's ceiling must still respect the VRAM Budget",+ );+});++test("the panel tells the resolver which kind of unified memory it has", () => {+ // Source-level, like the sibling assertions: the fix is one argument in a .tsx+ // this runner cannot render, and without this the two tests above pass on a+ // panel that never passes the flag.+ const source = readFileSync(PANEL, "utf8");+ const call = source.match(/resolveMemoryCapacityGb\(\{[\s\S]*?\n\s*\}\)/);+ assert.ok(call, "resolveMemoryCapacityGb is no longer called here");+ assert.match(+ call[0],+ /unifiedPoolReportedAsGpuMemory:\s*isAppleUnifiedMemory/,+ "only the Apple half may be read as the whole pool. Passing the general " ++ "signal here takes a ROCm APU's carved window as the machine's ceiling.",+ );+});++test("a Linux APU beside a discrete card is not independent VRAM", () => {+ // The third and last face of the same reporting split. `.every()` correctly+ // made a mixed set non-unified, so the ceiling became `dedicated + RAM` -- and+ // `dedicated` was computed from `sharedMemory` ALONE, which a Linux ROCm APU+ // reports as false. Its 48 GiB window was therefore added to the 128 GiB of RAM+ // that already contains it.+ //+ // Measured: 190.08 GiB on a machine holding 128, i.e. 46.56 GiB of capacity+ // that does not exist, in the direction that admits a load.+ const APU = { memoryTotalGb: 48, sharedMemory: false, unifiedMemory: true };+ const DGPU = { memoryTotalGb: 16, sharedMemory: false, unifiedMemory: false };+ const mixed = [APU, DGPU];+ const r = resolveMemoryCapacityGb({+ pinnedDevices: mixed,+ hostDevices: mixed,+ hostGpuTotalGb: 64,+ hostSharesSystemRam: false,+ systemRamTotalGb: 128,+ gpuBudgetFraction: 0.97,+ unifiedMemory: false,+ unifiedPoolReportedAsGpuMemory: false,+ });+ // Only the discrete card is memory BESIDE system RAM: 16 * 0.97 + 128.+ assert.equal(r.totalCapacityGb, 143.52);+ assert.ok(+ r.totalCapacityGb <= 128 + 16,+ `the ceiling cannot exceed RAM plus the one real card; got ${r.totalCapacityGb}`,+ );+});++test("the unified flag is read from the device, not just shared_memory", () => {+ // The two flags must be interchangeable for capacity, since the backend picks+ // between them by platform: Windows sends shared_memory, Linux sends+ // unified_memory, for the same silicon. If these two ever disagree, one+ // platform is being charged differently from the other for identical hardware.+ const base = {+ pinnedDevices: [] as never[],+ hostGpuTotalGb: 48,+ hostSharesSystemRam: false,+ systemRamTotalGb: 96,+ gpuBudgetFraction: 0.97,+ unifiedMemory: false,+ };+ const viaShared = resolveMemoryCapacityGb({+ ...base,+ hostDevices: [{ memoryTotalGb: 48, sharedMemory: true }],+ });+ const viaUnified = resolveMemoryCapacityGb({+ ...base,+ hostDevices: [{ memoryTotalGb: 48, sharedMemory: false, unifiedMemory: true }],+ });+ assert.deepEqual(+ viaUnified,+ viaShared,+ "Windows and Linux must price the same APU identically",+ );+});++test("a Linux APU's FREE memory is the pool's, not the window's", () => {+ // The free side of the same split, and a regression this PR introduced rather+ // than inherited. resolveMemoryFit asks the WHOLE-LOAD question of+ // freeGpuCapacityGb as soon as the pool is single, and marking a ROCm APU+ // single-pool (correctly) pointed that question at the free space inside a+ // BIOS-carved window. A 60 GiB load on a 96 GiB machine with 60+ GiB free was+ // then warned as not fitting, purely because 60 > the 48 GiB window.+ const APU = { memoryFreeGb: 44, memoryTotalGb: 48, sharedMemory: false, unifiedMemory: true };+ const freeVram = aggregateUsableFreeVramGb([APU], 0.97);+ const usableSystemRamGb = 62; // 64 GiB available, less the loader's 2 GiB headroom++ // What the panel now hands resolveMemoryFit for a non-Apple unified pool.+ const pooledFree = Math.max(freeVram, usableSystemRamGb);+ assert.ok(+ pooledFree >= usableSystemRamGb,+ `the pool's free memory cannot be smaller than the host's; got ${pooledFree}`,+ );+ // And the 60 GiB load the old figure refused now fits the one it should be+ // measured against.+ assert.ok(freeVram < 60, `the window must be the smaller figure; got ${freeVram}`);+ assert.ok(pooledFree > 60, `the pool must hold the load; got ${pooledFree}`);+});++test("two views of one host pool are not counted as two pools", () => {+ // What folding unifiedMemory into the FREE path actually buys, measured rather+ // than asserted. A ROCm APU (Linux: unifiedMemory) beside a Vulkan iGPU+ // (sharedMemory) are two reported views of the SAME host memory. Gating on+ // sharedMemory alone made the APU an independent addend:+ //+ // unfixed 77.12 GiB fixed 38.56 GiB+ //+ // The pool counted twice, on the figure the fit verdict is measured against.+ //+ // Worth recording what this does NOT buy, because the first version of this+ // test claimed it and was vacuous: for an APU beside a DISCRETE card the+ // aggregate is 52.08 either way. A fully shared device already contributes its+ // own free exactly once, so there is nothing to dedupe until a SECOND view of+ // the same pool shows up. That case is this one.+ const APU = { memoryFreeGb: 40, memoryTotalGb: 48, sharedMemory: false, unifiedMemory: true };+ const IGPU = { memoryFreeGb: 40, memoryTotalGb: 48, sharedMemory: true };+ const folded = aggregateUsableFreeVramGb([APU, IGPU], 0.97);+ const asDedicated = aggregateUsableFreeVramGb(+ [{ ...APU, unifiedMemory: false }, IGPU],+ 0.97,+ );+ assert.equal(folded, 38.56);+ assert.ok(+ asDedicated > folded,+ "treating the APU as its own memory must be the larger, wrong answer, " ++ `or this test is measuring nothing; got ${asDedicated} vs ${folded}`,+ );+ // One view's worth, not two.+ assert.ok(folded < asDedicated / 1.5);+});++test("the panel measures pool pressure against the pool", () => {+ const source = readFileSync(PANEL, "utf8");+ assert.match(+ source,+ /hasUnifiedMemory && !isAppleUnifiedMemory[\s\S]{0,160}?Math\.max\(\s*freeVram,\s*memoryUsableSystemRamGb\s*\)/,+ "a non-Apple unified pool's free capacity must fall back to the host view; " ++ "the carved window cannot answer a whole-load question",+ );+});diff --git a/studio/frontend/tests/model-memory.test.ts b/studio/frontend/tests/model-memory.test.tsindex fffa36e2559..9e58cec227e 100644--- a/studio/frontend/tests/model-memory.test.ts+++ b/studio/frontend/tests/model-memory.test.ts@@ -14,9 +14,12 @@ const { computeModelMemory, formatKvRate, formatMemoryGb } = await import(const GB = 1024 ** 3;-// 16 GB card -> 14.4 GB usable at the shared 0.90 headroom.+// 16 GiB card -> 15.52 GiB usable at the shared 0.97 fraction, which is what+// the loader admits at (_CTX_FIT_VRAM_FRACTION). This was 0.90 / 14.4, a value+// llama_cpp.py records as already tried and reverted: "0.90 dropped 91-94% fits+// to CPU offload, #5106".const GPU_GB = 16;-const BUDGET_GB = 14.4;+const BUDGET_GB = 15.52;test("no GPU or no weights cannot be charted", () => {assert.equal(@@ -71,11 +74,13 @@ test("speculative reserve counts toward the context segment", () => {const withSpec = computeModelMemory({weightsBytes: 10 * GB,kvBytes: 3 * GB,- specBytes: 2 * GB,+ // 3, not 2: at the 0.97 budget the old figure no longer tipped this over,+ // so the test would have passed while measuring nothing.+ specBytes: 3 * GB,gpuGb: GPU_GB,});assert.equal(withoutSpec.status, "fits");- assert.equal(withSpec.kvGb + withSpec.specGb, 5);+ assert.equal(withSpec.kvGb + withSpec.specGb, 6);// Turning on speculative decoding is what tips this one over.assert.equal(withSpec.status, "context-exceeds");});@@ -163,9 +168,14 @@ test("no context length means no rate rather than a wrong one", () => {});test("KV rate labels pick sane units", () => {- assert.equal(formatKvRate(0), "0 KB");- assert.equal(formatKvRate(6234), "6.1 KB");- assert.equal(formatKvRate(1024 * 1024 * 3), "3.0 MB");+ // KiB/MiB, not KB/MB. The divides are by 1024, so the old labels were the+ // same mislabel as the GB/GiB one a scale up.+ assert.equal(formatKvRate(0), "0 KiB");+ assert.equal(formatKvRate(6234), "6.1 KiB");+ assert.equal(formatKvRate(1024 * 1024 * 3), "3.0 MiB");+ // Non-finite input has no honest rendering and must not print "NaN KiB".+ assert.equal(formatKvRate(Number.NaN), "0 KiB");+ assert.equal(formatKvRate(-1), "0 KiB");});test("an unloadable model is flagged, not silently drawn as full", () => {@@ -194,8 +204,10 @@ test("bar holds the accent below 80% of budget", () => {});test("bar warns from 80% and turns critical from 90%", () => {+ // Figures rescaled for the 15.52 GiB budget: 13/15.52 = 83.8%, 14.5/15.52 =+ // 93.4%. The bands themselves are unchanged.const high = computeModelMemory({- weightsBytes: 10 * GB,+ weightsBytes: 11 * GB,kvBytes: 2 * GB,gpuGb: GPU_GB,});@@ -203,8 +215,8 @@ test("bar warns from 80% and turns critical from 90%", () => {assert.equal(high.pressure, "high");const critical = computeModelMemory({- weightsBytes: 12 * GB,- kvBytes: 1 * GB,+ weightsBytes: 13 * GB,+ kvBytes: 1.5 * GB,gpuGb: GPU_GB,});assert.ok(critical.fillPct >= 90, `got ${critical.fillPct}`);diff --git a/studio/frontend/tests/vram-total-gib-suffix.test.ts b/studio/frontend/tests/vram-total-gib-suffix.test.tsindex 6f68d1a49ce..109a0c78f1f 100644--- a/studio/frontend/tests/vram-total-gib-suffix.test.ts+++ b/studio/frontend/tests/vram-total-gib-suffix.test.ts@@ -102,25 +102,74 @@ test("helper-formatted totals pick the GiB helper, not the disk one", () => {}});-// The memory bar names its own unit rather than going through formatGiB, and it-// divides by 1024**3 throughout, including the gpuGb it measures against. Listed-// separately because the check is on its formatter, not on a call site.+// Both memory surfaces name their own units rather than going through+// formatGiB, and both divide by 1024 throughout -- including the gpuGb they+// measure against. Their formatters used to live in two feature modules, one per+// surface, and this guard only knew about one of them: the OTHER divided by+// 1024**3 and labelled the result "GB" across seven figures on the Load Model+// panel, which is exactly the defect this file exists to prevent, sitting+// outside its reach the whole time.+//+// They are now one module, so the check is on that module and covers every+// formatter in it. Listed by name rather than swept, so deleting one is a+// failure here rather than a silent reduction in what is guarded.const BINARY_FORMATTERS: [string, string][] = [- ["lib/model-memory.ts", "formatMemoryGb"],+ ["lib/memory/format.ts", "formatGiB"],+ ["lib/memory/format.ts", "formatBytesGiB"],+ ["lib/memory/format.ts", "formatKvRate"],];-test("the memory bar's own formatter names a binary unit", () => {+test("every shared memory formatter names a binary unit", () => {for (const [relative, fn] of BINARY_FORMATTERS) {const source = readFileSync(new URL(relative, SRC), "utf8");const helper = source.match(new RegExp(`export function ${fn}[\\s\\S]*?\\n}`),);assert.ok(helper, `${relative}: no ${fn}`);+ // Any B-suffixed literal that is not preceded by "Ki", "Mi" or "Gi".assert.doesNotMatch(helper[0],- /(?<!Gi)B["'`]/,+ /(?<!Ki|Mi|Gi)B["'`]/,`${relative}: ${fn} labels a binary value with a decimal unit`,);- assert.match(helper[0], /GiB/, `${relative}: ${fn} does not suffix GiB`);+ assert.match(+ helper[0],+ /(KiB|MiB|GiB)/,+ `${relative}: ${fn} names no binary unit at all`,+ );+ }+});++// The two surfaces reach those formatters through back-compat aliases that kept+// their old names. The aliases are the reason no call site had to change, and+// they are also how a future edit could quietly reintroduce a second+// implementation: redefining formatMemoryGb as a function in either module would+// shadow the shared one and this file would be none the wiser, since the check+// above only reads lib/memory/format.ts.+const ALIAS_ONLY = [+ "lib/model-memory.ts",+ "features/model-picker/model-config/memory-fit.ts",+];++test("the surfaces alias the shared formatters rather than redefining them", () => {+ for (const relative of ALIAS_ONLY) {+ const source = readFileSync(new URL(relative, SRC), "utf8");+ assert.doesNotMatch(+ source,+ /export function formatMemoryGb\b/,+ `${relative}: formatMemoryGb is defined here again. There were once two of ` ++ `these, with the same name and signature but different input units and ` ++ `different labels, and importing the wrong one typechecked cleanly.`,+ );+ assert.doesNotMatch(+ source,+ /export function formatKvRate\b/,+ `${relative}: formatKvRate is defined here again`,+ );+ assert.match(+ source,+ /from "\.\.?\/[^"]*memory\/format\.ts"/,+ `${relative}: no longer sources its formatters from the shared module`,+ );}});diff --git a/tests/studio/playwright_memory_estimate.py b/tests/studio/playwright_memory_estimate.pyindex 1e1f55eda41..5df4d651204 100644--- a/tests/studio/playwright_memory_estimate.py+++ b/tests/studio/playwright_memory_estimate.py@@ -22,7 +22,7 @@ to be displaying. What that buys, gate by gate:n_parallel, gpu_memory_mode). A row that re-renders without re-pricing, or one wiredto 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 byte -- `formatBytesGiB` 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@@ -118,7 +118,7 @@ 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)`,+# Exact quarter-GiB figures on purpose: `formatBytesGiB` 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)@@ -130,9 +130,19 @@ STUB_LAYER_COUNT = 27STUB_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"+def _gib(num_bytes: int) -> str:+ """Python-side mirror of `formatBytesGiB` in `lib/memory/format.ts`.++ The label is GiB, not GB, and that is the assertion rather than a detail.+ This mirror used to print "GB" because the panel did, so the test agreed+ with the app about a divide by 1024**3 that both of them called a decimal+ gigabyte. Consolidating the formatters corrected the app; correcting the+ mirror to match is what keeps this test measuring the app rather than+ re-stating whatever the app currently happens to do.++ Only the unit moved. Every figure here is byte-for-byte what it was.+ """+ return f"{num_bytes / GIB:.2f} GiB"_n = [0]@@ -904,27 +914,27 @@ with sync_playwright() as p:# 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)+ total_gib = _gib(STUB_TOTAL_BYTES)+ gpu_gib = _gib(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:+ if total_gib not in head:fail(- f"the row does not show the returned total {total_gb!r} "+ f"the row does not show the returned total {total_gib!r} "f"(total_bytes={STUB_TOTAL_BYTES}); header text={head!r}")else:- info(f"OK figures: total {total_gb} is on screen")+ info(f"OK figures: total {total_gib} is on screen")if re.search(r"\bGPU\b", head):- if gpu_gb not in head:+ if gpu_gib not in head:fail(- f"the row shows a GPU figure but not the returned gpu_bytes {gpu_gb!r}; "+ f"the row shows a GPU figure but not the returned gpu_bytes {gpu_gib!r}; "f"header text={head!r}")else:- info(f"OK figures: GPU {gpu_gb} is on screen")+ info(f"OK figures: GPU {gpu_gib} is on screen")else:info("single-pool layout: no separate GPU figure to check")shoot("04-row-collapsed")@@ -947,9 +957,9 @@ with sync_playwright() as p:)else:for label, value in (- ("Weights", _gb(STUB_WEIGHTS_BYTES)),- ("KV cache", _gb(STUB_KV_BYTES)),- ("Compute buffers", _gb(STUB_COMPUTE_BYTES)),+ ("Weights", _gib(STUB_WEIGHTS_BYTES)),+ ("KV cache", _gib(STUB_KV_BYTES)),+ ("Compute buffers", _gib(STUB_COMPUTE_BYTES)),):if label not in detail:fail(f"the breakdown has no {label!r} line; text={detail!r}")@@ -1017,7 +1027,7 @@ with sync_playwright() as p:)if wait_for_row(True):head = header_text()- if _gb(STUB_TOTAL_BYTES) in head:+ if _gib(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}")