Skip to content

Make the VRAM budget fraction tunable - #8589

Merged
danielhanchen merged 28 commits into
mainfrom
vram-budget-setting
Aug 13, 2026
Merged

danielhanchen merged 28 commits into
mainfrom
vram-budget-setting

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Aug 12, 2026 •

Copy link
Copy Markdown
Member

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:

  • the --parallel 4 slot logits buffers are a real cost of parallel chatting
  • the 2049 MiB compute-buffer term is measured, not padding. Under -sm layer ggml sets n_copies to GGML_SCHED_MAX_COPIES == 4 and the f16 KQ mask is a GGML_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:

llama_cpp.py:1894  _CTX_FIT_VRAM_FRACTION = 0.97   (module level)
llama_cpp.py:5747  _GPU_PIN_VRAM_FRACTION = 0.97   (class attribute)

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.py stores it in the existing app_settings table. Precedence follows UNSLOTH_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-budget mirrors model-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_model resolves 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:

  • the pre-computed absolute pool budgets keep passing 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 nested def re-evaluated per load_model call, 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 optional step so 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 same displayValue the 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_mib floors 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:

  • it applies only above the default, so an unset budget reserves exactly what it always did on every card size. Without that condition the floor would raise the reserve at 97% on any card under about 17 GB, where 3% is less than 512 MiB, and break the no-op guarantee this change is built on.
  • only the known-total branch floors. The pre-computed pool budgets pass budget_frac = 1.0 with total_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_fraction takes 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. bool is rejected explicitly since it subclasses int and True would 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

  • New 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_FRACTION so an unset budget stays a no-op.
  • New test_fit_context_follows_the_user_vram_budget in test_tensor_parallel.py: a raised budget yields strictly more fitted context, a lowered one strictly less, and clearing returns to exactly the old number.
  • New frontend test for the percent/fraction round-trip across the whole range.
  • Updated the source-text assertion in 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.
  • New 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.
  • Backend: 983 passed across the VRAM suites. Frontend: typecheck clean, 2023 passed.
  • Round-tripped against a real SQLite database: fresh install reads 0.97, a saved value survives a restart, stored beats env, clearing falls back to env and then to the default, and the resolver in llama_cpp sees 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_vram and proves the budget moves the number in both directions, but I have not watched a 27B actually load at 100%.

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.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Aug 12, 2026
…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.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Aug 12, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment on lines 6053 to +6056
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()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Aug 12, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

Before/after from two isolated installs, BEFORE at the merge base 51fac012b and AFTER at b99cf1f6d. Both sides are built from their own checked-out tree, since the frontend bundle only contains a change if it was built from a tree that had it.

VRAM Budget row, before and after

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:

budget_row_present   false -> true
panel_text           ... GPU Memory | Default | Chat Template ...
                  -> ... GPU Memory | Default | VRAM Budget | Chat Template ...
GET /api/settings/vram-budget
                     HTTP 404
                  -> {"fraction": 0.97, "is_stored": false, "default_fraction": 0.97,
                      "min_fraction": 0.8, "max_fraction": 1.0, "reload_required": false}

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:

  • The first attempt used a fixed viewport clip and returned two byte-identical PNGs while panel_text plainly differed. The clip had missed the settings column. It is an element screenshot now, so both sides frame the same node by construction.
  • A bare [role="slider"] matches the Context Length slider at the top of the same panel and reported aria-valuenow 262144 on both sides. That is a fact-shaped reading of the wrong control, which is worse than no reading at all. It is scoped to the budget row now.

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.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@danielhanchen

Copy link
Copy Markdown
Member Author

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.

VRAM Budget row, before and after

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:

budget_row_present  false -> true
budget_value        null  -> "97"
budget_input        null  -> "97"
settings_api        HTTP 404 -> {"fraction": 0.97, "is_stored": false, "default_fraction": 0.97,
                                 "min_fraction": 0.8, "max_fraction": 1.0, "reload_required": false}

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.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

… on terminal failure, settle open writes before Run
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 12, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 12, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 12, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 12, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 12, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 12, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 12, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 12, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 13, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 13, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 13, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

…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.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

--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.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 13, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 13, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 13, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 13, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 13, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 13, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 13, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 13, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment on lines +10806 to +10807
if gpus:
return _vram_frac

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

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.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 13, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 13, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. You're on a roll.

Reviewed commit: 1925092eae

ℹ️ 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".

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants