Repository navigation
Studio: honour an unmeasured context request and price the real attention plan - #11025
Conversation
…tion plan Two context numbers were wrong for the same underlying reason: a figure that described a load other than the one about to start. When a GGUF carries no attention dimensions, _can_estimate_kv() is False and two arms fall back to a short context: _plan_tensor_parallel (a bare 4096, now _TP_UNMEASURED_CTX) and the Metal unified-memory arm (_metal_floor_ctx). Both applied that fallback to an explicit request and published it as max_context_length, so a 262,144-token selection came back as 4,096 with the slider reporting that nothing longer fits. The fallback is a guess, which is why _metal_context_overcommit_message already refuses to refuse against it; a guess equally may not overrule a context the user typed, nor be published as "the largest that fits" once the load has run above it. Auto keeps the conservative fallback, and both arms now record why the ceiling is unmeasured. load_model also pinned planned_flash_attn = False unconditionally while every launch emits --flash-attn on. The estimator is not indifferent: with flash attention off it floors the V axis at f16 and pads variable-width V tensors, so a q8_0 cache at 262,144 was priced at 23.0 GB against the 16.0 GB the launch allocates, and q4_0 at 19.3 GB against 8.5 GB. In tensor mode --fit is a no-op, so that inflated cache became the published ceiling: KV quantization did not move the available context. Resolve the state once, from the build's capability, the environment, the extra arguments and the quantized-V rule that llama.cpp applies itself, and thread that one answer through the estimate and the argv. The pre-emptive reserve is not needed: tensor mode cannot take the flash-attention-off recovery at all, and elsewhere the no-flash respawn already re-enters _spawn_and_wait, whose own rung hands placement back to llama.cpp with --fit on. GET /api/models/kv-cache-estimate took the estimator's defaults for the three knobs that decide the cache layout and had no way to be told otherwise, which is how the memory panel, the loader's log and the context warning ended up quoting three different numbers for one model. It now accepts flash_attn, kv_unified, swa_full and no_mmproj_offload, resolves them the way the launch does when they are omitted, and hands the same plan to the planner half of its own answer.
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. |
|
Cross-platform CI for this branch, run on a staging repo so the org queue is untouched. Linux, Windows, Apple Silicon macOS and a live Studio Playwright leg, all off the same head.
Counts are read out of each job's pytest summary line rather than from the job's own conclusion, since the generated workflow deliberately treats "no tests ran" and a dependency-only collection failure as a pass. The Windows failure is macos-15 is the only leg that can execute the Metal arm on real hardware; it had not been given a runner at the last check, so that arm still rests on the platform seam the existing Metal suites use. I will add the counts here when it lands. |
The resolver folds llama.cpp's auto into on, and auto is llama.cpp saying it will decide at load time. It decides against flash attention whenever the backend, the model or the cache pair cannot take it, with no error and no log line, so an estimate that reads auto as on prices a cache that can turn out 1.44x larger at q8_0 and 2.28x at q4_0. Studio emits flash attention on rather than auto, so only a user's extra arguments or an inherited LLAMA_ARG_FLASH_ATTN reach this, and there the sizing that survives either answer is the padded one. A quantized V cache still forces it on, since llama.cpp turns it on itself, and last wins as before.
|
Second pass over this one. One gap found in the new resolver and fixed on the branch.
Fixed in 359d66a: an explicit auto, from the extras or from the environment, prices the padded f16-floored cache. Last wins is preserved in both directions, a quantized V cache still forces flash attention on because llama.cpp turns it on itself, and the managed launch is untouched. Five tests added. Also checked:
|
…pinned projector to VRAM load_model appends a managed --flash-attn on and llama.cpp reads LLAMA_ARG_FLASH_ATTN before argv, so with no user -fa the child runs with flash attention whatever the environment said, while the estimate priced the padded f16-floored cache and published a lower context ceiling. --no-mmproj-offload keeps vision on and puts the projector in host memory, but the route still itemised projector_bytes and the frontend adds it straight onto its GPU weights segment.
|
@codex security review |
|
Codex Review: Didn't find any major issues. Chef's kiss. 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". |
Delete-first pass over the blocks this PR adds and the tests it brings with it: collapse multi-line rationale to one line, drop measured numbers and restatements of the code. Comments, docstrings and whitespace only, AST gated; no behaviour change.
A blank --ctx-checkpoints now resolves to llama.cpp's default rather than zero, and --swa-full zeroes the checkpoint share, so the totals move the other way while the attention cache itself still grows.
|
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". |
…epending on import order test_a_host_pinned_projector_is_not_charged_to_the_card has never passed. It was added in d44cb0c passing no_mmproj_offload to _call_route, which does not take that argument and does not forward it, so the test raised TypeError at the call rather than exercising the route. The product half of that commit is correct and is unchanged here: --no-mmproj-offload keeps vision on and puts the projector in host memory, which is what load_model has assumed since #5825, and the route was the last place still itemising projector_bytes for it. _call_route now takes and forwards all four launch knobs the route resolves itself. Passed by name and as real None on purpose: a direct call leaves an omitted parameter holding its fastapi Query sentinel, which the route survives only because of an isinstance(..., bool) guard, and a helper that never names the argument cannot notice when a new one is added. With the argument threaded through, the test passes; reverting the route's `if _asked_no_mmproj: projector = None` turns it red on the assertion it was written for. The second half is the loggers stub. test_kv_cache_estimation installs a bare ModuleType into sys.modules["loggers"], and a bare module shadows the whole package rather than just its __init__, so `from loggers.media_progress import ...` in routes/inference.py (reached at import time through routes/__init__.py) dies with "'loggers' is not a package". That made test_kv_cache_estimate_route.py uncollectable on its own from the repo root, measured on 205771c. tests/conftest.py settles the real package first (#11028) and currently masks it, but that guard skips itself whenever `import loggers` raises, which is any runner where structlog is stubbed away. Give the stub a __path__ instead, the same fix and the same reason as test_preview_routes.py (#10995), and the ordering stops mattering in every case. The local try/except band-aid this branch added to test_kv_cache_estimate_attention_plan.py is then dead weight and is removed. test_the_shared_loggers_stub_is_still_a_package keeps that honest. It asserts against the stub object rather than the sys.modules slot, because the conftest guard usually wins the slot with the real package and a check on the slot would pass with the stub broken. Deleting the __path__ line turns it red in an ordinary run, guard and all. This is a product import-order question only in appearance. Nothing outside the test suite writes a bare module into that slot, and all four orderings of loggers, routes.models and routes.inference import cleanly against the real package. A caller reaching for studio.backend.routes.inference fails earlier and for an unrelated reason, on `No module named 'routes'` in routes/__init__.py, because the backend is a flat-layout app that wants studio/backend on sys.path.
|
@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: 996d419105
ℹ️ 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 any( | ||
| _flag_name(str(token)) in {"-fit", "--fit"} for token in (extra_args or ()) | ||
| ): | ||
| return fa_cmd |
There was a problem hiding this comment.
Honor inherited fit-off on no-flash retries
When LLAMA_ARG_FIT=off is inherited and an automatically placed launch crashes into the no-flash recovery, this guard only checks extra_args, so _enable_managed_fit_for_no_flash rewrites Studio's --fit off to --fit on and the CLI overrides the inherited setting. This contradicts _user_fit_disabled, which explicitly treats the environment value as user-disabled and reserves the larger no-flash cache for that case; the retry can therefore unexpectedly reduce GPU offload or context despite already having a safe fixed placement. Include the inherited fit setting in this skip condition.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct, and fixed in be7406b. LLAMA_ARG_FIT is only scrubbed from the child env under gpu_memory_mode == "manual" (_clear_manual_placement_env), and the no-flash retry is an auto-placement path, so outside manual an inherited off reached llama-server and the flip then beat it on the CLI. The skip now goes through _user_fit_disabled(extra_args, env = env), the same helper that already reserved the padded V cache for that load, so the respawn lands on a placement priced for the larger cache and has nothing to re-place. A user's own --fit token still skips whatever the environment says. Pinned by test_an_inherited_fit_off_survives_the_no_flash_retry, which fails without the guard.
…aths Comment and docstring text only, no behaviour change. Collapses the multi-line rationales added by this PR to their load-bearing facts, drops restatements of the code, the repeated re-price notes at each tensor-mode downgrade, and the section banners in the new test modules.
The retry's fit flip skipped a user's own --fit token but not the environment spelling of it, which only manual mode scrubs, so outside manual the flip put --fit on on the CLI and beat the inherited off. _user_fit_disabled reads that variable and had already reserved the padded V cache for the load, so the respawn lands on a placement priced for it and needs no re-place.
|
@codex review |
|
Codex Review: Didn't find any major issues. Hooray! 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 reserve read planned_flash_attn through a default argument, so it held whatever the plan said where the closure was written, above the four tensor downgrades that re-plan it. The KV cache and compute buffer beside it already re-read the plan at call time, so after a downgrade one total was assembled from two attention plans: the cache priced the layer split's padded, f16 floored V while the draft reserve still priced the tensor plan's unpadded one. A hybrid SWA draft head prices 4.5x larger with flash attention off, 3.5 GB at 262,144 tokens on a four layer shape, so the shortfall is an OOM at startup on a total the placement called safe, and a user --fit off, which is one of the states that makes the downgrade resolve attention off in the first place, takes away the re-placement that would have absorbed it. The other captures in that closure settle with the load and are left alone.
|
@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: 2f5b96d878
ℹ️ 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".
| flash_attn = _planned_flash_attn( | ||
| # Shared with load_model so the estimate and the launch cannot answer differently | ||
| # (#9697, #10489). | ||
| flash_attn = _planned_flash_attn_state( |
There was a problem hiding this comment.
Preserve the no-flash reserve in the admission estimate
When training is active and an Auto GGUF load has --fit off (or inherits LLAMA_ARG_FIT=off), this runtime estimate prices the flash-attention-on cache, while load_model deliberately passes the same plan through _reserved_flash_attn_state and prices the larger no-flash recovery because that retry cannot be re-placed. _estimate_gguf_kv_gb feeds this result into the active-training admission guard, so the guard can approve a load based on the smaller cache and then let a no-flash retry consume more VRAM than was admitted, potentially OOMing the training process. Apply the same reserve adjustment here for placements whose fitter is disabled.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct, and fixed in fb8d8fc. _estimate_gguf_kv_gb does feed the active-training admission guard, and load_model holds the reading down through _reserved_flash_attn_state for exactly the two placements you name, so resolving only the plan here admitted a load against the smaller cache that the same placement then reserves the larger one for. Measured on a ragged-SWA shape at 32,768 tokens with --fit off in the extras: admitted 9,709,813,760 against a reserve of 13,222,543,360, a 3.5 GB gap the guard would have approved.
Applied on the guard path only, via a reserve_no_flash_respawn keyword that _estimate_gguf_kv_gb passes and the panel does not. Putting it in _gguf_runtime_bytes unconditionally was my first attempt and it broke test_memory_estimate::test_an_auto_load_with_an_extras_ngl_is_not_fully_resident, which pins that an extras -ngl moves bytes between host and device without changing the total: the panel means what the launch uses, the guard means the worst the placement can reach. Tensor mode stays exempt on both paths, since there is no flash-attention-off respawn under SPLIT_MODE_TENSOR to reserve for.
Covered by test_the_admission_estimate_keeps_the_no_flash_reserve, which also pins the panel's totals unmoved. A ragged-SWA fixture because the axis is invisible otherwise: a quantized V forces flash attention on, and an equal-width f16 cache does not move with the state, so the control could not have failed on either.
_record_load_warning is first-notice-wins with one slot, and both arms that raise an unmeasured ceiling decide it long before the host-RAM and offload advisories run. Recording the notice there took the slot, so a load that is told it will page from disk heard only that its ceiling was unmeasured, on the one path that also raises the launched context from the fallback to the full request. Held in _unmeasured_ctx_notice and flushed past both advisories, appending when one spoke and recording when none did. Measured on the tensor arm with an unsizeable KV cache and an explicit 262,144: the host advisory survives and the notice follows it, where before only the notice was left.
_estimate_gguf_kv_gb feeds the active-training admission guard, and load_model holds the flash-attention reading down through _reserved_flash_attn_state for the two placements a flash-attention-off respawn cannot be re-placed out of: a user's own --fit off, and a fixed layer count. The route resolved only the plan, so the guard admitted a load against the smaller cache that the same placement then reserves the larger one for, and the respawn could take VRAM the guard never admitted and the training run with it. Measured on a ragged-SWA shape at 32,768 tokens with --fit off: admitted 9,709,813,760 against a reserve of 13,222,543,360. Asked for by keyword rather than applied in _gguf_runtime_bytes, because the panel means the other thing. It shows what the launch uses, and its total is placement-independent -- test_memory_estimate pins that an extras -ngl moves bytes between host and device without changing the total, which a reserve keyed on placement would break. Tensor mode stays exempt on both paths: llama.cpp has no flash-attention-off respawn under SPLIT_MODE_TENSOR to reserve for.
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. Breezy! 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". |
…tted (#11207) #11025, #10533 and #11067 each landed today with a blank line the ruff-format-with-kwargs hook removes or adds, so `pre-commit run --all-files` is red on main. Every open PR inherits that: pre-commit.ci evaluates the PR merged with main, finds files to rewrite that the PR never touched, and pushes them onto the PR branch, which is how unrelated files end up in a diff. On a branch too far behind main to apply, it fails outright instead. Output of the repo's own hook, with the pinned ruff 0.6.9. Blank lines only. Co-authored-by: danielhanchen <[email protected]>
…tion plan (unslothai#11025) * Studio: honour an unmeasured context request and price the real attention plan Two context numbers were wrong for the same underlying reason: a figure that described a load other than the one about to start. When a GGUF carries no attention dimensions, _can_estimate_kv() is False and two arms fall back to a short context: _plan_tensor_parallel (a bare 4096, now _TP_UNMEASURED_CTX) and the Metal unified-memory arm (_metal_floor_ctx). Both applied that fallback to an explicit request and published it as max_context_length, so a 262,144-token selection came back as 4,096 with the slider reporting that nothing longer fits. The fallback is a guess, which is why _metal_context_overcommit_message already refuses to refuse against it; a guess equally may not overrule a context the user typed, nor be published as "the largest that fits" once the load has run above it. Auto keeps the conservative fallback, and both arms now record why the ceiling is unmeasured. load_model also pinned planned_flash_attn = False unconditionally while every launch emits --flash-attn on. The estimator is not indifferent: with flash attention off it floors the V axis at f16 and pads variable-width V tensors, so a q8_0 cache at 262,144 was priced at 23.0 GB against the 16.0 GB the launch allocates, and q4_0 at 19.3 GB against 8.5 GB. In tensor mode --fit is a no-op, so that inflated cache became the published ceiling: KV quantization did not move the available context. Resolve the state once, from the build's capability, the environment, the extra arguments and the quantized-V rule that llama.cpp applies itself, and thread that one answer through the estimate and the argv. The pre-emptive reserve is not needed: tensor mode cannot take the flash-attention-off recovery at all, and elsewhere the no-flash respawn already re-enters _spawn_and_wait, whose own rung hands placement back to llama.cpp with --fit on. GET /api/models/kv-cache-estimate took the estimator's defaults for the three knobs that decide the cache layout and had no way to be told otherwise, which is how the memory panel, the loader's log and the context warning ended up quoting three different numbers for one model. It now accepts flash_attn, kv_unified, swa_full and no_mmproj_offload, resolves them the way the launch does when they are omitted, and hands the same plan to the planner half of its own answer. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Size a flash-attention auto request as the load that may not get it The resolver folds llama.cpp's auto into on, and auto is llama.cpp saying it will decide at load time. It decides against flash attention whenever the backend, the model or the cache pair cannot take it, with no error and no log line, so an estimate that reads auto as on prices a cache that can turn out 1.44x larger at q8_0 and 2.28x at q4_0. Studio emits flash attention on rather than auto, so only a user's extra arguments or an inherited LLAMA_ARG_FLASH_ATTN reach this, and there the sizing that survives either answer is the padded one. A quantized V cache still forces it on, since llama.cpp turns it on itself, and last wins as before. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Size flash attention as the launch runs it, and stop charging a host-pinned projector to VRAM load_model appends a managed --flash-attn on and llama.cpp reads LLAMA_ARG_FLASH_ATTN before argv, so with no user -fa the child runs with flash attention whatever the environment said, while the estimate priced the padded f16-floored cache and published a lower context ceiling. --no-mmproj-offload keeps vision on and puts the projector in host memory, but the route still itemised projector_bytes and the frontend adds it straight onto its GPU weights segment. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Trim the comments in the files this PR touches Delete-first pass over the blocks this PR adds and the tests it brings with it: collapse multi-line rationale to one line, drop measured numbers and restatements of the code. Comments, docstrings and whitespace only, AST gated; no behaviour change. * Cut the remaining comments to the facts the code does not state * Compare the attention cache net of the checkpoint share A blank --ctx-checkpoints now resolves to llama.cpp's default rather than zero, and --swa-full zeroes the checkpoint share, so the totals move the other way while the attention cache itself still grows. * Make the kv-cache-estimate route tests run, and stop the collection depending on import order test_a_host_pinned_projector_is_not_charged_to_the_card has never passed. It was added in d44cb0c passing no_mmproj_offload to _call_route, which does not take that argument and does not forward it, so the test raised TypeError at the call rather than exercising the route. The product half of that commit is correct and is unchanged here: --no-mmproj-offload keeps vision on and puts the projector in host memory, which is what load_model has assumed since unslothai#5825, and the route was the last place still itemising projector_bytes for it. _call_route now takes and forwards all four launch knobs the route resolves itself. Passed by name and as real None on purpose: a direct call leaves an omitted parameter holding its fastapi Query sentinel, which the route survives only because of an isinstance(..., bool) guard, and a helper that never names the argument cannot notice when a new one is added. With the argument threaded through, the test passes; reverting the route's `if _asked_no_mmproj: projector = None` turns it red on the assertion it was written for. The second half is the loggers stub. test_kv_cache_estimation installs a bare ModuleType into sys.modules["loggers"], and a bare module shadows the whole package rather than just its __init__, so `from loggers.media_progress import ...` in routes/inference.py (reached at import time through routes/__init__.py) dies with "'loggers' is not a package". That made test_kv_cache_estimate_route.py uncollectable on its own from the repo root, measured on 205771c. tests/conftest.py settles the real package first (unslothai#11028) and currently masks it, but that guard skips itself whenever `import loggers` raises, which is any runner where structlog is stubbed away. Give the stub a __path__ instead, the same fix and the same reason as test_preview_routes.py (unslothai#10995), and the ordering stops mattering in every case. The local try/except band-aid this branch added to test_kv_cache_estimate_attention_plan.py is then dead weight and is removed. test_the_shared_loggers_stub_is_still_a_package keeps that honest. It asserts against the stub object rather than the sys.modules slot, because the conftest guard usually wins the slot with the real package and a check on the slot would pass with the stub broken. Deleting the __path__ line turns it red in an ordinary run, guard and all. This is a product import-order question only in appearance. Nothing outside the test suite writes a bare module into that slot, and all four orderings of loggers, routes.models and routes.inference import cleanly against the real package. A caller reaching for studio.backend.routes.inference fails earlier and for an unrelated reason, on `No module named 'routes'` in routes/__init__.py, because the backend is a flat-layout app that wants studio/backend on sys.path. * Itemize the projector by where the launch will actually put it * Let tensor split decide auto flash attention the way llama.cpp does * Price the split the launch can actually take * Price the resolved layer split in the KV cache estimate When the tensor split cannot launch, the estimate downgraded the planner devices but still handed the raw request toggle and the untouched extras to both memory breakdown calls, so the breakdown re-resolved tensor mode and priced a split the launch would not take. * Re-plan the attention after a tensor-mode downgrade llama.cpp requires flash attention under SPLIT_MODE_TENSOR, so AUTO is planned ON whenever the split resolves to tensor. The plan was made once near the top of the load and never revisited, so the six later points that drop tensor mode left the KV and compute estimates budgeting an unpadded V that the layer split with AUTO attention off does not get. * Re-plan the attention after the early manual tensor downgrades too The three manual guards drop the toggle without touching the extras, so they were not covered by the re-plan on the strip sites. Manual placement runs with --fit off, so a plan that still says flash attention is on under-prices the V layout of a model that grows without it and the child can OOM at startup on a total the estimate called safe. The test now walks every downgrade after the plan is made rather than only the ones that strip a split mode. * Keep the no-flash reserve when the user turned the fitter off The planned state is what the first process runs with, and the argument for reserving only for it is that a hard-crash respawn without flash attention is re-placed by llama.cpp's fitter. A user's own --fit off wins by last-arg over the token that retry rewrites, so there is no re-placement: the padded, f16-floored V cache lands on a placement chosen for the smaller one and the recovery OOMs at startup on a total the estimate called safe. Tensor mode is excluded, since it cannot take that recovery at all. * Re-plan the attention against the environment the child will see Tensor mode can arrive through an inherited LLAMA_ARG_SPLIT_MODE, and the helper resolves the split from the extras, the toggle and that variable, so a re-plan carrying a downgraded False met a tensor answer inside it and priced the unpadded V of a load that decides the question again under a layer split. The launch clears that variable (and its paired tensor split) before spawning for exactly this reason, so the re-plan now resolves against the same scrubbed environment. * Re-enable the fitter for the no-flash retry An auto placement that fits appends a managed --fit off, the --flash-attn off respawn inherits it, and _fit_off_retry_eligible refuses to enable fitting for any command naming the flag, so the retry re-lands on the placement priced with flash attention on while running the padded f16 V cache. Flip Unsloth's own token back to on for both no-flash respawns; a user's --fit is left alone, since theirs wins by last-arg and the reserve already holds down for it. * Keep the reserve for a placement the fitter will not move Manual mode emits --gpu-layers N --fit off, which is token for token what an auto placement that fits emits, so the no-flash retry flipped it back on and the reserve priced a re-placement that cannot happen: common_params_fit_impl throws on any count but llama.cpp's own -1 default and the caller downgrades it to a warning, so the retry keeps the fixed placement. A fixed count now skips the flip and holds the reserve down, the same way a user's own --fit off does. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Say only what the resolver's own order guarantees The docstring claimed this helper mirrors llama.cpp's branch order end to end. It mirrors the one branch it has to: llama_init_from_model forces flash attention off for LLM_ARCH_GROK above both of llama.cpp's own upgrades, so the architecture is read before anything else here too. The quantized-V branch below it is not in that order and does not need to be. * Tighten comments in the flash-attention plan and unmeasured-context paths Comment and docstring text only, no behaviour change. Collapses the multi-line rationales added by this PR to their load-bearing facts, drops restatements of the code, the repeated re-price notes at each tensor-mode downgrade, and the section banners in the new test modules. * Honour an inherited LLAMA_ARG_FIT=off on the no-flash retry The retry's fit flip skipped a user's own --fit token but not the environment spelling of it, which only manual mode scrubs, so outside manual the flip put --fit on on the CLI and beat the inherited off. _user_fit_disabled reads that variable and had already reserved the padded V cache for the load, so the respawn lands on a placement priced for it and needs no re-place. * Price the MTP draft reserve with the attention the downgrade re-planned The reserve read planned_flash_attn through a default argument, so it held whatever the plan said where the closure was written, above the four tensor downgrades that re-plan it. The KV cache and compute buffer beside it already re-read the plan at call time, so after a downgrade one total was assembled from two attention plans: the cache priced the layer split's padded, f16 floored V while the draft reserve still priced the tensor plan's unpadded one. A hybrid SWA draft head prices 4.5x larger with flash attention off, 3.5 GB at 262,144 tokens on a four layer shape, so the shortfall is an OOM at startup on a total the placement called safe, and a user --fit off, which is one of the states that makes the downgrade resolve attention off in the first place, takes away the re-placement that would have absorbed it. The other captures in that closure settle with the load and are left alone. * Say the ceiling was a guess without spending the memory warning _record_load_warning is first-notice-wins with one slot, and both arms that raise an unmeasured ceiling decide it long before the host-RAM and offload advisories run. Recording the notice there took the slot, so a load that is told it will page from disk heard only that its ceiling was unmeasured, on the one path that also raises the launched context from the fallback to the full request. Held in _unmeasured_ctx_notice and flushed past both advisories, appending when one spoke and recording when none did. Measured on the tensor arm with an unsizeable KV cache and an explicit 262,144: the host advisory survives and the notice follows it, where before only the notice was left. * Admit a GGUF beside training against the reserve, not the plan _estimate_gguf_kv_gb feeds the active-training admission guard, and load_model holds the flash-attention reading down through _reserved_flash_attn_state for the two placements a flash-attention-off respawn cannot be re-placed out of: a user's own --fit off, and a fixed layer count. The route resolved only the plan, so the guard admitted a load against the smaller cache that the same placement then reserves the larger one for, and the respawn could take VRAM the guard never admitted and the training run with it. Measured on a ragged-SWA shape at 32,768 tokens with --fit off: admitted 9,709,813,760 against a reserve of 13,222,543,360. Asked for by keyword rather than applied in _gguf_runtime_bytes, because the panel means the other thing. It shows what the launch uses, and its total is placement-independent -- test_memory_estimate pins that an extras -ngl moves bytes between host and device without changing the total, which a reserve keyed on placement would break. Tensor mode stays exempt on both paths: llama.cpp has no flash-attention-off respawn under SPLIT_MODE_TENSOR to reserve for. --------- Co-authored-by: danielhanchen <[email protected]> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
…tted (unslothai#11207) unslothai#11025, unslothai#10533 and unslothai#11067 each landed today with a blank line the ruff-format-with-kwargs hook removes or adds, so `pre-commit run --all-files` is red on main. Every open PR inherits that: pre-commit.ci evaluates the PR merged with main, finds files to rewrite that the PR never touched, and pushes them onto the PR branch, which is how unrelated files end up in a diff. On a branch too far behind main to apply, it fails outright instead. Output of the repo's own hook, with the pinned ruff 0.6.9. Blank lines only. Co-authored-by: danielhanchen <[email protected]>
Summary
Three context and memory numbers Studio reports were computed for a load other than the one
about to start. This fixes the two causes behind them.
longer published as "the largest that fits". A 256k selection came back as 4,096.
quantization moves the available context instead of being priced away.
GET /api/models/kv-cache-estimatecan be asked about the plan a launch will really run,and resolves it the way the launch does when it is not told.
Root cause
The unmeasurable context (#9653). When a GGUF carries no attention dimensions,
_can_estimate_kv()is False and nothing can price the cache. Two arms fall back to a shortcontext there:
_plan_tensor_parallel(a bare 4096, now named_TP_UNMEASURED_CTX) and theMetal unified-memory arm (
_metal_floor_ctx). Both applied that fallback to an explicitrequest and published it as
max_context_length, so selecting 262,144 produced{"context_length": 4096, "max_context_length": 4096, "native_context_length": 262144}with the context slider then reporting that nothing longer fits, on a model llama.cpp opens
at a useful context when driven directly. The fallback is a guess, which cuts both ways and
is already written down in
_metal_context_overcommit_message: it will not refuse againstthat number, because refusing on a guess blocks loads that work today. Equally, a guess may
not silently overrule a context the user asked for, and may not be published as a measured
ceiling once the load has run above it.
The attention plan (#9697, #10489).
load_modelpinnedplanned_flash_attn = Falseunconditionally, as a pre-emptive reserve for the crash recovery that may relaunch a plan
with flash attention off, and then emitted
--flash-attn onon every launch whose build hasthe flag. The estimator is not indifferent to that state: with flash attention off it floors
the V axis at f16 and pads variable-width V tensors to the model-wide maximum. Measured on
Qwen3's shape at 262,144 tokens:
In tensor mode
--fitis a no-op, so that inflated cache is the only cap and becomes thepublished ceiling: q8_0 was selectable but the available context came out sized as though the
cache were fp16. The same pessimistic ceiling is what the context warning compares against
while the memory panel prices the optimistic one, and
GET /api/models/kv-cache-estimatehadno parameter for any of it, so one model and one cache type produced three different numbers.
Changes
studio/backend/core/inference/llama_cpp.py_planned_flash_attn_stateresolves the flash-attention state a launch will really run at,once, and every sizing call takes it: the build's capability,
LLAMA_ARG_FLASH_ATTN, alast-wins
-fain the extras, and a quantized V cache, which forces it on because llama.cppturns it on itself. An explicit
autois not an answer and is sized as the load that may notget it: llama.cpp decides auto at load time and decides against flash attention whenever the
backend, the model or the cache pair cannot take it, silently, which is a 1.44x KV cache at
q8_0 and 2.28x at q4_0. Unsloth emits
--flash-attn onrather thanauto, so only a user'sextra arguments or an inherited environment variable reach that arm.
_TP_UNMEASURED_CTX, beside the other context floors, for the one arm the_FIT_MIN_CTXparagraph already excluded: with no KV metadata nothing can prove a safe cap.
_plan_tensor_paralleltakesexplicit_ctx(default False, so every existing caller keepsits behaviour). It is read only when the KV cache cannot be sized: the fallback then
honours the request and publishes a ceiling the launch does not contradict. With a real KV
estimate the cap is a measurement and still binds, which is what
--fitbeing a no-op intensor mode requires of it.
Its measured verdicts, including the refusal, are untouched.
_unmeasured_context_notice, recorded onlast_load_warningby both arms, so the load saysonce that the reported maximum is the request rather than a measured ceiling. Auto is not
told anything: it made no request, and it keeps the conservative fallback.
_planned_flash_attn_stateresolves the state a launch will really run at from the build'scapability,
LLAMA_ARG_FLASH_ATTN, a last-wins-fain the extra arguments, and thequantized-V rule llama.cpp applies itself.
load_modeluses it in place of the pin, so oneanswer feeds every sizing call and the argv.
studio/backend/routes/inference.py_gguf_runtime_bytesresolves through the same helper. That also closes a gap its owntwo-step form had: a quantized V forced flash attention on even on a build with no
--flash-attnto emit, where the launch rewrites the V cache to f16 instead and the paddedprice is the right one.
studio/backend/routes/models.pyGET /api/models/kv-cache-estimateacceptsflash_attn,kv_unified,swa_fullandno_mmproj_offload, all optional. An asked-for value is expressed as the extra argument aload would carry and resolved by the same helpers, so the route cannot answer for a launch
that cannot happen. Omitted, they resolve the way the launch resolves them. The same plan is
handed to the planner half of the response, so
kv_bytesandgpu_bytesin one answercannot describe two different loads. The response shape is unchanged.
The pre-emptive flash-attention reserve is not replaced by anything, because two mechanisms
already provide what it was for. Tensor mode cannot take the flash-attention-off recovery at
all (llama.cpp requires flash attention for
SPLIT_MODE_TENSOR, whichtest_tensor_quant_kv_platform_matrix.pyalready pins), and elsewhere the no-flash respawnre-enters
_spawn_and_wait, whose own rung hands placement back to llama.cpp with--fit onwhen a forced
--fit offcrashes at startup, beside the strip of the fit's--load-mode nonethat exists for the same "the footprint changed" reason.
Compatibility
What changes for an input that already succeeded
This change is not confined to the unmeasurable case it was written for, and the
body should not imply that it is. A load that already succeeded can now receive a
different context argument, because the flash-attention state is resolved once and
every KV estimate taken during that load sees the same resolved state, rather than
each estimate assuming its own.
An earlier version of this section claimed that only a build supporting neither
--flash-attnnor--kv-unifiedmoves. That is measurably too narrow, and it iscorrected below, because it is the paragraph a reviewer uses to size the blast
radius. Everything that moves, moves toward what the launch emits.
GET /api/models/kv-cache-estimatewith no plan named, driven in process against aragged-SWA GGUF at 32,768 tokens, merge base versus head:
kv_byteskv_bytesLLAMA_ARG_FLASH_ATTN=off--flash-attnonly--kv-unifiedonlyLLAMA_ARG_SWA_FULL=1So three states that are not "neither flag" move:
--kv-unifiedonly. The flash-attention axis is independent of the unified one,so a build missing only
--flash-attnprices the padded V. This is the correctionthe PR is for; the old boundary simply excluded it.
LLAMA_ARG_SWA_FULL. Now honoured, which zeroes the checkpointshare and grows the live cache. The launch will run
--swa-full, so pricing it isright.
supports_kv_unifiedfails closed, so the cache resolves non-unified where the estimator's own default
was unified. This matches the loader, which emits
--kv-unifiedonly when theprobe says it is supported. Same delta at
ctx_checkpoints0, 8 and unset, so itis the stream layout rather than the checkpoint share. On a ragged-SWA shape the
published figure rises by up to 37.9% at four slots.
On the load path the same thing is true and larger. Driving the real argv
construction, 36-layer 8-KV-head shape, native 262,144, modern build, the only
argv token that ever differs is the
-cvalue:-c-c--fit off, or-ngl N, orLLAMA_ARG_FIT=off, orLLAMA_ARG_N_GPU_LAYERS=N-fa autoin the extras, f16--flash-attn, or Grok, or an explicit--flash-attn offThe two rows that move down are the deliberate part, and they are worth stating
plainly because nothing else in this PR costs a user anything.
_reserved_flash_attn_stateholds the plan at off for the two placements the flash-attention-off respawn cannot be
re-placed out of, a user's own
--fit offand a fixed layer count, and head prices thecompute buffer from that same held-down state. The merge base held only the KV cache down
and priced the compute buffer for the launch, which is a reserve that covers the respawn's
cache but not its mask. Completing it costs 36% of the context on those paths and buys a
respawn that does not OOM with no fitter left to absorb it. The compute buffer is far more
flash-attention-sensitive than the cache the risk table above quotes: 14x on this shape at
q8_0 and 66x at f16, against 1.44x and 1.00x for the cache.
Restricting the change to the unmeasurable case would reinstate the panel/loader
disagreement that #10489 was about, where the panel priced a cache the loader did
not use. The wider scope is intentional and is the point of the PR.
studio/backend/requirements/studio.txt), torch 2.11.0+cu130, Linux x86_64, NVIDIA B200studio/backend/tests, 12 workersunsloth/gemma-4-12b-it-GGUFUD-IQ2_M loaded at 262,144context_length,max_context_length,native_context_lengthGET /api/models/kv-cache-estimatewith no plan namedkv_bytes,gpu_bytes,total_bytesCross-platform staging CI (Linux, Apple Silicon macOS, Windows, with Playwright) is recorded
in the PR comments.
Tests
studio/backend/tests/test_unmeasured_context_ceiling.py(24 tests), the unmeasurablefallback: an explicit request honoured, Auto still floored, a measured cap still binding an
explicit request, the flag defaulting off for existing callers, the notice's wording, and the
Metal arm through the real
load_model(published ceiling, the advisory, Auto untouched, anda measured ceiling still refusing).
studio/backend/tests/test_resolved_flash_attn_plan.py(23 tests), the resolver and thelaunch: the managed default, a build without the flag, every argv spelling of an explicit
off, last-wins, the environment, a quantized V forcing it on, and the one case the route's own
earlier form got wrong. Then through the real
load_model: a tensor plan for a q8_0 cachelands above what a flash-attention-off cache prices, the published ceiling is that same
number, every KV estimate the load takes sees the resolved state, and an explicit off in the
extras is priced off.
studio/backend/tests/test_kv_cache_estimate_attention_plan.py(12 tests), the route: eachknob as an input, resolution when omitted, a quantized V not priced without flash attention,
the checkpoint share under
--swa-full, the parameters all optional, the response key setunchanged, and an unnamed plan not moving the answer for a plain model.
All 59 fail on the merge base and pass here. Commands and logs are in the report beside this
body.
One existing pin was made less brittle rather than worked around:
test_the_no_flash_rung_recomputes_the_memory_recordslicedload_model's source from thefirst mention of
_drop_fit_load_mode_for_no_flash, which is now a comment explaining why aplan may be sized for the launch rather than for that respawn. It now anchors on the
definition, as the sibling pin in the same file already did.
Evidence
Two isolated Studios, installed from the merge base and from this branch into their own
UNSLOTH_STUDIO_HOME, each on its own port with its own login, reading their own HF cachecontaining the
#10489model. Both were driven through the picker, both loadedunsloth/gemma-4-12b-it-GGUFUD-IQ2_M live at 262,144 with a q8_0 KV cache, and both werephotographed on the same three surfaces. Screenshots, composites, GIFs and the machine
readable facts are in the report's media directory.
swa_full=true): merge basekv_bytes3,083,862,016 andgpu_bytes11,450,519,974, unchanged from its default answerbecause it cannot be told; this branch 47,915,728,896 and 56,282,386,854, which is what that
launch reserves.
/v1/modelspayload the report quotes its numbers from: identical on both.What this evidence cannot show: #9653's published context needs an arm where the KV cache
cannot be measured, which is the tensor-parallel planner (two GPUs) or the Metal arm (Apple
Silicon). Neither is reachable on a single-card Linux host, so that half rests on the unit
suites and the macOS CI leg.
The number on screen, before and after
Two isolated Studios, one installed from this PR's merge base and one from the branch, each
built by the PR's own
install.sh --localinto its ownUNSLOTH_STUDIO_HOMEon its ownport with its own login. Both loaded
unsloth/gemma-4-12b-it-GGUFUD-IQ2_M live with aq8_0 KV cache at Auto context, on the same card held at about 20 GiB free so the fit
actually binds. The chat header's context chip is where the ceiling reaches the user:
241 / 234.2kon the merge base,241 / 262.1khere./v1/modelsagrees:context_lengthmax_context_lengthnative_context_lengthThe same 27,904 tokens the merge base could not offer are the f16 V-axis floor it charged a
cache the child allocates at q8_0.
native_context_lengthis identical, which is the control:only the measured ceiling moves.
Two things about the pair itself. The greeting line differs because it rotates at random, not
because of this change. And the free-VRAM row is not decoration: a first attempt held the card
with a topping-up ballast, which reclaimed what the BEFORE side released and left the two
halves measuring 1,572 MiB and 21,316 MiB, so that pair was discarded rather than posted.
Known limitations
priced as on. Only an explicit
autois treated as undecided, because no probe short oflaunching can answer the other case.
bar still abstains when a KV-shaping flag is in the extra arguments rather than pricing it.
Forwarding the extras the panel already holds is a small follow-up, and it is what makes
this visible to a user rather than to a client.
--fitvalve behind it, so a request nothing could check is launched as asked._plan_tensor_parallelkeeps its four-tuple return; the unmeasured verdict is re-derived bythe caller from the same
_can_estimate_kv()it plans on, rather than widening a contracteleven test modules unpack positionally.
Metal seam with a 24 GiB budget, the merge base refuses an explicit 262,144 naming 183,296
as the largest that fits, because it priced the cache without flash attention; head
launches it, since 14.9 GiB of cache at flash attention on plus 4 GiB of weights does fit.
A
--flash-attn offrespawn would want 25.4 GiB of that 24 GiB budget, and the only thingstanding behind it is llama.cpp's own Metal fitter, which head does arm (
--fit onis inthe argv) but whose free-memory report is exactly what the Metal guard exists to distrust.
The same cell on a build with no
--flash-attnstill refuses, so this is not a blanketrelaxation. Not testable off a real Mac.
--fit on, a single pool with no tensor split and nounified-memory budget, still says nothing: the notice is recorded only at the two arms that
publish a guessed ceiling. Unchanged from the merge base, and the fitter is the backstop
there, but the contract "a context nobody could measure is not a ceiling" does not cover it
yet.
load_modelcan still emit--split-mode tensorwith no--flash-attnflag, a pairllama.cpp refuses. The new
_tensor_split_can_launchguard refuses to price it on theroute side only. Unchanged from the merge base.
Fixes #9653
Fixes #9697
Fixes #10489
What the change looks like
Two isolated installs of this repository, merge base
128659085and headae0ef489e,each with its own Studio home and its own password, driven by one Playwright scene
against both. The model is the one #10489 reports,
unsloth/gemma-4-12b-it-GGUFatUD-IQ2_M, priced at its native 262,144 context with aq8_0KV cache and 4 servingslots. The shot is the server's own answer to
GET /api/models/kv-cache-estimatefor the launch plan that will really run.kv_bytesgpu_bytestotal_bytesweights_bytescompute_bytesnative_contextBefore, the route has no parameter for the launch plan, so naming it changes nothing: the
compact sliding-window cache is priced for a load that would open a full-context one, and
the quote is 17.2 GB for a launch that reserves 61.9 GB. After, the named plan is priced,
and the KV cache is what that launch actually takes.
The run also shoots two controls, and both are expected to match. The published context of
a load whose KV cache CAN be measured does not move, and the estimate for an UNNAMED plan
is byte-identical on both sides, which is the point: this adds an answer for a question the
route could not be asked before rather than changing the one it already gave. The third
pair being identical is the control passing, not the scene failing.
The host-pinned projector, and a test that had never run
test_a_host_pinned_projector_is_not_charged_to_the_cardhas not passed once since it wasadded in
d44cb0c9con this branch. It was written calling_call_route(..., no_mmproj_offload = ...), and_call_routeneither takes that argument nor forwards it, soevery run raised
TypeError: _call_route() got an unexpected keyword argument 'no_mmproj_offload'at the call and the route was never exercised. That is fixed here bythreading the four launch knobs the route resolves for itself through the helper. The route
itself is unchanged.
What the product half of
d44cb0c9cfixes is worth stating plainly, because the failingtest hid it.
--no-mmproj-offloadkeeps vision ON and puts the projector in HOST memory.The loader has assumed that since #5825, which measured a context dropping 9,984 to 4,096
from charging those bytes to the card. This route was the last place still itemising
projector_bytesfor that case, and the frontend adds it straight onto its GPU weightssegment (
use-model-memory.ts,weightsBytes + projectorBytes), which is what draws thememory bar and raises the "exceeds memory" warning. So a projector the user had explicitly
pinned off the card was charged against VRAM anyway, and at
_MMPROJ_VRAM_SAFETY(1.4x)rather than even at its file size.
Measured against the real mmproj files on the Hub:
unsloth/gemma-3-27b-it-GGUFmmproj-F16.ggufunsloth/Qwen2.5-VL-7B-Instruct-GGUFmmproj-F16.ggufunsloth/Qwen2.5-VL-7B-Instruct-GGUFmmproj-F32.ggufThe direction is an OVER-estimate, not an under-estimate. Studio refuses, or warns against,
a load that would have fit; it never accepts one that will OOM. On a 16 GB card the
Qwen2.5-VL F32 case is 3.79 GB of phantom VRAM, 24 percent of the card, against memory
nothing on the GPU occupies. Reverting the route's
if _asked_no_mmproj: projector = Nonenow turns the test red on the assertion it was written for, which it could not do before.
The same commit also makes
test_kv_cache_estimate_route.pycollectable on its own. Theshared
loggersstub intest_kv_cache_estimation.pywas a bareModuleType, whichshadows the whole package rather than just its
__init__, sofrom loggers.media_progress import ...inroutes/inference.pydied with "'loggers' is not a package" and this filecould not be imported at all from the repo root (measured on
205771c44). Giving the stuba
__path__, the same fix as #10995, removes the ordering dependence at its source, and thelocal try/except band-aid this branch added to
test_kv_cache_estimate_attention_plan.pyisremoved with it.
tests/conftest.pymasks this today (#11028) but skips itself wheneverimport loggersraises, sotest_the_shared_loggers_stub_is_still_a_packageassertsagainst the stub object rather than the
sys.modulesslot: deleting the__path__lineturns it red in an ordinary run, guard and all.
This is not a product import-order bug. Nothing outside the test suite writes a bare module
into that slot, and all four orderings of
loggers,routes.modelsandroutes.inferenceimport cleanly against the real package.