Repository navigation
Studio: reserve CUDA context and mmproj/MTP soft overhead in the GGUF fit budget - #6718
Conversation
There was a problem hiding this comment.
Code Review
This pull request introduces soft VRAM overhead calculations (for CUDA context, mmproj safety, and MTP draft compute) to prevent under-covering on tight tiers. The reviewer identified that the new assignment to model_size_fit makes a previous assignment redundant, resulting in dead code. Additionally, defining _subset_model_size before model_size_fit is fully computed relies on fragile late-binding behavior. The reviewer recommended removing the redundant assignment and reordering the definition of _subset_model_size to prevent future bugs.
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.
| # Charge the soft overhead _CTX_FIT_VRAM_FRACTION under-covers on tight | ||
| # tiers, gated so plain dense loads (#5106) only pay the CUDA-ctx base. | ||
| _soft_overhead = self._CUDA_CONTEXT_RESERVE_BYTES | ||
| if effective_is_vision and mmproj_size > 0: | ||
| _soft_overhead += int(mmproj_size * (self._MMPROJ_VRAM_SAFETY - 1.0)) | ||
| if _mtp_reserves_gpu: | ||
| _soft_overhead += self._MTP_DRAFT_COMPUTE_BYTES | ||
| model_size_fit = model_size + _compute_buffer_pipeline + _soft_overhead |
There was a problem hiding this comment.
The assignment to model_size_fit at line 5074 makes the previous assignment at line 5029 (model_size_fit = model_size + _compute_buffer_pipeline) completely redundant and dead code, as it is unconditionally overwritten here.
Additionally, defining _subset_model_size at line 5038 before model_size_fit is fully computed here relies on Python's late-binding behavior for closures. While correct at runtime since _subset_model_size is only called later, this is fragile and can easily lead to bugs if the code is refactored or if _subset_model_size is called earlier in the future.
Recommendation:
- Remove the redundant assignment
model_size_fit = model_size + _compute_buffer_pipelineat line 5029. - Move the definition of
_subset_model_size(lines 5038-5039) to be after line 5074, oncemodel_size_fithas been fully computed with the soft overhead.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 9b401b1440
ℹ️ 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".
| _soft_overhead += int(mmproj_size * (self._MMPROJ_VRAM_SAFETY - 1.0)) | ||
| if _mtp_reserves_gpu: | ||
| _soft_overhead += self._MTP_DRAFT_COMPUTE_BYTES | ||
| model_size_fit = model_size + _compute_buffer_pipeline + _soft_overhead |
There was a problem hiding this comment.
Apply the soft reserve to tensor planning
When tensor parallel remains enabled for non-vision MTP loads, this new model_size_fit is only consumed by the layer-split/--fit branches; the tensor branch below still pre-checks and calls _plan_tensor_parallel(..., model_size, ...), so the CUDA-context and MTP draft-compute reserves are not subtracted from the tensor KV budget. On tight multi-GPU tensor launches this can still pick a context that fits on paper but OOMs at startup, which is the class of failure this change is trying to avoid; thread the same soft overhead into the tensor pre-check/planner as well.
Useful? React with 👍 / 👎.
|
|
||
| # Charge the soft overhead _CTX_FIT_VRAM_FRACTION under-covers on tight | ||
| # tiers, gated so plain dense loads (#5106) only pay the CUDA-ctx base. | ||
| _soft_overhead = self._CUDA_CONTEXT_RESERVE_BYTES |
There was a problem hiding this comment.
Gate the CUDA reserve off Metal-only fits
When no CUDA/ROCm GPU is enumerated, the Apple Metal branch below is the active path, but this unconditional base still flows into model_size_fit used for the unified-memory cap. On Apple Silicon there is no CUDA/cuBLAS context to reserve; for models within ~320 MiB of the Metal working-set budget this can make model_footprint >= budget_bytes, forcing the UI/auto cap down to the 4096 fallback even though reducing KV would otherwise fit. Apply this reserve only to discrete GPU paths, or use a Metal-specific overhead.
Useful? React with 👍 / 👎.
… fit budget The deterministic VRAM auto-fit sizes weights, KV, draft KV and the mmproj file exactly, and leaves CUDA context, the worst-case mmproj projector buffer and the MTP draft decode graph to the _CTX_FIT_VRAM_FRACTION headroom. That 5 percent is too thin on tight 24GB tiers once a vision projector and an MTP draft also sit on the card, so a 27B MTP load pins -ngl -1 at a context whose real footprint overshoots and offloads to CPU. Charge that soft overhead to the fit footprint, gated so plain dense loads only pay the small CUDA context base: - CUDA context plus cuBLAS workspace, about 330 MiB (measured on a 27B at any ctx) - mmproj worst-case buffer, about 1.3x its file size (vision loads) - MTP draft decode graph, about 224 MiB above the draft KV (MTP loads) Qwen3.6-27B-MTP UD-Q4_K_XL plus mmproj on a 24GB card: the auto context drops from 121600 (real peak 23.6 GiB, offloads) to 98560 (real peak 21.9 GiB, full GPU). Plain dense fits such as 20.8GB on 22.8GB free are unchanged. Fixes #6682
9b401b1 to
e0469c8
Compare
|
Thanks for the reviews. Addressed in the latest push (rebased onto current main):
All fit, KV, compute-buffer, MTP and context tests pass. |
|
Reviewed this against the floored reserve in my #6688, on the reporter's model on a 24 GB 3090. Qwen3.6-27B-MTP UD-Q4_K_XL + mmproj-F16, q8_0 KV, the model's default sampling (temp 0.7, top_p 0.8, top_k 20, presence_penalty 1.5), 5-run average, all
On the bare engine both picks run at the same speed, so this PR is the better reserve: 36% more context at no cost. Through Studio the 90624 pick loses ~18% while 66560 doesn't, so the extra context currently runs slower in the app than the engine delivers. Same sampling on both sides, so it isn't presence_penalty or the params, it's a Studio-side cost that only shows at the larger context. I couldn't pin it. Reproduction, per ctx: # 1) bare engine: run the same llama-server command Studio logs, standalone.
# (needs the CUDA libs on LD_LIBRARY_PATH or it silently falls back to CPU)
LD_LIBRARY_PATH=~/.unsloth/llama.cpp/build/bin:<venv>/site-packages/nvidia/cu13/lib \
~/.unsloth/llama.cpp/llama-server -m Qwen3.6-27B-UD-Q4_K_XL.gguf -c 90624 \
--parallel 1 --flash-attn on --no-context-shift -ngl -1 \
--cache-type-k q8_0 --cache-type-v q8_0 \
--spec-type draft-mtp --spec-draft-n-max 2 --mmproj mmproj-F16.gguf
# 2) send the same request to the bare server and to Studio's /v1.
# tok/s = completion_tokens / wall_time, 5-run average.
curl -s localhost:PORT/v1/chat/completions -H 'Content-Type: application/json' -d '{
"messages":[{"role":"user","content":"Write a long detailed essay about the history of computing, at least 400 words."}],
"max_tokens":400,"temperature":0.7,"top_p":0.8,"top_k":20,"presence_penalty":1.5}' |
Empirical validation on B200s (per-PID, contamination-proof)Ran the full auto-context fit matrix on real hardware and measured each server's own GPU Coverage28 tightest cells (worst case per model x {MTP, non-MTP}) plus 4 giants, all fully
Separate vs embedded MTP both confirmed; non-MTP confirmed unaffected (the MTP-repo models A third bug this PR does not yet cover: context-linear compute buffer
Measured slope (q8_0 KV, ubatch 512):
Proposed fix (separate follow-up PR, +59 lines, monotonic, backwards compatible): add a KV-cache quantization changes the compute buffer tooThe KV cache type is already budgeted correctly on the supply side. It also moves the Overhead floor: 5% -> 3%With the compute buffer modelled, the predicted footprint over-predicts the real (real-card) I am changing For comparison: #6688 moved |
|
yes i concur |
Follow-up: overhead -> 3%, KV-quant awareness, multi-GPU + MLA fixesReduced the overhead cushion and fixed four more issues the validation surfaced, then Overhead 5% -> 3%
KV-cache quantization changes the compute bufferKV quant is budgeted correctly on the supply side already. It also moves the compute
Per-device compute buffer in a layer splitThe 397B multi-GPU case under-predicted by ~2.7%. Root cause from the server log: in a MLA models need a lighter compute rateMLA (compressed attention) needs far less dequant scratch than regular attention: Larger giants (multi-GPU layer split across 3 GPUs, per-PID)
GLM-5.2 with all four fixes predicts 273.9 GiB vs a real 263.4 (a true upper bound) and |
Tensor parallelism (
|
| ctx | per-device compute buffer | KV | total peak (2 GPUs) |
|---|---|---|---|
| 8,192 | 96 MiB | 256 | 7,304 MiB |
| 32,768 | 120 MiB | 1,024 | 8,120 MiB |
| 131,072 | 216 MiB | 4,096 | 11,384 MiB |
| 262,144 | 344 MiB | 8,192 | 15,736 MiB |
The per-device compute buffer grows at exactly 1024 B/token = n_ubatch*2, independent
of n_embd, and is replicated on every device (the total non-KV footprint grows 2048 B/tok
across the 2-GPU split). This is the same light KQ-mask term the f16 path already models,
just applied per device in tensor mode.
The gap and the fix
_plan_tensor_parallel subtracted n_dev * flat_reserve (context-independent) and never
charged the context-linear growth. For the 9B its large vocab makes the flat reserve
~631 MiB/device, which happens to cover the buffer up to ~570k context; but beyond that
(many models are 1M-native), for smaller-vocab models, and on wider splits it
under-reserves: 0.5 GiB at 262k on 2 GPUs up to ~4 GiB at 1M on 4 GPUs, unreserved,
which over-pins the context and OOMs on a tight pool.
Fix: charge n_dev * _compute_buffer_ctx_bytes(ctx) in the TP fit (inside the per-context
consumer, and in the even-split weighting). Because tensor mode forces f16 KV, this is the
light mask term, not the heavy quantized dequant scratch. The existing f16 term (1536
B/tok/device with its 1.5 safety) upper-bounds the measured 1024:
| ctx | predicted per-device reserve (flat + linear) | measured buffer | verdict |
|---|---|---|---|
| 8,192 | 643 MiB | 96 | upper bound |
| 131,072 | 823 MiB | 216 | upper bound |
| 262,144 | 1,015 MiB | 344 | upper bound |
Single-GPU and the layer-split path are unchanged. Added two tests
(test_tp_plan_reserves_context_linear_compute_buffer,
test_tp_plan_context_shrinks_vs_compute_unaware); 801 fit/compute/KV/MTP/TP tests pass.
…buffers so GGUF decode stays fast on tight VRAM Two VRAM-fit accuracy fixes on top of the tight-tier work. Memory-aware serving slot cap. Studio serves llama-server with a fixed --parallel 4, but each idle slot needs a large transient decode workspace that the context fit never reserved. On a memory-constrained card at the auto-picked max context, free VRAM drops to ~1-3 GiB and --parallel 4 decode collapses to ~40% throughput while --parallel 1 stays fast. Add _estimate_decode_workspace_bytes (dim-scaled per slot, MTP-aware) and _cap_serving_slots, which reduces the effective --parallel to what the tightest device can decode at full speed without shrinking the chosen context. Only ever reduces, floors at 1, and is a no-op on roomy cards (byte-identical behavior). Recovers a 24 GB / 27B / 90624 case from ~36 to ~88 tok/s; roomy cards unchanged. Tensor-parallel compute buffer. Under --split-mode tensor the per-device compute buffer is replicated on every GPU and grows with context; reserve n_dev copies of the context-linear compute buffer in the even-split fit so a tensor-split pick does not over-commit the aggregate device. Tests: TestDecodeWorkspace and TestCapServingSlots in test_compute_buffer.py, two tensor-parallel reserve cases in test_tensor_parallel.py. Full fit suite green.
|
Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits. |
|
@oobabooga thanks for pinning this down, the report was exactly right and it led straight to the fix. Here is what was going on and what I just pushed. Root cause: the serving slot count at the memory edge, not the fit mathStudio serves llama-server with a fixed Reproduced on a single card ballooned to ~24 GB, 27B-MTP Q4, ctx 90624:
So under pressure Fix (pushed to this branch)A memory-aware serving-slot cap. A new estimator reserves the transient decode workspace per slot (dim-scaled by Validated end-to-end on real hardware: fed the cap the real 27B GGUF metadata and the real free VRAM under a 24 GB balloon, it picks 1 slot; unballooned it keeps 4. Unit tests cover the estimator and the cap (tight card reduces, roomy keeps 4, floor 1, multi-GPU gated by the tightest device); full fit suite green. This also vindicates your throughput floor in #6688 for constrained cards specifically. The aggressive 3% pick stays free on roomy cards, but on a tight card the slot cap is what preserves decode speed. |
|
Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits. |
|
Reproduced the 1. The collapse reproduces (Studio's path:
|
| config @ 90624 | tok/s | GPU util | VRAM used | free |
|---|---|---|---|---|
--parallel 1 |
54.4 | 97% | 22413 | 1704 |
--parallel 1 with 336 MiB RAG embedder |
45.0 | 75% | 22528 | 1588 |
--parallel 4 --kv-unified |
18.0 | 35% | 21115 | 3002 |
Your --parallel 4 result confirmed: 18 tok/s, a third of --parallel 1. The tell is in the last row. VRAM used drops to 21115 with 3002 free, because the fit step pushed layers to host RAM.
2. It is the fit step offloading, not a VRAM wall
Same configs, but --fit off (force every layer onto the GPU):
| config @ 90624 | tok/s | GPU util | VRAM used | free |
|---|---|---|---|---|
--parallel 1 |
54.6 | 97% | 22413 | 1704 |
--parallel 1 with embedder |
54.2 | 97% | 22754 | 1362 |
--parallel 1 with 1600 MiB held |
52.8 | 97% | 24018 | 98 |
--parallel 4 --kv-unified |
52.1 | 97% | 23759 | 358 |
With everything forced onto the card, nothing collapses. --parallel 4 runs full speed at 358 MiB free, and --parallel 1 holds 52.8 tok/s down to 98 MiB free. So the slowdown is the fit step deciding to offload, not llama.cpp shrinking the decode graph at the edge.
3. How much VRAM --parallel 4 actually costs
Real footprint, --fit off, both slots fully on GPU:
| ctx | parallel 1 | parallel 4 | delta |
|---|---|---|---|
| 32768 | 19957 | 21279 | +1.3 GiB |
| 90624 | 22413 | 23759 | +1.3 GiB |
--kv-unified is a memory no-op on this build, so the total KV does not grow with slots. Only the per-slot compute buffer does, by about 1.3 GiB for 4 slots.
Concrete answers
--parallel 4costs ~1.3 GiB more than--parallel 1, not ~8 GiB. The 8 GiB is the reserve your estimator charges (~2 GiB/slot). The measured runtime footprint is ~440 MiB/slot. The card actually holds 4 slots fine, and--fit offproves it.- The RAG embedder is a real but minor factor. 336 MiB takes
--parallel 1from 54 to 45 tok/s (~17%), and only under--fit on. Under--fit offit is 54.2 vs 54.6, so no effect. - Both slowdowns are the same fit-step offload.
--parallel 4is the big lever (54 to 18), the embedder is the small one (54 to 45). Your slot cap removes the big one. Freeing the embedder before the model load removes the small one, which is what my Studio: stop the idle RAG embedder from holding inference VRAM and slowing generation #6744 does.
One thing worth checking on your side. Your slot cap uses the ~2 GiB/slot reserve to decide how many slots fit, but the measured footprint is ~440 MiB/slot, and 4 slots ran full speed at 358 MiB free. So the reserve may cap to 1 slot when the card could actually hold 2 or 3 at full speed. A smaller reserve would keep more concurrent slots on tight cards without bringing the offload back.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 120cc421e5
ℹ️ 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".
| _soft_overhead += int(mmproj_size * (self._MMPROJ_VRAM_SAFETY - 1.0)) | ||
| if _mtp_reserves_gpu: | ||
| _soft_overhead += self._MTP_DRAFT_COMPUTE_BYTES | ||
| model_size_fit = model_size + _compute_buffer_pipeline + _soft_overhead |
There was a problem hiding this comment.
Apply soft overhead in tensor-parallel budgets
For tensor-parallel launches, the new CUDA/mmproj/MTP reserves are only folded into model_size_fit, but the tensor branch below still plans with the raw model_size, so these reserves are skipped whenever tensor_parallel remains enabled. On tight multi-GPU tensor loads, especially VLM or MTP sessions, _plan_tensor_parallel can still choose a context/split that fits on paper but lacks the soft overhead this change intended to reserve, leading to the same OOM/CPU-spill behavior in tensor mode.
Useful? React with 👍 / 👎.
| gpus, | ||
| total_by_idx, | ||
| model_size or 0, | ||
| (mmproj_size if effective_is_vision else 0) or 0, |
There was a problem hiding this comment.
Do not count the projector twice when capping slots
In vision sessions model_size was already set to gguf_size + mmproj_size, but this call also passes mmproj_size separately and _cap_serving_slots adds it again in (model_size + kv_total + mtp_total + mmproj_bytes) / n_dev. On tight VLM loads with --parallel > 1, that double-counts the projector and can unnecessarily reduce the served slot count even though the actual VRAM load would fit.
Useful? React with 👍 / 👎.
| mtp_total = ( | ||
| mtp_overhead_fn(effective_ctx) | ||
| if (mtp_active and mtp_overhead_fn is not None) | ||
| else 0 |
There was a problem hiding this comment.
Recompute MTP reserve for each capped slot count
mtp_total is computed once before trying smaller k values, but the closure was created with the original n_parallel, and MTP reserves can scale with slots for separate draft KV or the MLA target-context copy. When a memory-tight MTP launch is tested at k < n_parallel, _fits(k) still charges the larger original MTP reserve, so the cap can reduce --parallel more than necessary despite the lower-slot configuration fitting.
Useful? React with 👍 / 👎.
| per_device_load = ( | ||
| (model_size + kv_total + mtp_total + mmproj_bytes) / n_dev | ||
| + static | ||
| + cuda_reserve |
There was a problem hiding this comment.
Subtract context-linear compute before capping slots
The slot cap compares remaining VRAM against the decode workspace, but per_device_load only subtracts the flat compute buffer and omits the context-linear compute term that was reserved earlier via _compute_buffer_ctx_bytes. For high-context pinned loads this can overstate free VRAM by GiBs and keep too many --parallel slots, so llama.cpp can still shrink the decode graph or spill even after the cap says the slots fit.
Useful? React with 👍 / 👎.
| even_share_mib = ( | ||
| (model_size + kv_bytes + mtp_bytes + cc_bytes) / len(gpu_indices) / (1024 * 1024) | ||
| ) |
There was a problem hiding this comment.
Subtract replicated context buffer from tensor split weights
When an even tensor split does not fit, the weighted tensor_split still uses each GPU's whole usable - reserve capacity even though the new cc_bytes term is replicated on every device and cannot be shifted to the larger GPU. On asymmetric GPUs at high context, this can assign the smallest card a weight share based on memory that must actually be kept for its own context-linear compute buffer, so the weighted tensor launch can OOM despite the pooled budget fitting.
Useful? React with 👍 / 👎.
| ) | ||
| footprint_mib = (_ms + kv + _mtp_bytes(capped)) / (1024 * 1024) | ||
| footprint_mib = ( | ||
| _ms + kv + _mtp_bytes(capped) + _cc_sub(capped) |
There was a problem hiding this comment.
Ensure each layer-split GPU holds the context buffer
In the auto layer-split path, _cc_sub(capped) is only added to the pooled footprint, so a large GPU can compensate for a small selected GPU that lacks room for its own replicated context-linear compute buffer. On mixed-memory systems at high context, this can accept a subset whose aggregate VRAM fits while one device cannot hold the per-device buffer, causing the pinned layer-split launch to OOM instead of trying a safer subset or --fit.
Useful? React with 👍 / 👎.
…ad (#6718) On a memory-tight card at a pinned high context, the extra --parallel slots push the footprint past the pin budget, so Studio falls back to --fit on and llama-server offloads layers to host RAM, collapsing decode about 3x (measured on a real 3090: 52 -> 18 tok/s). The prior decode-workspace reserve that tried to catch this was calibrated to a B200 allocator artifact (needing ~8 GiB free per config, vs ~0.35 GiB on a real 3090) and was gated on the non-offload path, so it never fired in the case that actually collapses. Replace it: when the fit would offload only because of the slot count, retry the on-GPU fit at fewer slots and keep the largest count that stays fully on GPU (-ngl -1), keeping the chosen context. Only ever reduces; roomy cards keep all 4 slots. Delete the decode-workspace estimator, its constants, and the old cap. No KV/compute-buffer estimator changes, so the model/quant fit behavior is unchanged. Adds _slots_that_fit_on_gpu (deterministic, unit-tested) and wires it into load_model before the launch command is built. Full fit suite green; new test_slot_offload_fit.py covers the reduction (largest-fitting, floor to 1, genuine-offload, multi-GPU, KV per candidate).
|
Pushed a follow-up (1a038f3) for the Your
The fix: when the fit would offload only because the slots inflate the footprint, retry the on-GPU fit at fewer slots and keep the largest count that stays fully on GPU ( On One honest caveat. On a 24 GB card at the pinned max context, Studio's footprint estimate is ~1.5 GiB more conservative than the real allocation you measured (24.7 vs 23.8 GiB), so it currently reduces to 1 slot rather than the 2-3 the card can actually hold on GPU. That still fixes the throughput collapse (on GPU at full speed, not offloaded) and keeps the context, but it keeps fewer concurrent slots than ideal. Tightening that estimate to keep more slots is a separate change: the per-slot output buffer carries a 1.15 safety margin it does not need, but trimming it has to preserve the tensor-parallel upper bound, so I would rather do it on its own with hardware confirmation than fold it in here. |
|
Your caveat said the fix reduces to 1 slot on a 24 GB card and still keeps the model on GPU at full speed. I tested 1a038f3 on a real 3090 with the reported model (Qwen3.6-27B-MTP UD-Q4_K_XL + mmproj, q8_0 KV) at ctx 90624, through Studio at I put a log line in
The estimate is higher than the ~1.5 GiB conservatism you noted. The 1-slot estimate (23455) is about 1 GiB over the real 1-slot footprint I measured with Bare llama-server at the same flags, for the real numbers (only
What worked for me: give the on-GPU slot check a near-full budget instead of the pin fraction, since the estimate already carries the safety margins and offload is a ~3x swing. diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.py
@@ -5714,6 +5714,13 @@ class LlamaCppBackend:
+ _mtp_bytes(effective_ctx)
+ _cc_bytes(effective_ctx)
)
+ # The footprint estimate already carries safety margins
+ # (1.15 compute, 1.4 mmproj, 320 MiB CUDA ctx), and staying on
+ # GPU vs offloading is a ~3x decode swing, so this on-GPU slot
+ # check keeps only a small hardware-noise reserve rather than the
+ # 0.97 pin fraction (which double-counts safety and rejected every
+ # slot, leaving the model offloaded).
+ _slot_gpu_fraction = max(self._GPU_PIN_VRAM_FRACTION, 0.995)
_gi_slots, _uf_slots, _slots = self._slots_that_fit_on_gpu(
n_parallel,
effective_ctx,
@@ -5721,7 +5728,7 @@ class LlamaCppBackend:
total_by_idx,
_base_footprint,
cache_type_kv,
- _pin_fraction,
+ _slot_gpu_fraction,
_pipeline_overhead_bytes + _cc_bytes(effective_ctx),
_layer_min_gpus,
_effective_ubatch,Now the reduction fires and it behaves the way your caveat expected:
Two things worth noting:
|
Bring the branch up to date with main (d918245) so the lint import-hoist check compares against the current base. main's models.py refactor was being flagged only because the branch was behind.
|
Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits. |
|
@codex review |
|
Full before/after verification for this change, comparing the code at 120cc42 (before) and 1a038f3 (after). The decision matrix is driven by both real code versions; speeds are measured live with llama-server on B200s ballooned to emulate each card. 1. Context length is identical before and after 130 cells (10 local models x 13 VRAM sizes) at
2. Serving decision when a context larger than auto is pinned Over the same 130 cells: 96 stay on GPU (unchanged), 27 offload at native pin on a card too small (both versions, auto context avoids this), 4 are the offload-to-onGPU fix, 3 keep more slots on GPU than before (old cap removed). Only ever reduces slots; roomy cards keep all 4.
3. Live confirmation (27B UD-Q4_K_XL, ballooned card)
Host offload is about 9x slower. Verdict The after-PR code takes the on-GPU path ( One honest caveat: the footprint estimate is conservative, so in the band where par4 would actually have fit, the reduction keeps fewer serving slots than the card can physically hold. That is not a slowdown (single-stream speed is identical, both on GPU), just less concurrency. Tightening the estimate to reclaim those slots is a separate follow-up. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d456d78164
ℹ️ 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".
| cc_bytes = _cc_ctx(effective_ctx) if effective_ctx > 0 else 0 | ||
| even_share_mib = ( | ||
| (model_size + kv_bytes + mtp_bytes + cc_bytes) / len(gpu_indices) / (1024 * 1024) |
There was a problem hiding this comment.
Reserve per-device compute before weighting tensor splits
When tensor mode uses a weighted split on asymmetric GPUs, the new replicated context-linear compute reserve is only added to the even-share check here; the adj weights immediately below are still based on usable - reserve_mib, so --tensor-split can allocate model/KV bytes to the smaller GPU as if its per-device context compute did not exist. For example, the existing 48GB/24GB tensor-plan case now computes about 96 MiB of per-device context buffer; with the returned split [41440, 18160], the smaller GPU is over its usable budget by ~38 MiB, which can turn the intended safe cap into a load-time OOM. The weighted capacities need to subtract the per-device context buffer as well before emitting the split.
Useful? React with 👍 / 👎.
| _soft_overhead += int(mmproj_size * (self._MMPROJ_VRAM_SAFETY - 1.0)) | ||
| if _mtp_reserves_gpu: | ||
| _soft_overhead += self._MTP_DRAFT_COMPUTE_BYTES | ||
| model_size_fit = model_size + _compute_buffer_pipeline + _soft_overhead |
There was a problem hiding this comment.
Include soft overhead in tensor planning
This only folds the new CUDA/mmproj/MTP reserve into model_size_fit, but the tensor-parallel branch still plans with model_size when it calls _plan_tensor_parallel, so tensor loads skip the newly modeled soft overhead. For vision or MTP tensor loads near the VRAM limit, Studio can still emit --split-mode tensor with a context that only fits because the extra mmproj safety or MTP draft-graph reserve was omitted, leading to the same load-time OOM/spill this reserve is meant to prevent.
Useful? React with 👍 / 👎.
| _loggers_stub.get_logger = lambda name: __import__("logging").getLogger(name) | ||
| sys.modules.setdefault("loggers", _loggers_stub) | ||
|
|
||
| from core.inference.llama_cpp import LlamaCppBackend |
There was a problem hiding this comment.
Stub external deps before importing the backend
In the dependency-light unit-test environment used by these backend tests, importing core.inference.llama_cpp goes through core.inference.__init__/orchestrator and imports structlog; this new test only stubs loggers, so python -m pytest -q studio/backend/tests/test_slot_offload_fit.py fails during collection with ModuleNotFoundError: No module named 'structlog'. Mirror the stubs used by the adjacent llama_cpp tests before this import so the new test can run without optional runtime dependencies.
Useful? React with 👍 / 👎.
|
Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits. |
|
Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits. |
|
Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits. |
|
Two changes on top of the PR, both tested live on a real 3090 (24 GB) and RTX 6000 Ada (49 GB).
Tensor-parallel fix, Ada 49 GB + 3090 24 GB:
Full backend suite: 5378 passed. The 22 failures are in untouched training/API tests that never import the changed module, so they are pre-existing env noise, not this diff. Merging now. |
|
CI green. |
The hoisted native_ctx_for_cap coupled two placement arms that do not otherwise talk to each other. The arm at "elif gpus and self._can_estimate_kv() and effective_ctx > 0" binds the same expression itself, so on the mainline path the hoist is overwritten before the re-fit reads it. The path where it survives is the one it was added for, and there it binds the wrong value: a GGUF with no native length reaches that elif while effective_ctx is still the 0 sentinel, so the arm is skipped, control falls through to "elif gpus:", and only that arm raises effective_ctx to 4096. The hoist has already captured 0, so _lo = 1, _hi = 0, the bisect body never runs, and both the re-fit and the ceiling update are silently skipped. Removing the hoist without replacing it is not an option either: the re-fit's guard is false at the hoist and true by the time it runs, so the name is unbound there, the broad except around placement swallows it, and the whole GPU plan is discarded for --fit on. That is the ~3x decode collapse this block exists to avoid (unslothai#6718). Bind it inside _largest_ctx instead, the way the two sweeps above already do. The cross-arm coupling goes, the third copy of the expression goes, and the no-native-metadata path now runs the bisect for real and returns 4096, matching what it produced before. Verified inert: across 15,360 spoofed platform cells and 138 degenerate-input cases, nothing moves except that those cells now enter the predicate instead of skipping it. Also: - Log the slot reduction after the re-fit. It reported the pre-re-fit context, which is sized for the slot count the load just stopped using, so the line named a context no launch ever ran with ("reduced 4 -> 2 ... at context 4096" immediately followed by "re-fitted 4096 -> 7680"). - The ceiling is not "a hardware bound". It is the largest context attainable at the slot count this load settled on; a larger request can drive a deeper reduction that frees the KV for more. Measured on 250 reduced-slot plans, ceiling + 256 still loads fully on GPU in 175 of them. The value is right and strictly better than what it replaced -- it removes a large class of false "may use system RAM" warnings -- but the comment invited the next reader to trust it as a maximum. Adds a platform matrix that pins which hosts the re-fit may touch at all. Metal enumerates no torch.cuda device and CPU-only hosts have none, so every macOS cell and every CPU-only cell fails the "and gpus" conjunct by construction, as do tensor-parallel, manual memory mode and a single-slot request. Watching the predicate rather than the argv means a cell that starts entering the block fails even when its numbers happen not to move.
* Studio: re-fit the context when Auto drops serving slots * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Bind the native context before the planner arms that do not set it * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Keep the context re-fit on the cards the slot reduction chose * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Charge the --ctx-checkpoints reserve in the slot and context fit llama-server allocates --ctx-checkpoints snapshots per slot (upstream default 32, and Unsloth charges only what the user explicitly asks for), so the reserve scales with the count the plan settles on. _slots_that_fit_on_gpu priced its candidates without it. That was survivable while the only consumer was the slot count: an over-optimistic candidate cost slots, not memory already promised. The post-reduction context re-fit runs the same predicate to pick the launched -c, so the omission started buying context with bytes the child had already been told to spend on checkpoints. Thread ctx_checkpoints through the helper and pass _effective_ctx_checkpoints at both call sites, which corrects the pre-existing slot search as well. Measured on a 12 GiB card, a 9,200 MiB sliding-window target, q8_0 KV, four requested slots and --ctx-checkpoints 16: the plan launched -c 12800 at three slots with --fit off, against a 4,794 MiB reserve the fit never charged. It now declines that context. Across 630 checkpointed shapes the count of plans that spent an uncharged reserve drops from 67 to 0; the seven that remain equal are at their native length, where there is nothing to give back. Also stop the search walking candidates the caller discards. _slots_hold accepts only n_parallel itself, and the helper had no early exit, so it re-ran the whole KV + compute-buffer + GPU-selection estimate down to one slot for answers it threw away: 45 percent of iterations across a 15-scenario sample, 74 percent worst case. The docstring summary still described the old [1, n_parallel) domain, which include_requested had already widened. * Bind the native context at the re-fit's own read site The hoisted native_ctx_for_cap coupled two placement arms that do not otherwise talk to each other. The arm at "elif gpus and self._can_estimate_kv() and effective_ctx > 0" binds the same expression itself, so on the mainline path the hoist is overwritten before the re-fit reads it. The path where it survives is the one it was added for, and there it binds the wrong value: a GGUF with no native length reaches that elif while effective_ctx is still the 0 sentinel, so the arm is skipped, control falls through to "elif gpus:", and only that arm raises effective_ctx to 4096. The hoist has already captured 0, so _lo = 1, _hi = 0, the bisect body never runs, and both the re-fit and the ceiling update are silently skipped. Removing the hoist without replacing it is not an option either: the re-fit's guard is false at the hoist and true by the time it runs, so the name is unbound there, the broad except around placement swallows it, and the whole GPU plan is discarded for --fit on. That is the ~3x decode collapse this block exists to avoid (#6718). Bind it inside _largest_ctx instead, the way the two sweeps above already do. The cross-arm coupling goes, the third copy of the expression goes, and the no-native-metadata path now runs the bisect for real and returns 4096, matching what it produced before. Verified inert: across 15,360 spoofed platform cells and 138 degenerate-input cases, nothing moves except that those cells now enter the predicate instead of skipping it. Also: - Log the slot reduction after the re-fit. It reported the pre-re-fit context, which is sized for the slot count the load just stopped using, so the line named a context no launch ever ran with ("reduced 4 -> 2 ... at context 4096" immediately followed by "re-fitted 4096 -> 7680"). - The ceiling is not "a hardware bound". It is the largest context attainable at the slot count this load settled on; a larger request can drive a deeper reduction that frees the KV for more. Measured on 250 reduced-slot plans, ceiling + 256 still loads fully on GPU in 175 of them. The value is right and strictly better than what it replaced -- it removes a large class of false "may use system RAM" warnings -- but the comment invited the next reader to trust it as a maximum. Adds a platform matrix that pins which hosts the re-fit may touch at all. Metal enumerates no torch.cuda device and CPU-only hosts have none, so every macOS cell and every CPU-only cell fails the "and gpus" conjunct by construction, as do tensor-parallel, manual memory mode and a single-slot request. Watching the predicate rather than the argv means a cell that starts entering the block fails even when its numbers happen not to move. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Tighten the comments on the context re-fit and its tests Comment-only pass: same wording, fewer lines. The exact= rationale lives in the helper docstring, so the call site keeps a trailing note instead of repeating it; the ceiling and _largest_ctx blocks keep the trap they document and drop the retelling. * Shorten the GPU-subset note on the context re-fit * Do not price checkpoints a build without the flag never allocates The argv builder emits --ctx-checkpoints only when the capability probe found one of the two aliases, and logs and drops the request otherwise. The priced count was resolved unconditionally, so on an older or custom llama-server the fit reserved per-slot SWA snapshots no child ever holds. On an SWA model that is not a rounding error: the reserve is charged per slot, so it can push the slot search down a step and, now that the same predicate picks the launched -c, hand back a smaller context than the card holds -- for a flag the launch never passed. Gate the resolve on the same server_caps entry the emission uses, which is already bound above. This changes no argv; it only stops the estimator charging for bytes the launch does not reserve, at all seven call sites, including the five that predate this branch. * Tighten the checkpoint gate comments --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: danielhanchen <[email protected]> Co-authored-by: danielhanchen <[email protected]>
…Auto offload context (unslothai#9594) * Price the serving-slot reduction at the fit floor, not the Auto offload context `Backend tests` has been red on main since unslothai#9492 (1f475d7), 26 failures across test_slot_reduction_context_refit.py and test_slot_refit_platform_matrix.py, both added by unslothai#9345 (1c06bc4). All 59 pass on unslothai#9492's merge base (15b9102). The two files were not run on that branch. The tests are reporting a real regression, not a stale baseline. unslothai#9492 introduced _AUTO_OFFLOAD_CTX = 8192 and put it in three places that had a literal 4096. Its reasoning: "Auto only reaches this path when no discrete-GPU subset can hold the model. llama.cpp must offload layers to host RAM either way, so prefer a context that remains useful for chat." That is true of two of the three sites, which are display values. The third, in load_model's auto arm, is the probe context of a placement search that runs AFTER it, in a block whose entire purpose is to overturn the premise "no subset can hold the model" by re-asking at fewer serving slots. Offload is not unavoidable at that point; it is avoidable in roughly the band where the constant now breaks it. What that costs, measured on a 12 GiB card at 4 requested slots: | weights | before unslothai#9492 | on main | |--------------------|-------------------------|------------------------| | hybrid 10,900 MiB | 1 slot, ctx 7,680, GPU | 4 slots, ctx 8,192, offload | | hybrid 11,000 MiB | 1 slot, ctx 6,144, GPU | 4 slots, ctx 8,192, offload | | hybrid 11,100 MiB | 1 slot, ctx 4,608, GPU | 4 slots, ctx 8,192, offload | | dense 9,800 MiB | 2 slots, ctx 4,608, GPU | 4 slots, ctx 8,192, offload | | dense 10,000 MiB | 1 slot, ctx 6,144, GPU | 4 slots, ctx 8,192, offload | | dense 10,500 MiB | 1 slot, ctx 4,096, GPU | 4 slots, ctx 8,192, offload | 8 of 14 sizes swept flip from fully GPU-resident to host offload, the ~3x decode collapse (unslothai#6718) named in _slots_that_fit_on_gpu's own docstring as the thing it exists to prevent. The failure is all-or-nothing: when no slot count fits at the probe, the block returns early, so the load keeps the full slot count it could not afford AND offloads. It gets 8,192 tokens at a third of the speed where it previously had 6,144 at full speed. Not a Pareto move. The arithmetic, at 10,200 MiB against a 12288 x 0.97 = 11,919.36 MiB budget. Candidates are 707.375 MiB apart (557.75 MiB of per-slot compute buffer plus 149.625 MiB of per-slot Mamba state, both context-independent), while probing higher costs a uniform 64 KiB/token. The 2-slot candidate is 11,685.0 MiB at 4096 and 11,947.0 MiB at 8192. A display constant moved it across the budget by 27.6 MiB. Two further consequences, both of which unslothai#9492 explicitly claimed it would not have. Its own comment at llama_cpp.py:2831-2841 makes placement-neutrality the correctness criterion for moving this constant. Placement moved anyway, through a call site the analysis did not enumerate: - Device pinning. At 10,200 MiB on a 12 GiB plus 1.25 GiB pair, the 2-slot candidate no longer fits card 0 alone, so the selector adds card 1 and the re-fit runs across both: CUDA_VISIBLE_DEVICES goes from "0" to "0,1", the layer split the block's comment says this path avoids. - Monotonicity. Asking for 2 slots returns 2; asking for 3 returns 1. unslothai#9492's coverage was structurally blind to all of this: test_auto_offload_ctx_platform_matrix.py never passes n_parallel, so all 108 cells ran at the GgufLoadIntent default of 1, and the block is gated on n_parallel > 1. ## The fix Three changes in llama_cpp.py, all in the reduction block: 1. The search is priced at a new local `_reduce_ctx`, which is `min(effective_ctx, _FIT_MIN_CTX)` and never _AUTO_OFFLOAD_CTX. An explicit context is the exception and keeps its own value, since it launches verbatim and a slot count picked at a lower context would not hold. `_FIT_MIN_CTX` rather than a literal because _largest_ctx starts its binary search at the same floor and the two have to agree; that search's `min(4096, _native)` now reads the constant too. 2. The re-fit is applied whenever it exists, not only when it exceeds effective_ctx. That gate was safe only while the search and effective_ctx shared a value. The re-fit is the largest context the FINAL slot count holds on the cards the reduction chose, so anything else launches a context that was never priced. 3. The published ceiling replaces the offload anchor rather than max()-ing with it. Reaching there means the anchor described a plan this block superseded, and max() would advertise a context the launched plan cannot serve, the same ceiling/selection inversion unslothai#9492 removed, pointing the other way. Placement is now invariant to _AUTO_OFFLOAD_CTX, which is what the constant being a display value means. unslothai#9492's intended improvements are all kept: the UI ceiling anchor, the file-size-only arm, and the 8,192 context on loads that do genuinely offload. ## Tests Two of the 26 were genuinely stale: both assert the offload fallback itself, never reach the reduction, and hardcoded 4096. They now read `min(_AUTO_OFFLOAD_CTX, NATIVE_CTX)` so the constant can move again, each with a guard asserting the case still lands in the branch its name claims. The explicit-context one keeps its 32768 literal, since honouring the request verbatim is the contract and a derived value there would assert nothing. TestTheReductionIsPricedAtTheFitFloor is new and pins the root cause: - the plan's slots, residency, context and devices are unchanged across _AUTO_OFFLOAD_CTX in {4096, 8192, 16384, 32768}, so this cannot be satisfied by re-baselining the constant into the expectation; - every size in the rescued band launches --fit off, with `slots < 4` proving it was rescued by the reduction rather than fitting outright; - a counterweight at 11,400 MiB that must still offload, so the band above is not green merely because everything is; - the final slot count is monotone in the requested count, with a guard that the row is not all the same number. test_compute_buffer.py's test_wired_into_both_call_sites counted source substrings and reddened on the variable rename here. It now reads the call sites out of load_model's parse tree and requires every one that passes split_extra_bytes to pass `_cc_split_extra(<name>)`. That turned up a fourth call site the counting version could not see: it counted the two spelled `effective_ctx` plus one spelled `ctx`, and the projector-floor site spells its context `_mm_floor_ctx`, so the check that claimed to cover every call site had never covered it. It has been wired correctly all along. ## Anti-vacuity One mutation at a time against the repaired suites (77 tests): | Mutation | Result | |---------------------------------------------------|------------------| | this branch | 77 passed | | probe put back at the offload fallback | 35 failed | | ceiling put back to max() | 7 failed | | re-fit gated on being an increase again | 16 failed | | explicit context probed at the floor | 2 failed | | _AUTO_OFFLOAD_CTX moved to 4096 | 77 passed | | _AUTO_OFFLOAD_CTX moved to 16384 | 3 failed | Every reintroduction of the defect reddens. Moving the constant to 4096 is fully green, which is the invariance the fix is for. At 16384 the three remaining failures are in test_slot_refit_ctx_checkpoints.py, where the charged case stops reaching the re-fit at all; placement there is still identical at both anchors (4 slots, --fit on, same search) and only the launched context tracks the constant, by design. Left alone rather than re-scoped: that file is green before and after this change. ## Local runs - the three re-fit suites: 77 passed, was 33 passed 26 failed. - 81 placement, VRAM, GPU, context and llama.cpp backend test files, the blast radius of this change: 4033 passed, 2 skipped, 0 failed. Was 1 failed. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Problem
The deterministic VRAM auto-fit (#6312) sizes the hard allocations exactly (weights, KV, draft KV, mmproj file size) and charges the soft runtime overhead to the
_CTX_FIT_VRAM_FRACTIONheadroom (5 percent of total). On tight 24GB tiers that 5 percent (about 1.2 GiB) is too thin once a vision projector and an MTP draft also sit on the card, so the estimate says a context fits, pins-ngl -1, and then overshoots and offloads to CPU.Reported in #6682 (Qwen3.6-27B MTP at
-c 112128, 29 percent GPU and 300 percent CPU).Measurements
Qwen3.6-27B-MTP UD-Q4_K_XL + mmproj-F16, q8_0 KV, on a 24GB card. Real
llama-serverpeak:The old estimate put 121600 at 22.2 GiB, 1.3 GiB under the real 23.6. That gap is the soft overhead the headroom did not cover: CUDA context (about 330 MiB), the mmproj worst-case buffer (file 884 MiB but the runtime allocates about 1158), and the MTP draft decode graph (about 190 MiB above the draft KV).
Change
Charge that soft overhead to the fit footprint in
load_model, gated so plain dense loads only pay the small CUDA context base:_CUDA_CONTEXT_RESERVE_BYTES320 MiB, always_MMPROJ_VRAM_SAFETY1.4, when a vision projector is on GPU_MTP_DRAFT_COMPUTE_BYTES224 MiB, when MTP reserves GPUThe measured-exact
_estimate_compute_buffer_bytesand_estimate_mtp_overhead_bytesare untouched, so their tests stay green. The plain dense pin (the #5106 20.8GB on 22.8GB case) is unchanged except for the small CUDA base.Validation
Fixes #6682