Skip to content

fix(studio): expose custom llama-server args in model config (#7022) - #7386

Closed
Souravrajvi0 wants to merge 21 commits into
unslothai:mainfrom
Souravrajvi0:fix/studio-llama-extra-args-ui-4af7
Closed

Souravrajvi0 wants to merge 21 commits into
unslothai:mainfrom
Souravrajvi0:fix/studio-llama-extra-args-ui-4af7

Conversation

@Souravrajvi0

Copy link
Copy Markdown
Contributor

Fixes #7022

Problem

Studio launches GGUF models with --fit on by 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-moe and --no-mmap, which were already supported on the CLI and backend (LoadRequest.llama_extra_args + validate_extra_args denylist) but had no control in the Studio model settings UI—forcing users to abandon the web UI and run unsloth 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: Persist llamaExtraArgs per 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: Forward llama_extra_args on GGUF /load requests.
  • 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-mmap in 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 — pass
  • pytest tests/studio/test_model_picker_contracts.py — not run here (pytest unavailable in this VM); new contract tests added for CI
  • Not run here: loading DeepSeek-V4-Flash-UD-Q2_K_XL on Windows 11 + RTX 5070 Ti — please retest on reporter setup with --cpu-moe --no-mmap in the new field

Compatibility

  • Backwards compatible: absent/empty extra args omit llama_extra_args on /load (inherit behavior unchanged).
  • Existing CLI and OpenAI auto-switch override API unchanged.

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

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 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".

Comment on lines +77 to +78
if (!args?.length) {
return undefined;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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.

Comment on lines +1060 to +1062
const effectiveLlamaExtraArgs = llamaExtraArgsForLoad(
ownConfig.llamaExtraArgs ?? compareLoadKnobs.llamaExtraArgs ?? undefined,
);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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.

Comment on lines +1118 to +1120
llama_extra_args: llamaExtraArgsForLoad(
stateBeforeUnload.loadedLlamaExtraArgs ?? undefined,
),

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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.

Souravrajvi0 and others added 2 commits July 24, 2026 03:49
- 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

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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.

Comment on lines +55 to +56
if (!/\s/.test(token)) {
return token;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Fixed in d9a828a. Measured at 7c7538b: {"date_string":"July"} came back as {date_string:July} on the next blur, because the formatter only quoted on whitespace. The test is now /[\s"']/, and the round-trip is pinned behaviourally.

Comment on lines +16 to +18
if (ch === "\\" && i + 1 < trimmed.length) {
current += trimmed[i + 1];
i += 1;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Fixed in d9a828a. Measured at 7c7538b: "C:\Users\Me\my template.jinja" parsed to C:UsersMemy template.jinja. Only a quote or another backslash escapes now, so both the quoted and the bare Windows spelling survive the field.

gpuLayers,
nCpuMoe,
selectedGpuIds,
llamaExtraArgs: llamaExtraArgs ?? undefined,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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.

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 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,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Not taking this one, for two measured reasons.

  1. It reverses the fix asked for one round earlier. Making \ an escape in the unquoted state means --chat-template-file C:\Users\Me\t.jinja parses to C: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.

  2. The escaped-space form is not reachable from a round trip. formatLlamaExtraArgs always renders a whitespace-bearing token double-quoted, so the field re-displays --chat-template-file "some path/template.jinja" and never some\ 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",

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Not taking this one. The 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 llamaExtraArgs and keeps the rest of the record (customContextLength 32768 -> 16384 survives, the flags do not).
  • with STORAGE_SCHEMA_VERSION bumped: the older build reports remembered=false, customContextLength=null, kvCacheDtype=null, and savePerModelConfig returns false. 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.

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 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".

Comment on lines +328 to +330
(prevState.loadedLlamaExtraArgs === null || hydratingExistingModel) && {
llamaExtraArgs: status.llama_extra_args,
loadedLlamaExtraArgs: status.llama_extra_args,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Not taking this one. The (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.

Comment on lines +80 to +84
const token = raw.trim();
if (!token) {
continue;
}
out.push(token);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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} />

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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.

Comment on lines 101 to +103
name = token.split("=", 1)[0]
if name.startswith("--"):
name = name.replace("_", "-")

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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.

danielhanchen and others added 2 commits July 26, 2026 21:13
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.

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 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".

Comment on lines +36 to +38
if (/\s/.test(ch)) {
if (current) {
tokens.push(current);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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.

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 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}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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.

Comment on lines +1045 to +1046
llamaExtraArgs: loadLlamaExtraArgs,
loadedLlamaExtraArgs: loadLlamaExtraArgs,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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.

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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.

@danielhanchen

Copy link
Copy Markdown
Member

@codex review

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 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".

Comment on lines +330 to +332
(prevState.loadedLlamaExtraArgs === null || hydratingExistingModel) && {
llamaExtraArgs: status.llama_extra_args,
loadedLlamaExtraArgs: status.llama_extra_args,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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.

@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. What shall we delve into next?

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

@danielhanchen

Copy link
Copy Markdown
Member

@codex review

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 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,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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.

Comment on lines +23 to +25
if (ch === "\\" && (next === quote || next === "\\")) {
current += next;
i += 1;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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.

Comment on lines +329 to +332
status.llama_extra_args !== undefined &&
(prevState.loadedLlamaExtraArgs === null || hydratingExistingModel) && {
llamaExtraArgs: status.llama_extra_args,
loadedLlamaExtraArgs: status.llama_extra_args,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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",

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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.

Comment on lines +633 to +634
llamaExtraArgs: null,
loadedLlamaExtraArgs: null,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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.
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Jul 27, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 👍

Reviewed commit: 93249344da

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 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,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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.

danielhanchen and others added 2 commits July 27, 2026 03:37
…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.

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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.
@danielhanchen

Copy link
Copy Markdown
Member

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. --no-jinja is a permitted pass-through, and user extra args are appended after Studio's own --jinja, so a user who supplies it wins last. Upstream then raises tools param requires --jinja flag, /apply-template returns 500, and the token counter silently fell back to concatenating message text: measured 324 tokens against a correctly rendered 467 on a six-turn chat with two tool schemas, a 30.6 percent undercount, with no error surfaced. That has been fixed on #7453 by refusing the fallback and returning 503, so the bar keeps its previous value instead of showing a confidently wrong number.

Nothing needs to change here, and I would specifically not add --no-jinja to the denylist. It is a legitimate flag, _TEMPLATE_FLAGS already handles it correctly for inherit-and-strip, and silently dropping a flag a user typed is worse than honouring it. The right shape is the one #7453 took: let the flag through, and make anything depending on template rendering fail loudly rather than degrade.

What it does illustrate is the standing property of this design. validate_extra_args is a denylist, so a newly added upstream flag is permitted by default, and the ways a permitted flag can interact with a Studio-owned feature are not enumerable in advance. This one surfaced two features away from the flag itself, in a token counter, via a template renderer. That is worth knowing when llama.cpp adds flags: the denylist needs review on each bump, and the more durable protection is that dependent features fail closed rather than approximate.

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 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,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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_start is 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_extras reads it live instead of taking one from a caller, so a stale index cannot be passed in.
  • _extras_after_startup_recovery gained 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 --mmproj text-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.

Comment on lines +486 to +489
Extra flags passed to llama-server after Unsloth&apos;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.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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.
@danielhanchen

Copy link
Copy Markdown
Member

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 llama_extra_args confirms the server runs the flags either way, but GET /api/inference/status has no llama_extra_args key there, so nothing round-trips back to the UI.

The round trip itself works. Typing --no-mmap --ctx-size 8192 --cache-type-k q8_0, reloading, then closing and reopening the panel re-shows exactly those args, and /status reports them. Validation also lands where it should: --api-key leaked-secret returns 200 {"valid": true} on the base (the field does not exist on ValidateModelRequest, so it is silently dropped) and 400 with a clear message on this branch, without unloading the running model. --ctx-size not-a-number behaves the same way.

The finding is on the MTP fallback rung. _effective_spec_type implements last-wins parsing, and the code comment states that a trailing --spec-default overrides an earlier --spec-type. Probing the shipped llama-server directly, version 10107 (857c97607), that does not hold:

--spec-default                                       -> STARTED OK
--spec-type none                                     -> STARTED OK
--spec-type draft-mtp                                -> FAILED (rc=1)
--spec-type draft-mtp --spec-default                 -> FAILED (rc=1)
--spec-default --spec-type draft-mtp --spec-default  -> FAILED (rc=1)
--spec-type draft-mtp --spec-type none               -> FAILED (rc=1)

Any --spec-type draft-mtp anywhere in the argv is fatal for a non-MTP model on this build. A trailing --spec-default does not override it, and neither does a later --spec-type none.

The practical effect: a user who puts --spec-type draft-mtp in the extras box against a non-MTP model triggers the fallback, the rewritten argv is now reported accurately (which is what the recent commits here fixed), and the retry then fails identically, so /load 500s. The fallback fires but cannot recover.

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 + ["--spec-default"]. Studio's own auto-emitted spec block is replaced rather than appended to, so that path is unaffected. This only reaches a user-supplied --spec-type through the new extras box, which is to say the PR makes an existing dead-end reachable rather than creating it.

Two things I would suggest, neither blocking. The comment should stop claiming a trailing --spec-default overrides an earlier --spec-type, since that is now measured to be false on the shipped build. And the honest fix for that rung is to strip the user's --spec-type on retry rather than append after it, matching what the auto-emitted path already does.

One incidental result that reflects well on the change: when the MTP reload fails, the previously loaded server survives and the panel and /status go back to reporting that server's real flags rather than the failed request.

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.

@danielhanchen

danielhanchen commented Jul 27, 2026 •

Copy link
Copy Markdown
Member

We won't merge this as well - thanks - this does not solve #7022

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] --fit on prevents loading large MoE models like DeepSeek-V4-Flash on consumer hardware; request for UI control over llama-server flags

2 participants