Repository navigation
Studio: keep the llama-server prompt cache on a shared-memory GPU - #10382
Conversation
The Windows full-offload tuning from #5692 emits --cache-ram 0 and --ctx-checkpoints 0 to keep host-RAM KV checkpoints off the PCI-E bus under WDDM. That reasoning is about a discrete card. An iGPU or a unified-memory APU has one pool and no bus, so the same flags save no transfer and remove the prompt cache instead, and --cache-ram 0 silently takes --cache-idle-slots with it ("--cache-idle-slots requires --cache-ram, disabling"). Measured on a Strix Halo running the Vulkan build with -ngl -1: one 48.8 hour session spent 44.3 hours re-ingesting prompts, 3.38 M prompt tokens against 72 k generated, with the reprocessed context climbing to 183 k tokens and one turn taking 4.3 hours. The argv Studio composed for that run carries --cache-ram 0 --ctx-checkpoints 0 --device Vulkan0. _offload_target_shares_system_memory answers whether every device this launch offloads to reports host RAM as its VRAM, keeping the two index spaces apart the way the rest of the file does: Vulkan ordinals against shared_gpu_ids, physical HIP and CUDA ids against the unified-memory sets. It fails closed, so a mixed selection, an unreadable inventory or a launch that pins nothing all keep the tuning exactly as it is today. The OMP thread half of the same block is untouched: it is about spin-wait CPU burn rather than bus traffic, and nothing here measures it.
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: a72f471e2a
ℹ️ 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".
| _shared_memory_offload = self._offload_target_shares_system_memory( | ||
| is_vulkan_backend = is_vulkan_backend, | ||
| shared_gpu_ids = _shared_gpu_ids, | ||
| detected_gpus = _detected_gpus, | ||
| gpu_indices = gpu_indices, | ||
| ) | ||
| if sys.platform == "win32" and full_offload_tuning_active and _shared_memory_offload: |
There was a problem hiding this comment.
Re-evaluate cache tuning when the fallback changes GPUs
On a Windows mixed ROCm host, the kernel-image recovery path later rebinds gpu_indices to _remaining and respawns the same cmd (_arch_crash_retry_gpu_ids explicitly supports moving between unified and discrete GPUs). Because this decision is baked into cmd before the first spawn, a discrete-to-APU retry retains --cache-ram 0 --ctx-checkpoints 0, recreating the severe prefix-reprocessing problem this change is intended to fix; the reverse retry also omits the WDDM tuning on its final discrete target. Recompute these cache flags against _remaining before the arch-fallback respawn.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct, and fixed in b6410ee. The arch-crash retry rebinds gpu_indices to _remaining and respawns the same cmd, which was built before the crash, so a discrete-to-APU retry carried --cache-ram 0 onto a shared pool and the reverse retry reached a discrete card without the tuning. The respawn now re-decides against the devices it is actually retrying, adding or removing the pair as the new device class requires. Only tokens this policy emitted are taken back off argv, so a user's own --cache-ram survives, which is asserted.
| _shared_memory_offload = self._offload_target_shares_system_memory( | ||
| is_vulkan_backend = is_vulkan_backend, | ||
| shared_gpu_ids = _shared_gpu_ids, | ||
| detected_gpus = _detected_gpus, | ||
| gpu_indices = gpu_indices, |
There was a problem hiding this comment.
Resolve final device overrides before tuning the cache
When gpu_ids is unset, a pass-through --device remains in _mem_extras and is appended later, after the generated Vulkan pin, so llama.cpp's last-wins parsing can make the actual target differ from gpu_indices. On a mixed Vulkan host, automatic placement filters the iGPU whenever a discrete GPU exists, so an extra such as --device Vulkan0 targeting that iGPU still makes this predicate inspect the discrete auto-selection and emit --cache-ram 0 --ctx-checkpoints 0, recreating the prefix-reprocessing regression on the actual shared-memory target; the inverse mismatch can also drop the intended WDDM tuning. Base this decision on the effective final device selection and the unfiltered Vulkan inventory.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct, and fixed in b6410ee. _strip_device_extra_args runs only when gpu_ids is not None, so an auto-placement launch keeps a user --device in the extras and last-wins parsing makes it the real target. Rather than re-derive that target from argv the helper now declines: the failure that matters is emitting --cache-ram 0 against a shared pool, and keeping the prompt cache on a discrete card only forgoes a tuning. Same direction as the helper's existing fail-closed contract.
| if sys.platform == "win32" and full_offload_tuning_active and _shared_memory_offload: | ||
| logger.info( | ||
| "Keeping the llama-server prompt cache: this load offloads to a GPU " | ||
| "that shares system memory, so --cache-ram 0 and --ctx-checkpoints 0 " | ||
| "would remove prefix reuse without saving a transfer." | ||
| ) | ||
| elif sys.platform == "win32" and full_offload_tuning_active: |
There was a problem hiding this comment.
Budget the caches restored on shared-memory devices
When a Windows APU load fits only with limited system-memory headroom, skipping both zeros restores llama.cpp's default 8192 MiB RAM cache and its default context checkpoints in the same physical pool used for model/KV offload, but the placement calculation does not reserve either default: _effective_ctx_checkpoints deliberately charges zero unless the user explicitly requested a value, and no fit term accounts for the default cache-ram. The load can therefore be classified as fully fitting and launched with -ngl -1, then exhaust shared system memory as checkpoints and cached slot states accumulate. Include these restored defaults in the shared-memory fit/admission budget or cap them to the proven remaining headroom.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not taking this one. The unbudgeted default --cache-ram (8192 MiB) and the 32 context checkpoints are pre-existing on every platform this PR does not touch, so the concern is not introduced here; and the cache is self-limiting rather than unbounded, as llama.cpp skips a state that does not fit ('prompt state size 9206.065 MiB exceeds cache size limit 8192.000 MiB, skipping'). Adding a fit term would change admission for every host, which is outside what this change is for.
The shared-memory predicate was evaluated on every launch on every platform, before the sys.platform gate that is its only consumer, and its non-Vulkan branch called _integrated_cuda_gpu_ids(). That reaches torch.cuda.get_device_properties(), which runs _lazy_init() and creates a CUDA primary context in the backend process that it never gives back. This file's own _get_gpu_memory prefers nvidia-smi and amd-smi to avoid exactly that cost, measured there at about 700 MiB, and it is VRAM the child llama-server then cannot use. The tensor-spill planner is the only other caller and smart offload is off by default, so nothing on the launch path was paying it before. Two changes. The call now short-circuits behind the platform gate, so a Linux, macOS or partial-offload launch never asks. And the predicate consults ROCm alone: its one caller is the Windows full-offload branch, and an integrated CUDA part (Jetson, DGX Spark, Tegra) is Linux-only, so the CUDA probe could only ever answer False here. _rocm_unified_memory_gpu_ids returns an empty set on a CUDA torch without touching the device. The test fakes a CUDA host whose device probe raises. It raises BaseException on purpose: every helper in this family swallows Exception per device, so an ordinary error would be caught and the test would pass against the code it exists to catch. Confirmed failing against the previous helper.
… gets Both fixes have the same root: the decision was made against gpu_indices, which is the picker's answer and not always the target. When gpu_ids is None the picker does not own placement, so _strip_device_extra_args does not run and a user --device in the extras survives into argv after the generated pin, where llama.cpp's last-wins parsing makes it the real target. Rather than re-derive that target from argv, this declines: the failure that matters is emitting --cache-ram 0 against a shared pool, and keeping the prompt cache on a discrete card only forgoes a tuning. That is the same direction as the helper's own fail-closed contract, and it is a deliberate trade rather than an oversight. The kernel-image arch-crash retry rebinds gpu_indices to _remaining and respawns the same cmd, which was built before the crash. A discrete-to-APU retry therefore carried --cache-ram 0 onto a shared pool, recreating exactly the prefix-reprocessing problem this tuning exists to avoid, and the reverse retry reached a discrete card without the WDDM tuning. The respawn now re-decides against the devices it is actually retrying, adding or removing the pair as the new device class requires. Taking flags back off argv is only safe for tokens this policy emitted itself, so the emission is recorded and _without_flag_pairs removes exactly those flag/value pairs. Every one carries a value, which is what makes the two-token step safe: a valueless flag would swallow the user extra that follows it, which is why the mlock path refuses to strip at all. A user's own --cache-ram survives, and that is asserted.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: b6410eeeda
ℹ️ 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".
| _cache_target_unknown = gpu_ids is None and bool( | ||
| _extra_args_set_any_flag(_mem_extras, _DEVICE_FLAGS) |
There was a problem hiding this comment.
Avoid reading
_mem_extras before assignment
When gpu_ids is unset—the normal automatic-placement path—this expression evaluates _mem_extras, but that local is not assigned until apply_model_memory_policy at line 22641. This therefore raises UnboundLocalError before llama-server starts on every unpinned load, including non-Windows launches because the assignment itself is not platform-gated; inspect extra_args here or move the check after _mem_extras is initialized.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct, and it was breaking every load, not only the tuned path: _mem_extras is assigned about 150 lines below the read. Fixed in 5dc8d70 by reading extra_args instead, which is the right source anyway -- _strip_device_extra_args only removes a device flag when gpu_ids pins the placement, and a gpu_ids pin is exactly the case this branch already excludes.
| if _retry_flags: | ||
| cmd.extend(_retry_flags) | ||
| _cache_flags_emitted = list(_retry_flags) |
There was a problem hiding this comment.
Preserve user cache flags during the arch retry
When automatic ROCm placement initially selects a shared-memory APU and the kernel-image fallback moves to a discrete GPU, cmd already contains the pass-through extras, but this new branch appends its zero-valued cache flags afterward. If the user supplied --cache-ram or --ctx-checkpoints in those extras while the corresponding UI field is unset, llama.cpp's last-wins parsing now replaces the user's value with zero on the retry, unlike the initial launch where extras intentionally override the tuning; skip the generated pair when the completed command already selects that setting or preserve the original ordering.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed: the extras are appended at the launch build, well before the retry, so a flag added at the retry wins the last-wins parse -- the reverse of the initial launch, where the tuning is emitted first and the extras override it. A typed --cache-ram would have been zeroed on the APU-to-discrete retry while the panel still showed the value.
Fixed in 525b589 by the first of your two options: _retry_cache_tuning_flags skips a setting the completed command already states, in either the separated or the attached spelling, and reads --swa-checkpoints as the same setting as --ctx-checkpoints since a build advertising one can still be handed the other. Four tests, with the negative control that the tuning is still applied when nothing states it.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: b6410eeeda
ℹ️ 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".
| _cache_target_unknown = gpu_ids is None and bool( | ||
| _extra_args_set_any_flag(_mem_extras, _DEVICE_FLAGS) | ||
| ) |
There was a problem hiding this comment.
Account for inherited device overrides before tuning caches
On a Windows mixed ROCm host using automatic placement, an inherited LLAMA_ARG_DEVICE can select only the shared-memory APU even when gpu_indices contains both an APU and a discrete GPU. This check considers only pass-through argv flags, while the later launch path explicitly preserves inherited device placement for automatic loads (llama_cpp.py:23129-23133), so the helper returns false for the mixed picker result and emits --cache-ram 0 --ctx-checkpoints 0 against the actual APU target, restoring the repeated-prefill problem. Fresh evidence beyond the earlier pass-through-argument finding is this unhandled environment twin, which survives into the child; include the effective environment selection in the unknown/target decision.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Right, and it is the same fail-closed question the argv check asks. Only an explicit gpu_ids clears LLAMA_ARG_DEVICE (_clear_device_placement_env), so on an automatic load the child inherits it verbatim, and llama.cpp reads the env before argv either way -- so the env twin names the target as much as the flag does.
Fixed in 525b589: the decision moves to _cache_tuning_target_unknown, which asks both spellings, mirroring what the tensor-spill decline already does at the same pair of conditions. Three tests, including the control that an explicit pin clears both and so leaves the target known.
|
Confirmed the Windows full-offload block in studio/backend/core/inference/llama_cpp.py still emits --cache-ram 0 and --ctx-checkpoints 0 even when the only offload target is an integrated GPU whose VRAM is host RAM, and the new predicate fails closed so a discrete card keeps today's behaviour. Will get this reviewed. |
… list _mem_extras is built later in the launch, so reading it where the cache target is decided raised UnboundLocalError on every load. extra_args is the right source anyway: _strip_device_extra_args only removes a device flag when gpu_ids pins the placement, which is exactly the case this branch already excludes. The checkpoint-flag source guard follows the tokens to their new sink, the list the arch-crash respawn takes its own flags back off. What it pins is unchanged: the recorded flag name, never a hard-coded one.
…y's precedence Two ways the tuning could still reach a device it was not chosen for. A user device selection has an env spelling, and only an explicit gpu_ids clears LLAMA_ARG_DEVICE, so on an automatic load the child inherits it verbatim and llama.cpp reads it before argv. Reading argv alone left the target unknown-check blind to it, which on a mixed Windows ROCm host emits --cache-ram 0 against the APU the picker had paired with a discrete card. The check now asks both spellings, mirroring what the tensor-spill decline already does. And the arch-crash retry appended its flags to a command that already carried the extras, so last-wins made the generated zero beat a typed --cache-ram -- the reverse of the initial launch, where the extras are appended after the tuning and win. The retry now skips a setting the command already states, in either spelling and under either checkpoint alias. Both decisions move to named helpers so they can be tested directly, each with the control that shows the fix has not simply disabled the tuning.
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: dc8b03f5f4
ℹ️ 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 ( | ||
| cache_ram is None | ||
| and server_caps.get("supports_cache_ram") | ||
| and "--cache-ram" not in stated |
There was a problem hiding this comment.
Honor the short cache alias during arch retry
When automatic ROCm placement starts on a shared-memory APU, retries on a discrete GPU, and the user supplied -cram 8192 with the cache field unset, stated contains only -cram, so this condition appends --cache-ram 0 after the extras and silently overrides the user's value. The fresh case not covered by the earlier long-form override fix is that _CACHE_RAM_FLAGS explicitly accepts -cram; check that alias here as well (and likewise -ctxcp in the checkpoint check).
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 0f7d522. Both guards now test the flag sets llama_server_args already keeps (_CACHE_RAM_FLAGS, _CTX_CHECKPOINTS_FLAGS) rather than literal long spellings, so -cram and -ctxcp state the setting exactly as --cache-ram and --ctx-checkpoints do. Test covers the pair together and each alone, including the attached -ctxcp=4 form, and fails on the pre-fix guard.
-cram and -ctxcp are aliases llama.cpp accepts and the extras panel offers, so a command that states one has stated the setting; the retry's tuning was appended after them and silently zeroed the user's value.
|
@codex review |
|
Codex Review: Didn't find any major issues. What shall we delve into next? Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
Comment-only pass over the files this PR touches: shorten the reasoning to the facts the code cannot show -- why the target is read from the env twin as well as argv, and what the measured cost of getting it wrong was.
Resolves two conflicts from #10351 (sharded readers in layout_from_gguf; both sides appended planner tests). Pins that #5692's Windows cache tuning and #10382's shared-pool exception never coincide with the planner's --cache-ram clamp: the tuning keys on fully_gpu_offloaded, which a planner-owned launch never sets, so the argv carries exactly one --cache-ram.
Studio's Windows full-offload tuning turns off the llama-server prompt cache. On a discrete card that is the trade #5692 intended. On an integrated GPU it is a pure loss, and it cost one user 44 hours.
What happened
From a Strix Halo log bundle, one 48.8 hour session:
Consecutive lines from the same slot, one turn apart:
53 minutes to re-ingest a context the server had just reported keeping. This is not a wedge and not a hang: it is real, repeated, avoidable work.
The argv Studio composed for that run:
--cache-ram 0 --ctx-checkpoints 0is ours, from thesys.platform == "win32" and full_offload_tuning_activeblock.-ngl -1makesfully_gpu_offloadedtrue, so the tuning fires. llama-server's own first lines then record the third feature it takes down:Why the tuning does not apply here
#5692 is about WDDM: host-RAM KV checkpoints on a discrete card cross PCI-E, so dropping them is a saving. The device in that argv is
Vulkan0on a Radeon 8060S, an integrated GPU whose VRAM is system RAM. There is one pool and no bus. The flags save nothing and remove every chance of reusing a prefix.The same reasoning is already in this file for the Apple case: "Unified memory: the 'VRAM' is host RAM, so the weights stay pageable however fully they are offloaded."
The change
_offload_target_shares_system_memoryanswers whether every device this launch offloads to reports host RAM as its VRAM, and the Windows tuning is skipped when it does.It keeps the two index spaces apart the way the rest of the file does, because they are not interchangeable: Vulkan ordinals are matched against
shared_gpu_ids(which the probe fills only for integrated devices, on the Vulkan path only), and physical HIP and CUDA ids against the unified-memory sets.It fails closed. A mixed selection, an unreadable inventory, or a launch that pins nothing all answer False and keep today's behaviour, so a discrete card is untouched. When it does answer True the load logs one line saying why the tuning was skipped.
The OMP half of the same block (
OMP_WAIT_POLICY=PASSIVE,OMP_NUM_THREADS=2) is deliberately left alone: it is about spin-wait CPU burn, not bus traffic, and nothing here measures it.Testing
11 new cases in
test_shared_memory_offload_keeps_the_prompt_cache.py, covering both index spaces and every way the predicate should decline: an iGPU-only target pinned and unpinned, a discrete card beside the iGPU, pinning only the iGPU of a mixed host, a discrete-only host, no device at all, an AMD APU, a discrete AMD card, an APU next to a discrete card, an unreadable inventory, and a Vulkan shared set offered to a ROCm launch (which must not be read as physical ids).2341 pass and 32 skip across the nine suites around the change (
test_shared_memory_offload_keeps_the_prompt_cache,test_idle_slot_clearing_is_known,test_server_tuning_flags,test_amd_apu_unified_memory,test_llama_server_args,test_load_mode_fit_matrix,test_slot_refit_ctx_checkpoints,test_offload_planner_seam,test_llama_cpp_placement). One failure,test_oversubscribed_decode_threads_decline_spill_planning, is host-only and pre-existing: it fails the same way on a clean checkout of main in a second worktree.What the tests do not cover, stated plainly: the predicate is unit tested, but the argv it gates is not, because there is no launch-level harness to assert
--cache-ramin the composed command. The composition is a single boolean at the call site.Not fixed here
The same bundle shows two other contributors to that 44 hours, both left for their own change:
--cache-ramis silently skipped (prompt state size 9206.065 MiB exceeds cache size limit 8192.000 MiB, skipping). Studio passes--slot-save-pathon every launch and never raises the limit to match the context it requests.--parallel 4 --kv-unified -c 262144advertises the whole pool to each of four slots, which then evict each other (purging slot 2 with 183269 tokens).