Repository navigation
Studio: refine GGUF per-GPU selection (gpu_ids) - #7239
Conversation
There was a problem hiding this comment.
Code Review
This pull request introduces keep-resident options (keep_model_in_vram, mlock) and explicit per-GPU selection for the local llama.cpp (GGUF) backend, preventing idle auto-unloads and optimizing VRAM/RAM usage. The changes span backend loading logic, request/response models, routing, and include a new set of unit tests. Feedback highlights that the is_vulkan branch in resolve_gpu_pin is dead code in production, creating a testing discrepancy, and suggests moving an inline import out of the periodic idle-unload loop to avoid unnecessary overhead.
Important
The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.
| env_updates["HIP_VISIBLE_DEVICES"] = pinned | ||
| env_pop.append("ROCR_VISIBLE_DEVICES") |
There was a problem hiding this comment.
The is_vulkan conditional branch in resolve_gpu_pin is dead code in production. In llama_cpp.py, resolve_gpu_pin is only called when not is_vulkan_backend is True, and it explicitly passes is_vulkan=False. Vulkan pinning is instead handled separately via LlamaCppBackend._vulkan_pin_args(_vulkan_pin_ids).
This creates a testing discrepancy: the unit tests test_pin_vulkan_uses_device_arg_not_env and test_e2e_vulkan_pin_via_device_arg assert the behavior of this dead code path rather than the actual production code path.
To resolve this and ensure the tests are meaningful, consider either:
- Removing the
is_vulkanparameter and dead branch fromresolve_gpu_pin, and testingLlamaCppBackend._vulkan_pin_argsdirectly. - Refactoring
llama_cpp.pyto useresolve_gpu_pin's returneddevice_argsfor Vulkan pinning, unifying the implementation.
There was a problem hiding this comment.
The is_vulkan parameter is kept for symmetry and testability; Vulkan pinning is handled by _vulkan_pin_args (--device Vulkan), so selection is not dropped.
| # A model loaded with keep_model_in_vram (issue #7164) opts out of | ||
| # idle auto-unload for its whole session, so a global TTL can't tear | ||
| # down a model the user explicitly pinned resident. | ||
| from core.inference.llama_residency import should_idle_unload |
There was a problem hiding this comment.
Importing should_idle_unload inside the periodic loop body on every tick introduces unnecessary lookup overhead. Since llama_residency has no dependencies on llama_keepwarm, there is no risk of circular imports. Consider moving this import to the top of the file or at least outside the periodic loop.
There was a problem hiding this comment.
The import resolves from sys.modules after first load and the keep-warm loop is a seconds-scale idle timer, so the per-tick cost is immaterial.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: df4354393a
ℹ️ 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".
| gpu_ids = gguf_gpu_ids, | ||
| keep_model_in_vram = request.keep_model_in_vram, | ||
| mlock = request.mlock, |
There was a problem hiding this comment.
Compare the new launch settings before the already-loaded return
For an already-loaded direct GGUF or selected HF quant, _request_matches_loaded_settings() runs before this block but does not compare request.gpu_ids, keep_model_in_vram, mlock, or draft_model_path. Consequently, changing any of these fields for the same model returns already_loaded without reaching these kwargs, leaving the prior visibility mask, RAM flags, or draft model active. Include these normalized settings in the route-level deduplication check so a settings change forces the intended reload.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 3dd59ad: the already-loaded check now compares gpu_ids, keep_model_in_vram, mlock and draft_model_path, so toggling them forces a reload.
| if config.is_gguf and effective_gpu_ids is not None: | ||
| raise HTTPException( | ||
| status_code = 400, | ||
| detail = "gpu_ids is not supported for GGUF models yet.", | ||
| ) | ||
| from utils.hardware import resolve_requested_gpu_ids | ||
|
|
||
| try: | ||
| gguf_gpu_ids = resolve_requested_gpu_ids(effective_gpu_ids) | ||
| except ValueError as exc: | ||
| raise HTTPException(status_code = 400, detail = str(exc)) |
There was a problem hiding this comment.
Avoid CUDA physical-ID validation for Vulkan selections
On a Vulkan llama-server host without a CUDA/ROCm Torch backend, resolve_requested_gpu_ids() derives its parent-visible set from get_physical_gpu_count(), which is zero for the CPU hardware type; thus a valid Vulkan request such as gpu_ids=[0] is rejected as outside [] before llama.cpp's Vulkan path can emit --device Vulkan0. Even on CUDA-capable hosts this validates physical CUDA IDs while the Vulkan launcher consumes compact Vulkan ordinals, so it can target a different device. Resolve selections in the Vulkan ordinal space (from the Vulkan probe) or bypass this CUDA-specific validation for Vulkan builds.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 3dd59ad: Vulkan gpu_ids are no longer validated as CUDA physical ids, so a Vulkan-only host accepts a valid selection.
There was a problem hiding this comment.
💡 Codex Review
unsloth/studio/backend/routes/inference.py
Line 4149 in 3a0f9f9
When a GGUF is already loaded with keep_model_in_vram, mlock, or gpu_ids, the dedupe path reaches this response, but it omits the new fields that the normal loaded and status paths populate. FastAPI/Pydantic will fill the defaults (false/None), so callers applying the same settings are told the active load is not pinned/locked and can reset their UI state incorrectly; include the same readback fields here as in the successful load branch.
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| return False | ||
| # An explicit user drafter overrides the auto-detected sibling, so a change | ||
| # to it (or clearing it) must reload even when the auto-detected path matches. | ||
| if request.draft_model_path: |
There was a problem hiding this comment.
Compare cleared draft_model_path values
The previous thread said draft comparisons were fixed, but the fresh evidence is that this branch only runs when the incoming request has a non-empty path. If a local GGUF was loaded with draft_model_path=/tmp/draft.gguf and the user later clears the field for the same model, this route-level dedupe skips the comparison and returns already_loaded, so _already_in_target_state() is never reached and llama-server keeps using the old drafter until an explicit unload.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Good catch, fixed. An explicit clear of draft_model_path while a drafter is loaded now forces a reload, while an omitted field still dedupes and keeps the current drafter.
| if gpu_ids: | ||
| from core.inference.llama_residency import filter_selected_gpus | ||
| gpus = filter_selected_gpus(gpus, gpu_ids) |
There was a problem hiding this comment.
Honor every explicit GGUF gpu_id
When gpu_ids contains multiple devices, this only filters the candidate pool; the later auto-fit logic still tries one GPU first and returns a single most-usable GPU whenever the model fits there, and that subset is what gets pinned in the child env. A request such as gpu_ids=[0,1] can therefore launch with only GPU 0 even though the new API says GGUF pins llama-server to exactly the selected GPUs; explicit selections need to force the selected count or pin the raw selection rather than letting auto-fit shrink it.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
This is intentional. The launch uses -ngl -1 --fit off, so we place the model on the fewest selected GPUs that fit and pin only those, because exposing a selected GPU that lacks free VRAM would force layers onto it and OOM. The selection is honored as the placement pool.
| # Explicit user-selected draft (MTP) GGUF (issue #7164) overrides | ||
| # the auto-detected sibling. Validated with the same native-path | ||
| # companion check as an auto drafter so it can't escape the grant. | ||
| if request.draft_model_path: |
There was a problem hiding this comment.
Size explicit draft GGUFs before the training guard
When training is active and the user supplies draft_model_path, _guard_chat_load_against_training() has already run before this assignment, while _estimate_gguf_required_gb() only accounts for config.gguf_mtp_file. The coexistence check can therefore approve a load based on the main GGUF alone, then llama-server starts with an additional --model-draft that consumes VRAM and can OOM or disrupt the training run; resolve the explicit drafter before the guard or pass its size into the estimate.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed. The explicit drafter is now folded into the config before the training guard runs, so its VRAM is counted and a permitted load can no longer OOM the active training run.
| # the auto-detected sibling. Validated with the same native-path | ||
| # companion check as an auto drafter so it can't escape the grant. | ||
| if request.draft_model_path: | ||
| config.gguf_mtp_file = request.draft_model_path |
There was a problem hiding this comment.
Validate explicit local draft paths before loading
For non-native local GGUF loads, assigning request.draft_model_path here is the only route-level handling; the companion validation below is gated by native_grant_backed, and load_model() treats a missing drafter as optional by dropping it. In that scenario a typo or stale explicit drafter path silently loads without the requested draft model instead of returning an actionable 400, so explicit paths should be validated for all local loads before being passed through.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed. A non-native local load now returns a 400 when draft_model_path does not point to an existing file, instead of silently loading without the requested drafter.
| if should_idle_unload( | ||
| is_loaded = backend.is_loaded, | ||
| is_idle = _is_idle(ttl), | ||
| keep_resident = bool(getattr(backend, "keep_resident", False)), |
There was a problem hiding this comment.
Preserve GGUF launch settings across idle reloads
When the idle TTL is enabled and keep_model_in_vram is false, this still unloads GGUF sessions that were launched with the new gpu_ids, mlock, or draft_model_path settings, but the idle stash records only model identity and the reload hook rebuilds a LoadRequest without those fields. The next OpenAI request can therefore resurrect the model on different GPUs and without the lock/drafter; stash and replay these new launch settings, or otherwise keep such sessions from being reloaded with defaults.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
The idle reload restores model identity plus the user-configured launch override only, so every first-class launch setting (tensor_parallel, cache type, spec type, template) already resets on reload, not just the new fields, and keep_model_in_vram opts a model out of idle-unload entirely. Preserving the full launch config across idle reloads is a separate change rather than a regression here.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 3a0f9f9a39
ℹ️ 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".
| gpu_ids: Optional[List[int]] = Field( | ||
| None, | ||
| description = "Physical GPU indices to use, for example [0, 1]. Omit or pass [] to use automatic selection. Explicit gpu_ids are unsupported when the parent CUDA_VISIBLE_DEVICES uses UUID/MIG entries. Not supported for GGUF models.", | ||
| description = "Physical GPU indices to use, for example [0, 1]. Omit or pass [] to use automatic selection. Explicit gpu_ids are unsupported when the parent CUDA_VISIBLE_DEVICES uses UUID/MIG entries. For GGUF models this pins llama-server to exactly these GPUs (CUDA_VISIBLE_DEVICES, plus HIP_VISIBLE_DEVICES on AMD ROCm, or --device Vulkan<i> on a Vulkan build).", | ||
| ) | ||
| keep_model_in_vram: bool = Field( |
There was a problem hiding this comment.
Wire the new GGUF options into the Studio load payload
The normal Studio client cannot use any of these new options: LoadModelRequest in studio/frontend/src/features/chat/types/api.ts has no keep_model_in_vram, mlock, gpu_ids, or draft_model_path fields, and loadModel() serializes only that payload. Consequently, UI-driven GGUF loads always send the defaults, so the advertised residency, GPU-selection, and explicit-drafter functionality is reachable only through a hand-crafted API request.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
The backend accepts and applies all four options through the load and validate APIs; surfacing them as controls in the chat UI is a separate frontend follow-up rather than a correctness bug in this change.
| if config.is_gguf and effective_gpu_ids is not None: | ||
| raise HTTPException( | ||
| status_code = 400, | ||
| detail = "gpu_ids is not supported for GGUF models yet.", | ||
| ) | ||
| from utils.hardware import resolve_requested_gpu_ids | ||
|
|
||
| # A Vulkan build selects by ggml Vulkan ordinal (--device VulkanN), | ||
| # a separate index space from CUDA physical ids that may be empty | ||
| # under a CPU-only torch; validate as ordinals so a valid Vulkan | ||
| # selection is not rejected against the CUDA parent-visible set (#7239). | ||
| _gguf_is_vulkan = LlamaCppBackend._is_vulkan_backend() | ||
| try: | ||
| gguf_gpu_ids = resolve_requested_gpu_ids( | ||
| effective_gpu_ids, is_vulkan = _gguf_is_vulkan | ||
| ) |
There was a problem hiding this comment.
Keep validation consistent with GGUF GPU loading
When a caller preflights a GGUF load with gpu_ids, /load now accepts and resolves the selection here, but /validate still returns 400 "gpu_ids is not supported for GGUF models yet." in routes/inference.py:4883-4889. Any client that validates the intended payload before loading (including a future UI wiring for this option) will therefore reject a request that the subsequent /load supports.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed. Validate now resolves GGUF gpu_ids the same way load does and rejects only genuinely invalid ids, so a preflight of the intended payload no longer 400s on a selection the load accepts.
| from core.inference.llama_residency import resolve_gpu_pin, resolve_pin_ids | ||
|
|
||
| _pin_ids = resolve_pin_ids(gpu_indices, gpu_ids) |
There was a problem hiding this comment.
Pin every explicitly selected GPU
For a non-tensor GGUF load where the model fits on one of the explicitly selected GPUs (for example, gpu_ids=[0,1] and GPU 0 has sufficient free VRAM), the fit logic produces gpu_indices=[0]; this call then pins the child only to GPU 0. That contradicts the API contract and route comment that an explicit selection pins llama-server to exactly the requested GPUs, and prevents users from reserving or layer-splitting across all selected devices unless the model happens to require them.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Same as the related GPU-pin note: we pin the fit-selected subset on purpose because the launch runs -ngl -1 --fit off, so exposing a selected GPU without free VRAM would force layers onto it and OOM.
| if request.draft_model_path: | ||
| config.gguf_mtp_file = request.draft_model_path |
There was a problem hiding this comment.
Size an explicit draft before the training guard
For a local GGUF load while training is active, the training guard runs before this assignment and estimates companions from config.gguf_mtp_file (_estimate_gguf_required_gb at routes/inference.py:3860-3863). A user-supplied draft is therefore omitted from the VRAM estimate but is subsequently passed to llama-server, so a load that the guard permits can consume the draft model's additional VRAM and OOM the active training job.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed together with the related draft-sizing item; the explicit drafter is now counted by the training guard before the load proceeds.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d3b66f356f
ℹ️ 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".
| flags: list[str] = [] | ||
| if keep_model_in_vram: | ||
| flags.append("--no-mmap") |
There was a problem hiding this comment.
Avoid using
--no-mmap as a RAM-saving mode
When keep_model_in_vram is enabled, this emits --no-mmap, but that makes llama.cpp read the GGUF into an allocated host buffer rather than a file-backed mapping; it does not remove the host-side weights. In the full-offload scenario this option targets, the existing load-progress implementation explicitly relies on mmap pages being released after VRAM offload, whereas the non-mmap allocation remains private RSS. Thus enabling the advertised save-RAM option can retain roughly a model-sized RAM allocation and OOM the systems it is intended to help; keep residency/idle-unload behavior should be decoupled from --no-mmap (or the option should use a mechanism that actually releases host weights).
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Upstream llama.cpp confirms --no-mmap is the recommended way to drop the host RAM copy under full VRAM offload, which is exactly the scenario this flag targets (discussion 19883 and the server README), so the behavior is intended and correct.
| _gguf_is_vulkan = LlamaCppBackend._is_vulkan_backend() | ||
| try: | ||
| gguf_gpu_ids = resolve_requested_gpu_ids( | ||
| effective_gpu_ids, is_vulkan = _gguf_is_vulkan |
There was a problem hiding this comment.
Pass Vulkan ordinal mode through the training guard
For a Vulkan llama-server with active CUDA training, this validates gpu_ids as Vulkan ordinals, but the subsequent _guard_chat_load_against_training receives the raw IDs and can_load_chat_during_training resolves them as CUDA physical IDs. When Vulkan and CUDA enumeration differ, the guard either checks the wrong CUDA devices or treats the ID as invalid and returns ok=True, allowing a load without the intended coexistence check. Thread the Vulkan mode/resolved device mapping into that guard (or conservatively refuse an unverifiable Vulkan selection) so this new GPU-selection path cannot OOM active training.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed, the load path threads is_vulkan into resolve_requested_gpu_ids but the training guard did not, so a Vulkan ordinal outside the CUDA set tripped the invalid_gpu_ids branch and returned ok=True; I threaded the Vulkan mode through and now size Vulkan selections against the pooled visible VRAM.
| keep_model_in_vram: bool = Field( | ||
| False, | ||
| description = "Whether the model was loaded keep-resident (--no-mmap + idle-unload opt-out).", | ||
| ) | ||
| mlock: bool = Field( | ||
| False, | ||
| description = "Whether host pages are locked in RAM (--mlock) for the active load.", | ||
| ) | ||
| gpu_ids: Optional[List[int]] = Field( | ||
| None, | ||
| description = "Explicit physical GPU selection the GGUF was pinned to, or None (auto).", |
There was a problem hiding this comment.
Return active GGUF load options on the dedupe path
When a second /load request matches a resident GGUF, _request_matches_loaded_settings now permits this already_loaded response, but this constructor omits all three newly added fields. Pydantic therefore returns keep_model_in_vram=false, mlock=false, and gpu_ids=null even when the active server was launched with them. A client that round-trips the load response can consequently render the wrong settings and submit defaults on Apply, causing an unintended reload that removes the requested residency or GPU pin; populate these fields from llama_backend here as in the successful-load response.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Good catch, the GGUF already_loaded response omitted keep_model_in_vram, mlock and gpu_ids so it reported defaults even when the live server was launched with them; I now populate all three from llama_backend as the successful-load response does.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 16b585cfb1
ℹ️ 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".
| # GGUF self-placement (incl. Vulkan ordinal selection): llama.cpp picks | ||
| # the GPU(s), so any visible GPU is a candidate -> size the whole pool. | ||
| free_vals = list(free_by_index.values()) |
There was a problem hiding this comment.
Do not approve Vulkan loads using unrelated CUDA GPUs
When CUDA training is active alongside a Vulkan llama-server, Vulkan ordinals are explicitly a separate device space, but this branch discards the requested Vulkan ordinal and sums every CUDA-visible device. For example, if Vulkan0 maps to the training-busy physical GPU while another CUDA GPU has enough free VRAM, this returns ok=True; /load then launches --device Vulkan0 and can OOM the training run. The fresh evidence is that the new vulkan_gguf path deliberately bypasses resolution and uses the entire CUDA pool, so it needs an ordinal-to-physical mapping or a conservative refusal rather than treating unrelated free CUDA memory as available to the selected Vulkan device.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 1a0499c. An explicit Vulkan ordinal is a separate index space from the CUDA/nvidia-smi index in free_by_index, so the pinned card cannot be mapped to a pool entry. can_load_chat_during_training now sizes an explicit Vulkan pin against the busiest visible GPU (min free across the pool) and approves only if the model fits even the most loaded card, so it can no longer be approved on another GPU's free VRAM.
| if gpu_ids: | ||
| from core.inference.llama_residency import filter_selected_gpus | ||
| gpus = filter_selected_gpus(gpus, gpu_ids) |
There was a problem hiding this comment.
Reject unmapped Vulkan ordinals instead of launching another GPU
For a Vulkan request whose ordinal is not in the ggml probe (for example gpu_ids=[3] with only Vulkan0), resolve_requested_gpu_ids(..., is_vulkan=True) accepts it and this helper deliberately restores the full GPU list. The fit commonly selects Vulkan0, and the later launch prefers that fit subset over the raw request, so the request succeeds on GPU 0 while status reports [3]. Validate the requested ordinals against the Vulkan probe, or fail when none match, rather than silently redirecting a selected-GPU load.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 1a0499c. When a Vulkan build's ggml probe does not enumerate any of the requested ordinals, the load now raises an actionable error naming the available Vulkan devices instead of fail-opening onto Vulkan0. On a narrowed fit (for example request [0,3] where only 0 exists) it records the ordinals actually pinned rather than the raw request, so /status and /load no longer misreport. Added a regression test that asserts the fully-absent case rejects before spawn.
| self._keep_resident = bool(keep_model_in_vram) | ||
| self._mlock = bool(mlock) | ||
| self._gpu_ids = sorted(int(x) for x in gpu_ids) if gpu_ids else None |
There was a problem hiding this comment.
Clear launch-option state on the diffusion-server path
After a regular GGUF was loaded with any of these options, loading a DiffusionGemma GGUF takes the early _start_diffusion_server return before these assignments run. The previous keep_resident, mlock, and gpu_ids therefore remain latched even though the diffusion runner ignores these llama-server options: /load and /status report the old settings, and the idle loop sees a loaded process with stale keep_resident=True and never TTL-unloads it. Initialize these fields for the diffusion path (and reset them on unload) so they describe the active runner.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 1a0499c. The diffusion shim honors none of the llama-server residency/GPU-pin flags, so a prior keep-in-VRAM chat load leaked keep_resident/mlock/gpu_ids into it. Those fields are now cleared when the diffusion runner starts and in unload_model, so they always describe the active runner and the idle TTL unload is no longer suppressed. Regression tests cover both resets.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 1a0499cf0e
ℹ️ 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".
| if config.is_gguf and not config.gguf_hf_repo and request.draft_model_path: | ||
| config.gguf_mtp_file = request.draft_model_path |
There was a problem hiding this comment.
Do not reserve a disabled draft model
When training is active, a local request with draft_model_path plus speculative_type="off" (or ngram) assigns the draft to config before the guard, so _estimate_gguf_required_gb() counts its file size and can return 409. The later _build_speculative_flags() does not emit --model-draft for those modes, so this rejects loads that would actually fit; only fold the draft into the estimate when the effective launch will use MTP (and account for any extra-arg override).
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Good catch. When training is active, an explicit draft_model_path with speculative_type off/ngram (or ngram-simple) assigned the drafter to config before the guard, so the estimate counted its file size and could 409 a load that actually fits, since _build_speculative_flags only emits --model-draft for MTP. Fixed by threading the effective speculative mode into the guard and only sizing gguf_mtp_file when the launch will really use it (mtp/mtp+ngram, and auto with a separate drafter), and skipping it when extras own --spec-type. The genuine-MTP case still counts the draft, and mmproj sizing is unchanged. Added regression tests covering off/ngram skip and MTP count.
| return True, {"mode": "explicit", "reason": "invalid_gpu_ids"} | ||
| free_vals = [free_by_index.get(i, 0.0) for i in resolved] | ||
| mode = "explicit" |
There was a problem hiding this comment.
Treat explicit GGUF GPUs as a placement pool in the guard
For a CUDA/ROCm GGUF request selecting multiple GPUs during training, this gives the request mode="explicit" and later applies the balanced-device per-GPU floor. That rejects a selection such as [0, 1] when GPU 0 is busy even if GPU 1 can fully hold the model, while the GGUF fit logic deliberately selects and pins the smallest fitting subset of the requested pool. This newly enabled GGUF selection path should use GGUF self-placement sizing (no even-share floor), rather than the HF device_map="balanced" rule.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Agreed. An explicit multi-GPU GGUF selection should size as a placement pool, not with the device_map=balanced even-share floor, because the GGUF fit deliberately pins the smallest fitting subset. In can_load_chat_during_training the per-GPU floor is now gated on mode == "explicit", and a GGUF request resolves to mode == "gguf", so a selection like [0, 1] with GPU 0 busy is approved when GPU 1 alone can hold the model. The explicit HF device_map=balanced path keeps the floor. Verified after merging main into the branch.
c02d34b to
bab9038
Compare
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 792fe63aeb
ℹ️ 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".
| _req_gpu_ids = sorted(int(x) for x in request.gpu_ids) if request.gpu_ids else None | ||
| if _req_gpu_ids != (llama_backend.gpu_ids or None): | ||
| return False | ||
| if bool(request.keep_model_in_vram) != bool(llama_backend.keep_resident): | ||
| return False | ||
| if bool(request.mlock) != bool(llama_backend.mlock): |
There was a problem hiding this comment.
Skip unsupported load-option checks for diffusion GGUFs
For a DiffusionGemma GGUF, _start_diffusion_server deliberately clears keep_resident/mlock and collapses a multi-GPU selection to its lowest GPU, but this route-level comparator runs before the backend's diffusion-specific normalization. Consequently, reapplying the same request with keep_model_in_vram=true, mlock=true, or gpu_ids=[0,1] always fails deduplication and tears down/restarts the diffusion runner even though that runner cannot honor those options. Normalize or ignore these fields when llama_backend.is_diffusion is true, matching _already_in_target_state's diffusion handling.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Right, the residency and raw-pin checks ran before the diffusion normalization, so a keep_model_in_vram / mlock / multi-GPU re-apply always failed dedup and restarted the runner. Gated those checks behind not is_diffusion in the route comparator (the GPU pick is still compared, collapsed to the lowest device, in the diffusion-aware block below). Applied the same gate to the _already_in_target_state mirror so a raced duplicate load behaves identically. Added dedup regression tests. fd5ef16
| if is_vulkan_backend: | ||
| self._gpu_ids = ( | ||
| sorted(int(x) for x in _vulkan_pin_ids) if _vulkan_pin_ids else None | ||
| ) | ||
| else: | ||
| self._gpu_ids = sorted(int(x) for x in gpu_ids) if gpu_ids else None |
There was a problem hiding this comment.
Record the effective CUDA/ROCm GPU pin set
When an explicit multi-GPU request is narrowed by the fitter (for example, gpu_ids=[0,1] but the model fits on GPU 0 alone), the child is masked with gpu_indices at lines 7729-7736, yet this stores the unfiltered request. /load and /status therefore report that the model is pinned to [0,1] even though llama-server can only see GPU 0, contradicting the response contract and making the selected placement impossible to diagnose. Store the resolved gpu_indices when it is used, as the Vulkan branch already does.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed. The non-Vulkan branch recorded the unfiltered request, so an explicit [0, 1] narrowed by the fitter to [0] reported [0, 1] even though the child was masked to [0]. Now records resolve_pin_ids(gpu_indices, gpu_ids), mirroring the Vulkan branch, gated on an explicit selection so auto stays None and the no-narrowing case is unchanged. fd5ef16
| self._keep_resident = bool(keep_model_in_vram) | ||
| self._mlock = bool(mlock) |
There was a problem hiding this comment.
Derive residency state after user flag overrides
llama_extra_args are intentionally appended after these flags, and the preceding comment explicitly says --mmap and --no-mlock win. A request such as mlock=true with llama_extra_args=["--no-mlock"] therefore launches without page locking, but _mlock is still recorded as true; status reports a nonexistent active flag and later deduplication will incorrectly treat the server as locked. The same mismatch marks a --mmap override as keep-resident and suppresses its idle unload. Compute these state fields from the final effective flags, or prevent conflicting pass-through overrides.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Agreed. Extras are appended after the residency flags and win under llama.cpp last-wins parsing, so mlock=true + --no-mlock launched unlocked while we still recorded it locked. Added a derive_residency_state helper that reads the final argv and moved the _keep_resident/_mlock recording to after the extras are appended, so status and dedup reflect what actually launched. Unit tests cover the --no-mlock / --mmap overrides. fd5ef16
| _wanted_ids = {int(x) for x in gpu_ids} | ||
| if is_vulkan_backend and not any(g[0] in _wanted_ids for g in gpus): | ||
| _vulkan_explicit_unmatched = True | ||
| _vulkan_requested_ids = sorted(_wanted_ids) | ||
| _vulkan_available_ordinals = sorted(g[0] for g in gpus) | ||
| gpus = filter_selected_gpus(gpus, gpu_ids) |
There was a problem hiding this comment.
Reject partially unmatched Vulkan GPU selections
The unmatched check only fails when none of the requested ordinals are present. With a probe reporting Vulkan 0 and 1, a request for gpu_ids=[0,99] passes this condition, is filtered down to Vulkan 0, and launches while silently dropping ordinal 99. This contradicts the explicit-selection guarantee and the following error path's intent to reject unavailable ordinals; compare the full requested set against the probed ordinal set instead.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Good catch. The guard only rejected when none of the requested ordinals matched, so [0, 99] against a probed {0, 1} slipped through on the 0 match and silently dropped 99. Switched it to reject when any requested ordinal is absent (_wanted_ids.issubset(_probed_ordinals)), evaluated before filter_selected_gpus narrows so a fully-present request the fitter later trims to a subset still loads. Added a partial-unmatched reject test plus an all-present-passes-guard test. fd5ef16
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: c48dc1072d
ℹ️ 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".
| description = "Physical GPU indices to use, for example [0, 1]. Omit or pass [] to use automatic selection. Explicit gpu_ids are unsupported when the parent CUDA_VISIBLE_DEVICES uses UUID/MIG entries. For GGUF models the picked devices are pinned via CUDA/HIP_VISIBLE_DEVICES.", | ||
| description = "Physical GPU indices to use, for example [0, 1]. Omit or pass [] to use automatic selection. Explicit gpu_ids are unsupported when the parent CUDA_VISIBLE_DEVICES uses UUID/MIG entries. For GGUF models this pins llama-server to exactly these GPUs (CUDA_VISIBLE_DEVICES, plus HIP_VISIBLE_DEVICES on AMD ROCm, or --device Vulkan<i> on a Vulkan build).", | ||
| ) | ||
| keep_model_in_vram: bool = Field( |
There was a problem hiding this comment.
Expose the residency options in the Studio load UI
These fields are only added to the backend schema: a repository-wide search of studio/frontend finds no references to keep_model_in_vram or mlock. Consequently, normal Studio loads always use the default false values, so users cannot enable the advertised keep-resident behavior or page locking without manually calling the API.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
The keep_model_in_vram and mlock fields are wired end to end on the backend: LoadRequest carries them, build_residency_flags emits --no-mmap/--mlock, and the effective state is recorded via derive_residency_state, so the API path is correct with prior behavior preserved by the False defaults. Adding a frontend control is a separate feature rather than a correctness gap in the backend this PR changes, so I am keeping it out of scope here.
| "Default off." | ||
| ), | ||
| ) | ||
| draft_model_path: Optional[str] = Field( |
There was a problem hiding this comment.
Expose draft-model selection in the Studio UI
draft_model_path is not read or sent anywhere under studio/frontend (verified with a repository search), so the new separate-drafter path is unreachable through the Studio product. Users can only exercise this GGUF option through a hand-crafted API request, despite the change being presented as a Studio load option.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
draft_model_path is fully wired on the backend and route: the load resolves it, the dedupe compares it (routes/inference.py:3216), and it feeds llama-server --model-draft, so it is reachable and correct over the API. Sending it from the frontend is a new UI feature rather than a bug in the backend code this PR touches, so I am leaving it out of scope for this correctness PR.
| # (--device VulkanN), a separate index space from CUDA/ROCm physical | ||
| # ids that is enumerated independently and may be empty under a CPU-only | ||
| # torch. The CUDA parent-visible / physical-count checks below therefore | ||
| # do not apply; only reject malformed ordinals (issue #7239). | ||
| if len(set(requested_ids)) != len(requested_ids): | ||
| raise ValueError(f"Invalid gpu_ids {requested_ids}: duplicate GPU IDs are not allowed.") | ||
| negative_ids = [gpu_id for gpu_id in requested_ids if gpu_id < 0] | ||
| if negative_ids: | ||
| raise ValueError( | ||
| f"Invalid gpu_ids {requested_ids}: GPU IDs must be non-negative. " | ||
| f"Rejected IDs: {negative_ids}." | ||
| ) | ||
| return requested_ids | ||
|
|
||
| if not parent_visible_spec["supports_explicit_gpu_ids"]: | ||
| raise ValueError( |
There was a problem hiding this comment.
Advertise Vulkan GPU selection as supported
This accepts Vulkan ordinals, but /api/system still sets gguf_gpu_ids_supported to false for every Vulkan build in studio/backend/main.py:1167-1175; the existing frontend uses that flag to mark all GPUs unpinnable and hide the picker (studio/frontend/src/hooks/use-gpu-info.ts:88-106). Thus the newly implemented Vulkan selection path remains inaccessible to Studio users.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
The advertisement is deliberate. /api/system keeps gguf_gpu_ids_supported False for Vulkan-only builds (main.py:1159-1172) because the frontend GPU picker keys on physical torch/nvidia-smi indices, while --device pins ggml's own Vulkan ordinals, a separate index space that can be empty under a CPU-only torch. If the picker advertised support, a physical-index pick would not map to the Vulkan ordinal and could land on the wrong device. The API path still validates and accepts Vulkan ordinals for callers who know them, so keeping the picker from offering a mismapped selection is the correct behavior.
| if bool(request.keep_model_in_vram) != bool(llama_backend.keep_resident): | ||
| return False | ||
| if bool(request.mlock) != bool(llama_backend.mlock): |
There was a problem hiding this comment.
Normalize residency overrides before deduplicating loads
When a caller uses the allowed pass-through overrides (for example, default keep_model_in_vram=false plus llama_extra_args=["--no-mmap"], or true plus --mmap), the launched state is intentionally derived from the final argv but these checks compare the raw request booleans. Every identical subsequent /load therefore misses deduplication and tears down/reloads the model; the backend race guard has the same raw comparison in LlamaCppBackend._already_in_target_state.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
I traced this and it cannot produce a wrong dedupe on a normal request. keep_resident/mlock are derived from the final argv, and the dedupe compares the request booleans against them (routes/inference.py:3209-3213); when only the boolean changes the check returns False and reloads. The one imperfection is a needless reload when the raw boolean differs but hand-crafted --no-mmap/--mmap extras make the effective state coincide, which is the safe false-negative direction and matches the reload symptom you describe rather than a wrong residency state. A normal session sends the boolean, not raw mmap flags, so I am leaving this as is.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: c48dc1072d
ℹ️ 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".
| if bool(request.keep_model_in_vram) != bool(llama_backend.keep_resident): | ||
| return False | ||
| if bool(request.mlock) != bool(llama_backend.mlock): |
There was a problem hiding this comment.
Compare effective residency flags before deduplicating
When a request uses the allowed llama_extra_args overrides such as --no-mmap, --mmap, --mlock, or --no-mlock, the launch code records the effective final state, but this check compares it with the raw boolean fields. For example, a default keep_model_in_vram=false request with --no-mmap loads a resident server, then every identical Apply fails this check and reloads it (the backend-level guard at llama_cpp.py:8585 has the same mismatch). Derive the requested residency state from the final/inherited extra args before these comparisons so supported pass-through flags do not defeat deduplication or briefly tear down a keep-resident model.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
I traced this and the only reachable failure is a redundant reload, never a wrong dedupe. The full extras list is compared right after (routes/inference.py:3353: if list(request.llama_extra_args) != backend_extra returns False), plus the inherit path, so if the extras differ the load already reloads. When extras are identical, derive_residency_state yields the same effective residency for both loads (a present --mmap/--mlock pins the result regardless of the raw boolean; absent, effective equals raw), so no divergence is possible. Your example (keep_model_in_vram=false plus --no-mmap: effective keep_resident=true vs raw false) reloads at 3210, which is the safe direction, a needless reload of a resident model rather than a wrong result. Leaving as is.
| _req_gpu_ids = sorted(int(x) for x in request.gpu_ids) if request.gpu_ids else None | ||
| if _req_gpu_ids != (llama_backend.gpu_ids or None): | ||
| return False |
There was a problem hiding this comment.
Deduplicate against a narrowed GPU selection
For an explicit multi-GPU request such as gpu_ids=[0,1], the auto fitter is permitted to narrow the child mask to [0] when that single selected GPU fits; the new load code records that actual mask in llama_backend.gpu_ids. A subsequent identical request still compares its raw [0,1] list here to [0], so it always tears down and reloads the server (and the backend guard repeats the same check at llama_cpp.py:8582). Normalize the requested selection to the effective planned mask, or retain the original requested set separately for deduplication.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
The backend records the fit-narrowed mask in _gpu_ids deliberately so /status echoes the ordinals actually pinned (llama_cpp.py:7630). The dedup compares the raw request gpu_ids to that narrowed set, so a [0,1] request narrowed to a loaded [0] reloads ([0,1] != [0]), the safe direction. A wrong dedupe would need dedup to return already-loaded while placement differs, but it only returns true when the raw request equals the narrowed loaded set, and in that case the running placement already satisfies the request (fit-narrowing is an optimization, not a guarantee). No reachable wrong residency or GPU state. Leaving as is.
| _gguf_is_vulkan = LlamaCppBackend._is_vulkan_backend() | ||
| try: | ||
| resolve_requested_gpu_ids(effective_gpu_ids) | ||
| gguf_gpu_ids = resolve_requested_gpu_ids( | ||
| effective_gpu_ids, is_vulkan = _gguf_is_vulkan | ||
| ) |
There was a problem hiding this comment.
Keep Vulkan ordinals out of the diffusion CUDA selector
This newly accepts Vulkan ordinals as gguf_gpu_ids for every GGUF, including DiffusionGemma, but the diffusion path passes that list to _diffusion_gpu_arg; its visual engine then remasks CUDA_VISIBLE_DEVICES with the value (see llama_cpp.py:4725-4734 and 4814-4818). Vulkan ordinal N is explicitly a different index space from CUDA physical GPU N, so on heterogeneous or reordered hosts a selected diffusion model can run on the wrong GPU (and the training guard sizes that same wrong physical index). Preserve the previous rejection for diffusion on Vulkan, or add an explicit ordinal-to-physical mapping before invoking the diffusion runner.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed. The diffusion runner pins its visual server by CUDA physical index (CUDA_VISIBLE_DEVICES), so a ggml Vulkan ordinal cannot be honored. The route now rejects an explicit gpu_ids for a diffusion GGUF on a Vulkan build up front via a metadata-authoritative _classify_diffusion_gguf (local/cached header decides, no kill), with a fallback on the load_model diffusion branch for the remote-uncached residual, and /validate mirrors the same rejection. The classifier also no longer treats a bare diffusion substring as DiffusionGemma, so a normal llama-server GGUF named with diffusion is not falsely rejected. Non-diffusion --device VulkanN pinning is unchanged.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 7cfe7ab1ea
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| max_seq_length: int = 0, | ||
| llama_extra_args: Optional[list[str]] = None, | ||
| n_parallel: int = 1, | ||
| include_mtp_draft: bool = True, |
There was a problem hiding this comment.
Apply draft exclusion to remote GGUF companions
When training is active and a remote GGUF is loaded with speculative_type="off"/"ngram" (or a --spec-type override), the guard now passes include_mtp_draft=False, but this switch is only applied to local gguf_mtp_file sizing. The remote branch still calls _remote_gguf_companion_bytes(), which unconditionally adds root mtp-*.gguf companions, while load_model() skips _download_mtp() for those modes. This can return a 409 based on a drafter that will not be launched; thread the flag into the remote companion filter as well.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Done in 3811886. _remote_gguf_companion_bytes gained include_mtp, and _estimate_gguf_required_gb passes include_mtp=include_mtp_draft, so the remote root mtp-*.gguf is only counted when the effective speculative mode will actually fetch and launch it. This matches the local branch's include_mtp_draft gate, so an off/ngram or user --spec-type load no longer over-estimates VRAM and 409s on a drafter it never loads.
| elif ( | ||
| "draft_model_path" in getattr(request, "model_fields_set", set()) | ||
| and llama_backend.mtp_draft_path |
There was a problem hiding this comment.
Preserve omitted custom draft paths
When a local GGUF is already serving with an explicit draft_model_path outside the auto-detected sibling, a follow-up LoadRequest that omits draft_model_path enters neither the explicit-path nor explicit-clear branch here. Fresh evidence is that it then falls through to the later detect_mtp_file(...) comparison, which compares the auto sibling/None to the stored custom drafter, forces a reload, and the reload has no draft path so it drops the active drafter. Treat omission as preserving the current drafter, or skip the auto-sibling comparison for explicit-draft sessions.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Done in 3811886. A reload that OMITS draft_model_path on the same local GGUF now inherits the live server's explicit drafter via _resolve_inherited_draft_path (guarded on omitted-field, local GGUF, and resolved gguf_path equality), mirroring _resolve_inherited_extra_args. An explicit set or clear still owns the drafter, so a settings-Apply or auto-switch reload keeps the custom drafter instead of dropping back to the auto sibling.
| ), | ||
| gpu_memory_mode = request.gpu_memory_mode, | ||
| # ValidateModelRequest has no speculative_type (and no | ||
| # draft_model_path, so no explicit drafter reaches this path); |
There was a problem hiding this comment.
Mirror draft/spec choices in validation
/validate still has no draft_model_path or speculative_type input, so it defaults to Auto and never sees an explicit drafter even though /load now validates and sizes those fields. During active training, a load that disables MTP can be rejected by validation because it counts an auto drafter that /load will not launch, while a typo in an explicit local drafter can pass validation and then fail in /load after the client acted on the preflight. Add these fields to ValidateModelRequest and thread them through the same guard/path checks as /load.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Done in 3811886. ValidateModelRequest now carries speculative_type and draft_model_path; validate_model threads the explicit drafter into config.gguf_mtp_file so the coexistence estimate sizes it exactly as /load, runs the same effective-MTP-gated existence check, and passes request.speculative_type to the guard. So a drafter-off load that fits no longer 409s in validate, and a typo'd path surfaces the 400 here instead of after the frontend unloaded the working model.
| # missing drafter as optional and drops it, which would silently | ||
| # load without the requested draft on a typo. Surface a 400 | ||
| # instead of a silent no-op (#7239). | ||
| if not native_grant_backed and not Path(request.draft_model_path).is_file(): |
There was a problem hiding this comment.
Skip disabled draft path validation
The fresh evidence after the disabled-draft fix is that /load still validates draft_model_path unconditionally here. When the caller sends speculative_type="off", "ngram", or an extra --spec-type override, _build_speculative_flags() will not emit --model-draft, so a stale or missing draft path can 400 a GGUF load that would otherwise run without using that file. Gate this hard path check on the same effective-MTP condition used by the training estimate.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Done in 3811886. The explicit-drafter existence 400 and the native raise-on-explicit are now gated on _effective_mtp (canonical spec mode not in off/ngram/ngram-simple and extras do not own --spec-type), computed with the same helpers the launch path uses. A stale or absent draft path under a disabled or non-MTP mode no longer 400s a load that runs without the drafter, while mtp/auto still rejects a real typo.
…nch drafter decision (#7239) /validate now mirrors /load's speculative choices: ValidateModelRequest carries speculative_type and draft_model_path, the drafter is sized into the coexistence estimate and existence-checked with the same effective-MTP gate, so validate agrees with the follow-up load instead of 409ing a load that fits with the drafter off or passing a typo'd path that then 400s after the frontend unloaded the working model. An omitted draft_model_path on a same-local-GGUF reload now inherits the live server's explicit drafter, so a settings-Apply or auto-switch reload keeps a custom drafter instead of silently dropping back to the auto sibling. An auto-selected Vulkan device is no longer recorded as an explicit gpu_ids pin; the child is still pinned to the fit-selected ordinal, but /status and the load dedupe see the auto pick as None, matching the CUDA and ROCm branches. Remote MTP companion bytes are only counted when the effective speculative mode will actually fetch and launch the drafter, so an off/ngram or user --spec-type load no longer over-estimates VRAM and 409s. An explicit draft path is only existence-400d, and a bad companion only hard errors, when the drafter will actually launch, so a stale path under a disabled or non-MTP speculative mode no longer rejects a load that runs.
commented
Jul 19, 2026
|
@codex review |
left a comment
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 34f40efbc6
ℹ️ 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".
| _req_gpu_ids = sorted(int(x) for x in request.gpu_ids) if request.gpu_ids else None | ||
| if _req_gpu_ids != (llama_backend.gpu_ids or None): | ||
| return False |
There was a problem hiding this comment.
Preserve dedupe after fit narrows selected GPUs
When an explicit multi-GPU request is narrowed by the fitter (for example, [0, 1] fitting entirely on GPU 0), the new launch code records only [0] as the active pin. This raw-request comparison then rejects the otherwise identical [0, 1] request, and the mirrored backend check does the same, so every subsequent Apply/load needlessly kills and reloads the healthy model. This is particularly disruptive because it discards the live llama-server session despite no effective placement change.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in d1e187f. The backend now records the raw requested pin (requested_gpu_ids) alongside the fit-narrowed effective gpu_ids, and both the route dedupe and _already_in_target_state compare the raw value. A [0, 1] pick the fitter narrows to [0] and re-sent as [0, 1] now dedupes to the live server instead of reloading it; an auto pick still matches None, a non-narrowed pick still matches, and an explicit change to [0] still reloads. /status keeps echoing the effective pin.
| if is_gguf and not getattr(config, "gguf_hf_repo", None) and request.draft_model_path: | ||
| config.gguf_mtp_file = request.draft_model_path | ||
| _val_extra_args = _resolve_inherited_extra_args(request, config, model_identifier, None) |
There was a problem hiding this comment.
Inherit the active drafter during validation
For a same-local-GGUF reload that omits draft_model_path, /load inherits the active explicit drafter via _resolve_inherited_draft_path (lines 4677–4684), but this validation path only assigns a drafter when the request field is truthy. Consequently, while training is active, /validate can approve the smaller no-draft estimate and the frontend can unload the current model, after which /load sees the inherited drafter and rejects the larger real estimate with 409. Mirror the omitted-field inheritance here before invoking the training guard.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in d1e187f. validate_model now mirrors /load: when draft_model_path is omitted on a same-local-GGUF reload it inherits the active explicit drafter via _resolve_inherited_draft_path before the training guard, so the coexistence estimate sizes the same drafter the follow-up load will run. This stops validate approving the smaller no-draft estimate and then /load 409ing on the larger real one after the model was unloaded.
| ) | ||
| gpu_ids: Optional[List[int]] = Field( | ||
| None, | ||
| description = "Physical GPU indices to use, for example [0, 1]. Omit or pass [] to use automatic selection. Explicit gpu_ids are unsupported when the parent CUDA_VISIBLE_DEVICES uses UUID/MIG entries. For GGUF models the picked devices are pinned via CUDA/HIP_VISIBLE_DEVICES.", | ||
| description = "Physical GPU indices to use, for example [0, 1]. Omit or pass [] to use automatic selection. Explicit gpu_ids are unsupported when the parent CUDA_VISIBLE_DEVICES uses UUID/MIG entries. For GGUF models this pins llama-server to exactly these GPUs (CUDA_VISIBLE_DEVICES, plus HIP_VISIBLE_DEVICES on AMD ROCm, or --device Vulkan<i> on a Vulkan build).", | ||
| ) | ||
| keep_model_in_vram: bool = Field( | ||
| False, | ||
| description = ( | ||
| "Keep the model resident in VRAM (GGUF only). Passes llama.cpp " |
There was a problem hiding this comment.
Expose the residency and draft options in the Studio client
These request fields are never added to the Studio client's LoadModelRequest/response/status types or any of its load payload builders; for example, the primary interactive load payload only sends through gpu_ids at use-chat-model-runtime.ts:841-861. Therefore Studio users have no control to enable keep_model_in_vram or mlock, cannot select draft_model_path, and cannot hydrate their active residency state, leaving the newly added functionality API-only despite this being a Studio change.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
keep_model_in_vram, mlock, and draft_model_path are backend LoadRequest and status fields, and the load, validate, and status endpoints handle them correctly for any client that sends them, so there is no incorrect behavior on a real request. The interactive load path already forwards speculative_type and gpu_ids. Surfacing keep_model_in_vram and mlock as UI toggles and hydrating residency state into the client types is a frontend feature addition rather than a correctness defect in this change, so I am tracking that client wiring separately rather than folding a UI surface into this correctness pass.
There was a problem hiding this comment.
keep_model_in_vram, mlock, and draft_model_path are backend LoadRequest and status fields, and the load, validate, and status endpoints handle them correctly for any client that sends them, so there is no incorrect behavior on a real request. The interactive load path already forwards speculative_type and gpu_ids. Surfacing keep_model_in_vram and mlock as UI toggles and hydrating the residency state into the client types is a frontend feature addition rather than a correctness defect in this change, so I am tracking that client wiring separately rather than folding a UI surface into this correctness pass.
commented
Jul 20, 2026
|
@codex review |
commented
Jul 20, 2026
|
Before and after for the GGUF validate and load GPU/draft handling, as a direct API contrast (real backend, no mocks). Before, POST /api/inference/validate rejected a GGUF request that carried gpu_ids, and a missing explicit draft path was dropped silently. After, validate accepts a physical gpu id and a missing draft path is surfaced as a 400 instead of a silent no-op. The image captures the earlier state of the fix; the branch has since been extended with the residency-dedupe and drafter-inheritance symmetry fixes. |
commented
Jul 20, 2026
|
@codex review |
left a comment
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 4fdd65e820
ℹ️ 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".
| if bool(request.keep_model_in_vram) != bool(llama_backend.keep_resident): | ||
| return False | ||
| if bool(request.mlock) != bool(llama_backend.mlock): |
There was a problem hiding this comment.
Compare dedupe against effective residency state
When an otherwise identical GGUF request combines keep_model_in_vram=true with the allowed last-wins extra argument --mmap (or mlock=true with --no-mlock), the launcher intentionally records the effective state as false. This comparison still uses the raw request booleans, so every subsequent Apply fails dedupe and tears down/reloads the server despite unchanged effective argv; normalize the request through the same final-argv/override logic, or compare the requested values rather than the effective status consistently.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Good catch, fixed in c0f2fbb. The dedupe now compares the raw requested residency (requested_keep_resident / requested_mlock) instead of the effective keep_resident / mlock that a last-wins --mmap / --no-mlock in the extras flips, mirroring the requested_gpu_ids raw pin already used for the GPU selection. Applied in both _request_matches_loaded_settings and _already_in_target_state; the effective state still drives /status and the idle-unload opt-out. Added regression tests for the negated-by-extra match, the real keep_model_in_vram change reload, and the mlock counterpart.
commented
Jul 20, 2026
|
@codex review |
left a comment
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: c0f2fbb7a2
ℹ️ 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".
| _effective_pin_ids = resolve_pin_ids(gpu_indices, gpu_ids) | ||
| self._gpu_ids = ( | ||
| sorted(int(x) for x in _effective_pin_ids) if _effective_pin_ids else None | ||
| ) |
There was a problem hiding this comment.
Apply the fallback GPU pin to the child environment
When gpu_memory_mode="manual" (either gpu_layers=-1 or an explicit layer count), the planner deliberately leaves gpu_indices as None, but this fallback is only recorded in _gpu_ids; the later visibility-mask branch still runs only when gpu_indices is not None. Thus a request such as gpu_ids=[1] launches CUDA/ROCm llama-server with all GPUs visible despite reporting GPU 1 as selected. This also defeats the training coexistence guard, which sizes against the selected GPU while the child may place work on a training-busy unselected GPU.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
The explicit pin is already applied to the child. When no narrower subset was chosen (manual mode, or a failed/file-size selection), the GPU picker pins the whole selected set at llama_cpp.py:7364-7365: if gpu_ids and gpu_indices is None: gpu_indices = sorted(gpu_ids). That runs in load_model's main flow after the GPU-planning try/except, so it fires whether the fit ran, was no-op'd in manual mode, or failed, and it runs before both the /status recording via resolve_pin_ids (~7741) and the CUDA/ROCm visibility-mask branch (~7866). So a manual-mode gpu_ids=[1] request has gpu_indices=[1] at the mask branch, which emits CUDA_VISIBLE_DEVICES=1 (plus CUDA_DEVICE_ORDER=PCI_BUS_ID and the HIP mirror on ROCm). resolve_pin_ids returns gpu_indices verbatim when it is non-None, so the recorded pin and the child mask are the same value and the training-coexistence sizing stays consistent with the child. No unmasked all-GPU launch occurs.
commented
Jul 20, 2026
|
@codex review |
left a comment
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: c0f2fbb7a2
ℹ️ 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".
| keep_model_in_vram: bool = Field( | ||
| False, | ||
| description = ( | ||
| "Keep the model resident in VRAM (GGUF only). Passes llama.cpp " |
There was a problem hiding this comment.
Wire residency and draft settings through the Studio client
These fields are only added to the backend schema. The Studio client still has no keep_model_in_vram, mlock, or draft_model_path in frontend/src/features/chat/types/api.ts, and its load/validate payload construction therefore never serializes them (for example, frontend/src/features/chat/api/chat-api.ts:119-140). Consequently, regular Studio users cannot enable either residency option or select an explicit drafter; every UI-originated load retains the default values.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
This PR intentionally lands the backend/API capability: keep_model_in_vram, mlock, and draft_model_path are accepted and honored on /load and /validate, recorded on /status, and covered by backend tests. Wiring them into the Studio frontend client (api.ts types plus the load/validate payload builders) is a separate frontend change and is a deliberate follow-up, not a regression in this PR. The backend contract added here is complete on its own; the UI surface lands separately.
| gpu_ids: Optional[List[int]] = Field( | ||
| None, | ||
| description = "Physical GPU indices to use, for example [0, 1]. Omit or pass [] to use automatic selection. Explicit gpu_ids are unsupported when the parent CUDA_VISIBLE_DEVICES uses UUID/MIG entries. For GGUF models the picked devices are pinned via CUDA/HIP_VISIBLE_DEVICES.", | ||
| description = "Physical GPU indices to use, for example [0, 1]. Omit or pass [] to use automatic selection. Explicit gpu_ids are unsupported when the parent CUDA_VISIBLE_DEVICES uses UUID/MIG entries. For GGUF models this pins llama-server to exactly these GPUs (CUDA_VISIBLE_DEVICES, plus HIP_VISIBLE_DEVICES on AMD ROCm, or --device Vulkan<i> on a Vulkan build).", |
There was a problem hiding this comment.
Advertise GPU selection on Vulkan builds
Although this change now accepts Vulkan ordinals, studio/backend/main.py:1159-1175 still sets gguf_gpu_ids_supported to false whenever the llama backend is Vulkan. The frontend consumes that capability to hide the GPU picker (frontend/src/hooks/use-gpu-info.ts:88-94), so Studio users on Vulkan cannot submit the newly supported gpu_ids selection through the UI.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Same scope boundary: this PR makes the backend accept and pin Vulkan ordinals (the load path resolves and applies them via --device). Flipping gguf_gpu_ids_supported for Vulkan builds in main.py and the frontend use-gpu-info gate so the picker shows on Vulkan is a follow-up frontend change; the backend capability added here is complete and does not regress the current Vulkan behavior.
| if request.draft_model_path: | ||
| try: | ||
| _req_draft = Path(request.draft_model_path).resolve() | ||
| _cur_draft = ( | ||
| Path(llama_backend.mtp_draft_path).resolve() | ||
| if llama_backend.mtp_draft_path | ||
| else None | ||
| ) | ||
| except OSError: | ||
| return False | ||
| if _req_draft != _cur_draft: |
There was a problem hiding this comment.
Skip sibling-drafter dedupe for an explicit draft path
When a local model is loaded with an explicit draft_model_path, this comparison correctly matches that path, but the later sibling check at routes/inference.py:3382-3397 still compares detect_mtp_file(...) with the explicit stored path. Unless the explicit draft happens to be the auto-detected sibling, every identical repeat request fails the route-level dedupe and needlessly runs the reload/guard path; this can also turn a harmless re-Apply during training into a new 409.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Good catch, fixed in 9539281. The active drafter is now classified at load as explicit (a request or inherited draft_model_path that is not the on-disk sibling) vs the auto-detected sibling, using the same detect_mtp_file the route uses. The sibling-appearance dedupe at routes/inference.py:3382 now runs only for an auto sibling, so an explicit non-sibling drafter is governed solely by the explicit-path compare above and an identical repeat dedupes instead of forcing a reload or a spurious 409 during training. The auto sibling still re-checks, so a sibling appearing or changing on disk still reloads. Regression tests cover the explicit inherit-and-repeat dedupe, an explicit path-change reload, and both auto-sibling cases.
| cmd.extend(str(a) for a in extra_args) | ||
| logger.info(f"Appending user extra args to llama-server: {list(extra_args)}") |
There was a problem hiding this comment.
Record the effective Vulkan device after user extras
For a Vulkan load with gpu_ids=[0] and permitted extra args such as --device Vulkan1, the code records GPU 0 before appending the extras, while the comment explicitly states that the final extra --device wins. /status therefore reports GPU 0 and a repeat request dedupes against GPU 0 even though llama-server is running on GPU 1. Derive the effective Vulkan pin from the final argv, or disallow an extra --device when gpu_ids is supplied.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
The dedupe is not affected here: it compares the raw requested_gpu_ids (inference.py:3212 and 3309) and additionally requires an exact extra_args match (3369), not self._gpu_ids. An identical repeat (gpu_ids=[0] plus the same --device Vulkan1) matches on the raw pin and identical extras, and both launches land on Vulkan1, so there is no wrong-device reuse. The only residue is /status echoing the pre-extras ordinal, and only when the user hand-types a --device into advanced llama_extra_args that contradicts their own gpu_ids pick (there is no per-device Vulkan sub-picker in the UI, which sends ordinals only). The effective device already governs the run and the dedupe, so leaving the cosmetic readback rather than parsing an override back out of user extras.
commented
Jul 24, 2026
|
@codex review |
left a comment
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: a5e98a615b
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
commented
Jul 24, 2026
|
@codex review |
left a comment
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: b616bd2486
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
commented
Jul 24, 2026
|
@codex review |
left a comment
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 492f6cdb57
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
commented
Jul 24, 2026
|
@codex review |
left a comment
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: a8b8c84a7c
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
commented
Jul 24, 2026
|
@codex review |
left a comment
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 0b93eba4bc
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
commented
Jul 24, 2026
|
@codex review |
left a comment
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: a5457a7c55
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
commented
Jul 24, 2026
|
@codex review |
left a comment
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 89fb25fc90
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Problem
GGUF per-GPU selection (
gpu_ids) already exists in Studio, but a few correctnessgaps remained around how a requested pin is validated, deduplicated on reload, and
mapped onto a Vulkan build's device ordinals.
Fix
Scoped to the
gpu_idspath, no new load options:gpu_idspick up front (before the training guard) so a bad pickis a clean 400, not masked by a VRAM 409: rejects negative / out-of-range /
duplicate ids and UUID/MIG parents, and XPU hosts.
--device Vulkan<i>), a separateindex space from CUDA ids. Validate the pick as ordinals via
resolve_requested_gpu_ids(..., is_vulkan=...)so a valid selection is notrejected against a possibly-empty CUDA-visible set, and size the chat-load guard
against the visible pool. A DiffusionGemma GGUF on a Vulkan build (its runner pins
by CUDA physical index, which has no Vulkan-ordinal mapping) is rejected up front.
gpu_ids) so anarrowed-then-re-sent pick does not needlessly reload; the effective fitted pin is
recorded for
/status.name or path as diffusion (the local GGUF header stays authoritative); the name
hint is scoped to the DiffusionGemma runner family and used only as a pre-download
fallback when the header is not yet cached.
Verification
studio/backend/tests/test_gpu_selection.pycovers the reload dedup, the physical-idand Vulkan-ordinal validation, and the diffusion-on-Vulkan reject (60 pass). The four
related backend suites pass together (233).
Compatibility
Additive and scoped to an explicit
gpu_idsrequest; omittinggpu_ids(automaticselection) is unchanged, and NVIDIA, ROCm, CPU, Mac and Vulkan are unaffected when no
pin is sent. Old load payloads validate unchanged.
Refs #7164