Skip to content

Studio: widen what the offload planner can place instead of declining - #9778

Merged
danielhanchen merged 9 commits into
mainfrom
smart-offload-coverage
Aug 26, 2026
Merged

danielhanchen merged 9 commits into
mainfrom
smart-offload-coverage

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

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_RE only matched ffn_(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.

spelling arches per-block spillable, on a fixture
ffn_(up|gate|down)_exps qwen3moe and friends 1200 MiB, already worked
ffn_gate_up_exps cohere2moe, deepseek2, dots3note 800 MiB, new
ffn_*_chexps grovemoe 1200 MiB, new

Both the layout classifier and the emitted -ot pattern 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, and llama-arch.cpp dispatches it with plain GGML_OP_MUL_MAT rather than MUL_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 is MUL_MAT_ID, which is what makes "read sparsely" true rather than assumed.

2. -nkvo is priced instead of declined

This was the pessimistic direction, not the safe one. --no-kv-offload puts the whole cache on the host (offload is one scalar for the cache object and the buffer type falls back to ggml_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 none and -ts are planned rather than declined

  • -sm none is a device list of one: llama.cpp clears model->devices and keeps only devices[main_gpu] (llama.cpp:288-299). That is the single GPU case, which is the one with the most measurement behind it.
  • -ts does not skew the free-memory split, it replaces it. The values are copied into splits verbatim and prefix summed (llama-model.cpp:1436-1447), which is exactly the row-ownership weight split_weights_per_device already carries.

Still declining, deliberately:

  • -sm row is tensor parallelism. Each tensor is split across cards rather than rows handed out, so the row model does not describe the placement at all.
  • -ts with fewer shares than cards, or an unparseable value. A guessed row model is a per-device shortfall waiting to happen.
  • -sm none together with an explicit --main-gpu. -mg is still a device flag and keeps declining, so -sm none is supported at llama.cpp's own default main GPU of 0. Letting -mg through 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_layers short of n_layers, and sliding-window attention. That last one is the sharp case, since with an interleaved window every layer is an attention layer, so the n_attention_layers guard 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_pattern feeds _estimate_kv_cache_bytes and simply never reached the planner. _kv_layer_weights now 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 unless UNSLOTH_SMART_OFFLOAD is set.

Net effect is 16 abstains down to 11, plus -nkvo moving 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_memory and test_mtp_partial_offload_evidence.

@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: 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$")

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

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

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 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".

Comment on lines +18977 to +18982
"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,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

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

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 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".

Comment on lines +555 to +558
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):

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

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.

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.

Comment on lines +23957 to +23958
_scale = max(split_weights) if split_weights else 1
split_weights = [int(round(p * _scale)) for p in _ts[: len(kept)]]

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

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

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. You're on a roll.

Reviewed commit: c3d6671fb4

ℹ️ About Codex in GitHub

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

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

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

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

@danielhanchen
danielhanchen force-pushed the smart-offload-coverage branch from c3d6671 to f2dede4 Compare August 26, 2026 10:13
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 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".

Comment on lines +809 to +810
cache_bytes(layout, n_ctx, kv_quantised = quantised, kv_bytes_floor = kv_bytes_floor)
+ layout.recurrent_bytes

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

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.

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.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 26, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 26, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 26, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 26, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 26, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 26, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 26, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 26, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 26, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 26, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

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

@danielhanchen
danielhanchen merged commit 20100c1 into main Aug 26, 2026
37 of 47 checks passed
@danielhanchen
danielhanchen deleted the smart-offload-coverage branch August 26, 2026 13:09
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant