Repository navigation
Studio: re-fit the context when Auto drops serving slots - #9345
Conversation
|
Codex Review: Didn't find any major issues. 👍 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". |
|
Confirmed this hits the path in studio/backend/core/inference/llama_cpp.py where the context and published ceiling stay sized for the pre-reduction slot count, and the MTP reserve call passes no slots so it is still priced off the requested pair. Will get this reviewed. |
|
Codex Review: Didn't find any major issues. Delightful! 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". |
|
Codex Review: Didn't find any major issues. More of your lovely PRs please. 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". |
llama-server allocates --ctx-checkpoints snapshots per slot (upstream default 32, and Unsloth charges only what the user explicitly asks for), so the reserve scales with the count the plan settles on. _slots_that_fit_on_gpu priced its candidates without it. That was survivable while the only consumer was the slot count: an over-optimistic candidate cost slots, not memory already promised. The post-reduction context re-fit runs the same predicate to pick the launched -c, so the omission started buying context with bytes the child had already been told to spend on checkpoints. Thread ctx_checkpoints through the helper and pass _effective_ctx_checkpoints at both call sites, which corrects the pre-existing slot search as well. Measured on a 12 GiB card, a 9,200 MiB sliding-window target, q8_0 KV, four requested slots and --ctx-checkpoints 16: the plan launched -c 12800 at three slots with --fit off, against a 4,794 MiB reserve the fit never charged. It now declines that context. Across 630 checkpointed shapes the count of plans that spent an uncharged reserve drops from 67 to 0; the seven that remain equal are at their native length, where there is nothing to give back. Also stop the search walking candidates the caller discards. _slots_hold accepts only n_parallel itself, and the helper had no early exit, so it re-ran the whole KV + compute-buffer + GPU-selection estimate down to one slot for answers it threw away: 45 percent of iterations across a 15-scenario sample, 74 percent worst case. The docstring summary still described the old [1, n_parallel) domain, which include_requested had already widened.
The hoisted native_ctx_for_cap coupled two placement arms that do not otherwise talk to each other. The arm at "elif gpus and self._can_estimate_kv() and effective_ctx > 0" binds the same expression itself, so on the mainline path the hoist is overwritten before the re-fit reads it. The path where it survives is the one it was added for, and there it binds the wrong value: a GGUF with no native length reaches that elif while effective_ctx is still the 0 sentinel, so the arm is skipped, control falls through to "elif gpus:", and only that arm raises effective_ctx to 4096. The hoist has already captured 0, so _lo = 1, _hi = 0, the bisect body never runs, and both the re-fit and the ceiling update are silently skipped. Removing the hoist without replacing it is not an option either: the re-fit's guard is false at the hoist and true by the time it runs, so the name is unbound there, the broad except around placement swallows it, and the whole GPU plan is discarded for --fit on. That is the ~3x decode collapse this block exists to avoid (unslothai#6718). Bind it inside _largest_ctx instead, the way the two sweeps above already do. The cross-arm coupling goes, the third copy of the expression goes, and the no-native-metadata path now runs the bisect for real and returns 4096, matching what it produced before. Verified inert: across 15,360 spoofed platform cells and 138 degenerate-input cases, nothing moves except that those cells now enter the predicate instead of skipping it. Also: - Log the slot reduction after the re-fit. It reported the pre-re-fit context, which is sized for the slot count the load just stopped using, so the line named a context no launch ever ran with ("reduced 4 -> 2 ... at context 4096" immediately followed by "re-fitted 4096 -> 7680"). - The ceiling is not "a hardware bound". It is the largest context attainable at the slot count this load settled on; a larger request can drive a deeper reduction that frees the KV for more. Measured on 250 reduced-slot plans, ceiling + 256 still loads fully on GPU in 175 of them. The value is right and strictly better than what it replaced -- it removes a large class of false "may use system RAM" warnings -- but the comment invited the next reader to trust it as a maximum. Adds a platform matrix that pins which hosts the re-fit may touch at all. Metal enumerates no torch.cuda device and CPU-only hosts have none, so every macOS cell and every CPU-only cell fails the "and gpus" conjunct by construction, as do tensor-parallel, manual memory mode and a single-slot request. Watching the predicate rather than the argv means a cell that starts entering the block fails even when its numbers happen not to move.
|
Reviewed and validated this, and pushed three commits to the branch. Summary of what changed and the evidence behind it. The fix itself holds upSwept 2,592 synthetic plans on the merge base and on your head, then again across a spoofed [Windows, Linux, WSL, macOS Apple Silicon, macOS Intel] x [NVIDIA, AMD/ROCm, Vulkan, CPU-only] matrix, 15,360 cells per revision:
Every context increase coincides with a slot reduction. Growth factor min 1.06x, median 1.50x, max 4.75x. macOS and CPU-only are excluded by construction, since Also checked: the bisect is exact (472 re-fit sites, linear-scanned the real predicate, zero non-monotone sequences, bisect equals brute force every time); the published ceiling is loadable in all 472 reduced-slot plans; explicit contexts are byte-identical across 2,592 explicit plans; and on the explicit path the ceiling raise removes a large class of false "may use system RAM" warnings, 110/600 down to 0. What I changed1. The gap is pre-existing on main, not something you introduced, and it only bites when the user opts in, since I had to merge current main to write it, since 2. 3. Two smaller ones. The slot-reduction log ran before the re-fit, so it named a context no launch ever used ("reduced 4 -> 2 ... at context 4096" immediately followed by "re-fitted 4096 -> 7680"); moved it below. And the ceiling comment calls it "a hardware bound" - it is the largest context attainable at the slot count this load settled on, and Verification
Nothing else needed from my side. The known speculative-decoding ordering limitation is real, pre-existing, strictly narrowed by this PR, and your tests pin it deliberately, so I would leave it for a separate change as you suggested. |
Comment-only pass: same wording, fewer lines. The exact= rationale lives in the helper docstring, so the call site keeps a trailing note instead of repeating it; the ceiling and _largest_ctx blocks keep the trap they document and drop the retelling.
|
Codex Review: Didn't find any major issues. Another round soon, please! 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". |
The argv builder emits --ctx-checkpoints only when the capability probe found one of the two aliases, and logs and drops the request otherwise. The priced count was resolved unconditionally, so on an older or custom llama-server the fit reserved per-slot SWA snapshots no child ever holds. On an SWA model that is not a rounding error: the reserve is charged per slot, so it can push the slot search down a step and, now that the same predicate picks the launched -c, hand back a smaller context than the card holds -- for a flag the launch never passed. Gate the resolve on the same server_caps entry the emission uses, which is already bound above. This changes no argv; it only stops the estimator charging for bytes the launch does not reserve, at all seven call sites, including the five that predate this branch.
|
Codex Review: Didn't find any major issues. Keep it up! 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". |
|
@codex review |
|
Codex Review: Didn't find any major issues. 👍 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". |
…Auto offload context (unslothai#9594) * Price the serving-slot reduction at the fit floor, not the Auto offload context `Backend tests` has been red on main since unslothai#9492 (1f475d7), 26 failures across test_slot_reduction_context_refit.py and test_slot_refit_platform_matrix.py, both added by unslothai#9345 (1c06bc4). All 59 pass on unslothai#9492's merge base (15b9102). The two files were not run on that branch. The tests are reporting a real regression, not a stale baseline. unslothai#9492 introduced _AUTO_OFFLOAD_CTX = 8192 and put it in three places that had a literal 4096. Its reasoning: "Auto only reaches this path when no discrete-GPU subset can hold the model. llama.cpp must offload layers to host RAM either way, so prefer a context that remains useful for chat." That is true of two of the three sites, which are display values. The third, in load_model's auto arm, is the probe context of a placement search that runs AFTER it, in a block whose entire purpose is to overturn the premise "no subset can hold the model" by re-asking at fewer serving slots. Offload is not unavoidable at that point; it is avoidable in roughly the band where the constant now breaks it. What that costs, measured on a 12 GiB card at 4 requested slots: | weights | before unslothai#9492 | on main | |--------------------|-------------------------|------------------------| | hybrid 10,900 MiB | 1 slot, ctx 7,680, GPU | 4 slots, ctx 8,192, offload | | hybrid 11,000 MiB | 1 slot, ctx 6,144, GPU | 4 slots, ctx 8,192, offload | | hybrid 11,100 MiB | 1 slot, ctx 4,608, GPU | 4 slots, ctx 8,192, offload | | dense 9,800 MiB | 2 slots, ctx 4,608, GPU | 4 slots, ctx 8,192, offload | | dense 10,000 MiB | 1 slot, ctx 6,144, GPU | 4 slots, ctx 8,192, offload | | dense 10,500 MiB | 1 slot, ctx 4,096, GPU | 4 slots, ctx 8,192, offload | 8 of 14 sizes swept flip from fully GPU-resident to host offload, the ~3x decode collapse (unslothai#6718) named in _slots_that_fit_on_gpu's own docstring as the thing it exists to prevent. The failure is all-or-nothing: when no slot count fits at the probe, the block returns early, so the load keeps the full slot count it could not afford AND offloads. It gets 8,192 tokens at a third of the speed where it previously had 6,144 at full speed. Not a Pareto move. The arithmetic, at 10,200 MiB against a 12288 x 0.97 = 11,919.36 MiB budget. Candidates are 707.375 MiB apart (557.75 MiB of per-slot compute buffer plus 149.625 MiB of per-slot Mamba state, both context-independent), while probing higher costs a uniform 64 KiB/token. The 2-slot candidate is 11,685.0 MiB at 4096 and 11,947.0 MiB at 8192. A display constant moved it across the budget by 27.6 MiB. Two further consequences, both of which unslothai#9492 explicitly claimed it would not have. Its own comment at llama_cpp.py:2831-2841 makes placement-neutrality the correctness criterion for moving this constant. Placement moved anyway, through a call site the analysis did not enumerate: - Device pinning. At 10,200 MiB on a 12 GiB plus 1.25 GiB pair, the 2-slot candidate no longer fits card 0 alone, so the selector adds card 1 and the re-fit runs across both: CUDA_VISIBLE_DEVICES goes from "0" to "0,1", the layer split the block's comment says this path avoids. - Monotonicity. Asking for 2 slots returns 2; asking for 3 returns 1. unslothai#9492's coverage was structurally blind to all of this: test_auto_offload_ctx_platform_matrix.py never passes n_parallel, so all 108 cells ran at the GgufLoadIntent default of 1, and the block is gated on n_parallel > 1. ## The fix Three changes in llama_cpp.py, all in the reduction block: 1. The search is priced at a new local `_reduce_ctx`, which is `min(effective_ctx, _FIT_MIN_CTX)` and never _AUTO_OFFLOAD_CTX. An explicit context is the exception and keeps its own value, since it launches verbatim and a slot count picked at a lower context would not hold. `_FIT_MIN_CTX` rather than a literal because _largest_ctx starts its binary search at the same floor and the two have to agree; that search's `min(4096, _native)` now reads the constant too. 2. The re-fit is applied whenever it exists, not only when it exceeds effective_ctx. That gate was safe only while the search and effective_ctx shared a value. The re-fit is the largest context the FINAL slot count holds on the cards the reduction chose, so anything else launches a context that was never priced. 3. The published ceiling replaces the offload anchor rather than max()-ing with it. Reaching there means the anchor described a plan this block superseded, and max() would advertise a context the launched plan cannot serve, the same ceiling/selection inversion unslothai#9492 removed, pointing the other way. Placement is now invariant to _AUTO_OFFLOAD_CTX, which is what the constant being a display value means. unslothai#9492's intended improvements are all kept: the UI ceiling anchor, the file-size-only arm, and the 8,192 context on loads that do genuinely offload. ## Tests Two of the 26 were genuinely stale: both assert the offload fallback itself, never reach the reduction, and hardcoded 4096. They now read `min(_AUTO_OFFLOAD_CTX, NATIVE_CTX)` so the constant can move again, each with a guard asserting the case still lands in the branch its name claims. The explicit-context one keeps its 32768 literal, since honouring the request verbatim is the contract and a derived value there would assert nothing. TestTheReductionIsPricedAtTheFitFloor is new and pins the root cause: - the plan's slots, residency, context and devices are unchanged across _AUTO_OFFLOAD_CTX in {4096, 8192, 16384, 32768}, so this cannot be satisfied by re-baselining the constant into the expectation; - every size in the rescued band launches --fit off, with `slots < 4` proving it was rescued by the reduction rather than fitting outright; - a counterweight at 11,400 MiB that must still offload, so the band above is not green merely because everything is; - the final slot count is monotone in the requested count, with a guard that the row is not all the same number. test_compute_buffer.py's test_wired_into_both_call_sites counted source substrings and reddened on the variable rename here. It now reads the call sites out of load_model's parse tree and requires every one that passes split_extra_bytes to pass `_cc_split_extra(<name>)`. That turned up a fourth call site the counting version could not see: it counted the two spelled `effective_ctx` plus one spelled `ctx`, and the projector-floor site spells its context `_mm_floor_ctx`, so the check that claimed to cover every call site had never covered it. It has been wired correctly all along. ## Anti-vacuity One mutation at a time against the repaired suites (77 tests): | Mutation | Result | |---------------------------------------------------|------------------| | this branch | 77 passed | | probe put back at the offload fallback | 35 failed | | ceiling put back to max() | 7 failed | | re-fit gated on being an increase again | 16 failed | | explicit context probed at the floor | 2 failed | | _AUTO_OFFLOAD_CTX moved to 4096 | 77 passed | | _AUTO_OFFLOAD_CTX moved to 16384 | 3 failed | Every reintroduction of the defect reddens. Moving the constant to 4096 is fully green, which is the invariance the fix is for. At 16384 the three remaining failures are in test_slot_refit_ctx_checkpoints.py, where the charged case stops reaching the re-fit at all; placement there is still identical at both anchors (4 slots, --fit on, same search) and only the launched context tracks the constant, by design. Left alone rather than re-scoped: that file is green before and after this change. ## Local runs - the three re-fit suites: 77 passed, was 33 passed 26 failed. - 81 placement, VRAM, GPU, context and llama.cpp backend test files, the blast radius of this change: 4033 passed, 2 skipped, 0 failed. Was 1 failed. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Credit to @Imagineer99 for correctly diagnosing the planner ordering bug that motivated this PR and providing the first CI reproduction.
Summary
Fix the Auto context reported in this r/LocalLLaMA thread, where Qwen3.8-27B loaded at
-c 4096and changing the KV-cache quantization did not update the estimated VRAM capacity.Studio initially fits context using the requested
--parallelcount, which defaults to four. If that plan cannot stay fully on GPU, it may reduce the serving slots before launch. The context and publishedmax_context_lengthwere not recalculated, leaving them sized for slots that were no longer used.This change re-fits context after slot reduction using the final slot count. For a fixture where four requested slots reduce to one:
Implementation
_slots_that_fit_on_gputo test the requested slot count itself.max_context_lengthfrom that result so the UI warning uses the final plan.Explicit context requests remain unchanged. The re-fit only widens Auto context and never changes the selected slot count or turns
--fiton. Tensor parallelism, Metal, KV caches whose size cannot be estimated, and models that require offload do not enter this path.Known limitation
With speculative decoding on Auto, drafter admission still happens before slot reduction. A direct one-slot request can therefore choose a different speculative mode and context than a four-slot request that later reduces to one. This behavior predates the change and is covered explicitly by the regression tests. Correcting it requires planning the drafter, slots, and context together and should be handled separately.
Verification
--fitdecisions did not change.ruff checkpassed on both changed files.The additional bisection runs only when slots are reduced and added about 0.7 ms to the measured planning time.