Repository navigation
Studio: pin GPU at 95% headroom and warn on silent CPU fallback - #5323
Conversation
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
There was a problem hiding this comment.
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.
| 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: |
There was a problem hiding this comment.
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
- 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 |
There was a problem hiding this comment.
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?
|
This PR appears to address open issue(s). The duplicate detector matched the following open issues with HIGH confidence:
If this PR fixes any of them, consider adding |
There was a problem hiding this comment.
💡 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: |
There was a problem hiding this comment.
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 👍 / 👎.
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_gpusand the auto-ctx pin loop instart_llama_serverused apool * 0.90threshold to decide whether the model fits on GPU. Models that need 91-94% of free VRAM were classified as "does not fit", so Studio setgpu_indices = Noneand emitted--fit onto llama-server without-ngl.The unsloth llama.cpp fork's
--fit onthen 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:
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 -1directly.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 tomin(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_gpusdecides whether to pin at all, where being conservative pushes layers to CPU.2. Warn on silent CPU fallback after load
After
_wait_for_healthsucceeds, scan llama-server's stdout formodel buffer sizelines. 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)-ngl -1,nvidia-smishows full VRAM utilization, no--fit onin the launch commandNew 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 GPUtest_explicit_ctx_at_94_pct_pins_to_gpu-- explicit ctx branch agrees with auto ctx at the 95% thresholdtest_genuine_overflow_still_uses_fit-- guards against threshold over-broadening; truly oversized models still fall back to--fit onTestClassifyGpuOffload(7 cases):test_cuda_buffer_present_returns_truetest_cpu_only_buffer_returns_falsetest_no_buffer_lines_returns_nonetest_no_gpus_detected_returns_nonetest_user_did_not_intend_gpu_returns_nonetest_rocm_buffer_marker_returns_truetest_metal_buffer_marker_returns_trueRefs #5106