Repository navigation
Add Estimated Memory Usage to the Load Model panel - #9525
Conversation
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.
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).
|
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: Parallel slots. Correct. Companion placement. Correct. Measured on a vision model with an MTP sidecar: One refinement on the suggestion. A CPU-pinned drafter is already dropped from the total upstream by 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. 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. |
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.
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.
|
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 Drafter runtime (P1). Right. Measured on the MTP sidecar in 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 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. Layer-split device count (P2). Right. Token changes (P2). Right. The key collapsed every non-empty token to the literal 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: |
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.
|
@codex review |
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.
|
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 Custom drafter path. Correct. Draft cache dtype. Correct. Layer count on an unsizable header. Correct, and the consequence is worse than losing a field. 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: Tests are 71, up from 61. One existing test asserted |
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.
|
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 Draft depth when the extras own the spec block (P2, correct). Drafter placement at zero GPU layers (P2, correct, fixed differently). A separate drafter does not inherit 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: Tests: 77 in |
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.
/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.
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.
…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.
|
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 Before and afterBefore, the panel had no pre-load number at all. The only sizing a user could see was return sizeGb * (1 + ACTIVATIONS_RATIO) + contextOverheadGb; // size * 1.15 + 1.0 GBwith 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 anythingThe one thing that genuinely worried me is that this refactors 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
685,568 comparisons in total, plus 173,056 against It adds no hardware path. Verified independently rather than taken on trust: a tripwire on What the measurement foundThis 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 Four findings, all over-reporting, all pre-existing in A quantized V cache was priced at f16. 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:
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 The SWA window is scaled by slot count. llama.cpp applies 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 routeReproduced first, then fixed, each with a test that fails on the parent commit.
Cache eviction under 64 threads holds. Token isolation holds. No GPU is touched, with one correction: FrontendThe verdict and advisory chain was module-private inside a 3,400-line
Coverage
Two notes on the bodyThe itemization is five terms, not four: The red check before my push was What I would still want before mergeThe 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 |
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.
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.
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 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) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 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) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
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.
|
Codex Review: Didn't find any major issues. 🎉 Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
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.
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. Nice work! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
Before / after: what this row actually showsTwo isolated Studio installs, built from this PR's merge base ( Before, the Load Model panel opens straight onto Context Length. There is no memory figure on it anywhere, and After, the row sits above Context Length reading
The numbers beside the picture come from the same server that was photographed, not from a stub: Two details from the run worth recording, because both are load-bearing elsewhere in the diff:
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 |

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 GBstyle heuristics ingguf-fit.tsandrecommended-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 onunsloth/Qwen3.8-27B-GGUF(UD-IQ3_XXS):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_byteswith its MLA / hybrid-Mamba / SWA / GQA / legacy paths, plus_estimate_compute_buffer_bytesand_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:
kv_estimablecomes 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 answersnot_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_gbis 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_identifierleavesgguf_fileunset for anything it resolved as a repository, even once the weights are sitting in the HF cache._estimate_gguf_required_gbbranches on that field, so a cached repo was priced through apaths-infocall: a network round trip behind a slider, and no estimate at all offline._localized_estimate_configpoints the config at the file on disk and runs the same companion detection the local-folder branch runs. It now works underHF_HUB_OFFLINE=1and picks up a 0.4 GB drafter the listing had been missing.Warm requests are about 73 ms, almost all of it the GGUF header walk.
Frontend
useMemoryEstimatedebounces 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
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.test_server_tuning_flags.py. It source-inspected_estimate_gguf_kv_gbfor 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.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.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.corein_apple_metal_memory_budget_bytes(llama_cpp.py) aborts the whole process on macOS when torch was imported first, and the surroundingtry/exceptcannot catch a C-level abort. Reproduces with this branch stashed, so it wants its own fix.