Repository navigation
studio: deterministic VRAM auto-fit for GGUF (MTP reserve, compute buffer, total-based budget) - #6312
Conversation
Auto-fit advertised a context (for example ~110k for the Qwen3.6-27B MTP GGUF) that fit on paper but OOMed mid-generation or during tool calls once MTP speculative decoding was active. The MTP draft path's VRAM was reserved as a flat 5% of total VRAM, which tracks neither of the two real costs: the MTP head keeps its own attention KV cache that grows with context, and the speculative verification buffer grows with --spec-draft-n-max. On the hybrid Mamba/attention Qwen3.6 models the main KV is small, so auto-fit happily kept a near-native context while the draft path pushed the load over budget at runtime. Replace the flat fraction with a byte-accurate, context- and n_max-aware reserve sized from GGUF dims: draft KV from nextn_predict_layers and the attention dims at f16 (llama.cpp's MTP draft context uses f16 KV regardless of the main cache type), plus a verify buffer per embedding-unit per draft token. The reserve is evaluated per candidate context inside the fit binary search and added to every pin/fit check, including the tensor-parallel planner and its even-split decision. Coefficients were calibrated against llama-server VRAM measurements on the Qwen3.6-27B MTP GGUF (RMS 14 MiB). The flat fraction remains as a fallback when GGUF dims are unavailable, so non-MTP loads are unchanged. The budget now also engages when the user wires MTP through extra args (--spec-type draft-mtp, including chains), reads the effective draft depth from --spec-draft-n-max or the legacy --draft-max with extras taking precedence over the first-class field, reserves a separate drafter's weights when supplied via --model-draft/--spec-draft-model/-md, and mirrors _build_speculative_flags so it never reserves for MTP the launch resolver will not emit (needs a head/drafter and a binary that supports --spec-type mtp). Adds tests/test_mtp_vram_budget.py.
There was a problem hiding this comment.
Code Review
This pull request replaces the flat 5% VRAM reservation fallback for Multi-Token Prediction (MTP) with a byte-accurate, context-aware overhead estimation. It introduces calculations for the MTP head's draft KV cache (which scales with context length) and speculative verification buffers (which scale with draft depth), falling back to the flat fraction only when GGUF dimensions are unavailable. The context auto-fitting, tensor parallel planning, and GPU selection logic are updated to evaluate this dynamic overhead per candidate context. Additionally, a comprehensive suite of unit tests is added to verify these calculations and prevent out-of-memory (OOM) regressions. There are no review comments, so no feedback is provided.
Important
The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.
Build on the byte-accurate MTP reserve with three changes that make the
GGUF auto-fit budget deterministic across architectures and recover usable
context, especially for MTP models on a single tight card.
1. Total-based budget. Cap GPU occupancy at a fraction of TOTAL VRAM rather
than a fraction of FREE VRAM, and raise the fraction from 0.90 to 0.95:
budget = free - (1 - 0.95) * total (per GPU, summed for a pool)
The reserve is now absolute (a fixed slice of the card) instead of
shrinking as the GPU fills, so a partly-used GPU keeps a constant cushion
for compute/CUDA/verify buffers instead of over-promising context and
spilling to CPU at runtime. _get_gpu_memory() reads memory.total alongside
memory.free; _fit_context_to_vram, _select_gpus and the load_model pool
loops thread the totals through. Multi-GPU layer-split pools
sum(free_i - 0.05*total_i); tensor mode reserves per device.
2. Deterministic compute-graph buffer. Replace the flat 5 GB/device tensor
reserve (a magic constant that over-reserved about 8x on a 27B model) with
_estimate_compute_buffer_bytes, sized from GGUF dims and the launch flags:
out = n_vocab * n_ubatch * 4 # vocab-width output buffer
act = 4 * n_embd * n_ubatch * 4 # activation scratch
pipeline_per_device = act + out * (n_parallel - 1)
tensor_per_device = 2*act + out * n_parallel
The buffer is context-independent and scales with --parallel (serving
slots), not with how the model is split across GPUs. It is now reserved in
BOTH multi-GPU paths (layer split folds one buffer into the pooled
footprint; tensor mode reserves it per device). The flat 5 GB stays only as
a fallback when vocab/embedding dims are unavailable. Calibrated against
llama-server measurements (parallel 1/2/4/8 give 36/492/1388/3220 MiB on a
single GPU; about 600 MiB/device tensor); the estimate is a small upper
bound.
3. GGUF parsing. Read vocab size (tokenizer tokens array length) and
feed_forward_length for the compute-buffer estimate.
Effect on the Qwen3.6-27B MTP Q6_K case (MTP on): a single 32 GB card at
about 31 GB free advertises f16 23k to 64k, q8_0 44k to 115k, q4_0 82k to
200k; 2x 24 GB tensor mode recovers the full 262k window for f16 (was about
134k). Validated on hardware: 1x 32 GB f16 at 64768 loads at 29.3 GB / 120
t/s; 2x 23 GB tensor f16 at 262144 loads at 22.2 GB/device / 98 t/s; both
within 0.4% of the estimate. Adds test_compute_buffer.py and updates the
KV/context-fit/MTP-budget tests for the 0.95 constant and the new budget.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 253231b0cf
ℹ️ 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 draft_kv is None: | ||
| return None | ||
| return draft_kv + max(0, draft_weights_bytes) |
There was a problem hiding this comment.
Account for draft depth in MTP reserve
When a load sets a larger spec_draft_n_max via the API or --spec-draft-n-max, the verifier buffer grows with that draft depth, but this return value is only draft KV plus drafter weights, so every n_max gets the same fit/pin budget. That can still advertise and pin a context that fits at the default draft depth but OOMs as soon as speculative decoding allocates the larger verifier buffer.
Useful? React with 👍 / 👎.
| db = self._draft_backend_for(drafter_path) | ||
| if db is None or not db._can_estimate_kv(): | ||
| return None | ||
| kv = db._estimate_kv_cache_bytes(n_ctx, draft_cache_type) |
There was a problem hiding this comment.
Pass serving slot count to drafter KV estimate
For a separate drafter with sliding-window layers (for example Gemma-style drafters) and n_parallel > 1, this call uses _estimate_kv_cache_bytes with its default n_parallel=1. The main KV estimator explicitly scales SWA cache by the serving slot count, so the drafter reserve undercounts the extra per-slot SWA KV and auto-fit/tensor planning can choose a context that does not leave enough VRAM for the actual drafter cache.
Useful? React with 👍 / 👎.
| if _usable(ranked[0][0], ranked[0][1]) >= model_size_mib: | ||
| return [ranked[0][0]], False |
There was a problem hiding this comment.
Try the largest usable GPU before expanding
With total_by_idx set, _usable() subtracts headroom based on total VRAM, so the GPU with the most free MiB is not necessarily the GPU with the most usable MiB. On mixed or partly occupied cards, this only tests the free-ranked first GPU for a single-GPU fit and can return a multi-GPU/--fit plan even when a slightly lower-free GPU would fit alone, unnecessarily slowing or offloading the load.
Useful? React with 👍 / 👎.
| "--cache-type-v-draft", | ||
| "--spec-draft-type-v", | ||
| "-ctvd", |
There was a problem hiding this comment.
Keep draft K and V cache types separate
llama.cpp exposes separate draft-cache flags for K and V, both defaulting to f16. Including the V-only aliases in this single found value means an extra arg like --cache-type-v-draft q4_0 makes the reserve price both K and V as q4_0 even though K remains f16, under-reserving roughly the K half of the draft KV cache at long context.
Useful? React with 👍 / 👎.
| _compute_buffer_pipeline = self._estimate_compute_buffer_bytes( | ||
| n_parallel = n_parallel, per_device_tensor = False | ||
| ) |
There was a problem hiding this comment.
Parse user ubatch overrides before sizing buffers
-ub/--ubatch-size is an allowed llama-server pass-through arg and is appended after Studio's flags, but this estimate always uses the default 512 micro-batch. If a user raises --ubatch-size for faster prompt processing, llama-server allocates a much larger compute graph than the fit/pin budget reserved here (and in the tensor reserve below), so Studio can still pick a context/GPU set that OOMs at startup.
Useful? React with 👍 / 👎.
Condense the docstrings and inline comments added by this PR (internal backend helpers): drop restated-signature docstrings, fold multi-line block comments to one or two lines, and remove notes that just repeat the code. No behavior change (AST-verified comment/docstring-only via comment_tools.py); the backend test suite is unchanged and green.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 39845ad69a
ℹ️ 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".
| reserve_mib = ( | ||
| _reserve_bytes // (1024 * 1024) | ||
| if _reserve_bytes > 0 | ||
| else self._TENSOR_PARALLEL_BUFFER_RESERVE_MIB |
There was a problem hiding this comment.
Reserve total-VRAM headroom in tensor planning
In the tensor-parallel path, when GGUF dims are available this replaces the old 5 GiB per-device reserve with only the estimated compute buffer (the new tests anchor this at ~600 MiB/device for Qwen), but _plan_tensor_parallel then budgets the entire remaining pool for weights+KV. Unlike the non-tensor branches, this leaves no 5% total-VRAM headroom for CUDA context/allocator slack, so a tensor load whose model+KV fits only in the last few percent of VRAM can still be selected with use_fit=False even though llama.cpp cannot shrink tensor-mode loads and may OOM at startup.
Useful? React with 👍 / 👎.
| _mtp_eff_n_max = 2 if gpus else 3 | ||
| # Separate-drafter weights live on GPU too (an embedded head is | ||
| # already in model_size). | ||
| _mtp_draft_for_budget = mtp_draft_path or _extra_args_mtp_draft_path(extra_args) |
There was a problem hiding this comment.
Budget the drafter that will actually be launched
When Studio auto-resolves mtp_draft_path and the user also passes a custom --model-draft/-md in extra_args, the custom flag is appended last and overrides the auto drafter at launch, but this or budgets the auto path instead. If the user-selected drafter is larger or has a larger KV cache (for example an F16 copy under MTP/), auto-fit can pin a context/GPU set that only fits the smaller auto drafter and then OOM when llama-server loads the overridden drafter.
Useful? React with 👍 / 👎.
|
/gemini review |
There was a problem hiding this comment.
Code Review
This pull request replaces flat, conservative VRAM reserves for Multi-Token Prediction (MTP) and tensor-parallel compute buffers with dynamic, byte-accurate estimates derived from GGUF metadata dimensions (such as vocabulary size, embedding length, and draft layers). It also updates GPU memory queries to retrieve total VRAM, enabling absolute headroom capping, and adds comprehensive unit tests to validate these calculations. The review feedback suggests a valuable performance optimization during GGUF metadata parsing: instead of reading the entire large tokenizer.ggml.tokens array into memory via _gguf_read_array_value just to get its length, the code should fast-skip the string array directly in the file stream to avoid significant overhead.
Important
The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.
| # Vocab size = token count; keep the length, not the strings. | ||
| if key == "tokenizer.ggml.tokens": | ||
| self._vocab_size = int(alen) | ||
| val_a = self._gguf_read_array_value(f, atype, alen) |
There was a problem hiding this comment.
Since tokenizer.ggml.tokens is a very large array of strings (often containing 256,000+ tokens), calling _gguf_read_array_value will loop through all elements and call _gguf_skip_value for each one. This introduces significant Python-level function call and dictionary lookup overhead, which can slow down metadata parsing by several hundred milliseconds on every model load.
Since we only need the array length (alen) to determine the vocabulary size, we can fast-skip the string array directly inside _read_gguf_metadata and continue the loop, avoiding the overhead of _gguf_read_array_value entirely.
# Vocab size = token count; keep the length, not the strings.
if key == 'tokenizer.ggml.tokens':
self._vocab_size = int(alen)
for _ in range(alen):
slen = struct.unpack('<Q', f.read(8))[0]
f.seek(slen, 1)
continue
val_a = self._gguf_read_array_value(f, atype, alen)Five fixes from a parallel-reviewer pass on this PR; all confirmed against the real functions and covered by new tests. - Tensor mode now honors the total-based VRAM cap. _plan_tensor_parallel took total_by_idx and budgets each GPU at free - (1-frac)*total, mirroring the layer-split paths; previously it fit against raw free and could spend the 5% safety cushion on a partly-used multi-GPU box (reproduced ~3.3 GB over). - Draft K and V cache types are parsed and accounted independently. A one-sided override (e.g. --cache-type-k-draft q4_0, V left f16) no longer applies the small quant to both axes and under-reserves the f16 axis. The embedded-head formula sizes per axis; the separate-drafter path uses the heavier type so it never under-reserves. - The compute-graph buffer honors a user --ubatch / --ubatch-size / -ub override (parsed and threaded into every _estimate_compute_buffer_bytes call and the tensor planner); it previously always assumed the 512 default, under-reserving up to ~8x at --ubatch 4096. - GPU ranking uses the usable budget (free - (1-frac)*total) instead of raw free in _select_gpus and both auto-context subset loops, so a more-used large card no longer outranks a less-used small card that has more usable room. Adds regression tests for each (tensor total cap, ubatch reserve scaling, split K/V no-under-reserve, --ubatch parser, usable-ranking GPU selection). Full targeted backend suite green (321 passed).
The tensor-parallel GPU admission filters still used raw free VRAM after the total-based budget landed, an asymmetric fix: a partly-used large card can clear the per-device compute-buffer reserve on raw free while its usable budget (free - (1-frac)*total) does not, so the planner admitted it and the even split could emit a near-zero weight slice for a GPU that should have been excluded. - _plan_tensor_parallel: admit GPUs by usable budget, not raw free (move the _usable helper above the filter). - load_model: admit the tensor set by _gpu_usable, and downgrade to layer split when the pooled usable budget cannot hold weights plus per-device compute buffers (the planner can only floor the context, not stop an overcommitted launch). Adds regression tests: planner drops a GPU whose usable budget is below the reserve, and a source-level check that load_model admits on the usable budget and carries the pooled-weight downgrade.
A user --model-draft passed in extra_args is appended last and wins at the llama-server launch, but the VRAM budget preferred Studio's auto-detected drafter (mtp_draft_path or extras), so a larger custom drafter was under-reserved. Flip the precedence to extras-first, matching the draft-depth (n_max) resolution two lines above. Adds a source-level regression test.
VRAM auto-fit: before vs after (measured)Test model: The change replaces the old free-VRAM fraction ( 1. Advertised context recovered (single GPU)UI context ceiling chosen by the auto-fit for the model above on a 32 GB card, by free VRAM and main KV type. Numbers are the actual
The gain grows as free VRAM tightens: the old fraction wasted more of the cushion exactly where weights already dominate. 2. Validated on real hardware (B200, capped to the stated budget)Each row is a real llama-server load plus a 256-token generation; VRAM is per-PID.
The after-PR f16 ceiling at ~32 GB free (78848) sits safely under the measured on-GPU max (98k loads at 31312 MiB), and the empirical points match the estimator within 0.1% at 64768 (predicted vs 29348 MiB measured). The 28 GB rows reproduce the reported symptom: losing ~4 GB of free VRAM turns a 98k load from 103 to 46 t/s as KV offloads to CPU. The cause was free-VRAM pressure, not the Studio or llama.cpp version (verified: Studio launch code is byte-identical across the reported versions, and b9496/b9510/b9518/b9585/b9625 all engage MTP identically). 3. The MTP reserve is now byte-accurateDraft-KV reserve sized from the model's
vs the old flat 5% of free, which under low free VRAM let the advertised full context silently offload to CPU. The reserve also splits draft K and V cache types independently and honors a user 4. Multi-GPUBoth split paths now budget against the same total-based usable VRAM (
Recommendation surfaced by the studyKeep MTP on (~1 GB, ~1.6x speed). The largest single lever for context on a fixed card is quantizing the main KV cache: |
|
I believe this issue is likely to be resolved by this: https://www.reddit.com/r/unsloth/comments/1u59lcz/running_into_issues_with_latest_update/ |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: a19ba2c995
ℹ️ 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".
| _tp_weight_budget_mib = ( | ||
| sum(_gpu_usable(g) for g in tp_gpus) - len(tp_gpus) * reserve_mib | ||
| ) | ||
| if _tp_weight_budget_mib <= model_size / (1024 * 1024): |
There was a problem hiding this comment.
Include MTP reserve in tensor fallback check
When tensor parallelism is requested for an MTP load with a separate drafter or other byte-accurate MTP reserve, this guard only checks that the main model weights fit after the per-device compute buffers. _plan_tensor_parallel can only shrink context to a floor and the caller then sets use_fit=False, so a pool where the main weights barely fit but drafter weights plus minimum draft KV do not will still launch --split-mode tensor and OOM instead of taking the intended layer-split fallback.
Useful? React with 👍 / 👎.
Two issues found by re-review of the prior fix: - The tensor-parallel capacity gate only checked the model weights against the pooled budget, not the MTP reserve. A separate-drafter MTP load whose weights fit but weights + drafter do not could still launch overcommitted in tensor mode. Add the non-shrinkable MTP reserve (drafter weights + floor draft KV, or the flat 2 GiB fallback when dims are unavailable) to the gate. - The nvidia-smi probe was switched to a three-column query (index,free,total) for the total-based budget but required exactly three columns, so a driver or mock returning the legacy two-column "index,free" was dropped and the probe fell through to the real GPUs. Accept two columns (total 0) and treat an unknown total as the legacy free*fraction in _select_gpus. Tests: tensor gate asserts the MTP term is included; _get_gpu_memory parses both two- and three-column output; the existing two-column GPU-detection mocks pass again.
On a restart the constructor reaps the previous run's orphaned llama-server, but the driver does not reclaim that VRAM synchronously. _kill_orphaned_servers now returns the number of processes it killed, and __init__ arms _last_kill_monotonic when that count is positive, so the first load_model waits for VRAM to settle before ranking GPUs by free memory instead of pinning the model onto the smaller card. The compute-graph / auto-fit reserve is handled separately in #6312.
…unknown _plan_tensor_parallel fell back to raw free VRAM when a GPU's total was unavailable (a two-column nvidia-smi probe reporting total 0), while _select_gpus and the load_model ranking both fall back to free*fraction. That let tensor planning spend the 5% cushion the rest of the fit preserves and over-advertise context in exactly that path. Align the fallback to free*_CTX_FIT_VRAM_FRACTION. Updates the no-totals planner test expectations (now free*frac) and adds a regression test that total 0 keeps the cushion.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 8ee8fb68c8
ℹ️ 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".
| ) | ||
| else: | ||
| _tp_mtp_floor = 2 * 1024**3 # flat reserve when dims unavailable | ||
| _tp_required_mib = (model_size + _tp_mtp_floor) / (1024 * 1024) |
There was a problem hiding this comment.
Include floor KV in tensor fallback gate
When --split-mode tensor is requested on a pool that has room for the weights (and _tp_mtp_floor) but not for the mandatory 2048-token main KV floor, this guard passes because _tp_required_mib excludes the main model KV. _plan_tensor_parallel then clamps the context to 2048 and the caller launches with use_fit=False, so llama.cpp still has to allocate that KV in tensor mode and can OOM instead of taking the layer-split fallback.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 144f9939a0
ℹ️ 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".
| found: Optional[str] = None | ||
| for i, raw in enumerate(args): | ||
| flag, eq, inline = raw.partition("=") | ||
| if flag not in ("--model-draft", "--spec-draft-model", "-md"): |
There was a problem hiding this comment.
Budget HF draft model overrides
When users pass a draft model via extra args using the HF draft flags, this parser returns None because it only recognizes local --model-draft aliases. I checked llama-server help, which lists --spec-draft-hf, -hfd, -hfrd, and --hf-repo-draft as the draft-model repository flags (https://manpages.debian.org/unstable/llama.cpp-tools/llama-server.1.en.html), and these extra args are appended last at launch; for --spec-type draft-mtp --spec-draft-hf big/repo:Q8_0, the fit budget sizes the embedded/auto drafter instead of the actual HF draft weights/KV, so Studio can pin a context/GPU set that OOMs when llama-server downloads and loads the overridden drafter.
Useful? React with 👍 / 👎.
|
|
||
| # Effective micro-batch (a user --ubatch override scales the | ||
| # compute buffer); None -> the 512 default in the estimate. | ||
| _effective_ubatch = _extra_args_n_ubatch(extra_args) |
There was a problem hiding this comment.
Honor LLAMA_ARG_UBATCH in buffer sizing
When Studio is launched with LLAMA_ARG_UBATCH in its environment, child_env_without_native_path_secret() preserves that env for llama-server and llama-server documents it as the env override for -ub, --ubatch-size (https://manpages.debian.org/unstable/llama.cpp-tools/llama-server.1.en.html). This only reads extra_args, so a service-level LLAMA_ARG_UBATCH=4096 still sizes the compute buffer at the 512 default while the child allocates the larger graph, allowing auto-fit to pin a context/GPU set that can OOM at startup.
Useful? React with 👍 / 👎.
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
|
Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits. |
A second review pass found the env-aware tensor/MTP handling was applied asymmetrically: some paths inherited LLAMA_ARG_* env, others didn't. Three real follow-ups, plus a small consolidation so the env semantics live in one place. 1. Tensor fallback ignored the inherited tensor env. load_with_tensor_fallback computed its retry gate with the env-blind resolve_tensor_parallel, so an env-only tensor load (toggle off, no --split-mode extra) that crashed on a tensor-incompatible GGUF re-raised instead of retrying layer split. It now uses the env-aware decision; and since the inherited env would otherwise re-engage tensor on the retry (CLI args persist, the env does too), the retry forces --split-mode layer (CLI wins over env) so it can't re-crash. 2. Duplicate-load matchers looped reloads after a tensor->layer downgrade. Both matchers compared the env-expanded tensor decision against the loaded server, but load_model may downgrade tensor to layer (capacity/buffer) and scrub the child env. The still-set parent env then made every identical request look like a mismatch, killing and reloading a healthy layer server. Add _tensor_parallel_matches_loaded, which only lets an inherited tensor env raise a match against a server that actually launched tensor; a downgraded server matches the same request (an identical load would downgrade the same way). 3. MTP binary-capability fallback leaked an inherited LLAMA_ARG_SPEC_TYPE. When the binary lacks MTP, _emit_mtp degraded but emitted no spec flag, so an inherited LLAMA_ARG_SPEC_TYPE=draft-mtp still reached the child and attempted MTP the gate had budgeted off. It now emits --spec-default (CLI wins over env) like the sibling no-head / non-MTP fallbacks. Consolidation: moved _env_split_mode_is_tensor / _effective_tensor_parallel into llama_server_args.py (with the new _tensor_parallel_matches_loaded) so the lightweight tensor_fallback module can share them without importing llama_cpp; llama_cpp re-exports them for back-compat. All gated on inherited env the documented benchmarks don't set; the single-GPU, tensor and pipeline reconfirm numbers are byte-identical, and the full backend suite passes (883) with regression tests for each fix.
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
|
Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits. |
A review pass found the explicit-extras counterpart of the env cache-type fix. load_model adopts the heavier inherited LLAMA_ARG_CACHE_TYPE_K/_V env for the reserve, but the explicit-extras path used resolve_cache_type_kv, which collapses both axes to one last-wins value. So extras such as --cache-type-k f32 --cache-type-v f16 (lighter axis last) budgeted f16 for both axes while the child allocates f32 on K, over-advertising context and re-opening the OOM path this PR closes. Add parse_cache_override_per_axis (keeps the K/V last-wins values apart) and _extra_args_main_cache_type_for_budget (the heavier of the two by bytes/elem), and budget from it. The user's extras are appended last and win per axis at the child, so this only raises the reserve; the emitted command and the asymmetric child cache are unchanged, and the common single-axis / symmetric cases resolve to the same type as before. Reconfirm numbers (single-GPU table, tensor, pipeline) are byte-identical, and the full backend suite passes (892) with per-axis parser and heavier-axis budget regression tests.
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
|
Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits. |
…ctors A review pass found two more env/extras edge cases on the speculative and tensor cache paths. Tensor-safety could miss a quantized axis. The previous change budgets the heavier-by-bytes cache type, but that masks a quantized axis paired with a heavier one: --cache-type-k f16 --cache-type-v q4_0 resolves to f16, so the tensor-safety block did not fire and the q4_0 axis survived into tensor mode, which aborts on quantized KV. Test each explicit --cache-type-k/-v axis (not just the budget type) so any quantized axis drops the cache for the tensor attempt. Inherited HF drafter selectors were not stripped. _extra_args_mtp_draft_path treats --spec-draft-hf / -hfd / -hfrd / --hf-repo-draft as drafter selectors, but _SPEC_FLAGS only stripped the local --model-draft selectors, so on an inherited- extras Apply a stale HF drafter survived and last-wins-overrode Studio's re-derived spec choice. Add the HF aliases to _SPEC_FLAGS. The per-drafter tuning knobs (--spec-draft-type-*, -ngld, --spec-draft-device) are intentionally left in place: the VRAM budget reads them via the same parsers the child honors, so they stay consistent on inherit, and stripping them would silently move a CPU-offloaded drafter back onto the GPU. A third flagged item -- that the HF draft env var should be LLAMA_ARG_HFD_REPO -- was a false positive from a stale manpage; the bundled binary's common/arg.cpp sets LLAMA_ARG_SPEC_DRAFT_HF_REPO for --spec-draft-hf, which the code already uses, so it is left unchanged. Reconfirm numbers (single-GPU table, tensor, pipeline) are byte-identical, and the full backend suite passes (899) with regression tests for both fixes.
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
|
Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits. |
…after reserve A review pass found two more tensor-path edges, one a regression from the per-axis cache change. Tensor-to-layer downgrade collapsed asymmetric cache extras. The per-axis tensor-safety check strips an asymmetric --cache-type-k/-v (tensor rejects quantized KV), but the downgrade restored only the scalar heavier type, so a layer fallback silently rewrote --cache-type-k q4_0 --cache-type-v f16 to symmetric f16/f16 even though layer split supports the original. Save the original extras before the tensor strip and restore them verbatim (minus the user --split-mode) on both downgrade points; the budget still uses the heavier scalar, the child gets the real asymmetric cache. Before the per-axis change this case happened to survive (last-wins was f16, untouched), so this restores that. Tensor mode reserved GPU VRAM for a CPU-offloaded drafter. The layer path drops the flat MTP reserve when the only drafter is a separate CPU one with no embedded head, but the tensor capacity gate and planner still charged it, under-advertising context. Gate the tensor reserve on the same condition via _mtp_reserves_gpu. Reconfirm numbers (single-GPU table, tensor, pipeline) are byte-identical (both fixes are gated on conditions the benchmarks don't hit), and the full backend suite passes (901) with regression tests for each.
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
The refactor re-pointed load_model and the matchers off resolve_tensor_parallel / resolve_cache_type_kv and moved the env split-mode helper into llama_server_args, leaving those three names imported but unused in llama_cpp. The repo's import-hoist safety-net lint blocks that, so drop them; the env split-mode test now imports _env_split_mode_is_tensor from its real home (llama_server_args).
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
Bring the branch up to date with main so the import-hoist lint diffs against a current base (clears the stale-base false-positive on main's scan_packages.py urllib import, which this branch never touched).
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
…GLM-5.2 OOM) (#6447) * Studio: reserve the duplicated MTP target KV context for MLA models GLM-5.2 UD-IQ1_S advertised its native 1,048,576-token context, loaded, then crashed cublasCreate on the first generation with "CUDA error: the resource allocation failed" on a 2x B200 box. The model loaded fine; the decode OOMed. Cause: when MTP speculative decoding is engaged, llama.cpp keeps a second full copy of the target model's KV context for draft verification (ctx_tgt=yes in the spec log), at f16. On an MLA model that copy is ~the main KV again -- for GLM-5.2 at 1M ctx llama.cpp sized it at ~97.5 GiB -- but the auto-fit reserve only counted the tiny embedded draft head (~2 GiB), 46x too low. So weights (~202 GiB) + main KV (~83 GiB) + a 2 GiB reserve looked like it fit in 2x182 GiB, when the real footprint with the ~97 GiB MTP copy is ~382 GiB and overruns the cards. Disabling speculative decoding removed the copy and the same context ran fine. _estimate_mtp_overhead_bytes now adds the duplicated target context (the main KV re-estimated at f16) for MLA models, so auto-fit backs the context off (or selects more GPUs) instead of advertising one that OOMs. It is gated strictly on MLA (kv_lora_rank present), which is exactly the family that keeps the extra copy (GLM-5.x, DeepSeek, Kimi-K2); non-MLA MTP (Qwen, Gemma) is byte-for-byte unchanged. The reserve stays deterministic from GGUF dims, matching #6312. test_mtp_mla_target_ctx.py covers it: the MLA reserve includes the f16 target copy and dominates the draft head, the copy is f16 regardless of the main cache type and scales with context, non-MLA embedded heads keep overhead == draft KV, and _fit_context_to_vram on the GLM-5.2 / 2x B200 budget now returns a context below the requested 1M where the old draft-only reserve kept the full 1M. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Studio: stub structlog/loggers in MTP-MLA test so it is import-order-independent The new test imports core.inference.llama_cpp, which pulls in orchestrator -> structlog. In the lightweight test env structlog is absent, so when this file is collected before test_mtp_vram_budget.py (it sorts first) or run directly, collection aborted with ModuleNotFoundError. Install the same loggers/structlog (+ conditional httpx) stubs the sibling MTP tests use before the import, matching the established per-file convention. --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
…#6449) _estimate_mtp_overhead_bytes is also reached for the separate-drafter spec modes (draft-simple / draft-eagle3) through _user_draft_via_extras. Those modes load a small distinct drafter with its own KV -- already counted in the draft KV + weights -- and keep no duplicated full target context; only MTP runs a second context over the target model's own KV geometry (llama.cpp ctx_tgt). Charging the ~main-KV-sized f16 copy there over-reserved by tens of GiB on an MLA model and needlessly shrank the advertised context, the same under-advertising #6312 set out to fix. Thread mtp_keeps_target_ctx through _estimate_mtp_overhead_bytes (True for MTP, False for separate-drafter modes) and derive _engaged_is_mtp at the fit call site so the target copy is added only when the engaged mode is actually MTP. MLA + MTP (GLM-5.2 / DeepSeek / Kimi) is unchanged, so the GLM-5.2 OOM fix is preserved; non-MLA and the draft-simple / draft-eagle3 paths no longer pay the copy. test_mtp_mla_target_ctx.py adds a case asserting the separate-drafter reserve collapses to the draft KV (no target copy) while the default MTP path keeps it.
Summary
Studio's GGUF auto-fit could advertise a context (for example ~110k for the Qwen3.6-27B MTP GGUF) that fit on paper but then OOMed mid-generation, or it left a lot of context on the table on a partly-used or multi-GPU box. This makes the auto-fit budget deterministic from GGUF dims and the launch flags, so the chosen
-cactually holds at runtime and uses the card fully.Three changes, each replacing a magic constant with a value derived from the model and the hardware:
1. Byte-accurate MTP draft reserve
The MTP draft reserve was a flat 5% of total VRAM. That tracks neither real cost: the MTP head keeps its own attention KV cache that grows with context (and on the hybrid Mamba/attention Qwen3.6 models the main KV is small, so auto-fit kept a near-native context while the draft KV scaled), and a separate drafter (Gemma) keeps its own weights on GPU.
The reserve is now sized from GGUF dims and evaluated per candidate context inside the fit binary search:
nextn_predict_layers) and Gemma's separate drafter GGUF (sized from the drafter's own dims and weights).--cache-type-k/v). An explicit--cache-type-k-draft/--spec-draft-type-krecomputes it, but the embedded single-layer head floors a quantized draft type at f16: llama.cpp cannot amortize quantized-KV overhead over one layer, so a quantized draft KV fits less context than f16 there, not more (Qwen3.6 + MTP: Calculated context size is smaller when I use `--spec-draft-type-* q4_0`. is this normal? ggml-org/llama.cpp#24102). A full separate drafter still uses its real type.Measured draft KV (27B MTP, nextn=1) is 64 / 256 / 512 MiB at 16k / 65k / 131k; the deterministic estimate matches within 2 MiB.
2. Total-based VRAM budget (0.95)
Cap GPU occupancy at a fraction of TOTAL VRAM rather than a fraction of FREE VRAM, and raise the fraction from 0.90 to 0.95:
freealready excludes other processes, so this is exactly0.95 * total - used. The reserve is now absolute (a fixed slice of the card) instead of shrinking as the GPU fills, so a partly-used GPU keeps a constant cushion for compute/CUDA/verify buffers instead of over-promising context and offloading to CPU at runtime._get_gpu_memory()readsmemory.totalalongsidememory.free;_fit_context_to_vram,_select_gpus, and theload_modelpool loops thread the totals through.Multi-GPU is handled on both axes. Layer split (the default, pipeline parallel) prefers the fewest GPUs that fit and pools
sum(free_i - 0.05 * total_i). Tensor parallel (--split-mode tensor, opt-in) reserves the compute buffer per device and weights--tensor-splitbyfree - buffer.3. Deterministic compute-graph buffer
The tensor path reserved a flat 5 GB/device (
_TENSOR_PARALLEL_BUFFER_RESERVE_MIB), which over-reserved about 8x on a 27B model; the layer-split path reserved nothing. Both now use a deterministic estimate from GGUF dims and the launch flags:The buffer is context-independent and scales with
--parallel(concurrent serving slots), a separate axis from how the model is split across GPUs.--kv-unifiedis memory-neutral (it changes window semantics, not total VRAM) and is emitted only when slots > 1, matching how the budget is computed. Vocab size (tokenizer tokens array length) andfeed_forward_lengthare now parsed from the GGUF for this. The flat 5 GB stays only as a fallback when dims are unavailable.Measured compute buffer (27B MTP, vocab 248320): single-GPU serving slots 1/2/4/8 give 36 / 492 / 1388 / 3220 MiB; tensor mode about 600 MiB/device. The estimate is a small upper bound over each point.
A layer split also pays a fixed per-device overhead (CUDA context + per-device scratch) on every participating GPU, separate from that slot-scaling buffer. Measured on the 27B GGUF, layer-split total VRAM grows about 0.9 GB per extra GPU (≈ +894 MiB at
--parallel 8, +946 MiB at--parallel 1; ~linear to +2.6 GB at 4 GPUs), independent of--parallel. The fit reserves(GPUs - 1) * _PIPELINE_PER_DEVICE_OVERHEAD_MIBso a tight multi-GPU layer split can't pin a context that fits the pool on paper but OOMs a device; a single GPU adds nothing, so single-GPU sizing is unchanged. The slot-scaling buffer above is conserved across the split, so it is still folded once.Root cause confirmed by an A/B bisect
A user reported the
unsloth/Qwen3.6-27B-MTPGGUF fitting 110k context on an older build but OOMing on a later build, single GPU. Installing both versions fresh into isolatedUNSLOTH_STUDIO_HOMEs and measuring on one GPU showed the Studio backend (auto-fit + MTP code) is byte-identical between the two, and so is the torch stack. The difference is that the bundled llama.cpp gained MTP support across the update: MTP went from inert (the GGUF behaved like a plain model, so 110k fit) to actually running--spec-type draft-mtp, and its draft KV now consumes the extra VRAM. The old flat-5% reserve did not track the context-scaling draft KV, so auto-fit still advertised ~110k and the load OOMed. This change reserves the right amount once MTP engages, and (via a binary-capability gate) reserves nothing when the bundled llama.cpp cannot run MTP.Effect on advertised / achievable context
Qwen3.6-27B MTP Q6_K, MTP on, before this PR vs after:
A single card roughly triples the supported f16 context (recovering the user's old ~60k while keeping it on-GPU); tight tensor setups recover the full native window.
Validated on hardware
Measured per-PID VRAM on B200s capped to the target free VRAM, b9625 llama-server, MTP on:
-c 64768uses 29.3 GB at 120 t/s, estimate within 0.1% (auto-fit advertises a slightly more conservative 64000 once the compute buffer is folded in, so the advertised context loads with headroom to spare).Capped runs also confirm the old behavior at low free VRAM advertised the full window and silently offloaded to CPU (the 100 to 20 t/s drop users reported); the new code returns a real on-GPU context.
Test plan
studio/backend/tests/test_compute_buffer.py(19 tests): the estimate is a safe upper bound on every measured allocation, scales with serving slots / vocab / ubatch, tensor exceeds pipeline, and falls back to the flat reserve when dims are missing.studio/backend/tests/test_mtp_vram_budget.pyrewritten for the deterministic design (embedded vs separate drafter, draft-KV-type recompute, overhead = draft KV + drafter weights, no tuned constants).test_compute_buffer,test_tensor_parallel,test_mtp_vram_budget,test_llama_cpp_context_fit,test_kv_cache_estimation,test_llama_cpp_max_context_threshold,test_llama_cpp_wait_for_vram_settle(310 passed).