Skip to content

Studio: pin GPU at 95% headroom and warn on silent CPU fallback - #5323

Merged
danielhanchen merged 4 commits into
mainfrom
dh/fix-5106-gpu-pin-threshold-and-cpu-fallback-warn
May 13, 2026
Merged

danielhanchen merged 4 commits into
mainfrom
dh/fix-5106-gpu-pin-threshold-and-cpu-fallback-warn

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Summary

Two related runtime-side fixes for #5106 ("model loaded fully on RAM instead of VRAM"). Companion to #5322, which fixes the Windows install-time half (paired cudart bundle).

1. Bump GPU pin threshold from 0.90 to 0.95

_select_gpus and the auto-ctx pin loop in start_llama_server used a pool * 0.90 threshold to decide whether the model fits on GPU. Models that need 91-94% of free VRAM were classified as "does not fit", so Studio set gpu_indices = None and emitted --fit on to llama-server without -ngl.

The unsloth llama.cpp fork's --fit on then ran with its default --fit-target 1024 (1 GiB margin per device, an upstream default inherited from ggml-org/llama.cpp#18679). On a tight fit where compute buffers + CUDA context push the projected free below the 1 GiB target, the fork's fit logic shaves layer weights off the GPU. Slow inference for users whose models would have loaded comfortably with -ngl -1.

The reproducer from noahterbest in #5106:

GGUF size: 20.8 GB, est. KV cache: 0.1 GB, context: 4096,
GPUs free: [(0, 22805)], selected: None, fit: True

20.8 GiB on a 22.27 GiB free RTX 4090 is 94% utilization. The model fits (1.4 GiB headroom), but the 0.90 threshold kicks it to fit mode. With this change the same case stays in the fits-on-GPU branch and Studio emits -ngl -1 directly.

The auto-ctx fallback also re-checks fit at 4096 before handing off to --fit on: a 20.8 GiB model with a 131072 native context fails the auto loop at native ctx, falls back to min(4096, ctx), but its weights + 4096 KV pin to the GPU comfortably. Without the re-check we still emitted --fit on.

_fit_context_to_vram's 0.90 budget for context binary search is intentionally left tighter than the pin fraction. That routine chooses the slider value, where over-promising would OOM at runtime. _select_gpus decides whether to pin at all, where being conservative pushes layers to CPU.

2. Warn on silent CPU fallback after load

After _wait_for_health succeeds, scan llama-server's stdout for model buffer size lines. If Studio detected GPUs and intended GPU use but only CPU buffers were allocated, log a structured warning that cites #5106. Markers cover CUDA / ROCm / Metal / Vulkan / OpenCL / SYCL backends. New _gpu_offload_active: Optional[bool] field surfaces the result for any future API consumer.

This catches runtime-load failures the install-time fix in #5322 cannot cover: user overriding --fit-target, uncommon driver + toolkit configurations, future regressions in the install path.

Test plan

  • python -m pytest studio/backend/tests/test_llama_cpp_context_fit.py (25 passed: 15 baseline + 10 new)
  • python -m pytest studio/backend/tests/test_llama_cpp_max_context_threshold.py studio/backend/tests/test_llama_server_args.py studio/backend/tests/test_kv_cache_estimation.py (all green)
  • Validate on an RTX 4090 (24 GB) with a ~20 GB model: GPU pins to -ngl -1, nvidia-smi shows full VRAM utilization, no --fit on in the launch command
  • Validate on a multi-GPU host: 2x and 3x GPU subsets still pin correctly when the model fits
  • Validate the warning fires on a deliberately broken Windows host where cudart cannot be resolved

New tests added in studio/backend/tests/test_llama_cpp_context_fit.py:

TestTightFitPinsToGPU (3 cases):

  • test_rtx_4090_qwen_24gb_class -- noahterbest's exact reproducer: 20.8 GiB model on 22.8 GiB free, auto ctx pins to GPU
  • test_explicit_ctx_at_94_pct_pins_to_gpu -- explicit ctx branch agrees with auto ctx at the 95% threshold
  • test_genuine_overflow_still_uses_fit -- guards against threshold over-broadening; truly oversized models still fall back to --fit on

TestClassifyGpuOffload (7 cases):

  • test_cuda_buffer_present_returns_true
  • test_cpu_only_buffer_returns_false
  • test_no_buffer_lines_returns_none
  • test_no_gpus_detected_returns_none
  • test_user_did_not_intend_gpu_returns_none
  • test_rocm_buffer_marker_returns_true
  • test_metal_buffer_marker_returns_true

Refs #5106

Two related runtime-side fixes for #5106 ("model
loaded fully on RAM instead of VRAM"):

1. GPU pin threshold bump 0.90 -> 0.95
-------------------------------------

``_select_gpus`` and the auto-ctx pin loop in ``start_llama_server``
used a ``pool * 0.90`` threshold to decide whether the model fits on
GPU. Models that needed 91-94% of free VRAM were classified as "does
not fit", so Studio set ``gpu_indices = None`` and shipped
``--fit on`` to llama-server without ``-ngl``. The unsloth
llama.cpp fork's ``--fit on`` then ran with its default
``--fit-target 1024`` (1 GiB margin per device, an upstream default
inherited from ggml-org#18679). On a tight fit where compute
buffers + CUDA context push the projected free below the 1 GiB
target, the fork's fit logic shaves layer weights off the GPU --
slow inference for users whose models would have loaded comfortably
with ``-ngl -1``.

The classic reproducer from #5106 (noahterbest's log):

    GGUF size: 20.8 GB, est. KV cache: 0.1 GB, context: 4096,
    GPUs free: [(0, 22805)], selected: None, fit: True

20.8 GiB on a 22.27 GiB free RTX 4090 is 94% utilization. The model
fits (1.4 GiB headroom), but the 0.90 threshold kicks it to fit
mode. Bumping to 0.95 keeps these in the fits-on-GPU branch and
emits ``-ngl -1`` directly. The fork's ``--fit on`` still serves as
the safety net for the genuinely-too-large case.

The auto-ctx fallback also re-checks fit at 4096 before handing off
to ``--fit on``: a 20.8 GiB model with a 131072 native context fails
the auto loop at native ctx, falls back to ``min(4096, ctx)``, but
its weights + 4096 KV pin to the GPU comfortably. Without the
re-check we still emitted ``--fit on``.

``_fit_context_to_vram``'s 0.90 budget for context binary search is
intentionally left tighter than the pin fraction. That routine
chooses the slider value, where over-promising would OOM at runtime.
``_select_gpus`` decides whether to pin at all, where being
conservative pushes layers to CPU.

2. Belt-and-suspenders: warn on silent CPU fallback
---------------------------------------------------

After ``_wait_for_health`` succeeds, scan llama-server's stdout for
``model buffer size`` lines. If Studio detected GPUs and intended
GPU use but only CPU buffers were allocated, log a structured
warning citing #5106. Markers cover CUDA / ROCm / Metal / Vulkan /
OpenCL / SYCL backends. New ``_gpu_offload_active: Optional[bool]``
field surfaces the result for any future API consumer.

This catches runtime-load failures the install-time fix cannot
cover (cudart bundle pairing PR #5322 is the install-side
companion): user overriding ``--fit-target``, uncommon driver +
toolkit configurations, future regressions in the install path.

Tests: 10 new cases in studio/backend/tests/test_llama_cpp_context_fit.py:
* TestTightFitPinsToGPU x3: noahterbest's exact reproducer (auto and
  explicit ctx pins to GPU at 94%); guard against threshold over-
  broadening (genuine overflow still falls back to ``--fit on``).
* TestClassifyGpuOffload x7: CUDA / ROCm / Metal buffer markers
  return True; CPU-only buffer lines return False; absent buffer
  lines or no GPUs detected return None (no warning).

25 context-fit tests pass (15 baseline + 10 new). 511 tests total
across the affected test files. No regressions.

Refs #5106

@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 increases the GPU VRAM pin threshold from 0.90 to 0.95 and introduces a fallback mechanism that attempts to fit models at a reduced context length before defaulting to CPU offloading. Additionally, it adds a diagnostic utility to detect silent CPU fallbacks by parsing llama-server logs for GPU buffer allocations. Feedback suggests refactoring duplicated logic for finding fitting GPU subsets into a centralized helper method to improve maintainability.

Comment on lines +2119 to 2134
if effective_ctx > 0:
for n_gpus in range(1, len(ranked) + 1):
subset = ranked[:n_gpus]
pool_mib = sum(free for _, free in subset)
kv = self._estimate_kv_cache_bytes(
effective_ctx,
cache_type_kv,
n_parallel = n_parallel,
)
total_mib = (model_size + kv) / (1024 * 1024)
if total_mib <= pool_mib * pin_fraction:
gpu_indices = sorted(idx for idx, _ in subset)
use_fit = False
break

elif gpus:

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

This logic for finding a GPU subset that can fit the model is very similar to the loop above (lines 2087-2105). To improve maintainability and avoid code duplication, you should extract this logic into a private helper method. This aligns with the repository rule to centralize recurring or complex logical checks into a single helper function to ensure consistency and simplify maintenance.

if effective_ctx > 0:
    gpu_indices, use_fit = self._find_fitting_gpu_subset(
        effective_ctx, ranked, model_size, cache_type_kv, n_parallel, pin_fraction
    )
References
  1. Centralize recurring or complex logical checks (like determining if a host is external) into a single helper function and reuse it across the codebase to ensure consistency and simplify maintenance.

# compute buffers; 0.90 was too conservative and dropped 91-94%
# fits to CPU offload (#5106). The fork's --fit on still catches
# the truly-too-large case.
_GPU_PIN_VRAM_FRACTION = 0.95

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.

Maybe we should have a small check. If 0.05 (the remaining) is at least 1GB, we good. Otherwise fallback to 0.9 or whatever ensures that we have 1GB free?

@danielhanchen

Copy link
Copy Markdown
Member Author

This PR appears to address open issue(s). The duplicate detector matched the following open issues with HIGH confidence:

  • unslothai/unsloth#5106 — @senyiloo7227 — PR fixes Studio llama.cpp GPU selection/offload fallback where detected GPUs still load intended GPU models on CPU/RAM.
  • unslothai/unsloth#4857 — @xyehya — Issue says --fit leaves VRAM unused and offloads layers to CPU; PR pins tight 95% VRAM fits to GPU instead of --fit.

If this PR fixes any of them, consider adding closes #N / resolves #N to the description so the issue auto-closes on merge. If the match is wrong, ignore this comment.

@danielhanchen danielhanchen added the auto-reviewing Auto-review in progress label May 10, 2026

@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: d9e7506880

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

)
total_mib = (model_size + kv) / (1024 * 1024)
if total_mib <= pool_mib * 0.90:
if total_mib <= pool_mib * pin_fraction:

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 Keep auto context capped when weights exceed 90%

In auto-context mode, if the model weights alone are between 90% and 95% of the selected GPU pool and the native KV cache is small enough to keep the total under 95%, _fit_context_to_vram() returns the unchanged native context because the weights already exceed its 90% budget, and this new 95% check then treats that uncapped value as a successful fit. In that case the block above has already set max_available_ctx to the 4096 fallback, but the server is launched with the full native -c, so Studio can over-promise context and risk the OOM path the tighter 90% context budget is meant to avoid; e.g. a ~21.2 GiB model with tiny KV on a 24,000 MiB-free GPU now pins native context instead of falling back to 4096/--fit.

Useful? React with 👍 / 👎.

@danielhanchen
danielhanchen merged commit 5205bc0 into main May 13, 2026
33 checks passed
@danielhanchen
danielhanchen deleted the dh/fix-5106-gpu-pin-threshold-and-cpu-fallback-warn branch May 13, 2026 11:48
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

auto-addresses-issue Pre-flight: appears to address an open issue auto-reviewing Auto-review in progress

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants