Skip to content

Studio: stop dropping quantized KV cache on tensor split - #8939

Merged
danielhanchen merged 12 commits into
unslothai:mainfrom
kissa01:studio-tensor-split-quantized-kv
Aug 25, 2026
Merged

danielhanchen merged 12 commits into
unslothai:mainfrom
kissa01:studio-tensor-split-quantized-kv

Conversation

@kissa01

@kissa01 kissa01 commented Aug 15, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #8888

The bug

load_model only allows f16, bf16 and f32 when tensor parallelism is on:

_TENSOR_PARALLEL_KV_TYPES = frozenset({"f16", "bf16", "f32"})

Anything else is removed from argv, popped from the child as LLAMA_ARG_CACHE_TYPE_K/_V, and budgeted as f16 instead. Only the log records it, so someone who asks for q8_0 with --split-mode tensor gets an f16 KV cache, about twice the size they planned for.

That limit is out of date: llama.cpp dropped its "TP rejects a quantized KV cache" check in ggml-org/llama.cpp#23792 and added support for it, shipped since b9455.

What changed

  • Quantized cache types now reach a tensor launch unchanged — argv, env, and budget all agree. This removes _TENSOR_PARALLEL_KV_TYPES, the drop/restore machinery around it, and the f16 budgeting fallbacks (_estimate_gguf_kv_gb, _env_main_cache_type_for_budget), so the fit prices the cache the child actually runs (Inkling's dense compute rate included).
  • /status shows the real cache type on a tensor load, and a repeat /load matches instead of reloading.
  • The deferred projector pin verdict was only withheld because it was priced against a forced f16; the probe now prices the real cache, so the carve-out is gone.

The tensor fit now prices the quantized dequant scratch, so auto-context can come out lower than the old f16 path advertised. On a build older than #23792 the tensor attempt fails instead of being downgraded, and load_with_tensor_fallback falls back to layer split with the quantized cache kept.

Tests

The placement tests run the real load_model path with Popen patched and verify that:

  • q8_0 and q4_0 reach a tensor launch unchanged.
  • Unknown managed cache types remain rejected.
  • Inherited quantized K/V environment settings reach the child and the tensor placement budget.
  • Each tensor-to-layer downgrade removes both --split-mode and --tensor-split while preserving unrelated user arguments.
  • The tensor-to-layer downgrade still gives the projector up, now covering both an unset and a q8_0 cache. The test for the old carve-out is removed.

Existing tests that asserted the old tensor-only gate are updated accordingly.

@kissa01
kissa01 marked this pull request as ready for review August 15, 2026 19:56
@kissa01
kissa01 requested a review from danielhanchen as a code owner August 15, 2026 19:56
Copilot AI lite review requested due to automatic review settings August 15, 2026 19:56

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@kissa01
kissa01 requested a balanced review from Copilot August 15, 2026 19:57

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@kissa01
kissa01 force-pushed the studio-tensor-split-quantized-kv branch from 0ed759b to 9de8ad9 Compare August 18, 2026 22:42
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 19, 2026
@danielhanchen

Copy link
Copy Markdown
Member

Confirmed main still drops a requested quantized cache type in the tensor branch of load_model and pops the inherited LLAMA_ARG_CACHE_TYPE_K and _V, so q8_0 silently runs as f16 under --split-mode tensor. Will get this reviewed.

@kissa01
kissa01 force-pushed the studio-tensor-split-quantized-kv branch from 9de8ad9 to 233cdda Compare August 19, 2026 22:08
@danielhanchen

Copy link
Copy Markdown
Member

Re-checked at the current head: the gate is gone from all four sites including the inherited LLAMA_ARG_CACHE_TYPE_K/_V pop and the f16 budget in routes/inference.py, and the split-mode strip is kept at each tensor to layer downgrade.

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 15d77aaf71

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

@kissa01
kissa01 force-pushed the studio-tensor-split-quantized-kv branch from 15d77aa to d8749df Compare August 22, 2026 12:29
chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@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: abc5bd7e14

ℹ️ 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 and others added 2 commits August 24, 2026 21:58
Follow-ups to the gate removal, from reviewing what became reachable once a
quantized KV cache started surviving a tensor split.

Every estimator resolves ONE cache type: the heavier axis, for KV bytes. That
same scalar also selected the compute-buffer rate, and _compute_buffer_ctx_bytes
charges the per-device dequant scratch only when its type is under f16 -- so an
asymmetric -ctk q4_0 -ctv f16 priced the scratch as if nothing were quantized.
The tensor gate used to make this unreachable by rewriting both axes, which is
what the comment removed from _plan_tensor_parallel said. Split the two: heavier
axis for bytes, lighter axis (_planned_scratch_cache_type) for scratch. Measured
end to end through load_model on an 80L/n_embd 8192 model, 4x48GB, n_ubatch 2048:
the emitted -c was 262144 and is now 175104. Tensor mode has no --fit valve, so
that surplus was a startup OOM rather than a spill. The layer path took the same
scalar and gets the same fix.

An older llama.cpp refuses the pair outright, in llama_init_from_model:
"simultaneous use of SPLIT_MODE_TENSOR and KV cache quantization not
implemented". That is LLAMA_LOG_ERROR + return nullptr, so it is a clean exit 1
and _should_record_tensor_split_abort cannot see it -- every load spent two full
model-load cycles (the tensor attempt plus the --fit retry) before the route's
layer fallback, forever, and reported "Check that the GGUF file is valid and you
have enough memory". Classify the marker, skip the fit retry on it as the
split-axis abort already does, and latch it. One doomed attempt on the first
load, then none, and a message naming b9455.

The abort latch was keyed on (binary, mtime, model). Now that the cache type
reaches the tensor child, an abort can be specific to it: iq4_nl asserts under a
tensor split on b10441 while q4_0 runs on the same binary and model
(ggml-org/llama.cpp#27116), and a pre-b9455 binary refuses every quantized type
while f16 is fine. Key it on the planned (K, V) pair too, so one type's failure
does not take tensor mode away from the types that work.

Two smaller ones on the same seam. A cache type kv_cache_type_from_str does not
know is never emitted, so the child inherits LLAMA_ARG_CACHE_TYPE_K/_V instead --
but the budget priced the unemittable string at _kv_bytes_per_elem's 2.0 unknown
default, a 2x under-reservation against an inherited f32. And an inherited type
that llama.cpp cannot parse (q3_K, a typo, or a case-mismatched Q8_0) now reaches
the child, aborting it at argument parsing; the layer retry inherits the same env
and fails too, leaving no server. The managed path has been allow-listed and
lowercased at emission for a long time; give the env path the same two.

Tests: a new OS x accelerator x cache-type matrix over
[linux, wsl2, windows, macos] x [nvidia multi/single, amd rocm, amd vulkan,
apple unified, cpu-only] x [f16, q8_0, q4_0, q5_1, iq4_nl], asserting both axes
per cell, that the >= 2-device cells keep tensor mode and the rest drop the whole
split-mode group, and that no tensor launch pairs --flash-attn off (still a hard
error upstream). Plus the end-to-end legacy-build cost, the scratch-axis
selection, the two budget guards, and the assertion the deleted restore-path test
used to carry: a downgrade must not rewrite an asymmetric pair.

Checked against current llama.cpp master rather than its docs: the guard #23792
deleted is gone from src/llama-context.cpp, while docs/multi-gpu.md still lists
the restriction -- it was last touched 2026-05-07, three weeks before #23792
merged.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

…ective cache

Three review findings from the round on the previous commit.

The pre-b9455 refusal was recorded in the model-and-cache-pair-keyed tensor-abort
set, but llama_init_from_model refuses every quantized type for every model on
such a binary. Loading a second model, or switching q8_0 to q4_0, therefore paid
another doomed full model load. It now records into its own
_tensor_quant_kv_unsupported_binaries set keyed on (binary, mtime) and is
consulted at the up-front gate, before the spawn. A non-quantized pair is
unaffected, since f16 still gets a tensor split on such a build, and the mtime
means an updated binary is re-probed. The split-axis abort keeps the finer key:
that one really is specific to a model and a cache type (iq4_nl asserts on b10441
while q4_0 runs, ggml-org/llama.cpp#27116).

_runtime_matches_intent compared self._cache_type_kv against intent.cache_type_kv.
That scalar holds only what Studio emitted as a managed flag, so a cache set
through extras or the environment left None on one side and a type on the other,
and an identical repeat /load tore down a healthy server to relaunch the same
thing. It now compares _effective_cache_types, the per-axis pair the running
child was actually launched with, against _planned_main_cache_types for the
incoming request. A layer load has always had this; the tensor gate used to hide
it by rewriting the cache away.

The inherited-cache-type normalisation compared against an already-stripped copy,
so " q8_0 " matched itself and nothing was written back. Compared against the
original value now. common_arg::get_value_from_env hands the raw getenv string
through and kv_cache_type_from_str compares it to ggml_type_name(t) exactly, so
surrounding whitespace aborts the child exactly as a typo does.

Not taken: the report that removing the cache scrub sends a quantized V cache to
a launch with --flash-attn off. The emitted argv is identical to main on the
layer path (the extras win last there too), and on the tensor path llama.cpp
rejects the load on "SPLIT_MODE_TENSOR requires flash_attn to be enabled", which
llama_init_from_model checks before any KV type, so the V type does not decide
the outcome.

_ALLOWED_TP_DROP_GUARDS gains the new binary-wide gate, which is what that
tripwire is for.
@unslothai unslothai deleted a comment from kissa01 Aug 24, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 24, 2026
@unslothai unslothai deleted a comment from kissa01 Aug 24, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 24, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 24, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 24, 2026
@unslothai unslothai deleted a comment from kissa01 Aug 24, 2026
@unslothai unslothai deleted a comment from kissa01 Aug 24, 2026
@unslothai unslothai deleted a comment from kissa01 Aug 24, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 24, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 24, 2026
@unslothai unslothai deleted a comment from kissa01 Aug 24, 2026
@unslothai unslothai deleted a comment from kissa01 Aug 24, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

danielhanchen and others added 2 commits August 24, 2026 23:41
…-GPU

Three more from the round on the last commit.

_env_main_cache_type_for_budget collected only the axes that were SET, so a
single quantized axis carried the whole scalar: LLAMA_ARG_CACHE_TYPE_V=q4_0 with
K unset returned q4_0, and the caller then priced K as q4 while the child ran it
at f16. An unset axis is not absent, it is llama.cpp's f16 default, so it now
takes part in the max. Measured on a key_length 192 / value_length 128 model at
131072: the reserve was 14.22 GiB against the 25.00 GiB the f16 K axis really
needs, so the cheap type had landed on the larger tensor. The existing assertion
that a lone q4_0 adopts q4_0 is updated; it pinned the under-reserving answer.

The reload matcher compared the pair the child was LAUNCHED with against the pair
the request resolves to. A launch-time rewrite makes those differ on purpose (a
build with no --flash-attn resets a quantized V cache to f16 before the spawn,
and the flash-attn crash recovery does the same), so every identical repeat load
was rejected and redid that normalization instead of reusing it. It now records
_requested_cache_types beside _effective_cache_types and compares requested
against requested, which is the rule the tuning group above it already uses.

The binary-capability skip added last commit downgraded to layer without raising
_layer_min_gpus, so the auto layer planner started at one GPU and stopped there as
soon as the model fit, quietly collapsing a multi-GPU request onto one card. The
adjacent split-axis skip raises it for the same reason: neither failure says
anything about capacity.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Aug 24, 2026
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Aug 24, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Already looking forward to the next diff.

Reviewed commit: e5c0e349af

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

Comments only, no code change. Collapses the longer rationale blocks in
llama_cpp.py and the two test headers to the same content in fewer lines.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 25, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 25, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 25, 2026
@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: 9d6dfeb004

ℹ️ About Codex in GitHub

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

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

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

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

Comment on lines +15974 to +15976
_planned_cache_pair = _planned_main_cache_types(
None if _cache_type_from_env else cache_type_kv,
extra_args,

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 Compute the cache pair from the unmodified request

When extras override only one cache axis, such as --cache-type-k q4_0, the earlier budget calculation replaces cache_type_kv with q4_0, so this records the request as (q4_0, q4_0). A repeat of the identical load is compared in _runtime_matches_intent using the original managed value (None) plus the extras, which resolves to (q4_0, f16); the mismatch unnecessarily tears down and reloads the healthy server every time. Preserve the pre-budget managed value when computing _planned_cache_pair.

Useful? React with 👍 / 👎.

@danielhanchen
danielhanchen merged commit 14c9b73 into unslothai:main Aug 25, 2026
1 check passed
rhsCZ pushed a commit to rhsCZ/unsloth that referenced this pull request Aug 25, 2026
…tton sends

Two findings from the last review round, both open at the previous head.

Manual tensor downgrade. load_model drops the tensor split twice in Manual mode
before it budgets anything, and neither drop is about how many cards are present:
gpu_layers=0 leaves nothing on the GPU to split, and Auto layers hand sizing to
llama.cpp --fit, which is incompatible with tensor mode. The estimator's condition
only asked whether more than one device existed, so both shapes were priced with
per-device compute buffers for a launch that runs a layer split. _manual_keeps_
tensor_split applies the loader's own rule, at the breakdown and at the device
count, after a -ngl in the extras has last-wins into the count exactly as /load
resolves it before its own drop.

Auto context. The Context Length control needs a number to display before a new
GGUF's header has been read and falls back to 32,768. The Load button does not:
resolveLoadMaxSeqLength sends 0 for an unset length and llama.cpp opens at the
model's native context. The panel was pricing the display fallback, so a model with
a much larger native context was quoted an explicit 32k and understated by the term
that grows fastest with context. resolveEstimateContext sends the load path's
value; 0 is already the request's 'price the native context'.

Also updates test_one_card_is_priced_as_the_layer_load_it_launches, which asserted
that a tensor split rewrites the cache to f16. unslothai#8939 removed that gate, so a
quantized KV now survives one; asserted equal rather than dropped, so a
reintroduced gate still fails. The compute-buffer half of the test is unchanged and
is what the downgrade was always about.

Backend 141 passing, frontend 4916, typecheck and i18n parity clean.
danielhanchen added a commit that referenced this pull request Aug 26, 2026
* Add Estimated Memory Usage to the Load Model panel

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.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Fix four issues in the memory estimate found in review

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).

* Apply ruff formatting to the review fixes

* Read the checked-in types.ts with an explicit utf-8 encoding

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.

* Fix six more issues in the memory estimate found in review

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.

* Find companions at the snapshot root, and price a blank draft depth

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.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Fix a crash and three drafter gaps in the memory estimate

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.

* Price speculation by its engaged mode and by where each piece sits

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.

* Resolve split mode and layer offload from the extras, as the launch does

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.

* Take the layer count, context and expert placement from the extras too

/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.

* Ask the pinned cards whether the GPU pool is system RAM

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.

* Price the tensor downgrade, the drafter's real cache layout, and the 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.

* Read the child's inherited environment where the launch does

An extras-owned spec block keeps LLAMA_ARG_SPEC_*, so the drafter, its
depth and its type come from there; an inherited LLAMA_ARG_MMPROJ loads
whatever the argv says; and on a Vulkan build the device pool comes from
the probed inventory, not from a CUDA count that sees nothing.

* Normalize manual extras, and say when a drafter's cache cannot be sized

Manual strips the offload flags at launch, so a stale -ncmoe must not
decide the pipeline question here. A --spec-draft-hf drafter has no local
header to read, so the row reports the total as a floor instead of a
confident figure missing a context-scaled cache.

* Apply the Manual tensor downgrades, and price the context the Load button sends

Two findings from the last review round, both open at the previous head.

Manual tensor downgrade. load_model drops the tensor split twice in Manual mode
before it budgets anything, and neither drop is about how many cards are present:
gpu_layers=0 leaves nothing on the GPU to split, and Auto layers hand sizing to
llama.cpp --fit, which is incompatible with tensor mode. The estimator's condition
only asked whether more than one device existed, so both shapes were priced with
per-device compute buffers for a launch that runs a layer split. _manual_keeps_
tensor_split applies the loader's own rule, at the breakdown and at the device
count, after a -ngl in the extras has last-wins into the count exactly as /load
resolves it before its own drop.

Auto context. The Context Length control needs a number to display before a new
GGUF's header has been read and falls back to 32,768. The Load button does not:
resolveLoadMaxSeqLength sends 0 for an unset length and llama.cpp opens at the
model's native context. The panel was pricing the display fallback, so a model with
a much larger native context was quoted an explicit 32k and understated by the term
that grows fastest with context. resolveEstimateContext sends the load path's
value; 0 is already the request's 'price the native context'.

Also updates test_one_card_is_priced_as_the_layer_load_it_launches, which asserted
that a tensor split rewrites the cache to f16. #8939 removed that gate, so a
quantized KV now survives one; asserted equal rather than dropped, so a
reintroduced gate still fails. The compute-buffer half of the test is unchanged and
is what the downgrade was always about.

Backend 141 passing, frontend 4916, typecheck and i18n parity clean.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Report the draft cache's own placement, and mark a drafter-bounded total

Three review findings on what the row asserts about numbers it cannot fully see.

Draft cache placement. The line took its 'host RAM' note from kv_on_gpu, which
is the TARGET cache's placement. The two are set by different flags, so the note
was wrong in both directions: silent about a draft cache that --spec-draft-ngl 0
really did put in host RAM, and claiming host RAM for one that --no-kv-offload
left on the GPU and that the same response had charged to gpu_bytes. Reported as
drafter_runtime_gpu_bytes rather than a placement flag, because under MTP the
term is not placed as one piece: the target-side verification state follows the
target cache while the draft cache follows the drafter, so the two halves can go
different ways in one load and no boolean can answer for both. The row now says
'host RAM', a GPU share, or nothing.

Drafter-bounded totals. A --spec-draft-hf drafter has its weights counted and
its cache omitted, which the response already documents as a lower bound, but
the headline printed it without the '>=' the unsizable-header case gets. Same
direction of error, so the same marker. The advisory chain still branches on
kvEstimable so each case names its own cause.

Auto context. Narrowed to resolveLoadMaxSeqLength's own fallbacks and no
further. An explicit length is itself and a reload keeps the context it is
resident at, but a known native context is no longer quoted: llama.cpp's --fit
can land below it, so a figure claims an outcome the load has not reached, where
0 lets the estimate resolve it the way the launch does.

Backend 773 passing across the seven suites that share the estimator, frontend
4925, typecheck and i18n parity clean.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Stop the estimate resolving a model that is not on this disk

The route's docstring says no model is loaded, no device is touched, nothing is
downloaded. Driven for real rather than with _cached_estimate_config stubbed, the
last clause was not true. An uncached remote id went through the load path's full
identification, which reaches the Hub: on unsloth/Llama-3.2-1B-Instruct, four
model_info attempts, an hf_hub_download of config.json, and 12 new paths / 1828
bytes of blob, ref, snapshot and lock file in the HF cache. For a request whose
answer is not_gguf, on an endpoint the settings panel fires on every change.

Every test in TestEstimateMemoryRoute monkeypatches _cached_estimate_config,
which is the one function that can violate the contract, so the suite asserted
the promise while stubbing out the only thing able to break it.

A repo that is not on this disk answers not_downloaded whatever the resolution
finds, so resolving it can produce nothing the route will use.
_estimate_target_is_on_this_disk asks that question from local state alone,
ahead of from_identifier. It reads every cache root Studio scans rather than the
configured one: a repo under the legacy or default root would otherwise read as
absent and the row would vanish for a model sitting right there, which is worse
than the round trip this avoids. It fails open, so an unreadable cache root
falls through to the old behaviour instead of refusing everything. A sentinel
keeps the answer honest: absent is not_downloaded, a resolution that was
attempted and failed is still unsizable.

Also serialises both cache evictions. The route body runs in an asyncio.to_thread
worker, so two panel requests are two real threads in there, and min() walks the
dict through a Python key function the interpreter can switch out of. A
concurrent pop makes that raise KeyError and a concurrent insert RuntimeError,
neither of which is caught between there and the worker, so it surfaces as a 500.
Reproducing it took hundreds of thousands of concurrent eviction cycles, so this
is a rare crash rather than a likely one, but a lock at this size costs nothing.

Backend 146 passing.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Do not reap processes or leak an atexit handler to price a load

The sizing helpers build a LlamaCppBackend purely to read a GGUF header and run
arithmetic, and LlamaCppBackend.__init__ does two things a probe has no business
doing: it reaps orphaned llama-servers, which walks every entry in /proc,
resolves each candidate's exe and signals the ones it recognises, and it
registers an atexit handler that holds the instance for the life of the process.

Both are right for the backend that owns the child. Before this panel existed
they ran on a load and on a training coexistence check. This route runs them on
every settings change, behind a 250 ms debounce.

Measured on the merged head, 50 estimates:

  before   250 constructions, 250 /proc scans, +250 atexit handlers, 120.6 ms each
  after      0 /proc scans, +0 atexit handlers, 43.3 ms each

The handler count is the one that does not self-correct: it grew linearly and
each entry retains a whole backend, so a session spent adjusting settings leaks
until exit. After the change it is flat at 0 over 50, 100 and 200 estimates.
A panel that prices a load must not be able to kill a server.

manages_processes defaults to True, so the real backend and every existing
caller keep today's behaviour exactly. _probe_backend falls back to the bare
constructor on TypeError because callers substitute LlamaCppBackend wholesale --
two stand-ins in test_chat_load_during_training.py are plain classes taking no
arguments, and both broke on the keyword before the fallback existed. A stand-in
that predates the flag has no reaper to suppress, so the fallback is correct and
not merely tolerant.

1556 backend tests passing across the estimator suites and all four platform
matrices.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Price the launch, not a near miss of it, in eight more places

Context checkpoints are host memory, not VRAM: llama.cpp keeps each one in
common_prompt_checkpoint's std::vector<uint8_t> buffers, bounded by --cache-ram,
and the load schema says so. They stay in the total and come out of the GPU
figure, and a build that lacks the flag is not charged for them at all.

Turning speculation off no longer adds a drafter. off, ngram and ngram-simple
all return out of _build_speculative_flags before --model-draft, so a model
shipping an MTP sidecar was billed gigabytes for disabling the feature. Extras
that own --spec-type still win.

An embedded NextN head is now priced. It is a drafter with no file, so nothing
was charged in the weights and the runtime block was skipped entirely, while the
head still allocates a context-sized draft cache.

--device none puts nothing on the GPU whatever the layer count says, and the
weights, cache, compute buffers and companions all follow it.

A --mmproj in the extras is the projector that opens: the launch appends the
extras after Studio's own, so the configured file was billed and a larger custom
one went free.

The quantization is part of which model an estimate belongs to. Switching Q4_K_M
to F16 leaves modelPath untouched, so one quant's footprint stayed on screen
under the other's name.

The advisory asks the aggregate question first. On a discrete host it read the
GPU verdict alone and offered spilling to system RAM as the remedy for a load
that does not fit in GPU and RAM combined.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Five more places the estimate and the launch disagreed

A CPU-pinned embedded head is still allocated. --spec-draft-ngl 0 and a CPU
draft device move the NextN head to host RAM rather than switching speculation
off, and gating the sizing on the pin dropped its context-sized draft cache from
the total as well, which is the direction that turns a multi-gigabyte load into
a fit. The pin now decides only which side of the GPU line the bytes fall on.

An Auto load on a machine with no GPU runs in host RAM. CPU placement was read
only from an explicit --device, so the row showed a multi-gigabyte GPU figure
against a capacity of zero. Keyed on a probe that ran and came back empty: an
unfilled snapshot is not absence, and the CUDA count is zero on every Vulkan
host, so neither may move the weights on its own.

A shared pool is the size of system RAM, not of the iGPU's allowance. The total
capacity was the capped 12 GB budget, so a 20 GB CPU-offloaded model read as
exceeding a host with 91 GiB. Taking the larger of the two keeps the bytes from
being counted twice without throwing the rest of the machine away.

A positive inherited LLAMA_ARG_CTX_SIZE is what the child runs at. The launch
drops one only when it is zero and --fit needs to run; the estimate fell through
to the header's native context, pricing a 4k load at 262k.

A repo the on-disk gate has already found is resolved offline first, so the
first estimate after a cache miss no longer makes two hf_model_info calls for an
answer that is on disk. The online path stays as the fallback.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Ask the header, not the mode, whether the draft head engages

The embedded-head gate was too coarse. Not-Off-and-not-ngram is not the same
question as does _build_speculative_flags emit MTP, and the difference is every
other fallback it has: DSpark and DFlash open their own sidecar or fall back to
--spec-default, Auto drops a sub-3B head for ngram-mod because MTP regresses
below 3B, and Auto drops an MLA head because llama.cpp's path there is about
half the speed of no speculation. Each is now mirrored through the loader's own
predicate. Both remaining drops are Auto's judgement rather than a hard
incompatibility -- forcing MTP on a sub-3B model logs Engaging anyway and emits
-- so an explicit request is charged for what it asked for.

Naming a drafter file is not owning the spec block. --model-draft alone leaves
the flags builder running, so on a target Studio recognises as an MTP model it
still emits --spec-type draft-mtp and the extras path merely last-wins; the
child then really does allocate the duplicated MLA context. On a target it does
not recognise the same extras are draft-simple and allocate neither, so the
caller answers that from the header rather than this deciding from the mode.

The estimate sends the speculative fallback the load path substitutes. A model
with no per-model override sent null, read as Auto, while the selector had been
showing the global setting; with that set to Off and an 11 GB DSpark sidecar in
the repo the row charged a sidecar the load disables.

Manual mode with Auto layers prices what --fit will size, not what is resident.
resolveFitMaxSeqLength sends a positive pin or 0 there and never the loaded
length, so changing a context-sensitive setting left the panel pricing the old
fit.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Make the CPU-only check reachable, and four more launch mismatches

The empty-GPU check added last round could never fire. _cached_inference_devices
ended in "or None", so the empty list a probed CPU-only host produces arrived as
the same value as a snapshot nobody had filled, and the branch that looks for it
was unreachable. Its tests passed because they replaced that function outright,
which is the one thing that could not be wrong; they drive the snapshot now.
Removing the collapse also stops a tensor split being priced on a host with no
cards, the other caller reading the same value.

Extras asking for MTP engage the embedded head. --spec-type draft-mtp on a NextN
GGUF is honoured by the child even though Studio emits no spec block of its own,
and with no drafter file there is nothing in the weights to notice, so the draft
cache and the target-side state went uncharged.

The host share is weighed against host RAM on its own. Spare VRAM cannot hold
bytes that placement has pinned outside the GPU, so a 70 GB CPU placement read
as fitting on a 24 GB card plus 64 GB of RAM.

A builtin-default GGUF load prices what --fit will size. resolveLoadMaxSeqLength
answers 0 there before it reaches the resident context, so the row was quoting
the old fit at the moment a setting had moved the next one.

The VRAM Budget caps the capacity the verdict is measured against. At 80 percent
a 20 GB footprint on a 24 GB card is past the line the slider directly above the
row draws, and the row called it comfortable.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Five more launch inputs the estimate was not reading

Draft cache types resolve in launch order. _extra_args_draft_cache_types falls
back to LLAMA_ARG_SPEC_DRAFT_CACHE_TYPE_K/_V by default, so asking it once and
then or-ing the panel field on gave the ENVIRONMENT precedence over the control.
At launch the field goes on argv, argv beats the env twin, and the extras are
appended after argv and beat both. Asked twice to get that, and the field is
dropped on a build with no draft cache-type flag, where Studio emits nothing and
the inherited value is what the child uses.

A build advertising no mtp_token cannot run MTP at all, so the embedded head is
not charged for one. Unlike the size and MLA drops this is a hard
incompatibility, so it applies to a forced request too.

The two tensor-split latches load_model consults are consulted here. A binary
that already refused a quantized KV cache under a tensor split, and a model that
aborted on one this session, both send the launch to a layer split; pricing
tensor after either charges per-device flat buffers for a launch that will not
use them.

An inherited remote drafter repo or projector URL marks the total as a floor.
LLAMA_ARG_SPEC_DRAFT_HF_REPO and LLAMA_ARG_MMPROJ_URL are both preserved for the
launch and both name a file the child fetches, which cannot be weighed without a
network call this route is documented not to make. Saying the figure is a lower
bound beats omitting gigabytes in silence.

The draft cache-type test asserted on source text, so it could only ever restate
the implementation. It checks the precedence by behaviour now, where a wrong
order changes the number rather than the spelling.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Warn when the card is already busy, and wait before pricing a maybe-diffusion

The fit verdict now sees what is free, not only what the cards hold. _select_gpus
admits on free-minus-reserve, so an 18 GB estimate on a 24 GB card with training
holding 14 of it was shown as a comfortable fit for a load that will spill. This
warns rather than refuses, and is capped at "tight" on purpose: the bytes a
pending load reclaims are the resident model's own, which cannot be attributed
per device from here, so raw free memory would call a reload of the loaded model
impossible. Both readings are honest at "tight", and the advisory says which.

An unclassified GGUF is no longer assumed not to be diffusion. The tri-state was
read through a boolean that folds "not yet classified" in with "not diffusion",
so the llama-server estimate could start on a target that may be DiffusionGemma,
whose runner allocates on a different plan. If the classifying probe never
answers, the tri-state never leaves undefined and the wrong figures stay up. A
moment with no row costs less than a confident wrong number.

A source switch clears the numbers during render, not after the paint. The
effect that clears them runs after React has already painted, so switching
directly between two GGUFs showed the previous model's footprint and fit colour
under the new name for a frame. The shown estimate carries its source identity
now and is masked when it does not match the render's.

* An explicit -c 0 is a request, and the budget is a reserve

"-c 0" asks for the native context; it is not the absence of a request. llama.cpp
reads argv after the environment, so the zero wins at the child, and folding it in
with "nothing was set" let an inherited LLAMA_ARG_CTX_SIZE=4096 answer for a launch
that opens at the header's 262k. The KV cache understated 64x, in the direction
that says fits.

The VRAM budget is subtracted from the card, not multiplied into what happens to
be free. _vram_usable_mib takes free minus an absolute reserve, so a 24 GB card
with 10 GB free at 80 percent offers 5.2 GB where a multiplication says 8, and a
7 GB load got no busy-card warning at all. The floor the loader keeps is modelled
too, since a flat 512 MiB would raise the reserve as the slider went up on any
card under about 17 GB.

The host share is weighed against what the machine can hand out now.
_host_offload_shortfall_message refuses on psutil's available memory less a
reserve, not on physical RAM, so a 70 GB host share read as fitting a 128 GB box
with 32 GB free. Warns rather than refuses, like the GPU figure and for the same
reason: the resident model's pages come back when this load replaces it.

On a single pool the whole load is weighed that way, which is also the closest
this can honestly get to Apple's Metal budget. That budget is 85 percent of the
smaller of MLX's recommended working set and what is available right now, and the
second term is the one that moves. The static ceiling stays unmodelled on purpose:
resolving it needs an import of mlx.core that can abort the process, which does
not belong on a path the panel drives on every settings change.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Four normalizations the launch applies before it sizes anything

A GPU pin owns placement. load_model strips the device flags and clears the
device environment when selected_gpu_ids names cards, so a stale "--device none"
left in Advanced Arguments made a pinned load read as CPU-only and report no GPU
footprint at all. The pin now overrides that reading, as it does at launch.

A --spec-draft-hf repository is no longer listed over the network. Sizing it
calls hf_model_info, which is right for the admission guard, where a running
training job is worth one request, and wrong for a row that re-prices on every
settings change. The panel asks for a local-only figure and marks the total a
floor, which is what it already did for a drafter it could not weigh. The flag is
part of the files cache key, so a local-only answer can never be served to the
guard.

The draft cache-type field needs BOTH flags. The launcher emits the pair or
neither, so a build exposing only one still allocates its inherited or default
cache while the estimate priced the requested dtype.

Slots are clamped on a build without --kv-unified, as load_model clamps them,
before the compute buffers and SWA layout are derived from the count.

The capability probe stays behind the slot check that used to short-circuit it.
Calling it unconditionally put a shelling-out call on every single-slot estimate,
and a raise there loses the whole runtime to the unknown fallback. The platform
matrix caught that on the Windows cells.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Name the encoding when the pip-cache test reads a workflow

Four read_text() calls with no encoding, so tests/test_source_read_encoding.py
fails on this branch. The file arrived with #9781 and the failure is on main as
well; it is fixed here because it is what is currently keeping this PR red.

The rule is the Windows one: read_text() without an encoding takes the platform
default, so these break the moment one of the workflow files it parses gains a
non-ASCII byte.

* Six things the estimate route was charging, reaping or waiting on

Measured the estimator against llama-server b10632 (commit 11cd98842, which is
what UNSLOTH_LLAMA_TAG=latest installs today) on two backends, the CPU build and
the Vulkan build on an NVIDIA card. Both report identical KV bytes, so the
numbers below are a property of the arithmetic rather than of the host.

A quantized V cache was priced at f16. _estimate_kv_cache_bytes was called with
flash_attn = False unconditionally, and that arm sets bpe_v = max(bpe_k, f16), so
the whole quantized saving on the V axis was charged straight back. It is the one
layout where flash attention is not a choice: llama.cpp turns it on itself, and
the log says so ("enabling flash_attn since it is required for quantized V
cache"), which _tensor_quant_kv_unsupported_binary already documents as an abort
in the other direction. So the conservative arm was pricing a launch that cannot
happen. Qwen3-0.6B at 32k with q4_0: 2296 MiB reserved against 1008 MiB
allocated. Every plain-GQA cell now matches llama.cpp to the byte, f16 included,
where 8 of 12 were off by 1.44x to 2.28x. f16, bf16 and f32 are untouched, so
only a quantized V moves, and it moves toward what is allocated.

An explicit --gpu-layers 0 on an unreadable header was priced fully GPU-resident.
_gguf_offloaded_layer_fraction answers 1.0 whenever layer_count is None, and a
header that yields no dims has none. The earlier round fixed the Mamba/RWKV
family by keeping block_count; this case has no count to keep and does not need
one. Zero needs no denominator, and the fraction is a scale factor for a partial
offload, which an explicit none is not.

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 after the offline attempt, so the
"nothing is downloaded" contract held only while a root was establishable. Now a
tri-state: the online retry is gated on unknown rather than on present, which
leaves production semantics unchanged and closes the fail-open. Three of the four
suspected triggers turned out to be safe already and are pinned as such, one of
them safer than its own docstring claimed, which is now corrected.

The inert probe could reap live servers. _probe_backend caught every TypeError
and fell back to the process-managing constructor, which walks /proc, signals
llama-servers and registers an atexit handler, 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 now asks the
signature instead of trusting the exception, and the two plain-class stand-ins in
test_chat_load_during_training still get their bare constructor.

A capability probe ran on the event loop. _effective_parallel_slots was called
before asyncio.to_thread and can shell out to llama-server --help; the codebase
is its own witness here, since _effective_default_slots already wraps the same
helper and its docstring records the stall it caused. The app-state read stays on
the loop, the clamp moves into the worker.

Both TTL caches stamped their entry before the slow work rather than after, so an
entry that took longer than the 30s TTL to build was inserted already expired.

Tests: 25 side-effect tests, of which 5 fail on the parent commit with their
intended evidence; 13 flash-attn parity tests including the four measured cells
reproduced as figures; and a 21-cell platform matrix over [Linux, WSL2, Windows,
macOS] x [NVIDIA single, NVIDIA multi, AMD ROCm, AMD Vulkan, Apple unified, CPU
only], 3928 priced responses, asserting the itemization sums, that the GPU share
never exceeds the total, that weights do not move when context does, and that no
cell reaches _apple_metal_memory_budget_bytes. That last one is confirmed: zero
calls across 880 probes with the conftest's bare-metal pin deliberately undone.

Three findings are recorded rather than fixed, because they are pre-existing in
llama_cpp.py and lowering the loader's reserve changes automatic context fitting
and GPU selection for every install: the compute buffer grows by 300 to 540 MiB
per serving slot where llama.cpp's shrinks (1039 MiB priced against 64 MiB
allocated at the default 4 slots), the SWA window is scaled by slot count where
llama.cpp only does so under a unified cache, and the context-linear compute term
is about 3x low at one slot. They want their own change and their own CI run.

* The row could not warn on the hardware that needed warning most

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.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Four placement inputs the panel was reading wrong

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.

* A discrete card beside an iGPU is two pools, not one

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.

* Price the standing GPU mode and the loader's own VRAM default

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.

* Keep an embedded NextN head with the target's placement

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

* Size the cache the launch will actually allocate

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.

* Do not fill a Windows runner's disk with the platform matrix

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.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: danielhanchen <[email protected]>
Co-authored-by: Daniel Han <[email protected]>
Co-authored-by: danielhanchen <[email protected]>
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.

Studio drops quantized KV cache when tensor parallelism is enabled

3 participants