Repository navigation
Studio: choose Off, When they fit or Always in Model memory, and keep the chat context when an image or video model takes the GPU - #14108
Merged
danielhanchen merged 95 commits intoOct 19, 2026
Conversation
…oads behind a chat load under Always, release CHAT after a CPU fallback
… arbiter that tracks residents Stores the mode in the owner's database with a bool-first migration, extends /api/settings/multi-model, and gives acquire_for a policy, an eviction report and per-owner residents. Adds the response fields, the MCP mode read, the padded-error headers and the structured out_of_memory check.
… the chat context when an image or video model takes the GPU Model memory's "Keep multiple models loaded" becomes a three-way Select (Off, When they fit, Always) with a description per value, and the image/video idle auto-unload row moves next to it. Both rows are searchable, and refusals link straight to the section. Saving the moved row no longer resends `enabled`. The Images and Video pages say what a load unloaded on their "Model loaded" toast, and a load refused under Always shows "Model not loaded" with an owner-only "Open settings" action. Refusals are recognised by the X-Unsloth-Refusal header first, then the padded body's headers, then the backend wording. When an image or video load is about to evict a GGUF chat model, the chat KV is saved first, outside every lock and within 45 s, while load-progress reports "saving_chat_context". The stash is promoted only when that model is actually evicted, is tagged by origin so a media TTL save keeps it, and is restored by the next load of the same chat model.
…inline-media-coresidency-d9c21971
…l/unsloth into studio-model-memory-modes-kv-swap
…rll/unsloth into studio-model-memory-modes-kv-swap
…ading the primary fit retry
…d report every model a load unloads Always is enforced in the arbiter for chat and media, at the primary-replace guard (same repo allowed), in the kept-slot retry loop and before the H3 image unload. The refusal answers 409 with X-Unsloth-Refusal everywhere, the OpenAI envelope on /v1 and auto-switch, and the existing 503 on /p. Chat, image and video loads list what they unloaded in evicted_slots, and callers that assumed one GPU owner now ask holds().
… the Always refusal on every surface
…io/r2-media-coresidency # Conflicts: # studio/backend/routes/inference.py # studio/backend/routes/video.py
…odel-memory-modes-kv-swap
…io/r2-media-coresidency # Conflicts: # studio/backend/routes/video.py
…rll/unsloth into studio-model-memory-modes-kv-swap
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
Collaborator
Author
…ther, and report kept models a vLLM or SGLang load retires - Arbiter: refuse_replacing_media() refuses an image or video load of another repo while one of its own kind is loaded; the image route checks it before the engine switch. - An off-torch image load that would unload a native H3 video model is refused under Always and reported otherwise. - A stale image or video claim whose load failed no longer blocks a chat load under Always. - Kept models retired by a vLLM/SGLang load appear in evicted_slots and evicted. - An unreadable setting keeps the last mode read; the video answer drops blank ids; managed accounts get the managed copy on a measured short fit.
…r video model still loading in full A chat load now passes its resolved GPUs to the arbiter, so When they fit and Always never unload or refuse over an image or video model on another GPU, and chat's recorded GPUs add up across kept chat models. A media resident still loading counts its weights too in the fit check, since live free VRAM does not show them yet. The Always out-of-memory refusal only names a model that shares a GPU with chat.
The When they fit peek follows the residency free order: chat on other GPUs stays, and an idle image or video model on these GPUs goes first. An Off route passes no policy, so the peek reads it as Off like the acquire does instead of re-reading the setting. A /v1 media call through the auto-switch no longer counts itself as chat work, and a save is dropped if Keep chat context across unloads was turned off while it ran.
…m/Etherll/unsloth into studio-model-memory-modes-kv-swap # Conflicts: # studio/backend/core/inference/chat_swap_kv.py
…, and credit a smaller replacement in full [skip ci]
danielhanchen
pushed a commit
to danielhanchen/unsloth-staging-2
that referenced
this pull request
Oct 18, 2026
danielhanchen
pushed a commit
to danielhanchen/unsloth-staging-2
that referenced
this pull request
Oct 18, 2026
danielhanchen
pushed a commit
to danielhanchen/unsloth-staging-2
that referenced
this pull request
Oct 18, 2026
danielhanchen
pushed a commit
to danielhanchen/unsloth-staging-2
that referenced
this pull request
Oct 18, 2026
Member
|
pre-commit.ci run |
# Conflicts: # studio/backend/routes/inference.py
# Conflicts: # studio/frontend/src/features/images/images-page.tsx
danielhanchen
added a commit
that referenced
this pull request
Oct 19, 2026
…eset the startup budget to the build (#14168) ## Summary Main is over the startup bundle budget, so `Frontend build + bundle sanity` fails on every PR based on it: ``` over the startup budget: transfer 2005.9 KB > 2003.5 KB, raw 6665.4 KB > 6659.1 KB (main at 2fee36f) ``` This PR takes two steps. It moves #14137's prompt upsampler client out of the startup chunks, which is real growth with a lazy home. It then resets both limits to the measured build. Main has gone over this budget repeatedly, and the root of that is a shortfall in how the limits were raised, which this corrects. ## Cause **#14137 (FLUX.3 prompt upsampling).** The Images page is lazy (`ImagesPage = lazy(...)` in `__root.tsx`), but `features/images/api.ts` is not. Startup modules import it for other calls (`loaded-models-api.ts`, `loaded-models-sources.ts`, `use-media-companion-bytes.ts`). #14137 put the four upsampler calls there, with value imports from `lib/prompt-enhance.ts`, so that module joined the startup chunks. Only `prompt-enhance-panel.tsx`, inside the lazy Images page, calls them. **The limits themselves.** Each raise since #14073 was sized from its own PR's delta and added to the previous limit. That previous limit already sat below the build, starting at #14073: - `475a02ac` measures 2,047,700 B transfer against the 2,047,608 B limit #14073 set. - By `2fee36ff` the gap is 6,500 B raw and 2,409 B transfer. The raises since (#14072, #14075, #14110, #14108, #14113) each added their delta, so the shortfall carried forward. CI agrees with my machine to the byte: the first run of this PR read 1999.7 KB transfer on both. ## Change - **New `features/images/prompt-upsampler-api.ts`:** holds `getPromptUpsamplerStatus`, `startPromptUpsamplerDownload`, `cancelPromptUpsamplerDownload` and `previewEnhancedPrompt`, moved unchanged, with the same `parseJson` error handling. - **`api.ts`:** now imports only the `PromptEnhancement` type from `lib/prompt-enhance` (erased at build). - **`prompt-enhance-panel.tsx`:** imports the calls from the new module. - **No behavior change** in the app. - **`check-bundle-budget.ts`:** both limits are reset to the measured build plus the usual margin (160 B raw, 189 B transfer), with an entry in the BUDGET comment block explaining why the reset is absolute rather than by delta. - `rawBytes`: 6,819,206 (main after #14113) -> 6,825,885. - `transferBytes`: 2,051,727 -> 2,054,261. ## Testing One machine and build, Node 24, exact byte totals from the budget script, 95 chunks throughout: | tree | raw B | transfer B | |---|---|---| | main `2fee36ff` | 6,825,378 | 2,053,999 | | main `2fee36ff` + the move | 6,821,006 | 2,052,708 | | main `78e5eefa4d` (adds #14113) + the move | 6,821,334 | 2,052,857 | | + #14183 | 6,821,410 | 2,052,614 | | + #14172 (one tooltip design) | 6,825,307 | 2,053,990 | | this PR (main `b227654927`, adds #14184, + the move) | 6,825,725 | 2,054,072 | - **The move saves:** 4,372 B raw and 1,291 B transfer. - **#14113 adds:** 328 B raw and 149 B transfer on this build. - **Landed while main was over, with no raise:** #14183 (+76 B raw, -243 B transfer), #14172 (+3,897 B raw, +1,376 B transfer, the shared tooltip is in the eager shell) and #14184 (+418 B raw, +82 B transfer). This is the treadmill the absolute reset stops: while main is red on this check, growth lands unaccounted. - **With the new limits:** `within budget (0.2 KB transfer, 0.2 KB raw to spare)`. - **`npm run typecheck`:** clean. - **`bundle-budget-cli.test.ts`, `bundle-budget-closure.test.ts`, `image-prompt-enhance.test.ts` and `loaded-models-platform-matrix.test.ts`:** 74 passed. --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
danielhanchen
added a commit
to danielhanchen/unsloth-staging-2
that referenced
this pull request
Oct 27, 2026
…the GPU (unslothai#15358) ## Summary unslothai#14108 made Unsloth Studio keep a GGUF chat model's context when an image or video load takes the GPU: the slots are saved before the eviction and restored when the same model loads again, as long as "Keep chat context across unloads" is on. An MLX chat model did not get this. Its prompt cache lives in the inference worker subprocess, which the eviction kills, so the next turn after an image or video generation re-read the whole conversation. This PR gives MLX chat models the same behavior through the same path: `chat_swap_kv` saves before the media acquire, `gpu_arbiter._evict_chat` promotes the save once it really unloads that model, `llama_keepwarm` holds it as the reload stash, and the next load of that model restores it. The "saving chat context" load phase, the 45 s save budget, the setting and the frontend are unchanged. ## What changed **MLX worker (first commit)** - `MLXInferenceBackend.save_prompt_cache_for_resume(directory)` writes the newest turn of each prompt cache store: the last entry of the mlx-lm LRU (including one held over the LRU budget), and for mlx-vlm the newest turn's boundary snapshot plus its replay snapshot. `restore_prompt_cache_for_resume(manifest)` inserts them back into the stores. - Serialization: each entry is one safetensors file. The arrays are the tensors, and the cache object layout is pickled into the metadata with the arrays pulled out by `persistent_id`. This round-trips every cache class (mlx-lm and mlx-vlm KV, rotating, quantized, TurboQuant, `CacheList`, recurrent `ArraysCache`) without a codec per class. mlx-lm's own `save_prompt_cache` resolves class names in mlx-lm's module only, so mlx-vlm caches would come back as the wrong type. Unpickling admits only classes from `mlx`, `mlx_lm`, `mlx_vlm` and `unsloth_zoo.mlx`. - A restore happens only when a fingerprint matches exactly: the model, the size and mtime of its weight and JSON files, the mlx / mlx-lm / mlx-vlm versions, the load route, KV quant bits / TurboQuant, the KV window, int8 prefill, the prefill step and the load arguments. A distributed load never saves. - New worker commands `save_prompt_cache` / `restore_prompt_cache`, answered by request id in both command loops (a backend without a prompt cache, or a batch with rows in flight, answers with an error rather than leaving the parent to time out). The orchestrator's `save_prompt_cache_for_resume(should_abort)` / `restore_prompt_cache_for_resume(manifest)` send them under `_gen_lock`. Each save gets its own directory under the new `mlx_prompt_cache_root()`, removed if the save fails or is abandoned. **Studio wiring (second commit)** - `chat_swap_kv` picks the saver for the resident chat model: llama-server slots for GGUF as before, otherwise the orchestrator when it serves an MLX model. - `_evict_chat` reads the MLX identity before unloading the orchestrator model and commits the pending save after it. - The orchestrator branch of the load route now passes the backend to `note_model_loaded` (off the event loop), and `restore_kv_resume` hands an MLX manifest to `restore_prompt_cache_for_resume`. A GGUF reload still drops an MLX stash, and an MLX reload still drops a GGUF one. - Deleting an MLX manifest also removes its directory, and the startup sweep removes leftover MLX save directories. ## Risks and tradeoffs - Only the newest turn per store is kept, not every LRU entry, to keep the save inside the budget and the disk use small. - For mlx-vlm models the restore matches what the live process had: a turn shorter than the 2048-token snapshot step only has its replay snapshot, so the next turn re-reads that conversation with or without this change. - An abandoned save stops at the parent. The worker finishes the file it is writing, so the eviction's unload can wait for that one write past the budget. Reaching this needs a cache of hundreds of GB. - The restore waits on `_gen_lock`, so if a `/v1` generation starts between the load being published and the restore, the load response waits for it. The Studio chat UI waits for the load response before it chats. - MLX idle auto-unload is out of scope; the idle loop only unloads GGUF today. ## Validation Tests for the save and restore round trip on real mlx-lm caches (newest entry only, fingerprint mismatches refused, replay flags kept, the over-budget entry), the unpickler refusals, the worker replies, the orchestrator's directory cleanup, and the swap flow through the real `_evict_chat` with a fake MLX orchestrator. Every one of 17 hand-written mutations of the guarded code fails the test that owns it. ```bash cd studio/backend python -m pytest -q tests/test_mlx_inference_backend.py tests/test_mlx_worker_audio_commands.py tests/test_swap_kv_resume.py tests/test_openai_auto_switch.py tests/test_gpu_init_crash_message.py # 1623 passed, 1 skipped ``` Real worker on Apple Silicon (M3 Max): chat, save, kill the worker, reload, restore, next turn. - Qwen3-0.6B: the next turn read 116 of 158 prompt tokens from the restored cache, and its greedy reply matched a run from an empty cache exactly. - Qwen3.5-0.8B (mlx-vlm, hybrid layers), 3.6k-token turn: 2048 tokens reused, the same as a process that was never unloaded. Live Unsloth Studio (API only): MLX chat turn, then `POST /api/inference/images/load` with Tongyi-MAI/Z-Image-Turbo, then reload the chat model and send the next turn. ```text image load phases: ['downloading', 'saving_chat_context'], evicted: Qwen/Qwen3-0.6B Media swap: kept the chat slot KV for restore on reload Restored the saved MLX prompt cache onto the reloaded model turn 2 usage: prompt_tokens 3664, cached_tokens 3630 (Qwen3-0.6B) turn 2 usage: prompt_tokens 3662, cached_tokens 2048 (Qwen3.5-0.8B) ``` The save directories were gone after the restore. --------- Co-authored-by: Daniel Han <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.










Includes #14088 and #14106; review the last 7 commits (2fc1ef2..HEAD).
The own commits are 2fc1ef2, e9c75e1, 0372bd3, da5685f, ab3ffac, 38b83a8 and 39c691f, plus one pre-commit.ci format fix (1b49896). The merge commits only bring in #14088 and #14106, so
git diff 4bbf7ee6ab HEADshows only this PR.Summary
Settings › Resources › Model memory now has a "Keep multiple models loaded" Select with three values: Off, When they fit and Always. The description under it changes with the selected value. The image/video idle auto-unload row moved from API keys into the same Model memory section. Both rows show up in settings search, and a new
resources-model-memorydeep link opens the dialog on that section. Saving the moved row throughPUT /api/settings/openai-auto-switchno longer needsenabled. The field is optional now, so a save from Model memory can't resend a stale value.On the Images and Video pages, the "Model loaded" toast now names the models the load unloaded. Chat shows the same eviction notice. A load refused under Always shows a "Model not loaded" toast with the backend's sentence, plus an "Open settings" action for the account owner only. Unsloth Studio recognises a refusal by the
X-Unsloth-Refusalheader first, then by the headers in a padded_deferred_errorbody, then by the backend wording.When an image or video load is about to evict a GGUF chat model, Unsloth Studio saves the chat KV first:
saving_chat_context./v1/images/generationsor/v1/videoscall that loads its model through the auto-switch also saves the chat KV. Before, the call counted itself as chat work and skipped the save.The "Keep chat context across unloads" row on API keys is now always shown, with new copy.
How it fits R1/R2
This PR reads R1's stored mode and its K2/K4 rules, and R2's
can_load_alongsideplus the fit keywords the media acquire uses. The pre-swap checkwould_evictasks the same questionacquire_forwill: under Always it never evicts (the load is refused instead), and under When they fit a priced load that fits alongside chat does not trigger a save. Under When they fit the model lifecycle row for the eviction is R2's "evicted" row. Under Off this PR writes the "swap" row.Testing
Frontend:
anthropic-dated-model-ids-reach-the-picker,custom-provider-api-type,llama-cpp-auto-reload) hit the load timeout in the full run and pass when run alone. None of them is touched here.typecheckandi18n:check:strictpass on the merged head, and the 80 tests in the files below pass there.model-memory-multi-model-mode.test.ts,images-evicted-toast.test.ts,load-refusal-header.test.ts,media-saving-chat-context.test.ts. Extended:settings-search.test.ts,media-auto-switch-setting.test.ts,media-idle-unload-api-only.test.ts,media-load-cancel.test.ts,tests/studio/playwright_settings_tabs.py.Backend:
test_swap_kv_resume.pyandtest_auto_switch_partial_save.py(85 pass). The tests for the When they fit order, the/v1save, keep KV turned off mid-save and the Off peek fail on the code before ab3ffac and 38b83a8.test_a_model_type_without_architectures_is_not_switchableneeds huggingface-hub < 1.0 (it fails the same way on main), andtest_setup_keeps_the_gate_and_lock_after_the_caller_gives_upis a timing test that passes 3/3 on its own. Neither file is touched here.Real GPU run with Qwen3-1.7B-GGUF Q4_K_M (chat) and Z-Image-Turbo-GGUF Q4_K_M (image), keep KV on, Keep multiple models loaded set to Off:
saving_chat_contextshowed for about 0.22 s.The Playwright settings-tabs harness passes.
The GPU run and the screenshots used head 0500dbb412. Later commits change only the When they fit peek (same fit keywords as the acquire), the lifecycle row under When they fit, and tests.
UI evidence
Follow-ups
LoadModelError.headersfor the chat refusal once Studio: clearer audio.cpp errors, cleaner Speak/Clone, reproducible takes #14075 merges. Until then chat recognises a refusal by its wording.UI before / after
BEFORE is the head of #14106 (this PR's base), AFTER is this PR, two separate installs.
Settings > Resources > Model memory: "Keep multiple models loaded" changes from a switch to an Off / When they fit / Always selector, and a new "Idle auto-unload for image and video" row appears in this section.
With the setting at Always, the description follows the selected value.
The "Keep multiple models loaded" hint now covers chat, image and video models and explains GPU placement and the 1 GB margin of When they fit.
Settings > API keys > Model auto-switch: the image/video idle-unload row moved out of this section, and "Keep chat context across unloads" shows even when chat idle unload is off.