Repository navigation
Studio: widen what the offload planner can place instead of declining - #9778
Conversation
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 23d3bcba07
ℹ️ 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".
| # axis, dispatched with plain GGML_OP_MUL_MAT. It is a latent projection every | ||
| # token crosses, so spilling it would push a hot tensor to the host under the | ||
| # rate the cost model reserves for cold ones. | ||
| _MOE_EXPERT_RE = re.compile(r"^ffn_(up|gate|down|gate_up)_(exps|chexps)\.weight$") |
There was a problem hiding this comment.
Price chunk experts with their own activation fraction
For Grovemoe, ffn_*_chexps are not activated at the ordinary expert_used_count / expert_count fraction used by _spill_penalty_ms: llama.cpp defines only expert_count / experts_per_group chunk experts and selects min(expert_used_count, chunk_expert_count) of them (unsloth_studio/llama.cpp/src/models/grovemoe.cpp:152-164). A typical 64-expert, 8-per-group, top-8 model therefore reads 100% of each newly spillable chunk tensor while the planner prices only 12.5%, substantially understating the per-token CPU cost. Track chunk-expert bytes separately with the correct fraction, or keep them resident rather than grouping them with ordinary sparse experts.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
The llama.cpp half of this is right and I checked it: grovemoe defines n_chunk_expert = n_expert / n_group_experts and selects min(n_expert_used, n_chunk_expert), so chexps do not activate at expert_used_count/expert_count.
Declining it anyway, because the mispriced value never reaches a decision. _spill_penalty_ms has exactly one caller, the predicted_gen_penalty_ms field, and a repo-wide search finds that field only in the dataclass, that assignment and four test assertions. It gates no spill choice, no fit claim and no emitted flag, so a wrong number here misreports a predicted cost rather than causing a bad placement. That is below the bar for changing the classifier, which is load-bearing for what actually gets spilled.
Worth revisiting if the penalty ever starts driving a decision.
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 6dc4595a3d
ℹ️ 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".
| "kv_layer_weights": self._kv_layer_weights( | ||
| effective_ctx, | ||
| swa_full = swa_full, | ||
| n_parallel = n_parallel, | ||
| kv_unified = planned_kv_unified, | ||
| n_ubatch = _effective_ubatch, |
There was a problem hiding this comment.
Include checkpoint KV in the spill plan
When an explicit --ctx-checkpoints is used with a multi-GPU SWA model, _spill_inputs["kv_cache_bytes"] is still calculated via _kv_bytes(effective_ctx) with the checkpoint count defaulting to zero, and this newly supplied vector also deliberately omits those checkpoint cells. Because the vector now bypasses the previous multi-GPU SWA abstain, a full-spill plan can pass the per-device check and emit --fit off without reserving the ctx_checkpoints * window allocation on the SWA rows, causing a device owning those rows to OOM.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Checked this one rather than taking it. Context checkpoints are host buffers, not VRAM: common_prompt_checkpoint holds std::vector<uint8_t> data_tgt/data_dft (common/common.h:1137-1147), and update_tgt serialises the seq state into them with llama_state_seq_get_data_ext (common/common.cpp:2282-2297) rather than allocating a second cache. n_ctx_checkpoints appears nowhere under src/ or ggml/ at all, so it never reaches KV-cache sizing. The total the spill planner works from is therefore right to pass ctx_checkpoints = 0.
That also settles the docstring note you pointed at: it hedged that the distribution was conservative because the total contained checkpoints. Since the total does not contain them either, the two are simply consistent, and I have rewritten the paragraph to say so with the citation instead of leaving the hedge standing.
There is a real version of this concern, in the opposite direction: checkpoints are host RAM, and the spill planner puts FFN blocks into that same pool behind a flat 2048 MiB headroom. Not fixed here, since checkpoints accumulate while serving rather than at load, and it predates this PR.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 341807e663
ℹ️ 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".
| layout.recurrent_bytes > 0 or layout.n_attention_layers != layout.n_layers or layout.has_swa | ||
| ) | ||
| weights = [max(0, int(w)) for w in kv_layer_weights] | ||
| if len(weights) != layout.n_layers or not any(weights): |
There was a problem hiding this comment.
Skip the recurrent abstain when KV is already on host
With --no-kv-offload on a multi-GPU recurrent hybrid, both the attention cache and recurrent state are host-resident, so their per-layer GPU distribution is irrelevant. This branch nevertheless returns the recurrent-state abstain before the later opts.kv_on_host logic zeroes the cache, meaning the newly supported host-KV path still cannot produce a full-spill plan for these models and falls back to the slower native whole-layer fitter. Apply the uneven-cache abstain only when the cache remains GPU-resident.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Your premise is right and I checked it: -nkvo clears cparams.offload_kqv, and that same scalar is handed to the recurrent memory (llama-model.cpp:2420-2427, and the hybrid constructors at :2455-2492), where llama-memory-recurrent.cpp:80-87 puts r_l/s_l in ggml_backend_cpu_buffer_type() unless offload is set. So recurrent state does move to host, and Studio already models it that way in resident_floor_bytes and _finish.
Where I disagree is the classification. _per_device_shortfall returning a reason does not produce a wrong plan: the caller turns it into a changed=False Plan, no spill flags are emitted, and the launch path falls through to --fit on, which is llama.cpp fitting the load exactly as it did before this PR existed. That is a conservative abstain costing coverage on multi-GPU recurrent hybrids run with -nkvo, not a wrong placement, so it does not meet the bar for a change here.
Noting the shape for later, since you traced it correctly: cache is already forced to 0 under kv_on_host, so kv_by_layer is all zeros and the per-layer shape genuinely stops mattering. It is a one-condition change whenever coverage there is worth having.
| _scale = max(split_weights) if split_weights else 1 | ||
| split_weights = [int(round(p * _scale)) for p in _ts[: len(kept)]] |
There was a problem hiding this comment.
Preserve positive tensor-split shares during scaling
For a valid highly skewed split such as -ts 1e-20,1, multiplying by the free-memory scale and rounding converts the first positive share to zero. llama.cpp keeps the original floating-point shares, so its upper_bound assignment gives row 0 to device 0 for any positive first share, whereas _device_slots receives zero here and assigns that row to device 1. If row 0 is large or device 0 is small, the per-device proof can therefore approve a placement that overflows device 0 after --fit off; retain the floating-point proportions or otherwise preserve every positive share.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
The mechanism is real and I reproduced both sides. llama.cpp keeps a positive share alive because the cumulative array is float32 and upper_bound(0.0) lands on index 0 (llama-model.cpp:1439-1456), while int(round(p * _scale)) here floors it to 0 and _device_slots then picks the next device. So the two disagree, as you say.
What I do not accept is the reachability. _scale is the largest card free VRAM in BYTES, so a share underflows only below 0.5 / _scale, which is about 2.9e-11 on a 16 GiB card. Every share anyone types (1, 3, 0.5, 24,8, 9,1) is more than ten orders of magnitude above that, and the real spelling for "give this card nothing", -ts 0,1, already agrees on both sides. The two adjacent classes are handled: non-finite shares decline, and an all-zero split is rejected here and is all_zero to llama.cpp anyway.
So this is hardening against an input the code does not receive. I would rather not add a branch whose test can only be written by inventing a value no user can produce.
|
Codex Review: Didn't find any major issues. You're on a roll. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
…n the layer vector
c3d6671 to
f2dede4
Compare
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 337502e2d5
ℹ️ 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".
| cache_bytes(layout, n_ctx, kv_quantised = quantised, kv_bytes_floor = kv_bytes_floor) | ||
| + layout.recurrent_bytes |
There was a problem hiding this comment.
Avoid charging recurrent state twice on the host
When --no-kv-offload is used with an MLA or Mamba/attention hybrid, the caller-supplied kv_bytes_floor already includes the recurrent state because _estimate_kv_cache_bytes adds _recurrent_state_bytes or _mamba_recurrent_state_bytes. Consequently, cache_bytes(...) includes that state here and adding layout.recurrent_bytes charges another copy. On a single-GPU hybrid that still needs a tensor spill, this can make host_bytes cross the RAM-headroom threshold unnecessarily, leave mmap enabled, and lose the intended host-offload performance benefit; separate the attention-cache floor from recurrent bytes or avoid adding the recurrent term twice.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Half the arithmetic is right and the effect is not reachable, so I am leaving it.
The overcount is real in one case: _estimate_kv_cache_bytes folds recurrent state into its return on the MLA and Mamba-hybrid paths, that value arrives as kv_bytes_floor, and _finish adds layout.recurrent_bytes on top, so when the floor wins the max() in cache_bytes it is counted twice. On the Mamba hybrid it often does not win, since the layout prices every block as attention while the real model is 1-in-N.
But nothing downstream can act on it. Plan.host_bytes has exactly one consumer outside the planner and its tests, a format argument in the logger.info at llama_cpp.py:19590. Plan.load_mode_none has no non-test consumer at all: its only reader is plan_to_args, which is referenced only from the planner tests, while the production emitter _spill_plan_flags_for returns -ngl -1 --fit off plus the -ot tokens and never --load-mode. So the chain you describe, crossing the RAM headroom and leaving mmap enabled, has no path to argv.
Two things also point the other way. Overstating host_bytes makes load_mode_none less likely, which keeps an over-commit pageable rather than OOM-killed, so the bias is the safe direction. And under -nkvo specifically, resident_floor_bytes returns before either term, so the VRAM deficit that actually drives the -ot set is untouched.
That leaves one log line reading high on a -nkvo MLA load, which is not worth a branch here.
|
@codex review |
|
Codex Review: Didn't find any major issues. Swish! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
Follow-up to #9675. The planner landed with a deliberately wide set of abstains, and several of them were not describing a limit of the approach, they were describing data we already had and were not passing across the seam. This widens what it can place, without loosening any of the safety properties.
Four changes.
1. Fused and chunked expert tensors are spillable
_MOE_EXPERT_REonly matchedffn_(up|gate|down)_exps, so a GGUF carrying the fused or chunked spelling got no spill help at all: the bytes landed in the resident bucket, the planner found nothing it was allowed to move, and the load fell through to--fit on.ffn_(up|gate|down)_expsffn_gate_up_expsffn_*_chexpsBoth the layout classifier and the emitted
-otpattern move together, or the plan credits itself bytes the pattern never moves.Not
ffn_routed_up/ffn_routed_down. That reads like a fourth expert spelling and is not one: kimi-k3 creates it{n_embd, n_embd_latent}, two dimensional with no expert axis, andllama-arch.cppdispatches it with plainGGML_OP_MUL_MATrather thanMUL_MAT_ID. It is a latent projection every token crosses, so spilling it would put a hot tensor on the host at the rate the cost model reserves for cold ones. The discriminator used throughout isMUL_MAT_ID, which is what makes "read sparsely" true rather than assumed.2.
-nkvois priced instead of declinedThis was the pessimistic direction, not the safe one.
--no-kv-offloadputs the whole cache on the host (offload is one scalar for the cache object and the buffer type falls back toggml_backend_cpu_buffer_type()for every layer, llama-kv-cache.cpp:210-219), so the cache and the recurrent state leave the VRAM footprint. Declining meant charging a cache to VRAM the child never puts there and spilling FFN blocks to cover it.On the test fixture that is 13 blocks spilled down to 0. The bytes are now charged to host RAM instead, so the mmap decision is still made against the real footprint rather than one short by the whole cache.
3.
-sm noneand-tsare planned rather than declined-sm noneis a device list of one: llama.cpp clearsmodel->devicesand keeps onlydevices[main_gpu](llama.cpp:288-299). That is the single GPU case, which is the one with the most measurement behind it.-tsdoes not skew the free-memory split, it replaces it. The values are copied intosplitsverbatim and prefix summed (llama-model.cpp:1436-1447), which is exactly the row-ownership weightsplit_weights_per_devicealready carries.Still declining, deliberately:
-sm rowis tensor parallelism. Each tensor is split across cards rather than rows handed out, so the row model does not describe the placement at all.-tswith fewer shares than cards, or an unparseable value. A guessed row model is a per-device shortfall waiting to happen.-sm nonetogether with an explicit--main-gpu.-mgis still a device flag and keeps declining, so-sm noneis supported at llama.cpp's own default main GPU of 0. Letting-mgthrough the placement guard is a separate decision.4. The per-layer KV vector crosses the seam
Three abstains existed only because the layout could not say which layers hold the big caches: a recurrent hybrid, an
n_attention_layersshort ofn_layers, and sliding-window attention. That last one is the sharp case, since with an interleaved window every layer is an attention layer, so then_attention_layersguard never fires while the per-layer sizes differ by roughly 6x on Gemma3 and far more at long context.The data already existed.
self._sliding_window_patternfeeds_estimate_kv_cache_bytesand simply never reached the planner._kv_layer_weightsnow builds the shape from it and passes it through.Only the ratios travel. The planner scales the vector to the byte-accurate total it already had, so this never becomes a second competing estimate of cache size. A test pins that: changing only the shape moves which card overflows without changing how much cache exists. A vector whose length does not match the model is ignored and falls back to the abstain rather than being stretched to fit.
One documented approximation: the vector omits the per-slot context-checkpoint extra, which lands on sliding-window layers only. That under-weights the small layers, which over-weights the full-attention ones, which is the direction that reserves more on whichever card draws them.
What did not change
Every safety property is where it was. The KV cache is still never moved by a plan, attention weights are still never selected and still cannot be matched by the anchored patterns, an abstaining plan still emits nothing and falls through to
--fit on, and the planner is still off unlessUNSLOTH_SMART_OFFLOADis set.Net effect is 16 abstains down to 11, plus
-nkvomoving from a decline to a strictly better plan.Tests
853 pass across
test_offload_planner,test_offload_planner_seam,test_offload_cost_model,test_llama_cpp_placement,test_llama_server_args,test_auto_offload_ctx_invariants,test_slot_offload_fit,test_host_offload_ram_guard,test_amd_apu_unified_memoryandtest_mtp_partial_offload_evidence.