Skip to content

Studio: image and video models stay loaded beside chat when they fit - #14106

Merged
danielhanchen merged 59 commits into
unslothai:mainfrom
Etherll:studio/r2-media-coresidency
Oct 19, 2026
Merged

danielhanchen merged 59 commits into
unslothai:mainfrom
Etherll:studio/r2-media-coresidency

Conversation

@Etherll

@Etherll Etherll commented Oct 18, 2026 •

Copy link
Copy Markdown
Collaborator

Includes #14088; review the last 10 commits (21c5b4c..HEAD).

The own commits are 21c5b4c, 53691de, dd7f1ea, 42f9da9, 7c33268, 4bbf7ee (formatting only), c0044d3, ec93a37, dc903fe and 5932e71. The merge commits only bring in #14088.

Summary

With Keep multiple models loaded set to When they fit or Always, loading an image or video model no longer unloads the chat model when both fit on the GPU. Before this, every image or video load evicted chat regardless of the setting.

The new core/inference/gpu_residency.py prices an image or video load from the checkpoint files already on disk (weights plus generation headroom) and compares it with live free VRAM per physical GPU, with a 1 GiB margin. An image load must also keep its transformer resident under the diffusion planner, so "fits" never means streaming weights. When the load fits, nothing is unloaded. When it does not:

  • When they fit unloads the cheapest residents on the same GPUs first and re-checks after each one. If it is still short, it unloads the rest on those GPUs, as Off does.
  • Always refuses the load and names the models that would have to go.
  • Residents on other GPUs are never touched. Chat loads pass the GPUs they target, and an image or video load passes its GPU even when it can't be priced. An idle H3 video server next to a video model on other GPUs stays too.
  • A resident image or video model that is still loading counts at its full price, since its weights are not in live free VRAM yet. A failed load's price stops counting once nothing is loaded or loading.
  • When freeing room for a primary chat load, anything freed (an idle video server counts) earns a retry at full size. The replace fallback, which has no retry after it, never refuses a partial fit.

The chat side changes too:

  • GGUF launches add media_held_mib() (what resident image and video models hold) to the VRAM already planned by other servers, so llama-server sizes itself around them.
  • A primary chat load that only partially fits beside an image or video model refuses the partial fit. When they fit then frees the image or video model and retries. Always only accepts a smaller context, otherwise it refuses.
  • Under Always, a chat load that runs out of memory beside an image or video model is refused instead of retried.
  • An image or video load that arrives while a chat load on unknown GPUs is in flight gets a retryable 409 under Always, since the chat model's size is not known until it launches. When they fit unloads chat as before. A CPU chat load, or one on known GPUs, is left to the per-GPU check.
  • Under Always, refusals name only the image or video models on the GPUs that are short.
  • A chat load whose GPU start fell back to the CPU releases its GPU claim, so it does not evict image or video models for nothing.

Evictions made by the co-residency path are reported through the arbiter's eviction sink, the same way #14088 reports other unloads. There is no UI change.

Upgrade behaviour change

#14088 migrates installs that had the old chat-only Keep multiple models loaded switch turned on to When they fit. With this PR on top, those installs see a behaviour change with no extra opt-in: image and video loads stop evicting chat whenever the fit check passes, and chat GGUF launches count media_held_mib when sizing. Installs on Off behave as before, apart from the CPU-fallback release noted below.

Release note: Unsloth Studio can keep an image or video model loaded beside a chat model when Keep multiple models loaded is set to When they fit or Always and both fit in GPU memory.

Known limits

  • Macs, unified-memory hosts and hosts with UUID or MIG masked GPUs cannot be priced, so co-residency is denied there and the load behaves as under Off (When they fit) or is refused (Always).
  • sd.cpp on GPU, MLX and H3 video loads have no price yet. They evict what shares their GPU first under When they fit, and are refused under Always when anything does.
  • The route-level require_no_foreign_generations() check in the media routes still refuses globally. That is outside this PR.
  • The CPU-fallback release only acts once the audio.cpp PR (Studio: clearer audio.cpp errors, cleaner Speak/Clone, reproducible takes #14075) records audio_device_fallback. It runs under Off too, so a primary that fell back to the CPU no longer holds the GPU claim there either.
  • The GPUs recorded for chat only grow while any chat model stays loaded. Unloading one kept chat model does not shrink them, so a later load on that GPU behaves as under Studio: add an Always choice to Keep multiple models loaded, track every model on the GPU, and report every model a load unloads #14088 there.
  • A failed image or video replacement that keeps the old model keeps the new model's price until the next load.

Testing

New and extended tests:

  • studio/backend/tests/test_gpu_arbiter.py
  • studio/backend/tests/test_gpu_residency_coexistence.py
  • studio/backend/tests/test_gpu_arbitration_sim.py
  • studio/backend/tests/test_audio_cpu_fallback_claim.py
  • studio/backend/tests/test_multi_model_primary_fit.py
  • studio/backend/tests/test_media_auto_switch.py
cd studio/backend
python -m pytest tests/test_gpu_arbiter.py tests/test_gpu_residency_coexistence.py tests/test_gpu_arbitration_sim.py tests/test_audio_cpu_fallback_claim.py tests/test_multi_model_primary_fit.py tests/test_media_auto_switch.py -q

On head 5932e71: 505 tests pass in the focused set (the files above plus #14088's multi-model, arbiter, MCP status and owner-mode tests), and tests/test_media_auto_switch.py passes on its own (111 passed, 1 skipped). The 49 other backend test files that touch the arbiter pass too (3,373 passed), except test_account_deactivated_account_fences.py::test_owner_run_cannot_take_a_deactivated_accounts_supervisor_slot, which fails the same way on #14088's head.

GPU check on head 5932e71, on one B200 (GPU 7), through the Unsloth Studio API:

  • Under When they fit, unsloth/Qwen3-8B-GGUF Q4_K_M and unsloth/Z-Image-Turbo-GGUF Q4_K_M were both resident with evicted=[], in both load orders (chat then image, image then chat). An image generation and a chat completion then both returned 200, with the two models holding about 6.6 GB and 14.6 GB. The same check also passed on 4bbf7ee and dc903fe.
  • Under Off, the image load unloaded the chat model and reported it: evicted=['unsloth/Qwen3-8B-GGUF'], evicted_slots=[{'kind': 'chat', 'model': 'unsloth/Qwen3-8B-GGUF'}].

Etherll and others added 13 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.
…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-19T01:18:19.071693Z ad78cb3 New commits
ℹ️ 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.

AhmedXN and others added 7 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.
An image or video load that can't be priced still passes its GPU, so it leaves chat on other GPUs alone. The media auto-switch only refuses behind a chat load that holds the GPU, not a CPU one. The Always refusal for a chat load that is short on a GPU names only the models on that GPU.
…ting a failed image or video load's price

A kept chat slot a request reached after it was picked stays loaded, so free_for no longer reports it. A media price counts only while its engine is loading or has a model loaded, so a failed load stops shrinking chat's room.
… Always media swaps when the load registers

- An ordinary chat switch lists the replaced primary in evicted_slots only; the legacy evicted list (the 'to make room' toast) is unchanged.
- An image or video load that replaces one of its own kind under Off or When they fit reports it.
- Under Always, an image or video load re-checks under the arbiter lock as it registers, so a load of another repo that registered meanwhile is not torn down.
…o-switch wait behind a placed chat load

free_for keeps an idle H3 video server when the resident video model sits on other GPUs. Under Always the media auto-switch only refuses at once behind a chat load whose GPUs are unknown; one on known GPUs is left to the arbiter's overlap check.
…ot be read as loaded

A probe that raises no longer lets a chat or media load evict that model, or replace it, under Always. Off and When they fit behave as before.
@Etherll

Etherll commented Oct 18, 2026

Copy link
Copy Markdown
Collaborator Author

Status on head 5932e71:

…tuck kept slots, and re-checks before an image engine switch

- A chat claim left by a failed load no longer blocks image and video loads under Always; one with a chat load in flight or a stuck kept slot still does.
- A vLLM/SGLang load under Always refuses while a kept slot that failed to stop still holds its model.
- The diffusion engine router runs an optional before_engine_switch check under its transition lock, before the switch unloads the active engine; the image load route uses it under Always.
@danielhanchen danielhanchen self-assigned this Oct 18, 2026
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Something went wrong. Try again later by commenting “@codex review”.

Failed to sample tokens
ℹ️ 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 and others added 14 commits October 18, 2026 10:28
… credit the replaced chat for native audio, and spare a serving primary under Always
…n alongside load or a native audio load under When they fit
# Conflicts:
#	studio/backend/core/inference/gpu_arbiter.py
Etherll added a commit to Etherll/unsloth that referenced this pull request Oct 18, 2026
@danielhanchen

Copy link
Copy Markdown
Member

pre-commit.ci run

@danielhanchen
danielhanchen merged commit 9bac178 into unslothai:main Oct 19, 2026
danielhanchen added a commit that referenced this pull request Oct 19, 2026
… the chat context when an image or video model takes the GPU (#14108)

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 4bbf7ee 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:

- New tests: `test_swap_kv_resume.py` and
`test_auto_switch_partial_save.py` (85 pass). The tests for the When
they fit order, the `/v1` save, keep KV turned off mid-save and the Off
peek fail on the code before ab3ffac and 38b83a8.
- On the merged #14088 + #14106 head, the swap, arbiter, co-residency,
Always and auto-switch suites give 1,415 passed (547 on the targeted
rerun after ab3ffac). Two fail:
`test_a_model_type_without_architectures_is_not_switchable` needs
huggingface-hub < 1.0 (it fails the same way on main), and
`test_setup_keeps_the_gate_and_lock_after_the_caller_gives_up` is 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:

- 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

<!-- screenshots added in a comment -->

## 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 #14075 merges.
Until then chat recognises a refusal by its wording.


<!-- ui-evidence:start -->
### 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](https://raw.githubusercontent.com/danielhanchen/unsloth-staging-2/pr-media/pr/14108/pr14108_pair_00-bb28d725c526.png)

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

![Always description before and
after](https://raw.githubusercontent.com/danielhanchen/unsloth-staging-2/pr-media/pr/14108/pr14108_pair_01-98b1b59d49cc.png)

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](https://raw.githubusercontent.com/danielhanchen/unsloth-staging-2/pr-media/pr/14108/pr14108_pair_02-83047baa8d6d.png)

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](https://raw.githubusercontent.com/danielhanchen/unsloth-staging-2/pr-media/pr/14108/pr14108_pair_03-58c0654e358d.png)
<!-- ui-evidence:end -->

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Etherl <[email protected]>
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