Repository navigation
studio: stop prompting to stop chats for a model already loaded - #8943
danielhanchen merged 37 commits into
Conversation
Picking the model that is already resident raised "Stop N running chat?" and reloaded it. selectModel decided whether a pick needed a load by comparing the picker row id against status.model_identifier, and only when the current checkpoint was an external provider. A cached row pinned to a snapshot dir loads by path while its row keeps the repo id, so the two sides hold different strings for one model and the resident model read as a different one. /load answers already_loaded ahead of its cancel hook, so nothing was ever going to be stopped. residentModelMatchesPick matches a pick against the resident model on either name each side holds (id / load path against active_model / model_identifier), normalized through normalizeModelIdentity so Windows paths compare by case and separator, and gated on the GGUF variant so a quant switch stays a real reload. The residency check now runs for any pick that does not force a reload, not only when the checkpoint is external. Verified end to end against a Studio instance with an MLX model loaded by snapshot path: re-picking it mid-generation raised the dialog before the change and adopts silently after, with the chat running to completion. Fixes unslothai#8893
residentModelMatchesPick hand-rolled the comparison that model-identity.ts already exports. It now uses residentModelIdMatches, modelIdsMatch and ggufVariantsMatch, the same pair hub-page.tsx compares a resident model with, which also collapses a snapshot path onto its repo id through publicModelId. A standalone .gguf is exempt from the variant comparison. The backend derives hf_variant from the filename for a direct path load and /status echoes it, while the picker row deliberately carries none (settingsGgufVariantForRow), so comparing the two left unslothai#8893 unfixed for On Device files: the variant alone answered "not resident" for the file that was loaded. The source-scan test now asserts the residency check is not gated on an external checkpoint again, which is the shape the bug had. Verified it fails against that shape and passes here.
Matching the pick against status.active_model treated any snapshot of a cached repo as the resident one. The public id is the same for every snapshot, while _repo_gguf_load_id repoints load_id at the newest by mtime, so a repo that advanced under a resident older snapshot read as resident and selectModel skipped a load that would have replaced stale weights. LlamaCppBackend.matches_load_source settles it on the raw identifiers, so residentModelMatchesPick now does the same: when status reports a model_identifier it has to equal what this pick would send as model_path, and the public-id alias is left for a native-lease load, which withholds the raw path and reports only its display label.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
unsloth/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts
Lines 684 to 685 in fe3e29e
When switching back from an external provider to a resident cached repo whose loadPath is a pinned snapshot, activeLoadId contains that snapshot while modelId is the public repo ID, so this condition always clears the valid pin immediately after residentModelMatchesPick verified it. For repos outside the active cache, the public ID deliberately does not resolve; a subsequent Reload/Apply reads the now-null activeLoadId and sends the unusable repo ID instead of the snapshot path. Compare the stored pin with loadPath, preserving it when it names the resident snapshot.
unsloth/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts
Lines 687 to 689 in fe3e29e
When re-adopting a standalone .gguf after an external-provider selection, the new matcher intentionally accepts the picker’s null variant against the quant derived by the backend, but this call then stores that derived residentStatus.gguf_variant. Standalone files are deliberately keyed as <path> rather than <path>:<quant>; after this return, the picker no longer considers its null-variant row the same loaded selection and per-model config resolution can use the wrong variant-qualified identity. Set the checkpoint variant from the pick (ggufVariant) for this path rather than reintroducing the backend-only label.
ℹ️ 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".
The adopt path cleared activeLoadId behind a condition that could never be false: both writers store the pin only when it differs from the id it was recorded against, so activeLoadId is either null or never equal to modelId. A pinned cached row therefore lost its snapshot pin the moment the pick was recognised as resident. Write the pin a completed load writes instead. The stale-pin case the old comment describes is still covered, since a pin taken for an earlier resident is overwritten either way.
|
Fixed in e8c3f9b. The condition was vacuous: both writers store activeLoadId only when it differs from the id it was recorded against (use-chat-model-runtime.ts:1508, chat-adapter.ts:2924), so it is either null or never equal to modelId, and the branch was an unconditional clear. The adopt path now writes the pin a completed load writes, loadPath === modelId ? null : loadPath, which still overwrites a pin taken for an earlier resident. One correction on the stated impact: a later Apply did not send the repo id. applyActiveModelStatusToStore runs immediately after and rewrites params.checkpoint through mergeBackendRecommendedInference({ modelId: checkpointId }) to resolveInferenceCheckpointId(status), so handleReloadActiveModel already had a loadable identifier. Verified on a running Studio with a snapshot-pinned MLX model: the send payload after the adopt carried the snapshot path, matching the state after a real load. The pin is worth keeping regardless, so the change stands. |
|
Codex Review: Didn't find any major issues. Delightful! Reviewed commit: ℹ️ About Codex in GitHubCodex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
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". |
… model Adopting on identity alone dropped a remembered config. The chat picker and Hub's Run button both pass one WITHOUT forceReload (chat-page.tsx stageOrLoad, hub-page.tsx handleRun), selection.config is only read inside performLoad, and the short-circuit returns before it. llama-server would have reloaded for any of those settings, so a remembered context length, KV dtype, drafter, slots, batch size, placement or extra arg silently did nothing, and the rollback to previousConfig made the panel agree with the server either way, so there was nothing on screen to say so. residentRuntimeMatchesConfig compares a pick's config against the invocation /status echoes, over the fields LlamaCppBackend._runtime_matches_intent reloads for plus the MLX pair _mlx_runtime_settings_match compares. A field the config leaves unset expresses no opinion, so a model the user never configured still adopts the resident copy and 8893 stays fixed; one the user did configure adopts it whenever the two already agree. Anything the status cannot report counts as a difference: answering "differs" costs one reload, which is what happened before any of this existed, while a wrong "matches" loses a setting invisibly. Three smaller ones on the same path: - a native pick no longer takes the short-circuit. It names its file by a bare label two different files can share, and the lease is written only by a completed load (activeNativePathToken, beside the pin), so adopting here would have kept a stale token. Every native call site forces a reload already; this pins the invariant where it can be seen. - the rollback uses restorePreviousConfig() rather than an inline apply, so it carries the loadedIsDiffusion flag the helper passes. Without it a resident image model restored its config through the wrong branch of applyPerModelConfigToRuntime. - the pin comment claimed applyActiveModelStatusToStore rewrites params.checkpoint. It writes residentCheckpoint; the caller sets the checkpoint one line earlier. The pin change itself stands. Tests: resident-config-match covers every compared field in matching, differing and not-reported form, plus the three states of llamaExtraArgs and the ordering rules (GPU ids are a set, argv is not). resident-model-match-matrix runs the identity comparator over Linux, macOS, Windows drive, UNC, WSL, relative, tilde, rooted, Unicode and spaced path shapes, against current, older and native-lease status shapes, and pins the /mnt/<letter> case fold as a known WSL-shaped limit.
|
Reviewed this end to end and reproduced the report first, so the fix is anchored to something real. The bug reproduces exactly as describedOn a build of this PR's own merge base ( Two things make it fire, and the PR is right about both. The pinned row loads by path, so One real regression, now fixed in 0c0013bWidening
Three smaller ones on the same path:
What I checked
Known limit, pinned in a test rather than left to be rediscovered: Before and after screenshots to follow. |
|
Shot this before/after from two isolated installs, head The moment is a new chat re-picking Staging, because the pair is worthless without it. The repo is seeded under the legacy HF root while
That is the mismatch the report needs, and the scene refuses to run if the row comes back unpinned, since an unpinned row makes both sides agree for a reason that has nothing to do with this change. Measured at the pick, one active generation on both sides:
The load count matters as much as the dialog: AFTER neither prompted nor reloaded, so the absence of the dialog is a skipped load rather than a silent one. Control, same still-generating state, both sides: picking a different cached repo ( Two notes on how it was run. The model is loaded with |
|
Before and after, from two isolated
Same flow in all three enginesDriven live against the head build, each with a positive control:
The control matters as much as the pass: without it, an engine where the click silently missed would look identical to one where the fix worked. Two things I got wrong building this, worth knowingNeither was a defect in the PR, and both had me briefly believing there was one. The picker's "Loaded" tag is not a signal of adoption. I first asserted that only AFTER would wear it after the pick, and that assertion failed a build that was behaving perfectly. Adoption does set it, since Nothing caps a chat reply. |
residentModelMatchesPick settles residency on status.model_identifier, which names one revision. When the status carries no raw identifier it falls through to residentModelIdMatches, and that collapses a snapshot dir onto its repo id. Every snapshot of one repo publishes the same public id, so a pick pinned to a different revision read as already resident and the load was skipped, leaving the user on the weights that were there. This file's own docstring names that hazard for the arm above it; the arm below still had it. Two shapes reach it. A backend old enough to predate model_identifier, and a native-lease load, which withholds the raw path on every version by design. A literal match on the name the pick would load by still settles it, so an older backend that put the raw path in active_model keeps adopting. What is refused is only the collapse, and only for a pick naming a cache snapshot, which is where the id cannot distinguish revisions. A native lease, a standalone .gguf and an unpinned repo id are unaffected. Found by fuzzing the function against LlamaCppBackend.matches_load_source over the cache layouts of each supported host: across 355 pairs these rows were the only ones the frontend adopted and the server would have reloaded.
… fields residentRuntimeMatchesConfig reads the GPU fields, so the host it runs on is a real axis even though it compares no paths: CUDA and ROCm report a placement pool and an offload mode, a CPU-only host reports manual with zero layers, and an MLX server reports none of them and a KV width instead. Each accelerator is crossed with every setting a remembered config can pin, in all three states that matter: the resident load already runs it, it runs something else, and the status cannot report it at all. The last one is the direction that must never read as agreement. Also covers config blobs written by older Studio versions, which simply lack the keys a newer field uses, and asserts placement compares as a set rather than an order. The structural test is the one that lasts. It parses PerModelConfig and fails when a field is added without being either compared or listed as deliberately excluded, so a new setting cannot be silently dropped by an adopted pick.
|
Ran this one hard before merging and pushed two commits: one fix, one test sweep. Everything below is against head The one real defect
Two shapes reach it: a backend old enough to predate Fixed in How it was foundFuzzed After the fix: 0 pairs adopted that must not be, 0 pairs looser than the backend beyond separator style and trailing separators (which name one file), 41 stricter (all of them a quant change or a case-differing POSIX path, where reloading is the safe answer), and 0 drift between Worth recording, since it looks alarming and is not: What was tested
Does it break the old pathsNo, and the shape of the change is why. Every arm can only answer "reload" more often than before, which is exactly the behaviour that existed before any of this. No hardware path changed: this is frontend TypeScript, and the GPU fields it reads are compared, never driven. The accelerator axis is covered above as data rather than as hardware, because that is all the function sees. One thing left as a note, not a change
|
residentRuntimeMatchesConfig treated speculativeType, gpuMemoryMode, gpuLayers and nCpuMoe as unpinned when the remembered config left them unset. applyPerModelConfigToRuntime resolves all four before the load runs (readPersistedSpeculativeType, readPersistedGpuMemoryMode, GPU_LAYERS_AUTO, 0), and selectModel sends the resolved value, so an unset field is not silence: a real /load would have carried the standing preference and could differ from the resident server. Compare the resolved value on both sides instead. The caller supplies the four defaults plus normalizeSpeculativeType, so the module stays a leaf the node suite can drive.
Same code, fewer lines of prose: the four 150 to 200 char single-line comments in selectModel are wrapped, and the docblocks that restated the same point twice say it once. 62 fewer comment lines across the seven files this PR touches. Verified by AST comparison rather than by eye: each file is parsed with the TypeScript compiler and reprinted with removeComments, and every one of the seven is identical to its previous revision. Suite still 3067 pass / 0 fail, tsc clean, and no new biome findings (the two in use-chat-model-runtime.ts are pre-existing at head).
residentRuntimeMatchesConfig treated an unset customContextLength, kvCacheDtype, mlxKvBits, specDraftNMax, nParallel, nBatch, nUbatch, chatTemplateOverride or selectedGpuIds as no opinion. It is one: applyModelLoadConfigToRuntime writes the config over the runtime store before selectModel runs (chat-page.tsx:3242, hub-page.tsx:1329) and resolves each of these with ?? null, so the snapshot performLoad takes reads null rather than inheriting the resident model's value. A real /load would send null and the backend would size the model from scratch, which is a different invocation from a server pinned to an explicit context, KV dtype, slot count, batch size, template or GPU. llamaExtraArgs stays conditionally pinned: it is the one field with no ?? null fallback, so undefined really does mean this copy never read it. The accelerator fixtures move with it. A default load requests no particular GPU and no MLX KV width, so those bases echo null; a pinned pool and a pinned width are swept as fields like everything else.
Two things the resident shortcut let slip. maxSeqLength is a client-side generation cap that no status field echoes, so applyActiveModelStatusToStore cannot correct it and the rollback that makes the panel agree with the resident server has the last word. That rollback carries the OUTGOING model's cap, so re-picking a resident model after an external provider silently changed truncation. Re-apply the pick's own cap after the rollback. _runtime_matches_intent deliberately answers False for a retryable drafter failure so the next identical load repairs it. Skipping the load suppressed that and left speculation off with nothing to retry it. residentSpeculativeNeedsRepair declines the shortcut for the reasons the backend actually retries, drafter_not_found and the two binary stand-downs, and only when the pick asks for a drafter at all. The Auto-mode policy downgrades are excluded on purpose: they never repair, so treating them as retryable would prompt to stop running chats on every re-pick, which is the bug this PR fixes.
…s for PR unslothai#8943 Two ways the resident shortcut could skip a load the backend was going to perform. performLoad sends reconcilePersistedGpuIds(selectedGpuIds, selectedGpuIndexKind), not the saved pick: a selection saved in another index namespace, or naming GPUs that are gone, becomes Automatic before /load. The residency comparison read the raw ids, so a saved physical [1] adopted a server pinned to Vulkan device 1, and an unreconcilable pick reloaded where the load would have agreed. The reconciler is passed in with the device cache warmed first, since load-on-selection can run before any GPU hook mounted and a cold cache passes the pick through unvalidated. adopt_load_intent_if_matched forces a reload when memory_state_satisfies_settings fails or the launched VRAM fraction differs from the active one. Both are server-wide, so a Model Memory or budget save between two picks of one model leaves the pick, its config and the status identical, and the setting never reached the child. The gate now reads both reload_required flags, and only an explicit true declines, so a failed read or a backend without the endpoints keeps the shortcut exactly as it was.
…8943 _reuse_loaded_gguf refuses its own already-loaded answer while _audio_probed is false, so load_model reaches its fast path and re-probes there. Nothing else re-probes, so a shortcut that skips /load leaves the model's audio capabilities undetected for as long as the server runs. That is a silent loss rather than one extra reload, which is why it is worth a status field. audio_probe_pending is reported with the same True default the route reads it with, so a backend that never tracked the probe is not mistaken for one with an outstanding probe, and only an explicit true declines the shortcut. The check sits inside the residency verdict, so the re-read before adopting judges it again.
…r PR unslothai#8943 The two failures are not symmetric, which is what my original wording missed. One extra reload costs the prompt this PR removes; adopting on a read that failed right after the user changed the Model Memory policy or the VRAM budget leaves the child on the old one with nothing on screen to say so. An absent route is still not a failed read, so a backend too old to serve either keeps the shortcut. Both fetchers now raise SettingsRouteAbsentError on a 404, and the budget reader gained a rethrow option for the one caller that has to tell them apart: it answers null for both, which every other caller is right to treat alike, since they paint rather than decide. The predicate takes three states now instead of a nullable one. Two source-shape tests move with it. The VRAM one pinned the catch as having no binding; the residency one anchored its slice on the first in the file, which is above that branch now.
…r PR unslothai#8943 The two failures are not symmetric, which is what my original wording missed. One extra reload costs the prompt this PR removes; adopting on a read that failed right after the user changed the Model Memory policy or the VRAM budget leaves the child on the old one with nothing on screen to say so. An absent route is still not a failed read, so a backend too old to serve either keeps the shortcut. Both fetchers now raise SettingsRouteAbsentError on a 404, and the budget reader gained a rethrow option for the one caller that has to tell them apart: it answers null for both, which every other caller is right to treat alike, since they paint rather than decide. The predicate takes three states now instead of a nullable one. Two source-shape tests move with it. The VRAM one pinned the catch as having no binding; the residency one anchored its slice on the first catch-with-binding in the file, which is above that branch now.
d5ba940 to
6b94038
Compare
…nslothai#8943 The drafter_not_found arm of _runtime_matches_intent is guarded on intent.gguf_path being None, and the route derives that field from the identifier alone, so a directly loaded file dedupes rather than retrying the fetch. Declining the shortcut for it reproduced the prompt this PR removes. The caller now tells the repair check whether the pick sends a path, using the same endswith(".gguf") test the route uses rather than the stricter isStandaloneGgufPath, which also demands a path-like shape. Only this arm is excused: a binary stand-down, a DFlash retry and the capability probe all repair whatever the pick names. I recorded this one as remaining looseness when the rest of the arm was mirrored, so this closes it.
… dropped for PR unslothai#8943 Two consequences of adopting where the backend would, without the side effects the backend performs while adopting. adopt_load_intent_if_matched records the incoming pool when it accepts a fitted subset (_record_matching_gpu_request), so the user's narrower pick becomes the request. Skipping /load skips that, and the hydration then put the status's wider pool back, restoring a GPU the user had removed. The pick's own reconciled selection is re-applied after the hydration, in the same place and for the same reason the sequence cap already is. diffusion_requested_ngl retains the request even when an older shim ignored the split, so once the installed shim gains --ngl support the same request has to go through and finally apply it. _runtime_matches_intent rejects it for exactly that window, and the comparison saw only the retained value. diffusion_split_supported is published for it, answered only for a diffusion runner, since off one there is no split to apply and False would claim the question was asked.
…i#8943 The tensor-parallel arch-gate excuse read the raw tensorParallel toggle while the backend's comparator reads resolve_tensor_parallel, so a config asking for a split through --split-mode tensor missed the excuse it exists for. parse_gpu_layers_override now reports absent, a value, and malformed as three states. The backend raises on a malformed override, so the load fails and says so; folding it into "no override" stripped the token, found the rest agreeable and adopted, losing the saved setting in silence.
The rollback before hydration restores the outgoing model's config, so the slot and batch controls in the store belong to the model the tab just left. The adopt path suppressed the model-change reseed, so a resident model running 4 slots could show the outgoing count, and the next Apply saved that over it. Every other load parameter at that call site already treats a changed checkpoint or variant as a model change, and the slot pair now does too.
|
@codex review |
|
Codex Review: Didn't find any major issues. Nice work! Reviewed commit: ℹ️ About Codex in GitHubCodex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
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". |
|
Heads up: this merged with The failing assertion is This PR changed that line to: and removed The reason I am not just pushing a fix is that I cannot tell from here which way you want it, and the two answers are materially different:
Given the PR is about not prompting to stop chats for a model that is already loaded, option 1 looks likely, but the slot-control reseed is a separate user-visible behaviour from the prompt, and I would rather ask than guess at someone else's intent. Happy to push whichever you prefer, or leave it with you. The only thing I would ask is that it lands soon, since main being red blocks the whole queue. One process note, said neutrally: this is the second stale source-shape contract test to reach main this week, after the prompt-queue one that #9026 repaired. These tests assert exact source strings, so any reformat or refactor of the line breaks them without the behaviour changing, and the failure gives no hint which of the two it is. Worth a separate look at whether they should assert behaviour rather than text. |


Fixes #8893.
Picking the model that is already loaded raised "Stop N running chat?" and reloaded it, killing a reply that was still streaming in another chat.
selectModelinstudio/frontend/src/features/chat/hooks/use-chat-model-runtime.tsdecided whether a pick needed a load by comparing the picker row id againststatus.model_identifier, and only when the current checkpoint was an external provider. Those two strings name the same model but need not be equal: a cached row pinned to a snapshot dir loads by path (_repo_gguf_load_idinstudio/backend/routes/models.pysetsload_idwhenever the repo id will not resolve on its own) while its picker row keeps the repo id, and/api/inference/statuspublishes the clean public id next to the raw load identifier. The resident model therefore read as a different one, and the confirmation fired for a load that/loadwould have answeredalready_loadedwithout touching llama-server.What changed
residentModelMatchesPickin the newstudio/frontend/src/features/chat/lib/resident-model-match.tsanswers whether the resident model is the one a pick names. It matches on either name each side holds, using the comparatorsstudio/frontend/src/features/hub/lib/model-identity.tsalready exports and thathub-page.tsxcompares a resident model with:residentModelIdMatches(status.active_model, pick.id, pick.loadPath), which also collapses a snapshot path onto its repo id throughpublicModelIdmodelIdsMatch(status.model_identifier, ...)for the raw load identifierggufVariantsMatch, so a quant switch within one repo stays a real reloadA standalone
.ggufis exempt from the variant comparison. A direct path load deriveshf_variantfrom the filename and/statusechoes it, while the picker row deliberately carries none (settingsGgufVariantForRow), so comparing the two answered "not resident" for the exact file that was loaded.selectModelnow runs the residency check for any pick that does not setforceReload, instead of only when the checkpoint is an external provider. Applying settings still reloads and still prompts, because a staged config always carriesforceReload.Before and after
Re-picking the loaded model while another chat is generating:
Picking a genuinely different model still prompts:
Checks
Verified end to end against a running Studio with
mlx-community/Qwen3-0.6B-4bitloaded from a cache whose repo id does not resolve, so the row id and the load path differ the way the report requires./api/inference/statusreportedmodel_identifieras the snapshot path.POST /api/inference/loadsent before the change, neither after, with the reply running to completion.active-generationsconfirmed at 1 at the moment of the pick in both runs.node --experimental-strip-types --test "tests/**/*.test.ts": 2711 pass, 0 fail.tsc -bandtsc -p tsconfig.test.json: clean.No Python changed, so ruff and pytest do not apply. GPU-specific checks were not run: this is a frontend change, exercised on Apple Silicon MLX inference.