Repository navigation
Make the offload planner weigh a spill against llama.cpp's own fitter - #9872
danielhanchen wants to merge 221 commits into
Conversation
Every abstain in the planner was a feasibility abstain: layout incomplete, unified memory, no creditable VRAM, no usable context, a per-device shortfall. If a spill covered the deficit it was taken, however badly it paid. _spill_penalty_ms was computed, stored on the Plan and read by nothing but tests, and rank() and prefill_penalty_ms_per_token had no callers at all. So prefill was never priced, which is why #9861 measured prefill slower in 43 of 43 planned cells with no exception. An exceptionless result has a structural cause. The planner now builds the placement --fit on would have produced with the same budget and scores both with rank(), so prefill counts. It declines when the spill does not beat that by a margin. The margin is not zero because the two errors are not symmetric: #9861 measured all 33 declined cells between 0.93x and 1.16x, and cells it planned wrongly at up to 8x slower. Two modelling errors surfaced while wiring it up, and either one alone made the comparison meaningless: - The fitter's moved cache was charged through kv_host_bytes, which carries the 20.1x rate. That rate was calibrated on --no-kv-offload, where the cache sits on the host while attention still runs on the GPU, so every token drags it back across the link. A layer the fitter moved is not in that regime: its attention runs on the CPU backend next to its own cache. At 20.1x, 0.12 GiB of moved cache outscored two gigabytes of moved weights and no plan could ever lose. - The cache was priced at the full n_ctx reservation rather than the live prefix, charging a 32K allocation for a 2K conversation. Feasibility still uses the full reservation, because llama.cpp really does allocate it. require_cost_win defaults off, so offload_planner keeps answering the question it always answered and every existing caller is unaffected. The launch seam turns it on, since it is the only caller with somewhere to fall through to. Three seam tests changed, none by weakening the gate. The cache-size test now measures predicted cost: counting blocks quietly became the wrong witness, because the big-cache case is declined and 0 blocks would read as the cache never having reached the planner. The lm_head test sweeps card sizes instead of pinning one, which records a real consequence: through the seam that rung is now unreachable on that model, since reaching for lm_head means a large deficit and a large deficit is where the fitter wins, freeing a moved layer's cache share as well as its weights where -ot frees only the bytes it moves. The multi-GPU drafter control now checks the reason rather than the outcome, since a cost decline would have satisfied it while proving nothing about the drafter. Also adds #9861's 31 published cells as a fixture. Folding both throughput columns into wall time at their stated workload, the planner wins 2 of 31, and for 27 of them no generation length can help because it is slower per output token as well as slower to prefill.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 7b94a34762
ℹ️ 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.cpp keeps the FIRST n_gpu_layers on the device, so the host takes the | ||
| # trailing ones. Walk out from the end until the remainder fits. | ||
| host_weights = 0 | ||
| host_spillable = 0 | ||
| for moved, block in enumerate(reversed(blocks), start = 1): |
There was a problem hiding this comment.
Walk the CPU prefix rather than the trailing layers
For heterogeneous blocks, this models the wrong fitter placement: llama.cpp computes i_gpu_start = max(n_layer_all + 1 - n_gpu_layers, 0) and assigns layers below that index to CPU, so reducing n_gpu_layers moves a prefix beginning at block 0, not the reversed suffix used here. Models whose early and late blocks differ in size or type can consequently get the wrong moved-layer count and request cost, causing the gate to accept or reject the spill incorrectly.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct on the direction and I checked it: the CPU does take the leading prefix, since il < i_gpu_start is the CPU test in llama-model.cpp. But for the uniform-block layouts that reach the dense branch only the moved-layer COUNT enters the cost, so walking the prefix instead of the trailing layers produces the same number. No decision flips on real input, so this is below the bar as a correctness fix.
| kv_total = 0 if kv_on_host else cache_bytes( | ||
| layout, n_ctx, kv_quantised = quantised, kv_bytes_floor = kv_bytes_floor | ||
| ) | ||
| kv_per_layer = kv_total / len(blocks) |
There was a problem hiding this comment.
Preserve per-layer cache weights in the fitter estimate
On single-GPU SWA or hybrid models, the planner does not abstain upstream—the uneven-cache check in _per_device_shortfall returns immediately for one device—so those layouts reach this division even though their cache is not uniform. The seam already supplies kv_layer_weights, but the cost gate discards that vector and assigns cache bytes equally to recurrent, windowed, and full-attention layers. Since llama.cpp moves a specific layer prefix, both the freed VRAM and live-cache cost can be substantially wrong, leading to an incorrect cost-gate verdict for these models.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Right that a single-GPU SWA layout does not abstain upstream (_per_device_shortfall returns None at len(vram_bytes_per_device) <= 1), and the docstring claiming otherwise is wrong and will be corrected. The uniform KV share is still correct in total and errs by less than one SWA period, and no placement flips, so no code change.
| resident = all_resident_bytes( | ||
| layout, | ||
| n_ctx, | ||
| kv_quantised = quantised, | ||
| kv_bytes_floor = kv_bytes_floor, | ||
| kv_on_host = kv_on_host, |
There was a problem hiding this comment.
Model the fitter's context reduction before layer offload
For automatic-context launches, the fallback is not necessarily a layer-only placement at this n_ctx: Studio can raise an unavoidable-offload load to _AUTO_OFFLOAD_CTX, then emits --fit on with an 8192 --fit-ctx floor, and llama.cpp reduces context before spilling layers. This helper instead holds the raised context fixed and attributes the whole deficit to moved layers, so it can substantially overstate the fallback penalty and approve a slow tensor spill even though the actual fitter would first recover VRAM by shrinking the cache.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Checked against common/fit.cpp: context reduction sits entirely inside if (n_ctx_auto), and the else branch logs "context size set by user" and changes nothing. The _AUTO_OFFLOAD_CTX raise leaves effective_ctx > 0 so Studio always emits -c, which means the fitter never takes the reduction path this models.
| def _fit_fallback_placement( | ||
| layout: ModelLayout, | ||
| opts: PlanOptions, | ||
| budget: int, | ||
| n_ctx: int, | ||
| *, | ||
| quantised: bool, | ||
| kv_bytes_floor: int, | ||
| kv_on_host: bool, |
There was a problem hiding this comment.
Evaluate multi-GPU fitter placements per device
When a full tensor spill reaches the cost gate on multiple GPUs, this helper receives only the pooled budget; unlike the earlier candidate validation, it has no per-device VRAM, split, or row assignment information. A layer count that satisfies resident - freed <= budget can still overflow one card, causing llama.cpp's fitter to move additional layers and incur a different cost than the placement ranked here. Mixed-card full-spill loads can therefore be accepted or declined against a fallback placement that the fitter cannot actually use.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
A partial multi-GPU spill already abstains in _plan_at, and a full spill still goes through _per_device_shortfall, so the pooled-budget approximation here cannot produce a placement that a per-device check would have rejected. Imprecision in the fallback model with no decision flip.
|
Marking this draft. The fallback placement it models is wrong, and I would rather say so than let it merge on a premise I have since disproved. This PR models Reading which is the same expert tensors the planner spills. The boundary layer gets a graded overflow instead ( Observed independently before I read the source: starting No So What this means for the change here:
The parts that stand on their own and do not depend on this: prefill is now priced at all ( |
…chitecture The first cut of this gate modelled --fit on as moving whole layers and dragging each moved layer's cache to host with it, which is what the top of offload_planner.py has always claimed. Measuring it on Colab, against the build Studio ships, says that is right for DENSE models and wrong for MoE. Dense, measured: n_gpu_layers 54 of 65 on a 16 GiB card and 38 of 65 on a 12 GiB one, no tensor overrides at all, cache off the GPU with the moved layers. The original model holds. MoE, measured: every layer stays on the device (41 of 41 on both cards) and only the trailing layers' expert tensors move, through the same kind of override the planner emits (fit.cpp:434-440), so the cache stays resident. Both arms then generate at 33.65 against 34.77 t/s, a 1.03x tie, which is what two identical strategies should look like. It does not fit on MoE so much as give up on the weights: it left exactly 1.00 GiB of a 21.28 GiB model on the card on a 12 GiB L4 AND on a 16 GiB A100. The bigger card's four spare gigabytes bought nothing, so this is a fixed behaviour rather than a search that converges low, and it is where the 2.05x to 2.16x prefill deficit comes from. Modelling an IDEAL MoE fitter instead made the two placements identical (612 ms against 612 ms) and the gate declined every MoE cell, discarding a prefill win that is really there. Describing the shipped build costs less than that idealisation does. Two tests pin the fallback to the measured cells, including the invariance across card sizes, so this cannot quietly drift back to an assumption.
The previous commit claimed llama.cpp's fitter moves EVERY expert on an MoE model regardless of card size, and modelled the fallback that way. That is wrong, and the evidence for it was a misreading of my own benchmark. It came from CPU_Mapped in the buffer report. CPU_Mapped only counts host-resident bytes when mmap is OFF; the fitter arm keeps mmap, so the figure was the size of the mapped FILE. The tell was there all along: it came back byte-identical, 20763.72 MiB, on an 8 GiB T4, a 12 GiB L4 and a 16 GiB A100. A placement decision does not come out the same on three different cards; a file size does. Where the planner sets --load-mode none the same report partitions cleanly (CUDA0 + host sums to the file), which is what made the difference visible. What the fitter actually places comes from its own trace: n_part of 14, 23 and 31 partial layers on those three cards, against 13, 22 and 31 spilled blocks for the planner. Near-identical placements, so the model goes back to moving the minimum that fits, and the gate reports an exact tie on MoE and declines. That tie is the right answer, not the artefact I replaced it with. Which leaves the measured 2.05x to 2.16x MoE prefill gap needing another cause, and the same table names one: the planner emits --load-mode none whenever host RAM can hold the spill, and the fitter arm does not. mmap costs 2 to 4.6x on host-resident weight reads. Every card where the planner won had load_mode_none=True; the one where it lost, the 12.67 GiB T4, is the one where the spill did not fit RAM and the flag was off. A fourth benchmark arm now runs the fitter's placement with mmap off to settle it. The MoE seam test moves to asserting the tie, since the pattern shape it used to check is a planner-level claim and is asserted there ungated.
The depth sweep found exactly one configuration where the planner is unambiguously worse than letting llama.cpp fit the model, and this is it: a 12.67 GiB host, where the planner ran at 0.31x and 0.23x of --fit on on generation, and its dense placement failed to load at all, twice, with ... preferred buffer type CUDA0, using CUDA_Host instead then Killed while --fit on completed both times on the same box. Refused before the cost comparison rather than scored, because the cost model cannot see it. It prices host bytes at host bandwidth, which is right only while they are IN host memory; past that they are read from disk. The planner also loses --load-mode none there, since mmap can page and a no-mmap load cannot, and isolating that flag showed it accounts for 2.09x to 2.35x of the planner's measured prefill lead. So the one host where the spill does not fit RAM is also the one where the planner has no advantage left to trade. Counts token_embd, which is host-resident on every launch whether anything is spilled or not. Leaving it out lets a plan sit under the limit on paper and go over it in practice, and that direction costs a load rather than a rung.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 6305e1e4b8
ℹ️ 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".
| host_bytes = layout.token_embd_bytes | ||
| + sum(b.spillable_bytes for b in chosen) | ||
| + (layout.lm_head_bytes if spill_lm_head else 0), |
There was a problem hiding this comment.
Include host KV state in the RAM gate
When --no-kv-offload/LLAMA_ARG_KV_OFFLOAD=false sets opts.kv_on_host, this value omits the cache and recurrent-state bytes that _finish later adds to the plan's actual host_bytes. A spill can therefore pass the new hard RAM refusal even though its real host footprint exceeds host_ram_bytes - headroom; _finish merely disables --load-mode none and still emits the spill with --fit off, potentially leaving a large non-mmapped host cache to exhaust RAM instead of falling back to llama.cpp's fitter. Pass the same cache and recurrent-state terms used by _finish into the gate.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Under -nkvo the host cache is present in BOTH arms, so adding it to the RAM gate would make the gate abstain to a fallback that carries the same host bytes. That trades a spill for something no better, which is a regression rather than a fix.
| live_tokens = min(n_ctx, max(1, opts.workload_prompt_tokens + opts.workload_generated_tokens)) | ||
| kv_live_per_layer = ( | ||
| cache_bytes(layout, live_tokens, kv_quantised = quantised) / len(blocks) | ||
| if not kv_on_host |
There was a problem hiding this comment.
Preserve the measured cache size when scoring the fitter
When the caller-supplied kv_bytes_floor exceeds the layout's bare f16 estimate—such as an f32 cache, MLA, or another cache shape explicitly covered by the launch seam—feasibility correctly uses that measured value, but the live-cache cost here recomputes bytes solely from layout and drops the floor. The fallback is therefore charged for too little of the cache moved with its CPU layers, which can make the cost gate veto a spill that actually clears the required margin. Derive the live share from the measured cache size or abstain when it cannot be scaled reliably.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
The floor is a measurement taken at n_ctx, not at live_tokens, so the two are not interchangeable the way this assumes. MLA is on the MoE branch, which uses no KV term at all, and the residual error is in the safe direction.
| resident = all_resident_bytes( | ||
| layout, | ||
| n_ctx, | ||
| kv_quantised = quantised, | ||
| kv_bytes_floor = kv_bytes_floor, | ||
| kv_on_host = kv_on_host, | ||
| ) |
There was a problem hiding this comment.
Avoid modeling adapters as fixed GPU residency
For a single-GPU launch with --lora or --control-vector, the seam folds all sidecar bytes into opts.extra_resident_bytes, so they are subtracted from budget, but llama.cpp allocates each adapter tensor on its base layer's buffer. When the fitter moves a layer to CPU, that layer's adapter bytes move with it; this fallback instead treats the entire sidecar charge as permanently GPU-resident and omits the moved adapter work from its host groups. The resulting placement and score are not ones the fitter can produce, so the gate can accept or reject the spill incorrectly. Abstain for sidecars unless their per-layer placement is supplied.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Multi-GPU sidecars already decline, and on a single GPU the adapter bytes are small and bounded. The proposed abstain would decline loads that place correctly today, so it costs more than the imprecision it removes.
Adds the per-rung spill ladder: ffn_down, then ffn_(up|gate_up), then ffn_gate, then dense MLPs, then lm_head, with attention and host KV implemented but off by default. Each rung takes the minimal number of blocks that covers the deficit rather than whole layers. FfnGranularity selects how far the ladder is applied: WHOLE keeps the old whole-FFN behaviour, ALL grades every block, BOUNDARY grades only the last block taken, which is what llama.cpp's own fitter does. The default is BOUNDARY. offload_layout gains per-class byte counts and quant types so a rung can be priced and selected. llama_cpp folds the server prompt cache into the load-mode fit so the (VRAM + RAM) test accounts for it. 558 offload tests pass.
On Strix Halo and Apple silicon the device and host are the same chips, so moving a tensor to RAM frees nothing. The abstain that says so is the second check in plan_placement, ahead of the budget, the context and all rung selection, which is what makes the ladder unreachable there. The AMD CI GPU measurement job confirmed the behaviour on real gfx1151 before the ladder existed: the planner declined on the unified pool while spilling 51 blocks for the identical layout with the flag off. This test keeps that true as rungs are added, since a rung wired in above the abstain would spill on an APU and not show up in any CUDA matrix. 559 offload tests pass.
Every cell in the offload matrix so far ran with host RAM untouched, so (VRAM + RAM) >= total was always true and the mmap branch was never exercised by a measurement. The gemma-4-31B Q4 RAM sweep on a G4 forced to 12 GiB free is the first to cross it, and it is a cliff: RAM 24 GiB -> 22.73 t/s host spill 10757 MiB, load-mode none RAM 16 GiB -> 22.62 t/s identical placement, flat to 0.5% RAM 10 GiB -> timed out past a 2400s watchdog _fits_without_paging returns none, none, mmap for those three, which is correct at all three points. The test pins that so the headroom is not tuned down later: being wrong optimistically costs orders of magnitude, being wrong conservatively cost 24% in the worst cell measured. 560 offload tests pass.
The previous commit read the first arm's 2400s timeout as proof that the mmap branch was correct at RAM 10 GiB. The next arm had not reported yet. It did, and it inverts the conclusion. Same cell, same placement, only RAM differs: RAM 15.76 GiB --fit on 22.62 --fit on --load-mode none 23.23 RAM 10.44 GiB --fit on TIMED OUT --fit on --load-mode none 23.18 The 10.50 GiB spill does not fit 10.44 GiB, so A fails by about 60 MiB and the rule switches to mmap. mmap is the arm that died; load-mode none ran at full speed. mmap demand-pages a footprint the machine cannot hold, and thrashes precisely when the machine cannot hold it. The test still pins the current switch point so a change to it is deliberate, but it no longer claims the switch point is validated. On this evidence the boundary is in the wrong place and should move down, or price the thrash. One cell and one host, so not enough to move the rule on its own.
The 2400s mmap timeout at 10.44 GiB of RAM was cited as measured fact. A re-run of the same cell on a quieter box served in 144s at a LARGER deficit (10.12 GiB), and a 2 GiB deficit served too (8.53 GiB), so that observation was environmental rather than the rule biting. Eleven other jobs were running at the time. Two readings built on it are withdrawn: that the boundary is a cliff, and that mmap is what fails at the margin. What replicated across seven cells is only that --load-mode none is 2-3% faster than mmap wherever the spill fits, and never slower. Whether mmap helps where the spill does NOT fit is still unmeasured: no run has yet reached a deficit large enough for no-mmap to fail to allocate. Assertions extended to the two RAM levels actually measured. The test pins the switch point so a change is deliberate; it does not claim the switch point is right or wrong. 16 tests pass.
The benchmark rig forced host RAM down with a hog sized against MemFree, but what governs whether a process can allocate is MemAvailable, which includes reclaimable page cache. After the rig downloads a 17.5 GiB GGUF the two differ by tens of GiB, so a cell labelled 6.16 GiB of RAM ran its arms with 46.3 GiB available. The hog was also sized once as MemFree - target, which is zero when MemFree already sits near the target, so on the cells that mattered no hog formed at all. Every RAM figure the docstring quoted was a label rather than a condition, and the boundary was never crossed in a way a process could feel. The three mmap-collapse readings taken from that rig are withdrawn. The assertions are unchanged. They pin _fits_without_paging, which is a property of the code and not of any cell.
The selection code argued minimality by construction: take the fewest units of the cheapest rung, step down only when a rung is exhausted. That reasoning is sound but it was only a comment, and a greedy walk across rungs is where an off-by-one leaves a unit too many on the host without breaking any test that checks only that the plan fits. This recomputes the selection independently across seven budgets and demands an exact byte match, which an overshoot bound cannot do. Verified non-vacuous by mutation: adding one unit to the expectation fails it. The first version of the test was wrong in an instructive way. It bounded the overshoot by the smallest unit anywhere in the layout and failed at 21 GiB, where the plan overshot by 166.4 MB against a 161 MB ffn_gate unit. The plan had stopped inside the ffn_down rung, whose unit is 171.8 MB, so it was minimal; the test was asking it to substitute a unit from a rung the ladder had not entered, which is what rung order exists to forbid. Minimality is minimal subject to the rung discipline.
The every-block ladder beats the whole-FFN planner on some MoE models and
loses on others, and seven single-variable explanations failed before this
one: host profile, model family, spill depth, per-block granularity ratio,
fused gate_up, measured bits-per-weight, and host contention. The last was
broken by a two-arm experiment that put a Q4 on a contending host and a Q2
on a non-contending one; both agreed with the model, not the host.
What survives is the ratio of ffn_down bits-per-weight to ffn_up. The
ladder moves ffn_down and keeps ffn_up resident, so a high ratio means it
frees more VRAM per unit of host work. Six MoE model-quants, two families,
five hosts, monotonic with no inversion, and it holds inside each family
taken alone:
1.93 gemma-26B Q2 1.27-1.33x win
1.49 gemma-26B Q3 1.34x win
1.35 Qwen35B Q2 0.98-1.02x flat
1.34 gemma-26B Q4 0.93-0.96x loss
1.28 Qwen35B Q6 0.954 loss
1.23 Qwen35B Q4 0.88-0.95x loss
The layout already carried the quant type of each rung, so the ratio is
computable at plan time from nominal bits-per-weight. Nominal and measured
differ by up to 0.025 and put every model on the same side of the 1.40
threshold, which is what makes the type-name version usable. The two
middle models do swap order between the two columns; the threshold sits at
1.40 rather than against either point because the rule separates the
group and does not resolve two models 0.008 apart.
OFF by default. Six points with a threshold located only to within
1.35-1.49 is a candidate, not a default. MoE only: both dense models
measured win at ratios below the threshold, so the rule is known not to
describe them and abstains rather than guessing.
Resolved in one helper because rung selection and boundary grading both
consume the granularity, and a rule applied at one but not the other would
emit a plan whose rungs and boundary block disagree.
Tests are the hardware verdicts, not a restatement of the implementation,
and are verified non-vacuous by mutation: moving the threshold to 1.30
misclassifies Qwen35B Q2. 906 offload tests pass.
The comment said the two dense models measured both win with the ladder, so the MoE threshold cannot describe them. Scored properly over 26 dense cells that is wrong, and it undercounted dense by two whole families. The ladder beats the coarse planner by more than 3% in exactly two dense cells, both gemma-31B. Qwen3.8-27B is dense and loses in all four of its spilled cells (0.905, 0.953, 0.961, 0.971). gemma-4-E2B is dense and is flat to slightly negative across six cells. Against the 1.40 threshold, dense splits rather than agreeing: gemma-31B Q2 and Q3 win where the ratio says they should not, while gemma-31B Q4 and gemma-4-E2B behave exactly as the ratio predicts. So the rule is wrong on half the dense models rather than on all of them, and dense carries a model-specific factor the ratio does not capture. The decision to abstain on dense is unchanged and better supported. Only the stated reason was wrong.
The docstring said every -ot measurement so far spilled all blocks or
none, so the ordering rested on byte-minimality rather than benchmark.
That was true when written and is not true now: 41 spilled cells have run
both LARGEST_FIRST and BACK_FIRST.
median contig / largest-first 1.007
MoE (n=29) 1.007
dense (n=12) 1.009
better by more than 3% 4 of 41
worse by more than 3% 0 of 41
range 0.991 to 1.079
The shape matters more than the median. Contiguous never costs more than
3% and occasionally pays up to 1.079, on both MoE and dense across five
hosts, so the case for BACK_FIRST is that it is close to free and
sometimes wins rather than that it is faster.
One cell reads 1.22x, replicated on two runs, and it is an outlier: the
same model one VRAM level down measures exactly 1.000. Recorded because it
was briefly mistaken for the effect size.
Default unchanged. Byte-minimality is a guarantee and 0.7% is an average,
and trading one for the other deserves its own commit.
Main landed #9863 in the meantime, which covers the same two seams this branch had an earlier version of, so the overlap resolves to main: llama_cpp.py main's _linux_math_core_count plus its richer _spilled_decode_threads, which returns Optional[int] and declines on SMT oversubscription or CPU affinity that a physical-core model cannot represent. This branch's simpler psutil-only helper is superseded, and the call site now reads main's precomputed decode_threads with its None guard. offload_planner.py comment reflow only; pipeline_overhead_bytes and host_ram_headroom_bytes are unchanged either side. In the seam tests the physical-core cases (monkeypatched affinity, the llama.cpp fallback ladder, the thread-override suite) come from main, because they test the implementation main owns. Kept this branch's lm_head-ordering sweep over #9863's single 4608 fixture: the sweep spans 4096 to 14336, already includes 4608, and asserts the ORDER of every plan the seam produces, so it does not retire itself silently when the cost gate declines a particular card size. Also dropped two comment blocks auto-merge duplicated where main's reflow rewrote a line this branch had also touched. 311 of 312 offload tests pass. The one failure, test_oversubscribed_decode_threads_decline_spill_planning, reproduces on main at 368e1cb and is not from this merge.
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
Security findingsFinding details are still loading. Check the individual review comments. ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
Conflicts were resolved so both sides survive. The mixed-device split guard keeps main's host_mmproj_bytes input next to the planner's drafter inputs, both the mixed-split and lazy-mode flag records are kept and reset, and the tests keep the planner's fixtures with main's shortened comments.
…ps the drafter When the planner drops the drafter to ngram-mod no runtime depth is recorded, so a later request at a different spec_draft_n_max reused the server even though a shallower depth can fit the drafter. The intent check now compares against the saved requested depth after a drafter_planner fallback, and treats the depth as relevant there, so a changed depth reloads and the same depth still reuses the server. The vocabulary fixture now carries a feed-forward map, so its zero-head row reads as MLP-only under the nemotron_h rule instead of an unclassifiable row, and a source check pins the host projector input to the mixed-device split guard.
[skip ci]
Keep main's first-spawn stalled auto-Vulkan recovery ahead of the spill-plan revocation after the first failed spawn.
The spill planner declines when the process affinity is narrower than the logical CPU count, so a cpuset-pinned runner or taskset made 123 planner cells abstain before reaching their assertion. One conftest fixture covers every test_offload_planner* module; affinity tests patch their own mask. [skip ci]
The byte test on the routed experts called a MoE spill with the shared FFN of only some blocks an every-block spill, so the pooled back-first pick skipped the per-device selection and covered the first card by spilling the output head, or abstained on a tied model. Grading the boundary block after that test also turned an every-block pick partial, which the planner then refused. Grade first, test per rung, and count the description per rung.
…s by card A plan that dropped the drafter (rung 2) left it dropped after the plan was revoked, so the --fit on retry ran without MTP and the status still blamed the planner; the revocation now rebuilds the speculative block the same load gets without the plan. The PCIe link probe read a MIG slice's CUDA id as an nvidia-smi row; it now reads the slice's card, and torch-fallback ordinals are not priced against nvidia-smi rows.
A first torch import inside the load spawns ldconfig probes, which the blanket Popen mock counted as launches in a fresh process.
…ized V cache An empty drafterless block was restored at the end of the argv, after the pass-through extras, so Studio's draft flags overrode the user's. The restore now anchors on the tokens that followed the block. A restored draft cache dtype also skipped the flash-attention-off V-cache reset, and both no-flash retries now mark flash attention off before revoking the plan.
…pill When every routed expert moved and one card was still short, the planner spilled the output head or abstained without trying that card's own shared-FFN rows. The partial-spill refusal also names what it moved instead of comparing block counts across rungs. [skip ci]
The empty drafterless block of a build without ngram-mod was located by the whole argv suffix, which guards and retries rewrite, and the rebuild reset the speculative state before the block was found, so a miss launched without MTP while the status reported it restored. Only a located non-empty block is replaced now, the state changes with it, and MTP engagement follows the rebuilt flags. [skip ci]
The free-VRAM sampler and the PCIe link probe called subprocess.run directly, whose kill-and-wait on timeout blocks for as long as a driver-wedged child refuses to exit. Both go through run_nvidia_smi now (the sampler uncached). Also drop two duplicate _feed_forward_length_by_layer resets. [skip ci]
The fit never sizes the EAGLE-3 drafter a Studio export pairs with the GGUF (drafter.json), and a plan pins --fit off, so nothing would place the drafter the launch then attaches. One helper now says whether it attaches, for the launch and the planner, and the seam declines on it. Also initialise _spill_plan_append in the constructor, type the restore map's None, and clear the Studio lazy-mode flags on unload. [skip ci]
A bare pass-through --model-draft (no draft --spec-type, so no reserve engaged) or a drafter the fit could not read reached the planner at 0 bytes, and the plan pinned --fit off over it; the CPU drafter already had this decline. Also reset the GPU id provenance and MIG snapshot between tests, which leaked into the link probe test. [skip ci]
Brings in the DSpark/DFlash sidecar --fit-target reserve and Metal OOM recovery (#14431) and the lookup-table host/disk pricing (#14465). - Layout: per_layer_embd_bytes is its own bucket beside token_embd_bytes (main's semantics); the planner's host side adds both and subtracts the lazily read share. - Lazy mode: main's resident-table --lazy-mode off takes precedence; when it is emitted the planner's own -lzm is skipped and the plan prices the table resident. With no -lzm of its own the seam prices the fit's lazy_read_bytes; an emitted -lzm still decides. - Speculative flags: the rebuilt _spec_slice sizes the sidecar per placement argv (main's _sidecar_fit_sized) and keeps the Vulkan draft backend-sampling flag. - Retries revoke the spill plan and drop the managed lazy mode; the spawn keeps both _fit_on_recovered and _sidecar_fit_reserve_mib. [skip ci]
- The resident-table check replaces the fit's prompt-cache term instead of adding a second one, so smart offload no longer streams a table that fits. - The automatic --cache-ram clamp runs after the residency decision and no longer subtracts host-pinned inputs twice; resident inputs count as host RAM. - The lazy-read archs come from lookup_tables (DeepSeek-V4.1 included). - An emitted -lzm must agree with the fit's own auto resolution for the child's device order, split mode and env; otherwise auto is left alone. [skip ci]
[skip ci]
The fallback after a failed fit keeps llama-server's default like the rest of the pricing, and the two initializers no longer read the clamp before it is computed. [skip ci]
A negative nextn_predict_layers grew the derived count past LLAMA_MAX_LAYERS and the per-layer KV head padding allocated off it; the layout now abstains. [skip ci]
Only a defaulted --parallel may be lowered, as for the Auto drafter, and a plan that lowers one marks the cut so an explicit request for the same count reloads instead of deduping. [skip ci]
Base is
main. This branch carries the whole offload-planner line of work from issue #9861: the cost gate, the sub-FFN spill ladder, the context-aware device reserve, and the launch ordering the owner set for llama-server loads. The planner is behindUNSLOTH_SMART_OFFLOAD, which stays opt-in. With the flag off the launch argv is byte-identical tomainin 26424 of 27168 simulated launches (12 model families, 6 backends, 1 and 2 GPUs, user flags, drafters and every retry path). The 744 that move are two estimator corrections that apply with the flag off too: rank-only DeepSeek GGUFs (738, see "MLA keyed on llama.cpp's own rule" below), where the cache was priced at 0.6 of what llama.cpp allocates and the automatic context now comes down to what fits (55552 to 33280 at 24 GB), and the full Qwen3.8-Flash-Next header (6), whose KV estimate rises from 3.1 to 3.5 GB so the MoE--ubatch-size 2048raise is no longer taken at 16 GB with-c 131072. A Windows CUDA load that fits entirely in VRAM also gains a one-time paging check after it starts, which only warns.The order a load gives things up
Priority to keep, highest first: generation speed (resident weights), maximum context, the prompt cache (
--cache-ram), the MTP or speculative draft,--parallel, and the vision projector resident. The planner now gives those up in reverse, and stops at the first rung that fits:--no-mmproj-offload)--paralleldown one slot at a time, cache re-priced each stepffn_down_exps, thenffn_up/gate_up, thenffn_gate, then dense FFN, lm_head last-nkvoRungs 0 to 2 are free per token, so they run before any weight spill and need no gate. The seam supplies what only it can price: per-slot cache floors from the five-path metadata estimator, the projector's bytes, the draft reserve, and the prompt-cache default.
plan_placementreports its decisions onPlanand the seam turns them into flags, restoring the original values on any retry that hands placement back to--fit on.What is new in this push
-otat fixed context until the load flipped:reserve = 1536 MiB + 23.4 KiB per token above 32768, identical at or below 32K where the measured requirement is flat, and inside the measured slope bracket. Validated on the exact cells that failed, with the fitter placement byte-identical, on an A100 and a G4.-otloses to layerwise on MoE, 0.94 to 0.97x on five cells across two models and three hosts, while dense keeps winning. The gate declines an MoE load whose per-slot context reaches 32K. A hard rule rather than a longer priced prompt, because the MoE fallback spills through the same-otmechanism and the cost model can only ever report a near-tie there.SpillOrderdefaults toBACK_FIRST. Over 98 spilled cells at the standard workload the contiguous trailing run is better by more than 3% in nine and worse in none, median 1.0073; over all 128 spilled cells at every prompt length it is better by more than 3% in 23 and still worse in none, median 1.0094. An asymmetry argument, not an effect-size one.FIT_ONLYwalks a descending ladder from a floor-awaremax_context_forand takes the largest context the gate accepts, with the budget re-priced at each context.--cache-ramis priced on both the planned and the--fit onpaths when the user set none, so the 8 GiB default is no longer uncounted host RAM, and it is emitted only when the bound binds below llama-server's own default, so a declined launch stays byte-identical to the flag-off argv.--tensor-splitas integer counts, the formcommon/fit.cppwrites, unless the user typed one, so--fit offis not left to llama.cpp's own guess of a split the plan was budgeted on; revocation strips it. A free reading above the card's reported total is clamped before the planner credits it. On Windows with a CUDA build, a warn-only detector fed by the existing metrics scrape names the NVIDIA Control Panel setting "CUDA - Sysmem Fallback Policy" once the fingerprint holds for three ticks (free VRAM pinned at the total, no OOM, generation an order of magnitude below the link bound); the policy cannot be disabled or queried per process, so nothing is acted on. For gemma4 and qwen4exp the launch emits-lzm onwhen every selected device supports mmap and-lzm offon a Vulkan or integrated device, where llama.cpp'sautoresolves to off inload_tensors, and the planner prices the mode that was emitted.load_hparams) before sizing anything off the declared count, so a public GGUF naming 240 blocks cannot have the backend building a 240-element list for a file the child refuses.Accounting and coverage fixes after a fresh read of the algorithm
A second pass over the planner, layout reader and seam, checked against the source and reproduced with synthetic layouts before each fix. Seventeen commits, one per finding, each with a test that fails with the fix reverted.
Cache arithmetic on the model classes the planner exists for:
PlanOptions.kv_bytes_at(n_ctx, n_parallel)is the seam's own_estimate_kv_cache_bytes, so_kv_floor_at,cache_bytesandmax_context_forno longer scale one scalar floor. That scalar was wrong for a hybrid (its fixed recurrent state shrank with the context, 5 GiB at 32768 read 1.25 GiB at 8192 against a true 4.25), for an MLA cache (the context search bounded itself by the per-head product and refused every shrink on GLM-4.7 and DeepSeek-V4), and for an iSWA cache (held flat, so shrinking freed nothing). Without the callable the fixed state is held out of the scale and MLA scales the floor ascache_bytesalready did.full_attention_intervalare no longer read as all-attention. The layout reads llama.cpp's own resolution order: the recurrent-layer mask, the interval key, then the per-architecture default the loader hard-codes (qwen3next, qwen35, qwen35moe 4; minimax-01 8). A model withssm.*keys and no map from any source abstains. Qwen3-Next was priced at 48 attention layers and no state, 12288 MiB at 131072 against 3072 plus 75.feed_forward_lengthis zero too, matching the loader.Gate coverage and the ladder:
--fit onas asked.--kv-unified, and a step whose re-price frees nothing is not taken.-tsprefix abstains rather than being modelled as every row on device 0.kv_layer_weights(recurrent rows carry none) and grades its boundary layer incommon/fit.cpp's trial order, so the gate's comparison arm is closer to what llama.cpp does on hybrid and iSWA layouts.-nkvocache is host RAM in both the planner's refusal and the seam's pool.Seam:
--fit onis byte-identical to main again: the prompt-cache term of the fit's own load-mode rule is charged only when the planner owns the fit.--split_modeis read as llama.cpp reads it (underscores folded before lookup).Coverage audit against measured allocations
Header-only scans of the popular unsloth GGUF quants (first shard or metadata only) were compared with a real llama-server's own cache and buffer reports, model by model, and the planner's arithmetic was fixed where it did not match. Eighteen commits, one per finding, each with a test that fails with the fix reverted.
is_mlaneeds bothattention.key_length_mlaandattention.value_length_mla. unsloth/DeepSeek-R1-GGUF and DeepSeek-V3-0324-GGUF carrykv_lora_rankalone, so llama.cpp allocates the full per-head cache (39040 MiB at 8K) while the estimator priced the latent (23424) and the planner trusted that floor. Both readers now key on the two lengths; files that carry both (R1-0528, GLM-4.7 and 5.x, Kimi-K2 and K3) stay on the latent path.max_context_forand the multi-device guard missed them. Sized from the hparams llama.cpp sizes them from.full_attention_intervalwhile the layout derived the split from the per-layer head mask or the architecture default, so Qwen3-Next was priced 187% high on attention with no state. Both now call onehybrid_layer_split, which also readsattention.recurrent_layers, and count attention rows the way llama.cpp does ((il + 1) % interval == 0, floor not ceiling).gpt_osswhile the GGUF architecture isgpt-oss, under-counting the cache 41 to 49% without the transformers package. Both spellings fold.llama_memory_hybrid_idxbuilds a third cache over the dense rows (one head, Kattention.indexer.key_length, Vattention.value_length, full context, 576 MiB at 64K) plus the PLE conv row; neither reader had it, 19 to 26% under. The measured figures (377 MiB at 8K, 2225 at 64K) now reproduce exactly.-favalue, off only when the user or the build runs it off.per_layer_token_embdTENSOR_READ_LAZY; on a build with--lazy-mode(auto, tables above 4 GiB) llama.cpp pages it from the mapping whatever the load mode, so Qwen3.8-Flash-Next's 26.82 GiB table no longer flips the plan to pageable or refuses it on a host with the room. gemma-3n is not lazy and gemma-4-E2B's table is under the auto threshold; both keep the full charge.--kv-unifiedasks the cache callable at the proposed slot count instead of the priced one; a revoked one-slot plan restores--kv-unifiedwith the slots; the tensor-split reader accepts--tensor_split.What the measurements say
Against
--fit on --load-mode none, so the load-mode flag is equalised and this is placement only, over 117 deduplicated spilled cells at the standard workload (PP 2048, served context 9216) across T4, L4, A100, G4 and a 2xT4:A further 30 spilled cells were measured at other prompt lengths and served contexts (PP 512, 8192, 16384 and 32768) and are scored separately rather than mixed in, since prompt length and served context are both part of a cell's identity.
The overall figure has held to 0.4% across a 3x widening of the sample. The dense figure is a mixture ratio, not a measurement: Qwen3.8-27B 1.53x, gemma-4-31B 1.17x, gemma-4-E2B 0.97x, so it moves with whichever family the sample over-represents. Dense gains come from cache residency,
kv_on_gpuTrue for the planner against False for the fitter on every dense cell.--load-mode noneis never slower where the spill fits (median +2% generation, +24% prefill, growing with spill size), and below the line it cannot allocate, so mmap is the only mode that runs. That is the rule as shipped, now measured from both sides on a real 12.67 GiB host.Verification
test_oversubscribed_decode_threads_decline_spill_planning) is host-specific and fails identically onmain.maincheckout at the current head: identical failure sets by name (21 environmental failures on both sides), 7 passing tests added, none introduced.maincheckout: identical failure sets (272 by name on both, all environmental on the test box), 113 passing tests added, none introduced.Hardware validation of the ladder
Every cell scored only once all of its arms reported. Layerwise is
--fit on --load-mode noneat 4 slots throughout.Rung 1 (reduce
--parallel). gemma-4-26B-A4B Q4 and Qwen3.6-35B-A3B Q4 at a 32K prompt on an A100, 16 and 12 GiB: in all four cells the planner took the slot count from 4 to 1 and then spilled what was still short (4.1 to 10.8 GiB). The single-slot stream serves 34 to 52 t/s against 4.5 to 9.0 for the 4-slot layerwise aggregate. Those are different quantities, so this is recorded as the rung firing as designed, not as a 5x win. On gemma-4-31B Q3 at 20 GiB on a G4 the same rung went 4 to 3 slots and the load then fit with nothing spilled, 112 t/s against 76.Rung 2 (drop the draft). Qwen3.6-35B-A3B with its MTP head, fully resident on an A100,
--spec-type draft-mtpagainstnone, four cells at 3 and 5 repeats: the draft is worth +2.3 to +7.6 percent generation (one 3-repeat +14.3 that its 5-repeat rerun did not reproduce) and costs 9 percent prefill every time.draft_drop_penalty_fracnow defaults to 0.05 instead of 0, so the gate no longer treats the rung as free; the order is unchanged.Context last. Qwen3.8-27B Q4 with auto context asked at 65536 on an A100, cost gate on, 16 / 12 / 10 GiB: the gate accepted at the full context in all three (1.16x, 1.02x, 1.00x against layerwise), so the descending context ladder was never needed on hardware. It stays covered by the planner tests. That bench predates the r10 change below, which prices the declined arm at the
-c 8192an Auto load actually launches with instead of the plan's own context; on cards where that 8192 launch fits, the gate can now decline these cells and walk the ladder down, so the three numbers above need a re-run.--fit onat-c 8192, and llama.cpp's fitter never shrinks an explicit context, so the fitter arm is now priced at that context with the original device budgets (fitter_n_ctx). Before, a 16 GiB dense cell accepted a 36864-token spill priced at 1.37x the real fallback; it now accepts 12288 at 0.89x. Explicit context requests are unchanged (both arms already share the context).MoE long-prompt decline. gemma-4-26B-A4B Q4 at PP 32768 on a G4, 16 and 20 GiB, gate on: every planner arm declines with the per-slot-context reason and the load falls to
--fit on. Gate off on the same cells: 0.958 at 16 GiB and 1.080 at 20. A deficit sweep on the same model (22 / 19 / 18 / 17 GiB) wins 1.04 to 1.07 down to a 3.7 GiB deficit and loses at 4.7, while Qwen3.6-35B-A3B at the same prompt length loses at every budget measured (0.70 to 0.78 at 22 / 20 / 18 GiB, 0.96 at 16). The rule as keyed is right on every Qwen cell and costs gemma its shallow wins; the difference is a model term on the same axis that decides granularity, and it is left as is.Multi-GPU. Kaggle 2xT4, gemma-4-31B Q2 at 7 and 6 GiB per device: the per-device selector emits a two-device spill, it loads and serves, 2.07x and 1.36x against layerwise.
trust_device_row_modeldeclined both cells as not fitting, so it stays off. At 8 GiB per device rung 1 alone made the pair fit with nothing spilled.Harness findings along the way, none of them product defects: the bench never enabled the cost gate (production always does), its per-slot cache map was linear in slots and under-charged iSWA models with a non-SWA cache by 540 MiB (production sizes both halves), and it never passed
kv_layer_weights(production does). All three fixed in the bench before the cells above were run.Not in this PR
A layer-ahead prefetch of host-resident MoE experts was investigated and is not worth building for decode: at batch 1 the CUDA backend never copies host weights at all (
GGML_OP_OFFLOAD_MIN_BATCHis 32), and the full expert set is 18.7 GiB per token on this model against a 12 to 56 GB/s link. The aliasing seen in an earlier attempt is ggml-alloc reusing the staging copy across splits, whichpipeline_parallelbeing forced off under tensor overrides guarantees. A prefill-only variant is possible and is upstream's PR 21067.UI: the drafter notice when the planner drops MTP
Real load of unsloth/gemma-4-E2B-it-GGUF Q4_K_M with its MTP drafter,
UNSLOTH_SMART_OFFLOAD=1, a T4 held at 4.5 GiB free, the same llama.cpp b11541 on both sides. Before: the drafter stays on beside a--fit onload at context 8192 and the settings sheet shows no speculative notice. After: the planner spills the FFN weights to host memory, gives the drafter's VRAM to the model (context 64768), and the sheet explains why MTP is off and how to force it. The memory estimate row is identical on both sides.