Repository navigation
Make the VRAM budget fraction tunable - #8589
Conversation
The fit reserves 3% of every card that the model and KV cache may not use. That was two hard-coded 0.97 constants, so the only way to trade the reserve for context was to edit the source. On a 2x24GB box it is 1475 MiB, about 18k tokens. Adds UNSLOTH_VRAM_FRACTION and a VRAM Budget slider in Advanced settings, both resolving through one setting stored in app_settings. Precedence follows UNSLOTH_MODEL_IDLE_TTL: a saved value wins, the environment is a startup default, the constant is the last resort. Unset resolves to 0.97, so nothing changes for anyone who does not touch it. The fraction is resolved once per load and threaded through every budget, so GPU ranking, the tensor-parallel admission check, the MTP probe and the fit are all priced against the same number. Ranking against one fraction and fitting against another mis-orders mixed-total setups. Both constants stay as the fallback. The pre-computed absolute pool budgets keep passing budget_frac = 1.0 and are untouched.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 5913dcffaa
ℹ️ 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".
| clearTimeout(saveTimer.current); | ||
| } | ||
| saveTimer.current = setTimeout(() => { | ||
| updateVramBudgetSettings(vramPercentToFraction(next)) |
There was a problem hiding this comment.
Expose a reset that sends a null fraction
Once the user moves the slider, every save sends a numeric fraction; isStored is never used and the client never invokes the API's null clearing behavior. Because a stored value takes precedence over UNSLOTH_VRAM_FRACTION, moving the slider back to the apparent environment or built-in default merely stores that number, so later environment changes remain ignored and there is no UI action that restores inheritance. Add a Reset action using isStored that sends { fraction: null }.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not taking this one. The observation is accurate (isStored is returned and unused, and every save sends a number), but a missing Reset button is an absent affordance rather than a defect: nothing executes wrongly and nothing is lost. The clear path itself is already wired end to end and I verified it against this tree's pydantic: fraction Optional[float] with ge/le accepts null while still rejecting 0.5, set_vram_budget_fraction(None) writes a null row, and updateVramBudgetSettings(null) exists, so clearing works today via the API and only lacks a button. isStored is kept because it is what such a button would key on. Worth a follow-up, not scope for this PR.
…Apple gate _vram_fraction_launched was assigned at the top of load_model, above the duplicate-load fast path. Requesting the same GGUF after saving a different budget returns early with the OLD child still serving, so the marker recorded a fraction that child was never sized against and reload_required went quiet. Cancellations and failed preflights had the same shape. It now commits with the rest of the known-good launch state, after _healthy. The budget slider debounced its PUT by 400 ms and the unmount cleanup only cleared the timer, so dragging it and then clicking Run, toggling Advanced or closing the panel dropped the save. This is a server-wide value held nowhere else, so nothing recovered it. Unmount now flushes the pending fraction instead. _plan_tensor_parallel resolved the budget a second time, which could disagree with the fraction load_model already captured if a save landed mid-load. It takes the load's fraction and only resolves its own for direct callers. Hid the control on macOS. Every branch that reads the budget is gated on a discrete GPU, and macOS reports none, so the Metal path sizes from _APPLE_UNIFIED_MEMORY_FRACTION and fits with budget_frac = 1.0. The slider could not move anything there while claiming it applied on the next load. Tests: the marker survives a duplicate-load adopt, and the unmount cleanup flushes rather than drops. Both fail without the fixes.
|
@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: b99cf1f6d8
ℹ️ 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".
| min_gpus = max(1, min(min_gpus, len(gpus))) | ||
| model_size_mib = model_size_bytes / (1024 * 1024) | ||
| if usable_fraction is None: | ||
| usable_fraction = LlamaCppBackend._GPU_PIN_VRAM_FRACTION | ||
| usable_fraction = _active_vram_fraction() |
There was a problem hiding this comment.
Enforce the custom reserve when falling back to --fit
For a Default-mode load whose weights and context exceed the selected fraction, this planner returns use_fit = true, but the checked command construction later emits only --fit on. The same module documents --fit-target as llama.cpp's margin control at lines 15763-15784 and emits it only for Manual + Auto, so a lower server-wide fraction merely triggers fallback fitting and is not carried into the fitter that chooses the final GPU occupancy. This defeats the setting specifically for tight models where reserving VRAM matters most; pass an equivalent per-device reserve to the fallback or keep placement under the fraction-aware planner.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not taking this one. The reading of the code is right: --fit-target has a single emission site, guarded on use_fit and auto_fit and the capability probe, so Manual plus Auto only, and its value is the literal 512, so the fraction is not carried into the fallback fitter. What makes it out of scope is that none of it is new. At the merge base 51fac01 the same --fit on extend, the same --fit-target 512 literal and the same Manual plus Auto docstring are already there, and the diff against that base has no hunk anywhere in the argv construction or in _ctx_integrity_flags. The hard-coded 0.97 this PR replaces was never transmitted on that path either, so the fallback is exactly as fraction-blind as it was before and this PR neither creates nor widens the gap. Worth saying that the fraction is not entirely absent from that path: it decides whether use_fit is returned at all, and on the non Manual plus Auto paths it reaches the child through effective_ctx and -c. Carrying a per-device reserve into --fit-target is a real improvement, and a separate change to the placement code rather than to the setting that surfaces it.
|
Before/after from two isolated installs, BEFORE at the merge base AFTER gains a VRAM Budget row directly under GPU Memory, reading 97 with its slider near the top of the 80-100 range. BEFORE goes straight from GPU Memory to Chat Template. Advanced settings reads ON in both halves, so neither side is a collapsed panel. The numbers beside the picture, read from the same servers that were photographed: The 404 on the BEFORE side is the intended behaviour, not a broken half: the client hides the control when the endpoint is missing, which is what keeps a newer UI working against an older backend. Two things worth recording, because both produced a clean-looking result that proved nothing:
Also worth knowing for anyone reproducing this: the panel is not reachable from a repo's Hub detail pane, which is the README. It opens from Hub -> On Device -> the card's Settings button. |
…ntrol, strict payload
|
Refreshed the before/after against the current head, since the review round moved the control behind two more gates (Manual mode and an empty GPU device list) and the earlier image no longer described what renders. Same install on both halves, built from the merge base 51fac01 and from a9b4f2f, Advanced settings switched on for both. AFTER gains one row, VRAM Budget, directly under GPU Memory, reading 97 with the slider near the top of its range; BEFORE goes straight from GPU Memory to Chat Template. Read out of the DOM rather than the picture: The 404 on the BEFORE side is the intended forwards-compatible behaviour: an older backend has no such route, and the client hides the control rather than erroring. |
…tings, clear the marker on diffusion
…ing value through finalization, serialise writes
… on terminal failure, settle open writes before Run
…riced A Manual + Auto child is fitted against the budget through --fit-target even though the planner never saw a GPU list, so record the fraction it launched with or a later change reports no reload needed. Close the control while Run settles a save, rather than settling repeatedly and still leaving an edge. A read displaced by a forced one no longer publishes its pre-load answer.
--fit-target now tracks the budget in both directions from each path's own starting margin, floored at 512 MiB, so raising the slider reclaims VRAM on the fallback too; an unreported total falls back to free, the scale the planner already uses there. Show the row for Manual + Auto, which the flag now reaches. Settle on the write itself rather than the chain that swallows its rejection, and hold a read back from publishing over a newer write.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 03640bc0c6
ℹ️ 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 gpus: | ||
| return _vram_frac |
There was a problem hiding this comment.
Keep unsupported fit fallbacks marked unpriced
When a tight Default-mode load sets use_fit but the selected llama-server does not advertise supports_fit_target, _ctx_integrity_flags emits no budget-adjusted target and llama.cpp fits with its own margin. Because gpus remains nonempty, this branch nevertheless records _vram_frac as the launched budget, so subsequent settings responses report no reload required and duplicate loads reuse a child that never applied the selected fraction. Fresh evidence beyond the earlier comment is the new capability guard at command construction combined with this unconditional launched marker; gate this result on whether the planner or emitted fit target actually priced the placement.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
I do not think this one holds, and the consequence is the other way round. A recorded fraction is what CAUSES the reload prompt: _vram_budget_reload_required returns launched != fraction, and returns False when launched is None, so recording None is what would report no reload required. Same in the duplicate check, which refuses to adopt when launched differs from the active fraction. There is also a real sense in which that child IS priced: with a non-empty gpus the planner chose devices, layers and the advertised context against the fraction, and --fit is the fallback for what would not fit inside it. If the setting then changes, the next load plans differently even on a server with no --fit-target, so prompting for a reload is correct rather than spurious. If I have misread which branch you mean, point me at the sequence where a stamped child leads to a MISSING reload prompt and I will take another look.
Suppressing the publish left the caller applying the same stale answer by hand, so a read overtaken by a save could put back the isStored and reloadRequired that save had just changed.
One value is broadcast to every device, so the largest card sizing it left a raised budget taking a smaller card below its own margin. Lowering now scales by the largest and raising by the smallest, which is safe on every card in both directions.
|
Codex Review: Didn't find any major issues. You're on a roll. 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". |
Comments only, no code changes.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 6be4d2fce8
ℹ️ 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".
| // baseline and the Reload button disabled, with the row asking for a reload the | ||
| // user could not start. Read off the same publish the row uses, so nothing is | ||
| // threaded through GpuMemorySettings and a row that never mounts leaves it false. | ||
| const [budgetReloadRequired, setBudgetReloadRequired] = useState(false); |
There was a problem hiding this comment.
Fetch the initial budget reload state
When an active model survives a browser/page remount while Advanced settings are collapsed, this state always starts false and only changes after a same-page publish. Because VramBudgetRow is mounted only under showAdvanced, no GET occurs in that state, so a budget previously changed through the API or before the remount can have reload_required=true on the server while the Reload model button remains disabled at baseline. Load the current budget state here (or retain it in a shared store) rather than relying solely on future events.
Useful? React with 👍 / 👎.


Why
A user on 2x RTX 3090 reported Studio offering 175k context where LM Studio offered 200-250k. I went through the reserve line by line and most of it is not slack:
--parallel 4slot logits buffers are a real cost of parallel chatting-sm layerggml setsn_copiestoGGML_SCHED_MAX_COPIES == 4and the f16 KQ mask is aGGML_TENSOR_FLAG_INPUT, so one live copy becomes four. Charging 1x would under-reserve by 2.67x.The part that is a policy choice is the 3% per-GPU headroom, and it was two hard-coded constants:
No env var, no CLI flag, no request field, no UI. On a 2x24GB box that reserve is 1475 MiB, about 18k tokens at this model's 84 KiB/token. Someone on a dedicated box has no way to claim it, and someone sharing a GPU has no way to give more of it up.
Worth being precise: this is worth about 18k tokens, not the 75k gap in that report. The rest is the slot buffers and the compute copies, and both are earning their keep.
What
UNSLOTH_VRAM_FRACTION, plus a VRAM Budget slider in Advanced settings. Range 80-100%, default 97%.New
utils/vram_budget_settings.pystores it in the existingapp_settingstable. Precedence followsUNSLOTH_MODEL_IDLE_TTL: a saved value wins, the environment is a standalone startup default, the constant is the last resort. Unset resolves to 0.97, so nothing changes for anyone who does not touch it.GET/PUT /api/settings/vram-budgetmirrorsmodel-memory, echoing the default, the bounds, whether the value is stored, and whether a reload is needed.The fraction is resolved once per load
load_modelresolves it into a local and threads that through every budget, so GPU ranking, the tensor-parallel admission check, the MTP probe and the fit are all priced against the same number. Ranking against one fraction and fitting against another mis-orders mixed-total setups. Nine reads changed; both constants stay as the fallback.Two things deliberately left alone:
budget_frac = 1.0. They pass an absolute budget from_pool_budget_mib, so the fraction must stay neutralised there._APPLE_UNIFIED_MEMORY_FRACTION(0.85) and_MTP_VRAM_RESERVE_FRAC(0.05). Apple memory is shared with the OS and has a different risk profile, and the MTP fraction is only a fallback for when GGUF dims are too sparse for the byte-accurate reserve._gpu_usable's default argument is a nesteddefre-evaluated perload_modelcall, so binding it to the resolved local is what carries the budget into the tensor-parallel admission check at the two call sites that rely on the default.UI
The slider sits with the GPU controls but renders in Default mode too, since the budget drives the auto-fit that Manual mode opts out of. It reuses
AdvancedGpuSlider, which now takes an optionalstepso this row can move in tenths of a percent while every other caller keeps whole steps. On a 24 GB card a whole percent is about 245 MiB of context, a coarser grid than this setting is worth. The number is shown with a percent sign through the samedisplayValuethe GPU Layers row uses for "Auto", and percent and fraction round-trip exactly on that grid, so 97.5% stores 0.975 and reads back 97.5%.Every other control in that panel is per-model and this one is not, so the hint says it applies to all models.
The warning is direction-specific, because the two failure modes are different:
100% still leaves 512 MiB
The top of the range is safe to pick.
_vram_usable_mibfloors the per-card reserve at 512 MiB, the same margin llama.cpp passes to its own fitter as--fit-target 512, so 100% means "leave 512 MiB" rather than "claim the card whole".Two conditions on that floor, both load-bearing:
budget_frac = 1.0withtotal_mib = None, and charging them a second reserve would double-count one the pool budget has already paid per card.On the 2x24GB box in the report, moving from 97% to 100% hands back 225 MiB per card.
Validation
Nothing can reach the fit malformed.
coerce_fractiontakes the stored JSON number and the raw env string down the same path, and the range check is two-sided on purpose: NaN loses every comparison, so a one-sided check would let it through and turn every per-GPU budget into NaN.boolis rejected explicitly since it subclassesintandTruewould otherwise read as 1.0. A corrupt row, an unreadable database or a malformed env var all fall through to the default rather than failing a load.Tests
test_vram_budget_settings.py, 41 cases: parsing, NaN/inf/bool/out-of-range rejection, precedence, corrupt-row fallback, and that the default tracks_CTX_FIT_VRAM_FRACTIONso an unset budget stays a no-op.test_fit_context_follows_the_user_vram_budgetintest_tensor_parallel.py: a raised budget yields strictly more fitted context, a lowered one strictly less, and clearing returns to exactly the old number.test_mtp_vram_budget.py. It pinned the literal expression at the subset-ranking site, which this change rewrites; the new assertion keeps its intent and also pins that the fraction is resolved once.TestFloorReserve, including the regression bar that the reserve at the default is unchanged on 4, 8, 16, 24 and 80 GB cards, and that an absolute pool budget is not charged twice.llama_cppsees each change.Backwards compatible: old installs have no stored row and read the fallback, so no migration. A newer UI against an older backend hides the control instead of erroring.
One thing I did not do: run the full model-load leg end to end at 80/97/100% on real hardware. The fit test exercises the real
_fit_context_to_vramand proves the budget moves the number in both directions, but I have not watched a 27B actually load at 100%.