Repository navigation
Studio: label GPU totals GiB, the unit they are actually in - #9570
Conversation
memory_total_gb comes off props.total_memory / 1024**3, so it is GiB, and nothing between the driver and the pixel subtracts a budget, reserve or headroom from it. Four renderers printed it with a GB suffix, which makes a 48 GB card read as 45 GB and was reported as broken VRAM detection: 45 GiB is 48.3 GB, so the number was right and only the unit was wrong. The model information sidebar is the one the report came from; the images and video GPU pickers and the wizard preview card carry the same string. hub-page and the About tab already said GiB, which is what makes the other four read as a discrepancy rather than a convention. Pinned by a test over every renderer of the field, because the fourth site turned up only after the first three were fixed. Fixes #9551
|
Confirmed the GPU total is built as bytes over 1024 cubed yet still printed with a GB suffix in model-config-page.tsx and the images, video and run preview surfaces, which is exactly the 45 versus 48 report in #9551. Will get this reviewed. |
The suffix test summed its match count across renderers, so hub-page.tsx
matching twice let another renderer drop to zero matches and still pass. Assert
per file instead.
Extending it turned up a fifth surface: the training model picker names the
unit inside the translation, so {total} kept a GB suffix in all 12 locales.
Relabel it, using Gio for fr and GiB for ru per IEC 80000-13 and GOST 8.417.
{est} stays GB: estimateLoadingVram divides by 1e9, so it really is decimal.
Also pin floating-monitor.tsx and resources-tab.tsx, which format through a
helper: formatGb is the decimal disk one and no memory value may reach it.
|
Codex Review: Didn't find any major issues. More of your lovely PRs please. 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". |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 5effd4ec98
ℹ️ 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 RENDERERS = [ | ||
| "features/model-picker/components/model-config-page.tsx", | ||
| "features/images/images-page.tsx", |
There was a problem hiding this comment.
Include the model-row tooltip in the GiB fix
When a user hovers an over-budget or tight-fit non-GGUF model row, ModelRow still renders the binary gpuGb value as GPU: ${gpuGb}GB in pickers.tsx:855-857; that value ultimately comes from memoryTotalGb. Because this active renderer is absent from RENDERERS, the new regression test passes while the original misleading total remains in the chat, image, video, and audio model pickers. Change that tooltip to GiB and add features/model-picker/components/model-selector/pickers.tsx to this guard.
Useful? React with 👍 / 👎.
* Studio: label GPU totals GiB, the unit they are actually in memory_total_gb comes off props.total_memory / 1024**3, so it is GiB, and nothing between the driver and the pixel subtracts a budget, reserve or headroom from it. Four renderers printed it with a GB suffix, which makes a 48 GB card read as 45 GB and was reported as broken VRAM detection: 45 GiB is 48.3 GB, so the number was right and only the unit was wrong. The model information sidebar is the one the report came from; the images and video GPU pickers and the wizard preview card carry the same string. hub-page and the About tab already said GiB, which is what makes the other four read as a discrepancy rather than a convention. Pinned by a test over every renderer of the field, because the fourth site turned up only after the first three were fixed. Fixes #9551 * Label the localized GPU total GiB and check every renderer separately The suffix test summed its match count across renderers, so hub-page.tsx matching twice let another renderer drop to zero matches and still pass. Assert per file instead. Extending it turned up a fifth surface: the training model picker names the unit inside the translation, so {total} kept a GB suffix in all 12 locales. Relabel it, using Gio for fr and GiB for ru per IEC 80000-13 and GOST 8.417. {est} stays GB: estimateLoadingVram divides by 1e9, so it really is decimal. Also pin floating-monitor.tsx and resources-tab.tsx, which format through a helper: formatGb is the decimal disk one and no memory value may reach it. * Tighten the comments in the GiB suffix test
* refactor(studio): move gguf-fit to the shared lib
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.
* feat(studio): size parallel slots and speculative decoding in kv-cache-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.
* feat(studio): show a VRAM memory bar on downloaded models
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.
* fix(studio): align memory-bar estimates with what the loader does
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.
* [pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
* feat(studio): make the memory bar opt-in, off by default
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.
* fix(studio): quieten the memory bar and address review feedback
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.
* fix(studio): stop the memory bar over-estimating three ways
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.
* i18n(studio): translate the memory bar strings into every overlay
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.
* [pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
* Studio: price the MTP reserve the loader will actually take
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.
* Studio: key the memory estimate by the request it actually made
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.
* Studio: draw the memory bar only where the budget is really VRAM
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 (#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 #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.
* Studio: take the KV estimate off the event loop
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.
* Studio: pin the /kv-cache-estimate compatibility contract
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.
* Studio: pin the memory bar opt-in default
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.
* [pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
* Studio: price the settings the launch actually applies
The estimate answered for a request that did not describe the load. Four
launch settings changed the reservation and none reached the route:
spec_draft_n_max sets the rollback states a drafter keeps, the draft cache
dtype sizes them, ctx_checkpoints buys saved SWA context, and disabling
vision frees the projector. A row with vision off was charged for a
projector the server would never allocate.
The route now takes all four and answers with projector_bytes broken out,
plus spec_unpriced for the case it can see a drafter it cannot size. A
number that is a guess is now labelled as one instead of being drawn as a
measurement.
Every parameter is optional and every response field is an addition, so a
client from the previous build sends the same request and reads the same
keys back. test_kv_cache_estimate_compat.py pins that.
* Studio: key the estimate by every field the request carries
The cache key stopped at the slot count, so the four settings the previous
commit added to the request all collapsed into one entry: turning vision
off, or changing the draft depth, returned the answer computed for the old
settings and the bar did not move. Zero is a real value for draft depth and
for checkpoints, so the key distinguishes it from unset rather than folding
both to a default.
Three more things the bar did not react to:
- A pinned quant row keyed on the repo id, so two cached copies of one
quant shared an answer and the bar could describe a file the click does
not open. It now carries the row's own load id.
- Changing the GPU mode or the speculative mode in another tab left a
mounted bar showing the old figure. The subscription now also takes the
native storage event, which fires only in other documents, so a write in
this tab is still handled by the existing custom event and is not
processed twice.
- A drafter the backend could see but not size was drawn as if it cost
nothing. The bar abstains on spec_unpriced instead of showing a total it
knows is short.
Also replaces a raw NUL byte in the cache-key separator with the \x00
escape. The string was the same one character either way, but the byte made
model-memory.ts binary to git and invisible to grep.
* Studio: say what happens over budget, rather than that it fails
"Too large to load" is not what llama.cpp does. A model that exceeds VRAM
loads, with the layers that did not fit running on the CPU, and it is slow
rather than broken. The old wording told a user their model would not open
and pushed them off a quant that works.
* Studio: apply the repo's kwarg spacing to the estimate route
* Studio: stop the bar reporting a fit it cannot support
Six ways the round-5 review found the bar saying "fits" for a load that would
not. All six fail in the same direction, which is the one that matters: a
spurious warning is an annoyance, a missing one is the feature failing silently
at the moment it was supposed to help.
Backend:
- Auto is not a mode that declines a sidecar. The load planner promotes it to
DSpark or DFlash whenever the repo ships one and the binary supports it,
ahead of MTP, so reading only the explicit modes left a DSpark reserve of
about 11 GB missing from an Auto row. Gated on the binary's own capability,
as the planner is, so a host that cannot run one is not blanked for nothing.
- Context checkpoints are reported as their own share of the cache. llama.cpp
keeps those snapshots in host heap and the planner's GPU figure subtracts
them, so folding them into a VRAM bar warns OOM over memory that never
reaches the card. Derived by difference against the same call with none,
which is how the planner derives it.
- The drafter's own weights are reported separately from the rest of its
reserve, since that part is fixed.
Frontend:
- The budget is the dedicated-only aggregate wherever the inventory mixes
pools. On a discrete card beside a Vulkan iGPU the combined total adds the
iGPU's allowance, which is a capped view of free system RAM, so a model was
judged against real VRAM plus whatever the desktop was not using.
`sharedMemory` cannot carry this on its own: it is every(), so a mixed host
reads false and reaches the budget unchallenged.
- Auto-fit softening no longer covers the whole speculative segment. Shrinking
context cannot shrink a drafter's resident weights, so target plus drafter
over budget is a hard verdict at any length.
- Pass-through args that resize the cache make the bar abstain. --swa-full
replaces a sliding window with a full-context cache and the loader honours
it, so a bar priced from the structured controls alone was describing a
different load.
* Studio: apply the repo's kwarg spacing to the estimate route
* Studio: take the load planner's own figures instead of guessing at them
The round-6 review found the Auto sidecar guard added last commit never ran. It
referenced _snapshot_dir_of and _companion_snapshot_sibling, which live in
_resolve_mtp_drafter's local scope, so every call raised NameError into the
surrounding except and left spec_unpriced false. A guard that fails quietly is
worse than no guard, since the bar looks like it checked. Imported properly,
and the tests now assert the outcome rather than that the block runs: they fail
on the parent commit, which the previous ones did not.
Auto also only looked at HF snapshots, so a plain local folder never found its
sidecar. It now resolves through detect_dspark_file and detect_dflash_file, the
same detectors that populate gguf_dspark_file and gguf_dflash_file at load.
The larger change is that the route now also asks _gguf_memory_breakdown, the
load planner's own estimator, and returns its compute_bytes, gpu_bytes and
total_bytes. That answers a whole class of review findings at once rather than
one at a time: the planner already applies the inherited environment
(LLAMA_ARG_CACHE_TYPE_K/V, LLAMA_ARG_SWA_FULL, LLAMA_ARG_CTX_SIZE), derives the
companion search roots the loader derives, and counts the compute buffers. Each
of those was a separate defect here because this route was reproducing the
planner term by term, and kept reproducing it incompletely.
Added beside the existing fields rather than replacing them: the planner defines
weights_bytes as the weights plus whichever projector and drafter the launch
opens, while this route's field shipped meaning the quant file alone. Moving it
would change a number an existing caller already reads.
The bar now counts the compute buffers in its total, folded into the cache
segment: every launch reserves them, they scale with slots and micro-batch, and
a row near the budget could report a fit while omitting gigabytes.
Finally the VRAM settings request is gated on a row having a plan rather than on
the feature being enabled. Every row in the list mounts the hook, including
remote and undownloaded ones, and that lookup holds no read-through cache, so
scrolling a long list issued one request per row that appeared.
* Studio: draw the verdict from the planner's total, not a partial sum
Round 6 added the planner's figures to the response and then left the frontend
reconstructing the verdict out of the legacy fields, so every case the
delegation fixed on the backend still displayed the old underestimate. The bar
now takes gpu_bytes as the total. The individual terms still drive the segment
geometry, which is what they are good for.
I declined gpu_bytes last round on the grounds that it carried placement
semantics the route could not reproduce. That was wrong: an unset gpu_memory_mode
is Auto, which the planner documents as 1.0, and budgetIsMeaningful already
abstains wherever a config pins placement, so every case the bar draws in is the
case gpu_bytes describes.
The auto-fit floor has the same shape of gap. It counted the drafter's weights
and nothing else, while a flat compute buffer and a Hybrid Mamba target's
rollback state are equally fixed and can be several GiB. Rather than name those
terms and miss the next one, the route prices the same plan a second time at a
minimal context and returns what is left as gpu_floor_bytes: whatever survives
shrinking the context is by definition what shrinking it cannot fix.
Also:
- nBatch, nUbatch and tensorParallel now reach the planner. The compute buffers
scale with them, and the planner was defaulting them.
- Extras that add resident files (--lora, --control-vector, --mmproj, a
hand-named drafter) make the bar abstain. They add a term that was never
priced rather than reshaping one that was, so the total is a floor.
- The runtime-store subscription is a no-op while the bar is disabled. It
watches the whole chat runtime store, which ticks on every streamed token, and
every row mounts this hook, so a disabled feature still woke every row per
token.
- The on-device card sends its own path. It has the exact file Run opens, while
the estimate was resolving from repoId alone, and a custom GGUF with no Hub
repo had the bar suppressed outright despite a usable path being right there.
The new backend test asserts the planner figures are actually present. The
delegation sits inside a try/except so an unsizable model still gets its KV bar,
and that except had already swallowed one silent failure this cycle.
* Studio: close the gaps the planner delegation left behind
Six follow-ups from round 8, four of them consequences of the delegation added
in the last two commits.
- A planner result of zero GPU bytes was folded into "no answer" by `or None`.
Inherited placement such as LLAMA_ARG_DEVICE=none makes a launch entirely CPU
resident, and discarding that sent the bar back to summing segments and
drawing VRAM pressure for a load that touches no card. Zero is now preserved,
and the bar draws nothing for it, since a VRAM bar has nothing to say about a
launch that reserves no VRAM.
- Tensor parallelism replicates its compute buffers on every device in the pool,
and both planner calls left n_devices at 1. The device count now comes from
_guard_device_count, the same source the load panel uses, and only in tensor
mode, where the replication actually happens.
- n_ubatch reached the planner but not the itemized KV estimate beside it.
Compact SWA sizing adds the micro-batch to its cell allowance, so a large
override produced a KV segment and a per-token readout that disagreed with the
total drawn next to them.
- The on-device card still required a fetched variant, which is exactly what a
direct .gguf path does not have: those entries skip variant selection, so
selectedQuant is null for the local files the previous commit claimed to
cover. The route resolves a direct file to itself, and the card no longer
waits for a quant label that is never coming.
Two gaps in the extra-args classifiers, both the same shape as the ones already
there:
- --flash-attn off changes the cache layout rather than its size: the estimator
then pads variable-width V tensors to the model-wide maximum.
- An extras --spec-type beats the structured speculative mode outright, so a
config reading "off" can still open an embedded NextN head, with the draft KV
and the target rollback state both missing from the total.
Both now make the bar abstain.
* Studio: check the abstention lists against the parsers that enforce them
Three rounds running found a missing flag spelling here, each fixed by adding
one more string, which is a fix that lasts until the next alias. llama.cpp
accepts several spellings for most of these and the backend groups them into
frozensets, so this adds the ones that were missing and then a test that reads
those frozensets and fails when one contains a flag the bar would not act on.
Missing placement spellings: -dev, the --cpu-moe pair, the drafter's own
--spec-draft-ngl group and --spec-draft-device, and the projector's
--mmproj-offload pair. A -dev cuda0 on a multi-GPU host confines the load while
the bar was comparing it against aggregate VRAM, and a drafter or projector
pinned to the CPU was host memory charged to the card.
Missing draft-memory spellings: --draft-max and --draft-min, the -ctkd and
-ctvd cache-dtype aliases, and --swa-checkpoints, upstream's older spelling of
--ctx-checkpoints.
The parity test is one-directional on purpose. The frontend lists are a superset
by design, since they also carry flags no single backend set groups together, so
requiring equality would fail on a difference that is intended. The invariant is
that everything the launch honours in these groups is recognised here.
Also gates the picker's sole-quant row on the task. The Images and Video pickers
deliberately keep diffusion GGUFs listed, and those load through the diffusion
planner on a single torch device rather than the aggregate inference pool. When
the KV estimator returns unsized for one, the bar falls back to the file size
and draws a weights-only verdict anyway, which is a confident number about the
wrong runtime.
One existing assertion was wrong and is corrected rather than worked around:
--gpu-layers-draft was listed as a near-miss that must not match, but it is in
_DRAFT_GPU_LAYER_FLAGS and does own placement, just the drafter's.
* Studio: price the launch that will run, not the request that was made
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.
* Studio: price the inherited environment in the itemized figures too
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.
* Studio: say whether the context is pinned, rather than inferring it
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.
* Studio: normalise pass-through flags the way the launch parses them
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.
---------
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: danielhanchen <[email protected]>
* Studio: freeze both memory-estimate route contracts before consolidating /api/inference/estimate-memory and /api/models/kv-cache-estimate already share the _gguf_memory_breakdown planner, so their arithmetic cannot drift, but their response contracts are still separate and are about to be consolidated onto one implementation. The hazard is not shape drift, which a typechecker catches. weights_bytes exists on both routes, is an int on both, and means different things: every resident file on the inference route (weights plus projector plus drafter), the quant file alone on the models route, where the planner aggregate travels separately as gpu_bytes / total_bytes / gpu_floor_bytes. Unifying the key changes the number under whichever caller loses, with no JSON change for a client to notice. These tests pin both envelopes and that collision, so the consolidation cannot silently resolve it. The models route has no response_model at all, so nothing else enforces its shape. Verified by mutation rather than by passing: adding a key, removing a key, repointing weights_bytes at the planner aggregate and disabling the delegation each fail the suite. The first draft did not catch the aggregate swap, because the planner delegation is gated on _cached_estimate_config resolving the repo to this disk and is skipped for a synthetic repo id, leaving every planner field present and null. A freeze written over that fixture asserts nothing. Pinning the config so the planner returns real figures is what makes these bite. * Studio: give both memory-estimate routes one canonical contract The two routes already share the _gguf_memory_breakdown planner, so their arithmetic agrees. Their vocabulary did not, and the sharp edge is weights_bytes: it exists on both, is an int on both, and means every resident file on /inference/estimate-memory but the quant file alone on /models/kv-cache-estimate. Nothing in the type system separates those, so a caller reading the wrong one is simply wrong, quietly. Adds models.inference.MemoryEstimate as the shared contract. It deliberately has no weights_bytes at all: the name is replaced by quant_file_bytes and resident_files_bytes, which each say which they are, and it is absent rather than redefined so no new reader can pick it up and guess. core/inference/memory_contract.py holds the projections back onto each route's existing wire shape. Both legacy mappings now sit side by side in one file, which is the only place either is written down, instead of being implied by two handlers that never referenced each other. /kv-cache-estimate is rewired onto the projection and its JSON is unchanged, which the contract-freeze suite from the previous commit verifies rather than assumes. Two subtleties it caught while this was being written: - gpu_bytes must keep 0 distinct from None. Zero is a real answer, an inherited LLAMA_ARG_DEVICE=none launch that touches no card; None means the planner never ran. The first draft applied `or None` uniformly and reintroduced a bug this route had already fixed. MemoryEstimate.gpu_bytes is Optional for that reason. - the quant figure is not clamped against the resident total, though a quant file cannot really exceed the files containing it. The two come from different resolvers, and clamping truncated a 4.1 GB quant to a 373 byte synthetic header rather than catching anything. kv_bytes is passed into the projection rather than read off the estimate: this route prices the target cache itself and the planner's figure is not interchangeable with it. * Studio: route the Load Model estimate through the shared contract too /inference/estimate-memory now builds the same canonical MemoryEstimate that /models/kv-cache-estimate builds, and projects back to EstimateMemoryResponse. Both routes go through one vocabulary; neither wire shape changes. weights_bytes keeps its aggregate meaning here through project_estimate_memory_response, which is the counterpart of the quant-file mapping the sibling route uses. The two sit next to each other in core/inference/memory_contract.py so the difference is impossible to read past. quant_file_bytes is 0 on this route rather than a stand-in. This handler 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 response does not carry the field, and inventing a value would be a wrong number for the sake of a non-null. * Studio: one presentation core for both memory surfaces The Load Model panel and the Hub memory bar were fed byte-identical figures by one backend planner and still disagreed about how to present them, 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. Each difference was defensible alone. Together they meant one model could read as fitting on one screen and not on the other. src/lib/memory/ now holds the shared core: - format.ts. There were two exported functions called formatMemoryGb, one per surface, both (number) => string, one taking bytes and one taking gibibytes, printing different labels. Importing the wrong one was off by 1024^3 and typechecked cleanly. They are replaced by formatGiB and formatBytesGiB, whose names carry the unit, plus formatKvRate. - thresholds.ts. The fit ratio and the pressure ramp measure different things and keep different values, but they now differ in one file rather than per surface. - verdict.ts. A superset vocabulary, not a winner: the panel's tight band and the bar's why-it-exceeds cause both survive, so neither surface loses a distinction it used to make. memory-fit.ts and model-memory.ts stay as each surface's entry point and become thin re-exporters, so no call site moves. memory-fit.ts keeps relative imports with explicit extensions rather than the @/ alias: three tests load it directly under node --experimental-strip-types without a bundler resolver, and an alias there breaks all three. Its docstring said "no imports" and meant no ALIAS imports; that is now written down. Two user-visible labels change, both mislabels rather than preferences: - the panel printed GiB values labelled GB across seven figures, the defect #9570 fixed elsewhere. vram-total-gib-suffix.test.ts could not see it, since its regex only matches interpolations naming a *TotalGb and neither module was in its list. That guard now reads the shared module, covers all three formatters including the panel's, and separately asserts neither surface has redefined one locally. - formatKvRate divided by 1024 and labelled the result KB/MB. Existing assertions were updated to the new expectations rather than relaxed, and two fixtures were retuned rather than left passing: at the wider budget the speculative-reserve case no longer tipped over, so it would have gone green while measuring nothing. * Studio: decide unified memory from the hardware, not from the platform The Load Model panel asked usePlatformStore(s => s.appleSilicon) whether the GPU and the rest of the system share one memory pool, and passed that answer to resolveMemoryCapacityGb. On a ROCm APU the answer was false, so the panel charged one pool as discrete VRAM PLUS host RAM: the same bytes counted twice, and a ceiling high enough to report a fit for a load that cannot open. The correct signal already existed. 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 exactly that flag. Only the panel was reading the platform instead of the hardware. The two uses are now separate rather than renamed wholesale, because they are genuinely different questions: - isAppleUnifiedMemory still drives the WORDING. "Unified" is what Apple calls its pool; an AMD APU's is a "Shared" one, and the panel already prints both. - hasUnifiedMemory drives the CAPACITY, and falls back to the Apple check while the device probe is in flight, so it is never a weaker answer than before. A discrete card is unaffected: its devices do not report unified_memory, so nothing about an ordinary NVIDIA host moves. Covered by tests on resolveMemoryCapacityGb for the APU pool and for a discrete card, plus a source assertion that the panel hands the capacity call the general signal. That last one is not decoration: the behavioural tests pin what the resolver does with each flag, not which flag it is given, and they both pass on the unfixed panel. Verified by reverting the fix and watching only the source assertion fail. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Studio: harden the memory contract and pin it across the platform matrix Adversarial pass over this PR's own changes. Three real defects, two of them mine, plus a simulation matrix that would have caught all three. Fixed, introduced by this PR: - routes/models.py assigned gpu_bytes, compute_bytes, total_bytes and n_ctx onto a MemoryEstimate AFTER building it. Pydantic does not validate assignment by default, so a post-construction write puts whatever it is handed straight onto the wire. Measured rather than assumed: on pydantic 2.13 m.gpu_bytes = "not an int" succeeds, and a declared int field accepts None the same way. Those four are now parameters of build_memory_estimate, so the model is built once and validated once. gpu_bytes needs a sentinel rather than a None default because it has three states: a number, a real None meaning the planner never ran, and "use the breakdown's". Fixed, pre-existing but in scope because it made the two surfaces disagree: - computeModelMemory turned a non-finite weightsBytes into "model-exceeds": a full destructive 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 reaches it without trying. classifyMemoryFit on the panel already answered "unknown" for the same input, which is the divergence this PR exists to remove. Null and undefined are untouched: those mean "has not arrived", an ordinary state. New simulation coverage: - memory-cross-surface-matrix.test.ts: [linux, wsl, win32, darwin] x nine device inventories (NVIDIA single and dual, ROCm discrete, ROCm APU, AMD Vulkan iGPU, Intel iGPU, Apple unified, mixed dGPU+iGPU, CPU only) x four footprints, minus the physically impossible cells, checked against six properties: no false fit, no bar/panel contradiction, one label per byte count, no pool counted twice, CPU-only draws nothing, and no NaN or Infinity reaching a label. 128 cells. The Infinity defect above is what P-hostile found. - test_memory_contract_platforms.py: the same four platform keys x six placements, pinning that both wire shapes are byte-identical everywhere and that weights_bytes keeps its own meaning per route in every cell. - Old-backend degradation: a backend that never sends unified_memory leaves hasUnifiedMemory exactly equal to the appleSilicon check it replaced, in both directions. Verified in a clean uv venv holding only pytest, pydantic, fastapi, structlog, huggingface_hub, psutil, pyjwt, passlib, bcrypt and cryptography: 710 passed. The only two failures there need the real transformers package and pass with it. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Studio: scope unified memory to the pin, and share one budget with the fit badge Two P2 review items, both reproduced before agreeing. 1. The unified-memory flag was host-wide. inferenceGpu.unifiedMemory is devices.some(...) over the whole inventory, so an APU beside a discrete card made it true, and a pin naming ONLY the discrete card then told resolveMemoryCapacityGb the two are one pool. Measured on a 16 GiB pin with an APU present and 128 GiB of RAM: totalCapacityGb collapsed from 143.52 to 15.52 GiB, so the panel warned "more than this machine holds" for a load that fits comfortably. That is a regression this branch introduced; on main the flag was the Apple check and read false there. hasUnifiedMemory now narrows to the pinned devices before asking, falling back to the whole inventory when nothing is pinned. The Apple check stays host-wide and unconditional: there every device really is the one pool, and it also covers the window before the per-device probe lands. SystemGpuDevice carries unifiedMemory per device for this, alongside sharedMemory, which is per device for the same reason. 2. The Hub fit badge and the memory bar render on the same row and judged against different budgets: gguf-fit.ts held 0.90 while the bar used the loader's own 0.97. gguf-fit now re-exports the shared constant. Worth being exact about what that buys, because the review item claims it removes the contradiction and it does not. Measured over 15-24 GiB on a 24 GiB card, badge-vs-bar disagreements go from 11/19 sizes to 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 no constant can reconcile them. Rewiring the badge onto the planner is a separate change with its own blast radius, since it also drives a filter. Frontend: 5677 passed, typecheck and build clean. * Do not treat a mixed GPU selection as unified memory Scoping the unified-memory flag to the pinned devices fixed the discrete-only pin, but the quantifier was still `.some()`, so a set holding one APU and one discrete card read as a single pool. That is every unpinned load on such a host, and any pin naming both. Measured on a 48 GiB APU beside a 16 GiB discrete card with 128 GiB of system RAM: unpinned, .some() gpu 62.08 total 62.08 singlePool true unpinned, .every() gpu 62.08 total 128.00 singlePool true pin both, .some() gpu 62.08 total 62.08 singlePool true pin both, .every() gpu 62.08 total 143.52 singlePool false One device with its own memory means there is real VRAM beside system RAM, so the two are not one pool and the RAM must not be discarded. `[].every()` is true, so a host with no probed devices would read as a unified-memory machine; guarded explicitly rather than relying on the caller never passing an empty set. use-gpu-info.ts deliberately keeps `.some()`. It answers a different question, whether the host has any unified-memory device at all, and is noted as such so the two are not "fixed" into agreement later. * Correct the memory-estimate scene's unit mirror to GiB The Playwright scene builds its expected strings with a Python mirror of the panel's formatter, and that mirror printed "GB" because the panel did. Both divided by 1024**3 and both called the result a decimal gigabyte, so the test agreed with the app about the wrong label and the agreement was what made it invisible. Staging CI caught it on this branch: row header text: 'GPU 4.75 GiB Total 5.50 GiB' FAIL: the row does not show the returned total '5.50 GB' Every figure is byte for byte what it was. Only the unit moved, which is the change this branch makes to the panel, so the mirror moves with it. * Separate the unified pool's size from the fact that it is one pool `unified_memory` on the wire is ROCm-only: hardware.py sets it from `_rocm_known_unified` and nothing produces it for Apple. So the panel's general signal is Apple-or-ROCm, and it was feeding a resolver branch whose comment reads "Apple reports the one pool as the GPU budget already". True for Apple, where memory_total_gb is the machine's unified memory. False for a BIOS-carved window onto system RAM. Measured on a 96 GiB machine carving a 48 GiB window, budget 0.97: gpu total singlePool Windows unified=F 46.56 96.00 true Windows unified=T 46.56 46.56 true Linux unified=F 46.56 142.56 false Linux unified=T 46.56 46.56 true Both are wrong on Linux and in opposite directions. Before this branch the ceiling double counted the window that already sits inside the RAM; after it, the ceiling discarded 49.44 GiB the load can really use, and the panel warned that a 60 GiB load exceeds a machine holding 96. The backend has said which figure is real all along, 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." `unifiedMemory` still classifies the pool. A new `unifiedPoolReportedAsGpuMemory` says whether the GPU figure is that pool's size. The ROCm case falls into the existing `Math.max(gpuCapacityGb, systemRamTotalGb)` branch the Vulkan iGPU already used for this exact reason rather than into new arithmetic. The flag defaults to true, so callers written before the ROCm case keep their answer untouched. Apple is deliberately not routed through the RAM branch: max(93.12, 96) would return the raw 96 and drop the VRAM Budget. Both are pinned as tests, and both new tests were confirmed to fail against the unfixed resolver. Score the Hub fit badge against the saved VRAM Budget Sharing one default constant fixed the loading and old-backend case. It did not reach the case where the user has actually saved a fraction: the badge kept applying 0.97 while the memory bar on the SAME ROW consumed the live value from use-model-memory.ts. On a 24 GiB card with a saved 0.90 the loader admits at 21.6 GiB while the badge scored against 23.28 GiB: size required badge [email protected] 18.0 21.70 fits OVER 18.5 22.27 fits OVER 19.0 22.85 fits OVER `GgufFitInput` takes an optional `budgetFraction`, and the Hub card reads the live value through a new `useVramBudgetFraction`. It is threaded into all three fit-scoring calls on the row, not only the badge: the sort and the menu use the same classifier and would otherwise rank rows against a line the badge no longer applies. Absent means "use the shared default", not "the whole card": scoring an unloaded fraction against 1.0 admits loads the loader refuses, which is the same error in the other direction. Zero, negative, above-one and non-finite values fall back too, since this arrives from a settings route; 1.0 is honoured, being a legitimate saved value. The hook is the fifth caller of subscribeVramBudgetSettings plus loadVramBudgetSettings and the first not to roll the pattern by hand. It subscribes before loading, so a save committed while the GET is in flight is not lost. Frontend suite 5685 pass, 0 fail; typecheck and build clean. * Do not count a Linux APU's window as VRAM beside system RAM Third face of one reporting split, exposed by the previous two fixes. hardware.py sets shared_memory only on Windows, so the same APU arrives as shared_memory true there and unified_memory true / shared_memory false on Linux. Making a mixed set non-unified correctly routed the ceiling to `dedicatedCapacityGb + systemRamTotalGb`, and `dedicated` was computed from sharedMemory alone. A 48 GiB APU beside a 16 GiB discrete card on a 128 GiB host at 0.97: before total = 190.08 GiB after total = 143.52 GiB (16 * 0.97 + 128) 46.56 GiB of capacity that does not exist, in the direction that admits a load. The two flags are folded where they are read rather than the capacity path learning about a second one: they answer the same question, and the split is a platform reporting detail, not a distinction the arithmetic should carry. SystemGpuDevice already grew unifiedMemory earlier in this branch and satisfies MemoryCapacityDevice structurally, so the panel carries it through with no call-site change. A test asserts Windows and Linux now price the same APU identically, which is the property that matters: if those diverge again, one platform charges differently for the same silicon. Credit the VRAM budget, not the raw card, once layers spill vram_budget_settings.py describes the reserve as "a slice of every card that the model and KV cache may not use", so the GPU's contribution to a partly offloaded load is the budget. Adding the raw card to the RAM allowance invented capacity the loader will not give. At the legal minimum 0.80 on a 24 GiB card with 16 GiB of RAM: budget 19.20 combined raw 32.00 combined@budget 27.20 size required before after 23 27.45 partial oom 24 28.60 partial oom 25 29.75 partial oom 26 30.90 partial oom Four quant sizes the badge and the fit sort recommended for a card that cannot load them. `marginal` deliberately keeps the raw card. `fits` returns for everything at or under the budget, so scoring this band against the budget too would make it unreachable; it names the gap between the budget and the card, which is a warning rather than a claim of admission. A test pins that it stays reachable. Frontend suite 5689 pass, 0 fail; typecheck and build clean. Both fixes were confirmed to fail their new tests when reverted. * Carry the saved budget and the unified pool to every surface Three consequences of the previous two rounds, each on a surface the earlier fix did not reach. Local On Device card ranked against the default budget. The live fraction went to the Hub download card's three fit-scoring calls and not to sortLocalGgufVariants, so that card rendered a memory bar using the saved fraction directly above a quant menu ranked against 0.97. Free capacity answered a whole-load question with a carved window. resolveMemoryFit sends the WHOLE load to freeGpuCapacityGb as soon as the pool is single, and marking a ROCm APU single-pool is what this branch did, so a 60 GiB load on a 96 GiB machine with 60+ GiB free was warned as not fitting a 48 GiB window. A non-Apple unified pool now takes the host view, the same discriminator the capacity side uses, so the two cannot answer differently. FreeVramDevice also folds unifiedMemory the way MemoryCapacityDevice does; measured, that changes nothing for an APU beside a discrete card (52.08 either way, since a fully shared device already contributes its free once) and matters when a SECOND view of the same pool appears, an APU beside a Vulkan iGPU: 77.12 -> 38.56. One GET per mounted card. loadVramBudgetSettings has no read-through cache by design and clears its shared promise once each request settles, so it coalesces only overlapping callers; a catalog mounting cards through scrolling and filtering issued a settings GET per card, and a 404 per card on an older backend. The FRACTION is now cached module-wide and kept live by the change event every reader already subscribes to, while the loader keeps its always-refetch behaviour for the callers that need reloadRequired. usableSystemRamGb was computed inline in JSX and is now hoisted, because the free-capacity memo needs the same figure and two copies of the same headroom subtraction is how they drift. Frontend suite 5694 pass, 0 fail; typecheck and build clean. Each fix was confirmed to fail its own test when reverted; one first-draft test asserted a double count that does not occur and was replaced with the case that does. --------- Co-authored-by: danielhanchen <[email protected]> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
* Studio: freeze both memory-estimate route contracts before consolidating /api/inference/estimate-memory and /api/models/kv-cache-estimate already share the _gguf_memory_breakdown planner, so their arithmetic cannot drift, but their response contracts are still separate and are about to be consolidated onto one implementation. The hazard is not shape drift, which a typechecker catches. weights_bytes exists on both routes, is an int on both, and means different things: every resident file on the inference route (weights plus projector plus drafter), the quant file alone on the models route, where the planner aggregate travels separately as gpu_bytes / total_bytes / gpu_floor_bytes. Unifying the key changes the number under whichever caller loses, with no JSON change for a client to notice. These tests pin both envelopes and that collision, so the consolidation cannot silently resolve it. The models route has no response_model at all, so nothing else enforces its shape. Verified by mutation rather than by passing: adding a key, removing a key, repointing weights_bytes at the planner aggregate and disabling the delegation each fail the suite. The first draft did not catch the aggregate swap, because the planner delegation is gated on _cached_estimate_config resolving the repo to this disk and is skipped for a synthetic repo id, leaving every planner field present and null. A freeze written over that fixture asserts nothing. Pinning the config so the planner returns real figures is what makes these bite. * Studio: give both memory-estimate routes one canonical contract The two routes already share the _gguf_memory_breakdown planner, so their arithmetic agrees. Their vocabulary did not, and the sharp edge is weights_bytes: it exists on both, is an int on both, and means every resident file on /inference/estimate-memory but the quant file alone on /models/kv-cache-estimate. Nothing in the type system separates those, so a caller reading the wrong one is simply wrong, quietly. Adds models.inference.MemoryEstimate as the shared contract. It deliberately has no weights_bytes at all: the name is replaced by quant_file_bytes and resident_files_bytes, which each say which they are, and it is absent rather than redefined so no new reader can pick it up and guess. core/inference/memory_contract.py holds the projections back onto each route's existing wire shape. Both legacy mappings now sit side by side in one file, which is the only place either is written down, instead of being implied by two handlers that never referenced each other. /kv-cache-estimate is rewired onto the projection and its JSON is unchanged, which the contract-freeze suite from the previous commit verifies rather than assumes. Two subtleties it caught while this was being written: - gpu_bytes must keep 0 distinct from None. Zero is a real answer, an inherited LLAMA_ARG_DEVICE=none launch that touches no card; None means the planner never ran. The first draft applied `or None` uniformly and reintroduced a bug this route had already fixed. MemoryEstimate.gpu_bytes is Optional for that reason. - the quant figure is not clamped against the resident total, though a quant file cannot really exceed the files containing it. The two come from different resolvers, and clamping truncated a 4.1 GB quant to a 373 byte synthetic header rather than catching anything. kv_bytes is passed into the projection rather than read off the estimate: this route prices the target cache itself and the planner's figure is not interchangeable with it. * Studio: route the Load Model estimate through the shared contract too /inference/estimate-memory now builds the same canonical MemoryEstimate that /models/kv-cache-estimate builds, and projects back to EstimateMemoryResponse. Both routes go through one vocabulary; neither wire shape changes. weights_bytes keeps its aggregate meaning here through project_estimate_memory_response, which is the counterpart of the quant-file mapping the sibling route uses. The two sit next to each other in core/inference/memory_contract.py so the difference is impossible to read past. quant_file_bytes is 0 on this route rather than a stand-in. This handler 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 response does not carry the field, and inventing a value would be a wrong number for the sake of a non-null. * Studio: one presentation core for both memory surfaces The Load Model panel and the Hub memory bar were fed byte-identical figures by one backend planner and still disagreed about how to present them, 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. Each difference was defensible alone. Together they meant one model could read as fitting on one screen and not on the other. src/lib/memory/ now holds the shared core: - format.ts. There were two exported functions called formatMemoryGb, one per surface, both (number) => string, one taking bytes and one taking gibibytes, printing different labels. Importing the wrong one was off by 1024^3 and typechecked cleanly. They are replaced by formatGiB and formatBytesGiB, whose names carry the unit, plus formatKvRate. - thresholds.ts. The fit ratio and the pressure ramp measure different things and keep different values, but they now differ in one file rather than per surface. - verdict.ts. A superset vocabulary, not a winner: the panel's tight band and the bar's why-it-exceeds cause both survive, so neither surface loses a distinction it used to make. memory-fit.ts and model-memory.ts stay as each surface's entry point and become thin re-exporters, so no call site moves. memory-fit.ts keeps relative imports with explicit extensions rather than the @/ alias: three tests load it directly under node --experimental-strip-types without a bundler resolver, and an alias there breaks all three. Its docstring said "no imports" and meant no ALIAS imports; that is now written down. Two user-visible labels change, both mislabels rather than preferences: - the panel printed GiB values labelled GB across seven figures, the defect #9570 fixed elsewhere. vram-total-gib-suffix.test.ts could not see it, since its regex only matches interpolations naming a *TotalGb and neither module was in its list. That guard now reads the shared module, covers all three formatters including the panel's, and separately asserts neither surface has redefined one locally. - formatKvRate divided by 1024 and labelled the result KB/MB. Existing assertions were updated to the new expectations rather than relaxed, and two fixtures were retuned rather than left passing: at the wider budget the speculative-reserve case no longer tipped over, so it would have gone green while measuring nothing. * Studio: decide unified memory from the hardware, not from the platform The Load Model panel asked usePlatformStore(s => s.appleSilicon) whether the GPU and the rest of the system share one memory pool, and passed that answer to resolveMemoryCapacityGb. On a ROCm APU the answer was false, so the panel charged one pool as discrete VRAM PLUS host RAM: the same bytes counted twice, and a ceiling high enough to report a fit for a load that cannot open. The correct signal already existed. 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 exactly that flag. Only the panel was reading the platform instead of the hardware. The two uses are now separate rather than renamed wholesale, because they are genuinely different questions: - isAppleUnifiedMemory still drives the WORDING. "Unified" is what Apple calls its pool; an AMD APU's is a "Shared" one, and the panel already prints both. - hasUnifiedMemory drives the CAPACITY, and falls back to the Apple check while the device probe is in flight, so it is never a weaker answer than before. A discrete card is unaffected: its devices do not report unified_memory, so nothing about an ordinary NVIDIA host moves. Covered by tests on resolveMemoryCapacityGb for the APU pool and for a discrete card, plus a source assertion that the panel hands the capacity call the general signal. That last one is not decoration: the behavioural tests pin what the resolver does with each flag, not which flag it is given, and they both pass on the unfixed panel. Verified by reverting the fix and watching only the source assertion fail. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Studio: harden the memory contract and pin it across the platform matrix Adversarial pass over this PR's own changes. Three real defects, two of them mine, plus a simulation matrix that would have caught all three. Fixed, introduced by this PR: - routes/models.py assigned gpu_bytes, compute_bytes, total_bytes and n_ctx onto a MemoryEstimate AFTER building it. Pydantic does not validate assignment by default, so a post-construction write puts whatever it is handed straight onto the wire. Measured rather than assumed: on pydantic 2.13 m.gpu_bytes = "not an int" succeeds, and a declared int field accepts None the same way. Those four are now parameters of build_memory_estimate, so the model is built once and validated once. gpu_bytes needs a sentinel rather than a None default because it has three states: a number, a real None meaning the planner never ran, and "use the breakdown's". Fixed, pre-existing but in scope because it made the two surfaces disagree: - computeModelMemory turned a non-finite weightsBytes into "model-exceeds": a full destructive 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 reaches it without trying. classifyMemoryFit on the panel already answered "unknown" for the same input, which is the divergence this PR exists to remove. Null and undefined are untouched: those mean "has not arrived", an ordinary state. New simulation coverage: - memory-cross-surface-matrix.test.ts: [linux, wsl, win32, darwin] x nine device inventories (NVIDIA single and dual, ROCm discrete, ROCm APU, AMD Vulkan iGPU, Intel iGPU, Apple unified, mixed dGPU+iGPU, CPU only) x four footprints, minus the physically impossible cells, checked against six properties: no false fit, no bar/panel contradiction, one label per byte count, no pool counted twice, CPU-only draws nothing, and no NaN or Infinity reaching a label. 128 cells. The Infinity defect above is what P-hostile found. - test_memory_contract_platforms.py: the same four platform keys x six placements, pinning that both wire shapes are byte-identical everywhere and that weights_bytes keeps its own meaning per route in every cell. - Old-backend degradation: a backend that never sends unified_memory leaves hasUnifiedMemory exactly equal to the appleSilicon check it replaced, in both directions. Verified in a clean uv venv holding only pytest, pydantic, fastapi, structlog, huggingface_hub, psutil, pyjwt, passlib, bcrypt and cryptography: 710 passed. The only two failures there need the real transformers package and pass with it. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Studio: scope unified memory to the pin, and share one budget with the fit badge Two P2 review items, both reproduced before agreeing. 1. The unified-memory flag was host-wide. inferenceGpu.unifiedMemory is devices.some(...) over the whole inventory, so an APU beside a discrete card made it true, and a pin naming ONLY the discrete card then told resolveMemoryCapacityGb the two are one pool. Measured on a 16 GiB pin with an APU present and 128 GiB of RAM: totalCapacityGb collapsed from 143.52 to 15.52 GiB, so the panel warned "more than this machine holds" for a load that fits comfortably. That is a regression this branch introduced; on main the flag was the Apple check and read false there. hasUnifiedMemory now narrows to the pinned devices before asking, falling back to the whole inventory when nothing is pinned. The Apple check stays host-wide and unconditional: there every device really is the one pool, and it also covers the window before the per-device probe lands. SystemGpuDevice carries unifiedMemory per device for this, alongside sharedMemory, which is per device for the same reason. 2. The Hub fit badge and the memory bar render on the same row and judged against different budgets: gguf-fit.ts held 0.90 while the bar used the loader's own 0.97. gguf-fit now re-exports the shared constant. Worth being exact about what that buys, because the review item claims it removes the contradiction and it does not. Measured over 15-24 GiB on a 24 GiB card, badge-vs-bar disagreements go from 11/19 sizes to 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 no constant can reconcile them. Rewiring the badge onto the planner is a separate change with its own blast radius, since it also drives a filter. Frontend: 5677 passed, typecheck and build clean. * Do not treat a mixed GPU selection as unified memory Scoping the unified-memory flag to the pinned devices fixed the discrete-only pin, but the quantifier was still `.some()`, so a set holding one APU and one discrete card read as a single pool. That is every unpinned load on such a host, and any pin naming both. Measured on a 48 GiB APU beside a 16 GiB discrete card with 128 GiB of system RAM: unpinned, .some() gpu 62.08 total 62.08 singlePool true unpinned, .every() gpu 62.08 total 128.00 singlePool true pin both, .some() gpu 62.08 total 62.08 singlePool true pin both, .every() gpu 62.08 total 143.52 singlePool false One device with its own memory means there is real VRAM beside system RAM, so the two are not one pool and the RAM must not be discarded. `[].every()` is true, so a host with no probed devices would read as a unified-memory machine; guarded explicitly rather than relying on the caller never passing an empty set. use-gpu-info.ts deliberately keeps `.some()`. It answers a different question, whether the host has any unified-memory device at all, and is noted as such so the two are not "fixed" into agreement later. * Correct the memory-estimate scene's unit mirror to GiB The Playwright scene builds its expected strings with a Python mirror of the panel's formatter, and that mirror printed "GB" because the panel did. Both divided by 1024**3 and both called the result a decimal gigabyte, so the test agreed with the app about the wrong label and the agreement was what made it invisible. Staging CI caught it on this branch: row header text: 'GPU 4.75 GiB Total 5.50 GiB' FAIL: the row does not show the returned total '5.50 GB' Every figure is byte for byte what it was. Only the unit moved, which is the change this branch makes to the panel, so the mirror moves with it. * Separate the unified pool's size from the fact that it is one pool `unified_memory` on the wire is ROCm-only: hardware.py sets it from `_rocm_known_unified` and nothing produces it for Apple. So the panel's general signal is Apple-or-ROCm, and it was feeding a resolver branch whose comment reads "Apple reports the one pool as the GPU budget already". True for Apple, where memory_total_gb is the machine's unified memory. False for a BIOS-carved window onto system RAM. Measured on a 96 GiB machine carving a 48 GiB window, budget 0.97: gpu total singlePool Windows unified=F 46.56 96.00 true Windows unified=T 46.56 46.56 true Linux unified=F 46.56 142.56 false Linux unified=T 46.56 46.56 true Both are wrong on Linux and in opposite directions. Before this branch the ceiling double counted the window that already sits inside the RAM; after it, the ceiling discarded 49.44 GiB the load can really use, and the panel warned that a 60 GiB load exceeds a machine holding 96. The backend has said which figure is real all along, 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." `unifiedMemory` still classifies the pool. A new `unifiedPoolReportedAsGpuMemory` says whether the GPU figure is that pool's size. The ROCm case falls into the existing `Math.max(gpuCapacityGb, systemRamTotalGb)` branch the Vulkan iGPU already used for this exact reason rather than into new arithmetic. The flag defaults to true, so callers written before the ROCm case keep their answer untouched. Apple is deliberately not routed through the RAM branch: max(93.12, 96) would return the raw 96 and drop the VRAM Budget. Both are pinned as tests, and both new tests were confirmed to fail against the unfixed resolver. Score the Hub fit badge against the saved VRAM Budget Sharing one default constant fixed the loading and old-backend case. It did not reach the case where the user has actually saved a fraction: the badge kept applying 0.97 while the memory bar on the SAME ROW consumed the live value from use-model-memory.ts. On a 24 GiB card with a saved 0.90 the loader admits at 21.6 GiB while the badge scored against 23.28 GiB: size required badge [email protected] 18.0 21.70 fits OVER 18.5 22.27 fits OVER 19.0 22.85 fits OVER `GgufFitInput` takes an optional `budgetFraction`, and the Hub card reads the live value through a new `useVramBudgetFraction`. It is threaded into all three fit-scoring calls on the row, not only the badge: the sort and the menu use the same classifier and would otherwise rank rows against a line the badge no longer applies. Absent means "use the shared default", not "the whole card": scoring an unloaded fraction against 1.0 admits loads the loader refuses, which is the same error in the other direction. Zero, negative, above-one and non-finite values fall back too, since this arrives from a settings route; 1.0 is honoured, being a legitimate saved value. The hook is the fifth caller of subscribeVramBudgetSettings plus loadVramBudgetSettings and the first not to roll the pattern by hand. It subscribes before loading, so a save committed while the GET is in flight is not lost. Frontend suite 5685 pass, 0 fail; typecheck and build clean. * Do not count a Linux APU's window as VRAM beside system RAM Third face of one reporting split, exposed by the previous two fixes. hardware.py sets shared_memory only on Windows, so the same APU arrives as shared_memory true there and unified_memory true / shared_memory false on Linux. Making a mixed set non-unified correctly routed the ceiling to `dedicatedCapacityGb + systemRamTotalGb`, and `dedicated` was computed from sharedMemory alone. A 48 GiB APU beside a 16 GiB discrete card on a 128 GiB host at 0.97: before total = 190.08 GiB after total = 143.52 GiB (16 * 0.97 + 128) 46.56 GiB of capacity that does not exist, in the direction that admits a load. The two flags are folded where they are read rather than the capacity path learning about a second one: they answer the same question, and the split is a platform reporting detail, not a distinction the arithmetic should carry. SystemGpuDevice already grew unifiedMemory earlier in this branch and satisfies MemoryCapacityDevice structurally, so the panel carries it through with no call-site change. A test asserts Windows and Linux now price the same APU identically, which is the property that matters: if those diverge again, one platform charges differently for the same silicon. Credit the VRAM budget, not the raw card, once layers spill vram_budget_settings.py describes the reserve as "a slice of every card that the model and KV cache may not use", so the GPU's contribution to a partly offloaded load is the budget. Adding the raw card to the RAM allowance invented capacity the loader will not give. At the legal minimum 0.80 on a 24 GiB card with 16 GiB of RAM: budget 19.20 combined raw 32.00 combined@budget 27.20 size required before after 23 27.45 partial oom 24 28.60 partial oom 25 29.75 partial oom 26 30.90 partial oom Four quant sizes the badge and the fit sort recommended for a card that cannot load them. `marginal` deliberately keeps the raw card. `fits` returns for everything at or under the budget, so scoring this band against the budget too would make it unreachable; it names the gap between the budget and the card, which is a warning rather than a claim of admission. A test pins that it stays reachable. Frontend suite 5689 pass, 0 fail; typecheck and build clean. Both fixes were confirmed to fail their new tests when reverted. * Carry the saved budget and the unified pool to every surface Three consequences of the previous two rounds, each on a surface the earlier fix did not reach. Local On Device card ranked against the default budget. The live fraction went to the Hub download card's three fit-scoring calls and not to sortLocalGgufVariants, so that card rendered a memory bar using the saved fraction directly above a quant menu ranked against 0.97. Free capacity answered a whole-load question with a carved window. resolveMemoryFit sends the WHOLE load to freeGpuCapacityGb as soon as the pool is single, and marking a ROCm APU single-pool is what this branch did, so a 60 GiB load on a 96 GiB machine with 60+ GiB free was warned as not fitting a 48 GiB window. A non-Apple unified pool now takes the host view, the same discriminator the capacity side uses, so the two cannot answer differently. FreeVramDevice also folds unifiedMemory the way MemoryCapacityDevice does; measured, that changes nothing for an APU beside a discrete card (52.08 either way, since a fully shared device already contributes its free once) and matters when a SECOND view of the same pool appears, an APU beside a Vulkan iGPU: 77.12 -> 38.56. One GET per mounted card. loadVramBudgetSettings has no read-through cache by design and clears its shared promise once each request settles, so it coalesces only overlapping callers; a catalog mounting cards through scrolling and filtering issued a settings GET per card, and a 404 per card on an older backend. The FRACTION is now cached module-wide and kept live by the change event every reader already subscribes to, while the loader keeps its always-refetch behaviour for the callers that need reloadRequired. usableSystemRamGb was computed inline in JSX and is now hoisted, because the free-capacity memo needs the same figure and two copies of the same headroom subtraction is how they drift. Frontend suite 5694 pass, 0 fail; typecheck and build clean. Each fix was confirmed to fail its own test when reverted; one first-draft test asserted a double count that does not occur and was replaced with the case that does. --------- Co-authored-by: danielhanchen <[email protected]> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
…hing (#9768) * Studio: stop a small context window ending a tool-using turn with nothing A chat at a 4096 context died with "request (4237 tokens) exceeds the available context size (4096 tokens)" after edit_file had already written the file. Measured through the model's own template and tokenizer, the overflow was not the tool result: it was the assistant's own edit_file arguments, which the template only renders once a tool message answers the call. Five defects came out of that one thread: 1. Completed tool-call arguments were replayed verbatim forever, so a whole-file write kept costing its full size on every later turn. They are now compacted in the replayed conversation only, leaving the stored thread and what the tool received byte-identical. 2. The fit was discovered after execution, so an unservable turn had already spent its side effect. The check is hoisted above the call, and a turn that cannot be rescued is refused before it writes. 3. edit_file took one old_string/new_string pair, so building a file meant one call per hunk and the model spent whole turns chunking. It now takes a batched edits[] array, matched against the original text with overlap detection and applied all-or-nothing. 4. A tool call whose JSON was cut off mid-stream was healed by filling the first single-string argument with the raw fragment, so a truncated python call became a program that was literally its own broken JSON. Truncated calls are now told apart from merely malformed ones and are never healed. 5. A turn could spend the entire window reasoning and stop on finish_reason length with no answer and no tool call. Because a truncated thought is correctly not promoted as an answer, that rendered as an empty message. It now continues with thinking off, and says which lever to pull if that still produces nothing. Verified against the live llama-server that produced the original 400. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Studio: stop a starved tool result turning into a read loop Asked to show a 2401-byte file inline at a 4096 window, a turn spent eighteen tool calls getting nowhere. The log says why: tool result: name=terminal budget_tokens=0 chars=109 Six of the last eight calls were priced at zero, so each returned only the notice saying it had been cut. The model read that as a fresh failure and tried again with a different line range every time. Three changes, cheapest first: - A result budget below a useful floor now triggers compaction and a re-price before the call runs. Room is exactly what compaction reclaims, and spending it here is what lets the call succeed rather than return a notice. - A call the window has already priced at nothing says so on the FIRST result. The pricing is known before the tool runs, so waiting for a repeat guard to rediscover it spends calls learning something already computed. - A tool that returns byte-identical results several times in a row now tells the model the answer will not change. Keyed on the RESULT and not the arguments, because the arguments differed on every one of the eighteen calls; an argument-keyed guard would have watched it happen. It never fires while results are still changing, so polling is untouched, and it tells the model rather than aborting the run. edit_file's description also now says a successful call means the file on disk holds what was sent, so there is no need to read it back. That is what started the spiral. The result-keyed guard and the never-fire-while-changing rule follow OpenClaw's tool-loop detection. hermes-agent's repetition guard was measured against this turn first and would not have fired: two repeats of a 75-char line in 9935 chars is far below its thresholds. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Studio: finish an answer the window cut in half, and stop leaking the unparsed-arguments sentinel Two things from live threads on the previous build. 1. A turn streaming a 2401-byte file inline at a 4096 window stopped mid-token, at `ctx.arc(6, -5, 5, 0` with a <!DOCTYPE and no closing tag. The earlier fixes had already done their part: the same turn made one tool call where the build before it made eighteen. What remained is arithmetic, and the room that ran out belongs to the reply rather than the prompt, so compaction cannot help and the answer has to span two turns. The existing continuation only covered a turn that showed NOTHING. It now also resumes a truncated answer, handing the partial back with continue_final_message so the model extends it mid-token instead of restarting and apologising. Thinking stays on, because thinking was never the problem here. hermes-agent's repetition guard is ported alongside it, and this is the path it was written for: their continuation nudge once stitched a repeated fragment into a 60,698-char response. A fragment that is mostly an echo of itself is kept as-is rather than extended. It was measured against the earlier read-loop first and correctly ruled out there. 2. `__unsloth_unparsed_arguments__` was reaching both places a caller looks. The tool card showed it to the user verbatim, and the replayed assistant turn showed it to the MODEL, teaching it a key that no tool declares. Both boundaries now go through one accessor: the card shows the fragment under `raw`, and the replay sends it verbatim as the arguments string, which is what that field is in this format. test_a_turn_that_answers_is_never_continued is retargeted rather than removed. It encoded the old rule that any turn with content was left alone, which the first change deliberately reverses; what still holds, and is what it now asserts, is that an answer resumes with thinking on and extends the partial rather than being treated as a stalled thought. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Studio: keep replayed tool-call arguments parseable The previous commit stopped `__unsloth_unparsed_arguments__` reaching the model by replaying the truncated fragment verbatim as the call's `arguments`, on the reasoning that the field is a string in this format so the fragment was the honest value. The field is a string the SERVER PARSES while rendering the chat template, which that reasoning missed. A fragment is unparseable by definition, that being why it is there at all, so every request carrying one failed outright: llama-server returned 500: Failed to parse tool call arguments as JSON: parse error at line 1, column 7201: missing closing quote That surfaced in the UI as "An internal error occurred", which is a worse outcome than the cosmetic leak it was fixing. The replay is now a short valid object naming the failure. The detail the model needs is already in the tool result, and the fragment is not worth resending: it is the content that overflowed the window. Five parametrised cases pin the invariant that was missing, that replayed arguments always parse, plus one that the replay stays small. Checked against the broken version: all seven fail there. The test that asserted verbatim replay is corrected rather than removed. Its comment stated the same wrong premise, so both now record what the assertion failed to consider. * Studio: shorten the guidance, and give it one consistent rule Reading every model-facing string in this branch side by side turned up a contradiction it had shipped: the compacted-arguments placeholder ended "read the file back if you need the content", while the edit_file description says not to read back what you just wrote and both no-progress notices say reading again will not help. Three lines discouraging a re-read and one inviting it, and the re-read is the loop that cost eighteen calls in a single turn. Every one of them now says the same thing: continue from what you have, in parts if it will not fit at once, and finish the task. Each is also shorter, since they are spent out of the same window they are describing (roughly 68 -> 32 tokens for the repeated-result notice, 68 -> 47 for the starved one, 41 -> 27 for the placeholder). The larger saving is not in those. Tool schemas go into EVERY prompt and came to about 1351 tokens, a third of a 4096-token window before any conversation at all. edit_file's description was 277 of it and is now 170, with every rule kept: batch into edits, match against the original text, no overlaps, exactly one match unless replace_all, all-or-nothing, do not read back. That is about 108 tokens returned on every turn. Also fixed: thinking_exhausted_message read "spent its whole reply of the 4096-token window on reasoning", from formatting a pre-spaced fragment. Four tests asserted the exact old phrasing. The meaning survives the rewrite in each, so the assertions moved rather than the messages. * Studio: continue a truncated answer in the final generation too A live run spent 25 tool calls and 22387 tokens, hit the tool-iteration ceiling, and then stopped on finish_reason length inside drawBird() with the game half-written and nothing to recover it. The continuation added earlier covers the generation INSIDE the tool loop. At the iteration ceiling the loop breaks, appends the budget-exhausted nudge, and runs a separate final generation after it, which had no continuation at all. A turn that spends its whole tool budget produces its answer there, so the one path most likely to be cut off was the one path with no way back. That generation is now wrapped in the same continuation, under the same rules: the partial goes back through continue_final_message to be extended rather than responded to, thinking is left as the caller set it because thinking is not what ran out, an answer that is mostly an echo of itself is left alone, and the whole thing is capped. Four tests drive the final path directly, with max_tool_iterations = 0 so the tool loop cannot take the request first. Checked against a disabled build: the two that assert the continuation fail there, and the two that assert it stays out (clean stop, echo) still pass. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Studio: address review findings on the small-window tool turn fixes Backend: - Rebind the assistant message after run-then-compact rebuilds the conversation, so a second call in the same batch is still visible to the model when its result arrives. - Compact only the last call carrying an id. Parsers number from call_0 on every turn, so rewriting every match relabelled an earlier call with a later one's outcome. - Keep the arguments of a call that never ran. A tool reply proves an answer, not an execution, and the completed receipt claimed a write the user had declined. - Word the receipt per tool. python, terminal and MCP calls write no file, so they no longer read as already written to disk. - Build the malformed-arguments receipt from the same phrase, so a refused call is not replayed as having run. - Continue a reasoning-only length stop in the final pass, which the in-loop continuation cannot reach, and say so when it never converges. - Drop an explicit reasoning effort for a thinking-off continuation. For that style the effort wins, so the retry re-ran the failing turn. - Give continuations their own loop credits instead of charging them to the caller's tool budget. - Count the final continuation prompt before reopening the stream, and keep the partial rather than send a request that cannot be served. - Replay only the new suffix on a final continuation, and fold each attempt's usage in before the next overwrites it. - Replay the truncated answer unstripped so the continuation builds on the whitespace it was cut on. - Price the result budget against the compacted prompt when the gate ran the call because compaction will make room. - Use the conservative estimate at the admission gate so dense ASCII cannot skip the exact check. - Key the no-progress guard on the arguments too, unless the result is a notice the window itself produced. - Count repeated windows without overlap, so one long rule no longer reads as an echo. - Detect a value cut mid-literal as truncation, and a complete document with trailing junk as not. - Derive healing keys from the request's schemas as well, restoring auto-healing for single-string MCP tools. - Offer a lever the refused tool actually has. Frontend: - Tell the Max Tokens wall from the context wall using the prompt count, so a cap the prompt left no room for is not blamed. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Studio: keep a continuation inside the caller's budget and stop guessing disk state - Respect an explicit max_tokens when continuing a truncated answer. A caller cap and the context wall both report finish_reason length, so a 100-token request was continued twice into roughly 300. The retry now gets the remainder of the caller's budget, and an attempt that ended on length is charged its whole allowance when the server reported no usage. max_tokens unset, or equal to the window, is still the context wall the continuation exists for. - Build the continuation as a candidate and commit it only once another stream is certain to run. The replay and the usage fold happened first, so a refused continuation reported roughly double the tokens it cost: the same usage went into the accumulator and then into the metadata event. - Pair a tool reply with its own call site. Ids restart at call_0 every turn, so a conversation-wide set of answered ids let an earlier success vouch for a later declined call, which was then replayed as already written. - Earn the file wording from the reply rather than the tool name. An edit_file that ran and returned an error is not a write, and a python or terminal call may well have created files, so both directions of the guess are wrong. Anything the reply does not settle gets a receipt that claims nothing about the disk. - Require evidence a result was actually cut before saying so. The budget is what the window allowed, not what the tool returned, and a short complete result was being reported as nothing usable. - Cap the edits array. Each entry rescans a file that may be 16 MiB, so an unbounded batch turns one call into gigabytes of scanning. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Studio: re-baseline the refactor guard and drop an unused import The guard pins the tool-call parsing stack by AST, runtime surface and a digest of every guarded function's output. This PR adds six symbols to tool_call_parser, so the inventories needed the snapshot the module's own docstring prescribes. Two of the new notices take a result alongside the tool name, which had no argument fixture, so the driver reported them as undrivable rather than pinning them. Audited rather than taken on trust: no existing digest changed, nothing was removed from any inventory, and the only additions are the three new guarded functions. The apparent deletions are entries re-ordered and re-added with identical digests. Also removes an import of re that this branch added to tool_loop_controller and never used. Ruff does not reach it; the lint job's import-hoist check does, and only for files a change touches. * Studio: carry the continuation guards into the tool loop and compact on aggregate size The previous round guarded the final generation pass. A request with tools enabled takes the in-loop path instead, which had neither guard: - Count the in-loop continuation prompt before retrying, and keep the partial when the retry would not be served. With a single user turn there is no older history to evict, so the retry was window-sized. - Spend the caller's output budget across the whole reply rather than per attempt. The in-loop payload rebuilds max_tokens from the caller's value every iteration, so a request capped at 100 tokens ran two more 100-token generations. Also: - Compact arguments on their aggregate size, not per string. A batched refactor of fifty 800-character edits is tens of thousands of characters with no single string over the floor, so nothing was reclaimed and the call stayed in the prompt for good. The final check that the receipt is smaller than what it replaces still applies. - Word an elided old_string neutrally. Only new_string is on disk after a replacement; the completed phrase sent the model after content the edit had just removed. - Reset in_thinking once a truncated reasoning block is closed. The thinking-off retry closed it a second time on its first content token, and the route showed the stray tag as answer text. - Apply a lone replace_all without enumerating its matches. There is nothing to overlap with, so str.replace does it in linear space where spans cost a tuple per match. Entries inside a batch still need spans for overlap detection and are bounded instead. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Studio: guard the reasoning retry too, and stop blaming a file for every tool call The previous round guarded the in-loop partial-answer continuation. The reasoning-only continuation beside it mutated the conversation directly and checked neither thing: - Count its candidate prompt before committing, and keep the thought when the retry would not be served. - Spend the caller's cap across the whole reply here as well, and stop when it is gone. Also: - Compact the arguments of a call the user denied. The denial is itself the tool message that makes the template render the call it refused, so declining an oversized write cost the prompt the very arguments it declined to afford, and the bulk pass skips denials by design. - Size a result against a prompt carrying the current call's stand-in reply. Templates that render a tool call only once a reply follows it were pricing the result without the arguments it sits beside. - Keep the destination path out of the elision. It is the one field that says which file was changed, and the lower aggregate floor had started spending it. - Repeat the path inside a receipt only when it is short. Every elided leaf embeds it, so a long path cost more than the content removed and the size check rejected the whole compaction. - Blame a file only when a file is involved. An oversized python, terminal or MCP call was answered with advice to ask for a smaller file, which names the wrong cause and cannot be acted on. - Treat a cap reached together with the context wall as context-bound. At equality raising Max Tokens creates no room, so the advice to do so is the one thing that cannot help. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Studio: rebind to the current turn, neutralize the replay, and name the right wall Three of these are defects in the fixes from the previous rounds: - Scan backward when rebinding the assistant message after a compaction. Generated ids restart at call_0 every turn, so a forward scan bound the oldest turn carrying the id and the rest of the batch was appended to history instead of the live exchange. - Rebind after compacting a denied call too. The denial path was added last round with the same detached-handle defect the executed path had already been fixed for. - Neutralize a continuation candidate before counting and sending it. The first payload neutralizes every message; the replay put raw model output back, so a template delimiter inside printed code was read as chat structure, and the admission count described a different string from the one actually sent. And three from elsewhere: - Resolve the forced choice when a call is refused by the context gate, as a user denial already does. Left pending, the next iteration advertised the same tool as required and the model was pushed into the same call and the same refusal. - Say so when a reasoning turn was stopped by the caller's own Max Tokens rather than by the window. The two have opposite levers, only one attempt ran, and this text reaches the client as ordinary content where the frontend's cap-aware error cannot correct it. - Pass the local context length only for local requests. The resident GGUF window stays populated while an external model is selected, so an external request with a 16K cap was measured against an unrelated 4096-token window. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Studio: price both counts alike, bound the repetition scan, name the right lever Six review items, four of them defects in earlier commits on this branch. Argument compaction chose aggregate mode from the largest leaf, so one 1100-char edit beside fifty 800-char ones stayed in per-leaf mode and compacted only the first, replaying about 40 KB. Chosen from the total now, which is the shape a batched refactor actually produces. The result-budget rescue re-counted the prompt without the empty tool stand-in the initial sizing uses. On templates that render a call only once a reply follows, that dropped the pending call's own arguments from the count and handed the room they occupy to the result. The final-pass retry runs with thinking off but was admitted under the thinking-on kwargs, pricing a prompt nobody sends. The kwargs are computed once now and used for both admission and the request. Final-pass exhaustion always blamed the context window. When a caller-set Max Tokens is what was spent, it now says so, matching the fork the in-loop give-up already made. The repetition scan kept one 60-char slice per starting offset, so a very long fragment held a large multiple of itself alive to decide one continuation. Keyed by hash with a collision check and a ceiling on distinct windows; both directions of the bound fail open. The GenerationLengthError toast hardcoded the Max Tokens advice, overriding the remedy the error had already chosen from the cap and the prompt size. It repeats the message now. Each fix has a regression test confirmed to fail without it. Affected backend modules 457 passed, frontend 5647 passed, tsc and ruff clean. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Studio: judge a continuation on its own attempt, and make room before giving up Five review items. A tool reply was paired with the OLDEST pending announcement of its id. Textual parsers number from call_0 every turn, so an interrupted call leaves a stale site under the same id: the reply marked the abandoned call executed and left the call that actually ran replaying its arguments in full. The in-loop retry was admitted under the previous attempt's thinking-on kwargs even though it goes out with thinking off, which prices a request nobody sends. The final pass already computed its own; this path now does too. A continuation that did not fit ended the turn, so the next iteration's ordinary preflight never got its chance to drop an older exchange. Under truncate_oldest the candidate is now fitted once before being abandoned, to the room the continuation itself needs rather than to the caller's cap: with a small max_tokens the preflight target is larger than the window minus the reply floor, so fitting to the caller's figure would evict and still leave it unservable. Applied at all three continuation sites. has_content_tokens and _last_emitted are cumulative across attempts by design, so a continuation that produced nothing but reasoning was classified as another truncated visible answer: it replayed an empty suffix with thinking still on instead of taking the reasoning-off recovery. Each attempt is now judged on what it put on screen itself. Because content events are cumulative, the give-up no longer sends its explanation on its own once an earlier attempt has written an answer, which would have replaced the answer with a message about not having one. Reaching either give-up by exhausting the retry limit left the cap classification at its default, so a turn whose last permitted attempt finished off an explicit Max Tokens was told to raise the Context Length. Both sites re-read the remaining cap. Each fix has a regression test confirmed to fail without it, except the one guarding the answer against being overwritten, which guards behaviour the per-attempt change made reachable. Affected backend modules 590 passed, ruff clean. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Studio: price a continuation as one, and give the safety tests their guards back Three review items. The in-loop answer continuation is sent with continue_final_message, which renders without a generation prompt and with the partial as the turn being extended, but the admission counted it as an ordinary prompt. The flag is threaded through _loop_continuation_fits now, and the eviction retry added alongside it uses the same flag. Two edit_file safety tests still called execute_tool directly with the top-level old_string and new_string shape. That shape is refused outright now, and the refusal starts with "Error:" like the failures they were asserting, so test_full_access_does_not_replace_a_device_node and test_a_failed_create_removes_the_partial_file passed without reaching the device-node guard or the simulated ENOSPC cleanup. Both now send edits, and both assert the message their own guard produces rather than any error, so neither can go green again on a malformed call. Cap attribution passed a null context length for a local safetensors or MLX request on the legacy stream path, where neither GGUF field is set. A null window reads as infinite, so every context-length stop was reported as a Max Tokens stop and the user was told to raise a value already at the model's maximum. params.maxSeqLength is added last and coerced from zero, the same order the RAG context_length beside it already uses. Each fix has a regression test confirmed to fail without it. Affected backend modules 591 passed, frontend 5648 passed, tsc and ruff clean. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Studio: fix the AttributeError that 500s every planned GGUF load (#9821) * Studio: fix the AttributeError that 500s every planned GGUF load _planned_tensor_spill read the host-RAM headroom as host_ram_headroom_bytes = self._HOST_RAM_HEADROOM_MIB * 1024 * 1024 copying the shape of _PIPELINE_PER_DEVICE_OVERHEAD_MIB on the line directly above it. That one is a class attribute (llama_cpp.py:9597). The headroom is module-level (llama_cpp.py:4721), so it is not reachable through self, and every load that got as far as the planning call raised 'LlamaCppBackend' object has no attribute '_HOST_RAM_HEADROOM_MIB' and came back to the client as a 500. Since #9779 the planner is default-on, so this is on the path of every GGUF load, not an opt-in one. Observed loading unsloth/Qwen3.8-Flash-Next-GGUF UD-IQ1_S on a Colab T4 high-RAM VM: llama-server never spawned and the load returned 500. The seam suite stayed green through all of it because the _Stub double declared _HOST_RAM_HEADROOM_MIB = 2048 itself, so the lookup found it on the double and never on the class under test. Dropping that line from the double is most of the fix here: with it gone and the source left unpatched, 66 of the 127 seam tests fail. A named test also asserts the double declares no attribute the real class lacks, and that the seam source no longer reaches for this one through self. * Tighten the comments on the host RAM headroom fix * Tighten the comments this PR added (#9825) Post-convergence comment pass over the 3,346 comment lines this branch adds across 27 files. 810 lines out, 609 back: every block keeps the fact that made it worth writing and drops the paragraph restating it. What stays, deliberately. The measured figures (2296 MiB reserved against 1008 MiB allocated; 1039 -> 2105 MiB at 4k), the upstream citations (fit.cpp:463, llama_init_from_model(model_tgt), server-context.cpp gating on a non-empty mmproj.path, common_prompt_checkpoint on the host heap), and the "what this looked like when it was wrong" clause on each. Those are the parts a reader cannot reconstruct from the code. What does not change. The estimate-memory path operation's docstring is untouched: FastAPI renders it as the route's OpenAPI description, so editing it is an API change rather than a comment change. The class docstrings in test_memory_estimate.py are untouched too -- each carries a distinct account of the defect its tests exist for, and at that density the next cut removes a fact. AST-gated throughout: comment_tools.py check 17/17 with --strip-docstrings, and prepush_gate.py --comment-only against the pre-pass head. Backend 909 passed, frontend 5331 passed, typecheck clean. * Fix the studio PEP 604 union ratchet and name what breaches it (#9826) * Fix the studio PEP 604 union ratchet and name what breaches it main is red on Core and Python 3.13: AssertionError: 37 studio files now evaluate PEP 604 unions on the floor, up from 35. #7880 added studio/backend/tests/test_kv_cache_estimate_compat.py and test_kv_cache_estimate_route.py, which annotate with Path | None, str | None and int | None but carry no `from __future__ import annotations`. requires-python is still 3.9, where those evaluate to a TypeError at import. The ratchet is right and the new files are the thing to fix. The debt it tracks is FastAPI routers and pydantic models, where the future import has real failure modes around class dependencies; these two are plain test modules with no such constraint, so they take the import and the count returns to 35. Raising the ratchet instead would bank the debt for no reason. Also make the next breach diagnosable. The check stored a bare count, so the failure said only that 37 exceeded 35 and then printed all 37 truncated at 2000 characters. Finding the two additions meant re-running the scan against an older checkout and diffing by hand. It now stores the SET and reports the difference: 37 studio files now evaluate PEP 604 unions on the floor, up from 35. Add `from __future__ import annotations` to these, do not raise the ratchet: studio/backend/tests/test_kv_cache_estimate_compat.py studio/backend/tests/test_kv_cache_estimate_route.py The count still governs the assertion, so one file fixed and another added cannot pass on set membership alone, and a file that stops offending is named too so the list can shrink. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> * Studio: keep the memory row readable on a narrow panel (#9824) * Studio: keep the memory row readable on a narrow panel The model config panel is w-[min(468px,calc(100vw-1rem))], so once the window is under about 460px it shrinks with the viewport. The Estimated Memory Usage header is the only row carrying a title and two figures at once, and the figures do not shrink, so the title absorbed the entire shortfall: measured on the current build it went from 150px at 460px wide to 91px at 400, 51px at 360 and 11px at 320, where it rendered as "E...". Let that header wrap. The figures drop to a line of their own only at the widths where they would not have fitted beside the title anyway, and ml-auto keeps them under the right edge they already had, since justify-between has nothing to push against on a line holding one item. At 460px and above the layout is unchanged. The breakdown captions had a smaller version of the same problem: "f16 . 262,144 tokens . 4 slots" broke at whatever space fitted, which left the word "slots" alone on a line under "... tokens . 4". Gluing each item together with U+00A0 leaves one break opportunity per bullet, and gluing the bullet to the item that follows it puts the break before the bullet rather than orphaning it at the end of the previous line. Measured in the real 183px caption column, the final line goes from a 22px fragment to the whole 38px item. * Leave an unseparated breakdown note breakable Only the KV caption is a list. The Weights and Draft cache notes are ordinary prose ("256 of 257 layers on GPU", "2.14 GB on GPU"), and passing those through glueNoteItems replaced every space with U+00A0, leaving them zero break opportunities. On a narrow panel, or at an enlarged browser font, that made them a single unbreakable run that overflows the caption column instead of wrapping inside it, which is worse than the orphaned word the function exists to prevent. Return a note with no separator untouched. There are no items to keep apart, so gluing bought nothing and cost every break the note had. --------- Co-authored-by: danielhanchen <[email protected]> * route thinking controls to ollama * Studio: expose Thinking for Ollama and forward reasoning_effort Ollama connections had no reasoning capability, so Studio hid Thinking and never sent reasoning_effort. A reasoning model then kept its default thinking with no way to turn it off (#9649). Flag the connection as a reasoning model to show Thinking, then map off/on onto Ollama's OpenAI-compat reasoning_effort field. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Studio: pin Ollama thinking per model and keep research Thinking off Ollama connections can serve mixed catalogs, so the reasoning-model toggle now stores which model ids support thinking. Unmarked models no longer advertise Thinking or send reasoning_effort. Deep Research serializes reasoningEffort "none" when Thinking is off so Ollama does not fall back to the model's default. * preserve ollama max reasoning effort * fail closed on malformed reasoning pins * prune stale ollama reasoning pins * name ollama reasoning model controls * isolate ollama reasoning request tests * align reasoning regression test style * keep ollama gpt-oss reasoning enabled * gate research reasoning on model support * match ollama reasoning pins case insensitively * reset reasoning state on provider changes * remove ollama reasoning ui --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Maheswar Kumar <[email protected]> * Read the memory row's captions past their line-breaking glue (#9831) The breakdown captions now join their items with U+00A0 so a narrow panel breaks between "262,144 tokens" and "4 slots" rather than inside either. The scene asserts on the caption with a plain `"6,144 tokens" in text`, which stopped matching: the figure was correct on screen and in the response, but the space between it and "tokens" is no longer a space. Normalise the glue back to ordinary spaces in the two inner_text readers, so every assertion reads the caption the way it looks rather than the way it is encoded. Verified against the exact strings CI reported. Co-authored-by: danielhanchen <[email protected]> * Studio: persist model disclaimer across instances (#9835) * Studio: persist model disclaimer across instances * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Studio: invalidate queued preference reads --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> * Studio: consolidate the two memory-estimate stacks (#9830) * Studio: freeze both memory-estimate route contracts before consolidating /api/inference/estimate-memory and /api/models/kv-cache-estimate already share the _gguf_memory_breakdown planner, so their arithmetic cannot drift, but their response contracts are still separate and are about to be consolidated onto one implementation. The hazard is not shape drift, which a typechecker catches. weights_bytes exists on both routes, is an int on both, and means different things: every resident file on the inference route (weights plus projector plus drafter), the quant file alone on the models route, where the planner aggregate travels separately as gpu_bytes / total_bytes / gpu_floor_bytes. Unifying the key changes the number under whichever caller loses, with no JSON change for a client to notice. These tests pin both envelopes and that collision, so the consolidation cannot silently resolve it. The models route has no response_model at all, so nothing else enforces its shape. Verified by mutation rather than by passing: adding a key, removing a key, repointing weights_bytes at the planner aggregate and disabling the delegation each fail the suite. The first draft did not catch the aggregate swap, because the planner delegation is gated on _cached_estimate_config resolving the repo to this disk and is skipped for a synthetic repo id, leaving every planner field present and null. A freeze written over that fixture asserts nothing. Pinning the config so the planner returns real figures is what makes these bite. * Studio: give both memory-estimate routes one canonical contract The two routes already share the _gguf_memory_breakdown planner, so their arithmetic agrees. Their vocabulary did not, and the sharp edge is weights_bytes: it exists on both, is an int on both, and means every resident file on /inference/estimate-memory but the quant file alone on /models/kv-cache-estimate. Nothing in the type system separates those, so a caller reading the wrong one is simply wrong, quietly. Adds models.inference.MemoryEstimate as the shared contract. It deliberately has no weights_bytes at all: the name is replaced by quant_file_bytes and resident_files_bytes, which each say which they are, and it is absent rather than redefined so no new reader can pick it up and guess. core/inference/memory_contract.py holds the projections back onto each route's existing wire shape. Both legacy mappings now sit side by side in one file, which is the only place either is written down, instead of being implied by two handlers that never referenced each other. /kv-cache-estimate is rewired onto the projection and its JSON is unchanged, which the contract-freeze suite from the previous commit verifies rather than assumes. Two subtleties it caught while this was being written: - gpu_bytes must keep 0 distinct from None. Zero is a real answer, an inherited LLAMA_ARG_DEVICE=none launch that touches no card; None means the planner never ran. The first draft applied `or None` uniformly and reintroduced a bug this route had already fixed. MemoryEstimate.gpu_bytes is Optional for that reason. - the quant figure is not clamped against the resident total, though a quant file cannot really exceed the files containing it. The two come from different resolvers, and clamping truncated a 4.1 GB quant to a 373 byte synthetic header rather than catching anything. kv_bytes is passed into the projection rather than read off the estimate: this route prices the target cache itself and the planner's figure is not interchangeable with it. * Studio: route the Load Model estimate through the shared contract too /inference/estimate-memory now builds the same canonical MemoryEstimate that /models/kv-cache-estimate builds, and projects back to EstimateMemoryResponse. Both routes go through one vocabulary; neither wire shape changes. weights_bytes keeps its aggregate meaning here through project_estimate_memory_response, which is the counterpart of the quant-file mapping the sibling route uses. The two sit next to each other in core/inference/memory_contract.py so the difference is impossible to read past. quant_file_bytes is 0 on this route rather than a stand-in. This handler 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 response does not carry the field, and inventing a value would be a wrong number for the sake of a non-null. * Studio: one presentation core for both memory surfaces The Load Model panel and the Hub memory bar were fed byte-identical figures by one backend planner and still disagreed about how to present them, 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. Each difference was defensible alone. Together they meant one model could read as fitting on one screen and not on the other. src/lib/memory/ now holds the shared core: - format.ts. There were two exported functions called formatMemoryGb, one per surface, both (number) => string, one taking bytes and one taking gibibytes, printing different labels. Importing the wrong one was off by 1024^3 and typechecked cleanly. They are replaced by formatGiB and formatBytesGiB, whose names carry the unit, plus formatKvRate. - thresholds.ts. The fit ratio and the pressure ramp measure different things and keep different values, but they now differ in one file rather than per surface. - verdict.ts. A superset vocabulary, not a winner: the panel's tight band and the bar's why-it-exceeds cause both survive, so neither surface loses a distinction it used to make. memory-fit.ts and model-memory.ts stay as each surface's entry point and become thin re-exporters, so no call site moves. memory-fit.ts keeps relative imports with explicit extensions rather than the @/ alias: three tests load it directly under node --experimental-strip-types without a bundler resolver, and an alias there breaks all three. Its docstring said "no imports" and meant no ALIAS imports; that is now written down. Two user-visible labels change, both mislabels rather than preferences: - the panel printed GiB values labelled GB across seven figures, the defect #9570 fixed elsewhere. vram-total-gib-suffix.test.ts could not see it, since its regex only matches interpolations naming a *TotalGb and neither module was in its list. That guard now reads the shared module, covers all three formatters including the panel's, and separately asserts neither surface has redefined one locally. - formatKvRate divided by 1024 and labelled the result KB/MB. Existing assertions were updated to the new expectations rather than relaxed, and two fixtures were retuned rather than left passing: at the wider budget the speculative-reserve case no longer tipped over, so it would have gone green while measuring nothing. * Studio: decide unified memory from the hardware, not from the platform The Load Model panel asked usePlatformStore(s => s.appleSilicon) whether the GPU and the rest of the system share one memory pool, and passed that answer to resolveMemoryCapacityGb. On a ROCm APU the answer was false, so the panel charged one pool as discrete VRAM PLUS host RAM: the same bytes counted twice, and a ceiling high enough to report a fit for a load that cannot open. The correct signal already existed. 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 exactly that flag. Only the panel was reading the platform instead of the hardware. The two uses are now separate rather than renamed wholesale, because they are genuinely different questions: - isAppleUnifiedMemory still drives the WORDING. "Unified" is what Apple calls its pool; an AMD APU's is a "Shared" one, and the panel already prints both. - hasUnifiedMemory drives the CAPACITY, and falls back to the Apple check while the device probe is in flight, so it is never a weaker answer than before. A discrete card is unaffected: its devices do not report unified_memory, so nothing about an ordinary NVIDIA host moves. Covered by tests on resolveMemoryCapacityGb for the APU pool and for a discrete card, plus a source assertion that the panel hands the capacity call the general signal. That last one is not decoration: the behavioural tests pin what the resolver does with each flag, not which flag it is given, and they both pass on the unfixed panel. Verified by reverting the fix and watching only the source assertion fail. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Studio: harden the memory contract and pin it across the platform matrix Adversarial pass over this PR's own changes. Three real defects, two of them mine, plus a simulation matrix that would have caught all three. Fixed, introduced by this PR: - routes/models.py assigned gpu_bytes, compute_bytes, total_bytes and n_ctx onto a MemoryEstimate AFTER building it. Pydantic does not validate assignment by default, so a post-construction write puts whatever it is handed straight onto the wire. Measured rather than assumed: on pydantic 2.13 m.gpu_bytes = "not an int" succeeds, and a declared int field accepts None the same way. Those four are now parameters of build_memory_estimate, so the model is built once and validated once. gpu_bytes needs a sentinel rather than a None default because it has three states: a number, a real None meaning the planner never ran, and "use the breakdown's". Fixed, pre-existing but in scope because it made the two surfaces disagree: - computeModelMemory turned a non-finite weightsBytes into "model-exceeds": a full destructive 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 reaches it without trying. classifyMemoryFit on the panel already answered "unknown" for the same input, which is the divergence this PR exists to remove. Null and undefined are untouched: those mean "has not arrived", an ordinary state. New simulation coverage: - memory-cross-surface-matrix.test.ts: [linux, wsl, win32, darwin] x nine device inventories (NVIDIA single and dual, ROCm discrete, ROCm APU, AMD Vulkan iGPU, Intel iGPU, Apple unified, mixed dGPU+iGPU, CPU only) x four footprints, minus the physically impossible cells, checked against six properties: no false fit, no bar/panel contradiction, one label per byte count, no pool counted twice, CPU-only draws nothing, and no NaN or Infinity reaching a label. 128 cells. The Infinity defect above is what P-hostile found. - test_memory_contract_platforms.py: the same four platform keys x six placements, pinning that both wire shapes are byte-identical everywhere and that weights_bytes keeps its own meaning per route in every cell. - Old-backend degradation: a backend that never sends unified_memory leaves hasUnifiedMemory exactly equal to the appleSilicon check it replaced, in both directions. Verified in a clean uv venv holding only pytest, pydantic, fastapi, structlog, huggingface_hub, psutil, pyjwt, passlib, bcrypt and cryptography: 710 passed. The only two failures there need the real transformers package and pass with it. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Studio: scope unified memory to the pin, and share one budget with the fit badge Two P2 review items, both reproduced before agreeing. 1. The unified-memory flag was host-wide. inferenceGpu.unifiedMemory is devices.some(...) over the whole inventory, so an APU beside a discrete card made it true, and a pin naming ONLY the discrete card then told resolveMemoryCapacityGb the two are one pool. Measured on a 16 GiB pin with an APU present and 128 GiB of RAM: totalCapacityGb collapsed from 143.52 to 15.52 GiB, so the panel warned "more than this machine holds" for a load that fits comfortably. That is a regression this branch introduced; on main the flag was the Apple check and read false there. hasUnifiedMemory now narrows to the pinned devices before asking, falling back to the whole inventory when nothing is pinned. The Apple check stays host-wide and unconditional: there every device really is the one pool, and it also covers the window before the per-device probe lands. SystemGpuDevice carries unifiedMemory per device for this, alongside sharedMemory, which is per device for the same reason. 2. The Hub fit badge and the memory bar render on the same row and judged against different budgets: gguf-fit.ts held 0.90 while the bar used the loader's own 0.97. gguf-fit now re-exports the shared constant. Worth being exact about what that buys, because the review item claims it removes the contradiction and it does not. Measured over 15-24 GiB on a 24 GiB card, badge-vs-bar disagreements go from 11/19 sizes to 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 no constant can reconcile them. Rewiring the badge onto the planner is a separate change with its own blast radius, since it also drives a filter. Frontend: 5677 passed, typecheck and build clean. * Do not treat a mixed GPU selection as unified memory Scoping the unified-memory flag to the pinned devices fixed the discrete-only pin, but the quantifier was still `.some()`, so a set holding one APU and one discrete card read as a single pool. That is every unpinned load on such a host, and any pin naming both. Measured on a 48 GiB APU beside a 16 GiB discrete card with 128 GiB of system RAM: unpinned, .some() gpu 62.08 total 62.08 singlePool true unpinned, .every() gpu 62.08 total 128.00 singlePool true pin both, .some() gpu 62.08 total 62.08 singlePool true pin both, .every() gpu 62.08 total 143.52 singlePool false One device with its own memory means there is real VRAM beside system RAM, so the two are not one pool and the RAM must not be discarded. `[].every()` is true, so a host with no probed devices would read as a unified-memory machine; guarded explicitly rather than relying on the caller never passing an empty set. use-gpu-info.ts deliberately keeps `.some()`. It answers a different question, whether the host has any unified-memory device at all, and is noted as such so the two are not "fixed" into agreement later. * Correct the memory-estimate scene's unit mirror to GiB The Playwright scene builds its expected strings with a Python mirror of the panel's formatter, and that mirror printed "GB" because the panel did. Both divided by 1024**3 and both called the result a decimal gigabyte, so the test agreed with the app about the wrong label and the agreement was what made it invisible. Staging CI caught it on this branch: row header text: 'GPU 4.75 GiB Total 5.50 GiB' FAIL: the row does not show the returned total '5.50 GB' Every figure is byte for byte what it was. Only the unit moved, which is the change this branch makes to the panel, so the mirror moves with it. * Separate the unified pool's size from the fact that it is one pool `unified_memory` on the wire is ROCm-only: hardware.py sets it from `_rocm_known_unified` and nothing produces it for Apple. So the panel's general signal is Apple-or-ROCm, and it was feeding a resolver branch whose comment reads "Apple reports the one pool as the GPU budget already". True for Apple, where memory_total_gb is the machine's unified memory. False for a BIOS-carved window onto system RAM. Measured on a 96 GiB machine carving a 48 GiB window, budget 0.97: gpu total singlePool Windows unified=F 46.56 96.00 true Windows unified=T 46.56 46.56 true Linux unified=F 46.56 142.56 false Linux unified=T 46.56 46.56 true Both are wrong on Linux and in opposite directions. Before this branch the ceiling double counted the window that already sits inside the RAM; after it, the ceiling discarded 49.44 GiB the load can really use, and the panel warned that a 60 GiB load exceeds a machine holding 96. The backend has said which figure is real all along, 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." `unifiedMemory` still classifies the pool. A new `unifiedPoolReportedAsGpuMemory` says whether the GPU figure is that pool's size. The ROCm case falls into the existing `Math.max(gpuCapacityGb, systemRamTotalGb)` branch the Vulkan iGPU already used for this exact reason rather than into new arithmetic. The flag defaults to true, so callers written before the ROCm case keep their answer untouched. Apple is deliberately not routed through the RAM branch: max(93.12, 96) would return the raw 96 and drop the VRAM Budget. Both are pinned as tests, and both new tests were confirmed to fail against the unfixed resolver. Score the Hub fit badge against the saved VRAM Budget Sharing one default constant fixed the loading and old-backend case. It did not reach the case where the user has actually saved a fraction: the badge kept applying 0.97 while the memory bar on the SAME ROW consumed the live value from use-model-memory.ts. On a 24 GiB card with a saved 0.90 the loader admits at 21.6 GiB while the badge scored against 23.28 GiB: size required badge [email protected] 18.0 21.70 fits OVER 18.5 22.27 fits OVER 19.0 22.85 fits OVER `GgufFitInput` takes an optional `budgetFraction`, and the Hub card reads the live value through a new `useVramBudgetFraction`. It is threaded into all three fit-scoring calls on the row, not only the badge: the sort and the menu use the same classifier and would otherwise rank rows against a line the badge no longer applies. Absent means "use the shared default", not "the whole card": scoring an unloaded fraction against 1.0 admits loads the loader refuses, which is the same error in the other direction. Zero, negative, above-one and non-finite values fall back too, since this arrives from a settings route; 1.0 is honoured, being a legitimate saved value. The hook is the fifth caller of subscribeVramBudgetSettings plus loadVramBudgetSettings and the first not to roll the pattern by hand. It subscribes before loading, so a save committed while the GET is in flight is not lost. Frontend suite 5685 pass, 0 fail; typecheck and build clean. * Do not count a Linux APU's window as VRAM beside system RAM Third face of one reporting split, exposed by the previous two fixes. hardware.py sets shared_memory only on Windows, so the same APU arrives as shared_memory true there and unified_memory true / shared_memory false on Linux. Making a mixed set non-unified correctly routed the ceiling to `dedicatedCapacityGb + systemRamTotalGb`, and `dedicated` was computed from sharedMemory alone. A 48 GiB APU beside a 16 GiB discrete card on a 128 GiB host at 0.97: before total = 190.08 GiB after total = 143.52 GiB (16 * 0.97 + 128) 46.56 GiB of capacity that does not exist, in the direction that admits a load. The two flags are folded where they are read rather than the capacity path learning about a second one: they answer the same question, and the split is a platform reporting detail, not a distinction the arithmetic should carry. SystemGpuDevice already grew unifiedMemory earlier in this branch and satisfies MemoryCapacityDevice structurally, so the panel carries it through with no call-site change. A test asserts Windows and Linux now price the same APU identically, which is the property that matters: if those diverge again, one platform charges differently for the same silicon. Credit the VRAM budget, not the raw card, once layers spill vram_budget_settings.py describes the reserve as "a slice of every card that the model and KV cache may not use", so the GPU's contribution to a partly offloaded load is the budget. Adding the raw card to the RAM allowance invented capacity the loader will not give. At the legal minimum 0.80 on a 24 GiB card with 16 GiB of RAM: budget 19.20 combined raw 32.00 combined@budget 27.20 size required before after 23 27.45 partial oom 24 28.60 partial oom 25 29.75 partial oom 26 30.90 partial oom Four quant sizes the badge and the fit sort recommended for a card that cannot load them. `marginal` deliberately keeps the raw card. `fits` returns for everything at or under the budget, so scoring this band against the budget too would make it unreachable; it names the gap between the budget and the card, which is a warning rather than a claim of admission. A test pins that it stays reachable. Frontend suite 5689 pass, 0 fail; typecheck and build clean. Both fixes were confirmed to fail their new tests when reverted. * Carry the saved budget and the unified pool to every surface Three consequences of the previous two rounds, each on a surface the earlier fix did not reach. Local On Device card ranked against the default budget. The live fraction went to the Hub download card's three fit-scoring calls and not to sortLocalGgufVariants, so that card rendered a memory bar using the saved fraction directly above a quant menu ranked against 0.97. Free capacity answered a whole-load question with a carved window. resolveMemoryFit sends the WHOLE load to freeGpuCapacityGb as soon as the pool is single, and marking a ROCm APU single-pool is what this branch did, so a 60 GiB load on a 96 GiB machine with 60+ GiB free was warned as not fitting a 48 GiB window. A non-Apple unified pool now takes the host view, the same discriminator the capacity side uses, so the two cannot answer differently. FreeVramDevice also folds unifiedMemory the way MemoryCapacityDevice does; measured, that changes nothing for an APU beside a discrete card (52.08 either way, since a fully shared device already contributes its free once) and matters when a SECOND view of the same pool appears, an APU beside a Vulkan iGPU: 77.12 -> 38.56. One GET per mounted card. loadVramBudgetSettings has no read-through cache by design and clears its shared promise once each request settles, so it coalesces only overlapping callers; a catalog mounting cards through scrolling and filtering issued a settings GET per card, and a 404 per card on an older backend. The FRACTION is now cached module-wide and kept live by the change event every reader already subscribes to, while the loader keeps its always-refetch behaviour for the callers that need reloadRequired. usableSystemRamGb was computed inline in JSX and is now hoisted, because the free-capacity memo needs the same figure and two copies of the same headroom subtraction is how they drift. Frontend suite 5694 pass, 0 fail; typecheck and build clean. Each fix was confirmed to fail its own test when reverted; one first-draft test asserted a double count that does not occur and was replaced with the case that does. --------- Co-authored-by: danielhanchen <[email protected]> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> * fix(prompt storage): rework prompt storage into a master-detail layout (#8692) * Studio: rework prompt storage into a master-detail layout Cards rendered the full prompt body with no truncation, so a few dozen saved prompts became a long scroll of uneven cards. Editing happened inline in a four-row textarea, so long prompts were edited through a peephole while the list shifted underneath. Replace the flat list with a master-detail layout: a compact rail of name plus one-line preview on the left, and a detail pane on the right that owns its height. Unsaved edits are held per entry so switching rows no longer discards them, with a dirty marker in the rail and Save/Revert in the footer. List items now auto-size to their content and reorder by dragging the grips, animated with FLIP. The drag listener lives on window rather than using setPointerCapture: reordering makes React move the row's DOM node, and detaching implicitly releases pointer capture, which ended the drag after one row. Hit-testing uses offsetTop/offsetHeight since a client rect reports the pre-animation position while FLIP is in flight. Add a Preview toggle on both tabs backed by the existing MarkdownPreview, and allow bookmarking prompt lists into the + menu next to bookmarked prompts. Rows there carry a Prompt / List pill, since selecting a prompt fills the composer while selecting a list queues and sends every prompt in it. Presentation only: no schema migration, no API change, no change to the export formats or import parser, and onUse/onRunList signatures are unchanged. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Studio: address review feedback on prompt storage Select a newly created prompt or list only after the refresh resolves. The keep-a-row-selected effect runs against whatever list is in state, so selecting the new id while the old list was still in state made the effect bounce the selection to the first existing entry, and the new entry was never shown. Let the body shrink and stack on small viewports. The fixed 420px floor plus the header could exceed the dialog's 94dvh on a short window and clip the detail pane's actions behind overflow-hidden, and a fixed 248px rail left the detail pane unusably narrow below ~600px. The floor is now capped against the viewport, the rail narrows at sm and stacks below it, and the action rows wrap. Report when a list cannot be queued. startQueue refuses synchronously when queueing is unavailable and does not run the onAborted callback, so running a list from the project new-chat composer silently did nothing from both the Run button and the bookmarked-list menu items. * Studio: auto-scroll the prompt list while dragging A list taller than the detail pane could only be reordered within the visible region: the pointer handler hit-tested coordinates but never scrolled the overflow-y-auto ancestor, and pointerdown suppresses the browser's own drag gesture, so there was nothing to pull the list along. Holding a grip near the top or bottom edge now scrolls the pane and re-runs the hit-test each frame, so a drag can reach any row. The step ramps with depth into the edge band and is capped per frame. The step calculation lives in its own module with unit tests covering the dead zone, both directions, the ramp, the cap, and panes too short to hold two edge bands. * Studio: clear the search when selecting a newly created prompt or list Awaiting the refresh was not enough on its own. With a search active that the new entry does not match, the refreshed rail still excludes it, so the keep-a-row-selected effect bounced the selection to the first row that did match and the form closed on someone else's prompt. Clear the search alongside the selection so the new entry is eligible for the filtered rail. Applies to both create forms. * Studio: remeasure auto-grown textareas on resize, and end a drag released off-window The auto-sizing textarea only remeasured when its value changed, so any width change that rewrapped the text left the old height in place. With overflowY set to hidden that clipped the newly wrapped lines until the next keystroke. It now remeasures on window resize, and on a ResizeObserver width change for the cases where the column moves without the window doing so. The grip deliberately does not capture the pointer, so releasing the mouse outside the window delivered neither pointerup nor pointercancel and the drag stayed live, still autoscrolling and reordering. A move reporting no buttons held is now treated as the release that was missed, and window blur ends the drag for a release that happens entirely off the page. * Studio: export the visible draft, and ignore non-primary presses on grips Export passed the saved entry while the pane could be showing unsaved edits, so the downloaded file silently disagreed with what was on screen. It now exports the draft when there is one, normalised the way saving would normalise it, for both prompts and lists. A right- or middle-press on a reorder grip started a drag, and the zero-buttons recovery could not end it because buttons reads 2 or 4, so opening a context menu over a grip could reorder the list. Reordering now starts only on a primary press; touch and pen contacts report button 0 so they still drag, and isPrimary keeps a second finger from starting a competing drag. * Studio: run the visible list draft, scope drags to one pointer, keep new-entry drafts Run queued entry.items while the editor could be showing something else. Worst case, deleting every draft item left the button enabled off the stored length and silently ran the whole old list. Run now fires the visible non-blank items and disables on those. The window-level drag listeners saw every pointer on the device, so a second finger's movement reordered using its own clientY and its release ended the firs…
Problem
memory_total_gbis built asprops.total_memory / 1024**3(utils/hardware/hardware.py), and nothing between the driver and the pixel subtracts a budget, reserve or headroom from it. The VRAM budget fraction never reaches/api/system, andtrusted_mem_get_infocaps free only, never total. So the number is GiB.Four renderers printed it with a
GBsuffix. On a 48 GB card that reads as "45 GB", which is what #9551 reports as broken VRAM detection. 45 GiB is 48.3 GB, so the number was right the whole time and only the unit was wrong.The model information sidebar is the one the report came from.
hub-page.tsx:1291andabout-tab.tsx:194already say GiB, as dofloating-monitor.tsxandresources-tab.tsx, which is what makes the other surfaces read as a discrepancy rather than a convention.Fix
GBtoGiBat four render sites:studio/frontend/src/features/model-picker/components/model-config-page.tsxstudio/frontend/src/features/images/images-page.tsxstudio/frontend/src/features/video/video-page.tsx(a fourth site, not in the original triage)studio/frontend/src/features/studio/wizard/run-preview-card.tsxPlus a fifth surface that names its unit inside the translation rather than at the render site: the training model picker tooltip (
studio.modelPicker.vramNeeds/vramTight) interpolatesgpu.memoryTotalGbas{total}and suffixed itGBin all 12 locales. Relabelled there too, usingGiofor fr andГиБfor ru per IEC 80000-13 and GOST 8.417-2002.{est}keeps itsGB:estimateLoadingVramdivides by1e9, so that one really is decimal.on-device-folders-dialog.tsx:65is left alone: that is disk, which the backend does report in decimal GB (round(disk.total / 1e9, 2), alongsideround(memory.total / 1024**3, 2)in the same payload).Tests
studio/frontend/tests/vram-total-gib-suffix.test.tswalks every renderer of the field and fails on a decimal suffix, in three families: inline interpolation, helper-formatted (formatGiBvs the disk-onlyformatGb), and localized. Each assertion is checked per file rather than in aggregate, so one renderer cannot go dark behind another's spare match, and each was verified by mutation.Verified on Linux: frontend suite 4672 passed 0 failed,
i18n:check:strictclean,tsc -bandvite buildclean, eslint clean.Unit invariance was simulated across the cartesian product of [Linux, Windows, WSL, macOS] and [NVIDIA, AMD, Intel XPU, Apple MLX, Vulkan discrete, Vulkan integrated, CPU-only], driving the real probes with mocked drivers and every amd-smi payload shape: every path yields the same 45.0 for a 45 GiB card, never 48.32. An AST walk of the four renderers at base and at head confirms the node structure is identical and the only literal delta is
GBtoGiB, so no behaviour and no browser-visible logic changed.Fixes #9551