Skip to content

Studio: consolidate the two memory-estimate stacks - #9830

Merged
danielhanchen merged 17 commits into
mainfrom
studio/memory-estimate-consolidation
Aug 27, 2026
Merged

danielhanchen merged 17 commits into
mainfrom
studio/memory-estimate-consolidation

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Follow-up to #7880 and #9525, which added two independent answers to the same question three weeks apart.

During #7880's review its route was changed to delegate to #9525's _gguf_memory_breakdown, so the arithmetic already agrees. Everything around it did not. Two response contracts, two presentation layers, two sets of thresholds, two unit conventions, and two exported functions with the same name taking different units. Two surfaces could describe one load differently while being fed byte-identical figures.

What was actually divergent

Panel (#9525) Bar (#7880)
formatMemoryGb takes bytes, prints "GB" takes GB, prints "GiB"
Budget fraction fallback DEFAULT_VRAM_FRACTION = 0.97 VRAM_HEADROOM_RATIO = 0.9
Verdicts fits / tight / exceeds / unknown fits / context-exceeds / model-exceeds / unknown
Rounding always 2 dp adaptive
KV rate not shown binary divide labelled KB/MB
Response typing Pydantic model bare dict, no response_model

Backend: one contract, two adapters

The sharp edge is that weights_bytes exists on both routes, is an int on both, and means different things: every resident file on one, the quant file alone on the other. Nothing in the type system separates those, so unifying the key would change the number under whichever caller loses, with no shape change for a client to detect.

So the merge is done by unifying the implementation and the contract, then keeping both URLs as projections of it:

  • models.inference.MemoryEstimate is the shared contract. It deliberately has no weights_bytes at all: the name is replaced by quant_file_bytes and resident_files_bytes, and it is absent rather than redefined so no new reader can pick it up and guess.
  • core/inference/memory_contract.py holds both legacy mappings side by side, which is now the only place either is written down.
  • Both wire shapes are unchanged. A contract-freeze suite verifies that rather than assuming it, and was written and mutation-checked before either handler was touched.

Frontend: one presentation core

src/lib/memory/ holds format.ts, thresholds.ts and verdict.ts. The two feature modules stay as their surfaces' entry points and become thin re-exporters, so no call site moves.

The verdict vocabulary is a superset rather than 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.

Three behaviour changes, each isolated

Units. The panel printed GiB values labelled GB across seven figures, the defect #9570 fixed elsewhere. formatKvRate did the same one scale down with KB/MB. The existing guard test could not see either, because its regex only matches interpolations naming a *TotalGb and neither module was in its list. It now reads the shared module and covers all three formatters.

Budget fraction. The bar warned at 0.90 while the loader admits at _CTX_FIT_VRAM_FRACTION = 0.97. 0.90 is not a more cautious guess but a measured wrong one, per llama_cpp.py:

0.90 dropped 91-94% fits to CPU offload, #5106

The bar moves to 0.97, so rows currently shown as over-budget correctly report a fit.

Unified memory. The panel decided whether the GPU shares one pool with the system from usePlatformStore(s => s.appleSilicon). On a ROCm APU that is false, so it charged one pool as discrete VRAM plus host RAM and could report a fit that cannot happen. The correct per-device signal already existed in use-gpu-info.ts, and the Hub bar already abstains on it. The wording use ("Unified" vs "Shared") stays Apple-specific; only the capacity question changes.

Verification

  • Contract-freeze suite written first, confirmed green on main, then mutation-checked: adding a key, removing a key, repointing weights_bytes at the planner aggregate and disabling the delegation each fail it. The first draft did not catch the aggregate swap, because the planner delegation is skipped for a synthetic repo id and every planner field comes back present-and-null. A freeze written over that fixture asserts nothing.
  • Backend: 1734 passed across the memory / kv-cache / estimate suites.
  • Frontend: 5655 passed, typecheck, build (tsc -b), bundle:check within budget, i18n:check:strict clean.
  • Lint: 816 problems before and after, i.e. zero added.
  • 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.

Deliberately not in scope

  • Removing either legacy URL. Needs a deprecation window. Both remain, byte-identical.
  • Adding a canonical third route. It would be either dead API surface or a frontend migration of two hooks with different request shapes and cache policies. That belongs with the deprecation, not here.
  • Moving _gguf_memory_breakdown into core/. The transitive closure is ~2,219 lines across 28 symbols. A move that size in the same PR as semantic changes hides the semantic changes in review; only 4 of those symbols have non-test callers outside routes/inference.py, all in routes/models.py, so it is a clean follow-up.
  • Moving the bar onto the panel's pooled capacity model. Changes what the bar does on unified-memory and iGPU hosts and needs the full hardware matrix re-run.
  • Merging the two cache policies. A list of many rows and a single panel have genuinely different access patterns.

danielhanchen added 6 commits August 27, 2026 04:12
/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.
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.
/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.
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.
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.
One conflict, in memory-fit.ts, where #9825 reworded the comments on the exact
functions this branch moves into src/lib/memory/. Resolved in favour of this
branch: the prose upstream tightened describes code that no longer lives here.

#9824's additions to the same file, NOTE_SEPARATOR and glueNoteItems, are kept.
Those are substantive rather than cosmetic, so taking "ours" wholesale would
have dropped them; checked for explicitly rather than assumed from the fact that
the visible half of the conflict was comments.

Also updated the module docstring, which upstream had just rewritten to say
"Import-free". That is no longer true and the reason matters: the imports here
are RELATIVE with explicit extensions, which node --experimental-strip-types
resolves, while an @/ alias breaks the three tests that load this module without
a bundler resolver.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

@danielhanchen

Copy link
Copy Markdown
Member Author

UI evidence, from two isolated installs: the merge base 54367e5 and head d331185 (the later merge commit only brings main in and changes no behaviour). Same machine, same seeded opt-in key, same downloaded blob in a private cache, one Playwright scene driven against both.

before and after

The bar is unchanged and its presence proves nothing here; this PR changes what the row prints, not whether it appears. One thing moves:

BEFORE   KV reserved, ~144 KB/token
AFTER    KV reserved, ~144 KiB/token

Same number, corrected label, because the divide was always by 1024. Everything else on the row is pixel-identical: weights 2.3 GiB, context 37 GiB, total 40 GiB, and the bar geometry. That is the right outcome, since this PR does not touch the arithmetic and a moved figure would have been a regression.

One prediction I wrote before running was wrong, and it is worth stating. I expected the "of 174 GiB usable VRAM" term to grow with the 0.90 to 0.97 budget change. It did not. That fallback is only reachable while /api/settings/vram-budget is still in flight, or on a backend without the route; a live Studio answers it and both sides then use the setting's own value. Confirmed numerically rather than assumed: this host's card is 183359 MiB = 179.06 GiB, and 174 / 179.06 = 0.972, so both sides were already drawing at 0.97.

So the budget change is real and pinned by a unit test, but no screenshot of a healthy Studio can show it. Worth knowing for anyone judging the blast radius: in practice it only affects the first paint and older backends.

Two of the three behaviour changes are not covered by this pair at all, and I am not claiming otherwise:

  • the panel's GB to GiB relabel needs the Load Model panel rather than the Hub row
  • the ROCm APU capacity fix needs an APU, which this host is not

Both are covered by tests instead: memory-shared-core.test.ts and memory-unified-apu.test.ts, the latter including a source assertion that the panel hands the capacity call the general unified-memory signal, verified by reverting the fix and watching only that assertion fail.

pre-commit-ci Bot and others added 3 commits August 27, 2026 05:27
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.
@danielhanchen

Copy link
Copy Markdown
Member Author

Adversarial verification pass over this PR's own changes, since reviewing your own consolidation is exactly where confirmation bias lives. Theorised the failure modes first, then built simulations to try to hit them. Three real defects found, two of them mine.

Fixed: mine

1. Post-construction mutation bypassed Pydantic validation. 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. Measured rather than assumed, on pydantic 2.13:

m = MemoryEstimate(available=True)
m.gpu_bytes = "not an int"   # succeeds, and goes straight onto the wire
m.total_bytes = None         # declared int, accepted

Those four are now parameters of build_memory_estimate, so the model is built once and validated once. gpu_bytes needed 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

2. A non-finite footprint produced a confident verdict. computeModelMemory turned weightsBytes = Infinity into model-exceeds: a full destructive bar reading "Larger than VRAM" next to 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, so this was also the two surfaces disagreeing about identical bytes. null/undefined are untouched, since those mean "has not arrived yet".

Found by the property suite, not by reading.

Found, NOT fixed, and out of scope

3. The fit badge and the memory bar contradict each other on the same row. Measured on a 24 GiB card:

18   GiB model: badge=marginal   bar=fits
20   GiB model: badge=marginal   bar=fits
20.5 GiB model: badge=partial    bar=fits

This is not the budget fraction: it is identical at 0.90 and 0.97. classifyGgufFit still uses the old size * 1.15 + 1 GB heuristic while the bar uses the planner, so they disagree because they are different estimators, not different budgets. That is a third estimator in gguf-fit.ts which also drives a filter, so rewiring it belongs in its own PR rather than being smuggled into this one.

Simulation coverage

memory-cross-surface-matrix.test.ts — 128 cells: [linux, wsl, win32, darwin] x nine inventories (NVIDIA single/dual, ROCm discrete, ROCm APU, AMD Vulkan iGPU, Intel iGPU, Apple unified, mixed dGPU+iGPU, CPU only) x four footprints, minus physically impossible cells. Six properties per cell: no false fit, no bar/panel contradiction, one label per byte count, no pool counted twice, CPU-only draws nothing, no NaN/Infinity in any label. Defect 2 is what this caught.

test_memory_contract_platforms.py — the same four platform keys x six placements (single card, dual, partial offload, unified APU, LLAMA_ARG_DEVICE=none, planner absent), pinning that both wire shapes are byte-identical everywhere and weights_bytes keeps its own meaning per route in every cell.

Compatibility

Old backend, new frontend. The one new field read is unified_memory, and use-gpu-info.ts was already reading it on main — I only consumed it. A backend that never sends it leaves hasUnifiedMemory exactly equal to the appleSilicon check it replaced, in both directions. Pinned by a test.

Old client, new backend. Both response shapes are unchanged, verified by the mutation-checked freeze suite rather than by inspection. No new request parameters, no localStorage or per-model-config changes.

Browsers. The entire frontend addition uses Math.round and Number.isFinite and nothing else — no DOM, no CSS, no browser-only API. Number.isFinite is Baseline widely available (ES2015, since September 2015) per MDN, so Chrome, Edge, Firefox and Safari are all covered. Build target is unchanged at ES2022.

Sandbox

Fresh uv venv on Python 3.13 with only pytest, pydantic, fastapi, structlog, huggingface_hub, psutil, pyjwt, passlib, bcrypt, cryptography: 710 passed. The only two failures there need the real transformers package and pass with it, which also confirms the consolidation pulls in no dependency it does not declare.

Frontend: 5673 passed, typecheck, tsc -b build, bundle:check in budget, i18n:check:strict clean. tsc -b caught two type errors in my own new tests that the test runner had happily executed, which is the usual reason to run both.

pre-commit-ci Bot and others added 3 commits August 27, 2026 06:04
…e 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.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Aug 27, 2026
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.
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. What shall we delve into next?

Reviewed commit: 635e7500d7

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

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

This comment was marked as resolved.

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

This comment was marked as resolved.

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.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 27, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 27, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 27, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 27, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 27, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 27, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 27, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 0a06f0cfe7

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +12 to +14
/** The saved VRAM Budget, so the sort ranks against the line the loader will
* actually admit at rather than against the default. */
budgetFraction?: number;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Apply the saved budget to local GGUF sorting

When the user saves a VRAM budget other than the 0.97 default, only GgufDownloadCard supplies this new value. LocalOnDeviceCard still calls sortLocalGgufVariants with only gpuGb and systemRamGb, so its quant menu ranks non-active/non-default variants against 0.97 while the memory bar on the same card uses the saved fraction. For example, with an 0.80 budget, a variant considered over-budget by the bar can remain ahead of a smaller fitting variant in the local menu; pass the live fraction from that card too, or make this input required so callers cannot silently fall back.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Correct, exactly as described. LocalOnDeviceCard renders ModelMemoryBarFor at line 728 and calls sortLocalGgufVariants at line 349 with gpuGb and systemRamGb only, so one card drew a bar against the saved fraction and ranked the quant menu directly above it against 0.97.

Fixed by reading the same hook there. I took the "pass the live fraction" option rather than making the input required: GgufVariantResources is shared with the remote path, and a required field would force every caller to have an answer at a point where "not loaded yet" is a legitimate state, which is the case the optional-with-default fallback exists to serve.

There is now a test asserting that BOTH cards read the fraction and pass it on, so a third card cannot be added without one.

Comment on lines +2848 to +2849
if (governing.length === 0) return false;
return governing.every((device) => device.unifiedMemory === true);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Use system availability for ROCm unified-pool pressure

When every governing device is a ROCm APU, this newly marks the load as a single pool, but memoryFreeGpuCapacityGb is still produced by aggregateUsableFreeVramGb, whose FreeVramDevice logic checks only sharedMemory and therefore treats a Linux APU (sharedMemory: false, unifiedMemory: true) as dedicated VRAM. resolveMemoryFit then compares the entire totalBytes against that GPU-visible free window and treats either this result or the system-RAM result as pressure. On the documented 48 GiB window/96 GiB RAM case, a 60 GiB load with over 60 GiB of system memory available is consequently warned as not fitting what is free merely because it exceeds the carved GPU window. For a ROCm unified pool, use the available system-memory view for the whole-load pressure check, or teach the free-capacity path how unifiedMemory differs from a dedicated device.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

You are right, and I was wrong to scope this out last round. I said the free-VRAM path was "not reachable from anything this PR touches"; it is reachable, and this PR is what made it so.

The mechanism is the one you name. resolveMemoryFit sends the WHOLE load to freeGpuCapacityGb as soon as the pool is single:

const freeGpuFit = classifyMemoryFit(
  singleMemoryPool ? estimate.totalBytes : estimate.gpuBytes,
  capacity.freeGpuCapacityGb,
);

Marking a ROCm APU single-pool is precisely what this branch did, so the whole-load question started being asked of the free space inside a carved window. A 60 GiB load on a 96 GiB machine with 60+ GiB available was warned for exceeding 48.

Both halves are addressed:

  • A non-Apple unified pool now takes the host view for that figure, using the same hasUnifiedMemory && !isAppleUnifiedMemory discriminator as the capacity side, so free and capacity cannot answer differently about the same machine. Apple is untouched: its GPU figure already is the pool.
  • FreeVramDevice folds unifiedMemory the way MemoryCapacityDevice does.

One correction worth recording, because my first attempt at the second half claimed more than it delivers. I wrote a test asserting the fold stops an APU's window being double counted beside a discrete card. Measured, it does not: 52.08 GiB either way, because a fully shared device already contributes its free exactly once and there is nothing to deduplicate until a SECOND view of the same pool appears. The mutation check caught it. The case where the fold does matter is an APU beside a Vulkan iGPU, both views of the same host memory:

unfixed  77.12 GiB     fixed  38.56 GiB

The test now pins that, and the comment says plainly what the fold does not buy.

Comment on lines +629 to +632
// The live VRAM Budget, so the badge and the sort score against the line the
// loader will actually admit at. The memory bar on this same row already reads
// it; without this the two disagreed for every saved fraction below the default.
const budgetFraction = useVramBudgetFraction() ?? undefined;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Share the budget read across Hub cards

Every GgufDownloadCard now mounts this hook unconditionally, even before variants or fit information are available. loadVramBudgetSettings explicitly has no read-through cache and clears its shared promise after each request, so it only coalesces cards whose effects overlap; cards mounted later through scrolling, filtering, or pagination each start another /api/settings/vram-budget GET (and repeatedly hit a 404 against an older backend). A catalog with many progressively mounted GGUF cards therefore generates repeated settings traffic for one host-wide value. Load the fraction once in a catalog-level provider/store, or keep a fraction-only cache updated by the existing change event rather than invoking the always-refetching settings loader per card.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Correct. vram-budget.ts says so in its own comment ("No read-through cache: reloadRequired describes the running process and goes stale on any load or swap") and clears the shared promise in a finally, so it coalesces only callers whose requests overlap in time. A catalog that mounts a card per repo through scrolling, filtering and pagination therefore issues a GET per card, and a 404 per card against a backend predating the route.

Taken the second of your two options. The FRACTION is now cached module-wide inside the hook, while loadVramBudgetSettings keeps its always-refetch behaviour for the callers that actually need reloadRequired; splitting them that way means the settings panel is unaffected. Concurrent mounts still share one in-flight promise, and a null answer sets a routeAbsent flag so an older backend is asked once rather than once per card.

The cache is kept honest by the change event every other reader already subscribes to, so a save still reaches every mounted card immediately. A transient failure deliberately does NOT set routeAbsent, so one bad response cannot pin the session to the default.

A provider would have been the other reasonable shape. I did not take it because the value is host-wide rather than catalog-scoped and three non-catalog readers want it too, so a catalog-level provider would have left them on the old path.

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

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Aug 27, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

UI evidence: the panel figures, before and after

Estimated Memory Usage row, BEFORE and AFTER

Two isolated install.sh --local builds, same scene driven against both, same machine and viewport.

  • BEFORE: merge base 1fe27b1b5
  • AFTER: 0a06f0cfe

0a06f0cfe rather than the current head, and worth saying so: the two commits after it are the ROCm APU free-pool fix and the saved-budget plumbing, neither of which touches these labels. This pair is evidence for the relabel only.

What it shows. Five figures on the row, and the same five numbers on both sides:

BEFORE AFTER
GPU 39.72 GB 39.72 GiB
Total 39.72 GB 39.72 GiB
Weights 2.33 GB 2.33 GiB
KV cache 36.00 GB 36.00 GiB
Compute buffers 1.40 GB 1.40 GiB

The values being IDENTICAL is the stronger half of the claim. formatMemoryGb was (bytes / 1024**3).toFixed(2) + " GB", so the divide was always binary and only the label was wrong, overstating every figure by 7.4%. A pair where a number had moved would mean the estimate itself changed, which this PR does not claim and would be a regression. That is why the figures are captured as data next to the picture rather than left to the eye.

This is the surface the earlier evidence on this PR could not reach. The Hub row's figures were already GiB, so that shot could only ever demonstrate the KB/token to KiB/token change.

What this pair does NOT cover, so it is not read for more than it proves: the ROCm APU capacity, free-pool and saved-budget fixes from the review rounds. Those need an APU, which this host is not, and a saved budget below 0.97 on a card small enough for the fit bands to differ, where this box has a 179 GiB card. They are covered by unit tests instead, each confirmed to fail when the fix is reverted.

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 0b5c6fea20

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

}

function ensureLoaded(): Promise<void> {
if (cachedFraction !== null || routeAbsent) return Promise.resolve();

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Refresh a cached budget after subscribers remount

When cachedFraction was populated during an earlier Hub visit and all cards later unmount, a budget update from ModelConfigPage publishes its change event with no hook subscriber present. On returning to the Hub, this early return prevents a new GET, so variant badges and sorting continue using the old fraction indefinitely. Keep a module-level subscription alive or revalidate the cache when the first consumer remounts.

Useful? React with 👍 / 👎.

// Null is the route being absent, not a transient failure, so record it
// rather than asking the next card to find out again.
if (settings) cachedFraction = settings.fraction;
else routeAbsent = true;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Retry transient budget-loading failures

loadVramBudgetSettings returns null for any caught error, including transient network/server failures and superseded reads, not only when the route returns 404. Marking every null result as routeAbsent means a temporary failure on the first catalog request permanently disables retries for the session, leaving every card on the default fraction despite a saved value. Set this flag only when route absence is explicitly confirmed and leave other failures retryable.

Useful? React with 👍 / 👎.

@danielhanchen
danielhanchen merged commit 14d4fb3 into main Aug 27, 2026
46 of 53 checks passed
@danielhanchen
danielhanchen deleted the studio/memory-estimate-consolidation branch August 27, 2026 08:00
danielhanchen added a commit that referenced this pull request Aug 27, 2026
* 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>
danielhanchen added a commit that referenced this pull request Aug 27, 2026
…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…
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant