Repository navigation
Studio: make the GGUF memory estimate match the compute buffers llama.cpp allocates - #11043
Conversation
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: c95ac31335
ℹ️ About Codex in GitHub
Codex has been enabled to automatically 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 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| if not flash_attn: | ||
| n_head = getattr(self, "_n_heads", None) or max(1, n_embd // 64) | ||
| per_tok += ub * n_head * 4 |
There was a problem hiding this comment.
Forward Flash Attention mode to tensor buffer sizing
When tensor parallelism is used with Flash Attention explicitly or environmentally disabled, _plan_tensor_parallel, _tensor_split_fits_budget, and the tensor branch of _gguf_runtime_bytes call this helper without forwarding the resolved mode, so flash_attn defaults to True and this newly modeled score-matrix allocation is omitted. The measured cases in the added tests show that omission can be several GiB per device, allowing the tensor planner to choose an unloadable context or the training guard to admit a process that exhausts VRAM; the actual launch mode needs to be threaded through these tensor callers separately from the intentionally conservative KV-cache mode.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
llama.cpp never runs a tensor split with Flash Attention off. In llama_init_from_model (src/llama-context.cpp), LLAMA_SPLIT_MODE_TENSOR turns flash_attn_type AUTO into ENABLED and returns nullptr with "SPLIT_MODE_TENSOR requires flash_attn to be enabled" for DISABLED. So the flash_attn=True default is the only mode these tensor callers can price: a tensor launch with FA disabled fails context creation and never allocates the score matrices. The layer-split callers, where FA off is a real launch, already receive the resolved mode.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 378e63453f
ℹ️ About Codex in GitHub
Codex has been enabled to automatically 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 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| * 4 | ||
| * _out_slots | ||
| * (devices if tensor_parallel else 1) | ||
| mask_bytes = budget_ctx * effective_ubatch * 2 * devices * split_mult |
There was a problem hiding this comment.
Account for Flash Attention-off in remote reserves
For an uncached remote GGUF launched in layer mode with a last-wins --flash-attn off extra, this always charges a two-byte Flash Attention mask and omits the non-Flash float32 score matrix. For example, at 32K context, ubatch 512, and 32 heads, the omitted score allocation alone is 2 GiB, so the training coexistence guard can admit a download whose eventual launch exhausts VRAM. Resolve the effective Flash Attention mode from the arguments/environment here and conservatively price the unknown head dimensions when it is disabled.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not changing this. The remote reserve has no header, so it does not price the KV cache either, and at 32K context that is usually a larger allocation than the score matrix. It only prices what needs no dimensions: the exact KQ mask plus an activation and vocabulary ceiling. The score matrix is ctx * ubatch * n_head * 4 bytes, so pricing it without n_head needs a head-count ceiling. Llama 3.1 405B's 128 heads would add 8 GiB at 32K/512 and refuse loads that fit. Once the file is downloaded, the local guard and the loader price Flash Attention off from the real head count. main did not price it on this path either.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d30b2c7cfc
ℹ️ About Codex in GitHub
Codex has been enabled to automatically 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 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| output_rows = min( | ||
| effective_ubatch, | ||
| max(1, n_parallel) * (1 + LlamaCppBackend._UNKNOWN_SPEC_DRAFT_N_MAX), | ||
| ) |
There was a problem hiding this comment.
Reserve all speculative verification output rows
For an uncached remote GGUF that engages speculative decoding, this reserves only n_parallel * (1 + n_max) output rows, while the newly added local estimator charges n_parallel * n_max * _SPEC_VERIFY_ROW_COPIES verification rows in addition to the normal output rows, and _SPEC_VERIFY_ROW_COPIES is 3. The min(effective_ubatch, ...) cap can undercount further because the local verification term is not capped. With multiple slots or tensor devices this can omit hundreds of MiB to several GiB from the training-coexistence guard and admit a load that exhausts VRAM after download.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
The comparison is with the loader's MTP reserve, not the training guard. The local guard (_estimate_gguf_required_gb -> _gguf_runtime_bytes) charges drafter files, KV and the compute buffer, whose output rows are min(ubatch, slots). It does not charge _mtp_draft_compute_bytes or its verification rows, and the remote guard likewise has no draft KV or MTP runtime term. On that basis the remote min(ubatch, slots * 17) rows are already above the local guard's min(ubatch, slots). Charging slots * 16 * 3 extra rows only on the remote path would make an uncached load cost more than the same load once downloaded.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: c85f3670bb
ℹ️ About Codex in GitHub
Codex has been enabled to automatically 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 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| _ubatch_for_slots(slots) if slots else _effective_ubatch, | ||
| _scratch_cache_type_kv, | ||
| layer_split = n_gpus > 1 and not _pipeline_parallel_off, | ||
| flash_attn = _launch_flash_attn, |
There was a problem hiding this comment.
Reserve the non-Flash retry's score matrix
When the initial Flash Attention launch is supported, this passes True and omits the non-Flash float32 score matrix, but the recovery path at lines 28141-28149 respawns the already-fitted command with Flash Attention disabled and without rerunning placement. The existing planned_flash_attn = False at lines 22002-22004 explicitly reserves the larger retry KV layout, so compute needs the same treatment; at 32K context, ubatch 512, and 32 heads, the omitted term is about 2 GiB per device and can turn a recoverable Flash Attention failure into an OOM.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
This boundary is intentional and listed in the PR's limitations. The KV side uses planned_flash_attn=False because the padded-V difference is small. Pricing the no-flash score matrix on every load would take about 2 GiB of context at 32K/512/32 heads, per device, to cover a recovery path that runs only after a flash-attention crash. main did not price that matrix on any path, so a respawn with Flash Attention off is no worse than before. If the respawn does not fit, the load fails with an error, and a normal launch never allocates that matrix.
|
Codex Review: Didn't find any major issues. 🎉 Reviewed commit: ℹ️ About Codex in GitHubCodex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback". |
|
Confirmed this hits the compute-buffer path in studio/backend/core/inference/llama_cpp.py that decides slots and context for every GGUF load, and the measured estimate-versus-actual tables look right. The one thing I want to settle before review is the Gemma 4 31B default moving from 1 slot at 24320 context to 3 slots at 8448, which refuses a 17k prompt that loads today: could you confirm that is the intended tradeoff rather than a planner policy we should adjust alongside the costs? |
Three conflicts, all from main landing context checkpoints and a help-text default parser next to this branch's build probe. - llama_cpp.py and routes/inference.py were additive on both sides: main's _advertised_int_default and effective_ctx_checkpoints_for_caps sit alongside this branch's probe_build_number and _ASSUMED_MAX_VOCAB. Both kept. - test_the_drafter_cache_is_priced_at_the_targets_layout needed a real resolution. Main compares GPU cache bytes, excluding the host-only kv_checkpoint_bytes, and asserts the drafter runtime equals them exactly. This branch adds the draft decode graph floor to drafter_runtime_bytes, so that equality is off by about 230 MiB. The merged test keeps main's checkpoint semantics and takes the difference between the two sides, which is what still holds once a term rides on top.
|
@codex review |
|
@codex security review |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 54ce8bd170
ℹ️ 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".
| spec_compute = self._mtp_draft_compute_bytes( | ||
| n_ctx, | ||
| drafter_path = drafter_path, | ||
| n_ubatch = n_ubatch, | ||
| n_parallel = n_parallel, |
There was a problem hiding this comment.
Price quantized draft-cache dequantization scratch
When MTP or another model-draft mode uses a quantized draft cache (through spec_draft_cache_type or draft cache flags), this call drops draft_cache_type_k and draft_cache_type_v before estimating the draft graph. Consequently, _mtp_draft_compute_bytes charges only the mask and activations, while the draft context also needs the context-linear K/V dequantization scratch that _compute_buffer_ctx_bytes accounts for on the target. At long contexts this can omit gigabytes and let the placement planner select a context that OOMs; thread the draft cache types into this helper and size the scratch using the drafter's metadata.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed, and measured. The call at llama_cpp.py:15689 passes n_ctx, drafter_path, n_ubatch, n_parallel and spec_draft_n_max only, so _mtp_draft_compute_bytes charges ub * 2 * n_ctx, the f16 mask rate, and never the context-linear dequant scratch that _compute_buffer_ctx_bytes adds for the target when the cache is quantized. The path is reachable: spec_draft_cache_type and the extras parsed by _extra_args_draft_cache_types both reach real launch flags, and those same types already size the draft KV at llama_cpp.py:23385, so the compute side is the only place they are dropped.
Sizing it against the real drafter in unsloth/gemma-4-E4B-it-GGUF (MTP/mtp-gemma-4-E4B-it-Q8_0.gguf, _attention_dequant_width 2048), the omitted term is dequant_width * 2 * n_ctx:
| context | micro-batch | charged | omitted |
|---|---|---|---|
| 32768 | 512 | 192.0 MiB | 128.0 MiB |
| 131072 | 512 | 192.0 MiB | 512.0 MiB |
| 262144 | 512 | 252.6 MiB | 1024.0 MiB |
So at long context the omission is several times the charged figure, on a path whose comment at llama_cpp.py:19565 says under-reservation is meant to OOM at startup rather than be absorbed.
Two things that bound it. It needs an explicitly selected quantized draft cache, not a default load. And it is an incomplete new term rather than a regression: main has no _mtp_draft_compute_bytes at all and charges zero draft compute, so this branch is still strictly more conservative than what it replaces. Leaving the call on how to close it to @oobabooga: threading the draft cache types through and sizing from the drafter's own metadata looks right, and listing it beside the ngram verification buffers in Remaining limitations would also be a defensible answer for this PR.
main's #11043 added `_planned_flash_attn` with two rules, one of which this branch did not have: a quantized V cache forces flash attention on, and `grok` forces it OFF, because llama.cpp will not run that architecture with it. This branch replaced the same resolution with `_planned_flash_attn_state` wrapped in `_reserved_flash_attn_state`, which is richer (the managed `--flash-attn on`, the inherited environment, the tensor-parallel upgrade, and a re-resolution after a tensor-mode downgrade) and exists so the estimate and the launch share ONE state (#9697, #10489). Neither side alone is right, so the merge keeps both. - `_architecture_forces_flash_attn_off` names main's rule once, with the upstream reference: llama-context.cpp forces flash attention off for `LLM_ARCH_GROK` at the top of `llama_init_from_model`, ABOVE both of llama.cpp's own upgrades (the `SPLIT_MODE_TENSOR` one and the quantized-V one), so nothing can put it back. `_planned_flash_attn_state` takes an `architecture` and applies it in that same position, and the post-launch `_flash_attn_enabled` readback uses the one helper rather than an inline string test. - `load_model`, `_gguf_runtime_bytes` and `GET /api/models/kv-cache-estimate` all pass the architecture they already read from the header. - The compute-buffer pricing at the `_cc_bytes` seam takes the resolved `planned_flash_attn` instead of a separately computed `_launch_flash_attn`, so a tensor-mode downgrade re-prices compute as well as KV, and one load cannot be described by two answers. `_plan_tensor_parallel` and `_tensor_split_fits_budget` pass the state they already hold down to the same term, which they were not doing. - `_planned_flash_attn` and `_launch_flash_attn` are gone; the rules they carried are not. Two collisions git could not see: - `test_the_loader_prices_the_attention_mode_it_launches` asserted `False in calls["kv"]`, which pins the unconditional no-flash KV reserve this branch removes on purpose. It now asserts that the KV cache and the compute buffers are priced with the same resolved state, which is the contract that replaced it. - `test_the_state_is_still_named_planned_flash_attn` pins the identifier, so the resolved state keeps its name. New: `studio/backend/tests/test_grok_flash_attn_exception.py`, 26 tests that fail if the Grok rule is lost and if either sizing seam stops reading the one resolved state. studio/backend/tests: 5552 passed, 59 skipped, 1 failed. The failure, `test_offload_planner_seam.py::test_oversubscribed_decode_threads_decline_spill_planning`, fails identically on origin/main f6cf06d and depends on the host CPU count.
….cpp allocates (unslothai#11043) * Studio: price GGUF compute buffers from what llama.cpp reserves * Replicate the remote compute reserve's output rows across tensor devices * Resolve planned Flash Attention in launch argument order * Reprice the layer-split step for each candidate slot count * Keep target verification rows when the drafter runs on CPU * Price Grok without Flash Attention --------- Co-authored-by: danielhanchen <[email protected]>
Studio uses memory estimates to decide how much context a GGUF model can fit on the GPU. The current formula often overestimates the temporary working memory that llama-server needs, and underestimates it in some configurations. This PR brings those estimates closer to the buffers llama-server actually reserves.
The mismatch came up in #10683: increasing the vision micro-batch size cost about 1.1 GiB on the GPU, while Studio estimated an extra 2.5 GiB.
Before and after in Studio
I loaded the same models through main and this branch on a 24 GB RTX 3090. The table shows both what Studio chose to load and how its compute-buffer estimate compared with llama-server's allocation.
A slot serves one request at a time. Context is the token capacity. MTP uses a draft model or prediction head to speed up generation. The last two columns show estimated / actually reserved compute and draft-buffer memory, in MiB.
Each estimate uses that side's launched settings, so the actual buffer sizes can differ too. These are compute-buffer figures, not total GPU memory.
The context tradeoff matters: Gemma 4 31B now keeps three slots instead of one, leaving less memory for context. A 17k-token prompt that main accepted is refused with the new default load. The planner still prioritizes the most slots that fit at its minimum context, then increases context with the remaining memory. This PR changes the costs it uses, not that policy.
The Gemma loads answered a 1400x1400 image. Every load answered a 17k-token prompt (34k for Qwen3 8B) where its context allowed, and llama-server stayed up throughout.
What changes
The old estimate treated several buffers as much larger than they are and missed others. The fix covers:
The loader and memory panel share the estimator. Missing metadata uses fallback dimensions, and a cached
llama-server --versioncheck handles older output-buffer behavior, including the b9415 macOS fallback. The existing DeepSeek4 and Inkling attention rates are unchanged.How close are the estimates?
I measured llama-server's
compute buffer sizelogs on b10909 using an RTX 6000 Ada and RTX 3090, across 17 models and different context lengths, slot counts, micro-batch sizes and cache types.The ratios below compare the estimate with the actual reserved buffer: 1x is exact, 2x means twice as much memory was estimated. An underestimate means the estimate was smaller than the allocation.
The additional models caught two metadata cases that are fixed here: Phi-4-mini's sliding window exceeds its context, and Granite stores its expert width under a different field. Some overestimation remains because buffers that peak at different times are counted together.
Further measurements covered Flash Attention off (66 configurations, estimates 1.01x to 1.35x actual), two-GPU splits (48 configurations, 1.00x to 1.36x per device), and MTP draft buffers (29 configurations, all covered). On b9415 Vulkan, Gemma 4 E2B reserved 2704 MiB and was estimated at 2896 MiB.
Remaining limitations
Verification
tests/studio/test_llama_cpp_mmproj_batch.py: 63 passed.Before and after in the memory panel
unsloth/Qwen3.5-2B-MTP-GGUFQ4_K_M, shot on two isolated installs built from this branch and from its merge base, at the same default load settings on both sides (Auto context, 262,144 tokens, 4 slots).Weights and KV cache are unchanged, which is what makes the pair readable: only the compute term this PR rewrites moves. Recomputing the same settings through
_gguf_memory_breakdownon both trees agrees to the digit (compute 2.027 to 0.310 GiB, total 6.341 to 4.624 GiB).