Repository navigation
studio: preserve gguf settings across chat switches - #9562
Conversation
|
Confirmed the switch-back path reloads with a default 4096 context instead of the saved per-model settings, and this carries the chat's resolved GGUF variant through so the stored config is found. Will get this reviewed. |
Lyxot
left a comment
There was a problem hiding this comment.
Root cause is right, and I confirmed it against the branch: per-model settings key on (modelId, ggufVariant), so resolveInitialConfig("unsloth/Qwen3.8-27B-GGUF", "UD-IQ1_S") returns the saved 32768, while the same call without the variant returns remembered: false and falls through to DEFAULT_MAX_SEQ_LENGTH (4096). Storing the variant on the thread row is the right fix, and for local GGUF directory chats it works cleanly.
One issue in the new Hub branch of chatModelSwitchMeta. It returns:
{ source: 'hub', isLora: false, ggufVariant: 'UD-IQ1_S', isGguf: true }
with no isDownloaded. In stageOrLoad that makes wantManagerStage true, so an already-downloaded model gets routed through the download manager instead of loading directly:
const wantManagerStage =
wantManagerDownload ||
(selection.source === "hub" && hasGgufSource(selection) && !selection.isDownloaded);
if (wantManagerStage) { setPendingHubAutoLoad(...); return; }It does recover — the pendingHubAutoLoad effect calls downloadManager.requestStart, the job completes immediately for a cached repo, and onComplete loads with the right variant and context. Tested in the UI on unsloth/qwen3.8-27b-gguf UD-IQ1_S: a "Downloading model" toast appears for a model with nothing to download, then it loads correctly. That toast is what the deleted comment was guarding — "Already on disk: without this the load shows a download progress bar for a model that has nothing to download."
Two requestStart outcomes don't recover, though: conflict (an earlier partial download on a different transport) and busy both toast and return without loading, where main loaded unconditionally. Narrow, but it's a new way for switch-back to do nothing.
isDownloaded: true on that branch fixes it. Worth considering dropping the synthesized source: "hub" instead — wantManagerStage and isDownloadableHubRepo both gate on source === "hub", and /api/models/list already gives selectModel the isGguf it needs, which is why the old code returned undefined here. { ggufVariant } alone would carry the fix without opting out of the resolver.
The test can't catch this — assert.deepEqual(..., { source: "hub", isLora: false, isGguf: true, ggufVariant: "Q8_0" }) pins the current shape exactly, so adding isDownloaded would fail it. A test over the selection → stageOrLoad predicate would be more useful than one over the meta shape.
Smaller notes:
meta.configis redundant.stageOrLoadalready doesselection.config ?? rememberedConfigFor(selection), which is the sameresolveInitialConfig(id, ggufVariant)lookup — I checked, the two objects aredeepEqual. Dropping it also removes thelocalStoragedependency that forced the new fake in the test file.shouldPersistResolvedQueuedModelre-checks!queuedCheckpoint, which the caller already returned on four lines earlier.resolveChatModelSwitchTargetnever recovers a variant for a Hub repo id — the basename has no quant token. So existing chats onunsloth/…-GGUFstill switch back at 4096; only chats created after this lands are fixed. Worth stating in the description.local-model-options.ts: settingisDirectGguffor.ggufpaths is load-bearing here (and incidentally fixesselectionMeta.isGgufbeing false for single-file GGUF picks in the chat picker). WideningisGguftomodel_format === "gguf"is a separate change that affects the picker's format filter and row tags for GGUF directories — probably worth splitting out or calling out.createChatModelHistoryReader.applyUpdatefires on everyCHAT_HISTORY_UPDATED_EVENTfor the thread, including renames and archives, returning a fresh object each time — three re-renders for one model read in my test.
89884cf to
2f102ba
Compare
|
Thanks @Lyxot, all of it is addressed and the branch is rebased onto latest The Hub branch and the download manager. Took the second option: The predicate, and the test over it.
Not fixed: the variant for a pre-existing Hub chat. One thing the rebase added: Verification: |
chatModelSwitchMeta synthesized source: "hub" for a Hub repo id, which is what stageOrLoad keys the download manager off. An already-cached model was routed through downloadManager.requestStart, and its conflict and busy outcomes toast and return without loading, so the switch back did nothing. The Hub branch now carries only ggufVariant: /api/models/list already supplies isGguf and isLora, and selectModel derives the GGUF flag from the variant. stageOrLoad wrote the same staging condition twice; both are now wantsDownloadManagerStaging in utils/model-download-staging.ts, alongside the three predicates it composes, so a test can load it without the whole store. Other review items: meta.config is gone, since stageOrLoad already falls back to rememberedConfigFor, the same resolveInitialConfig(id, ggufVariant) lookup; shouldPersistResolvedQueuedModel drops the queued-checkpoint check its caller returned on four lines earlier; createChatModelHistoryReader compares the model before emitting, so a rename or archive event no longer re-renders the notice; and chatLocalModelOptions goes back to main's isGguf, keeping only the isDirectGguf widening this fix needs. The meta-shape assertions are replaced by a test over the selection that handleCheckpointChange builds and the staging predicate stageOrLoad applies to it.
2f102ba to
5fa414c
Compare
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 5fa414c37a
ℹ️ 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".
| "title": ("title", patch.get("title")), | ||
| "modelType": ("model_type", patch.get("modelType")), | ||
| "modelId": ("model_id", patch.get("modelId")), | ||
| "modelGgufVariant": ("model_gguf_variant", patch.get("modelGgufVariant")), |
There was a problem hiding this comment.
Clear the variant when patching to a different model
When a thread already stores a GGUF variant, a valid PATCH containing only a new modelId updates model_id but leaves model_gguf_variant attached to the old model. This differs from the new upsert logic, which explicitly clears the variant when the model changes. Such a row makes ChatModelNotice pass the stale quant to the new model during “Switch back,” potentially loading the wrong artifact or failing the load. Clear model_gguf_variant when modelId changes unless the patch supplies a replacement variant.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
No caller sends that patch. The only two writers of modelId on an existing row both send modelGgufVariant in the same PATCH: persistResolvedQueuedModel in chat-adapter.ts ({ modelId, modelGgufVariant }) and the queued-run correction in thread.tsx (modelGgufVariant: runSettingsAtQueueStart.activeGgufVariant).
Both are typed string | null, updateChatThread does JSON.stringify({ ...patch }) so an explicit null survives the wire, and patch_thread reads the body with model_dump(exclude_unset = True), so the key is present and update_chat_thread writes model_gguf_variant = NULL. Every other updateStoredChatThread call patches title, archived, projectId, settings or a container id, and the route is the only caller of update_chat_thread in the backend.
The upsert CASE is not there to clear the variant on a model change: plain model_gguf_variant = excluded.model_gguf_variant already does that. It exists to preserve the variant on a same-model save from a client that does not send the field. A modelId-only PATCH is not a shape the app produces, so there is no stale-quant row for ChatModelNotice to read.
|
@codex review |
|
Codex Review: Didn't find any major issues. What shall we delve into next? Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
Lyxot
left a comment
There was a problem hiding this comment.
All addressed — verified against f040a3db4b rather than by reading the diff.
The Hub branch. chatModelSwitchMeta returning { ggufVariant } and nothing else puts the pick back on the path a bare-id switch took before, and wantsDownloadManagerStaging now answers false for it while still answering true for a genuinely uncached Hub GGUF — so staging wasn't disabled wholesale. Agreed this is the better of the two options: isDownloaded: true would have asserted something the notice can't know, and /api/models/list carrying undownloaded default_models is a case I hadn't considered.
Confirmed the load path is intact downstream, which is the part the PR doesn't touch: with no isGguf on the meta, use-chat-model-runtime.ts derives it from explicitIsGguf ?? (ggufVariant != null || …), so the pick still loads as a GGUF and stageOrLoad's rememberedConfigFor resolves the saved context off (id, ggufVariant).
The test. Reintroduced the exact defect ({ source: "hub", isLora: false, ggufVariant, isGguf: true }) and switching back to a hub GGUF loads it instead of staging a download fails, along with a saved GGUF variant is carried back exactly. It guards the behavior, not the shape.
The rest. meta.config dropped and still resolved by stageOrLoad; shouldPersistResolvedQueuedModel down to the thread alone; the reader emits once for a model read plus two unrelated thread updates instead of three; isGguf in local-model-options.ts back to what it was, with only the isDirectGguf widening kept. The wantsDownloadManagerStaging extraction is a faithful move — isLocalModelPath's regex is unchanged and the composed predicate is equivalent to the two duplicated expressions it replaces. Carrying modelGgufVariant on ThreadCreationClaim is a good catch on the rebase; without it the row would pair a claimed model with a store-read variant.
Checks: chat-remembers-its-model.test.ts 25 pass, npm run typecheck clean, backend test_chat_history_{storage,routes}.py 90 pass, test_multi_chat_prompt_queue_contract.py 13 pass. Merges clean into current main.
Two things I'd leave alone, noted only so they're on the record:
- The "Downloading model…" toast and 0% progress bar still appear on a Hub switch-back, since
isDownloadedisfalsegoing intoselectModel. That's identical to the behavior before this PR, so it's pre-existing rather than introduced — worth a separate issue if it's worth fixing at all, as a correct fix needs a cache probe the notice doesn't have. - The
pre-commit.cicommit reformatted an assert intest_health_answers_within_probe_budget.py, which this PR doesn't otherwise touch. Harmless, just unrelated diff noise.
Agreed on not guessing a variant for pre-existing Hub chats — a wrong guess would load a quant the chat never ran and pop the notice on a chat already sitting on its own model. Good that it's stated in the description.
LGTM.
…load (unslothai#15139) The model picker, the compare pane and auto-load each built two payloads from the same settings: one for the `/validate` preflight and one for `/load`. `validateModel` then re-serialized the first through a hand-kept allow-list. That is 13 payload literals across `use-chat-model-runtime.ts`, `shared-composer.tsx`, `chat-adapter.ts` and `chat-api.ts`, and every new load setting had to be added to each one. The history shows the copies drifting apart: - unslothai#9410 added Checkpoints and the draft KV dtype to every load and never to the allow-list. - unslothai#13596 (vLLM/SGLang KV dtype, seed, memory limit) had to edit the picker, compare and `chat-api.ts` separately. - The managed-engine offer (unslothai#13135, then unslothai#13229) and GGUF settings preservation (unslothai#9562, then unslothai#11311) each landed on the picker first and needed a follow-up PR for compare and auto-load. The preflight exists so Studio refuses a load before it unloads the working model, and also to guard training. When `/validate` judges a different command from the one `/load` runs, it approves a load that `/load` then refuses after the unload, or refuses one that would fit. ## Changes - **One request, sent twice.** Each path builds one `LoadModelRequest` and sends it to both `/validate` and `/load`. Only the load-only fields are added at the `/load` call: request id, lease, force flags and `alongside`. - **The allow-list is gone.** `/validate`'s body is the load request; the route ignores load-only fields. `validateRequestBody` fills defaults for the non-nullable fields only. - **`llamaServerLoadFields`** owns the one rule for llama-server's knobs, which the three paths used to spell out with slightly different gating: - reasoning budget, batch sizes, server tuning and pass-through args are sent for GGUF only; - diffusion GGUF requests omit custom reasoning overrides, server tuning and pass-through args, while still forwarding batch sizes; - blank values are omitted, never sent as null. - **The picker re-baselines once.** On a model switch it re-baselines its per-model settings before `/validate`, instead of mirroring that reset in a second set of `validate*` variables. - **New module.** `lib/load-request.ts` holds the three helpers. Production code is 225 lines shorter. ## Preflight and load now agree - **The three dropped settings now reach `/validate`.** `validateModel` dropped `ctx_checkpoints`, `spec_draft_cache_type` and `tensor_split`. Checkpoints affect sizing; a load with Checkpoints set was priced at the default 32. Forwarding the draft KV dtype and GPU split makes validation apply the same explicit-setting precedence over inherited flags as loading. The training coexistence guard does not directly price draft KV memory. - **The picker and compare preflights now send the speculative mode and depth.** They omitted `speculative_type` and `spec_draft_n_max`, so validation used the default Auto mode, which already counts some drafters but can differ from the selected mode. The preflight now receives the same selected values as loading. Auto-load already sent them. - **A model switch with a staged run-settings config is now sized like the load.** The picker's preflight used Auto layers and no context pin, while `/load` used the staged layer count and context length. - **Compare and auto-load no longer send llama-server's pass-through args or tuning to a diffusion GGUF.** The diffusion runner takes none of them, and the picker already left them out. ## Validation - **Wire check:** the same GGUF request was sent through the real `chat-api.ts` of each checkout, comparing what `/validate` receives with what `/load` receives. On `main`, `/validate` is missing `tensor_split`, `spec_draft_cache_type` and `ctx_checkpoints`; here it is missing nothing. - **Contract test:** `chat-load-request-one-builder.test.ts` reads `ValidateModelRequest` from `studio/backend/models/inference.py`. It fails if any field it prices cannot ride `LoadModelRequest` or is not forwarded. It also table-tests the llama-server knob rule and checks that every path sends one request. - **Frontend:** `npm test` gives 13,857 passed. The 3 failures are HTML/TextEdit charset decoding tests that fail the same way on `main` in this environment. Typecheck is clean with both `bun check` and `tsc`. - **Python contract tests:** the 30 files in `tests/studio` that read these sources give 807 passed and 63 skipped. The two Playwright files cannot import here, on `main` too. - **The auto-load harness** (`test_chat_autoload_failure_gate.py`) now inlines the real `load-request.ts` instead of a copy; all 81 scenarios pass. - **Rewritten tests:** text-matching tests that counted the duplicated literals now assert one request per path. The rule they pinned is tested behaviourally in the new file. | Case | Before | After | |---|---|---| | GGUF load with Checkpoints, draft KV dtype or a per-GPU split | `/validate` sent none of the three; used default checkpoints and could resolve inherited flags differently | Same fields as `/load` | | Picker or compare load with a DFlash/DSpark drafter | Preflight sized Auto rather than the selected speculative mode | Selected mode forwarded, as in `/load` | | Model switch from a staged config with a context length and manual layers | Preflight sized Auto context and Auto layers | Sized like `/load` | | Compare or auto-load of a diffusion GGUF with remembered extra args | Args and tuning sent to a runner that takes none | Not sent, as the picker already did | Not in this PR: auto-load still ignores a model's saved engine (vLLM/SGLang) and loads it on the default engine. That looks deliberate (background loads avoid starting a managed engine), so it is left as is. --------- Co-authored-by: Daniel Han <[email protected]>
Fixes #9546.
Persist each chat's GGUF variant in
chat_threadsand carry the resolved variant through queued model selection.ChatModelNoticenow switches with the saved variant and restores its per-model context and llama.cpp settings instead of falling back to a 4096-token load.Recover legacy GGUF variants only when one saved config matches the quant in the local model path. Ambiguous or unproven variants stay unset.
Keep history updates thread-scoped so queued initialization cannot leave the notice on stale model metadata. Backfill resolved queued models only for fresh empty thread rows.
chatModelSwitchMetacarries only the GGUF variant for a Hub repo id./api/models/listalready suppliesisGgufandisLora, and a synthesizedsource: "hub"would send an already-downloaded model through the download manager, whoseconflictandbusyoutcomes toast and return without loading.Scope
A pre-existing chat on a Hub repo id such as
unsloth/Qwen3-4B-GGUFstill switches back at 4096.resolveChatModelSwitchTargetrecovers a variant only from a quant token in the model path, and a Hub repo name has none, so guessing between saved configs would load a quant the chat may never have run. Chats created from this change onward record the variant on the thread row and are unaffected.chatLocalModelOptionssetsisDirectGguffor.ggufpaths, which is what keeps a single-file GGUF loading as one.isGgufis left as it was on main: widening it tomodel_format === "gguf"changes the picker's format filter and row tags for GGUF directories, which is a separate change.Checks
ruff check studio/backend/routes/chat_history.py studio/backend/storage/studio_db.py studio/backend/tests/test_chat_history_routes.py studio/backend/tests/test_chat_history_storage.pypython -m pytest -q tests/test_chat_history_storage.py tests/test_chat_history_routes.py(81 passed, run before the rebase onto main; the backend diff is unchanged since)npm run typechecknode --experimental-strip-types --testover the 68 frontend test files that read the changed modules (1084 passed)git diff --check