Skip to content

Studio: add an Always choice to Keep multiple models loaded, track every model on the GPU, and report every model a load unloads - #14088

Merged
danielhanchen merged 22 commits into
unslothai:mainfrom
Etherll:studio-multi-model-always
Oct 19, 2026
Merged

danielhanchen merged 22 commits into
unslothai:mainfrom
Etherll:studio-multi-model-always

Conversation

@Etherll

@Etherll Etherll commented Oct 17, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Unsloth Studio could not promise an unattended server that no load unloads another model, and a load that did unload something often went unreported. This PR:

  • turns Keep multiple models loaded into a mode: Off (default for fresh installs), When they fit (fit, today's "on") and Always, which refuses any load that would unload another chat, image or video model;
  • fixes a managed account's load reading its own studio.db, seeing the setting as off, and unloading the owner's idle kept models;
  • makes the GPU arbiter track every resident model instead of a single owner, without changing behaviour under Off;
  • reports every model a load unloads, including media freed by a chat load and chat models freed by an image or video load.

The frontend Select and toast copy come in a follow-up PR; this one is backend only.

What changes

Setting (utils/multi_model_settings.py, routes/settings.py)

  • get_multi_model_mode() returns off | fit | always. It is read in the owner's database (run_as(OWNER)), from one get_app_settings snapshot, with a 2 s cache and a write generation.
  • Bool-first migration: keep_multiple_models_loaded False or missing → off; True with multi_model_mode: "always" → always; True otherwise → fit. An older build that turns the setting off still wins after an upgrade.
  • set_multi_model_mode() writes both keys in one call. PUT /api/settings/multi-model takes {mode} or the legacy {enabled}. A legacy enabled: true keeps Always. The response adds mode and default_mode: "off".

Arbiter (core/inference/gpu_arbiter.py)

  • acquire_for(..., policy="off", evicted=None, gpu_ids=None). Under always it raises MultiModelAlwaysRefusal instead of evicting a chat, image or video model; a Decision API server is still evicted as before. off and fit evict exactly as today.
  • _residents keyed by owner with physical GPU ids (CUDA_VISIBLE_DEVICES=2,3 maps ordinal 0 to GPU 2), plus holds() and residents(). _owner stays as the last claimant. When a caller or test sets _owner directly, it wins over _residents.
  • owner_account(owner=None) and restore_owner_account(owner) work per owner.
  • evicted= or the eviction_sink context variable collects {kind, model} for every model an evictor unloads: chat primary, each kept slot, image, video. Idle H3 servers are not listed.

Where Always is enforced

  • In the arbiter, for chat ↔ image/video. A claim whose load failed and holds nothing (no reported model, no load in flight, no stuck kept slot) is still evicted. A model whose status cannot be read counts as loaded.
  • Before an image or video load of another repo replaces the loaded model of its own kind, on any device and before the image route's engine switch, and again under the arbiter lock as the load registers, so a concurrent load of another repo is not torn down either. Another file of the same repo is allowed, as for chat.
  • In _load_model_impl, before any teardown, when a load would replace the serving primary with a different repo. Another quant, context length or engine of the same repo is allowed. This covers /api/inference/load, API auto-switch, CPU audio and zero-VRAM loads that never enter the arbiter, the NPU path, and vLLM/SGLang loads that would retire kept models.
  • In the kept-slot retry loop: no kept model is evicted and the primary is not replaced. A capped context still retries alongside, because a smaller context is not an unload.
  • Before the H3 video route unloads an off-torch image engine (routes/video.py ~468), and before an off-torch image load unloads a native H3 video model.
  • The chat fast paths re-assert the GPU claim, and under Always they skip it instead of refusing: the loaded model stays usable and nothing is unloaded.
  • Training and the idle TTL still free the GPU. keep_resident is still ignored, as today.

Refusal shape (one contract everywhere)

  • 409 with X-Unsloth-Refusal: multi-model-always, no Retry-After.
  • Plain-string detail on /api/inference/load and on the image and video load routes. Before this, a raw refusal would have become a 500 in the load catch-all, or a 409 without the header on the media routes.
  • OpenAI envelope with error.code: "multi_model_always" on /v1 and auto-switch, including media auto-switch.
  • The /p preview keeps its existing 503.
  • When the keep-alive padding has already started, _deferred_error keeps x-unsloth-refusal and retry-after under headers.
  • Owner copy: "Loading this model would unload the chat model unsloth/Qwen3-8B-GGUF, and Keep multiple models loaded is set to Always. Unload that model first, or choose When they fit." The managed-account copy says "which Unsloth Studio is set to keep loaded" and never names a model another account loaded. MULTI_MODEL_REFUSAL_MARKERS exports both phrases for readers that lose headers.

Eviction report

  • LoadResponse.evicted keeps list[str] and now also lists image/video models a chat load freed and kept models a vLLM/SGLang load retired. New evicted_slots: [{kind: chat|audio|image|video, model}] uses public ids. audio means a native or audio.cpp audio model.
  • An ordinary switch to another chat repo lists the replaced model in evicted_slots only. The legacy evicted list drives the chat page's "Unloaded … to make room" toast, which a normal switch should not show.
  • /images/load and /video/load answers gain evicted and evicted_slots, including the image or video model a load of another repo replaces. They are filled only on the POST answer and are [] on GET.

Other

  • An unreadable setting keeps the last mode read instead of falling back to Off.
  • diffusion_engine_router gains a before_engine_switch check that runs under its transition lock before a switch unloads the active engine. The image load route uses it under Always.
  • /api/inference/status gains multi_model_mode. MCP studio_status reads it as chat.multi_model_mode, which is None against an older server.
  • _ran_out_of_memory accepts the structured {code: "out_of_memory"} detail, so an audio.cpp OOM still frees an idle kept model.
  • The "does not fit" message named a setting that never existed ("Keep other models loaded"). It now names Keep multiple models loaded, with an Always variant.
  • Callers that assumed one owner now ask holds(): post-load guards, the /p pre-check, managed-engine reap, account_access, and Laya, which yields to any resident that is not a Decision API server. The native-audio handoff waits for freed VRAM only when the media model was actually evicted.

Compatibility

  • Off and When they fit behave as before (When they fit is today's "on"). policy_kwargs("off") passes no new kwargs, so existing fakes that take acquire_for(owner, register) still work.
  • Test edits are in place only: three source-pinned literals, six owner_account fakes that now accept arguments, the :975 copy, and two settings monkeypatches.

Tests

  • New: tests/test_multi_model_settings.py, tests/test_multi_model_always.py, tests/multi_account/test_multi_model_owner_mode.py. Also new arbiter cases in tests/test_gpu_arbiter.py and the MCP mode read in tests/test_mcp_tools_status.py.
  • Arbiter, arbitration sim, multi-model serving, account, decision, diffusion/video route, auto-switch, preview and multi-account suites pass. In this environment the known baseline failures, which fail the same way on main, are test_alice_bob_matrix (no av module), a transformers/huggingface-hub version clash in one auto-switch test, and an order-dependent test_tunnel_safe_long_post case.

UI evidence and the load-orchestrator CI run follow in a comment.

… 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().
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 17, 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:16:34.651173Z 1f25a77 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.

…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.
@Etherll

Etherll commented Oct 18, 2026 •

Copy link
Copy Markdown
Collaborator Author

Unsloth Studio evidence

Before is main at the merge base e795149d99; after is this PR at 0bbee14412. The later commits (a46aa12e6a..0b13d1eaae) add the image/video same-kind refusal, registration-time re-checks and more eviction reporting, which these scenes don't exercise. Both ran CPU-only Unsloth Studio on fresh homes, with the same frontend build and the same cached Qwen3 GGUFs.

Refusal under Always (real llama-server, API client). Load unsloth/Qwen3-0.6B-GGUF, turn the setting on (head: {"mode": "always"}, main: {"enabled": true}), then POST /api/inference/load for unsloth/Qwen3-1.7B-GGUF with alongside: false.

main this PR
Replacing load 200, evicted: [], Qwen3-0.6B silently unloaded 409 + X-Unsloth-Refusal: multi-model-always
Detail n/a "Loading this model would unload the chat model unsloth/Qwen3-0.6B-GGUF, and Keep multiple models loaded is set to Always. Unload that model first, or choose When they fit."
Loaded afterwards unsloth/Qwen3-1.7B-GGUF unsloth/Qwen3-0.6B-GGUF (multi_model_mode: "always" on /api/inference/status)

The chat page's own model switch is unchanged: when the page believes the setting is Off it calls /api/inference/unload first, an explicit user action that Always does not block.

GPU-short toast copy. /api/inference/load was answered with each tree's own _gpu_short_message(13.2, 8.4, 32768, 32768, False) text; main names a setting that never existed.

GPU-short toast copy before and after

Tests at 0b13d1eaae. The PR's own and touched suites, plus the diffusion, video, auto-switch, preview, decision and diffusion-engine-router suites: 3,672 passed. All 7 failures fail the same way on main at e795149d99: five test_gpu_selection attention-resolver cases, test_a_model_type_without_architectures_is_not_switchable and test_video_download_plan_judges_a_quantized_reference_pick_per_partition (environment and version gaps on this host). Every other test file that drives the chat load path: 2,356 passed, and its 18 failures are the same 18 on main.

… 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.
…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.
…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

@danielhanchen

Copy link
Copy Markdown
Member

@codex security review

@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

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: be5f0b5485

ℹ️ 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".

Comment on lines 490 to +494
if getattr(images, "runs_off_torch_device", False) is True:
# No arbiter owner evicts it, yet it holds the one managed sd.cpp tree H3 installs into.
image_slots = resident_slots(DIFFUSION) or [{"kind": "image", "model": ""}]
if multi_model_mode == "always":
raise refusal_for(image_slots, "image")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Recheck the shared sd.cpp tree while registering

When an off-torch image load and a native H3 video load start concurrently, this check and _unload_native_video_sharing_the_sd_cpp_tree both run before either load is registered: video can check before image activates its engine, while image checks before video calls begin_load. Their later locked registration callbacks only recheck their own modality, so both background loads can be admitted against the single managed sd.cpp tree and one can disrupt the other despite Always. Repeat the cross-modality shared-tree check in the same locked registration step that starts the load.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This race is already on main: both routes run the same unlocked shared-tree checks before either load registers, and a recheck at registration would run after the image route has already activated the sd.cpp engine. Closing it needs one lock over engine activation and begin_load in both routes, which is out of scope here.

@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@danielhanchen

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 3d563da96b

ℹ️ 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".

serving or (request.engine != "auto" and (model_slots.slots or model_slots.stuck))
):
# A native lease's model_path is only its display label; the granted path is the identity.
await _guard_primary_replacement(

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Validate chat targets before the Always replacement guard

When Always is enabled and a different primary is serving, this guard runs before the normal model validation below. For example, ModelConfig.from_identifier can still reject the identifier at lines 19681-19687, and _reject_unsupported_managed_kind can reject a GGUF requested through vLLM/SGLang at line 19750; these requests cannot load or unload anything, but they now return a 409 telling the user to unload a healthy model instead of the actionable 400. Run the non-destructive validation before this guard, as the NPU path already does.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The request is invalid either way and the 409 unloads nothing; moving the guard past model resolution would run resolution and downloads before the Always check, so the order stays.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 18, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 18, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. What shall we delve into next?

Reviewed commit: 9dcd3be670

ℹ️ 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".

# Conflicts:
#	studio/backend/core/inference/gpu_arbiter.py
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

Etherll added a commit to Etherll/unsloth that referenced this pull request Oct 18, 2026
Etherll added a commit to Etherll/unsloth that referenced this pull request Oct 18, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 66e5ea056f

ℹ️ 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".

Comment on lines +1481 to +1483
current = get_multi_model_mode()
mode = (current if current != "off" else "fit") if payload.enabled else "off"
set_multi_model_mode(mode)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve Always across concurrent legacy updates

When an older client sends {"enabled": true} concurrently with a {mode: "always"} PUT, the legacy request can read off here, let the Always write commit, and then write fit on line 1483. That contradicts the compatibility promise directly above and leaves the server able to evict models even though the other request successfully selected Always; make the read/conditional write atomic (or serialize mode writes) so a legacy enable cannot downgrade a concurrent Always update.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This needs an old client and a new one saving the owner-only setting within the same instant; each request is a single owner action and a re-save fixes it, so the read-then-write stays as is.

@danielhanchen
danielhanchen merged commit 9edc731 into unslothai:main Oct 19, 2026
danielhanchen added a commit that referenced this pull request Oct 19, 2026
…14106)

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 (#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 #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`

```bash
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'}]`.

---------

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]>
danielhanchen added a commit that referenced this pull request Oct 19, 2026
… load unloads (#14089)

Includes #14088 (Studio: add an Always choice to Keep multiple models
loaded, track every model on the GPU, and report every model a load
unloads); review the last 16 commits (7c4c66d..HEAD, leaving out the
merges of #14088's branch and pre-commit.ci's autofix).

## Summary

Agents followed long Unsloth Studio work by polling in shell loops: in
one promo run, 598 of 854 MCP calls were polls. `load_model` blocked for
the whole download and load, so a client timeout (Codex defaults to 60
s, and 8 of 14 promo loads took longer) lost the result. Loads also
missed media evictions (`load-ltx` over Qwen-Image reported `evicted:
[]`), `unload_model(kind="tts")` echoed `"llm"`, and MCP.md said long
work "returns at once". With this change, one `get_job` call waits for a
job to move, a load outlives the call that started it, and every load
names what it unloaded.

## What changes

- `get_job` takes `wait_s` (0 to 240). It re-reads the job every 2 s,
reports progress, and returns when the job finishes, its status or phase
changes, or the wait runs out. A job that is still running includes
`poll_after_s`.
- `get_job` gains the kinds `training` and `diffusion_training` (run
folder and checkpoint names once completed) and `load`.
- `load_model` takes `wait_s` (240 s when unset). The load runs as a job
in the new `studio_mcp/job_store.py`, so a client that stops waiting
does not stop it. An early return gives `status: "loading"` and a
`job_id` for `get_job(kind="load")`, and calling `load_model` again
joins the load already in flight. The job is registered before any route
read (resident-model snapshot, image and video Hub and download-plan
reads), so `wait_s=0` always returns a `job_id` at once.
- Loads return `evicted_slots` (`{kind, model}`). The list comes from
the load response's `evicted_slots` (added by the included PR), else its
`evicted` ids placed by a snapshot of resident models, plus a
before/after diff of the slots that list does not cover (all of them for
routes that report nothing).
- A repeat `load_model` with the same model, variant, settings and Hub
token joins the load already running; so does a chat load (without
`variant`) that Unsloth Studio is already running for another caller. A
failed status read while following a load is skipped.
- An image or video `load_model` of another variant of the resident repo
waits for that variant: the resident check compares the requested GGUF
file (image status) or its quant and MiniMax-H3 partition (video
status), not only the repo id. Video status drops a `-<n>bpw` suffix, so
a bpw build is confirmed only once the load reports ready.
- `unload_model` echoes the kind that was requested, and speech-to-text
loads run as jobs too. `cancel` has no load kind, so
`unload_model(kind="image"|"video"|"stt")` also stops a `load_model` of
that kind still running. Image and video post their unload route, which
cancels a pending load. A speech-to-text load still downloading has its
download cancelled; one past its download is unloaded once it finishes,
even if that takes longer than the call. Chat loads in flight keep their
earlier unload behavior: stopping a GGUF download needs the load to
carry a `load_request_id`, which is left for a follow-up.
- `export_jobs.py` is now a thin wrapper over the job store.
- The server INSTRUCTIONS still say "poll get_job"; #14081 rewrites
INSTRUCTIONS, and the `wait_s` sentence goes in after it lands. Until
then the `load_model` and `get_job` descriptions carry the `wait_s`
guidance.
- MCP.md describes `wait_s`, the 240 s cap, and `wait_s=50` for Codex's
60 s default timeout, and drops "Audio runs cannot be cancelled" (the
cancel tool's own description keeps that fact until audio cancel lands).

## Tests

- `tests/test_mcp_tools_loading.py` and the new
`tests/test_mcp_tools_jobs.py`. Every new test fails on main
`e795149d99` and passes on this head.
- Full `tests/test_mcp_*.py` suite: 1506 passed, 3 skipped on the
current head (merged with #14088).

```bash
cd studio/backend
python -m pytest tests/test_mcp_tools_loading.py tests/test_mcp_tools_jobs.py -q
python -m pytest tests/test_mcp_*.py -q
```

## Live check

Unsloth Studio from this branch on one B200, MCP clients with a 60 s
timeout, fresh no-context agents given only the task:

- "Render 3 short clips and train 30 steps on a tiny model": 24 tool
calls, 1 `get_job(wait_s=50)` per clip (Wan2.2-TI2V-5B), 5 for the
30-step run (each returned on a phase change), no shell loop, no client
timeouts.
- "Load a 7B+ model, then chat for a 2k-token reply":
`unsloth/Qwen3-8B-GGUF` loaded inside `wait_s=50`, chat returned 2,383
tokens.
- Image then video load: the video `load_model` answered
`"evicted_slots":[{"kind":"image","model":"unsloth/Z-Image-Turbo-GGUF"}]`;
on main this was `evicted: []`.
- A 9 GB `unsloth/Qwen3-14B-GGUF` load whose client gave up after 5 s
kept running; the next `load_model` returned `status: "loading"` with a
job id, a third call got the same job id, and `get_job(kind="load",
wait_s=50)` returned the loaded result. The server log shows one
download and one llama-server start.


















## Follow-ups

- A video download plan that picks a plain `.safetensors` checkpoint
while a GGUF build of the same repo is resident can still read as loaded
early, because video status names no checkpoint file. The fix (reject a
GGUF resident for a non-GGUF request) is a narrow build-matrix case,
kept for a follow-up.

---------

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]>
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]>
danielhanchen added a commit that referenced this pull request Oct 19, 2026
…ad, and queue videos (#14090)

Includes #14088 (Studio: add an Always choice to Keep multiple models
loaded, track every model on the GPU, and report every model a load
unloads) and #14089 (Studio: MCP agents follow long work in one call and
see every model a load unloads); review the last 40 commits
(005cf16..HEAD, one of them from pre-commit.ci: `git log --no-merges
53c03f7..HEAD`), leaving out the merges of #14089's branch. The
partial-variant refusal skips a variant `/api/hub/download-status`
reports in flight, so this PR adds that one read-only route to the MCP
forward allowlist (00e364f); the PR stacked on this one widens it to
the download routes.

## Summary

Over MCP, an agent could load a model but not say where it should run,
could not see what a load would download or unload before starting it,
and had to retry `generate_video` itself whenever Unsloth Studio was
already making a video. `load_model` now takes placement and memory
options, a new read-only `plan_load` tool previews a load,
`unload_model(kind="all")` frees every slot in one call, and
`generate_video` queues a clip that Unsloth Studio is too busy for.

## Changes

### `load_model` placement

- Image and video loads take `memory_mode`, `speed_mode` and `h3_task`
(video only), plus `transformer_quant` and `text_encoder_quant` (image
only). They are sent to both the download plan and the load. If an older
Unsloth Studio answers the plan with 422, the plan is asked again
without them.
- Chat, TTS and audio loads take `device` (`auto`/`cpu`/`gpu`),
`alongside`, `kv_cache_type` and `gpu_layers`. `device="cpu"` on a
llama-server GGUF sends `gpu_memory_mode="manual"`, `gpu_layers=0` and
`speculative_type="off"`. `audio_device` is sent only for tts and audio,
never for `kind="llm"`.
- `device="cpu"` with `kind="llm"` and a non-GGUF model is refused, as
are a `gpu_layers` value that contradicts `device` and a placement or
media option passed to a kind that ignores it. These are refused before
any request goes out.
- Under Keep multiple models loaded set to Always, a `device="cpu"` load
next to a serving chat model sends `alongside=true` automatically, so
the load is not refused for replacing that model.
- `LoadResult.placement` reports where the model ended up (`device`,
plus `memory_mode`, `offload_policy` and the quant fields for image and
video). `alongside_applied` says whether the chat model that was serving
before the load still serves. `studio_status` reports the same
`placement` on the image and video slots.
- A load with different placement fields no longer attaches to an
in-flight load of the same model.
- A GGUF variant with only part of its files on disk is refused with
"still downloading or incomplete" instead of failing later with a
misleading memory error. It is not refused while Unsloth Studio is
downloading it (`/api/hub/download-status`) or while an image or video
load is downloading it.

### `plan_load`

New read-only tool that loads and downloads nothing. It returns:

- `variants`: the GGUF repo's quantizations, each with its size and
whether it is downloaded or partial.
- `download_bytes`: bytes still to download (0 when nothing is left),
from the media download plan for image and video.
- `est_gpu_bytes`: the GPU estimate, for a downloaded GGUF chat model.
- `residents`, `multi_model_mode` and `would_evict`.

Under Off the eviction prediction is exact when it does not depend on
where Unsloth Studio places the load. It is an upper bound
(`would_evict_exact: false`) when it does: unloading another kind of
model (it happens only when the load reaches the GPU, which no setting
guarantees), an unreadable slot status, a model only held in memory, or
any load of a repo already resident (it may load again with another
context, device, cache type, variant or build). Under When they fit it
is always an upper bound. Under Always nothing is unloaded and
`would_refuse` says whether the load may be refused. Another variant of
a resident GGUF repo counts as a new load.

### `unload_model(kind="all")`

Unloads every chat slot, then the image, video and speech-to-text
models, and lists them under `unloaded` as `{kind, model}`. Kept chat
models are unloaded before the primary so none is promoted in between,
and models held in memory behind the active one are unloaded too. The
embedding model stays loaded. Because `unloaded` is a bool for one kind
and a list for `"all"`, the tool now publishes a combined output schema.

### Video queue

`studio_mcp/video_queue.py` queues a `generate_video` call that Unsloth
Studio refuses with "A video generation is already in progress." and
returns a `vq_...` id with `queue_position` and `eta_s`. A background
task per account submits clips in order once the previous video ends.
While it waits, it handles `gpu_busy`/`Retry-After` and network errors,
and settles a clip as `failed` with the route's reason when Unsloth
Studio refuses it for another reason. `get_job` and `cancel` accept the
queue id, and a clip can be withdrawn until its POST starts. The queue
is per account, holds at most 32 waiting clips, and lives only as long
as the MCP server process, so a restart drops clips that have not
started.

`studio/MCP.md` lists `plan_load` and the `kind="all"` behavior.

## Testing

New tests: `test_mcp_tools_placement.py`, `test_mcp_tools_plan_load.py`
and `test_mcp_video_queue.py`. `test_mcp_server.py`,
`test_mcp_no_host_paths.py`, `test_mcp_tools_status.py`,
`test_mcp_tools_loading.py` and `test_mcp_tools_video.py` were updated
for the new tool, the slot `placement` field and the queue.

```bash
cd studio/backend
python -m pytest tests/test_mcp_tools_placement.py tests/test_mcp_tools_plan_load.py tests/test_mcp_video_queue.py tests/test_mcp_server.py tests/test_mcp_no_host_paths.py tests/test_mcp_tools_status.py tests/test_mcp_tools_loading.py tests/test_mcp_tools_video.py -q
```

Result on the head of this branch: every `tests/test_mcp*.py` file and
`tests/test_multi_model_always.py` pass (1,550 passed, 3 skipped) except
three `test_mcp_images.py` tests that fail the same way on a clean
`main` in this environment.

## Not in this PR

- The `[multi_model_always]` error hint alternatives and the
INSTRUCTIONS sentence about `device="cpu"`, `alongside`,
`unload_model(kind="all")` and `plan_load` wait for the MCP errors PR,
which owns `errors.py` and INSTRUCTIONS.

## Follow-ups

- Bound the video queue's POST of a queued clip. A timed-out POST may
still have been accepted, so retrying it could submit the clip twice;
this needs an idempotency key on `/v1/videos` first. Every MCP POST has
no timeout today.
- Prune the per-account video queue state (an admission lock and a few
small entries per account that used the queue) once it is idle, without
breaking admission order.

---------

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]>
danielhanchen added a commit that referenced this pull request Oct 19, 2026
…oad models ahead of time (#14107)

Includes #14088, #14089 and #14090; review the last 24 commits
(7cbecec..HEAD: `git log --no-merges 06a089d..HEAD`), leaving out
the merges of #14090's branch.

## Summary

Over MCP, an agent could start training in Unsloth Studio, but it could
not upload its own data, load the model it had trained, or download the
next model ahead of time. This PR adds dataset uploads, loading a
checkpoint or export by name, a resolved `validate_only` echo, TTS
fine-tuning guidance, and a `download_model` tool backed by Unsloth
Studio's download manager.

## Changes

### Datasets

- `datasets(action="upload", filename, data_base64 | rows)` sends a file
to `/api/hub/datasets/upload`. It returns a `ref:` handle for
`config.local_datasets`, never the stored path the route returns.
- `datasets(action="upload_images", name, images, captions)` sends
captioned images to the diffusion dataset route. Every image gets a
fresh file stem, so a later upload never replaces an earlier one. Images
past Unsloth Studio's upload limit are refused before anything is sent,
with a note to split them across calls. It returns the dataset name that
`start_training(kind="diffusion")` takes as `data_dir`.

### Loading what you trained

- `load_model(checkpoint="<run>" | "<run>/checkpoint-N")` resolves the
name through `checkpoints.resolve`. `load_model(export="<name>")`
resolves it under the exports folder, and `variant` picks a GGUF
export's quantization.
- Both load through a minted `ref:` handle and report the name back,
never a path or the handle. `evicted_slots` entries get their names back
the same way, and so does the `get_job(kind="load")` result of a load
that outlasted `wait_s`. `unload_model(model=<that name>)` finds it.
- `is_lora` follows the run's PEFT type, passed through #14090's
`is_lora` kwarg. The load route detects LoRA itself, so a full fine-tune
is not forced to load as LoRA.
- A GGUF export loads as its folder plus the quantization in its file
name, or the `variant` passed, so `device="cpu"` places it as GGUF. An
export whose file name has no quantization needs `variant` before it can
be placed. A checkpoint is refused for `device="cpu"`.
- `checkpoint` and `export` are refused for `kind` image, video and stt.
- Unsloth Studio serves a trained load under its `ref:` handle, so the
field text says to chat with it by leaving `chat`'s `model` unset.

### `start_training`

- `validate_only` now returns the resolved config, with every path and
secret dropped.
- Refusals name the model as the caller sent it, never the host path a
`ref:` handle resolves to.
- It runs the trainer's audio-type detection. GGUF, audio.cpp and native
TTS ids are refused, with the list of trainable bases. It sets
`is_dataset_audio` for codec TTS: Orpheus/SNAC, CSM, Spark/BiCodec and
OuteTTS/DAC. A real start runs the same check, so it refuses the same
models and sends `is_dataset_audio` for codec TTS.
- The docstring names the trainable TTS bases:
`unsloth/orpheus-3b-0.1-ft`, `sesame/csm-1b`, `unsloth/Spark-TTS-0.5B`
and `unsloth/Llama-OuteTTS-1.0-1B`. It covers:
- the columns (audio + text, optional speaker_id) and the
`custom_format_mapping` roles;
  - CUDA only;
  - that GGUF/audio.cpp TTS (Qwen3-TTS, Breeze) can't be trained;
- the one-GPU order main uses: training unloads image and video models,
and unloads chat or TTS only when they don't fit next to it. A 409 comes
back while inference is running. Then export →
`load_model(checkpoint/export)` → `generate_audio`.
- Agents follow training with `get_job(kind="training", wait_s=50)`
instead of `studio_status`.

### Prefetch

- `ALLOWED_PREFIXES` gains exactly `/api/hub/download`. That covers
`/download`, `/download-status`, `/download-progress` and
`/download/cancel`, and nothing else under `/api/hub`.
- `download_model(model, kind, variant?)` starts a download without
loading anything. GGUF repos send `gguf_variant`, image and video send
their download-plan entries with `scope_id="diffusion"`, a native TTS or
audio model sends its audio download-plan entries (companion codec repos
included) with `scope_id="audio"`, and STT reuses `download_stt`. Image
and video downloads take the same options `load_model` takes
(`memory_mode`, `speed_mode`, `transformer_quant`, `text_encoder_quant`,
`h3_task`), so the plan stages the files the load will read.
- The id carries each start's `generation`, so
`cancel(kind="model_download", id)` (through `/download/cancel`) stops
only the run `download_model` started. `get_job(kind="download", id)`
reads `/download-status` and works with `wait_s`.
- An image or video download that fails part-way stops the parts it
already started. A cancel stops every part before it reports a refusal.
- `repo:variant` shorthand downloads and waits on that variant. A native
speech prefetch under `kind="tts"` or `"audio"` serves a load of either
kind.
- K16 guard 2: `load_model` waits for a running Unsloth Studio download
of the same model or variant before #14090's partial-variant refusal.
The wait runs inside the load job (#14090 now runs every pre-load read
there), so it outlives `wait_s`: the call returns `loading` with a job
id, `get_job(kind="load")` names the download id while it waits, and the
load starts once the download ends. The wait is capped at an hour, after
which the load fails and names the download id. A managed download is
waited on, never refused. An attach to an in-flight load (guard 1) still
comes first, and an unmanaged partial variant is still refused.
- New outputs: `JobStatus.download` and `DownloadRef`.

`studio/MCP.md` gets the `download_model` row and updated `datasets` and
`start_training` rows.

## Testing

New tests: `test_mcp_tools_datasets_upload.py`,
`test_mcp_tools_datasets_images.py`,
`test_mcp_tools_training_validate.py`, `test_mcp_tools_download.py`,
`test_mcp_train_to_use.py` and `test_mcp_k16_guard_order.py`.
`test_mcp_server.py`, `test_mcp_forward.py`,
`test_mcp_no_host_paths.py`, `test_mcp_tool_contract.py` and the cancel,
jobs, placement, training and video tests were updated. #14090's
allowlist test now expects the whole download manager to be forwarded.
In #14090's `test_mcp_tools_plan_load.py`, the fake `download-status`
now reports only the partial Q8_0 as running: with guard 2, a
`load_model` waits on any running managed download, so a world where
every download is running made those loads wait out `wait_s`.

```bash
cd studio/backend
python -m pytest tests/test_mcp_*.py tests/test_gpu_arbiter.py tests/test_multi_model_always.py tests/test_multi_model_settings.py -q
```

Result on this head: 1,840 passed, 3 skipped.

GPU run on the head before the last two own commits (one device, real
Unsloth Studio on its own port, 91 MCP calls):

- **Train to use:**
- `datasets(upload)` with 40 rows returned a `ref:`, and `validate_only`
echoed the config with no paths.
- `unsloth/Qwen3-0.6B` trained for 10 steps (~57 s), followed with
`get_job(kind="training", wait_s)`.
- `load_model(checkpoint=<run>)` loaded it in 26 s, reported the name
only, and `chat` answered. `checkpoint-5` also loaded.
- `export_model(format="lora")`, then `get_job(kind="export")`, then
`load_model(export="<run>/lora")` and `chat` worked.
  - `unload_model(kind="all")` returned GPU memory to baseline.
- **TTS:** MOSS-TTS-Nano and Qwen3-TTS GGUF were refused with the
trainable list. Orpheus `validate_only` set `is_dataset_audio`.
- **Prefetch ("plan a film for a 24 GB card and prefetch everything",
GPU size stubbed):** zero calls went around MCP.
- `download_model` worked for Qwen3-4B-GGUF UD-Q4_K_XL, Z-Image-Turbo
and Wan2.2-TI2V-5B GGUF (already on disk, so they came back completed),
and audio.cpp TTS.
- FLUX.2-klein and LTX-2.3 (69 GB) were cancelled while running with
`cancel(kind="model_download")`.
- A `load_model` during a running download returned `loading` with a job
id and later finished.

No UI change.

## Not in this PR

- The INSTRUCTIONS prefetch sentence waits for the MCP errors PR
(#14081), which owns INSTRUCTIONS.
- After a checkpoint or export load, `studio_status` and
`unload_model(kind="all")` show its `ref:` handle (opaque, not a path)
instead of its name. That code is owned elsewhere; follow-up.
- GGUF and diffusion downloads report no percent, because
`gguf-download-progress` is left off the allowlist on purpose.
- A merged or LoRA export whose `save_directory` has only one level is
not found by name. Use `"<run>/<name>"`.
- Backend TTS refusals and an audio dataset builder are deferred.

## Follow-ups

- A safetensors repo whose id contains "gguf" is treated as GGUF by
`download_model` (no variant listed, so it is refused). This is the same
name-based rule #14090's `is_gguf` uses for loads, so prefetch and load
agree. Moving both to the listing signal is a follow-up.
- A `get_job(kind="load")` read in the same event-loop turn a trained
load finishes can still show its `ref:` handle, and a cancelled trained
load names the handle. The fix belongs in the shared load job runner.

---------

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