Skip to content

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

Merged
danielhanchen merged 35 commits into
unslothai:mainfrom
IMJONEZZ:feat/model-memory-bar
Aug 27, 2026
Merged

danielhanchen merged 35 commits into
unslothai:mainfrom
IMJONEZZ:feat/model-memory-bar

Conversation

@IMJONEZZ

@IMJONEZZ IMJONEZZ commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

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:

  • Chat model picker — only the selected row charts itself, and compactly (3px, held back at opacity while the fit is comfortable, gaining presence as it fills). A meter under every row turns a list you scan into a wall of charts, and a model that comfortably fits is not news.
  • Hub split view / on-device card — full bar with the GB readout. One model, room to read it.
  • GGUF variant expander — nothing. It's the densest surface in the app and already carries per-variant OOM/TIGHT badges.

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:

n_ctx llama.cpp reported estimator error
4096 36 MiB 35.8 MiB +0.4%
32768 204 MiB 203.8 MiB +0.1%
131072 780 MiB 780.3 MiB −0.04%

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-estimate gains three things, all additive:

  • n_ctx is 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_parallel scales per-slot KV stream padding.
  • speculative_type prices an MTP draft reserve, returned as spec_bytes — null for ngram, which drafts from generated text and costs no VRAM. _estimate_mtp_overhead_bytes already existed; it just wasn't reachable from the API.

_resolve_mtp_drafter handles drafters shipped as a separate file beside the weights (Gemma 4's mtp-*.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

  • Draws nothing when the budget stops describing where the model loads — pinned GPU ids, manual GPU memory mode, or CPU offload. Charting a multi-GPU total against a model pinned to one card would call a 30 GB quant "fits" on a 2×24 GB host.
  • Caching: estimates are keyed by the inputs that change them and duplicate requests fold into one, so a long list costs one metadata read per model rather than one per row. Capped at 256 entries; failures expire after 30s so a backend restart doesn't blank rows for the session.
  • per-model-config now emits a change event. The browser's storage event 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 -w is the useful view of pickers.tsx; the raw diff carries some reindentation from the row content moving into a wrapper.
  • gguf-fit.ts is moved to src/lib/ in its own commit. It already described itself as the single source of truth for GGUF fit, but living under features/hub meant the picker couldn't reach it without inverting the src/lib → features dependency.
  • i18n strings are in a new top-level modelMemory section. studio.model is the training page's bucket, so folding them there would be misleading — happy to move them if you'd rather.
  • 18 unit tests cover the segment maths, fit classification, pressure bands and formatters.

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.py today (Vulkan has is_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.py rather 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:check clean; full suite green (362 tests, 18 of them new here). Exercised on a DGX Spark (GB10, 128 GB unified memory) against downloaded GGUFs including gemma-4-E2B-it (separate MTP drafter), Qwen3.6-27B-MTP (embedded MTP head), and a 171 GB Inkling-Small quant for the too-large path.

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.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

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.
@IMJONEZZ

IMJONEZZ commented Aug 5, 2026

Copy link
Copy Markdown
Contributor Author

Thanks — four of these are addressed in e796f54.

Auto GPU-layer configs suppressed the bar — correct, and the worst of the set. gpuLayers: -1 is truthy, so my guard read the runtime's Auto value as a manual override and hid the bar for ordinary saved configs. Now mirrors gpuFieldsAtDefault (gpuLayers == null || gpuLayers < 0), and treats selectedGpuIds == null as default rather than checking array length.

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 readPersistedGpuMemoryMode() and readPersistedSpeculativeType(), so a standing Manual mode stops the bar drawing against a budget the load won't use, and a standing MTP mode gets its draft reserve without needing a per-model save first.

Drafter discovery — fixed. _download_mtp's docstring is explicit that MTP/ copies are explicit-selection and skipped, and my recursive scan could sort one ahead of the root companion. Now non-recursive and root-level only, which also takes a directory walk off the request path.

Auto MTP suppression — fixed by reusing _auto_mode_drops_mtp rather than re-deriving the threshold, so the separate-drafter exemption comes along for free. Verified: gemma-4-E2B (2B, separate drafter) still prices its 93 MB reserve under auto; Qwen3.6-27B-MTP (embedded head) prices 32 MB.

Also took the draft KV dtype point in the same commit — no longer forwarding the main cache_type_kv as both draft types, so a quantized main cache stops underpricing the drafter.

Two left, both real, deferred rather than dismissed:

  • Auto-fit context. Sizing at native context can warn OOM for a context the loader would have auto-reduced. Solving it properly means reproducing auto-fit in the estimate; softening the warning when auto-fit may intervene is probably the better shape, and I'd rather do that deliberately than bolt it on here.
  • Snapshot-pinned rows. Rows backed by a loadId load a concrete snapshot while the estimate resolves by repo id, so a duplicate/recovered cache can disagree. Needs the path plumbed through to the estimate.

Happy to fold either into this PR if you'd prefer them here rather than as follow-ups.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

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.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

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.
@IMJONEZZ

IMJONEZZ commented Aug 9, 2026

Copy link
Copy Markdown
Contributor Author

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 > 1 guard started discarding a real choice. Now any positive override is sent.

MTP reserve on a binary that can't run MTP — correct. _emit_mtp gates on mtp_token and declines on an inconclusive probe as well, and the separate-drafter path is emitted behind that same gate, so metadata alone was the wrong signal. The estimator now mirrors it. probe_server_capabilities caches on (path, mtime), so this doesn't put a subprocess on the request path.

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.

@BardiaKoopah

Copy link
Copy Markdown
Contributor

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 npm run i18n:check:strict didn't exist yet there, so npm run i18n:check:strict on your branch just says Missing script. The script landed on main afterwards and is a blocking step in studio-frontend-ci.yml, between typecheck and the unit tests. On current main I added a modelMemory block to en.ts and nothing else:

main, untouched            exit 0   (ran twice)
main + 5 en-only keys      exit 1   (ran twice)

  - modelMemory.readout
  - modelMemory.readoutWithSpec
  - modelMemory.kvRate
  - modelMemory.oomLikely
  - modelMemory.tooLarge
Missing keys above. Add them to every overlay, or run without --strict to accept the English fallback.

You're adding seven leaf keys (showMemoryBar, showMemoryBarDescription, and the five under modelMemory), and there are 11 non-English overlays in src/i18n/locales/. Nothing backfills them: check-parity.ts is the only i18n tooling in the tree, and there's no pre-commit hook or workflow that writes overlays. So it's 77 entries by hand, or the gate stays red.

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 computeModelMemory with property tests rather than examples, because the clamping is where this kind of thing usually goes wrong. Every combination of 7 budgets, 9 weight values, 9 KV values, 9 spec values and 7 context lengths, including zeros and negatives:

cases: 35721
violations: 0

Checked that the three segment percentages never sum past 100 or go negative, that nothing comes back NaN or Infinity (nCtx: 0 and a zero budget were the ones I expected to divide badly), and that status never says fits while the total is over budget. It holds throughout.

Gates on da74d246f: npm test 362 passed, typecheck clean, build clean.

I didn't look at the backend half of this at all, so routes/models.py and whether the estimates it returns match what llama.cpp actually allocates is untouched by anything I ran.

# 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.
@IMJONEZZ

Copy link
Copy Markdown
Contributor Author

@BardiaKoopah You were right, and the reason I couldn't see it is exactly the one you gave: i18n:check:strict doesn't exist on my base, so npm run i18n:check:strict was a Missing script rather than a failure. Verified on upstream/main — the script is there, and Locale parity is a blocking step in studio-frontend-ci.yml (just above Typecheck rather than between it and the tests, but blocking either way; Biome next to it is continue-on-error).

Fixed, both halves:

Merged upstream/main in (394 commits). Four conflicts, all resolved: two were upstream expanding imports the merge kept alongside mine, and one was a real overlap — upstream retuned downloadedRowShellClassName to drop focus-within in favour of has-[:focus-visible] / has-[[data-state=open]], which I've kept while keeping the radius switch, since two call sites still render a bar under the row. Merged rather than rebased so the inline review comments stay anchored.

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.

npm run i18n:check:strict   exit 0, "All locale overlays pass parity"
npm run typecheck           clean
npm test                    1620 passed
npm run build               clean

The backend half you didn't run: tests/test_kv_cache_estimation.py is 152 passed. On whether the estimates match what llama.cpp actually allocates — that part is measured, not assumed. Against llama-server -lv 10 on a GB10, reading llama_kv_cache: size = N MiB: 4096 ctx → 36 MiB, 32768 → 204 MiB, 131072 → 780 MiB. Linear, allocated at context creation before any token, and within 0.5% of what the estimator predicts. That measurement is why the bar prices KV up front at all.

Thanks for the property tests — 35721 cases over the clamping is a better shape than the examples I wrote, and nCtx: 0 against a zero budget was the case I'd have most expected to divide badly.

danielhanchen added 7 commits August 26, 2026 13:34
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.
@danielhanchen
danielhanchen self-requested a review as a code owner August 26, 2026 15:05
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 26, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 26, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 26, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 26, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 26, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 26, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

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.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

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.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 26, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 26, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 26, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 26, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 26, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 26, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 26, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 26, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

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.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

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.
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Hooray!

Reviewed commit: 29130f39be

ℹ️ 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".

# Conflicts:
#	studio/backend/utils/hardware/hardware.py
#	studio/frontend/src/hooks/use-gpu-info.ts
#	studio/frontend/src/hooks/use-system.ts

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment on lines +229 to +233
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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Comment on lines +567 to +572
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),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Comment on lines +735 to +738
repoId={repoId || localGgufPath}
loadId={localGgufPath}
quant={selectedQuant ?? ""}
sizeBytes={selectedVariant?.size_bytes}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

@danielhanchen

Copy link
Copy Markdown
Member

Before/after UI evidence for this PR, from two isolated installs: the merge base 6516b1b and the current head 4ff335e. Same machine, same seeded opt-in key, same downloaded blob in a private cache, one Playwright scene driven against both.

before and after

Model is unsloth/Qwen3-4B-Instruct-2507-GGUF Q4_K_M, picked for the size relationship rather than to be interesting: 2.33 GiB of weights against a 262144 token native context.

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:

Weights 2.3 GiB + context 37 GiB = 40 GiB of 174 GiB usable VRAM
KV reserved, ~144 KB/token

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: kv_bytes 36.0 GiB over weights_bytes 2.33 GiB is 15.48x, with gpu_bytes 39.72 GiB, gpu_floor_bytes 3.38 GiB, compute_bytes 1.4 GiB, n_ctx 262144. That is the case the old size * 1.15 + 1 GB badge could not express, since it has no context term at all.

Two things the run surfaced on its own:

  1. On the merge base, /api/models/kv-cache-estimate answered HTTP 422 for this call, because n_ctx was required there. This PR widens it to optional. So the before state has no bar for two independent reasons: no component, and no usable estimate. Widening a required query param is backwards compatible, so old callers passing n_ctx are unaffected.
  2. Units read GiB throughout the readout, so the GiB-labelled-as-GB issue is fixed on this path too.

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants