Skip to content

Add Estimated Memory Usage to the Load Model panel - #9525

Merged
danielhanchen merged 52 commits into
mainfrom
studio-estimated-memory-usage
Aug 26, 2026
Merged

danielhanchen merged 52 commits into
mainfrom
studio-estimated-memory-usage

Conversation

@shimmyshimmer

Copy link
Copy Markdown
Member

Adds an Estimated Memory Usage row to the Load Model panel, so you can see what a model will cost before you load it and how much context you can actually fit.

The row sits directly above Context Length, since that is the control that moves the number most. It expands into a breakdown of weights, KV cache and compute buffers.

Why not a rule of thumb

We already had size * 1.15 + 1 GB style heuristics in gguf-fit.ts and recommended-fit.ts. Those are fine right up until the KV cache stops being a rounding error, and then they are not slightly wrong, they are missing the largest term. Measured on unsloth/Qwen3.8-27B-GGUF (UD-IQ3_XXS):

Context KV dtype Weights KV cache Compute Total
4,096 f16 12.32 GB 0.40 GB 0.05 GB 12.77 GB
40,223 f16 12.32 GB 2.61 GB 0.10 GB 15.04 GB
262,144 f16 12.32 GB 16.15 GB 0.42 GB 28.89 GB
262,144 q4_0 12.32 GB 10.40 GB 2.86 GB 25.58 GB

At full context the cache outweighs the model. The last row is worth a second look too: quantizing the cache to q4_0 saves 5.75 GB but adds 2.44 GB of dequant scratch to the compute buffer, so the intuition that q4 quarters your cache cost is wrong. Splitting the breakdown into three lines is what makes both of those visible.

So the numbers come from the loader's own sizing, not a new approximation: _estimate_kv_cache_bytes with its MLA / hybrid-Mamba / SWA / GQA / legacy paths, plus _estimate_compute_buffer_bytes and _compute_buffer_ctx_bytes. That is the same code that decides how much context a load actually gets, so the panel and the loader cannot disagree.

Saying so when it cannot be known

Three cases where a confident number would be worse than none:

  • Header without attention dims. kv_estimable comes back false, the row shows a floor with an amber note rather than a total whose biggest component was assumed. This is the one that matters, since a KV cache priced at zero is indistinguishable from a real zero.
  • --n-cpu-moe. Moves individual expert tensors, not whole blocks, and there is no layer arithmetic that gets it right. Reported as unmodelled instead of guessed.
  • --no-kv-offload. The cache lives in host RAM, so it comes out of the GPU figure.

Backend

New POST /api/inference/estimate-memory. Header-only and allocation-free: no model is loaded, no device is touched, nothing is downloaded. A model that is not on disk answers not_downloaded, and an Ollama manifest reference is refused before anything is materialized, since resolving one writes a link to disk and that belongs to the load path.

_estimate_gguf_kv_gb is split into _gguf_runtime_bytes, which returns KV and compute separately plus the flag. The old function remains as the summing wrapper the training admission guard calls, with its value unchanged.

Two things fixed along the way:

  • from_identifier leaves gguf_file unset for anything it resolved as a repository, even once the weights are sitting in the HF cache. _estimate_gguf_required_gb branches on that field, so a cached repo was priced through a paths-info call: a network round trip behind a slider, and no estimate at all offline. _localized_estimate_config points the config at the file on disk and runs the same companion detection the local-folder branch runs. It now works under HF_HUB_OFFLINE=1 and picks up a 0.4 GB drafter the listing had been missing.
  • Both TTL caches are now keyed by a hashed token fingerprint, so a gated repo resolved with one subject's token is not served to another.

Warm requests are about 73 ms, almost all of it the GGUF header walk.

Frontend

useMemoryEstimate debounces at 250 ms and aborts in flight, so a slider drag lands one request and a slow answer for a context you already dragged past cannot overwrite a newer one. A re-price keeps the previous numbers on screen rather than blinking through a spinner. GGUF only; diffusion stands down because its runner allocates on a different plan.

Testing

  • 49 new tests in test_memory_estimate.py: the KV/compute split against synthetic headers, the unsizable-header path, the offload split, --no-kv-offload, the localization (including that the cached config is never mutated), token-scoped caches, and the route's refusal answers. The load-bearing one asserts that the weights figure does not move when the context does, which is what proves the two arms of the subtraction stay paired.
  • One assertion updated in test_server_tuning_flags.py. It source-inspected _estimate_gguf_kv_gb for the checkpoint threading, and that arithmetic now lives in _gguf_runtime_bytes. Behaviour is unchanged; the test now asserts both halves of the split, so dropping the field in either place still fails.
  • 720 passing across every file that touches the shared estimator: test_kv_cache_estimation, test_chat_load_during_training, test_mtp_drafter_companion, test_batch_sizes_per_load, test_mmproj_placement_policy, test_server_tuning_flags.
  • Frontend: 4391 tests, typecheck and i18n parity clean.

Known gap

Verified end to end against a real cached model through the route, and at the API level for every branch, but not yet visually confirmed in a browser on a machine with the row on screen. Worth a look before merge.

Separately, there is a pre-existing crash unrelated to this change: a bare import mlx.core in _apple_metal_memory_budget_bytes (llama_cpp.py) aborts the whole process on macOS when torch was imported first, and the surrounding try/except cannot catch a C-level abort. Reproduces with this branch stashed, so it wants its own fix.

Shows what the current settings would cost before you load, itemized into
weights, KV cache and compute buffers.

The figures come from the loader's own sizing (_estimate_kv_cache_bytes and
the compute-buffer math in llama_cpp.py) rather than a weights-times-a-constant
approximation. That distinction is the point: at 262k context on Qwen3.8-27B
the cache is 16.15 GB against 12.32 GB of weights, so a rule-of-thumb estimate
is not slightly off, it is missing the largest term.

Where the GGUF header cannot supply the attention dims the row reports a floor
and says so, instead of quoting a total whose biggest component was assumed.
Same for --n-cpu-moe, which moves tensors rather than blocks and is flagged as
unmodelled, and --no-kv-offload, which moves the cache off the GPU figure.

Backend:
- POST /api/inference/estimate-memory, header-only and allocation-free
- split _estimate_gguf_kv_gb into _gguf_runtime_bytes, which returns KV and
  compute separately plus a kv_estimable flag; the old function stays as the
  summing wrapper the training guard calls, unchanged in value
- _localized_estimate_config points a cache-resident HF repo at its files on
  disk, so the estimate stops pricing itself through a paths-info call and
  works offline
- both TTL caches keyed by a hashed token fingerprint

Frontend:
- collapsible row above Context Length, GGUF only, debounced at 250ms with
  in-flight aborts so a slider drag lands one request

Tests: 49 new, covering the KV/compute split, the unsizable-header path, the
offload split, the weights-do-not-move-with-context invariant that the
subtraction depends on, and the route's refusal answers.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

Native leases (P2): the route verified grants under "estimate-memory", which is
not an operation a client can mint and never matches the "validate-model" lease
the frontend signs. Leases compare the operation exactly, so every picked or
drag-dropped GGUF failed verification and the row never appeared for them.
Verified now under "validate-model", the same read-only header probe /validate
performs. Confirmed with a signed lease: the old name raises "grant operation is
invalid", the new one returns a native grant.

Parallel slots (P1): a blank Parallel Slots field is the default UI state and
means the server default, four in a standard launch, which is what /load resolves
through _resolve_parallel_slots. Pricing one slot underestimated the default
configuration by 2.07 GB on Qwen3.8-27B at 40k context (15.04 -> 17.11 GB). The
route now takes the FastAPI request and resolves and clamps slots the same way.

Companion placement (P2): --gpu-layers splits the model, not the projector and
drafter beside it, which are placed by their own flags. Scaling the whole files
term by the layer fraction let --gpu-layers 0 report an empty GPU while 2.14 GB
of companions sat in VRAM. Only the main weight is scaled now. A CPU-pinned
drafter is already dropped from the total upstream, so the projector is the one
companion that can be charged and off-GPU; --no-mmproj-offload moves exactly it,
measured as the projector's 0.86 GB with the 1.28 GB drafter left on the GPU.

Pinned GPU pool (P2): the fit verdict compared against every installed card, so a
load pinned to one 8 GB card read as fitting on a two-card 16 GB total. Capacity
now sums the pinned devices, and tensor mode sizes its per-device buffers from
the pinned count rather than the whole host.

Tests: 57 total, up from 49. The manual-split test asserted the old whole-weights
scaling and now asserts the corrected split, with its fixture pinning the main
and companion shares (the synthetic header is a few hundred bytes, which made the
old split degenerate).
@shimmyshimmer

Copy link
Copy Markdown
Member Author

Thanks, all four were real. Checked each against the code before changing anything, and each fix is verified rather than assumed.

Native leases. Correct, and worse than described: _validate_payload compares the operation exactly, and estimate-memory is not in the NativePathOperation union at all, so it was not a mismatch that might sometimes pass, it could never pass. Verified by minting a real signed lease for validate-model and running it through _resolve_model_identifier_for_request both ways: the old name raises "Native path grant operation is invalid", the new one returns a grant with native_grant_backed=True. Now verified as validate-model, which is the right grant since this is the same read-only header probe /validate performs.

Parallel slots. Correct. _PARALLEL_DEFAULT_PLAIN is 4, so the default UI state was priced at a quarter of the slots it will actually launch with. On Qwen3.8-27B at 40k context that is 15.04 GB reported against 17.11 GB actual, and the whole 2.07 GB gap is the compute buffer plus cache the extra slots take. The route now takes the FastAPI request and goes through _resolve_parallel_slots and _effective_parallel_slots, so it also picks up the one-slot clamp on builds without --kv-unified. An explicit count still wins.

Companion placement. Correct. Measured on a vision model with an MTP sidecar: --gpu-layers 0 reported 0.00 GB on the GPU while 2.14 GB of projector and drafter were resident. Only the main weight is scaled by the layer fraction now.

One refinement on the suggestion. A CPU-pinned drafter is already dropped from the total upstream by _charge_no_drafter, so any drafter bytes that made it into the figure are GPU-resident by construction. That leaves the projector as the only companion that can be both charged and off-GPU, so --no-mmproj-offload moves it alone rather than sweeping every companion off with it. Measured: 2.14 GB drops to 1.28 GB, which is exactly the 0.86 GB projector leaving and the 1.28 GB drafter staying.

Pinned GPU pool. Correct. Capacity now sums only the pinned devices, and the total ceiling follows it so the RAM-inclusive figure is not measured against cards the load cannot reach. config.selectedGpuIds is already reconciled against gpuDevices upstream, so the indices are in the same namespace and filtering by device.index is safe. Also threaded the selection to the backend as selected_gpu_ids, so tensor mode sizes its per-device buffers from the pinned count: _guard_device_count([0,1], tensor_parallel=True) gives 2 instead of every card on the host.

Tests are 57, up from 49. One existing test asserted the old whole-weights scaling and now asserts the corrected split; its fixture had to pin the main and companion shares, because the synthetic header is a few hundred bytes and made the split degenerate against a patched 4 GB files term.

One correction while writing the slot tests: I first asserted the KV cache grows with slots, and it does not for a plain GQA model under unified KV, where the slots share one set of cells. Only the compute buffer always grows. The assertion now reflects that instead of the behaviour I expected.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

tests/test_source_read_encoding.py fails the build on this read: without an
encoding it takes the platform default, so it breaks on Windows the moment
types.ts gains a non-ASCII byte.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

Drafter runtime (P1): a separate drafter keeps its own KV cache and rollback
state on top of its file, which the loader budgets through
_estimate_mtp_overhead_bytes and the files term says nothing about. Charging only
the file made speculation look nearly free: on Qwen3.8-27B with its MTP sidecar
that is 0.83 GB of draft cache at 4k and 16.58 GB at 262k. The request now also
carries the draft depth and draft cache dtype, which both move the figure.

The drafter is identified by the bytes it added rather than by re-deriving the
mode precedence. That precedence depends on capability probes and Auto-mode rules
inside _estimate_gguf_required_gb, and a second copy would price a different
sidecar from the one actually charged.

Unified memory (P1): the row labelled gpu_bytes "Unified" and hid the total. On
one pool an offloaded byte is not a freed byte, so a zero-layer load read as
almost free while the weights still filled memory. Reports the total there now.

CPU-pinned drafter (P2): _estimate_gguf_required_gb drops it because it is a VRAM
admission figure, but this panel reports host RAM too. Recovered by re-pricing
with the pin overridden, so the weights and the drafter's own runtime stay in the
total and leave only the GPU column. Verified: total identical either way, GPU
drops by 4.33 GB.

Shared Vulkan memory (P2): an iGPU's memoryTotalGb is already a capped view of
system RAM, so adding systemRamTotalGb counted the same bytes twice. GpuInfo now
carries sharedMemory and those devices get the single-pool treatment.

Layer-split device count (P2): a pinned multi-GPU load layer-splits, and
_gguf_runtime_bytes charges per-device pipeline overhead and replicates the
context-linear compute term. The count was forced to 1 outside tensor mode.

Token changes (P2): the debounce key collapsed every token to "token", so
swapping one for another never re-fetched even though the backend caches per
token. Keyed on a djb2 identity instead, which never carries the credential.

Tests: 61, up from 57.
@shimmyshimmer

Copy link
Copy Markdown
Member Author

Second round, all six checked before changing anything. Five were right and I fixed them; one I implemented differently from the suggestion, explained below.

Unified memory (P1). Right, and this is the one that would have bitten hardest on a Mac. The row showed gpuBytes under a "Unified" label, so a zero-layer manual load read as almost free while the weights still sat in the same pool. On one pool an offloaded byte is not a freed byte, so it reports the total there now, and the fit verdict and the "does not fit" note follow the same figure.

Drafter runtime (P1). Right. Measured on the MTP sidecar in unsloth/Qwen3.8-27B-GGUF: the draft cache alone is 0.83 GB at 4k and 16.58 GB at 262k, none of which was counted. _estimate_mtp_overhead_bytes is now called with draft_weights_bytes = 0, since the file is already in the weights term. The request carries spec_draft_n_max and spec_draft_cache_type too, and both move the number: at 262k a q8_0 draft cache is 42.38 GB against 49.88 GB for f16.

One deliberate difference. Rather than re-deriving which sidecar the mode picks, the drafter is identified by the bytes it added: price the files once normally and once with --spec-draft-ngl 0 appended, and the difference matches against the config's candidate sidecars. Both draft flags are last-wins in llama.cpp's parsers, so an appended value overrides earlier arguments and the environment fallback. That precedence lives in _estimate_gguf_required_gb behind capability probes and Auto-mode rules, and a second copy of it would eventually price a different sidecar from the one actually charged, which is worse than not pricing the cache at all.

CPU-pinned drafter (P2). Right, and the same reasoning applied to the runtime, not only the weights: a drafter in host RAM still holds its KV there. Recovered with the same last-wins trick in reverse, re-pricing with the pin overridden. Verified: total is byte-identical whether the drafter is pinned or not, and the GPU column drops by 4.33 GB, which is the 1.28 GB file plus 3.05 GB of draft state.

Shared Vulkan memory (P2). Right. systemRamAvailableGb is already zeroed for those devices in use-gpu-info.ts but systemRamTotalGb is not, so my total capacity added the same RAM the iGPU budget already represents. GpuInfo now carries sharedMemory and those devices get the same single-pool treatment as Apple Silicon, including the wording of the advisory, which previously offered to spill layers into RAM the load was already counting.

Layer-split device count (P2). Right. _guard_device_count already handled it and I only wired it for tensor mode. Now passed for both; automatic placement still resolves to one, and the non-tensor path returns without probing devices.

Token changes (P2). Right. The key collapsed every non-empty token to the literal "token", so swapping a token that cannot reach a gated repo for one that can never re-fetched. Keyed on a djb2 identity of the token instead, which distinguishes two values without the credential entering the key.

Tests are 61, up from 57: the drafter is found by its byte count and not guessed, the drafter runtime grows with context while the weights do not, a CPU-pinned drafter keeps its bytes in the total and loses them from the GPU, and a pinned layer split counts its cards.

Also rebased onto @danielhanchen's encoding fix, which was a real bug in a test I added: read_text() without an encoding takes the platform default and breaks on Windows. tests/test_source_read_encoding.py and test_text_io_encoding.py both pass.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

Two estimate gaps found in review.

The companion search passed the weight's own parent as search_root, which is
what detect_mmproj_file already uses as start_dir, so its upward walk never ran.
A cached repo that files each quant under its own directory keeps the projector
and drafter at the snapshot root, so the panel dropped a 0.8 to 2.6 GB projector
on the Llama-4-Scout, Qwen2.5-VL-72B and Qwen3-VL-235B GGUF repos. Use the load
path's own _local_gguf_companion_search_root instead.

Blank draft depth was priced as zero, but the launch emits its own default when
the field is unset, and the rollback state is multiplied by that depth. A hybrid
Mamba target lost 1.57 GB at one slot and 6.29 GB at four. Resolve the depth the
launch would really use, with the same precedence: extras, then the request
field, then the platform default.
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

chatgpt-codex-connector[bot]

This comment was marked as resolved.

UnboundLocalError (mine, from the last round): only the non-pinned branch bound
gpu_drafter_bytes, so a CPU draft pin on a model that ships no sidecar read it
unbound and answered 500, taking the row out for an otherwise ordinary load.
Reproduced, then bound before the branch.

Custom drafter path: a --model-draft naming a file outside the discovered
sidecars was charged in the files term but never matched by
_charged_drafter_path, so its cache and rollback state were dropped. The extras
path is taken first now and without the size match, since it is the drafter the
launch opens whatever discovery found. A remote --spec-draft-hf is not a local
file, so it stays unsized rather than guessed.

Draft cache dtype: K and V are independent overrides that the launch resolves
through _extra_args_draft_cache_types, and passing the panel field for both
priced a cache the load will not allocate. Extras beat the field, as at launch.
Verified: --cache-type-k-draft f32 moves the draft figure from 4.81 to 7.28 GB.

Layer count on an unsizable header: block_count is a separate GGUF key and is
usually present, but the unknown-runtime return discarded it. A manual split then
had nothing to scale against, so _gguf_offloaded_layer_fraction answered 1.0 and
called --gpu-layers 0 a fully GPU-resident load. Carried out now, which takes
that case from 1.0 to 0.0.

Also itemizes the drafter runtime as its own response field and breakdown line.
Daniel judged this below the bar as a fix and he is right that no displayed
figure was wrong, but the line is cheap and the term is large: the four items now
sum to Total exactly, and on Qwen3.8-27B at 262k the draft cache is 18.34 GB
against 12.32 GB of weights.

Tests: 71, up from 61.
@shimmyshimmer

Copy link
Copy Markdown
Member Author

Four open findings this round, all four correct. Also picked up @danielhanchen's snapshot-root and blank-draft-depth fixes by rebasing.

The UnboundLocalError is mine, from the last round, and it is the worst of the batch. Only the non-pinned branch bound gpu_drafter_bytes, so a CPU draft pin on a model that ships no sidecar read it unbound and answered 500. My own verification last round used a model that does have an MTP sidecar, which is exactly why I missed it. Reproduced it first, then bound both counters before the branch. There is a regression test for the no-sidecar pin now.

Custom drafter path. Correct. _extras_bytes charges a --model-draft naming a file outside the discovered sidecars, so it landed in gpu_drafter_bytes, but _charged_drafter_path only matched the three config attributes and returned None, dropping the cache. The extras path is taken first now and without the size match, since it is the drafter the launch opens whatever discovery found. A remote --spec-draft-hf is not a local file so it stays unsized rather than guessed, which matches what _estimate_gguf_required_gb does with it.

Draft cache dtype. Correct. _extra_args_draft_cache_types resolves K and V independently and I was passing the panel field for both, pricing a cache the load will not allocate. Extras beat the field now, same precedence as the launch. Verified end to end: --cache-type-k-draft f32 moves the draft figure from 4.81 GB to 7.28 GB at 40k.

Layer count on an unsizable header. Correct, and the consequence is worse than losing a field. block_count is a separate GGUF key and usually present, but the unknown-runtime return dropped it, so _gguf_offloaded_layer_fraction had nothing to scale against and answered 1.0. A manual --gpu-layers 0 on such a model was reported as fully GPU-resident. Carried out of the header walk now: that case goes from 1.0 to 0.0.

On the itemization comment. Daniel is right that no displayed figure was wrong, so it was not a correctness fix. But the line is about ten lines and the hidden term is not small, so I added it rather than leaving it: drafter_runtime_bytes is its own response field and its own "Draft cache" row, shown only when a separate drafter is loaded and annotated when it sits in host RAM. The four items now sum to Total exactly, which I assert rather than assume. On Qwen3.8-27B at 262k that row is 18.34 GB against 12.32 GB of weights, which seems worth being able to see.

Tests are 71, up from 61. One existing test asserted layer_count is None on the unsizable header, which was the behaviour being fixed; it now asserts the count survives and that the offload fraction it feeds is 0.0 rather than 1.0.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

A separate drafter is not an MTP head: DSpark and DFlash were charged a
second copy of an MLA target's KV context. Extras that own --spec-type
draft at the build's depth, not the panel's. And a drafter does not
inherit --gpu-layers, so its cache is on the GPU at --gpu-layers 0 while
the target-side terms stay with the target.
@shimmyshimmer

Copy link
Copy Markdown
Member Author

Round-up for 0728b94. Three of the four this round were correct and are fixed; the fourth I am pushing back on with evidence, and it is @danielhanchen's, so worth reading in the thread.

Mode-specific spec terms (P2, correct). The estimator called _estimate_mtp_overhead_bytes with its defaults, which charge both target-side terms because an unsure caller should over-reserve. The loader is not unsure: it derives them per engaged mode. On an MLA target at 128k a DSpark drafter was charged 1.500 GB where it allocates 0.750 GB, the difference being a second full copy of the target KV that only MTP keeps. draft-simple was also charged rollback state it never allocates.

Draft depth when the extras own the spec block (P2, correct). _build_speculative_flags returns before emitting a depth once --spec-type is present, so neither the panel field nor the 2/3 platform default reaches the child. Priced depth goes 3 to 16, and 2 to 16 when the field says 2. Read from the capability cache the loader already fills, never probed, since this runs on every settings change.

Drafter placement at zero GPU layers (P2, correct, fixed differently). A separate drafter does not inherit --gpu-layers, so its cache sits in VRAM at --gpu-layers 0. Charging the whole reserve on the drafter's placement would have moved terms that are not the drafter's, so the reserve is now split: target-side terms follow the target cache, the draft cache follows the drafter. That also fixes the mirror case, where a CPU-pinned drafter dropped the target-side terms the loader keeps.

Layer count on an unsizable header (not taking). The truncation and required-key reasoning holds, but the path is reached by a whole family rather than by a corrupt file: llama-model.cpp:1177 reads the attention head counts with required = false while block count and embedding length are required, so every pure SSM model (Mamba, Mamba2, RWKV) lands there with a layer count and no attention dims. Verified through _read_gguf_metadata rather than argued. Without the count, a manual --gpu-layers 0 reads as a fully GPU-resident load on all of them.

Tests: 77 in test_memory_estimate.py, 41 in test_server_tuning_flags.py, all passing. The six new ones fail on the parent commit and pass on this one, which is how each of the four above was checked before and after.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

A --split-mode in Advanced Arguments last-wins over the toggle, and Auto
emits -ngl -1 that a user -ngl overrides. Both were priced from the panel
fields alone, so a tensor launch read as a layer split and a CPU-only
Auto load read as fully GPU-resident.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

/load translates a manual -ngl into the field, resolves the context
last-wins rather than at the maximum the coexistence guard uses, and
leaves the expert-offload flags in place outside Manual. The panel now
prices all three the same way.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

sharedMemory is devices.some(...) across the host, so on a mixed Vulkan
inventory a pin naming only the discrete card still suppressed system
RAM from the ceiling and called a load that fits impossible.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

…encoder

One card drops tensor mode and gets its quantized KV back, a drafter's
cache takes the target's swa/slot/ubatch layout rather than the helper
defaults, and a vision projector costs the encoder buffers the placement
path budgets on top of its file.
Extracted the verdict and advisory chain out of model-config-page.tsx into an
import-free model-config/memory-fit.ts, following estimate-context.ts, whose own
header explains why: the node runner cannot load a .tsx, so classifyMemoryFit,
worseMemoryFit and the whole advisory ladder were unreachable from any test. That
is how the three below survived review. The page is 170 lines lighter and the
behaviour is identical apart from the fixes.

The single-pool advisory was unreachable. The pool ternary gated the entire tail
of the chain, and the sub-branch inside its false arm selected on the pool flag
again, so the string the author had written for a pressured unified host could
never render. An exhaustive sweep over every reachable capacity and verdict
combination selects it zero times. The user-visible half: Apple unified, 64 GB
pool, a 30 GB load with 6 GB free reported both pressure flags true and said
nothing at all. The pool now decides the wording and which figures are compared,
not whether the branch exists. freeGpuFit was measured on gpuBytes even on one
pool, so a partly offloaded load looked comfortable against memory that has to
hold all of it; it now mirrors what usableHostFit already did.

Host RAM read as zero on every box with an integrated GPU. use-gpu-info zeroes
systemRamAvailableGb host-wide when any device reports shared_memory, which is
correct for the roughly thirteen call sites that add that field to a GPU budget
and wrong for this one, which asks how much RAM is free. It stayed zero even
under a discrete pin, where the pool genuinely is separate, so the host-pressure
advisory could never fire there. Added systemRamAvailableHostGb rather than
changing the field with existing consumers. systemRamTotalGb was never zeroed, so
the row had been mixing an honest total with a destroyed available.

Free VRAM could count one pool twice. Not on the plain dGPU plus iGPU pairing,
which is consistent with the total it is weighed against; that reproduction is
disproved and pinned as such. It needs two shared devices, which ggml-vulkan
produces on any box with two ICDs installed since it enumerates one device per
ICD and the probe does not dedup, or an iGPU reporting a zero total, where the
no-total fallback subtracts no reserve at all: a 16 GB card plus such a device
reported 94.52 GB of VRAM. Both flip a fit verdict.

classifyMemoryFit(NaN, ...) returned "fits". NaN <= 0 is false and every ratio
comparison is false, so control fell through to the confident green answer.
Reachable without malice, since JSON.parse("1e999") is Infinity and the ?? 0
defaults never see it.

response.json() could reject. An HTML 200 or a truncated body threw inside the
panel's effect instead of hiding the row. Verified against 400 through 503, an
HTML 200, a truncated body, and a 200 whose body is null, a number, a string or
an array: all hide, none reject. toMemoryEstimate now guards types as well as
absence, since Boolean("false") is true.

Added a route memo, narrowly. A new bundle on an old backend POSTs to an absent
route after every settings change for the life of the tab. It latches only on
404, 405 and 501, with a five-minute TTL so it self-heals without coupling to any
restart signal, and a 500 clears it rather than setting it, because a backend
answering at all is not one missing the route.

The djb2 token identity is a 32-bit hash and a collision is constructible; two
well-formed HF tokens that collide are in the test. It keys the row only, never a
request, so it can leave a stale byte count on a row labelled Beta and can never
send the wrong token anywhere. Documented rather than widened.

Tests: 86 new, 5320 pass, typecheck, build and bundle budget clean. The PR's own
capacity and context suites pass unmodified. A new Playwright scene on the picker
shard drives the row under chromium, firefox and webkit, all passing; it asserts
the API exchange and not only the pixels, because the row hides itself rather
than erroring and a screenshot alone proves nothing.

Not done, and worth its own PR: the row is about thirty English literals with no
i18n plumbing in this file at all. i18n:check:strict cannot see it, because it
compares the twelve catalogs against each other and never reads a .tsx, so a
string that never enters en.ts is structurally invisible to it.
@danielhanchen

Copy link
Copy Markdown
Member

Went through this end to end: merged main, measured the estimator against a real llama-server rather than against itself, ran a platform and browser matrix, and pushed fixes for what came out of it. Three commits on top of de199a8e4.

Before and after

Before, the panel had no pre-load number at all. The only sizing a user could see was gguf-fit.ts:

return sizeGb * (1 + ACTIVATIONS_RATIO) + contextOverheadGb;   // size * 1.15 + 1.0 GB

with CONTEXT_OVERHEAD_GB described in its own comment as "a flat KV/context allowance at a typical 4K window". No context term at all. _estimate_gguf_kv_gb already computed a real figure, but only the training admission guard consumed it.

After, the row shows weights, KV cache, compute buffers, draft cache and projector, itemized, with an explicit "cannot be known" path.

The issue is real, and the merge base proves it rather than the PR body asserting it. A flat 1.0 GB context allowance is short by more than the weights on any long-context load. This is not a fabricated problem.

Will merging break anything

The one thing that genuinely worried me is that this refactors _estimate_gguf_kv_gb, which is the training admission guard's input. A regression there does not look like a wrong number in a panel; it looks like a chat load evicting a training run.

So I ran it as a differential rather than trusting the in-branch test, which compares the new wrapper against its own new tuple and is vacuous as a compatibility proof. Merge base and head imported in separate subprocesses, synthetic headers, capability probes frozen identically on both sides, values compared as float.hex():

profile cells differences
modern llama-server, every capability present 43,264 0
probe could not run 43,264 0
build without --kv-unified 43,264 7,600
build without --ctx-checkpoints 43,264 512

685,568 comparisons in total, plus 173,056 against origin/main as a drift control, which also came back at 0. All three divergences are the launch-parity gates this PR documents, all in the conservative-to-correct direction, and the --kv-unified one cannot reach the production guard at all because _guard_chat_load_against_training already clamps n_parallel to 1 on such a build before it calls the wrapper, identically on both revisions.

It adds no hardware path. Verified independently rather than taken on trust: a tripwire on _apple_metal_memory_budget_bytes across 880 probes on an Apple-unified cell, with the conftest's bare-metal pin deliberately undone, records zero calls. The uncatchable import mlx.core abort is not reachable from this route.

What the measurement found

This is the part worth your attention. I priced two real GGUFs with the estimator and then launched llama-server on the same files with the same arguments, on two backends (the CPU build and the Vulkan build on an NVIDIA card) at b10632, which is what UNSLOTH_LLAMA_TAG=latest installs today. Both backends report identical KV bytes, so what follows is a property of the arithmetic, not of my host.

Four findings, all over-reporting, all pre-existing in llama_cpp.py:

A quantized V cache was priced at f16. flash_attn = False was passed unconditionally, and that arm sets bpe_v = max(bpe_k, f16). It is the one layout where flash attention is not a choice: llama.cpp turns it on itself and says so in the log, and _tensor_quant_kv_unsupported_binary already documents the abort in the other direction. So the conservative arm was pricing a launch that cannot happen. Fixed. Qwen3-0.6B at 32k with q4_0 went from 2296 MiB reserved against 1008 MiB allocated to exact. Every plain-GQA cell now matches llama.cpp to the byte; 8 of 12 were off by 1.44x to 2.28x. f16, bf16 and f32 do not move.

This also disposes of a headline claim in the body: q4_0 does not add dequant scratch to the compute buffer. Measured, it slightly reduces it, because forcing flash attention on removes the materialised KQ tensor.

The compute buffer grows by 300 to 540 MiB per serving slot. llama.cpp's shrinks. Measured slope, Vulkan, Qwen3, 4k, f16:

slots 1 2 4 8
allocated (MiB) 76.04 68.04 64.04 62.04
priced (MiB) 15.2 1039.0

llama-server defaults to 4 slots and so does the panel, so this is the default view: gemma-3-270m reports about 1.8 GB of "Compute buffers" against 46 MiB actual. The embedding branch is wrong the same way (29.54 MiB at both 1 and 4 slots, measured). The comment justifying the term cites {1:36,2:492,4:1388,8:3220}; whatever that measured, it is not b10632 on either backend for either mode.

The SWA window is scaled by slot count. llama.cpp applies n_seq_max to it only under a unified cache. gemma-3-270m at 4k: 27.0 priced at one slot and 49.5 at four, against 12.0 allocated at both.

The context-linear compute term is about 3x low at one slot. Qwen3 at 32k: 57.2 priced, 188.0 allocated. The flat and linear halves are miscalibrated in opposite directions, which is why the one-slot total looks tolerable while both components are wrong.

I fixed the first and deliberately did not fix the other three. They live in the loader's own sizing, and lowering that reserve changes automatic context fitting and GPU selection for every existing install. My evidence covers two backends and three models but not CUDA, tensor split, MoE or Metal. They want their own change and their own CI run.

The honest framing for this PR: it does not introduce these. It inherits them by design, and the design claim, "the panel and the loader cannot disagree", holds. What changes is the cost of being wrong. Before, the over-estimate was invisible and only made the guard conservative. After, it is an itemized user-facing number, wrong by up to 90x on the default configuration, in the direction that says "does not fit".

Full evidence, raw TSVs and the scripts are reproducible from the commit; the KV column is backend-independent so it reproduces anywhere.

Six defects in the route

Reproduced first, then fixed, each with a test that fails on the parent commit.

  • The route could reach the network on a host with no cache root. _estimate_target_is_on_this_disk fails open on every error path and _cached_estimate_config then retries online, so "nothing is downloaded" held only while a root was establishable. Now a tri-state with the online retry gated on unknown rather than present, which leaves production semantics unchanged. Three of the four triggers I suspected turned out safe and are pinned as such, one of them safer than its own docstring claimed.
  • The inert probe could reap live servers. _probe_backend caught every TypeError and fell back to the process-managing constructor, which walks /proc and signals llama-servers, on a route the panel fires five to six times per settings change. Unreachable for the real class, reachable for exactly the substituted backends the fallback exists to serve. It asks the signature now.
  • A capability probe ran on the event loop. _effective_parallel_slots was called before to_thread and can shell out to llama-server --help. The codebase is its own witness: _effective_default_slots already wraps the same helper and its docstring records the stall.
  • Both TTL caches stamped the entry before the slow work, so an entry that took longer than the 30s TTL to build was inserted already expired.
  • An explicit --gpu-layers 0 on an unreadable header was priced fully GPU-resident. The earlier round fixed the Mamba/RWKV family by keeping block_count; this case has no count to keep and does not need one.
  • Request = None is not a defect and Optional[Request] = None would break registration. I was wrong about that one.

Cache eviction under 64 threads holds. Token isolation holds. No GPU is touched, with one correction: torch.cuda.is_available() and device_count() do fire via _effective_gpu_count, so "no device is touched" is a slight overstatement. There is no in-flight dedup, so 32 concurrent misses on one cold key run 32 resolutions; recorded, not fixed.

Frontend

The verdict and advisory chain was module-private inside a 3,400-line .tsx and unreachable from the node runner, which is how these survived review. Extracted to an import-free memory-fit.ts, following estimate-context.ts.

  • The single-pool advisory was unreachable. An exhaustive sweep selects it zero times. Apple unified, 30 GB load, 6 GB free: both pressure flags true, row says nothing.
  • Host RAM read as zero on every box with an iGPU, including under a discrete pin where the pool genuinely is separate.
  • Free VRAM could count one pool twice. Not on the plain dGPU plus iGPU pairing, which is consistent; that reproduction is disproved. It needs two ICDs enumerating the same device, or an iGPU reporting a zero total, where the fallback subtracts no reserve at all: a 16 GB card plus such a device reported 94.52 GB of VRAM.
  • classifyMemoryFit(NaN, ...) returned "fits". Reachable without malice, since JSON.parse("1e999") is Infinity.
  • response.json() could reject on an HTML 200 or a truncated body, throwing inside the panel's effect instead of hiding the row.
  • Added a route memo for the old-backend case, latching only on 404/405/501 with a five-minute TTL. A 500 clears it rather than setting it.

Coverage

  • Platforms: 21 cells over [Linux, WSL2, Windows, macOS] x [NVIDIA single, NVIDIA multi, AMD ROCm, AMD Vulkan, Apple unified, CPU only], 10 model shapes, 3,928 priced responses. Zero invariant violations, and the assertions were mutation-tested rather than trusted for passing first try. Worth knowing: the matrix collapses to three behaviours, one device, two devices, none. sys.platform moves nothing.
  • Browsers: a new Playwright scene on the picker shard, passing under chromium, firefox and webkit. It asserts the API exchange and not only the pixels, because the row hides itself rather than erroring and a screenshot alone proves nothing. Real Safari and real Edge were not run; this is a Linux box.
  • Compatibility: old backend and new bundle verified across 400 through 503 plus malformed bodies; new backend and old bundle keeps both documented fallbacks. pyproject.toml says >=3.9 but routes/inference.py carries 13 runtime-evaluated PEP 604 annotations and cannot import on 3.9 on the merge base too, and CI enforces a 3.10 floor. Pre-existing metadata bug, not this PR, worth its own issue.
  • Backend suite: 33,067 collected, and every one of the 149 local failures is a missing optional dependency here (av, fastmcp, pymupdf, a diffusers pin). None in the estimator. Frontend: 5,320 pass, 86 new.

Two notes on the body

The itemization is five terms, not four: projector_runtime_bytes is its own row and is inside the total. The arithmetic is right, the sentence is stale, and there is now a test asserting both directions so they cannot drift apart again.

The red check before my push was tests/studio/test_pip_cache_naming.py, which arrived with #9781 and fails main's own encoding gate. Fixed here because it was what kept this PR red, but it is main's bug.

What I would still want before merge

The compute-buffer term. A 270M model reporting 1.8 GB on the default configuration is the kind of number that makes a user distrust the whole row, and it is the row's own headline claim that it is not a rule of thumb. Either that term gets corrected in its own PR first, or this row should not present it as an exact figure while it stands.

Longer term, llama.cpp now ships llama-fit-params and llama_memory_breakdown_print, which measure the real graph with no_alloc = true: exact, no weights loaded, and it cannot drift from upstream the way hand-maintained arithmetic just did.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

pre-commit-ci Bot and others added 2 commits August 26, 2026 11:03
All four from this round were correct. Checked each against the code at head and
against llama.cpp's own source before changing anything.

A pinned card was charged for a CPU-only launch. When Manual resolves the layer
count to zero, load_model drops the split flags outright, and
_manual_keeps_tensor_split already knows that. But the route still handed the
pinned IDs to _guard_device_count, whose layer-mode branch returns their full
count, so _gguf_runtime_bytes added per-device pipeline overhead and replicated
the context-linear compute term for buffers no card allocates. Measured on a
two-card pin: 1039 to 2105 MiB at 4k, 1417 to 5129 MiB at 262k, all of it
attributed to a load running entirely on the CPU. The pin is now resolved through
the same placement function the panel prices with, so the two cannot disagree
about whether anything lands on a GPU at all.

An inherited LLAMA_ARG_N_GPU_LAYERS was ignored in Auto. This is the sharpest of
the four. The fitting path emits no -ngl, so an inherited count is the ONLY layer
policy the child sees, and llama.cpp will not overrule it: common/fit.cpp:463
throws "n_gpu_layers already set by user" on any value the user really set and
the caller downgrades that to a warning, so the launch proceeds with the count as
given. Verified against the b10632 source rather than from memory. With
LLAMA_ARG_N_GPU_LAYERS=0 the weights run from host RAM while the panel assigned
every one of them to VRAM. The loader has consulted _env_fixes_gpu_layers for
this since its placement gate; the panel did not. -1 and auto stay full offload,
because those are llama.cpp's own default and leave the fitter free, and an
extras -ngl still wins over both, since argv is parsed after the environment.

Pass-through adapters were missing from the footprint. llama.cpp loads every
--lora, --lora-scaled, --control-vector and --control-vector-scaled into resident
tensors on top of the base model, on the base tensor's own buffer type, and
neither path mmaps. The files term prices the target and its companions only, so
a multi-gigabyte adapter load was shown as a fit on the base model's size alone.
Charged now, and scaled by the layer fraction rather than treated as a companion,
because that is the placement llama-adapter.cpp gives them. A named file that
cannot be stat'd is the engaged-but-unsized case: the loader abstains from the
whole figure there, which for a panel would hide the row, so it carries a floor
marker instead, in a new adapters_unsized field that an older bundle ignores.

The VRAM budget was applied to a launch it does not constrain. A fixed Manual
placement is launched verbatim: load_model empties its probed GPU set and emits
--gpu-layers N --fit off, so the server-wide budget never reaches the planner. A
16 GiB fixed placement on a 24 GiB card read as exceeding under a 50% budget. Auto
stays budgeted, because Auto is exactly the mode that hands the decision to the
planner. The free-VRAM reserve keeps its floor either way: what is free right now
still constrains the launch, whatever set the number.

Tests: the three that are wiring rather than helper behaviour are driven through
the route or the breakdown and fail on the parent commit; asserting the helpers
in isolation passed on the unfixed tree, which is the mistake this catches.
Backend 1100 pass across the estimator and its nine adjacent suites, frontend
5321 with typecheck clean.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

Correct, and the reasoning already in the tree was only looking at half the
effect. GpuInfo.sharedMemory was devices.some(shared_memory), so one Vulkan iGPU
in the inventory marked the whole host single-pool. The existing test asserted
that and justified it as the safe direction: under-counting the discrete card
refuses a load rather than admitting one.

But the flag does not only shrink the ceiling. On a single pool the row shows one
Shared figure carrying total_bytes and the GPU verdict is never rendered at all
(model-config-page.tsx, the label/value/tone triple), so on a dGPU + iGPU box the
only check that would catch a fixed Manual placement larger than the discrete
card was gone. That is the admitting direction, not the refusing one.

sharedMemory is every() now, length-guarded because every() on an empty list is
true and a host with nothing probed has no pool to be single. Deliberately NOT
the same rule as the systemRamAvailableGb zeroing two lines above it: that one is
about a SUM, where one shared device is enough to count the same bytes twice, and
it keeps some(). The same correction applies per pin in gpu-vram.ts, where a pin
naming both cards is still two pools.

Flipping the flag alone would have traded one wrong answer for another, because
the mixed branch then reaches gpuCapacityGb + systemRamTotalGb and the iGPU's
budget is already inside that RAM. So the ceiling takes a new dedicated-only
aggregate: 16 GB card + 12 GB iGPU allowance + 96 GB RAM is 112, not 124 and not
96. On any host with no shared device the two aggregates are equal, so every
discrete-only machine keeps exactly the ceiling it had, which is what the third
new test pins.

Tests: 5324 pass. Three new cases cover the mixed inventory, the three pin shapes
and the discrete-only regression guard. The existing case that asserted the old
behaviour is updated rather than deleted, with the reasoning that was wrong
recorded next to it.
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

@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: 7754814b51

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

tensor_parallel = _effective_tensor_parallel(
request.llama_extra_args, bool(request.tensor_parallel)
)
and _tensor_split_possible(request.selected_gpu_ids or None)

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 Filter unusable GPUs before pricing tensor mode

When tensor parallelism is requested on a host where fewer than two GPUs have enough usable VRAM for the replicated compute buffer, this predicate treats every enumerated or pinned device as usable and prices a tensor split. The actual loader first filters devices by _gpu_usable(g) >= reserve_mib and, when fewer than two remain, disables tensor parallelism and falls back to a layer split (llama_cpp.py:17484-17530). Since tensor and layer modes use different flat-buffer replication and cache planning, a busy or heterogeneous multi-GPU host can receive a materially different footprint and fit verdict from the process that launches; apply the loader's reserve filter using the cached per-device free/total readings before selecting this arm.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Not taking this one. The predicate you are asking for is free-VRAM state, which this route deliberately does not model: _guard_device_count says so in its own docstring, and the free-VRAM map only exists downstream in can_load_chat_during_training. Pricing it here would make the panel flap with whatever else is momentarily resident and predict a layer split for a load that will fit, since Studio unloads the resident model before launching. Free VRAM already reaches the panel on a separate track that warns and never refuses.

Two values the Estimated Memory Usage row resolved differently from the
launch, both in the ordinary case rather than an edge one.

normalizeGpuFields only ever persists "manual", so a model with no
per-model override means "follow the standing preference" -- which is
exactly what applyPerModelConfigToRuntime resolves it to on the load
path. The panel sent the absence as null, the backend read null as Auto,
and a Manual launch was priced against the wrong plan. Resolved through
the same readPersistedGpuMemoryMode fallback the speculative type two
lines above already uses, and applied at all three sites that read the
mode: the request, the fixed-layer context substitution, and whether the
VRAM budget governs the launch.

The budget fraction started at 1. loadVramBudgetSettings is async and
returns null on failure -- an older backend has no such route -- and in
both windows the launcher still applies VRAM_FRACTION_DEFAULT, so a full
card is a figure no setting of that slider produces. Seeded with the
loader's own 0.97 instead, pinned to the backend constant by test.

Also fixes this PR's own Playwright scene, which reported the row
missing for twenty seconds while the screenshot it took shows the row
painted with the stubbed figures. The run-settings panel is mounted more
than once in the document, so `.first` was a coin toss and the copy it
landed on is not the one on screen. Takes the first visible match, names
the strategy that found it, and warns if only the structural locator
does -- a toggle no screen reader can announce is worth hearing about
rather than silently passing.
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

@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: 100ea9c84c

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

llama_extra_args,
default = managed_kv_unified,
)
_resolved_checkpoints = resolve_ctx_checkpoints(llama_extra_args, ctx_checkpoints)

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 Price the default context checkpoints

When ctx_checkpoints is omitted—the normal UI default—resolve_ctx_checkpoints(..., None) resolves to 0, so the estimate excludes all checkpoint memory. The load contract documents an omitted value as llama.cpp's default of 32 checkpoints (models/inference.py:214-224), and the command builder leaves the flag absent in that case (llama_cpp.py:19293-19300), allowing that default to apply. For sliding-window models, _estimate_kv_cache_bytes multiplies this checkpoint term per slot, so the displayed total can be several GiB low and produce a false fit verdict; resolve the actual default for this route or mark the result as excluding checkpoint growth.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

The premise is right and the impact is not, so I am leaving this. The default really is 32 (common.h: n_ctx_checkpoints = 32) and the builder omits the flag, but that number is a ceiling, not an allocation: create_checkpoint emplaces lazily during prompt processing and trims while size() >= n_ctx_checkpoints, and the bytes are std::vector<uint8_t> in common_prompt_checkpoint, i.e. host RAM. A fresh load allocates none of it, so pricing 32 into a load estimate would over-report by GiB rather than close a gap. It also would not stay in the panel: _gguf_runtime_bytes is the training admission guard's input, so this would start refusing chat loads during training that work today, over memory the process has not allocated and will not allocate on the card. The real oddity here is that an explicitly requested count IS charged, and charged as GPU-side KV; that is merge-base behaviour in the guard and belongs in its own change, not in a panel PR.

--spec-draft-ngl 0 and --spec-draft-device cpu carry
params.speculative.n_gpu_layers and .devices, which llama.cpp copies into
the model params only inside common_base_params_to_speculative's
has_draft branch. With no draft model to load it builds the draft context
with llama_init_from_model(model_tgt), so an embedded head keeps whatever
placement the target has and neither flag can move it.

The panel moved the head's draft cache out of gpu_bytes anyway, which on
a GPU-resident NextN model at a long context drops gigabytes off the GPU
figure for bytes that are allocated on the card -- the direction that
turns an overflow into a fit. _extra_args_draft_offloaded_to_cpu says an
embedded head follows the main -ngl in its own docstring, and the launch
budget enforces it through _draft_cpu_no_embedded, so the branch was
contradicting the helper it called.

The test that asserted the old placement now asserts the pinned and
unpinned figures are identical, and fails on the parent.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

Three placements the panel read differently from the load.

Flash attention. load_model appends --flash-attn on to every launch whose
build has the flag, so the default is on; the estimate inferred it solely
from whether V was quantized and passed False for every f16 cache. The
false arm pads variable-width V tensors to the model-wide maximum, so an
architecture whose global and SWA layers disagree about n_embd_v_gqa got
an inflated cache and could be shown as exceeding a card it fits on.
Resolved the way the launch resolves it: the managed default, narrowed by
the same capability probe the builder asks, then llama.cpp's
env-then-last-wins-argv rule, with a quantized V forcing it on top.

Partial offload. A cache buffer defaults to ggml_backend_cpu_buffer_type()
and is only overridden with model.dev_layer(il) when offload is set, so
offload_kqv decides whether per-layer placement is consulted at all, not
that every layer lands on a card. A layer left on the CPU keeps its cache
in host RAM. The GPU share now scales by the same layer fraction the
weights already used; at a long context the cache is the larger term, so
a 6-of-33 Manual placement read as an overflow.

Embedded NextN head. The other half of the previous commit: with no
drafter file host_drafter_bytes is 0, so the head was GPU-resident even
for a target placed on the CPU. It follows the target's fraction now.

Each of the three tests that encoded the old behaviour fails on the
parent, including the one whose comment asserted llama.cpp keeps the
whole cache on the GPU under a partial offload.
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🎉

Reviewed commit: 9acbcc652f

ℹ️ 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 matrix pads twelve synthetic GGUFs to GB scale with truncate(), which
on POSIX punches a hole and costs nothing. NTFS does not: unless the file
is marked sparse BEFORE it is extended, Windows commits and zero-fills
every byte, so the twelve came to 34 GB and every cell in the file errored
with ENOSPC on the staging Windows runner while all 213 passed on Linux.

Asks for FSCTL_SET_SPARSE first, which is a no-op anywhere else, and falls
back to a twelfth of each pad where the flag cannot be set. That keeps the
shapes GB-scale, which is the whole reason for the padding, without the
34 GB. FORCE_DENSE_PAD exercises the fallback from a POSIX box, since it
is the arm only Windows takes and would otherwise never be run: 213 pass
either way.

Also applies the formatting pre-commit.ci has been unable to push for
three rounds, so its autofix has nothing left to conflict over.
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: d3a946e044

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

@danielhanchen

Copy link
Copy Markdown
Member

Before / after: what this row actually shows

Two isolated Studio installs, built from this PR's merge base (2640fad25) and its head (d3a946e04). Same machine, same seeded Hugging Face cache holding one model, unsloth/gemma-3-270m-it-GGUF UD-Q4_K_XL (254 MB). Same panel, opened the same way: chat model picker, On Device, the gear on that row.

Estimated Memory Usage row, before and after

Before, the Load Model panel opens straight onto Context Length. There is no memory figure on it anywhere, and POST /api/inference/estimate-memory does not exist.

After, the row sits above Context Length reading GPU 2.14 GB / Total 2.14 GB, and expands into the itemisation:

term figure
Weights 0.24 GB
KV cache (f16, 32,768 tokens, 4 slots) 0.13 GB
Compute buffers 1.78 GB
Total 2.14 GB

The numbers beside the picture come from the same server that was photographed, not from a stub: POST /api/inference/estimate-memory answers available: true, total_bytes: 2302485126 (= 2.14 GiB) at n_ctx: 32768, layer_count: 18. That matches the figure on screen to the byte.

Two details from the run worth recording, because both are load-bearing elsewhere in the diff:

  • The old backend answers 405, not 404. A sibling router owns that path for another method and replies first. routeAbsentStatus in memory-estimate.ts already treats 405 the same as 404 for exactly this reason, so the row hides cleanly on a backend predating the route rather than surfacing an error. This run is what that branch is for.
  • The probe has to ask for n_ctx: 0, not a literal window. The control reads Auto, resolveEstimateContext sends 0, and the backend resolves it to the model's native 32,768. An earlier probe at an explicit 8192 put 2.04 GB next to a panel showing 2.14 GB -- same code, different question.

Compute buffers dominating a 270M model is expected at this size and context: the KQ mask and the output buffer are context- and slot-scaled while the weights are not, which is the asymmetry the old flat size x 1.15 + 1.0 heuristic could not represent at any context.

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants