Skip to content

Make the offload planner weigh a spill against llama.cpp's own fitter - #9872

Open
danielhanchen wants to merge 221 commits into
mainfrom
planner-cost-gate
Open

danielhanchen wants to merge 221 commits into
mainfrom
planner-cost-gate

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Aug 27, 2026 •

Copy link
Copy Markdown
Member

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 behind UNSLOTH_SMART_OFFLOAD, which stays opt-in. With the flag off the launch argv is byte-identical to main in 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 2048 raise 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:

rung what moves per-token cost
0 projector to host (--no-mmproj-offload) none, paid once per image
1 --parallel down one slot at a time, cache re-priced each step none for a single user
2 the MTP / draft reserve configurable, 0 until measured
3 to 6 ffn_down_exps, then ffn_up / gate_up, then ffn_gate, then dense FFN, lm_head last the cost gate decides
never attention weights, -nkvo measured 2.5 to 3.7x and 5.2 to 6.3x slower, worse at short prompts
last context, down to the largest context the gate accepts

Rungs 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_placement reports its decisions on Plan and 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

  • A context term in the per-device reserve. The flat 1.5 GiB failed identically at every budget once the served context reached about 64K: the planner fills precisely to budget minus reserve, so it left exactly that much free and the child refused to start. Measured by walking device headroom with -ot at 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.
  • A floor on the total reserve. The seam hands the planner usable VRAM that already withholds 3% of the card and then charged only the CUDA context and the compute term on top. On a 40 GiB card that reaches the validated intercept; on a 12 GiB card it left about 700 MiB where 1536 was measured to be needed. The total is now never below the curve.
  • An MoE long-prompt decline. At a 32K prompt -ot loses 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 -ot mechanism and the cost model can only ever report a near-tie there.
  • SpillOrder defaults to BACK_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.
  • Context is reduced last. A gate decline used to return straight out; now FIT_ONLY walks a descending ladder from a floor-aware max_context_for and takes the largest context the gate accepts, with the budget re-priced at each context.
  • --cache-ram is priced on both the planned and the --fit on paths 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.
  • Heterogeneous and Windows hosts, from the community evidence. The CUDA SM coverage check answers per device, so a mixed pair (a card below the build's oldest SM beside one above it) declines the plan naming the card instead of being admitted because any card qualified. A multi-device plan carries its modelled per-device layer counts and emits --tensor-split as integer counts, the form common/fit.cpp writes, unless the user typed one, so --fit off is 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 on when every selected device supports mmap and -lzm off on a Vulkan or integrated device, where llama.cpp's auto resolves to off in load_tensors, and the planner prices the mode that was emitted.
  • The layout readers refuse a block count above llama.cpp's layer cap (512, asserted in 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.
  • Fallback model corrections from the review round: lm_head is not charged to the host, the moved cache is charged at the calibrated cache rate, recurrent state moves with its layer, and the live-prefix cache carries the same floor correction as the reservation.

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:

  • The seam's estimator now re-prices the cache for the planner. PlanOptions.kv_bytes_at(n_ctx, n_parallel) is the seam's own _estimate_kv_cache_bytes, so _kv_floor_at, cache_bytes and max_context_for no 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 as cache_bytes already did.
  • Hybrids without full_attention_interval are 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 with ssm.* 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.
  • Nemotron-H MLP-only rows are not charged a recurrent state. Zero-head rows only count as recurrent when the per-layer feed_forward_length is zero too, matching the loader.

Gate coverage and the ladder:

  • Knob-only plans are ranked. A plan that only pinned the projector, dropped the draft or reduced slots skipped the cost gate, so the measured draft penalty never applied when the draft was the only thing given up.
  • The MoE long-prompt veto falls through at the requested context. It was a gate decline, which the FIT_ONLY ladder read as "try a smaller context", so a 65536 MoE request walked to 31744 and took the same spill. The veto now leaves the load to --fit on as asked.
  • A fitter placement that cannot be modelled declines instead of waving the spill through unranked.
  • The context ladder runs when the reserve at the requested context exceeds the card, instead of returning "no creditable VRAM" where a smaller context fits resident.
  • Rung 1 keeps slots it cannot buy anything with: skipped under --kv-unified, and a step whose re-price frees nothing is not taken.
  • A pooled fit with one card short tries the rungs and the per-device selector before abstaining, which is the lopsided pair (4 GiB plus 24 GiB) that used to fall back to the fitter with nothing tried.
  • An all-zero active -ts prefix abstains rather than being modelled as every row on device 0.
  • The trailing spill pick is no longer size-blind: a byte-minimal walk is built beside the contiguous tail and takes over when the tail moves more than twice the bytes the deficit needs, or outright under the cost gate. A 100 MiB deficit on a layout with an 8 GiB trailing block moved 4 GiB.
  • The modelled fitter places the cache by kv_layer_weights (recurrent rows carry none) and grades its boundary layer in common/fit.cpp's trial order, so the gate's comparison arm is closer to what llama.cpp does on hybrid and iSWA layouts.
  • A caller -nkvo cache is host RAM in both the planner's refusal and the seam's pool.

Seam:

  • Flag-off --fit on is 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_mode is 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.

  • MLA keyed on llama.cpp's own rule. is_mla needs both attention.key_length_mla and attention.value_length_mla. unsloth/DeepSeek-R1-GGUF and DeepSeek-V3-0324-GGUF carry kv_lora_rank alone, 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.
  • Non-Mamba recurrent state. Kimi-K3's KDA state (443 MiB per slot) and GLM-5.3-Flash's linear-attention state (146 MiB) were invisible to the layout, so the resident floor, max_context_for and the multi-device guard missed them. Sized from the hparams llama.cpp sizes them from.
  • One hybrid split for both readers. The estimator needed full_attention_interval while 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 one hybrid_layer_split, which also reads attention.recurrent_layers, and count attention rows the way llama.cpp does ((il + 1) % interval == 0, floor not ceiling).
  • The gpt-oss bootstrap table was keyed gpt_oss while the GGUF architecture is gpt-oss, under-counting the cache 41 to 49% without the transformers package. Both spellings fold.
  • Qwen3.8-Flash-Next's indexer cache. llama_memory_hybrid_idx builds a third cache over the dense rows (one head, K attention.indexer.key_length, V attention.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.
  • Flash attention priced as the launch runs it. The planner pinned FA off, 17 to 102% over the real allocation on every model in the set; the pin's reason (surviving the FA-off retry) was obsolete since that retry revokes the plan. Now priced from the resolved -fa value, off only when the user or the build runs it off.
  • A lazily read per-layer embedding is not resident host RAM. gemma4 and qwen4exp create per_layer_token_embd TENSOR_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.
  • Prefill priced at the host's own PCIe link. The 55 GiB/s constant was measured on PCIe 5 x16; nvidia-smi's negotiated maximum (gen and width, not the gen 1 x1 a consumer card reports while idle before the load) now sets the rate, minimum over the credited devices, so a Colab L4 or a desktop x4 slot is priced several fold slower and a spill that loses there is declined.
  • Fitter fallback: a load that already fits gives the fitter nothing to move, the MoE arm grades its boundary block like the dense arm, and a windowed cache charges only the live prefix of its full-context layers, since the saturated window is flat in context.
  • Rung 1 under --kv-unified asks the cache callable at the proposed slot count instead of the priced one; a revoked one-slot plan restores --kv-unified with 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:

n best planner arm shipped default
all 117 1.136x 1.080x
dense 53 1.279x 1.250x
MoE 64 1.088x 1.052x

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_gpu True for the planner against False for the fitter on every dense cell.

--load-mode none is 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

  • 3059 tests across the planner, seam, estimator, launch, stats and arch-gate suites at the current head, each new test checked non-vacuous by mutation; the one failure (test_oversubscribed_decode_threads_decline_spill_planning) is host-specific and fails identically on main.
  • Flag-off differential over 19 launch suites against a clean main checkout at the current head: identical failure sets by name (21 environmental failures on both sides), 7 passing tests added, none introduced.
  • Full backend suite against a clean main checkout: identical failure sets (272 by name on both, all environmental on the test box), 113 passing tests added, none introduced.
  • AMD CI on the Strix Halo pools at da5be5d, Linux gfx1151 and Windows 11: NO_REGRESSION. Windows runs the ten offload suites from the venv install.ps1 builds, 2400 passed at the head against 2122 at the base, with three failures present at both states (a Windows path-separator assertion, the host-only thread test, and the pass-through adapter pricing test).
  • Hardware: the reserve fix validated at 20, 16 and 12 GiB on an A100 and at 20 and 16 GiB on a G4, on the cells that previously could not start. The rungs above the weight spill were then run on hardware; results below.

Hardware validation of the ladder

Every cell scored only once all of its arms reported. Layerwise is --fit on --load-mode none at 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-mtp against none, 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_frac now 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 8192 an 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.

  • The gate prices the fallback it would really get. A declined Auto load launches --fit on at -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_model declined 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_BATCH is 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, which pipeline_parallel being 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 on load 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.

Before and after: the settings sheet explains that Auto turned MTP off

danielhanchen and others added 3 commits August 27, 2026 13:37
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.

@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: 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".

Comment on lines +353 to +357
# 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):

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

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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

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

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.

Comment on lines +325 to +330
resident = all_resident_bytes(
layout,
n_ctx,
kv_quantised = quantised,
kv_bytes_floor = kv_bytes_floor,
kv_on_host = kv_on_host,

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

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.

Comment on lines +292 to +300
def _fit_fallback_placement(
layout: ModelLayout,
opts: PlanOptions,
budget: int,
n_ctx: int,
*,
quantised: bool,
kv_bytes_floor: int,
kv_on_host: bool,

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

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.

@danielhanchen

Copy link
Copy Markdown
Member Author

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 --fit on as moving whole layers through n_gpu_layers, dragging each moved layer's share of the attention cache to host with it. That is what the top of offload_planner.py has always claimed, and it is what justifies the module existing at all.

Reading common/fit.cpp in the build Studio ships (b10472-mix-4b653db), it is not what happens. common_params_fit sets n_gpu_layers and tensor_buft_overrides (fit.cpp:490, :499). The patterns come from get_overflow_pattern, and for every layer past the boundary the fraction is LAYER_FRACTION_MOE:

blk\.<il>\.ffn_(up|down|gate_up|gate)_(ch|)exps

which is the same expert tensors the planner spills. The boundary layer gets a graded overflow instead (LAYER_FRACTION_ATTN / _UP / _GATE / _MOE, fit.cpp:407-440), so it can move part of a layer, and ngl_per_device with overflow_bufts makes the whole thing per-device.

Observed independently before I read the source: starting llama-server with -m -c -fa on --fit on --no-warmup --port and nothing else, it logs

llama_model_loader: tensor overrides to CPU are used with mmap enabled - consider using --load-mode none for better performance

No -ot was passed. The fitter set those overrides itself.

So --fit on keeps attention and the cache resident and moves expert tensors, which is the planner's strategy, with finer granularity at the boundary, per-device awareness, and a memory figure measured by get_memory_for_layers rather than estimated. That is a straightforward explanation for #9861 measuring it ahead in 40 of 43 planned cells, and for all 33 declined cells landing between 0.93x and 1.16x: when the planner declines, the two are doing the same thing.

What this means for the change here:

  • _fit_fallback_placement charges the fallback for moved attention weights and moved KV. Both are wrong in this build, and both inflate the fallback's cost, so the gate is biased toward planning. It is too lenient, not too strict.
  • The module docstring needs correcting on the same point.
  • The -ngl arm in our benchmarks, commented as "the layer spill --fit does today", is not that either.

The parts that stand on their own and do not depend on this: prefill is now priced at all (rank() and prefill_penalty_ms_per_token had no callers), the 20.1x KV rate was being applied outside the --no-kv-offload regime it was calibrated in, and the cache was priced at the full n_ctx reservation rather than the live prefix. I will rebase those on a correct fallback model.

@danielhanchen
danielhanchen marked this pull request as draft August 27, 2026 15:39
shimmyshimmer and others added 6 commits August 27, 2026 16:45
…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.

@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: 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".

Comment on lines +1106 to +1108
host_bytes = layout.token_embd_bytes
+ sum(b.spillable_bytes for b in chosen)
+ (layout.lm_head_bytes if spill_lm_head else 0),

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

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.

Comment on lines +350 to +353
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

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

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.

Comment on lines +325 to +331
resident = all_resident_bytes(
layout,
n_ctx,
kv_quantised = quantised,
kv_bytes_floor = kv_bytes_floor,
kv_on_host = kv_on_host,
)

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

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.
Base automatically changed from planner-budget-and-threads to main August 30, 2026 04:04
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.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 2, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ⚠️ Failed 2026-10-18T19:27:37.851075Z 815bdb2 New commits
🔒 Security Review ✅ Completed 2026-09-10T07:10:43.116849Z da5be5d Manual request

Security findings

Finding details are still loading. Check the individual review comments.

ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

danielhanchen and others added 5 commits October 22, 2026 19:37
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.
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]
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]

This branch has not been deployed

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

6 participants