Skip to content

Studio: reserve CUDA context and mmproj/MTP soft overhead in the GGUF fit budget - #6718

Merged
oobabooga merged 11 commits into
mainfrom
studio-vram-fit-tight-tiers
Jul 3, 2026
Merged

oobabooga merged 11 commits into
mainfrom
studio-vram-fit-tight-tiers

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

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_FRACTION headroom (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-server peak:

ctx real peak result
121600 (old auto pick) 23.6 GiB offloads, about 42 tok/s
98560 (new auto pick) 21.9 GiB full GPU, about 62 tok/s

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_BYTES 320 MiB, always
  • _MMPROJ_VRAM_SAFETY 1.4, when a vision projector is on GPU
  • _MTP_DRAFT_COMPUTE_BYTES 224 MiB, when MTP reserves GPU

The measured-exact _estimate_compute_buffer_bytes and _estimate_mtp_overhead_bytes are 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

  • All fit, KV, compute-buffer, MTP and context tests pass.
  • Real launches across 9B, 27B, 35B-A3B (MoE), gemma 12b/31b (vision) at 16 to 192 GB: the chosen context fits with margin, and the earlier picks that overshot a real 24GB card no longer do.

Fixes #6682

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

Comment on lines +5067 to +5074
# 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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

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:

  1. Remove the redundant assignment model_size_fit = model_size + _compute_buffer_pipeline at line 5029.
  2. Move the definition of _subset_model_size (lines 5038-5039) to be after line 5074, once model_size_fit has been fully computed with the soft overhead.

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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
@danielhanchen
danielhanchen force-pushed the studio-vram-fit-tight-tiers branch from 9b401b1 to e0469c8 Compare June 27, 2026 12:26
@danielhanchen

Copy link
Copy Markdown
Member Author

Thanks for the reviews. Addressed in the latest push (rebased onto current main):

  1. Dead model_size_fit assignment and closure ordering (Gemini): removed the now-redundant model_size_fit = model_size + _compute_buffer_pipeline, and _subset_model_size is now defined after model_size_fit is fully computed, so it no longer relies on late binding.

  2. CUDA reserve on Apple Metal (Codex): the CUDA/cuBLAS context base is now gated on a discrete GPU being present (_CUDA_CONTEXT_RESERVE_BYTES if gpus else 0). The Metal no-GPU cap below shares model_size_fit, so it no longer over-reserves 320 MiB on Apple Silicon. The mmproj worst-case buffer and the MTP draft graph are kept on every backend since they are allocated regardless of the GPU API.

  3. Tensor-parallel pre-check (Codex): the tensor path passes raw model_size to _plan_tensor_parallel, which computes its own per-device compute buffer, so it deliberately does not consume model_size_fit. Folding the lump model_size_fit in there would double-count that buffer, and the CUDA context is per device, so a correct reserve has to be threaded into the planner per device. That is a separate change from this single-GPU fit fix and is not a regression from this PR, so I left it as a follow-up. Note the mmproj part is moot on that path anyway, since tensor split is disabled for vision models.

All fit, KV, compute-buffer, MTP and context tests pass.

@oobabooga

Copy link
Copy Markdown
Member

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 -ngl -1, nothing offloaded, MTP active.

reserve auto-pick ctx bare llama-server through Studio
#6718 (this PR) 90624 53.5 44.0
#6688 (floored max(5%, 3 GiB)) 66560 53.5 54.3

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}'

@danielhanchen

Copy link
Copy Markdown
Member Author

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
footprint with nvidia-smi --query-compute-apps (per-PID), so other users on the shared
card never inflate the numbers. GPU-total measurements were discarded after they produced
false overshoots (a 2B showed an 18 GiB "peak" that was 13 GiB of someone else's allocation;
its true footprint is 4.4 GiB).

Coverage

28 tightest cells (worst case per model x {MTP, non-MTP}) plus 4 giants, all fully
GPU-offloaded with no CPU spill:

  • Gemma-4 E2B / E4B / 12B / 26B-A4B / 31B, non-MTP and separate-drafter MTP (mtp-*.gguf).
  • Qwen3.5 2B/4B/9B, Qwen3.6 27B/35B-A3B, non-MTP and embedded MTP (nextn). Q4/Q3/Q2_K_XL.
  • Giants, layer-split across 3 GPUs: 122B-A10B (MoE+MTP), GLM-5.2 IQ1_S (MLA, 1M ctx,
    predicted 262.9 vs real 263.4 GiB), 397B-A17B (MoE, +/- MTP), Kimi-K2.7 Q2 (MLA 316 GiB).
  • Budgets 8/12/16/24/48 GB measured; 96/192 GB and multi-GPU computed (strictly looser).

Separate vs embedded MTP both confirmed; non-MTP confirmed unaffected (the MTP-repo models
with MTP off fit identically).

A third bug this PR does not yet cover: context-linear compute buffer

_estimate_compute_buffer_bytes is modelled flat (~40 MiB) but the real flash-attn compute
buffer is linear in context (from #6312, predates this PR). Confirmed real, not
contamination: Qwen3.5-4B Q4 at 256k on an 8 GB budget really needs ~8.5 GiB on a real
card (weights 2.4 + KV 4.3 + compute 1.3 + CUDA ctx) and spills to CPU. The soft overhead in
this PR does not catch it because the term scales with context, not a flat reserve.

Measured slope (q8_0 KV, ubatch 512):

model n_embd compute @256k slope / n_embd
Qwen3.5-2B 2048 0.78 GiB 1.50
Qwen3.5-4B 2560 1.30 GiB 2.02 (worst)
Qwen3.5-9B 4096 1.30 GiB 1.25
Qwen3.6-27B 5120 1.33 GiB 0.99
Gemma-4-12B 3840 0.80 GiB 0.74
Gemma-4-31B 5376 2.34 GiB 1.69

Proposed fix (separate follow-up PR, +59 lines, monotonic, backwards compatible): add a
context-linear term to the fit, 2.25 x n_embd x n_ctx, which upper-bounds the worst case
plus the under-modelled flat base. It only ever lowers a pinned context (never breaks a
fitting pin). With it the 4B @ 8 GB case caps to ~210k and fits.

KV-cache quantization changes the compute buffer too

The KV cache type is already budgeted correctly on the supply side. It also moves the
compute buffer, because a quantized cache needs a context-sized dequant scratch and f16 does
not. Qwen3.5-4B at 256k: 1.30 GiB compute at q8_0 vs 0.31 GiB at f16. So the follow-up
uses 2.25 x n_embd for a quantized cache and 0.5 x n_embd for f16/bf16/f32 (unknown ->
quantized, the safe default); otherwise f16 runs lose context to a dequant scratch they never
allocate. Validated: 4B Q4 @ 8 GB with f16 KV pins 148k (vs 218k at q8_0, the 2x KV
dominating) and fits.

Overhead floor: 5% -> 3%

With the compute buffer modelled, the predicted footprint over-predicts the real (real-card)
footprint on every tightest cell (-1.9% to -25% of budget), so the cushion no longer has to
cover it. Its remaining job is fragmentation + unknown allocations + the per-device CUDA
context on a multi-GPU split (397B on 3 GPUs under-predicts by 2.7%, which sets the floor).

I am changing _CTX_FIT_VRAM_FRACTION and _GPU_PIN_VRAM_FRACTION from 0.95 to 0.97
(3%)
. Re-validated: all 19 tightest cells re-pin larger (e.g. Gemma-31B @ 24 GB 48k -> 58k,
Qwen3.5-9B @ 8 GB 20k -> 26k) and still fit on a real card (tightest is 4B @ 8 GB at
7.6 / 8 GiB). Below 3% a single fragmentation spike or the 3-GPU CUDA-context delta overflows,
so 3% is the floor. 503 unit tests pass.

For comparison: #6688 moved _GPU_PIN_VRAM_FRACTION the other way (0.90), which reintroduces
the #5106 regression (a 20.8 GiB load on 22.8 GiB free offloads to CPU at 0.90 but pins at
0.95+). The fix for spills is to model the compute buffer, not to shrink the pin fraction.

@256k

256k commented Jun 30, 2026

Copy link
Copy Markdown

yes i concur

@danielhanchen

Copy link
Copy Markdown
Member Author

Follow-up: overhead -> 3%, KV-quant awareness, multi-GPU + MLA fixes

Reduced the overhead cushion and fixed four more issues the validation surfaced, then
physically re-checked the larger giant quants. All per-PID (contamination-proof). 799
Studio fit/compute/KV/MTP unit tests pass.

Overhead 5% -> 3%

_CTX_FIT_VRAM_FRACTION and _GPU_PIN_VRAM_FRACTION are now 0.97. With the compute
buffer modelled, the predicted footprint over-predicts the real (real-card) footprint on
every tightest cell, so the cushion no longer covers it. Kept at 3% and not lower: its
remaining job is fragmentation + unknown allocations + the per-device CUDA context on a
multi-GPU split, which measure ~2-3%. Re-validated: all 19 tightest cells re-pin to a
larger context at 3% (e.g. Gemma-31B @ 24 GB 48k -> 58k) and still fit on a real card.

KV-cache quantization changes the compute buffer

KV quant is budgeted correctly on the supply side already. It also moves the compute
buffer: a quantized cache needs a context-sized dequant scratch, f16 does not. Measured
Qwen3.5-4B at 256k: 1.30 GiB compute at q8_0 vs 0.31 GiB at f16. The context-linear
term is now KV-quant-aware:

  • Quantized (q8_0/q5/q4/iq4), regular attention: 2.25 x n_embd per token.
  • f16/bf16/f32: KQ mask only, a flat n_ubatch*2 bytes per token, independent of n_embd
    (measured 1024 B/tok on Qwen-9B and Gemma-31B alike). Was 0.5 x n_embd, which
    over-charged large f16 models.
  • cache_type_kv None -> f16 (llama.cpp's default), which also fixes the tensor-parallel
    path (it drops quantized KV to f16). An env-set quantized cache is budgeted as f16 on
    the KV side, whose over-reservation absorbs the dequant scratch.

Per-device compute buffer in a layer split

The 397B multi-GPU case under-predicted by ~2.7%. Root cause from the server log: in a
layer split the compute buffer is replicated on every device (CUDA0/1/2 each reserve
~1673 MiB for 397B at 256k, ~5 GiB total) but the estimator counted it ~once. Fix: scale
the context-linear term by the device count. General, not MoE-specific; single-GPU
unchanged. With it, Qwen3.5-397B goes from under-predicting to a true upper bound.

MLA models need a lighter compute rate

MLA (compressed attention) needs far less dequant scratch than regular attention:
measured 0.94 x n_embd on GLM-5.2 and Kimi-K2.7 vs up to 2.02x on Qwen/Gemma. Charging
the regular 2.25x rate (times the per-device count above) badly over-reserved a tight MLA
multi-GPU pin. MLA (kv_lora_rank present) now uses 1.25 x n_embd.

Larger giants (multi-GPU layer split across 3 GPUs, per-PID)

model quant ctx predicted real verdict
GLM-5.2 (MLA) UD-IQ2_XXS 1,048,576 283.2 283.6 FIT
GLM-5.2 (MLA) UD-Q4_K_XL 754,688 479.3 476.5 FIT
GLM-5.2 (MLA) all-fixes UD-IQ1_S 1,048,576 273.9 263.4 FIT (upper bound)
Qwen3.5-397B-A17B (MoE) UD-Q3_K_XL +/-MTP 262,144 177 180-182 FIT
Kimi-K2.7-Code (MLA) UD-Q2_K_XL 262,144 329.6 331.3 FIT

GLM-5.2 with all four fixes predicts 273.9 GiB vs a real 263.4 (a true upper bound) and
still pins the full 1M context. Weights were really downloaded (GLM IQ1_S/IQ2/Q4 up to
435 GiB, 397B, Kimi) and deleted after each check.

@danielhanchen

Copy link
Copy Markdown
Member Author

Tensor parallelism (--split-mode tensor): the compute buffer grows with context there too

Checked what the compute-buffer fix does when tensor parallelism is enabled. It exposed
that the fix was wired into the layer-split path only: the tensor-parallel planner
(_plan_tensor_parallel) reserved just a flat, context-independent per-device compute
buffer, so at high context on a tight pool it over-pinned the same way layer split used
to. Fixed and measured.

Measured: the TP compute buffer is context-linear and per-device

Real --split-mode tensor load of Qwen3.5-9B (Q4_K_XL) across 2 GPUs, f16 KV (tensor mode
forces a non-quantized cache), per-PID accounting:

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.
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.
Repo admins can enable using credits for code reviews in their settings.

@danielhanchen

Copy link
Copy Markdown
Member Author

@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 math

Studio serves llama-server with a fixed --parallel 4 (the unsloth studio run default). Each extra slot needs a large transient decode workspace that the context fit never reserved (it only reserved the static per-slot output buffers, so the model "fits" with no spill). On a memory-constrained card at the auto-picked max context, free VRAM drops to ~1-3 GiB, and at that edge llama.cpp shrinks the --parallel 4 compute graph and decode collapses to about 40% throughput. --parallel 1 never reaches that edge and stays fast, which is why your bare --parallel 1 repro ran full speed while the larger auto-picked context through Studio did not.

Reproduced on a single card ballooned to ~24 GB, 27B-MTP Q4, ctx 90624:

config tok/s
--parallel 4 --kv-unified @ 66560 42.1
--parallel 4 --kv-unified @ 90624 36.0
--parallel 1 @ 90624 88.7

So under pressure --parallel 4 runs at ~40% of --parallel 1 and degrades further with context, matching your pattern. Ruled out with data: the reserve math (the fit is correct, no spill), the prompt cache (disabling it barely moved it, 36.8 vs 38.9), n_predict (forcing a smaller max_tokens did not change decode), and the KV cache type.

Fix (pushed to this branch)

A memory-aware serving-slot cap. A new estimator reserves the transient decode workspace per slot (dim-scaled by n_embd * n_layers, MTP-aware), and the loader reduces the effective --parallel to what the tightest device can decode at full speed, without shrinking the auto-picked context. It only ever reduces, floors at 1, and is a byte-for-byte no-op on roomy cards (they keep all 4 slots and the max context). On the 24 GB / 27B / 90624 case it now serves 1 slot and recovers about 36 to 88 tok/s; roomy cards are unchanged.

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.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.
Repo admins can enable using credits for code reviews in their settings.

@oobabooga

Copy link
Copy Markdown
Member

Reproduced the --parallel 4 collapse on a real 3090, and measured the actual slot cost and the embedder. Same model as your table: Qwen3.6-27B-MTP UD-Q4_K_XL with mmproj-F16, q8_0 KV, MTP on, -ngl -1, ctx pinned to 90624. Bare llama-server with Studio's exact flags, 2-run average.

1. The collapse reproduces (Studio's path: --fit on)

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 4 costs ~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 off proves it.
  • The RAG embedder is a real but minor factor. 336 MiB takes --parallel 1 from 54 to 45 tok/s (~17%), and only under --fit on. Under --fit off it is 54.2 vs 54.6, so no effect.
  • Both slowdowns are the same fit-step offload. --parallel 4 is 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.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Comment on lines +3144 to +3147
mtp_total = (
mtp_overhead_fn(effective_ctx)
if (mtp_active and mtp_overhead_fn is not None)
else 0

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Comment on lines +3170 to +3173
per_device_load = (
(model_size + kv_total + mtp_total + mmproj_bytes) / n_dev
+ static
+ cuda_reserve

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Comment on lines +4540 to +4542
even_share_mib = (
(model_size + kv_bytes + mtp_bytes + cc_bytes) / len(gpu_indices) / (1024 * 1024)
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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).
@danielhanchen

Copy link
Copy Markdown
Member Author

Pushed a follow-up (1a038f3) for the --parallel 4 collapse you measured.

Your --fit off control was the key: it is the fit step offloading to host, not llama.cpp shrinking the decode graph at the edge. Studio flips to --fit on when it estimates the model does not fit at 4 slots, and llama-server then offloads layers, which is the ~3x drop. Two problems with what was there:

  1. The decode-workspace reserve I had added was calibrated to a B200 allocator artifact: par4 with -ngl -1 needs ~8 GiB free on a B200 to stay fast, but only ~0.35 GiB on your 3090, so it did not represent real hardware.
  2. It was gated on the non-offload path, so it never ran in the --fit on case that actually collapses.

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 (-ngl -1), keeping the chosen context. Only ever reduces; roomy cards keep all 4. This is the "scale slots to VRAM" direction you suggested, applied at the offload decision. I deleted the decode-workspace estimator and its constants; no KV or compute-buffer estimator changed, so model and quant fit behavior is unchanged (full fit suite green, plus new tests for the reduction).

On --kv-unified: confirmed Studio sets it by default for --parallel > 1, and I measured it memory-neutral on this build (par4 24067 MiB with, 23986 without), so it is not saving memory here; its role is keeping the full per-request context.

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.

@oobabooga

Copy link
Copy Markdown
Member

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 --parallel 4, and it does neither. It does not reduce at all: it stays at --parallel 4 --fit on, offloads layer 0, and collapses to ~18 tok/s, same as before the fix.

I put a log line in _slots_that_fit_on_gpu to see why the reduction never fires. It runs, tries 3/2/1 slots, and rejects all three against the 0.97 pin budget (23314 MiB), so it gives up and keeps 4 slots:

slots footprint estimate vs budget
3 24570 MiB reject
2 24012 MiB reject
1 23455 MiB reject

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 --fit off (22413), which is enough to put even a single slot over budget. It is not KV: est. KV = 3197 MiB is the correct hybrid value (full_attention_interval=4 gives 17 attention layers, 17 * 90624 * 4 * 512 * 1.0625 = 3197). It is the soft-overhead reserves, and then the 0.97 pin fraction reserves another ~720 MiB on top of an estimate that is already padded.

Bare llama-server at the same flags, for the real numbers (only --fit on at 4 slots offloads, which is the collapse):

config @ 90624 GPU used tok/s placement
--fit off p1 22413 MiB 55.6 on GPU
--fit off p4 --kv-unified 23759 MiB 52.1 on GPU
--fit on p1 22413 MiB 52.4 on GPU
--fit on p4 --kv-unified 21115 MiB 19.0 offloaded

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:

Studio, --parallel 4 @ 90624 reduction launched tok/s
1a038f3 (embedder warm) none --parallel 4 --fit on, offloaded 18
+ fix (embedder warm) 4 -> 1 --parallel 1, on GPU 44
+ fix, embedder freed 4 -> 1 --parallel 1, on GPU 54

Two things worth noting:

  1. It reduces to 1 slot, not the 2-3 the card holds, because of that same soft-reserve padding. That is the 1.15 output-buffer margin you flagged; trimming it would keep more slots.

  2. The 44 with the embedder warm vs 54 without is the RAG embedder. With the fix the model is on GPU, but the startup-warmed embedder (336 MiB) is still resident, so ~291 MiB of the model spills to host. Freeing it before the load (Studio: stop the idle RAG embedder from holding inference VRAM and slowing generation #6744) recovers the rest. So for this model it takes both changes.

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.
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.
Repo admins can enable using credits for code reviews in their settings.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@danielhanchen

Copy link
Copy Markdown
Member Author

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 --parallel 4, auto context: 0 differences. This change only adjusts the serving-slot count on the offload path, so context selection is byte for byte the same, and auto context is always chosen to fit on GPU (the default path never offloads).

Model native 8G 12G 16G 20G 24G 32G 40G 48G+
Qwen3.5-9B 256k 4k 80.5k 204k 256k 256k 256k 256k 256k
Qwen3.6-27B 256k 4k 4k 4k 4k 63.2k 218k 256k 256k
Qwen3.6-35B-A3B 256k 4k 4k 4k 4k 4k 256k 256k 256k
gemma-4-31b 256k 4k 4k 4k 4k 4.2k 123.2k 256k 256k

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.

Model 8G 12G 16G 20G 24G 32G 40G 48G+
Qwen3.5-2B fix to 3 on GPU on GPU on GPU on GPU on GPU on GPU on GPU
Qwen3.5-9B offload offload fix to 1 on GPU on GPU on GPU on GPU on GPU
Qwen3.6-27B offload offload offload offload offload offload +1 slot on GPU
gemma-4-26B-A4B offload offload offload offload fix to 2 on GPU on GPU on GPU
gemma-4-31b offload offload offload offload offload offload +2 slot on GPU

offload = native 256k pinned on a card too small, both versions offload (auto context avoids it). fix to N = before offloaded to host, after keeps N slots fully on GPU. +N slot = after keeps N more slots on GPU than before.

3. Live confirmation (27B UD-Q4_K_XL, ballooned card)

Config Layers tok/s
-ngl -1, all on GPU 65/65 63-72
25 layers on host 40/65 7.0
--fit on par4, real footprint > card spills to host 7.0
--fit on par4, real footprint < card all on GPU 71.9

Host offload is about 9x slower. --fit on offloads only when the real footprint exceeds the card; when it fits, it stays on GPU. The after-PR -ngl -1 path ran fully on GPU at full speed across the whole sweep (2B 333, 9B 181, 27B 72 tok/s), no OOM.

Verdict

The after-PR code takes the on-GPU path (-ngl -1 at fewer slots) in exactly the regime where before flipped to --fit on and offloaded. The offload path is measured about 9x slower and the on-GPU path is measured at full speed, matching the 54 vs 18 tok/s collapse reported on the 3090. Context length never changes.

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.

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

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

Comment on lines +4513 to +4515
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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.
Repo admins can enable using credits for code reviews in their settings.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.
Repo admins can enable using credits for code reviews in their settings.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.
Repo admins can enable using credits for code reviews in their settings.

@oobabooga

Copy link
Copy Markdown
Member

Two changes on top of the PR, both tested live on a real 3090 (24 GB) and RTX 6000 Ada (49 GB).

  1. Pass --fit off on the fully-on-GPU launch so llama.cpp respects Studio's placement instead of second-guessing it and offloading ~1 GB (which halved decode). If the forced load ever OOMs, it retries once with --fit on and offloads rather than failing.
  2. Reserve the same VRAM overhead in the tensor-parallel planner that the single-GPU path already reserves, and fix the split across uneven GPUs so the smaller card isn't handed more than it holds. Without it, tensor mode could over-commit and OOM at startup.

--fit off fix, single 3090:

check result
auto load ctx 56320, on GPU (22780 MiB), 54-56 tok/s (was ~30 offloaded)
slot reduction (--parallel 4) reduces 4 -> 1 slots to stay on GPU
OOM fallback (forced --fit off @ 200k ctx) try0 OOMs (exit -11), retries --fit on, loads offloaded, no failed load
spec compliance 102/102

Tensor-parallel fix, Ada 49 GB + 3090 24 GB:

check result
live load across both GPUs splits over Ada + 3090 (20 + 18 GB), 77 tok/s, no OOM
uneven-split math (40 GB model, 3090 the smaller card) fix keeps the 3090 at 23.6 of its 23.8 GB budget; the old math gave it 23.9 GB and would OOM at load

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.

@oobabooga

Copy link
Copy Markdown
Member

CI green.

@oobabooga
oobabooga merged commit 9c2eacc into main Jul 3, 2026
46 of 47 checks passed
@oobabooga
oobabooga deleted the studio-vram-fit-tight-tiers branch July 3, 2026 16:07
danielhanchen pushed a commit to oobabooga/unsloth that referenced this pull request Aug 23, 2026
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.
danielhanchen added a commit that referenced this pull request Aug 23, 2026
* 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]>
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Aug 23, 2026
…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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] VRAM spill with automatically set context size

4 participants