Repository navigation
fix(studio): expose custom llama-server args in model config (#7022) - #7386
Souravrajvi0 wants to merge 21 commits into
Conversation
Add a per-model "Custom llama-server Args" field to the GGUF advanced settings panel and forward the parsed tokens through /load as llama_extra_args. This lets Studio UI users pass flags like --cpu-moe and --no-mmap without falling back to the CLI. Fixes unslothai#7022
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 0bf4d7e21f
ℹ️ 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 (!args?.length) { | ||
| return undefined; |
There was a problem hiding this comment.
Send an empty list when users clear args
When the user removes custom args and reloads the same GGUF model, this helper omits llama_extra_args; the backend treats None/omission as "inherit" and preserves the previous args across /unload + /load (studio/backend/routes/inference.py:3291, studio/backend/core/inference/llama_cpp.py:2080). That means a cleared field can keep launching with stale flags such as --cpu-moe, --no-mmap, or --ctx-size until the backend is restarted; the clear path needs to send an explicit [] rather than undefined.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 0f1a5d9. At 0bf4d7e llamaExtraArgsForLoad returned undefined for an empty list, so clearing the field read as inherit on the backend; it now keys on args == null, and normalizeLlamaExtraArgs no longer collapses [] to undefined. Measured on the real module: clearing the field went from undefined to []. Pinned by tests/studio/test_llama_extra_args_roundtrip.py::test_clearing_the_field_sends_an_explicit_empty_list.
| const effectiveLlamaExtraArgs = llamaExtraArgsForLoad( | ||
| ownConfig.llamaExtraArgs ?? compareLoadKnobs.llamaExtraArgs ?? undefined, | ||
| ); |
There was a problem hiding this comment.
Do not reuse active args in compare loads
In generalized compare, an unremembered GGUF pane gets resolveInitialConfig defaults, but this falls back to compareLoadKnobs.llamaExtraArgs captured from the active model. Since these args are per-model launch overrides, comparing another model while the active one has flags like --cpu-moe or --ctx-size will pass those flags to the other model too, skewing the comparison or making the second load fail; only that pane's own saved/configured args should be sent.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 0f1a5d9. The fallback was ownConfig.llamaExtraArgs ?? compareLoadKnobs.llamaExtraArgs ?? undefined; it is now ownConfig.llamaExtraArgs alone, so a compare pane never inherits the active model's per-model launch flags.
| gpu_layers: effectiveGpuLayers, | ||
| n_cpu_moe: effectiveNCpuMoe, | ||
| gpu_ids: effectiveGpuIds ?? undefined, | ||
| llama_extra_args: effectiveLlamaExtraArgs, |
There was a problem hiding this comment.
Seed runtime state after autoloading args
This autoload path now sends saved llama_extra_args, but the GGUF setState below only writes the GPU/spec/template fields and never seeds llamaExtraArgs or loadedLlamaExtraArgs like the primary load path does. After startup autoloads a remembered GGUF with custom args, the active settings pane and dirty tracking believe no args are loaded, so later saving/reloading can silently drop or omit the flags that are actually running.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 0f1a5d9. The GGUF autoload setState now seeds llamaExtraArgs and loadedLlamaExtraArgs from the config it loaded with, so dirty tracking and the settings pane agree with what the server is actually running.
| n_cpu_moe: loadNCpuMoe, | ||
| tensor_split: loadSplitRatio ?? undefined, | ||
| gpu_ids: loadSelectedGpuIds ?? undefined, | ||
| llama_extra_args: llamaExtraArgsForLoad(loadLlamaExtraArgs ?? undefined), |
There was a problem hiding this comment.
Validate custom args before unloading
For GGUF loads with custom args, the preflight validateModel call still omits llama_extra_args, but the actual /load at this line sends them after the current model has been unloaded. If a user enters a denied flag such as --model/--port, or an allowed memory-affecting flag makes the training guard reject, validation passes, Studio unloads the working model, and only then /load returns 400/409; the same args need to be included in validation before unload.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 0f1a5d9. The preflight validateModel payload now carries validateLlamaExtraArgs, the same list the post-unload /load sends, so a denied flag or a rejecting training guard fails before the working model is unloaded.
| n_cpu_moe: effectiveNCpuMoe, | ||
| tensor_split: compareLoadKnobs.splitRatio ?? undefined, | ||
| gpu_ids: effectiveSelectedGpuIds ?? undefined, | ||
| llama_extra_args: effectiveLlamaExtraArgs, |
There was a problem hiding this comment.
Record pane-specific args after compare load
After a compare pane loads with effectiveLlamaExtraArgs, the setState below never assigns llamaExtraArgs or loadedLlamaExtraArgs (loadedGpuMemoryFields does not carry them). When the compared model has remembered/custom args different from the active model, the UI state after load still shows the old or null args, so saving or reloading from the settings pane can drop the flags or reload with the wrong ones.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 0f1a5d9. The post-compare-load setState now assigns llamaExtraArgs and loadedLlamaExtraArgs from ownConfig, so the pane's own flags become the baseline instead of the previously active model's.
| llama_extra_args: llamaExtraArgsForLoad( | ||
| stateBeforeUnload.loadedLlamaExtraArgs ?? undefined, | ||
| ), |
There was a problem hiding this comment.
Restore args in rollback state
When a switch away from a GGUF model with custom args fails, this rollback request correctly reloads the previous server with loadedLlamaExtraArgs, but the rollback setState that follows never restores llamaExtraArgs/loadedLlamaExtraArgs. The backend is then running with the old flags while the settings UI believes none are loaded, so the next save or reload can silently lose or fail to clear them.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 0f1a5d9. The rollback setState now restores llamaExtraArgs and loadedLlamaExtraArgs from stateBeforeUnload.loadedLlamaExtraArgs, matching the rollback request that reloads the previous server with them.
| return ""; | ||
| } | ||
| return args | ||
| .map((token) => (/\s/.test(token) ? `"${token}"` : token)) |
There was a problem hiding this comment.
Preserve quoted tokens when formatting args
When a saved/runtime token contains both whitespace and quotes, such as a JSON-valued flag entered as --chat-template-kwargs '{"date_string": "July 24"}', this formatter renders the token with unescaped double quotes. If the user later focuses and blurs the field, the parser treats those embedded quotes as delimiters and mangles the value into different tokens, so a reload sends different llama-server args than the saved config.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 0f1a5d9. Measured on the real module at 0bf4d7e: a blur round-trip turned {"date_string": "July 24"} into the two tokens {date_string: July and 24}. The formatter now escapes backslashes and quotes inside the quoted form, and format -> parse is a fixed point. Pinned by tests/studio/test_llama_extra_args_roundtrip.py::test_blur_round_trip_is_stable_for_quoted_values.
- Use text-ui-11 instead of raw text-[11px] (font-scale contract) - Send [] to clear inherited args; omit only when unset - Seed/compare/rollback runtime llamaExtraArgs state consistently - Do not inherit active-model args in compare panes - Validate denied llama_extra_args on /validate before unload - Escape quoted tokens when formatting the args field
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 7c7538bb73
ℹ️ 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 config.is_gguf and request.llama_extra_args is not None: | ||
| from core.inference.llama_server_args import validate_extra_args | ||
| try: | ||
| validate_extra_args(request.llama_extra_args) |
There was a problem hiding this comment.
Pass validated extras into training preflight
Fresh evidence: the validate endpoint now receives and checks request.llama_extra_args, but it discards the returned list; the later training guard still calls _resolve_inherited_extra_args(..., None), which returns None whenever the request explicitly supplied extras. With training active, allowed sizing flags such as --ctx-size 131072 can therefore pass /validate using the smaller max_seq_length, then the follow-up /load sees the real extras and rejects after the frontend has already unloaded the current model.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in c448501: /validate now calls _resolve_inherited_extra_args(request, config, model_identifier, request.llama_extra_args). Measured with the real resolver on a request carrying --ctx-size 131072: passing None returned None (guard sizes from max_seq_length), passing the request's list returned ['--ctx-size', '131072']. The preflight and the follow-up load now guard on the same extras.
| if (!/\s/.test(token)) { | ||
| return token; |
There was a problem hiding this comment.
Quote tokens that contain quotes
When a stored token contains quote characters but no whitespace, this returns it unquoted, so a value like {"date_string":"July"} is rendered back into the input as raw shell text. If the user focuses and blurs the field, the parser treats those quotes as syntax and stores {date_string:July} instead, silently changing the llama-server arguments on the next reload.
Useful? React with 👍 / 👎.
| if (ch === "\\" && i + 1 < trimmed.length) { | ||
| current += trimmed[i + 1]; | ||
| i += 1; |
There was a problem hiding this comment.
Preserve backslashes in quoted args
For quoted values, this consumes every backslash as an escape marker, including in single quotes and before ordinary characters. A Windows path with spaces such as --chat-template-file "C:\Users\Me\my template.jinja" is parsed with the path backslashes removed, so the saved/reloaded llama-server argument points at a different path than the user entered.
Useful? React with 👍 / 👎.
| gpuLayers, | ||
| nCpuMoe, | ||
| selectedGpuIds, | ||
| llamaExtraArgs: llamaExtraArgs ?? undefined, |
There was a problem hiding this comment.
Hydrate active args from server status
This active-model config now reads custom args only from the client store, but /api/inference/status still doesn't return the backend's stored extra_args and the status hydrator never seeds llamaExtraArgs/loadedLlamaExtraArgs. After a browser refresh or adopting a model started by the CLI/API with custom GGUF args, the settings panel shows an empty field while the server is still running those args; clicking Reload sends undefined, so the backend inherits them and the user cannot clear the apparently-empty args.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in c448501. InferenceStatusResponse gained llama_extra_args, /status now reads llama_backend.extra_args, and the store hydrator seeds llamaExtraArgs / loadedLlamaExtraArgs. After a refresh, or when adopting a server started by the CLI, the field shows the flags that are running and Reload can clear them.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 13172e8e1a
ℹ️ 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".
| gpu_layers: effectiveGpuLayers, | ||
| n_cpu_moe: effectiveNCpuMoe, | ||
| gpu_ids: effectiveGpuIds ?? undefined, | ||
| llama_extra_args: effectiveLlamaExtraArgs, |
There was a problem hiding this comment.
Include saved args in background autoload validation
When startup autoloads a remembered GGUF whose saved args include a sizing override such as --ctx-size, canAutoLoad validates without effectiveLlamaExtraArgs, while the actual /load sends them here. With training active, validation can approve a smaller VRAM estimate and the load then fail with 409; a newly denied saved flag likewise fails only during the load, consumes an attempt, and can cause the last-used model to be skipped in favor of a fallback. Pass the same llama_extra_args through the background validation payload.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in c448501: the canAutoLoad payload now carries llama_extra_args: effectiveLlamaExtraArgs, the same value the loadModel call below sends, so the background preflight validates and sizes the command it will actually run.
| quote = ch; | ||
| continue; | ||
| } | ||
| if (/\s/.test(ch)) { |
There was a problem hiding this comment.
Parse escaped whitespace outside quoted args
When a user enters a shell-style escaped space outside quotes, such as --chat-template-file some\ path/template.jinja, this whitespace branch splits the value into some\ and path/template.jinja because backslashes are handled only while already inside quotes. The resulting reload sends a different argv shape and can make llama-server reject the request or read the wrong file; consume backslash-escaped whitespace and quote characters in the unquoted state as the documented shell-style parser implies.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not taking this one, for two measured reasons.
-
It reverses the fix asked for one round earlier. Making
\an escape in the unquoted state means--chat-template-file C:\Users\Me\t.jinjaparses toC:UsersMet.jinja. That bare Windows spelling parses correctly today and is far likelier in this field than POSIX escaping; keeping unquoted backslashes literal is what makes it work. -
The escaped-space form is not reachable from a round trip.
formatLlamaExtraArgsalways renders a whitespace-bearing token double-quoted, so the field re-displays--chat-template-file "some path/template.jinja"and neversome\ path. Quoting is the supported way to pass a value containing spaces and it round-trips losslessly, which is now pinned in tests/studio/test_llama_extra_args_roundtrip.py.
| "gpuLayers", | ||
| "nCpuMoe", | ||
| "selectedGpuIds", | ||
| "llamaExtraArgs", |
There was a problem hiding this comment.
Version the persisted schema for custom args
Adding llamaExtraArgs to the version-1 stored record without incrementing STORAGE_SCHEMA_VERSION defeats this module's future-schema preservation logic. If a user saves these flags, temporarily opens an older Studio build, and changes any setting for the same model, that build treats the record as its known version 1 and rewrites it without the unknown args; returning to this build silently loses the launch flags. Store this field under a newer schema version so older clients take the existing refuse-to-overwrite path.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not taking this one. The mechanism is real, but I measured the remedy and it costs more than the defect.
Simulated the downgrade with the real per-model-config module from main as the older build and the module at head as the new build, sharing one localStorage:
- as it stands: the older build drops
llamaExtraArgsand keeps the rest of the record (customContextLength32768 -> 16384 survives, the flags do not). - with
STORAGE_SCHEMA_VERSIONbumped: the older build reportsremembered=false,customContextLength=null,kvCacheDtype=null, andsavePerModelConfigreturnsfalse. It loses the entire record rather than one field, and can no longer save any per-model setting for that model.
Trading one dropped field for a record the older build can neither read nor write is the worse outcome, and the trigger is installing an older Studio build over a newer one rather than anything in a session.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: c448501bcd
ℹ️ 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".
| (prevState.loadedLlamaExtraArgs === null || hydratingExistingModel) && { | ||
| llamaExtraArgs: status.llama_extra_args, | ||
| loadedLlamaExtraArgs: status.llama_extra_args, |
There was a problem hiding this comment.
Refresh args after same-model status changes
When another client or the API reloads the same model with different extras, hydratingExistingModel remains false and any previously loaded non-null list makes this condition skip the update. The settings panel therefore continues showing the old flags, and its next Reload sends those stale flags back, undoing the external change; this should detect status changes and advance the loaded baseline while preserving only genuinely dirty local edits, as the GPU fields do.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not taking this one. The (prevState.loadedX === null || hydratingExistingModel) shape is this module's existing seed pattern, shared verbatim by speculativeType, specDraftNMax, cache_type_kv and tensor_parallel in the same setState on main. An external same-model reload leaves all four equally stale, so this is not behaviour the PR introduces, and moving only llamaExtraArgs onto the GPU fields' gpuStatusChanged dirty-tracking would leave the four siblings inconsistent. Worth doing for all of them at once, separately from this PR.
| const token = raw.trim(); | ||
| if (!token) { | ||
| continue; | ||
| } | ||
| out.push(token); |
There was a problem hiding this comment.
Preserve token whitespace while normalizing saved args
For remembered configurations containing an intentionally whitespace-sensitive token, such as a quoted literal passed to --chat-template, this trims the token during both save and restore normalization. The immediate load uses the unnormalized page config and can work, but after a restart the persisted argument has different contents, so normalization should validate strings without modifying the argv token bytes.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 10a292c. Reproduced on the real module: --chat-template "{{ x }} " parses to the token {{ x }} , which /load sends verbatim, while normalizeLlamaExtraArgs persisted {{ x }} - so the same saved config launched one way now and another way after a restart. normalize now validates on the trimmed form and stores the token verbatim; blank and non-string entries are still dropped. Pinned by tests/studio/test_llama_extra_args_roundtrip.py::test_save_persists_the_same_argv_the_load_sent, which reddens when the trim is put back.
| moeLayerCount={moeLayerCount} | ||
| /> | ||
|
|
||
| <LlamaExtraArgsSetting config={config} update={update} /> |
There was a problem hiding this comment.
Reject custom args for diffusion-backed GGUFs
For a DiffusionGemma GGUF, this control still accepts and persists llama-server flags, but LlamaCppBackend._start_diffusion_server launches the visual shim from a fixed command and never appends extra_args; it even records the ignored list afterward for status hydration. Users can therefore reload with flags such as --no-mmap and see them reported as active despite their having no effect, so these args should be hidden or rejected for diffusion-backed models rather than silently accepted.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not taking this one. _start_diffusion_server builds a fixed command (--gguf / --host / --port / --gpu / --maxtok), so it ignores the whole GGUF advanced block rather than just this control: it hard-sets self._tensor_parallel = False and never consumes cache_type_kv, speculative_type, gpu_layers or n_cpu_moe either. Hiding one of five equally inert controls would be the inconsistent half-measure. The picker also has no pre-load diffusion signal - is_diffusion is classified by the backend during load - so rejecting for diffusion-backed GGUFs is only expressible once the model is already running. Making the whole advanced block diffusion-aware is worth doing as its own change.
| name = token.split("=", 1)[0] | ||
| if name.startswith("--"): | ||
| name = name.replace("_", "-") |
There was a problem hiding this comment.
Normalize underscore aliases in every runtime parser
This now accepts long underscore spellings as equivalent to hyphenated llama.cpp flags, but the runtime helpers in llama_cpp.py still compare raw names in _extra_arg_flag_name and _effective_spec_type. For inputs such as --spec_type draft-mtp or --gpu_layers 0, llama-server honors the appended flag while Studio fails to detect it and can budget VRAM, download a drafter, apply full-offload tuning, and report state for a different launch mode; forced MTP can consequently run without its required reserve. The same normalization needs to be shared by all consumers of extra args.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 10a292c. Confirmed the premise against a real llama-server (b10107): --spec_type BOGUS reports error while handling argument "--spec-type" while a genuinely unknown flag reports invalid argument, matching the std::replace(arg, '_', '-') applied to every -- arg in common/arg.cpp.
Reproduced 11 mismatches at head: _effective_spec_type, _extra_args_requests_mtp, _extra_args_requests_separate_draft, _extra_args_set_spec_type (so Studio also appended its own --spec-type), the offload-override check, _extra_args_spec_draft_n_max and _extra_args_mtp_draft_path all missed the underscore spelling, and a stale LLAMA_ARG_SPEC_TYPE survived an underscore-spelled override that turns MTP off.
The folding now lives in one module-level helper that LlamaCppBackend._canonical_long_flag delegates to, and every extra-args consumer routes its flag name through it: spec type, draft n-max, drafter path, draft cache types, draft CPU offload, ubatch, GPU device pin, sidecar weight files and the prompt-cache switch. Regression tests are in studio/backend/tests/test_llama_cpp_mtp_detection.py; disabling the folding reddens nine of them.
One deliberate omission: _with_flash_attn_off reads the built spawn command on a crash-recovery rung and rewrites argv in place, rather than reading the extras list, so I left it alone here.
Resolve the two conflicts by keeping llama_extra_args alongside main's requested_gpu_ids in InferenceStatusResponse and its /status construction, and add requested_gpu_ids to the loaded-backend stand-in the extra-args status test builds.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 34c845c4bf
ℹ️ 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 (/\s/.test(ch)) { | ||
| if (current) { | ||
| tokens.push(current); |
There was a problem hiding this comment.
Preserve empty quoted arguments
When an option intentionally receives an empty string, such as field text --chat-template "" or stored argv ['--chat-template', ''], current remains empty, so neither this branch nor the end-of-loop branch emits that token; the formatter likewise renders an empty token without quotes. Focusing and blurring the field therefore changes the argv into a lone flag, which can make llama-server reject the reload or interpret subsequent tokens differently. Track whether a token was started independently of its contents and format empty tokens as "".
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in b19b6a8. Confirmed on llama-server b10107 that this is a silent argv shift, not just a dropped token: --chat-template "" --ctx-size BOGUS fails with error while handling argument "--ctx-size", while the argv the field produced after a blur, --chat-template --ctx-size BOGUS, fails with invalid argument: BOGUS -- llama-server took --ctx-size as the template string, so every following token was reinterpreted and the flag the user set was never applied.
The parser now tracks whether a token was opened rather than whether it has content, so --chat-template "" --no-mmap parses to three tokens; the formatter renders an empty token as ""; and normalize stores every string token verbatim (it only drops non-strings) so the save path cannot re-drop it. A field holding only whitespace still yields no tokens, and a""b still joins to one token as a shell would.
Pinned by tests/studio/test_llama_extra_args_roundtrip.py::test_empty_quoted_argument_survives_the_field, which reddens when the token tracking is reverted.
…saved argv tokens verbatim for PR unslothai#7386
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 731d2e9769
ℹ️ 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".
| type="text" | ||
| value={draft} | ||
| onChange={(event) => setDraft(event.target.value)} | ||
| onBlur={commit} |
There was a problem hiding this comment.
Commit custom args before handling Load
When a user edits this field and immediately clicks Load model or Reload model, the blur only updates the parent config, while handleRun can still use the render-time config captured before that blur. The numeric inputs explicitly bridge this same-click case through imperative commit() refs in handleRun, but this input has no equivalent, so validation and /load receive the previous args while the UI subsequently displays the new ones as though they were applied. Expose and consume a synchronous commit result for this field when constructing effectiveConfig.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 36659bc. Confirmed against the component's own documented behaviour rather than assuming it: NumericValueInput carries the comment "Same-click Load: blur commits via onChange and clears dirtyRef before the button onClick runs, while parent value is still stale", and handleRun opens with the matching note about the click closure capturing the pre-blur config. That is exactly why the four numeric inputs have imperative handles. This field has the same shape (local draft, commit on blur) and had no bridge, so a typed-then-clicked edit was validated and loaded at the previous args.
It now exposes a LlamaExtraArgsInputHandle that mirrors NumericValueInputHandle, including the one-shot blur cache cleared on any settled render, and handleRun commits it and folds the result into pendingPatch alongside the numeric drafts (gated on non-null, so an untouched field never fabricates an override). Pinned by tests/studio/test_model_picker_contracts.py::test_same_click_commit_covers_the_custom_llama_args_field.
| llamaExtraArgs: loadLlamaExtraArgs, | ||
| loadedLlamaExtraArgs: loadLlamaExtraArgs, |
There was a problem hiding this comment.
Store the effective args after manual-mode stripping
When GPU Memory mode is manual, /load strips explicit offload flags including --gpu-layers, --fit, --cpu-moe, and sometimes --tensor-split before launching (inference.py:4319-4346), but this state update records the original request as both the editable and loaded args. The settings panel therefore reports stripped flags as active—for example, the advertised --cpu-moe can have no effect—and subsequent saves or mode changes operate from a false baseline. Seed these fields from the backend's effective list rather than loadLlamaExtraArgs.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 36659bc. Reproduced with the exact example the field's own hint advertises: with gpu_memory_mode="manual" and ['--cpu-moe', '--no-mmap'], /load's manual-mode branch strips the offload group and launches ['--no-mmap'], while the frontend recorded the un-stripped request as both llamaExtraArgs and loadedLlamaExtraArgs.
The root cause was that LoadResponse had no field for it: every sibling in that same setState (cache_type_kv, tensor_parallel, speculative_type) is read back off the load response, and the extras were the only one seeded from the request. LoadResponse now carries llama_extra_args sourced from llama_backend.extra_args on both GGUF paths (fresh load and the already-loaded dedupe), and all three frontend load paths baseline on it, falling back to the request when an older backend omits it rather than blanking a field that is running. Regression tests in tests/studio/test_model_picker_contracts.py and studio/backend/tests/test_validate_model_error.py; reverting either half reddens them.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: b19b6a8c31
ℹ️ 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 name.startswith("--"): | ||
| return name.replace("_", "-") | ||
| return name | ||
| return _canonical_long_flag_name(name) |
There was a problem hiding this comment.
Canonicalize flash-attention flags during recovery
Fresh evidence after the earlier underscore-parser fix: _with_flash_attn_off at lines 6218-6235 still compares raw tokens instead of this canonical form. On a ROCm build that enters the hard-crash recovery path, a custom --flash_attn=on is honored by llama.cpp but ignored by the rewrite; because the custom token follows Studio's hyphenated flag, the retry only disables the earlier flag and the last-wins underscore token re-enables flash attention, causing the recovery attempt to hard-crash again. Apply the canonicalizer while detecting and rewriting these flags.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in e68e7a2. You are right and I was wrong to scope this out of the previous commit; the reachability argument holds and I reproduced it.
Verified every premise rather than reasoning about it: llama-server b10107 reports error while handling argument "--flash-attn" for both --flash-attn BOGUS and --flash_attn BOGUS, Unsloth hard-codes --flash-attn on in its own command (llama_cpp.py:7797), and user extras are appended last (llama_cpp.py:8160), so last-wins puts the pass-through token in charge. Driving _with_flash_attn_off over the real launch command, the retry came back with flash attention still ON for --flash_attn=on, bare --flash_attn, and --flash_attn on - the recovery rung was a no-op and the retry would crash exactly like the first attempt.
Detection and rewrite now both go through the shared canonicalizer. The rewrite keeps the user's own spelling (--flash_attn=off, not --flash-attn=off) since llama.cpp accepts either, and the list length is still preserved for the downstream slices. Pinned by studio/backend/tests/test_llama_cpp_mtp_detection.py::test_flash_attn_off_recovery_sees_underscore_aliases, which also covers the already-off and no-flag cases returning None, and reddens when the folding is disabled.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: e68e7a25c4
ℹ️ 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".
| (prevState.loadedLlamaExtraArgs === null || hydratingExistingModel) && { | ||
| llamaExtraArgs: status.llama_extra_args, | ||
| loadedLlamaExtraArgs: status.llama_extra_args, |
There was a problem hiding this comment.
Refresh args when a same-model reload changes them
When another tab or client reloads the same model and GGUF variant with different llama_extra_args, hydratingExistingModel remains false and loadedLlamaExtraArgs is already non-null, so status polling ignores the new server value. The settings panel consequently continues showing the old arguments and a later Reload can overwrite the externally applied configuration. Compare the incoming arguments with the loaded baseline, advance that baseline on changes, and preserve llamaExtraArgs only when this tab has an actual pending edit.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Holding this one. The guard shape here is not specific to the args field: speculativeType, specDraftNMax, cache_type_kv and tensor_parallel all use the identical loadedX === null || hydratingExistingModel predicate, and four of those five already read that way on main untouched by this PR. Evaluating the real spread expressions out of the file under exactly the scenario described (same model, same variant, hydratingExistingModel false, loaded baseline non-null, incoming value different) returns no update for all five fields, and flipping only hydratingExistingModel to true makes all five update, so the harness is measuring live behaviour rather than a constant. The follow-on risk is shared too: the Reload payload sends cache_type_kv, speculative_type, tensor_parallel and llama_extra_args from the same stale store state, so a stale-overwrite is possible for each of the four equally. Refreshing only the args field would make it the single load param that adopts external same-model changes, which is inconsistent with the other four rather than more correct. If this shape should change it belongs in one pass over all of them, not in a PR scoped to exposing the args field.
| config.gpuMemoryMode ?? currentStore.gpuMemoryMode; | ||
| const effectiveGpuLayers = config.gpuLayers ?? GPU_LAYERS_AUTO; | ||
| const effectiveNCpuMoe = config.nCpuMoe ?? 0; | ||
| const effectiveLlamaExtraArgs = llamaExtraArgsForLoad(config.llamaExtraArgs); |
There was a problem hiding this comment.
Apply remembered args in the no-cache fallback
The remembered llamaExtraArgs are resolved only inside loadAutoLoadCandidate, so the separate “No cached models” fallback that downloads unsloth/Qwen3.5-4B-MTP-GGUF neither reads that model's persisted configuration nor sends llama_extra_args to its validation/load requests. If a user remembered custom arguments for this model and later deleted its cached weights while leaving the per-model configuration intact, startup redownloads it with different arguments than the saved settings advertise; omission can also inherit stale same-model backend arguments instead of explicitly applying or clearing the saved value.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Holding this one too. The first half is factually right but is not something this PR introduced or can scope: the "No cached models" fallback never calls resolveInitialConfig at all, so it drops every per-model setting, not just the args. Extracting both payloads from the file shows the cached path forwards 12 per-model config fields and the fallback forwards 0 of them, with cache_type_kv, tensor_parallel, chat_template_override and llama_extra_args absent from the request body entirely. Running the same extraction against main gives the identical result for the 11 pre-existing fields, and the fallback block is byte-identical between main and this head, all six hunks this PR adds to the file land between lines 1501 and 1707 inside loadAutoLoadCandidate while the fallback starts at 1928. The block also carries an explicit comment stating the intent, that a fresh default model has no remembered settings so the per-model knobs stay at their defaults. Wiring only the args field in would make it the sole remembered setting honoured by a path that still ignores the context pin, GPU layer pin, MoE offload, KV cache dtype, tensor parallel and chat template override. The second half does not hold: inheriting stale same-model backend args needs that model already loaded, but autoLoadSmallestModel early-returns through tryAdoptServerActiveModel whenever status.active_model is set, so the fallback is only reachable with nothing loaded and there are no backend args to inherit.
|
@codex review |
|
Codex Review: Didn't find any major issues. What shall we delve into next? 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: 54e45a1489
ℹ️ 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".
| config.selectedGpuIds !== undefined | ||
| ? reconcilePersistedGpuIds(config.selectedGpuIds) | ||
| : null, | ||
| llamaExtraArgs: config.llamaExtraArgs ?? null, |
There was a problem hiding this comment.
Send an empty argument list when resetting the field
When an active GGUF was launched with custom arguments, clicking Reset produces the default config where llamaExtraArgs is absent; this assignment converts that state to null. The reload path subsequently passes null through llamaExtraArgsForLoad as an omitted field, which /load interprets as “inherit the previous same-model arguments,” so Reset visibly clears the input but relaunches with the old flags. Preserve an explicit empty list for this reset path so the backend actually clears the arguments.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct, fixed in 9324934.
Confirmed end to end on the real code. Reset stages { ...DEFAULT_PER_MODEL_CONFIG }, whose llamaExtraArgs is absent; applyPerModelConfigToRuntime mapped that to null, and llamaExtraArgsForLoad(null ?? undefined) dropped the key, so the /load body was literally {"model_path": "..."} with no llama_extra_args. Running the real _resolve_inherited_extra_args against a backend holding ["--cpu-moe", "--no-mmap"] returns those same args for an omitted field and [] for an explicit empty list, so Reset + Reload relaunched exactly the flags it had just cleared.
applyPerModelConfigToRuntime now assigns config.llamaExtraArgs ?? []. That is consistent with the rest of that setState: every sibling per-model field there (KV dtype, tensor parallel, GPU layers, n_cpu_moe, GPU pick, chat template) is already sent explicitly on the load that follows, so the args field was the only one degrading to "no opinion". The body now carries "llama_extra_args": [] and _request_matches_loaded_settings sees [] != ["--cpu-moe", "--no-mmap"], so the reload actually restarts the server without them.
| if (ch === "\\" && (next === quote || next === "\\")) { | ||
| current += next; | ||
| i += 1; |
There was a problem hiding this comment.
Preserve backslashes inside single-quoted values
For single-quoted input, this branch treats \\ as an escape and collapses it to one backslash, although shell single quotes preserve backslashes verbatim. Inputs commonly entered this way, such as --chat-template-kwargs '{"path":"C:\\foo"}' or single-quoted grammar expressions, therefore reach llama-server with altered or invalid JSON/grammar content. Apply backslash escaping only under double quotes and copy characters literally while quote === "'".
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct, fixed in 9324934.
Checked the parser against shlex.split(posix=True) before changing anything, since the field is documented as shell style. At the old head, 3 of 6 probe inputs diverged: --chat-template-kwargs '{"path":"C:\\\\foo"}' came out as {"path":"C:\\foo"} (and \\f is a JSON formfeed escape, so the value is not even the path the user typed), --grammar 'root ::= "\\\\n"' lost the literal backslash the grammar needs, and 'a\\\\b' collapsed to a\\b. The escape branch was firing for both quote characters even though the comment above it says "as in a shell".
Gated it on quote === '\"'. A 33-case differential sweep across unquoted / double-quoted / single-quoted forms: divergence from shlex 13 -> 8, exactly 5 parses changed, all of them single-quoted, all now matching shlex, and format -> parse is still a fixed point everywhere (the formatter only ever emits double quotes, so the round trip is unaffected). The 8 residual divergences are all the unquoted-backslash case, which is a deliberate documented deviation pinned by test_quoted_windows_path_keeps_its_backslashes, so I left it alone. New behavioural test test_single_quotes_keep_every_backslash asserts the single-quote rows against shlex and keeps the double-quoted and unquoted rows as controls.
| status.llama_extra_args !== undefined && | ||
| (prevState.loadedLlamaExtraArgs === null || hydratingExistingModel) && { | ||
| llamaExtraArgs: status.llama_extra_args, | ||
| loadedLlamaExtraArgs: status.llama_extra_args, |
There was a problem hiding this comment.
Reconcile same-model argument changes from status
After this tab has seeded a non-null loadedLlamaExtraArgs, a same-model reload performed by another client or an OpenAI auto-switch can change the server's arguments, but opening the model selector and refreshing status will never adopt the new array because hydratingExistingModel is false and the baseline is already non-null. The panel consequently displays the stale arguments and a later Reload silently restores them over the server's newer configuration. Compare the incoming arguments with the loaded baseline, advancing the baseline and preserving only genuinely pending local edits, as the GPU status fields do.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Position unchanged, declining again, and re-measured at 54e45a1 rather than re-argued.
The "as the GPU status fields do" part is right: the GPU group does reconcile, via gpuStatusChanged reopening the seed and preserveSameModelEdits holding dirty edits. But the seeds that group with llamaExtraArgs are the four non-GPU load-param seeds, and they all ship the same guard shape today.
I extracted every ...(seedLoadParams && ...) spread verbatim from the shipped file and evaluated them against a prevState with all baselines seeded and hydratingExistingModel false, on this head and on origin/main. On both, a same-model refresh updates only the GPU group; speculativeType, specDraftNMax, kvCacheDtype, tensorParallel and llamaExtraArgs all refuse. Flipping hydratingExistingModel to true makes all five update, so the harness is reading the live guard and not a paraphrase. Four of those five guards are on main verbatim (lines 301, 307-308, 315, 321 there).
So the stale-panel and stale-Reload consequence you describe applies identically to cache_type_kv and tensor_parallel on main today. llamaExtraArgs is not diverging from the convention, it is following it. Making it the one non-GPU seed that reconciles would be a cross-cutting behaviour change to a shared guard, which is outside what this PR should carry; if the convention is wrong it should change for all five at once, in its own PR.
| "gpuLayers", | ||
| "nCpuMoe", | ||
| "selectedGpuIds", | ||
| "llamaExtraArgs", |
There was a problem hiding this comment.
Bump the persisted-config schema for the new field
Adding llamaExtraArgs changes the persisted record while STORAGE_SCHEMA_VERSION remains 1. A stale tab or downgraded frontend therefore considers a new record compatible, normalizes away this unknown field, and can overwrite the same model's entry without its required launch arguments; the existing future-version guards cannot protect it. Increment the schema version when storing this field so older clients refuse to apply or rewrite the record.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Position unchanged, declining again. Re-ran the downgrade against this head; the bump makes the outcome worse, not better.
Simulated one browser origin (one localStorage) shared by the real head module and the real origin/main module, over a record carrying llamaExtraArgs plus customContextLength, kvCacheDtype, gpuMemoryMode, gpuLayers and selectedGpuIds.
As shipped (both at version 1) the old build reads the record fine (remembered=true, ctx 8192, kv q8_0, gpuLayers 24, gpuIds [0]) and, when it writes, drops llamaExtraArgs and keeps everything else. One field lost on a downgrade write.
With the bump applied to the real head module, the old build reports remembered=false with ctx, kv, gpuLayers and gpuIds all null, and savePerModelConfig returns false. So the whole remembered config goes invisible on every downgrade read, and the old tab can no longer save or delete any config for that model at all. Note this is the same result for the conditional form you propose ("increment when storing this field"), because the record under test carries the field, so it is stored at version 2 either way.
It is also not the convention here: gpuMemoryMode, gpuLayers, nCpuMoe, selectedGpuIds and chatTemplateOverride were all added to this same record at version 1 without a bump and are on main that way now. Bumping for this one field would not retroactively protect any of them, and the version guards are built for a genuine format change, not for an additive optional field that older clients already normalize away safely.
| llamaExtraArgs: null, | ||
| loadedLlamaExtraArgs: null, |
There was a problem hiding this comment.
Clear stale arguments after the default GGUF auto-load
This helper clears the new argument state only for non-GGUF responses, while the cached-candidate load paths separately overlay the GGUF response echo. The final “download a small default GGUF” branch in autoLoadSmallestModel also calls loadedGpuMemoryFields(loadResp) but never applies loadResp.llama_extra_args, so if the runtime store still contains arguments staged for a previous model, Qwen loads without them but its active settings panel continues to show them and a later Reload sends them to Qwen. Have the default GGUF branch baseline both argument fields from the response, or make this response helper do so for every GGUF caller.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct, fixed in 9324934.
Lifted the real loadedGpuMemoryFields and the real setState literal of the default-GGUF branch out of the sources and applied them to a store holding ["--cpu-moe", "--no-mmap"]. The helper does not touch either args field for an is_gguf response, and the branch itself set no args key, so the store kept the stale pair while the response echoed []. The same branch already re-baselines kvCacheDtype, tensorParallel and the GPU pick, so the args fields were the odd ones out.
Reachable without anything exotic: performLoad calls applyPerModelConfigToRuntime before validation and download, and the failure rollback is gated on previousWasUnloaded && previousCheckpoint. With nothing loaded yet, a model whose remembered config carries custom args leaves them in the store when its load fails, params.checkpoint stays empty, and the next message falls through to this branch.
Took the first of the two options you offered and baselined both fields from the response in the branch, rather than changing the shared helper: the helper is called from six sites that each already overlay their own args, so widening it would be the larger change.
… for PR unslothai#7386 Three fixes to the custom llama-server args field, all in the frontend. Reset now clears the args on the server. Reset stages DEFAULT_PER_MODEL_CONFIG, whose llamaExtraArgs is absent, and applyPerModelConfigToRuntime mapped that to null; llamaExtraArgsForLoad then omitted the field from /load, which reads an omitted field as "inherit the previous same-model args". So Reset blanked the input and relaunched the same flags. Every other field in that same setState is sent explicitly on the following load, so send [] here too. Single-quoted values keep their backslashes. The quoted-escape branch fired for both quote characters, but a shell keeps a single-quoted value verbatim, so '{"path":"C:\\foo"}' reached llama-server as {"path":"C:\foo"} (whose \f is a JSON formfeed escape) and a single-quoted grammar lost the backslash it needed. Gate the branch on the double quote; double-quoted and unquoted parsing is unchanged and the format/parse round trip is still a fixed point. The default GGUF auto-load baselines both args fields. That branch sends no extra args, and loadedGpuMemoryFields only clears them for a non-GGUF response, so args staged for a model that never finished loading stayed in the store: the panel showed them for Qwen and the next Reload sent them to it. Its siblings there (KV dtype, tensor parallel, GPU pick, chat template) were already re-baselined. Tests: a behavioural single-quote test cross-checked against shlex.split(posix=True), and two source contracts for the other two.
|
@codex review |
|
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". |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 753dd83f14
ℹ️ 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".
| n_moe_layers = llama_backend.n_moe_layers, | ||
| gpu_ids = llama_backend.gpu_ids, | ||
| requested_gpu_ids = llama_backend.requested_gpu_ids, | ||
| llama_extra_args = llama_backend.extra_args, |
There was a problem hiding this comment.
Report recovery-rewritten args instead
When a startup hard-crash is recovered by _with_flash_attn_off, the successful child may run with flash attention disabled and quantized V-cache flags rewritten to f16, but LlamaCppBackend still stores the original extra_args. Echoing that list here makes the settings panel baseline flags such as --flash-attn on --cache-type-v q8_0 as active even though the recovered server is running off/f16, so later saves and reloads operate from a false runtime state. Record and return the extras after recovery rewrites, as is already done for manual-mode stripping.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct, fixed in bd9c42a.
Reproduced end to end by driving the real load_model with the spawn and health calls faked: attempt 1 hard-crashes (exit -6), the _with_flash_attn_off rung fires, attempt 2 comes up healthy. The two argvs:
attempt 1 ... --flash-attn on ... --cache-type-v q8_0 --spec-default --flash-attn on --cache-type-v q8_0
attempt 2 ... --flash-attn off ... --cache-type-v f16 --spec-default --flash-attn off --cache-type-v f16
Both the trailing user extras and Unsloth own flags get flipped, because the extras are already appended into cmd before the rewrite. backend.extra_args afterwards was still ["--flash-attn", "on", "--cache-type-v", "q8_0"]: the commit stores the caller list, and the rewrite only ever touched cmd.
The round trip that matters: /load echoes that list, the panel baselines on it, a save persists it, and the next load replays it. Same harness, load then save then reload:
before saved per-model config: ["--flash-attn", "on", "--cache-type-v", "q8_0"]
replayed launch argv : ["--flash-attn", "on", "--cache-type-v", "q8_0"]
ROUND_TRIP_BROKEN: the saved config encodes flags the server the user was looking at never ran
after saved per-model config: ["--flash-attn", "off", "--cache-type-v", "f16"]
replayed launch argv : ["--flash-attn", "off", "--cache-type-v", "f16"]
ROUND_TRIP_OK
The recovered args are not recorded anywhere the route could read: _last_spawn_cmd is a local in load_model, and nothing on the backend keeps the launched argv, so there was no existing source to prefer.
Fix: _extras_after_startup_recovery slices the extras back out of the retry argv. _with_flash_attn_off preserves the token count and rewrites in place, so the window recorded where the extras were appended still holds them; it returns None unless every flag name in the window still matches, so a mis-sliced list is never reported. Both flash-attn rungs adopt it before respawning, which also covers the later rungs since they build on the rewritten argv. The --fit off retry appends after the extras, hence the recorded start index rather than a tail slice.
Negative control, tests/test_llama_cpp_mtp_detection.py: with the hunk reverted 6 failed, 262 passed; restored 268 passed.
| # raises the KV estimate), else inherited. | ||
| effective_extra_args = _resolve_inherited_extra_args( | ||
| request, config, model_identifier, None | ||
| request, config, model_identifier, request.llama_extra_args |
There was a problem hiding this comment.
Account for cache precision in training preflight
With training active, forwarding extras here still underestimates a local GGUF that requests a heavier cache such as --cache-type-k f32 --cache-type-v f32: _estimate_gguf_kv_gb reads only the context override and calls _estimate_kv_cache_bytes without a cache type, so it budgets the f16 default even though the launched server allocates roughly twice as many KV bytes. The preflight and subsequent /load can therefore admit a model that exhausts VRAM and disrupts the training run; derive the heavier per-axis cache type from these extras just as the llama.cpp load-time budget does.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct, fixed in the same commit bd9c42a.
The asymmetry is real. load_model derives the budget type from the extras via _extra_args_main_cache_type_for_budget(extra_args), while _estimate_gguf_kv_gb parsed only --ctx-size and called _estimate_kv_cache_bytes with no type at all. Measured on a 32-layer GQA probe at ctx 8192 with --cache-type-k f32 --cache-type-v f32:
llama.cpp load-time budget : type=f32 2.00 GB
training preflight : type=None 1.00 GB (2.00x under)
so the preflight, and the /load it gates, could admit a model needing twice the KV it reserved while a training run holds the rest of the VRAM.
Fix reuses the same helper rather than adding a second parser, exactly as you suggest, since a divergent copy is what produced this gap. On the per-axis point: that helper calls parse_cache_override_per_axis, so it reads --cache-type-k and --cache-type-v independently and budgets the heavier one; it does not assume they match, and it is not parse_cache_override, whose single last-wins value would still under-budget k=f32 v=f16. I deliberately did not make this path exact-per-axis: _estimate_kv_cache_bytes takes one type for both axes, so an exact 1.5 GB for k=f32 v=f16 would sit below the 2.0 GB the launch reserves and reintroduce the invariant this preflight exists to hold, that validation never passes a smaller estimate than the load. Over-reserving the lighter axis is the safe direction for a guard.
Scope note: validate_extra_args is a denylist and stays one; this touches only the sizing path, and both --cache-type-k/-v are already permitted pass-through flags, so nothing changes about what is accepted.
Negative control: with the hunk reverted tests/test_validate_model_error.py + tests/test_chat_load_during_training.py gave 7 failed, 77 passed; restored 84 passed.
…as cache type for PR unslothai#7386 The flash-attn-off startup recovery rewrites the whole launch argv, user extras included, so a load that survives it can run --flash-attn off and an f16 V cache while the backend still stores the pre-recovery request. /load, /status and the settings panel then advertise flags the server never ran, and a save persists them, so the next load replays the argv that just crashed. Slice the extras back out of the retry argv (the rewrite preserves the token count and edits in place) and adopt them at both recovery rungs, mirroring the manual GPU strip. The training preflight sized its GGUF KV reserve at the f16 default even when the extras asked for --cache-type-k/-v f32, budgeting half of what the server allocates and letting the guard admit a model that then exhausts VRAM under an active run. Derive the type from the same helper the llama.cpp load-time budget uses, which reads each axis on its own and budgets the heavier one.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 575db45feb
ℹ️ 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".
| list(extra_args or ()), | ||
| recovered, | ||
| ) | ||
| extra_args = recovered |
There was a problem hiding this comment.
Replay the recovery-rewritten extra arguments
When startup recovery changes a custom --flash-attn or V-cache argument here, only the local extra_args variable is updated; _pending_load_kwargs was captured before this rewrite and is later committed as the supposedly known-good _last_load_kwargs. If the recovered server subsequently exits and the generic respawn or MTP watchdog replays that snapshot, it launches the original crash-inducing arguments again instead of the effective arguments reported by /load and /status, causing another avoidable hard crash and recovery cycle. Update the pending replay snapshot whenever recovered extras are adopted.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct, and reproduced. Fixed in f2da4a1.
_pending_load_kwargs is built from the caller kwargs above the spawn and committed unchanged as _last_load_kwargs, so the previous round left reporting and replay disagreeing.
Driving a real load_model through a real recovery (spawn 0 and its inner --fit off retry segfault, the --flash-attn off rung survives), with the user asking for --flash-attn on --cache-type-v q8_0:
spawn 0: ... --spec-default --flash-attn on --cache-type-v q8_0
spawn 1: ... --spec-default --flash-attn on --cache-type-v q8_0
spawn 2: ... --spec-default --flash-attn off --cache-type-v f16
/status reports self._extra_args : ["--flash-attn", "off", "--cache-type-v", "f16"]
replay snapshot _last_load_kwargs[extra_args] : ["--flash-attn", "on", "--cache-type-v", "q8_0"]
Then killing that recovered server:
llama-server for "owner/model" exited (code -9); respawning to recover the session
respawn relaunches with: ["--flash-attn", "on", "--cache-type-v", "q8_0"]
So the snapshot is consumed, not merely mismatched. Two paths replay it independently: _respawn_if_dead passes dict(self._last_load_kwargs) straight to load_model, and _maybe_recover_from_mtp_crash replays the same snapshot with only speculative_type forced off. Both relaunch the argv that just hard-crashed, so the recovery runs a second time for a config already known to fail.
The remedy updates the snapshot inside the existing _adopt_recovered_extras helper, so _extras_after_startup_recovery stays the single derivation of the effective extras. It sits after that helper guard, which returns early when the slice does not line up flag-for-flag or nothing changed, so a load that recovered nothing still replays exactly what the caller asked for. Confirmed by a no-crash run: one spawn, snapshot unchanged at --flash-attn on --cache-type-v q8_0. The snapshot is per-load and unload_model clears _last_load_kwargs, so a rewrite the user never asked for does not outlive the server it belongs to.
Negative control: reverting the hunk leaves the snapshot on the crashing request and reddens test_adopted_extras_reach_the_replay_snapshot; restoring it greens. Coverage adds two executable tests that pin each replay path reading the snapshot rather than the reported extras, plus the ordering and single-derivation pin.
Suites: test_llama_cpp_mtp_detection.py + test_llama_server_args.py 532 -> 535 passed, test_validate_model_error.py 28 passed, tests/studio/test_llama_extra_args_roundtrip.py + test_model_picker_contracts.py 59 passed.
…nslothai#7386 When the startup crash recovery rewrites a custom --flash-attn or V-cache argument, the previous round adopted the effective extras so /load and /status report what the surviving server actually runs. The replay snapshot was left behind: _pending_load_kwargs is filled from the caller's kwargs above the spawn and committed unchanged as _last_load_kwargs, so it still held the pre-rewrite request. Both replay paths take their argv from that snapshot verbatim, so a later death relaunched the flags that had just hard-crashed and bought a second recovery cycle for a config already known to fail. _respawn_if_dead and the MTP-crash watchdog now replay the same flags /status reports as effective. The update reuses _extras_after_startup_recovery through the existing adopt helper rather than deriving the effective extras a second time, and sits after its guard, so a load that recovered nothing still replays exactly what the caller asked for.
|
One cross-reference from a sibling PR, because it is direct evidence about the design choice here rather than a new bug in this one. While investigating the token-count endpoint on #7453, the reachability chain for a materially wrong token count turned out to run through this PR's flag handling. Nothing needs to change here, and I would specifically not add What it does illustrate is the standing property of this design. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: da7d0a3d5d
ℹ️ 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".
| n_moe_layers = llama_backend.n_moe_layers, | ||
| gpu_ids = llama_backend.gpu_ids, | ||
| requested_gpu_ids = llama_backend.requested_gpu_ids, | ||
| llama_extra_args = llama_backend.extra_args, |
There was a problem hiding this comment.
Rewrite custom spec args after the MTP fallback
When custom extras request MTP and startup or the first decode fails, the fallback at LlamaCppBackend.load_model appends --spec-default to the successful command, but unlike the flash-attention recovery path it never updates extra_args. This response therefore reports the original --spec-type mtp as loaded even though the surviving server runs the later --spec-default; the settings panel baselines and can persist the ineffective flag, causing every subsequent reload to retry the configuration that already failed.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct, and fixed in ac18a32.
Reproduced: with --spec-type mtp typed in the custom args box, _build_speculative_flags returns [] (the user owns --spec-type), so the fallback splices --spec-default in at _spec_start and appends a second one after the extras. The surviving child runs
llama-server -m /m.gguf --flash-attn on --spec-default --spec-type mtp --spec-default
_effective_spec_type on that tail is default, but extra_args was still ['--spec-type', 'mtp'], so _extra_args_requests_mtp stayed True and every reload re-requested the MTP that had just crashed.
On the "do not add a third bespoke patch" point: I checked whether _extras_after_startup_recovery could just be called here, and it cannot as written. The splice sits before the extras, so with the recorded _extra_args_start it returns None and adopts nothing; with a shifted start it returns the window unchanged, because this rung does not rewrite the extras at all, it appends an override after them. A bare third call site would have looked like a fix and done nothing.
So the adopt step is now uniform rather than per-rung:
_extra_args_startis an invariant maintained alongside the argv. A rung that splices before the extras updates it (_extra_args_start += 1 - len(spec_flags)), and_adopt_recovered_extrasreads it live instead of taking one from a caller, so a stale index cannot be passed in._extras_after_startup_recoverygained the tokens a rung appended after the extras and folds them into the returned list. It refuses them unless they are literally the argv tail following the window, so the None-unless-everything-lines-up property you asked me to keep now covers the suffix too.- The
--mmprojtext-only retry is the one rung with nothing to adopt (it drops Unsloth's own flag pair and adds no override); that is recorded in place rather than left as an omission.
Both paths, proven together: the adopt closure rebinds the local extra_args that the healthy commit copies into _extra_args (reporting) and rewrites _pending_load_kwargs["extra_args"] that it commits as _last_load_kwargs (replay). test_the_mtp_fallback_rung_reports_and_replays_what_it_launched re-hosts the shipped rung and closure and asserts both come back as ['--spec-type', 'mtp', '--spec-default'], that they agree, and that _extra_args_requests_mtp on the result is False. test_mtp_fallback_extras_reach_both_the_report_and_the_replay then feeds that list through _respawn_if_dead and _maybe_recover_from_mtp_crash.
Adopting the verbatim argv tail rather than a synthesised list is deliberate: _effective_spec_type is last-wins, so --spec-type mtp --spec-default resolves to default and a reload skips the MTP budget and the crash entirely, while the field still shows the user their own text plus the flag that actually took effect. An env-only MTP request leaves extra_args empty and is still declined, so no flag the user never typed appears in their box.
Negative control, twice. Reverting llama_cpp.py wholesale with git show HEAD: (verified applied: git status showed only the test file dirty) reddened 5 of the new tests. Reverting only this rung, splicing HEAD's block back in verbatim while keeping the helper change, reddened the behavioural test for the right reason:
> assert fallback[start:] == launched
E AssertionError: assert ['--spec-defa...spec-default'] == ['--spec-type...spec-default']
E At index 0 diff: '--spec-default' != '--spec-type'
Suites: test_llama_cpp_mtp_detection.py + test_llama_server_args.py 535 -> 543 passed; test_validate_model_error.py 28 -> 28; tests/studio/test_llama_extra_args_roundtrip.py + test_model_picker_contracts.py 59 -> 59.
| Extra flags passed to llama-server after Unsloth's defaults. | ||
| Useful for large MoE models on consumer GPUs, e.g.{" "} | ||
| <code className="text-ui-11">--cpu-moe --no-mmap</code>. Unsloth-managed | ||
| flags (model path, port, parallel slots) are rejected. |
There was a problem hiding this comment.
Reconcile custom device overrides with GPU placement
On Vulkan, combining a picker selection such as gpu_ids=[0] with custom --device Vulkan1 makes the child use Vulkan1 because load_model deliberately appends extras after its generated device pin, but _gpu_ids and _requested_gpu_ids are recorded from the picker before those extras are applied. The load/status response therefore reports GPU 0 while the server uses GPU 1, and during training the coexistence guard checks the wrong device and can admit a load onto the training GPU; either reject device-selection extras when placement is managed or derive the effective placement from them.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
The ordering premise is right, but the harm it is built on does not hold, so I am leaving this.
The training guard does not read _gpu_ids or _requested_gpu_ids. _guard_chat_load_against_training is passed requested_gpu_ids = effective_gpu_ids, which is request.gpu_ids (routes/inference.py:4573 and 5209). The recorded attributes feed only /status, the load response, and the matches_gpu_ids dedupe. So the stale value you identified is not an input to any safety decision in the tree.
And on Vulkan the guard is device-identity agnostic by construction, so no --device swap can move its verdict. can_load_chat_during_training budgets the N least-free visible cards for an N-device Vulkan request (routes/training_vram.py:311-320), precisely because ordinals cannot be mapped to physical indices. Executed with training holding physical GPU 1 (2 GB free) and GPU 0 idle (79 GB free), model needing 20 GB:
is_vulkan=True
requested_gpu_ids=[0]: ok=False info={'mode': 'gguf_vulkan', 'usable_gb': 2.0, 'needed_gb': 27.0, 'min_free_gb': 2.0}
requested_gpu_ids=[1]: ok=False info={'mode': 'gguf_vulkan', 'usable_gb': 2.0, 'needed_gb': 27.0, 'min_free_gb': 2.0}
Byte-identical. The branch already assumes the worst possible mapping, and swapping which ordinal the child uses is exactly a re-mapping, so it cannot admit a load onto the training GPU.
The CUDA/ROCm half cannot happen either: there the pin is a visibility mask (_emit_child_gpu_visibility sets CUDA_VISIBLE_DEVICES / ROCR_VISIBLE_DEVICES), not --device. A --device CUDA1 in extras under a mask exposing only CUDA0 names a device the child cannot see, so parse_device_list throws invalid device and the server exits loudly. That is the behaviour the code comment already promises.
The reporting half of your description is real: --device is not on the denylist, _vulkan_pin_args emits --device Vulkan0, extras go last, and llama.cpp assigns rather than merges in the -dev/--device handler, so the child does run Vulkan1 while /status echoes GPU 0. But that is entirely pre-existing and deliberate, and this PR touches none of it: the diff against main has zero lines mentioning device, _gpu_ids or vulkan_pin in llama_cpp.py, and does not touch training_vram.py, main.py or use-gpu-info.ts. The ordering is documented intent at llama_cpp.py:8154, "before user extras so a user --device wins", which is the same principle this PR follows for every other permitted flag.
It is also barely reachable as described. On a Vulkan build gguf_gpu_ids_supported is False (main.py:1204), which clears physicalIndex and hides the picker (showGpuPicker, model-config-page.tsx:284), so the picker selection your scenario combines with the custom arg does not exist in that UI. And only the space-separated spelling reproduces it; --device=Vulkan1 passes our validator but makes llama-server abort at startup, since its parser does not split --flag=value.
Of your two remedies I would not take either here. Rejecting device extras breaks users relying on --device today, and deriving placement from them would fold a new input into matches_gpu_ids dedupe and /status on code this PR does not otherwise touch. Your third framing, report the effective device and make the guard use it, is the right shape, but the guard half is already a no-op and the reporting half is a pre-existing cosmetic mismatch, so it belongs in a change that owns the placement path.
…hai#7386 The MTP fallback swaps Unsloth's spec block for --spec-default and, when the user's own extras asked for MTP, appends a second --spec-default that llama.cpp takes last. Neither half reached extra_args, so the surviving server ran spec-default while the load response, /status and the settings panel kept advertising --spec-type mtp; saving that re-requested MTP on every later load, paying the crash and this fallback again each time. The two flash-attn rungs already adopt their rewrite, so make the same step work at every rung instead of patching this one: - _extras_after_startup_recovery now takes the tokens a rung appended after the extras and folds them in, refusing them unless they really are the argv tail that follows the window. The flag-for-flag window check is unchanged, so a mis-sliced list is still never adopted. - _extra_args_start is kept in step with the argv: the spec-block swap moves the extras, so the rung updates the recorded index and the adopt helper reads it live rather than taking one from a caller. - The text-only --mmproj retry, the one rung with nothing to adopt, records why in place. Both consumers land together: extra_args feeds the reported list and the helper rewrites the replay snapshot that _respawn_if_dead and the MTP watchdog relaunch, so neither walks back into the configuration that just failed. Tests re-host the shipped rung and adopt closure and run them, so a rung that stops adopting, mis-tracks the start index or stops naming its override fails, plus a tripwire over the whole set of recovery rungs.
|
Ran this branch and the merge base as two isolated Studios side by side to check the behaviour visually, and turned up something worth recording. It is not a regression from this PR, but it does mean one rung does not do what its comment says. First, a correction to how I have been describing this PR. The merge base has no custom llama-server arguments field in the model config panel at all; this PR introduces it. So the before state is not "shows a stale value", it is "there is nothing to show". Loading the base through its API with identical The round trip itself works. Typing The finding is on the MTP fallback rung. Any The practical effect: a user who puts Scope, so this is not read as worse than it is. The rung and the trailing-append shape both pre-date this PR; the merge base has the same Two things I would suggest, neither blocking. The comment should stop claiming a trailing One incidental result that reflects well on the change: when the MTP reload fails, the previously loaded server survives and the panel and I could not induce a genuine startup hard crash on CUDA with this prebuilt, so the flash-attention-off and V-cache-to-f16 recovery rung is not covered by this run, and I did not stage a fake crash to fill the gap. Screenshots, videos and the raw probe output are saved locally. |
|
We won't merge this as well - thanks - this does not solve #7022 |
Fixes #7022
Problem
Studio launches GGUF models with
--fit onby default. For very large MoE models on consumer GPUs (e.g. DeepSeek-V4-Flash ~100GB on a 16GB RTX card), that configuration often fails to load. The reporter's working setup uses extra llama-server flags such as--cpu-moeand--no-mmap, which were already supported on the CLI and backend (LoadRequest.llama_extra_args+validate_extra_argsdenylist) but had no control in the Studio model settings UI—forcing users to abandon the web UI and rununsloth studio run ...instead.Fix
studio/frontend/src/features/model-picker/model-config/llama-extra-args.ts: Shell-style parser/formatter and load helper for extra argv tokens.studio/frontend/src/features/model-picker/model-config/per-model-config.ts: PersistllamaExtraArgsper model in localStorage.studio/frontend/src/features/model-picker/components/model-config-page.tsx: Add Custom llama-server Args text field under GGUF advanced settings (with tooltip for MoE/Windows flags).studio/frontend/src/features/model-picker/model-config/apply-per-model-config.ts: Round-trip through runtime store and config equality/signature checks.studio/frontend/src/features/chat/{api/chat-adapter,hooks/use-chat-model-runtime,shared-composer}.ts: Forwardllama_extra_argson GGUF/loadrequests.tests/studio/test_model_picker_contracts.py: Source-contract guards for the new field and load wiring.Users can now enter e.g.
--cpu-moe --no-mmapin model settings; flags are validated server-side by the existing denylist (model path, port, parallel slots, etc. remain blocked).Verification
cd studio/frontend && npm run typecheck— passpytest tests/studio/test_model_picker_contracts.py— not run here (pytestunavailable in this VM); new contract tests added for CIDeepSeek-V4-Flash-UD-Q2_K_XLon Windows 11 + RTX 5070 Ti — please retest on reporter setup with--cpu-moe --no-mmapin the new fieldCompatibility
llama_extra_argson/load(inherit behavior unchanged).