Repository navigation
Studio: pin GGUF to CPU on virtualised Metal, clamp parallel slots under MTP - #7717
Conversation
…der MTP Two GGUF inference defects found while driving the desktop app end to end. 1. On a virtualised Apple GPU every offloaded layer returns corrupt tokens. On macos-14/15 runners the same model, quant and binary emit an ordered walk through the character set with offload and correct English at gpu_layers=0, while MLX on the same machine stays coherent. _metal_device_is_paravirtual detects the case from MLX's device name, falling back to system_profiler, and load_model pins gpu_layers=0 only there. Physical Apple Silicon never reports "Paravirtual" and keeps full offload. 2. llama.cpp's draft-mtp path serves one sequence, but Studio still asked for the default 4 parallel slots, so concurrent chats against unsloth/Qwen3.5-2B-MTP-GGUF shared tokens across replies. Clamp --parallel to 1 when MTP is selected, both from an explicit --spec-type in extra_args and from the resolved spec flags.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 04240f8443
ℹ️ 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".
| model_identifier or gguf_path, | ||
| ) | ||
| gpu_memory_mode = "manual" | ||
| gpu_layers = 0 |
There was a problem hiding this comment.
Force GPU companions onto CPU as well
On a paravirtual Mac loading a vision GGUF with an mmproj or an MTP model with a separate drafter, setting only the main model's gpu_layers to zero does not eliminate Metal execution. This file's _cmd_has_gpu_companion explicitly records that mmproj and draft models offload independently of --gpu-layers, and _zero_offload_keeps_gpu_visible consequently preserves GPU access for these launches. Those companion kernels can therefore continue using the corrupt paravirtual Metal path; the guard must also force projectors and drafters to CPU or disable them.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed in aaf081f. Neither companion reads --gpu-layers: clip.cpp picks its backend from mmproj_use_gpu, which defaults true, and common_base_params_to_speculative overwrites n_gpu_layers for a separate drafter whose -1 default means auto. Both are now pinned. Scoped --spec-draft-ngl to separate drafters only, since an embedded MTP head has no draft model and that override is skipped, so it already follows the main placement. Both flags are gated on a --help probe like the other optional flags in this file: an older build would reject the unknown argument and refuse to start, which is worse than the corrupt output it prevents.
| gpu_memory_mode = "manual" | ||
| gpu_layers = 0 |
There was a problem hiding this comment.
Strip late offload overrides before forcing CPU
When an Auto-mode request on a paravirtual Mac contains an accepted -ngl, --gpu-layers, or --n-gpu-layers extra argument, the route does not strip it because the request was not originally Manual. This block then emits managed --gpu-layers 0, but the command builder appends extra_args afterward, and llama.cpp applies the later layer flag, re-enabling the corrupt Metal offload. The forced fallback needs to strip or override all layer-offload extras after converting the request to Manual.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
This was the serious one, fixed in aaf081f. Every strip_offload at the route is gated on gpu_memory_mode == "manual" (inference.py:3549, 3637, 5347, and the unconditional one at 5745 sits inside a manual-only block), so an Auto request carries -ngl straight through. --gpu-layers is emitted at llama_cpp.py:8844 and user extras at 9255, after it, and llama.cpp is last-wins. The log said "Forcing gpu_layers=0" while the launch offloaded anyway.
| "virtualised and offloaded layers produce corrupt output.", | ||
| model_identifier or gguf_path, | ||
| ) | ||
| gpu_memory_mode = "manual" |
There was a problem hiding this comment.
Normalize the fallback before duplicate-load comparison
For every ordinary Auto-mode load on a paravirtual Mac, this mutation records the live backend as gpu_memory_mode="manual", while _pending_load_kwargs and subsequent identical API requests retain "auto". Because _already_in_target_state runs before this normalization and requires the modes to match, repeated or concurrently raced identical /load requests miss the fast path and tear down/reload the healthy CPU server. Apply the paravirtual normalization before the duplicate-state check or compare against the normalized effective request.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Reproduced and fixed in aaf081f. The duplicate-load check ran before the guard, so it compared the raw request against the normalized manual/0 the previous launch recorded, missed the fast path on every repeat Auto load, and tore down a healthy CPU server. The guard now settles placement above that check, and normalizes tensor_parallel, tensor_split and n_cpu_moe too so the recorded state and the next identical request agree.
| # llama.cpp's draft-mtp path serves one sequence only. Left at the default of | ||
| # 4 slots, concurrent chats do not merely slow down, they share tokens across | ||
| # replies. Clamped beside the --kv-unified clamp so the KV fit matches. | ||
| if n_parallel > 1 and _extra_args_requests_mtp(extra_args): |
There was a problem hiding this comment.
Clamp only the MTP mode that actually launches
When LLAMA_ARG_SPEC_TYPE=draft-mtp is inherited but Studio is about to emit a non-MTP CLI mode such as speculative_type="ngram" or Auto on a non-MTP model, this call still sees the environment value and reduces the server to one slot. _build_speculative_flags later emits --spec-type ngram-mod or --spec-default, which overrides that environment value, so the launched server is non-MTP yet unnecessarily loses parallel serving; the same stale clamp remains after an explicit MTP launch falls back to --spec-default. Base the clamp on the resolved launch flags, or consult the environment only when Studio will emit no overriding spec flag.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Reproduced and fixed in aaf081f. _extra_args_requests_mtp([], {"LLAMA_ARG_SPEC_TYPE": "draft-mtp"}) is True, and when the user owns --spec-type _build_speculative_flags returns an empty list, so the backstop was judging a launch by the environment rather than by the flags. Both clamps now pass env = {} and the backstop skips user-owned spec types.
| gpu_memory_mode = "manual" | ||
| gpu_layers = 0 |
There was a problem hiding this comment.
Apply the Metal fallback before the training guard
On a paravirtual Mac with an active MLX training run, an Auto-mode non-diffusion GGUF request reaches _guard_chat_load_against_training before this backend-only normalization, so the guard treats the model as GPU-resident and can reject it with a 409 for insufficient free GPU memory. The launch would subsequently force the main GGUF to CPU and qualifies for the guard's existing Manual-GGUF exemption, so the request is refused based on placement that never launches. Normalize the effective placement before the coexistence guard, or make that guard aware of the paravirtual CPU fallback.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not taking this one. It needs a virtualised Mac running concurrent MLX training, and the proposed ordering takes the manual exemption, which skips the guard entirely. On Apple unified memory that can OOM the training run, so the fix is worse than what it addresses.
| if n_parallel > 1 and _extra_args_requests_mtp(extra_args): | ||
| logger.warning( | ||
| "MTP speculative decoding (--spec-type draft-mtp) does not support " | ||
| "%d parallel slots; using 1. Load without MTP to serve chats in " | ||
| "parallel.", | ||
| n_parallel, | ||
| ) | ||
| n_parallel = 1 |
There was a problem hiding this comment.
Size training coexistence with the clamped MTP slot count
When training is active and an MTP GGUF is requested with the default four slots, _guard_chat_load_against_training runs before this clamp and estimates the model's KV and compute footprint using all four slots. It can therefore return a 409 even when the one-slot MTP server that this block actually launches would fit beside training. Apply the same effective-MTP slot resolution in the pre-load guard so its capacity decision matches the command.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct, fixed in aaf081f. load_model clamps MTP to 1 while the guard sized 4, so a load that fits could still be refused with a 409. It now mirrors the clamp the same way it already does for --kv-unified, with env = {} so only an explicit user --spec-type counts this early; a mode that only resolves to MTP later still over-sizes here, which errs toward protecting training.
Review found five real defects in the first version. Four of them meant the fix
looked applied and did nothing.
The pin was defeatable. Only manual mode strips offload flags at the route, so
an Auto request still carries `-ngl 99` into load_model, and user extras are
appended after the managed `--gpu-layers 0` where llama.cpp's last-wins parser
takes them. The log said "Forcing gpu_layers=0" while the launch offloaded
anyway. Offload flags are now stripped when the fallback fires.
The pin also missed everything that does not read --gpu-layers. clip.cpp picks
its backend from mmproj_use_gpu, which defaults true, so a vision encoder kept
running the corrupt path; and common_base_params_to_speculative overwrites
n_gpu_layers for a separate drafter, whose -1 default means auto. Both are now
pinned, gated on a --help probe like the other optional flags here, since an
older build would reject the unknown argument and refuse to start.
Repeat Auto loads tore down a healthy server. The duplicate-load check ran
before the guard, so it compared the raw request against the normalized state
the previous launch recorded, missed the fast path every time, and killed a
working CPU server. The guard now settles placement above that check.
The MTP backstop could clamp launches that are not MTP. When the user owns
--spec-type, _build_speculative_flags returns nothing, and judging that empty
list falls through to LLAMA_ARG_SPEC_TYPE. Measured:
_extra_args_requests_mtp([], {"LLAMA_ARG_SPEC_TYPE": "draft-mtp"}) is True.
Both clamps now pass env = {} and the backstop skips user-owned spec types.
The training guard sized 4 slots while load_model clamped to 1, so a load that
fits could still be refused with a 409. It now mirrors the clamp, as it already
does for --kv-unified.
Rejected one suggestion: applying the fallback before the training guard would
take the manual exemption and skip the guard, which on unified memory can OOM a
concurrent training run.
Also corrected the MTP comment. It claimed draft-mtp serves one sequence and
that concurrent chats share tokens. Upstream keeps MTP state per sequence and
acceptance is gated on target logits, so committed text stays correct. The
clamp is still right, because the model card ships -np 1 and split_equal ubatch
reordering against raw-index nextn reads collapses draft acceptance above one
slot.
Tests: guard 8 -> 15, parallel slots +2, both asserting the negative case so the
fixes cannot over-apply. Full related suite goes 98 -> 100 failures against clean
main, the two additions being the new tests themselves, which fail there for the
same pre-existing pollution that already fails their five untouched
test_training_guard siblings; the file passes 43/43 in isolation.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: c4c4a283b8
ℹ️ About Codex in GitHub
Codex has been enabled to automatically 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 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| if not (gpu_memory_mode == "manual" and gpu_layers == 0): | ||
| if _metal_device_is_paravirtual(): |
There was a problem hiding this comment.
Treat explicit CPU placement as paravirtual too
On a paravirtual Mac, a caller that already requests gpu_memory_mode="manual" with gpu_layers=0 skips this detector entirely, leaving _paravirtual_cpu_forced false. That means the later companion guards do not append --no-mmproj-offload or --spec-draft-ngl 0, so a manual CPU load of a vision model or separate drafter can still run the companion on the corrupt Metal path. Fresh evidence is that the new bypass is keyed on the request already being Manual/0 rather than on whether the host is paravirtual.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Right, fixed in 82a52c8. The guard was keyed on the request, so Manual + 0 layers on the same virtualised Mac left _paravirtual_cpu_forced False and silently dropped both companion pins, and neither companion reads --gpu-layers so nothing else covered them. Manual + 0 is a first-class UI selection (model-config-page.tsx renders the layers input under Manual) and it is exactly what someone seeing corrupt output reaches for. The detector now gates the block; only the placement rewrite is skipped, since for that request there is nothing left to rewrite.
| elif _extra_args_requests_mtp(llama_extra_args, env = {}): | ||
| n_parallel = 1 |
There was a problem hiding this comment.
Size UI-selected MTP loads at one slot
This clamp only catches pass-through --spec-type draft-mtp; the route still passes request.speculative_type only to load_model, not into this guard, so normal UI/default Auto MTP loads with n_parallel > 1 are still estimated at the requested slot count even though load_model later clamps the launched server to one slot. In active-training scenarios that can still reject a load that the actual one-slot MTP server would fit. Fresh evidence is that the new guard inspects only llama_extra_args, while first-class speculative mode is omitted from the guard call.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not taking this one. The guard cannot know a UI-selected mode resolves to MTP: _build_speculative_flags drops it on at least four paths (_mtp_too_small, _mtp_drafter_missing, _auto_mla_embedded_mtp, and a binary whose probe says no MTP), and in each the server launches with all four slots because the backstop clamps only on the resolved spec_flags. Clamping on the requested mode would under-reserve KV whenever those fire, trading a conservative 409 for a training-run OOM. Resolving further needs the GGUF header, the drafter resolution and the model size, none of which the pre-load guard has. The sibling item about mirroring the certain case is already fixed; this residual is deliberate.
| _paravirtual_cpu_forced | ||
| and _extra_args_mtp_draft_path(spec_flags) is not None | ||
| and server_caps.get("supports_spec_draft_ngl") | ||
| ): | ||
| cmd.extend(["--spec-draft-ngl", "0"]) |
There was a problem hiding this comment.
Honor final drafter extras when forcing CPU
For a paravirtual Mac where llama_extra_args owns speculation, for example --spec-type draft-simple --model-draft d.gguf, _build_speculative_flags returns no drafter flags so this condition is false, and those user extras are appended later. A trailing draft-layer alias such as --spec-draft-ngl -1 can also last-win over this managed --spec-draft-ngl 0 because the paravirtual strip only removes main offload flags. Fresh evidence is that the new CPU pin is based only on spec_flags and is emitted before pass-through extras, so supported separate-drafter loads can still offload to the corrupt Metal backend.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Both halves hold, fixed in 82a52c8. A user-owned --spec-type makes _build_speculative_flags return an empty list, so their --model-draft was invisible to the pin's check; it now reads extra_args alongside spec_flags. And the pin was emitted about 200 lines before the pass-through extras, where a trailing -ngld wins. llama.cpp's parse_cli_args keeps seen_args only to warn, and it keys on the literal alias, so --spec-draft-ngl 0 ... -ngld 99 does not even warn, it just takes 99. Stripping cannot cover it either: _SPEC_FLAGS deliberately excludes the drafter knobs. Both companion pins now emit after the extras.
While fixing this I found the capability gate itself was wrong. It probed --spec-draft-ngl or -ngld and then emitted the literal --spec-draft-ngl, which only exists from b8955, so an older build would answer supported and refuse to start on an unknown argument. The -ngld half was dead code too, since the help-block parser records long forms only. The probe now walks --spec-draft-ngl, --gpu-layers-draft and --n-gpu-layers-draft and records which one the build has.
…tras Round two of review, plus a defect I introduced in round one. The guard was keyed on the request, not the hardware. A user picking Manual with 0 layers on the same virtualised Mac never set _paravirtual_cpu_forced, so the mmproj and drafter pins were silently dropped, and neither of those reads --gpu-layers so nothing else covered them. Manual + 0 is a first-class UI selection and exactly what someone with corrupt output reaches for. The detector now gates the block; only the placement rewrite is skipped when there is nothing left to rewrite. Both companion pins were also undoable. --mmproj-offload and -ngld are real positive flags a user can pass, the pass-through extras are appended after the managed flags, and llama.cpp is last-wins. llama.cpp's seen_args only warns and keys on the literal alias, so "--spec-draft-ngl 0 ... -ngld 99" does not even warn, it just takes 99. The strip cannot help: _SPEC_FLAGS deliberately excludes drafter knobs. Both pins now emit after the extras. The drafter pin also reads extra_args alongside spec_flags, since a user-owned --spec-type makes _build_speculative_flags return nothing and their --model-draft was invisible. The capability gate I added in round one was itself broken. It probed '--spec-draft-ngl' or '-ngld' and then emitted the literal --spec-draft-ngl, which only exists from llama.cpp b8955, so an older build would answer "supported" and then refuse to start on a name it does not know -- the exact failure the gate exists to prevent. The '-ngld' half was dead code besides: the help-block parser records long forms only. The probe now walks --spec-draft-ngl, --gpu-layers-draft and --n-gpu-layers-draft and records which one the build has, mirroring spec_draft_n_max_flag. Declared the new tensor_parallel drop site in _ALLOWED_TP_DROP_GUARDS. The allowlist is there so a new drop is conscious rather than silent; this one drops nothing real, since a paravirtual Mac has a single emulated device. Rejected one item: the training guard cannot know a UI-selected mode resolves to MTP, and clamping on the requested mode would under-reserve KV on the four paths where _build_speculative_flags drops MTP, trading a conservative 409 for a training-run OOM. Tests: guard and parallel-slot files 61 passed in isolation, mtp detection 275 passed, tp regression 42 passed. Full related suite is 100 failures, byte identical to the PR-head baseline.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 92e5b177cf
ℹ️ About Codex in GitHub
Codex has been enabled to automatically 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 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| "virtualised and offloaded layers produce corrupt output.", | ||
| model_identifier or gguf_path, | ||
| ) | ||
| gpu_memory_mode = "manual" |
There was a problem hiding this comment.
Normalize paravirtual placement in the route dedupe
On paravirtual Macs this rewrites an Auto GGUF request to the backend's stored manual/0 placement, but the route-level already-loaded check still compares the next raw Auto request against llama_backend.gpu_memory_mode before load_model can take its backend fast path. Fresh evidence is that _request_matches_loaded_settings runs from the route before the active-generation gate, so an identical Apply while a chat is running is treated as a real model swap and can return the active-generation 409 or cancel the chat with force_cancel_active, even though the backend would later no-op. Normalize the route comparison as well.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Checked this again with the active-generation gate in mind, and I still do not think it is reachable.
The 409 / force_cancel_active path is real: the load route calls on_reload_confirmed(cancel=False) past every already_loaded fast return, which raises 409 or cancels in-flight generations. So if a second request could still arrive as auto, the harm would follow. It cannot, because the response echoes the normalized placement and every client adopts it. load_model records gpu_memory_mode="manual" / gpu_layers=0, the GGUF load response and /status both echo those, and loadedGpuMemoryFields() in chat-runtime-store.ts spreads them into the standing preference on every load path and every status poll. shared-composer.tsx says so in a comment: the first load response rewrites the live store. So the next Apply sends manual/0, not auto.
At manual/0 the comparator matches on every branch: manual == manual, 0 == 0, and n_cpu_moe / tensor_split are only compared under gpu_layers >= 0 where both sides are 0/None. The extras branch matches too, because a manual request hits the route strip before the comparator runs, which test_route_normalizes_explicit_extras_before_reload_dedupe already pins. Diffusion GGUFs are exempt anyway, since the comparator skips the placement compare and the store deliberately does not adopt the mode for them.
Adding a second copy of the paravirtual normalization in the route is also the request-vs-hardware duplication that caused the earlier defect on this branch, where the guard was keyed on the request and Manual+0 silently lost both companion pins. Happy to revisit if you can point at a client that re-sends auto after reading a manual/0 response.
| strip_cache = False, | ||
| strip_spec = False, | ||
| strip_template = False, | ||
| strip_split_mode = False, |
There was a problem hiding this comment.
Strip split overrides during the CPU fallback
When an Auto load on a paravirtual Mac carries an allowed pass-through --tensor-split/-ts, this fallback rewrites the request to manual gpu_layers=0 but preserves the split flags here. The later zero-layer cleanup only clears the first-class tensor_split, so the trailing extra still reaches llama-server while the CPU-only path hides GPUs; the surrounding code notes that a per-GPU ratio with zero offload can abort instead of loading on CPU. Strip the split/tensor-split extras when this fallback fires.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed in eff31d2.
You are right that this is not inert, though for a different reason than tensor placement. --tensor-split really is a no-op here: splits is built but never indexed once act_gpu_layers is 0, and parsing only bounds it against llama_max_devices(). --split-mode is the one that bites. llama.cpp builds a buffer-type list for every device in model->devices before any layer is assigned, so n_gpu_layers never reaches that step: the make_gpu_buft_list loop runs at llama-model.cpp:1270 and i_gpu_start/act_gpu_layers are not computed until :1315. So -sm row throws "device does not support split buffers" on everything except SYCL, and -sm tensor throws "LLAMA_SPLIT_MODE_TENSOR not implemented for architecture". Either turns the CPU rescue into a server that will not start, and the zero-offload mask cannot cover it, since it only writes CUDA/HIP visibility vars and this fallback is darwin-only.
I did not take the strip, deliberately. strip_shadowing_flags rewrites extra_args, the duplicate-load comparator compares the stored extras verbatim, and the UI does not round-trip the extras box, so stripping would leave the two permanently unequal and turn every later Apply into a real model swap. Appending --split-mode layer after the user extras gets the same result through last-wins, matching the mmproj and drafter pins already on this branch, and it lands before the env block because _zero_offload_keeps_gpu_visible reads the finished cmd.
16 tests, each with negatives so it cannot over-apply: -ts and --tensor-split return nothing, an existing layer returns nothing, and an AST check pins the call site to the _paravirtual_cpu_forced guard so a real Mac keeps its row/none split.
…lback --split-mode is a GPU placement flag, and the paravirtual fallback has already pinned the load to CPU, but it is not inert at --gpu-layers 0. llama.cpp builds a buffer-type list for every device in model->devices before any layer is assigned (llama-model.cpp: the make_gpu_buft_list loop runs at :1270, the i_gpu_start/act_gpu_layers split is not computed until :1315), so n_gpu_layers never reaches that step. -sm row therefore throws "device <X> does not support split buffers" on every backend except SYCL, and -sm tensor throws "LLAMA_SPLIT_MODE_TENSOR not implemented for architecture" on every arch llm_arch_supports_sm_tensor excludes. Either one turns the CPU rescue into a server that refuses to start. The zero-offload mask cannot save it: it only writes CUDA/HIP visibility vars, so the Metal device stays in the list on the one platform this fallback fires on. Overridden rather than stripped. llama.cpp is last-wins, so appending the default "layer" neutralises the mode without rewriting extra_args. Stripping would: the route's duplicate-load comparator compares the stored extras verbatim and the UI does not round-trip the extras box, so a rewrite would leave the two permanently unequal and turn every later Apply into a real model swap. Emitted after the pass-through extras for the same reason as the mmproj and drafter pins, and before the env block, since _zero_offload_keeps_gpu_visible reads the finished cmd. --tensor-split needs no treatment: splits is built but never indexed once act_gpu_layers is 0, and parsing only bounds it against llama_max_devices(). 16 tests, each with negatives so the override cannot over-apply: -ts/ --tensor-split return nothing, an existing "layer" returns nothing, and an AST check pins the call site's guard to _paravirtual_cpu_forced so a real Mac keeps its row/none split.
… run
Cross-platform staging CI ran the four test files this PR touches in one pytest
session and produced 18 failures on Linux, macOS and Windows alike, all one
error: "module 'httpx' has no attribute 'Response'" out of routes/inference.py.
sys.modules.setdefault("httpx", stub) only checks whether httpx has already been
imported, not whether it is installed, so on a runner that pip-installs the real
httpx the stub still won if this file imported first. Every file importing later
then found a working httpx and kept it, and this stub is a strict subset of the
real module, so anything reaching httpx.Response blew up. test_tp_vision_
regression.py and test_parallel_slots_per_load.py already guard against this by
preferring the real module; this file now does the same, and its fallback stub
carries Response so the deps-absent path is covered too.
Pre-existing, not introduced here: the same 18 failures reproduce at the merge
base from the two untouched files alone. It surfaced now because this PR is the
first change to touch both halves of the pair, so CI selects them together.
Combined run goes from 18 failed / 360 passed to 394 passed. Each file
separately is unchanged: 275, 43, 42 and 34 passed. On an interpreter with no
httpx at all the count is identical to the merge base, so the stub path did not
regress.
|
@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: 7b357e0360
ℹ️ 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".
| cmd[_np_at + 1] = "1" | ||
| # _commit_effective_parallel_slots below reports what launched, | ||
| # so rebind rather than only patching cmd. | ||
| n_parallel = 1 |
There was a problem hiding this comment.
Restore requested slots after the MTP fallback
When a load requests multiple slots and resolves to MTP, this permanently rewrites n_parallel and the command to one slot before startup. If that MTP startup then fails because the drafter or architecture is unsupported, the fallback at fallback_cmd only replaces the speculative flags with --spec-default; it copies the already-patched --parallel 1. The successful non-MTP server therefore loses the requested concurrency, while _requested_n_parallel still records the original ask, so identical reloads deduplicate and never restore it. Fresh evidence in the final tree is that fallback_cmd is derived from cmd after this assignment and never restores the requested slot count.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed in d186963. Good catch, this one was real.
Traced it end to end. --parallel is emitted at llama_cpp.py:8870 and _spec_start is taken at :9110, so the clamped token sits in the cmd[:_spec_start] prefix that fallback_cmd copies verbatim; only the spec slice is replaced. So the --spec-default retry, which is not MTP, came up serving one chat at a time.
The stickiness is as you describe. _requested_n_parallel is set from the pre-clamp snapshot at :9942, and the dedupe at :10425 compares that original ask against the incoming ask, so they match and an identical reload returns already_loaded rather than rebuilding. _requested_spec_mode is deliberately preserved across the fallback, so the spec-mode branch dedupes too.
It is reachable on the ordinary path, not just a corner: the earlier clamp at :7463 fires only on an explicit user --spec-type in extras, and the route passes n_parallel through untouched (the training guard clamps only a local for VRAM sizing). The backstop exists precisely because Auto/MTP is not resolved until _build_speculative_flags runs, which is the path a user picking Auto in the UI takes.
One deliberate narrowing: I restore the clamp-time count rather than the caller original ask, so the fitter own reduction is respected and the KV budget still covers it. Rebound at patch time rather than on healthy, since the mmproj text-only retry and the no-fit retry both derive from fallback_cmd.
6 tests, 4 negative: a single-slot load stays single, a user-owned --spec-type gains nothing, a non-MTP resolution is inert, and an 8-slot ask the fitter already cut to 4 restores 4 and not 8. An AST check pins the restore to the one branch that actually drops MTP, so a successful MTP launch and the flash-attention retry both stay clamped.
The MTP backstop patches cmd's --parallel to 1 in place, and the --spec-default retry slices fallback_cmd out of that already-patched cmd. --parallel is emitted long before _spec_start, so it sits in the untouched prefix and the retry inherits the clamp. That retry is not MTP, so a load that asked for N slots, resolved to MTP, and then failed MTP startup came up on a working non-MTP server that serves one chat at a time. It was also permanent. _requested_n_parallel is set from the pre-clamp snapshot, so the dedupe compares the original ask against the incoming ask, they match, and an identical reload returns already_loaded instead of rebuilding the server. _requested_spec_mode is deliberately preserved across the fallback, so the spec-mode branch dedupes too. Reachable on the ordinary path: the earlier clamp fires only on an explicit user --spec-type in extras, and the route passes n_parallel through untouched (the training guard clamps only a local for VRAM sizing). The backstop exists exactly because Auto/MTP is not resolved until _build_speculative_flags runs. Restores the clamp-time count, not the caller's original ask, so the fit's own reduction is respected and the KV budget still covers it. Rebound at patch time because the mmproj text-only retry and the no---fit retry both derive from fallback_cmd. 6 tests, 4 of them negative: a single-slot load stays single, a user-owned --spec-type gains nothing, a non-MTP resolution is inert, and an 8-slot ask the fitter already cut to 4 restores 4 rather than 8. An AST check pins the restore to the one branch that actually drops MTP, so a successful MTP launch and the flash-attention retry both stay clamped.
|
@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: 378286bcac
ℹ️ 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".
| # past the pass-through extras like the drafter pin, since | ||
| # --mmproj-offload is a real positive flag a user can pass and | ||
| # llama.cpp is last-wins. | ||
| if _paravirtual_cpu_forced and server_caps.get("supports_no_mmproj_offload"): |
There was a problem hiding this comment.
Disable projectors that cannot be pinned to CPU
On a paravirtual Mac using an older/custom llama-server whose probe does not advertise --no-mmproj-offload, this condition simply skips the projector pin while still launching --mmproj; clip therefore retains its default Metal backend and image embeddings can remain corrupt even though the main model is forced to CPU. Fresh evidence after the prior fix is that the final tree gates the pin on supports_no_mmproj_offload without disabling the projector or failing over to text-only when that capability is absent.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in e80ef16. The gap is real, though the cause is not the one described, so worth recording the correction.
The code gap is exactly as you say: only the pin was probe-gated, not the projector, so with the capability absent --mmproj still shipped and clip kept its Metal backend. And clip has no other lever. tools/mtmd never reads n_gpu_layers, mmproj_use_gpu defaults true in common.h, and --device does not reach clip (clip_context_params has no device field, and --device cpu is rejected during parsing). So --no-mmproj-offload really is the only way off the device.
Where the item is wrong is the trigger. An older llama-server cannot reach this code. --no-mmproj-offload landed in 7c727fbe on 2025-04-24, but the base argv always passes --flash-attn on, and that value form only arrives in e81b8e4b on 2025-08-30. A build old enough to lack the first would reject the second and exit before serving anything, and the flash-attention retry rewrites on to off rather than dropping the flag. The window "has --mmproj, accepts --flash-attn on, lacks --no-mmproj-offload" is empty by about four months. The path that does reach it is a failed or timed-out --help probe, which zeroes every capability at once.
Rather than launch a projector that cannot be pinned, it is now dropped up front. I clear launch_mmproj_path rather than just effective_is_vision, since the same value feeds the mmproj VRAM budget and the audio-encoder probe, and a half drop would leave the server advertising an encoder it never launched.
The tradeoff is worth stating: on a virtualised Mac whose probe fails, vision goes away for the session instead of returning corrupt embeddings. That is the direction this change argues for throughout, the warning names both the cause and the fix, and the branch is confined to paravirtual hardware. 6 tests, 3 of them negative so the drop cannot over-apply.
| # --mmproj-offload is a real positive flag a user can pass and | ||
| # llama.cpp is last-wins. | ||
| if _paravirtual_cpu_forced and server_caps.get("supports_no_mmproj_offload"): | ||
| _pv_mmproj_cpu_pin = ["--no-mmproj-offload"] |
There was a problem hiding this comment.
Record CPU-pinned projectors as CPU-only
When this pin is applied successfully, the finished command still contains --mmproj, and _cmd_has_gpu_companion treats any such command as GPU-resident without considering the later --no-mmproj-offload. Consequently _zero_offload_gpu_flag commits _gpu_offload_active=True; the training coexistence code then reports and unloads this otherwise CPU-only vision server when training starts, even though both its main model and projector were explicitly pinned off Metal.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
The narrow fact is right but the chain breaks one step earlier, so I am leaving this alone.
_cmd_has_gpu_companion does return True on any --mmproj and never looks at a later --no-mmproj-offload, which does not match that prefix. Confirmed directly.
But _zero_offload_gpu_flag short-circuits on "if not detected_gpus: return None" before _zero_offload_keeps_gpu_visible is ever consulted, and _get_gpu_memory enumerates only Vulkan, nvidia-smi and torch.cuda (which covers ROCm through the same namespace). Metal is never enumerated, and torch.cuda.is_available() is False on a Mac, so detected_gpus is empty and the flag is None, not True. Changing _cmd_has_gpu_companion would not alter the outcome on the machine this describes.
The unload also is not caused by the projector. training_vram.py tests "is not False", so None behaves exactly like True, and a text-only paravirtual load is unloaded on the same path. The actual reason is can_keep_chat_during_training returning False for any non-CUDA, non-XPU device. On Apple unified memory that is arguably correct anyway, since a CPU-resident llama-server is holding exactly the RAM the training run needs.
Off Mac, reaching this needs a user hand-passing --no-mmproj-offload with Manual and 0 layers on a CUDA or ROCm box, and reporting True there is defensible rather than wrong: the same predicate drives the child GPU visibility mask, so llama.cpp really does allocate a device context and the server is not holding zero VRAM. Mask and bookkeeping stay consistent.
I also checked the drafter for the same blind spot, since that would have been the stronger version of this report. It does not have it: _cmd_has_gpu_companion routes the drafter through _extra_args_draft_offloaded_to_cpu, which honours --spec-draft-ngl 0 with last-wins semantics, and test_cmd_companion_ignores_cpu_forced_drafter already pins that. Making the mmproj side match would have to be last-wins-aware too, since --mmproj-offload and LLAMA_ARG_MMPROJ_OFFLOAD can re-enable it, and getting that wrong would mask devices out from under a genuinely GPU-resident vision server.
…Metal device The projector pin was probe-gated but the projector itself was not: with supports_no_mmproj_offload false, --mmproj still shipped and clip kept its default Metal backend, so the main model ran on CPU while every image was encoded from the corrupt device this fallback exists to avoid. clip has no other lever: tools/mtmd never reads n_gpu_layers, mmproj_use_gpu defaults true, and --device does not reach clip, so --no-mmproj-offload is the only way off. The reachable trigger is a failed or timed-out --help probe, which zeroes every capability, not an old llama-server. A build that lacks --no-mmproj-offload (llama.cpp 7c727fbe, 2025-04-24) cannot start at all here, since the base argv always passes --flash-attn on and that value form only arrives with e81b8e4b, 2025-08-30, four months later. Clears launch_mmproj_path rather than only effective_is_vision, because the same value feeds the mmproj VRAM budget and the audio-encoder probe; a half drop would leave the server advertising an encoder it never launched. Tradeoff: on a virtualised Mac whose probe fails, vision goes away for the session instead of returning corrupt embeddings. The warning names the cause and the fix, and the branch is confined to paravirtual hardware. 6 tests, 3 negative: a pinnable projector survives on the same hardware, a real Mac keeps vision on a build without the flag, and a text-only GGUF is unaffected. The three positives fail with the source change reverted.
|
@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: 69a1cc288d
ℹ️ 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 ( | ||
| _paravirtual_cpu_forced | ||
| and _extra_args_mtp_draft_path([*spec_flags, *(extra_args or [])]) is not None | ||
| and server_caps.get("spec_draft_ngl_flag") |
There was a problem hiding this comment.
Disable speculative drafters that cannot be CPU-pinned
On a paravirtual Mac with an older or custom llama-server whose capability probe returns no spec_draft_ngl_flag, this condition silently skips the CPU pin even when spec_flags or extra_args selects a separate drafter. That drafter retains its independent automatic GPU placement and can execute on the corrupt Metal backend, defeating the fallback and potentially collapsing speculative acceptance and performance. As with the unpinnable projector path, disable the separate drafter/speculation or otherwise prevent this launch when no supported draft-layer flag exists.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 896e3e9. Genuine, with one correction to the severity.
The gap is real and is the projector gap one flag over: the pin was probe-gated but the drafter was not, so with no draft-ngl flag the CPU pin was skipped while --model-draft still shipped. A separate drafter does carry its own placement, as you say. common_base_params_to_speculative overwrites n_gpu_layers with the draft default of -1, and any negative resolves to every layer, so --gpu-layers 0 never reaches it.
The consequence is throughput, not correctness. Draft tokens are only ever compared, never emitted: common_sampler_sample_and_accept_n pushes the target model own draw and breaks at the first mismatch, and the server rolls back the provisional tokens before streaming. So a corrupt drafter has every proposal rejected and costs a wasted forward pass per step; it cannot leak into the output. "Collapsing speculative acceptance and performance" is right, "defeating the fallback" overstates it.
The older-build trigger is impossible here too. llama-server has advertised a draft-ngl flag since d9d54e49 (2024-11-25) and the base argv requires --flash-attn on from e81b8e4b (2025-08-30), so a build old enough to lack the pin exits before serving. The reachable paths are a failed or timed-out --help probe, which zeroes every capability at once, or a custom fork.
The spec group and the inherited LLAMA_ARG_SPEC_* go with the drafter, since a surviving --spec-type would reach a server with no drafter to serve it and --spec-type appends rather than replaces. A drafter the user already pinned themselves is left alone: the probe only decides whether Unsloth can emit the flag, so their pin works either way and dropping it would cost them speed for nothing. 12 tests, 8 negative, each gate clause pinned by mutation.
… device Same gap as the projector, one flag over. The pin was probe-gated but the drafter was not, so with no spec_draft_ngl_flag the CPU pin was skipped while --model-draft still shipped. A separate drafter carries its own placement: common_base_params_to_speculative overwrites n_gpu_layers with the draft default of -1, and any negative resolves to every layer, so --gpu-layers 0 does not reach it and the drafter ran on the corrupt device. Severity is throughput, not correctness. Draft tokens are only ever compared: common_sampler_sample_and_accept_n pushes the target model's own draw and breaks at the first mismatch, and the server rolls back the provisional tokens before streaming. A corrupt drafter therefore has every proposal rejected, costing a wasted forward pass per step, and cannot leak into the output. As with the projector, an old build is not the trigger. llama-server has advertised a draft-ngl flag since d9d54e49 (2024-11-25), and the base argv requires --flash-attn on from e81b8e4b (2025-08-30), so the only reachable paths are a failed or timed-out --help probe or a custom fork. Takes the spec group and the inherited LLAMA_ARG_SPEC_* with it, since a surviving --spec-type would reach a server with no drafter to serve it, and --spec-type appends rather than replaces. A drafter the user already pinned themselves is left alone: the probe only decides whether Unsloth can emit the flag, so their pin works regardless and dropping would cost them speed for nothing. 12 tests, 8 negative. Each gate clause is pinned by mutation: deleting any one of them fails exactly the negative that guards it.
|
pre-commit.ci run |
|
@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: 62c84566c1
ℹ️ 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 gpu_ids and not _paravirtual_cpu_forced: | ||
| effective_pin = gpu_indices if gpu_indices is not None else gpu_ids | ||
| self._gpu_ids = sorted(int(idx) for idx in effective_pin) | ||
| else: |
There was a problem hiding this comment.
Keep the forced-CPU effective pin cleared
When a paravirtual-Mac request includes explicit gpu_ids, this correctly clears self._gpu_ids, but the later final-recording block at lines 10001-10023 runs in the same load and assigns those IDs again because Metal is not Vulkan. The resulting CPU-only server therefore reports an effective GPU pin and clearing that ineffective selection misses matches_gpu_ids, causing an unnecessary reload. Fresh evidence after the prior fix is this second assignment, which overwrites the cleared value before launch.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Right, and my earlier fix was on the wrong site. load_model records the pin twice: the block at :9421 and then the authoritative one at :10001, which takes elif gpu_ids on Metal and re-assigned the value I had just cleared, so nothing changed by launch time.
Cleared at the final recorder too in a10ec08, ahead of the backend branches.
The test was the real miss here: it asserted on one site, so it passed while the later block undid the fix. It now walks every if in load_model that writes self._gpu_ids, runs them in source order under a forced-CPU scope, and fails on whichever one re-pins. Reverting just this second fix makes it fail and name line 10001, so it would have caught the original gap.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: a10ec08814
ℹ️ 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".
| # above makes this retry genuinely non-MTP, so hand those back | ||
| # too, or --parallel 1 sticks and the requested-vs-requested | ||
| # dedupe keeps every later load on the same one-slot server. | ||
| _mtp_clamped_slots = max(_mtp_clamped_slots, _pv_extras_clamped_slots) |
There was a problem hiding this comment.
Rebudget before restoring explicit-MTP slots
When extra_args explicitly selects MTP with more than one slot and MTP startup fails, the earlier extras clamp reduces n_parallel to 1 before the VRAM fit, including the slot-scaled compute-buffer estimate, but this assignment restores the pre-fit count for the non-MTP retry. On a tight placement, the fallback can therefore launch with output/compute buffers for N slots that were never admitted and OOM or spill layers to CPU. Preserve the requested count through the fit or rerun admission before restoring it.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed. The extras clamp at :8006 cuts n_parallel to 1 before the slot fit at :9312, whose gate needs > 1, so the fit was skipped entirely and the count I hand back in the retry was never admitted. The Unsloth-resolved clamp does not have this problem because it runs after the fit, which is why its restore was safe and this one was not.
Fixed in 159fb8a: the fit now sizes against the count the retry could restore and caps it.
_fit_slots = n_parallel if n_parallel > 1 else _pv_extras_clamped_slotsThe cap lands only on _pv_extras_clamped_slots; gpu_indices, use_fit and n_parallel are untouched in that branch, so the MTP launch keeps its single slot and its placement. Test drives the real fit block with a stub that admits 2 of 8 slots and asserts the retry count comes down to 2 while n_parallel stays 1.
| # shared with both duplicate-load comparators. | ||
| _paravirtual_cpu_forced = _metal_device_is_paravirtual() | ||
| if _paravirtual_cpu_forced: | ||
| _pv_placement = paravirtual_normalized_request( |
There was a problem hiding this comment.
Clear diffusion GPU pins when forcing CPU
On a paravirtual Mac, a diffusion GGUF request with explicit gpu_ids is CPU-normalized here without normalizing the device selection. _start_diffusion_server consequently chooses its CPU token because manual_ngl == 0 but still records the supplied ID in _gpu_ids and _requested_gpu_ids; /status reports a GPU the runner does not use, and clearing that ineffective selection misses matches_gpu_ids and reloads the same CPU server. Keep the raw request separately if needed, but clear the effective diffusion pin on this forced-CPU path.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct, and reachable whenever the shim has --ngl: the refusal at :6508 only fires when it does not, so otherwise the runner takes its CPU token while _start_diffusion_server still recorded the pick.
Fixed in 159fb8a. The effective pin is cleared on that path and the raw pick is kept:
_pv_diffusion_cpu = manual_ngl == 0 and _metal_device_is_paravirtual()
self._gpu_ids = [sorted(gpu_ids)[0]] if gpu_ids and not _pv_diffusion_cpu else None
self._requested_gpu_ids = [sorted(gpu_ids)[0]] if gpu_ids else Nonematches_gpu_ids needed the matching half: its diffusion branch compared against _gpu_ids alone, so clearing it would have fixed the clear case and made re-sending the same pick reload instead. It now accepts the raw request too, which is a no-op for a runner that really pinned a device since both fields are equal there.
Covered in both directions, including that a real pin still reloads on a changed pick. test_start_diffusion_server_resets_tensor_parallel pinned the old assignment verbatim, so it now pins the new one with the same intent.
|
@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: 159fb8a4ae
ℹ️ 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".
| use_fit | ||
| and n_parallel > 1 | ||
| and _fit_slots > 1 |
There was a problem hiding this comment.
Refit restored slots even when one slot already fits
For an extras-owned MTP load where the one-slot clamp fits on the initially selected GPU subset but the requested slot count does not, use_fit is already False, so this new _fit_slots branch never calls _slots_that_fit_on_gpu; the startup fallback later restores _pv_extras_clamped_slots unchanged and can still spill or OOM. Fresh evidence after the prior rebudgeting report is that 159fb8a retained the one-slot use_fit gate while only replacing the parallel-count gate; run the restored-count admission independently of that flag and carry its placement into the retry.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct, and checking it turned up a second problem with my own fix: _slots_that_fit_on_gpu searches [1, n_parallel) and never tests the requested count itself, returning (None, True, n_parallel) when nothing below fits. So calling it with the restored count could only ever cap to N-1 or lower, even when N fits. Combined with the use_fit gate you point at, that fix was both incomplete and quietly over-restrictive.
Rather than keep patching the admission, 795c723 reverts the fit block to what it was and gates the restore instead:
if not _detected_gpus:
_mtp_clamped_slots = max(_mtp_clamped_slots, _pv_extras_clamped_slots)The extras clamp runs before any GPU admission, so on a GPU box the count was never budgeted and the honest answer is not to restore it. Off GPU there is nothing to budget and the slots come back, which is the case this PR is about. A GPU launch now keeps the single slot it started with, exactly as it did before I touched this, so there is no OOM path and no regression against main.
Test drives the real strip branch both ways: 4 slots restored with no GPUs detected, none restored with one.
|
@codex review |
1 similar comment
|
@codex review |
|
@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: 72678e378e
ℹ️ 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 is_gguf and _guard_gpu_memory_mode == "manual" and (diffusion_kind is False): | ||
| return |
There was a problem hiding this comment.
Skip GPU budgeting for unclassified forced-CPU GGUFs
On a paravirtual Mac with training active, an uncached remote GGUF whose name does not identify DiffusionGemma has diffusion_kind is None, so this condition does not return even though the normalization immediately above has forced the request to Manual/0. The guard then budgets the full model against GPU memory and can return 409, while the loader will either run an ordinary or supported diffusion model on CPU (or reject an unsupported diffusion shim separately). Fresh evidence after the earlier normalization fix is that the early return still requires diffusion_kind is False, leaving the common unclassified remote path sized as GPU-resident.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed. The early return needs diffusion_kind is False, and the zero-ngl exemption below needs is True, so an unclassified GGUF (None, the common uncached remote case) falls through both and gets budgeted as GPU-resident. The is True there is deliberate, since an ordinary GGUF at ngl 0 can still be held on the GPU by a device pin, tensor mode, mmproj or a GPU drafter, but the forced-CPU pin removes every one of those: --device none, --no-mmproj-offload, and the drafter pinned to CPU.
Fixed in c60e012 with an early return on that path, ahead of the classification checks:
if _pv_guard_forced_cpu:
returnNothing lands on the GPU there, so there is nothing to budget whatever the GGUF turns out to be, and a CPU-only chat load can no longer be 409ed against training it never competes with.
| _fb_tail = strip_shadowing_flags( | ||
| _fb_tail, | ||
| strip_context = False, | ||
| strip_cache = False, | ||
| strip_spec = True, |
There was a problem hiding this comment.
Persist sanitized extras after the startup fallback
When MTP supplied through extra_args fails during startup, this correctly strips the speculative group from the retry command, but extra_args itself remains unchanged and the success path later records that original MTP list in both _extra_args and _requested_extra_args. A subsequent same-model Apply that omits the extras field but changes another setting therefore inherits the failed MTP arguments rather than the sanitized launch state and repeats the crash/fallback cycle. Record the stripped list as the launched extras while retaining the original list only as requested state, as the runtime-crash recovery path already does.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Right. The retry stripped the spec group out of the argv but left extra_args alone, and the success path records that variable as the launched list, so the failed MTP flags became the inheritance source and the next Apply that omitted extras walked straight back into the same crash.
Fixed in c60e012, mirroring the runtime-crash replay: the stripped list is computed alongside the argv strip and swapped in only once the retry comes up healthy, with the original kept as the requested state.
if _fb_stripped_extras is not None:
_pv_suppressed_spec_extra_args = (... else list(extra_args or []))
extra_args = _fb_stripped_extrasGating on the healthy retry matters: a fallback that also fails must not rewrite what was asked for. Test pins the ordering (strip, then swap, then record) and that the original survives as requested state.
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. Another round soon, please! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
* Studio: stop MTP forcing llama-server to a single parallel slot #7717 clamped --parallel to 1 whenever MTP resolved, six days after #7455 raised the default slot count from 1 to 4. Anyone serving an MTP GGUF went from four concurrent slots to one, with a logger.warning as the only signal. Measured on b10310 with Qwen3.5-9B-MTP-GGUF Q4_K_M, 8 concurrent requests: four slots with MTP is 1.97x the batch throughput of one and 1.29x four slots without MTP, so the acceptance collapse the clamp was avoiding no longer outweighs the concurrency it cost. Removes both clamp sites and the two restore paths that existed only to undo them. The --kv-unified and diffusion downgrades stay: those are real limits, and they now carry an allow-slot-clamp marker. A new stdlib-ast lint plus a launch-argv test matrix keep a silent downgrade from coming back. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Tighten the comments in the parallel-slot changes * Catch the annotated spelling of a slot clamp `n_parallel: int = 1` in a function body is an ast.AnnAssign, which the lint never visited, so the exact regression it exists to block could be reintroduced past a green gate. Handle both nodes, with self-test and pytest cases for the annotated form, its allow-slot-clamp opt-out, and a non-literal annotated assignment. * Record llama.cpp#26031 next to the slot decision It reports concurrent MTP garbling on hybrid architectures. It did not reproduce on qwen35 or qwen35moe here, so the slots stay, but a reader weighing this code should find the open report from it. * Re-price the MTP reserve for each slot-fit candidate The reserve is not slot-independent after all: compact SWA scales its window allowance by the slot count under kv_unified, and an MLA target with recurrent KDA layers charges per slot. _base_footprint carried it at the originally requested count, so every reduced candidate was over-charged and one that really fits could be rejected, leaving the load on --fit with layers offloaded to host. _slots_that_fit_on_gpu now takes mtp_bytes_for_slots and re-prices the reserve alongside the KV and compute buffer; the base footprint drops it. Passing None keeps the non-MTP path byte-identical. Also catch a clamp spelled as an expression: min(n_parallel, 1) and a conditional with a literal 1 branch both pinned the count past a green gate. A real bound like min(n, cap) and a conditional between two live counts stay clean. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Price the MTP reserve at the candidate micro-batch, and close two lint gaps The slot re-pricing added last commit only overrode the slot count. A reduced candidate also lowers the batch floor, so its micro-batch shrinks, and compact SWA adds one micro-batch to its window allowance. The reserve kept the ubatch captured for the original request, so it was still over-priced. The callback now takes (slots, ubatch) and the fit passes the candidate pair. The lint missed two shapes it should have caught from the start. Tuple targets were only tested at the outer ast.Tuple, so `gpu_indices, use_fit, n_parallel = gi, False, 1` -- the very style load_model uses for the VRAM fit -- passed a green gate. Targets are flattened and paired positionally with a tuple value now; an unpairable right-hand side says nothing and is still skipped. And the route resolves the request into `_n_parallel` before the load paths see it, so that alias counts as a slot variable too. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Track the server-wide slot alias in the clamp lint A request that names no count resolves to llama_parallel_slots, so a clamp on that name reduces the same user-facing slots the rule exists to protect. The existing bindings are keyword arguments rather than assignments, so the tree stays clean; self-test and pytest cover both the clamp and the handoff. * Tighten the comments added after the opening pass --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Two GGUF inference defects found while installing the desktop bundles on clean Windows, macOS and Linux runners and driving the app the way a user would.
1. Gibberish on virtualised Apple GPUs
Chat against a GGUF on a virtualised Mac comes back as garbage. Same model, same quant, same llama.cpp binary, one machine:
An ordered walk through the character set is a broken kernel, not a model behaving badly, and MLX on the very same machine is perfectly coherent. That clears the model, the tokenizer and the API layer and leaves the Metal offload path.
The machines that do this report themselves as
Apple Paravirtual device: GitHub's macos-14 and macos-15 runners, and the same applies to Parallels, UTM and hosted Mac providers._metal_device_is_paravirtual()reads the Metal device name from MLX, falls back tosystem_profiler SPDisplaysDataTypewhen MLX is not installed, andload_modelpinsgpu_layers = 0only when that string appears.Physical Apple Silicon never reports
Paravirtual, so a real Mac keeps full GPU offload. That discrimination is the part worth guarding, so it is pinned by tests:Apple Paravirtual devicefalls back,Apple M1/M3 Max/M4 Prodo not, non-darwin short circuits without probing, and a probe that raises leaves offload alone rather than guessing.Result on macos-14 and macos-15, before and after in the same job:
Making the pin actually stick
The first version of the pin was defeatable in three ways, all found in review and all fixed:
strip_offloadat the route is gated ongpu_memory_mode == "manual", so an Auto request carries-ngl 99straight intoload_model.--gpu-layersis emitted before user extras, and llama.cpp's parser is last-wins, so the log saidForcing gpu_layers=0while the launch offloaded anyway. Offload flags are now stripped when the fallback fires.clip.cpppicks its backend frommmproj_use_gpu, which defaults true and never reads--gpu-layers, so every image was still encoded on the corrupt path. Now--no-mmproj-offload.common_base_params_to_speculativeoverwritesn_gpu_layerswith the drafter's own value, whose-1default means auto. Now--spec-draft-ngl 0, scoped to separate drafters only: an embedded MTP head has no draft model, that override is skipped, and it already follows the main placement.Both new flags are gated on a
--helpcapability probe, like the other optional flags in this file. An older build would reject an unknown argument and refuse to start, which is a worse outcome than the corrupt output being prevented.And not tearing down a healthy server
The duplicate-load fast path ran before the guard, so it compared the raw request against the normalized
manual/0that the previous launch had recorded. On a paravirtual Mac that missed on every repeat Auto/loadand killed a working CPU server. The guard now settles placement above that check, and normalizestensor_parallel,tensor_splitandn_cpu_moetoo so the recorded state and the next identical request agree.2. Concurrent chats corrupt each other under MTP
unsloth/Qwen3.5-2B-MTP-GGUFsays it on its card: it ships-np 1, and-np > 1is not supported with MTP. Studio was still passing the default of 4 parallel slots.To be accurate about why, since the first version of this PR got the reason wrong: llama.cpp does keep MTP state per sequence, and acceptance is gated on target logits, so committed text stays correct. What breaks above one slot is the draft. Unequal per-slot token counts make
split_equalreorder the ubatch while the nextn hidden states are still read by raw token index, so slots read each other's rows, acceptance collapses, and MTP ends up slower than no speculation at all.--parallelis clamped to 1 when MTP is in play, in two places, because there are two ways to get there:--kv-unifiedclamp, which catches an explicit--spec-type draft-mtpinextra_args, ahead of the KV estimates so the fit matches what launches_build_speculative_flags, the first point at whichspeculative_type="auto"resolves to MTPBoth pass
env = {}deliberately._extra_args_requests_mtpfalls back toLLAMA_ARG_SPEC_TYPEwhen it sees no flag, and when the user owns--spec-typethe builder returns an empty list, so the backstop was judging a launch by the environment rather than by the flags. Measured:_extra_args_requests_mtp([], {"LLAMA_ARG_SPEC_TYPE": "draft-mtp"})isTrue. A launch that was demonstrablyngram-modcould be clamped to one slot.The chat-vs-training guard also sized 4 slots while
load_modelclamped to 1, so a load that fits could be refused with a 409. It now mirrors the clamp, as it already does for--kv-unified.Testing
studio/backend/tests/test_metal_paravirtual_guard.py, 8 to 15 testsstudio/backend/tests/test_parallel_slots_per_load.py, 2 addedtest_training_guard_*siblings on clean main; the file passes 43/43 in isolationunsloth/Qwen3.5-2B-MTP-GGUF