Repository navigation
Studio: show a VRAM memory bar on downloaded models - #7880
Conversation
gguf-fit.ts calls itself the single source of truth for "will this GGUF fit?", but living under features/hub meant only Hub could reach it. Moving it to src/lib lets the model picker share the same budget instead of growing a second copy of the formula. Also exports VRAM_HEADROOM_RATIO, so a caller can draw a meter against the same 0.90 budget this classifier judges against. No behaviour change.
…e-estimate /kv-cache-estimate could only answer for a single slot at an explicit context, and never reported what an MTP draft mode reserves -- even though the estimator behind it already knows. That left callers unable to size a load the way the loader actually performs it. - n_ctx is now optional and defaults to the GGUF's native context length, so a caller no longer needs a round trip just to learn the number it then asks about. The response echoes the context used. - n_parallel scales the per-slot KV stream padding. - speculative_type prices an MTP draft reserve, returned as spec_bytes. Null for ngram, which drafts from the generated text and costs no VRAM. - _resolve_mtp_drafter finds a drafter shipped as its own file beside the weights (Gemma 4's mtp-*.gguf), which the embedded-head path cannot see. Scoped to the weights' own directory and bounded, since this is on the request path. All fields are additive; the existing response shape is unchanged.
A downloaded model row said how big the file was, not whether it would
load. The two are different questions once the KV cache is involved: a
model can sit well inside VRAM while the context window pushes the total
past it, and the fix for that is not the fix for oversized weights.
Adds a bar under on-device rows splitting the footprint into weights, KV
cache at the context the model will load with, and any MTP draft reserve,
drawn against the same usable budget the fit badge uses. It warns when the
weights alone are too large ("try a smaller quantization") and, separately,
when only the context tips it over ("OOM likely") -- and stays quiet when
neither is true. Segment colours follow the user's accent until 80% of
budget, then amber, then destructive at 90%.
Notes:
- The bar charts the reservation, not usage: llama.cpp allocates the whole
KV cache when the context opens (131072 context allocates 131072 cells
before a token arrives). A per-token rate is shown alongside, since that
is what says whether a shorter context would help. Estimates were checked
against llama.cpp's own reporting and agree within 0.5%.
- It draws nothing when the budget stops describing where the model loads
-- pinned GPU ids, manual GPU memory, or CPU offload -- rather than
charting against a total the model will never get.
- Estimates are cached by the inputs that change them, with duplicate
requests folded into one, so a long list costs one metadata read per
model rather than one per row.
- per-model config now emits a change event: the browser's storage event
only reaches other tabs, so an edit made beside the row had nothing to
notify it.
Rendered in the chat model picker, the Hub split view, and the local
on-device card.
Four places where the estimate could disagree with the load it describes, found in review. - A saved config carrying the runtime's Auto layer value (gpuLayers: -1) suppressed the bar entirely: -1 is truthy, but per-model-config treats gpuLayers < 0 as automatic placement. Mirror gpuFieldsAtDefault instead of testing truthiness, and treat a null selectedGpuIds as default rather than an empty array. - GPU memory mode and speculative type are standing preferences when a model has no override, and the loader reads them from there. The estimate sent nothing, so a standing Manual mode drew against a budget the load would not use, and a standing MTP mode omitted the draft reserve until a per-model value was saved. - Drafter discovery accepted nested candidates, so a cache holding both the root mtp-*.gguf companion and higher-precision MTP/ copies could price the wrong one. _download_mtp fetches the root-level companion and deliberately skips MTP/, so match it and stop recursing. - Auto declines MTP on a sub-3B embedded head, where its per-token cost regresses, while exempting a separate drafter. Reuse _auto_mode_drops_mtp rather than pricing a reserve the load will not take. Also stop passing the main KV dtype as the draft cache types: the load path keeps them independent and defaults to f16, so forwarding a quantized main cache underpriced the drafter.
|
Thanks — four of these are addressed in e796f54. Auto GPU-layer configs suppressed the bar — correct, and the worst of the set. Standing Manual GPU mode / persisted speculative default — also correct. Both fall back to a standing preference when a model has no override, and I was sending neither. The estimate now reads Drafter discovery — fixed. Auto MTP suppression — fixed by reusing Also took the draft KV dtype point in the same commit — no longer forwarding the main Two left, both real, deferred rather than dismissed:
Happy to fold either into this PR if you'd prefer them here rather than as follow-ups. |
Settings > Chat gains a switch under "Show all Quantizations". The gate lives in the hook rather than at each render site, so a disabled bar also costs no estimate request. The figures are estimates, and a row that cannot be sized is better left plain than annotated with a guess -- so it stays off until asked for. Also in the hook: config lookup is now variant-exact, matching resolveInitialConfig. Falling back to a model-level entry sized the bar from settings the variant would never load with.
Presentation, after feedback that the bar was distracting: - Only the selected picker row charts itself. A meter under every row turns a list you scan into a wall of charts, and a model that comfortably fits is not news. At most one bar is on screen. - That bar is compact: 3px, and held back at opacity while pressure is normal, gaining presence as it fills. - Dropped from the GGUF variant expander entirely. It is the densest surface in the app and already carries per-variant OOM/TIGHT badges. - The hub detail card keeps the full bar and GB readout: one model, room to read it. Correctness: - kv-cache-estimate defaults n_parallel to the server's own slot count instead of 1. Assuming one slot understated a default load, which now starts with four. - The auto gate also declines an MLA embedded head (GLM/DeepSeek/Kimi), matching the loader: that path keeps a duplicated full target-KV context and runs slower than no speculation. - A saved per-model config no longer reports back as unsaved when the host cannot dispatch events. The write has already landed by then, so notifying listeners is best-effort. - The local on-device card renders the bar below its action row, not inside it: a full-width bar in a horizontal flex row became another flex item and squeezed the Run/Train buttons.
All three showed the same symptom -- a reserve the load will not take, so the bar can warn OOM on a model that fits. - An explicit one-slot choice reached the estimator as "omitted", which now means the server's slot count rather than one. Send any positive n_parallel override, including 1. - The MTP reserve is priced from metadata alone, but llama-server only takes that path when it advertises a --spec-type mtp token, and the loader declines on an inconclusive probe too. Gate on the same capability; the probe is cached on (path, mtime). - A re-download can change the file under a stable quant name, and the cached estimate's weights outranked the row's fresh size. Fold the size into the cache key.
|
All three taken — thanks, these were good catches, and two of them were mine. Explicit one-slot estimates — correct, and a regression from the previous round. Making the backend default to the server slot count meant the caller's MTP reserve on a binary that can't run MTP — correct. Stale estimate after a re-download — correct. File size is folded into the cache key. All three failed in the same direction — over-estimating, which surfaces as a false "OOM likely" on a model that would load. For a feature whose whole value is a trustworthy warning, that's the worst way to be wrong, so they were worth fixing together. |
|
This will fail the Locale parity gate the moment you rebase, and you can't see it from where you're branched. Your base is from Aug 4, and You're adding seven leaf keys ( Worth knowing that main currently sits at zero missing keys, which is why this bites now and wouldn't have a week ago. Your own base is already 17 behind, which is what makes the local check look content. Separately, I went at Checked that the three segment percentages never sum past 100 or go negative, that nothing comes back NaN or Infinity ( Gates on I didn't look at the backend half of this at all, so |
# Conflicts: # studio/frontend/src/features/model-picker/components/model-selector/pickers.tsx # studio/frontend/src/features/model-picker/index.ts # studio/frontend/src/features/model-picker/model-config/per-model-config.ts # studio/frontend/src/i18n/locales/en.ts
Locale parity runs with --strict in CI and blocks on any key that exists only in en.ts. Seven leaf keys across eleven overlays. The two settings strings sit beside the switch they describe; the bar's own strings go in a top-level modelMemory section, mirroring en.ts. Placeholders are left verbatim, and quantization terminology follows what each overlay already uses for the neighbouring quantization settings.
|
@BardiaKoopah You were right, and the reason I couldn't see it is exactly the one you gave: Fixed, both halves: Merged Translated all seven keys into all eleven overlays — 77 entries. Placeholders verbatim; quantization terminology follows what each overlay already uses for the neighbouring quantization settings rather than a fresh coinage. The backend half you didn't run: Thanks for the property tests — 35721 cases over the clamping is a better shape than the examples I wrote, and |
Six conflicts, all in the frontend and all resolved to main's behaviour with the bar's additions re-applied on top: - chat/index.ts, hub/lib/gguf-variant-sort.ts, settings/tabs/chat-tab.tsx, model-config/per-model-config.ts: import and hook-order churn, take both. - hub/catalog/gguf-download-card.tsx: main's gguf-fit import is dropped in favour of the branch's @/lib/gguf-fit, which is the same module after the move. - model-selector/pickers.tsx: main rewrote this component substantially (mediaPageForTask replacing diffusionPageForTask, a widened passesTaskGate, audio routability, ggufQuantChipLabel). Those all win. Re-applied on top are the memory prop, the selected-row-only useModelMemory call, the button wrapper and radius switch, and the two call sites that pass a memory source.
The memory bar's whole value is a warning you can trust, and the estimate had two ways to overstate the reserve and two ways to name the wrong drafter. All four fail in the same direction: a false "OOM likely" on a model that loads. Follow the loader's is_mtp_model precondition. A model with no embedded head, no MTP name and no separate drafter cannot run MTP, so llama-server gets --spec-default and reserves nothing. The route skipped that check and called _estimate_mtp_overhead_bytes anyway, which defaults mtp_keeps_target_ctx=True so an unsure caller over-reserves. Every MLA model was therefore billed a second full f16 copy of its own KV: measured 7.750 GiB of "draft reserve" on top of an identical 7.750 GiB target cache, on a model that drafts nothing. Resolve the drafter with the loader's own resolvers instead of a second scan. _resolve_mtp_drafter walked Path(main).parent itself, which got four things wrong. It passed an absolute path to _is_mtp_only_drafter_path, whose _drafter_path_kind matches any ancestor segment named mtp or dspark, so every GGUF under a folder called mtp/ read as a drafter, and since the main weight was excluded only by a lexical f != main it could be returned as its own drafter and have its whole file size billed as draft weights. It was non-recursive on the weight's directory, so the BF16/model.gguf layout that _resolve_quant_gguf explicitly supports never found the snapshot-root companion the loader fetches, and priced the reserve at 0. It sorted Path objects, whose ordering is case-folded on Windows and not on POSIX, so two hosts really could pick different files despite the docstring promising they agree. And nothing dropped the AppleDouble shadow macOS writes beside every file, which sorts first. Snapshots now go through _companion_snapshot_sibling with _pick_mtp, and local folders through detect_mtp_file, which is what model_config calls when it builds the launch. _pick_mtp is lifted to module level next to _pick_dspark and _pick_mmproj, which are already there for this exact reason: they are handed a live repo listing as well as a snapshot. Its mtp- prefix rule excludes AppleDouble shadows on its own, so it needs no separate guard. Drops the dead _DRAFTER_SCAN_TIMEOUT_SECONDS, whose comment promised a request-path bound the code never applied, and a dead drafter_path = None. 21 route tests, 10 of which fail on the parent commit, covering the MTP precondition, ngram costing nothing, a binary without the mtp token, the quant subdirectory, the mtp/ directory, self-billing, MTP/ precision copies, the AppleDouble shadow, uppercase extensions, live and broken snapshot symlinks, and identical resolution across linux, wsl, win32 and darwin.
Three cache defects, all of which show the user a number that belongs to a different load. An omitted slot count is not one slot. The request leaves n_parallel off when there is no override and the backend fills in the server's standing count, which defaults above one, but the key recorded both as 1. So an explicit single-slot row and a default-slot row shared one answer, in whichever direction they happened to be asked. A 200 that sized nothing was remembered as a success. The route is best-effort and answers with every field null rather than failing, so "could not size it" arrives down the success path, and only .catch() marked an entry failed. FAILURE_TTL_MS exists precisely because the usual cause is a backend that is briefly away, and it never applied to the case that needed it most: a row blanked that way stayed blank for the rest of the session, and a backend coming back could not clear it. Standing GPU-memory mode and speculative type did not re-key. A model with no override follows both, but they live in localStorage, whose storage event only reaches other tabs, and the epoch tracked per-model writes alone. Switching the global mode to Manual left every mounted bar drawn against a budget the load would no longer use. The runtime store changes in lockstep with those writes in-session, so it stands in as their notification. Their signature is two short strings and is checked on every read; serialising the saved configs stays behind the config event, so the store ticking on each streamed token no longer puts an O(all configs) stringify in the render path. Also stops re-pricing an existing key from evicting an unrelated row: only a new key grows the map. Key composition and the unsized test move to lib/model-memory.ts as pure functions so both are covered directly. 10 tests.
The bar warns "OOM likely" against whatever number it is handed, so what that number means on each host is the whole correctness question. It is not the same quantity everywhere, and on three classes of machine it is not a VRAM ceiling at all. A Vulkan iGPU reports free shared system RAM minus a host reserve, so it is not a total and it moves with desktop usage: the same model flips between fits and OOM as other apps come and go. Apple Silicon reports the entire machine's RAM, which says fits for almost anything Metal would refuse, and the MLX record never sets shared_memory so it counted as dedicated. Both now decline to draw, which is what the PR description already said they did. GpuInfo carries the shared_memory flag the backend had been publishing and the frontend was dropping. A ROCm APU reports its whole GTT pool and is still not flagged; that needs a unified-memory signal in hardware.py, which is the follow-up the description names. A session GPU pin lives in the runtime store rather than in a saved config, so a user who pinned cards without saving a per-model override reached none of the existing tests and was charted against the whole multi-GPU sum. On a 2x24 host that calls a 30 GiB quant "fits" when it fits on neither card. Use the loader's admission fraction instead of a hardcoded 0.90. The bar drew at 0.90 while the loader admits at _active_vram_fraction(), which defaults to 0.97 and is user-settable through /api/settings/vram-budget. On a 24 GiB card that is 1.68 GiB of headroom the loader would have taken, so everything in the 90 to 97 per cent band got a false OOM warning. llama_cpp.py records why that band matters: 0.90 was tried and reverted because it dropped 91-94 per cent fits to CPU offload (unslothai#5106). VRAM_HEADROOM_RATIO is untouched and remains the fallback, since it is what the fit badge on the same row judges against and it is the only answer available before the settings request lands. Label the readout GiB. Every figure in it is a binary divide, including the gpuGb it measures against, which arrives as props.total_memory / 1024**3 with nothing subtracting a budget on the way. Calling those GB overstates each by 7.4 per cent, which is the defect unslothai#9570 fixed elsewhere; its guard test listed neither of these files, and now covers the formatter. 35 new tests over [linux, wsl, win32, darwin] x [NVIDIA single, NVIDIA multi, ROCm discrete, Intel XPU, Vulkan iGPU, Apple unified, CPU-only], asserting the gate matches what each budget means, that segments never sum past the track or report fits while over budget on any of them, and that the fraction moves the verdict in both directions.
The route reads a GGUF header, walks every HF cache root in _resolve_quant_gguf, resolves a drafter and probes the llama-server binary, all of it blocking disk work, and it ran inside the coroutine. The memory bar calls it once per visible row, so opening a long model list stalled everything else the process was serving, streamed chat tokens included. Moved into asyncio.to_thread, matching the shape of scan_loras and the other routes in this file that already do it. n_ctx and n_parallel are bound as arguments rather than closed over, since the body assigns to both to apply their defaults and would otherwise raise on the read. The regression test is the one from test_scan_loras_off_event_loop.py: a heartbeat coroutine counted strictly between the call and its return, which is the only measurement that separates the two versions.
The route already shipped, so this change has to be an upgrade rather than a break. Nothing here alters behaviour; it records what an existing caller is entitled to, so a later edit cannot quietly take it away. Both directions are covered. An old client still sends n_ctx and reads kv_bytes, weights_bytes and native_context: those keys must still be present, the new n_parallel and speculative_type must stay optional or its request would 422, and an unchanged request must produce an unchanged number, which is the assertion that proves the added parameters default to what the previous version implied. A new client may omit n_ctx, and that answer must equal the one it would get by naming the native length explicitly. Also pins the shape of the answer when nothing resolves: every key present and null, rather than a short dict that KeyErrors in the caller, and the no-cost speculative modes reporting no reserve.
The default is one boolean and it carries the whole backwards-compatibility story: an existing install upgrading into this build has no such key in localStorage, so it reads false and the app behaves exactly as it did before. Losing it would silently switch a new chart on for every existing user. Also asserts that a disabled bar describes no request at all, rather than building one and discarding the result: the enabled check is the first statement of the plan memo, and the VRAM budget lookup is gated on the same flag, so an install that never opts in generates no extra backend traffic.
Round 10. Several of these are the estimate describing a command the loader would have adjusted before running it. - Parallel slots are clamped through _effective_parallel_slots first. A build without --kv-unified serves one slot whatever was asked for, so a four-slot default was pricing the cache several times over and could warn OOM about a command that never launches that way. - A blank Draft Tokens field is not zero. _build_speculative_flags emits its own default and the rollback state is multiplied by it, so pricing zero dropped the dominant allocation on a Hybrid Mamba target. An explicit zero is still honoured, which is what the updated test now separates. - Tensor mode is resolved through _effective_tensor_parallel, so an inherited LLAMA_ARG_SPLIT_MODE=tensor counts devices as the launch does. Reading the request boolean alone left n_devices at one for exactly that case. - A snapshot's projector sits at the snapshot root while the weights sit in a quant subdirectory, so scanning the weights' own directory found nothing. Anchored the way the drafter lookup already is. Frontend: - A direct .gguf row is no longer rejected for having no quant label. The previous commit taught the route to resolve such a file and the card to send it, and then this guard dropped it on the floor, so the feature it added was unreachable. - The memory-bar opt-in joins the Reset All key list. Its default is off, so leaving it out meant a reset that said it restored defaults left the bar on. Spelled out rather than imported, for the import-cycle reason the file's own note gives, with a test pinning the literal against the store's constant. - The Hub inspector card is gated on the runtime, as the picker already is. - An auto-fitted row draws its pressure from the irreducible floor. Priced at the native context, the total is an upper bound on a length the loader will never open; suppressing only the words left a model that loads perfectly well showing a full destructive-red bar, which says "this will not work" louder than the text did.
The delegation gave the planner total the inherited environment, and the itemized fields beside it kept their own answer. Both are shown at once, so the components could contradict the total drawn next to them. - An omitted context defaulted to the header's native length before the planner ran, and the planner reads the inherited LLAMA_ARG_CTX_SIZE only when its own input is zero. So a child pinned to 4k by the environment was priced at the header's window, and an inherited context larger than native was underpriced while still reading as auto-fitted. The omission is preserved through the planner now, and the route resolves the inherited value the way load_model does, where a positive inherited context beats the header. - kv_bytes was computed with the request's cache type, which is None when only the environment set one, so an inherited q8_0 cache was sized as f16: about twice the real reservation, in the KV segment, the per-token rate and the readout. Resolved through _planned_main_cache_types, the same call the planner uses, taking the heavier of the pair as it does. Frontend, both about work done by rows that cannot draw anything: - The runtime-store subscription is gated on the row having a source as well as on the opt-in. Every mounted picker row calls this hook, most with no source, and the store ticks on every streamed token, so each token was multiplied by the number of mounted rows -- localStorage reads included. - The session GPU pin joins the epoch signature. budgetIsMeaningful reads it, but it lives in the runtime store rather than in a saved config, so a preset changes it with no config write: the subscription fired, the snapshot did not move, useSyncExternalStore suppressed the rerender, and a bar stayed drawn against aggregate multi-GPU VRAM after the launch had been pinned to one card. The index namespace goes in with it, since the same ordinals mean different cards under a different kind.
The P1 here is one the previous two commits created between them. Round 11 taught the route to price an inherited LLAMA_ARG_CTX_SIZE, and round 10 changed an auto-fitted row to draw only its irreducible floor. The frontend still decided "auto-fitted" from the absence of a saved context, so an inherited window over budget both lost its warning and drew a near-empty bar: a confident fit for a launch that will OOM, and worse than before either change. The route now answers context_is_pinned. Only a context nobody pinned is auto-fitted, and load_model keeps a positive inherited value rather than fitting it, so that flag is the loader's own answer instead of a guess made two layers away. The frontend falls back to its old inference when the field is absent, so an older backend behaves as before. Also: - A ROCm APU's total is the GTT/system pool, which moves with host usage and is not a ceiling a fit verdict can be measured against. hardware.py already classifies these positively for its own free-VRAM path; it now reports unified_memory on the device and the bar abstains. Deliberately a new field rather than reusing shared_memory: the total and free aggregates already act on that one, so overloading it would change what they return on this hardware, which is a wider decision than naming the property. - Forced speculative modes (mtp, mtp+ngram, dspark, dflash) are session-only and never persisted, so a model loaded with one but not remembered was priced as auto. Auto drops MTP on an MLA target while the forced load engages it and opens another full cache. The live runtime value is read first and joins the epoch signature, since nothing else would re-key it. - The local on-device card takes the same runtime gate the inspector already applies to the remote card, so a local diffusion or audio GGUF no longer gets a llama.cpp verdict.
The abstention policy compared raw tokens, so llama.cpp's underscore spellings (--gpu_layers, --ctx_size, --spec_draft_hf) slipped past all three predicates at once while still changing the real launch. That is a hole in the policy rather than a missing entry in one list: the backend normalises underscores to dashes in _flag_name before parsing, and now so does this. One shared helper, so a spelling cannot be handled in one predicate and missed in another. The parity test grew to match. It already read the backend's frozensets for the placement and cache groups; it now covers _LOCAL_DRAFT_FLAGS and _HF_DRAFT_FLAGS too, which is how --spec-draft-model, -hfd, -hfrd and --hf-repo-draft were missing, and it exercises the normalisation directly rather than trusting a list. Both gaps were in the part of the policy the previous test did not reach. Also: - The pinned-quant picker row takes the runtime gate the sole-quant row beside it already had. Gating one call site and not the other left the same wrong verdict reachable by a different path. - An inherited LLAMA_ARG_DEVICE confines the child to the cards it names, and an automatic launch preserves that pin. budgetIsMeaningful sees browser-side pins and saved config, so this was the one placement override it could not reach: a 30 GiB model read as fitting 2x24 GiB while the child had one card. The route reports the pin and the bar abstains. Any pin at all counts, since the route does not know the host's inventory and abstaining is the safe direction; "none" is excluded because that is a CPU-only launch the planner already answers with zero GPU bytes.
|
@codex review |
|
Codex Review: Didn't find any major issues. Hooray! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
# Conflicts: # studio/backend/utils/hardware/hardware.py # studio/frontend/src/hooks/use-gpu-info.ts # studio/frontend/src/hooks/use-system.ts
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 4ff335ecfd
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| const autoFitted = Boolean(input.contextIsAutoFitted); | ||
| const pressureGb = | ||
| autoFitted && input.gpuFloorBytes != null | ||
| ? // The floor alone. Auto-fit sizes the cache to whatever is left, so the | ||
| // useful signal is how much of the budget is spoken for before the |
There was a problem hiding this comment.
Scale the displayed bar for auto-fitted contexts
When an unpinned model's native-context estimate exceeds the budget, this branch lowers only fillPct; totalGb remains the native over-budget value and modelPct/kvPct/specPct remain sized from the native reservation. On Hub cards, which enable showReadout, the result can therefore have status fits and normal coloring while showing a saturated bar and text such as “48 GiB / 21.6 GiB.” Scale the displayed segments/readout to the fitted estimate (or suppress them until that estimate is known), rather than adjusting pressure alone.
Useful? React with 👍 / 👎.
| const weights = estimate?.weightsBytes ?? source?.sizeBytes; | ||
| return computeModelMemory({ | ||
| // The projector is resident alongside the weights, so it belongs in that | ||
| // segment rather than as a fourth sliver the eye cannot resolve. | ||
| weightsBytes: | ||
| weights == null ? weights : weights + (estimate?.projectorBytes ?? 0), |
There was a problem hiding this comment.
Account for inherited partial GPU offload in weight segments
When LLAMA_ARG_N_GPU_LAYERS fixes a partial offload, the load path preserves that inherited count and the planner correctly scales gpu_bytes by the offloaded layer fraction, but this hook still passes the entire GGUF file (plus projector) as GPU-resident weights. Unlike an explicit config or extra argument, this environment override does not make budgetIsMeaningful abstain and is not covered by inheritedDevicePin, so the resulting status can be fits while the bar and Hub readout claim that the full disk weight size occupies VRAM. Return the planner's GPU-resident weight share or suppress the bar when an inherited layer policy owns placement.
Useful? React with 👍 / 👎.
| repoId={repoId || localGgufPath} | ||
| loadId={localGgufPath} | ||
| quant={selectedQuant ?? ""} | ||
| sizeBytes={selectedVariant?.size_bytes} |
There was a problem hiding this comment.
Invalidate cached estimates when a direct GGUF changes
For a direct .gguf path, selectedVariant is absent by design, so this passes an undefined sizeBytes; the estimate cache is consequently keyed only by the stable path, empty quant, and settings, and successful entries never expire. If LM Studio, a custom downloader, or the user replaces that file in place, reopening or refreshing the inventory continues using the old weight, context, and planner figures for the rest of the Studio session, potentially preserving a stale fits verdict for a larger replacement. Include a stat-derived size/mtime or explicitly invalidate this cache when the local inventory changes.
Useful? React with 👍 / 👎.
|
Before/after UI evidence for this PR, from two isolated installs: the merge base Model is Before. The downloaded Q4_K_M row shows its chips and Run button, then the metadata chips, and nothing in between. Worth noting the row carries no fit signal at all here: the fit badge lives in the collapsed variant list, not on the selected row. After. The same row gains the segmented bar plus: The premise is visible rather than asserted. The weights segment is a sliver and the KV segment runs about 15x wider, and the filled run stops at 23% of the track, which is 40 of 174. The API read from the same server agrees: Two things the run surfaced on its own:
The two crops align pixel for pixel above the insertion point (the image diff between the full shots starts at y=363), so the only variable between the halves is the build. |

What
A downloaded model row tells you how big the file is, not whether it will load. Those diverge as soon as the KV cache is involved — a model can sit well inside VRAM while the context window pushes the total past it, and the fix for that ("shorten the context, or quantize the KV cache") is not the fix for oversized weights ("pick a smaller quant").
This adds a bar under on-device rows splitting the footprint into weights, KV cache at the context the model will actually load with, and any MTP draft reserve, drawn against the same usable budget the existing fit badge uses.
It warns separately for the two failures — "Too large to load — try a smaller quantization" when the weights alone don't fit, and "With current settings OOM likely" when only the context tips it over — and stays quiet when neither is true. Segment colour follows the user's accent until 80% of budget, then amber, then destructive at 90%.
Opt-in, off by default — Settings > Chat, under "Show all Quantizations". The figures are estimates, and a row that can't be sized is better left plain than annotated with a guess. The gate lives in the hook, so a disabled bar costs no request either.
Where it draws, and how loudly:
Why the numbers are what they are
The bar charts the reservation, not usage: llama.cpp allocates the whole KV cache when the context opens. Measured on a GB10 with
gemma-4-E2B-it-UD-Q4_K_XL, against the estimator this PR reuses:llama_kv_cache: size = 768.00 MiB (131072 cells, ...)— allocated before a token is seen. Because a reservation isn't the same as what a prompt occupies, the bar also shows a per-token rate, which is what says whether a shorter context would actually help.Backend
/kv-cache-estimategains three things, all additive:n_ctxis now optional, defaulting to the GGUF's native context, so a caller doesn't need a round trip purely to discover the number it then asks about. The response echoes the context used.n_parallelscales per-slot KV stream padding.speculative_typeprices an MTP draft reserve, returned asspec_bytes— null for ngram, which drafts from generated text and costs no VRAM._estimate_mtp_overhead_bytesalready existed; it just wasn't reachable from the API._resolve_mtp_drafterhandles drafters shipped as a separate file beside the weights (Gemma 4'smtp-*.gguf), which the embedded-head path can't see. It's scoped to the weights' own directory — one level up is the snapshot root spanning every revision and quant — sorted for determinism, and bounded because it runs on the request path.Behaviour worth calling out
per-model-confignow emits a change event. The browser'sstorageevent only reaches other tabs, so an edit made in the settings sheet beside the row had nothing to notify the bar.Notes for review
git diff -wis the useful view ofpickers.tsx; the raw diff carries some reindentation from the row content moving into a wrapper.gguf-fit.tsis moved tosrc/lib/in its own commit. It already described itself as the single source of truth for GGUF fit, but living underfeatures/hubmeant the picker couldn't reach it without inverting thesrc/lib → featuresdependency.modelMemorysection.studio.modelis the training page's bucket, so folding them there would be misleading — happy to move them if you'd rather.Deliberately not in this PR
The budget is VRAM only. On unified-memory hosts (DGX Spark, Strix Halo) weights and KV live in system RAM, so a RAM + VRAM budget would be the truthful one — but there's no CUDA unified-memory flag in
hardware.pytoday (Vulkan hasis_igpu, ROCm has_reconcile_rocm_unified_memory, CUDA has neither), and summing without one would hand a Spark a ~164 GB budget on a 121 GB machine.That detection belongs in
hardware.pyrather than in this bar, and it would also fix the existing fit badge and "fits on device" filter, which read the same budget. Happy to open it as a follow-up — this PR deliberately keeps the same budget everything else already uses.Testing
Typecheck, ESLint and
i18n:checkclean; full suite green (362 tests, 18 of them new here). Exercised on a DGX Spark (GB10, 128 GB unified memory) against downloaded GGUFs includinggemma-4-E2B-it(separate MTP drafter),Qwen3.6-27B-MTP(embedded MTP head), and a 171 GBInkling-Smallquant for the too-large path.