Skip to content

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 into
unslothai:mainfrom
Etherll:studio-model-memory-modes-kv-swap
Oct 19, 2026
Merged

danielhanchen merged 95 commits into
unslothai:mainfrom
Etherll:studio-model-memory-modes-kv-swap

Conversation

@Etherll

@Etherll Etherll commented Oct 18, 2026 •

Copy link
Copy Markdown
Collaborator

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 HEAD shows 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-memory deep link opens the dialog on that section. Saving the moved row through PUT /api/settings/openai-auto-switch no longer needs enabled. 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-Refusal header first, then by the headers in a padded _deferred_error body, 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:

  • The save runs outside every lock and is capped at 45 s. While it runs, load-progress reports the phase saving_chat_context.
  • The saved stash is promoted only when the chat model is actually evicted. If the load ends up not evicting chat, the pending save is dropped, and a save that finishes after the 45 s cap has its files deleted.
  • The stash is tagged with its origin, so saving the media idle TTL no longer purges it. Turning "Keep chat context across unloads" off still does.
  • Loading the same chat model again restores the saved KV, so the conversation does not have to be re-read.
  • The save runs only when the load will really unload chat. Under When they fit, chat on other GPUs stays and an idle image or video model on the same GPUs is unloaded first, the same order the residency code uses. The peek counts that as making room only with the 1 GB fit margin to spare, and a chat model still loading on those GPUs counts as unloaded. A save is dropped if "Keep chat context across unloads" is turned off while it runs.
  • A client that disconnects mid-load no longer drops the save: the routes close it only once the acquire thread is done, so a late eviction still keeps it.
  • A /v1/images/generations or /v1/videos call 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_alongside plus the fit keywords the media acquire uses. The pre-swap check would_evict asks the same question acquire_for will: 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:

  • Full node suite: 12,547 pass. Three files (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.
  • typecheck and i18n:check:strict pass on the merged head, and the 80 tests in the files below pass there.
  • New tests: 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:

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:

  • The chat reached 5015 prompt tokens.
  • Image load: POST took 1.50 s, and saving_chat_context showed for about 0.22 s.
  • Reloading the chat model plus one new turn (5052 tokens) evaluated 37 tokens. With keep KV off, the same reload evaluated all 5052.

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

  • Only the primary chat model's KV is saved. Extra chat models kept by Keep multiple models loaded are unloaded without a save, as the chat idle unload already does; saving and restoring them needs a per-slot stash.
  • Read LoadModelError.headers for 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.

Model memory section before and after

With the setting at Always, the description follows the selected value.

Always description before and after

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.

Hint before and after

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.

Model auto-switch section before and after

Etherll and others added 21 commits October 17, 2026 13:07
…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.
…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().
…io/r2-media-coresidency

# Conflicts:
#	studio/backend/routes/inference.py
#	studio/backend/routes/video.py
…io/r2-media-coresidency

# Conflicts:
#	studio/backend/routes/video.py
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 18, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ⚠️ Failed 2026-10-18T15:31:49.671679Z e28b5c0 Manual request
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@Etherll

Etherll commented Oct 18, 2026

Copy link
Copy Markdown
Collaborator Author

UI evidence

Before is upstream main e795149d99, after is this branch. Both are CPU-only Unsloth Studio builds with a fresh home, Chromium 1280 px, DPR 2, light theme. The shots were taken at 0500dbb412; studio/frontend/src is identical between that commit and the current head beb0a22eaf. Scenes marked mocked stub the Images endpoints with page.route (download plan, load POST, load-progress, status); the rest are real.

Model memory: Keep multiple models loaded is a Select (Off / When they fit / Always)
Select open

The description follows the selected value (mocked GET so the stored mode is When they fit)
When they fit description

Long labels at UI size 20 (German, Russian)
de at UI size 20
ru at UI size 20

The image/video idle row moved from API keys into Model memory
Idle row moved

Keep chat context across unloads: always shown, new copy
keepKv row

Images load toast while the chat KV is saved (mocked: load POST held, load-progress phase saving_chat_context; main has no such phase, so before shows its plain load toast)
Saving chat context

Model loaded toast names what the load unloaded (mocked: evicted_slots on the POST answer)
Model loaded, evicted

Refusal under Always: owner gets Open settings, a managed account does not (mocked: 409 with X-Unsloth-Refusal: multi-model-always)
Refusal toast

Open settings lands on Model memory
Open settings

Design check against the Unsloth Studio design guide: compliant, no blocking notes.

AhmedXN and others added 5 commits October 17, 2026 23:01
…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.
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
@danielhanchen

Copy link
Copy Markdown
Member

pre-commit.ci run

@danielhanchen
danielhanchen merged commit 22531d3 into unslothai:main Oct 19, 2026
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants