Repository navigation
Studio: never start llama-server at native context on Metal - #8709
Conversation
llama.cpp reads "-c 0" as fit_params_min_ctx = UINT32_MAX, which pins the model's full native context and disables the reduction --fit would otherwise do. load_model already knows this and says so in a comment. On Apple Silicon no GPU is enumerated, so the Apple unified-memory cap is the only thing holding the context down, and two paths reach the command builder with a zero context after that cap has been skipped or discarded. The cap is guarded on effective_ctx > 0, so a GGUF whose metadata carries no context length is never capped at all. The `except Exception` around GPU selection restores the original request, which is 0 when context is on Auto. That throws away a context the cap had already computed, and the handler logs "using --fit on" while emitting the one argument that turns --fit off. Either way llama-server starts at the model's native length on unified memory and dies in KV or compute allocation, which is the over-commit #5118 and #6529 describe. _metal_zero_ctx_floor returns the context to start at instead, the same 4096 the cap itself falls back to when it cannot estimate KV, or the model's own length when that is shorter. It is a separate helper rather than an inline condition because the existing coverage in this area is source-string inspection, and a decision worth making is worth testing directly. Left alone: Auto-layers, which omits -c entirely and lets --fit size the context, and manual offload, where the user owns memory management including the cap. Inert off Apple Silicon, since the budget is 0 there. The floor sits above the base cmd list rather than between it and the -c emission. test_llama_cpp_no_context_shift pins those two as adjacent, and it was right to complain when the first version of this separated them. Tests: 21 new. 125 in the three suites that own this behaviour, 2257 across the llama.cpp, memory-mode, context-fit, placement and vram suites. The five video failures are present on main unchanged.
|
Codex Review: Didn't find any major issues. Keep them coming! 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". |
|
I verified this against This PR bounds the context in those two failure paths. Differential testing showed that non-Apple loads, manual offload, Auto-layers, and explicit positive contexts are unchanged. The relevant test suites pass, and I found no reachable regression. This fixes a real bug and is safe to merge. I recommend merging it. |
User extras are appended after Studio's own -c, and llama.cpp is last-wins
("only last value will be used"), so a pass-through "-c 0" outlived both the
new floor and the existing Apple cap and re-pinned the model's native length.
Verified against llama.cpp common/arg.cpp: the -c handler sets
fit_params_min_ctx = UINT32_MAX on value 0, which disables the context
reduction --fit would otherwise do, so "-c 0" is strictly worse than passing
no -c at all when memory is tight.
Drop a zero context override from the extras on Metal. Only zero: a positive
-c stays honored exactly as before. This matches a decision load_model
already makes, since explicit_ctx is requested_ctx > 0, so "-c 0" never
counted as an honored override and the cap already ran for it; the trailing
copy in the extras was silently undoing the cap's answer. Whatever context
Studio computed is what survives, so a model whose native length is 2048
still launches at 2048 rather than a flat floor.
Inert off Apple Silicon and on manual memory management, same scope as the
floor. Also corrects the floor docstring: the cited reports surface as
llama-server's "Compute error." at decode, not a start-time allocation death.
Tests: argv-level coverage driving the real load_model for the floor path,
the capped path, both -c spellings, a positive override, and the off-Metal
no-op, plus unit tests for the new strip helper.
On the exception path max_available_ctx outlives the reset that discards effective_ctx, so the cap's KV-based answer can already be below 4096. The floor ignored it and floored back up, which re-created a smaller version of the same over-commit and then advertised 4096 as the ceiling through max_context_length, /v1/models and the frontend context slider. Take the ceiling into account when it exists. The no-metadata path never ran the cap and has none, so it still floors to 4096 as before.
Two problems with the zero-context strip, both flagged in review and both
reproduced before touching anything.
The strip rewrote what the user is recorded as having asked for.
extra_args was overwritten in place, and the commit block stores both
_extra_args and _requested_extra_args from it. _requested_extra_args is
the comparator side that a later Apply is matched against, so an
unchanged request compared unequal to itself:
user asked for : ['--threads', '8', '-c', '0', '--mlock']
stored as requested : ['--threads', '8', '--mlock']
next identical Apply: ['--threads', '8', '-c', '0', '--mlock']
comparator equal? : False
which reloads the model on every Apply. A pre-strip copy is now kept for
the requested side; the stripped list is still what launches and what is
stored as effective.
The advertised ceiling outlived the cap that never ran. On the exception
path max_available_ctx still holds the native length its initialiser put
there, and nothing established that the length fits, but max() kept it:
exception path: cap never ran floor=4096 published=262144
cap ran, KV ceiling 3000 floor=3000 published=3000
so the server ran at 4096 while max_context_length told the UI 262144 was
the largest that fits, and its warning threshold came from the same
number. The floor is already bounded by any real ceiling the cap did
compute, so the ceiling is now replaced by the floor rather than maxed
with it.
Worth recording: the first probe for the second problem was misleading.
_apple_metal_memory_budget_bytes returns 0 off Apple Silicon, so the floor
came back 0 on this Linux box and the mismatch looked different from what
it is. Re-run with the budget stubbed, the numbers above are the real
ones.
Tests: 8 new. 35 in the Metal context suite, 1816 across the llama.cpp,
memory-mode, context-fit and placement suites. The four video failures are
in the origin/main baseline.
Auto-layers (manual memory mode with a negative layer count) is the one mode where the context is decided entirely by --fit: the managed command omits -c on purpose so llama-server can size it. User extras are appended after that and llama.cpp is last-wins, so a pass-through -c 0 survives and sets fit_params_min_ctx = UINT32_MAX, which is exactly the flag that stops --fit reducing the context. On Metal that pins the native length and re-creates the allocation failure this branch exists to prevent. Drop the zero override there as well. A fixed manual layer count still keeps it, since there the user owns the budget, and everything off Apple Silicon is unchanged. Also replaces the source-string assertion on the pre-strip extras copy with a behavioural one: it read the exact formatting of an assignment and broke when the formatter joined it onto one line.
On a virtualised Apple GPU the CPU pin rewrites every placement, a plain Auto one included, to manual with 0 layers, in the locals and in the intent, and it does so above the two Metal context guards. Both guards read gpu_memory_mode there, so the default Auto request on a virtualised Mac looked like a caller-owned manual configuration: the floor stayed inert and a pass-through -c 0 was kept, which is the native-context over-commit this branch exists to prevent. Off that hardware the same request emits -c 4096. Read the ownership question once, before the pin, and pass it to both guards. A manual mode with a fixed layer count is still the caller's, on a virtualised device as anywhere else. Also fixes the comparator on that path. The drafter drop snapshots the extras for the duplicate-load comparison, and that snapshot is taken after the zero-context strip and was preferred over the pre-strip copy, so an identical repeat Apply compared unequal and reloaded the model every time. Prefer the pre-strip copy; the snapshot is only ever set alongside it, and the spec strip it guards runs later still.
…ilopen # Conflicts: # studio/backend/core/inference/llama_cpp.py
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 11b185afdf
ℹ️ 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".
| # Read here, before the pin below rewrites every placement (a plain Auto | ||
| # one included) to manual/0 in both the locals and the intent. Whether the | ||
| # user owns the memory budget is a property of what was asked for, and the | ||
| # two Metal context guards further down skip themselves on it. | ||
| _caller_owns_budget = gpu_memory_mode == "manual" and gpu_layers >= 0 |
There was a problem hiding this comment.
Recognize pass-through fixed-layer placement as caller-owned
On Apple Silicon, an Auto-mode request can still explicitly own placement through a pass-through -ngl/--gpu-layers flag, which is allowed and appended last, but this predicate considers only the first-class mode and layer fields. For example, gpu_memory_mode="auto" with extra_args=["-ngl", "0", "-c", "0"] launches with the caller's fixed zero-layer placement while the new guards remove the caller's context choice and force 4096; account for the effective last-wins layer override when deciding whether the caller owns the budget, just as the manual first-class form is exempted.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not taking this one. The behaviour is real, I checked it: gpu_memory_mode="auto" with extras ["-ngl", "0", "-c", "0"] launches with -ngl 0 preserved and the context at 4096. That is the intended outcome rather than a defect, for three reasons.
-c 0 is not a context choice. llama.cpp's own -c handler sets fit_params_min_ctx = UINT32_MAX on value 0, which is the single argument that disables the reduction, and it is the direct cause of #5118/#6529. A caller who wants a particular context passes -c <n>, which is still honored last-wins: ["-c", "8192"] comes out as 8192.
-ngl 0 does not remove the over-commit, it moves it. With no layers offloaded the KV cache for the full native context is allocated in system RAM, and on Apple Silicon that is the same unified pool the cap exists to protect. Exempting this combination would reinstate the exact failure on the exact hardware.
_caller_owns_budget is deliberately about the memory-budget setting Studio owns and the UI exposes, a manual mode with a fixed layer count, not about layer placement. The paravirtual item in this same round is the argument against inferring it from anything else: reading ownership off a placement rather than off the request is what produced that bug.
llama.cpp resolves LLAMA_ARG_CTX_SIZE through the same handler as -c, in a loop that runs before argv is parsed, so a 0 there sets fit_params_min_ctx = UINT32_MAX exactly as the flag does. Everywhere Studio emits a -c the command line wins and the variable is harmless, but Auto-layers deliberately emits none so --fit can size the context, and there an inherited zero cancels the fit the mode is entirely sized by. Drop it in that case, in the same shape as the LLAMA_ARG_THREADS scrub alongside it. Only a zero, and only under the conditions that already drop a pass-through zero, so a positive inherited context stays the legitimate way to size an Auto-layers launch and nothing changes off Apple Silicon or on a caller-owned budget.
|
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". |
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 068030b536
ℹ️ 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 effective_ctx > 0 or auto_fit or caller_owns_budget: | ||
| return 0 |
There was a problem hiding this comment.
Check effective fit before exempting auto-layer launches
When Manual + Auto layers is combined with a pass-through --fit off (optionally alongside the -c 0 this change strips), auto_fit is still true, so this guard returns without supplying a safe context. The command builder then omits -c, while the user extras are appended after Studio's --fit on and disable fitting last-wins, causing llama.cpp to select the native context and recreating the Metal overcommit this guard is intended to prevent. Base this exemption on the effective fit state after extras, or emit the context floor when fitting is disabled.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct, and it reproduced. Auto-layers on Metal with extras ["--fit", "off"] emitted --fit on ... --fit off and no -c at all: the exemption assumes the context will be sized by a fitter the extras had just disabled last-wins, so llama.cpp falls back to the model's native context. Same with ["--fit", "off", "-c", "0"].
Fixed in 0b168f9 by gating the exemption on the effective fit state, as suggested: the floor now receives auto_fit and fit_is_effectively_on(extra_args), reusing the helper already in llama_server_args.py rather than adding a second definition of what turns the fitter off. Extras alone are the right input here because Studio's own --fit on already beats an inherited LLAMA_ARG_FIT, argv being parsed after the environment.
After the change: --fit off gives ['4096'], --fit off -c 0 gives ['4096'], an explicit --fit on keeps the exemption at [], a caller-owned fixed layer count stays ['0'], and off Apple Silicon it is still []. Regression tests added for all five.
…8825) * Studio: hold the Auto-layers context exemption only while --fit runs Follow-up to #8709. Auto-layers earns its exemption from the Metal context floor by leaving the context to --fit, so the exemption is only sound while --fit is actually going to run. User extras land after Studio's own --fit on and llama.cpp is last-wins, so a pass-through --fit off produced a command carrying neither a -c nor a fitter, which is llama.cpp's native context and the same over-commit the floor exists to prevent (#5118, #6529). Gate the exemption on fit_is_effectively_on over the extras, reusing the helper in llama_server_args.py rather than adding a second definition of what turns the fitter off. Extras alone are the right input because Studio's own --fit on already beats an inherited LLAMA_ARG_FIT, argv being parsed after the environment. Driving load_model on Metal in Auto-layers, before and after: --fit off [] -> ['4096'] --fit off -c 0 [] -> ['4096'] --fit on [] -> [] no extras [] -> [] --fit off, non-Apple [] -> [] A caller-owned fixed layer count is untouched. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
What happens today
llama.cpp reads
-c 0asfit_params_min_ctx = UINT32_MAX, which pins the model's full native context and disables the reduction--fitwould otherwise do.load_modelalready knows this and says so in a comment above the emission.On Apple Silicon no GPU is enumerated, so the Apple unified-memory cap is the only thing holding the context down. Two paths reach the command builder with a zero context after that cap has been skipped or thrown away:
effective_ctx > 0, so this model is never capped at all.except Exceptionaround GPU selection. It restores the original request, which is0when context is on Auto:That discards a context the cap had already computed, and the message says "using
--fit on" while the code goes on to emit the one argument that turns--fitoff.Either way llama-server starts at the model's native length on unified memory and dies during KV or compute allocation. That is the over-commit #5118 and #6529 describe.
-c 4096-c 4096-c 0-c 4096-c 0-c 4096-c 0-c 0What this changes
_metal_zero_ctx_floorreturns the context to start at instead: the same 4096 the cap itself falls back to when it cannot estimate KV, or the model's own length when that is shorter.It is a separate helper rather than an inline condition because the existing coverage in this area is source-string inspection, and a decision worth making is worth testing directly.
Deliberately left alone:
-centirely and lets--fitsize the context. That is already correct._apple_metal_memory_budget_bytesreturns 0 there, so the helper returns 0 before doing anything.On placement
The floor sits above the base
cmdlist rather than between it and the-cemission.test_llama_cpp_no_context_shiftpins those two as adjacent, and it correctly failed when the first version of this change separated them. Worth mentioning because that test earned its keep.Tests
21 new, in
test_metal_never_starts_at_native_context.py: both zero-context paths floored, a model shorter than the floor keeping its own length, a positive context untouched, Auto-layers and manual offload untouched, and a parametrised sweep asserting nothing changes with no Metal budget.125 pass in the three suites that own this behaviour, 2257 across the llama.cpp, memory-mode, context-fit, placement and vram suites. Five failures in
test_video_backend.pyandtest_video_prequant.pyare present onmainunchanged.Relationship to #8706
Independent but adjacent: #8706 makes the Metal budget reflect free memory, this one makes sure the budget is applied at all. Either can land first.