Skip to content

Studio: MCP agents follow long work in one call and see every model a load unloads - #14089

Merged
danielhanchen merged 70 commits into
unslothai:mainfrom
Etherll:Etherll/mcp-long-work-evictions
Oct 19, 2026
Merged

danielhanchen merged 70 commits into
unslothai:mainfrom
Etherll:Etherll/mcp-long-work-evictions

Conversation

@Etherll

@Etherll Etherll commented Oct 17, 2026 •

Copy link
Copy Markdown
Collaborator

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"; Studio: MCP errors, cancels and chat controls agents can act on #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

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.

… load unloads

- get_job takes wait_s (0-240 s): 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, with poll_after_s for a job still running. New kinds:
  training and diffusion_training (run folder and checkpoint names once
  completed) and load.
- load_model takes wait_s (unset: 240 s). The load runs as a job in a new
  studio_mcp/job_store.py, so a client that stops waiting never stops it; an
  early return gives status "loading" and a job_id for get_job(kind="load"),
  and a repeat call follows the load in flight.
- Loads report evicted_slots ({kind, model}) from the load answer's
  evicted_slots, else its evicted ids placed by a resident snapshot, else a
  before/after diff of the chat, image and video slots. unload_model echoes
  the kind asked for.
- export_jobs.py is a thin wrapper over the job store.
… 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.
… failed read, and keep media evictions

- A chat load started elsewhere is followed only when no variant is asked
  for (the status names only the repo), and a repeat call follows a load
  only with the same variant and settings.
- Following a load skips a failed status read instead of failing.
- A route's chat-only evicted list no longer hides an image or video model
  the load also unloaded; evicted is built from evicted_slots.
- Progress keeps its last fraction through a step that reports none.
…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-18T14:26:48.065507Z 53c03f7 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.

AhmedXN and others added 4 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.
…d a speech-to-text load past its download finishes before it unloads
…ncelling the MCP job does not stop a GGUF download
Etherll added a commit to Etherll/unsloth that referenced this pull request Oct 18, 2026
…mcp-load-placement

# Conflicts:
#	studio/backend/studio_mcp/tools/models.py
Etherll added a commit to Etherll/unsloth that referenced this pull request Oct 18, 2026
…a queued video that starts mid-read reports as that video

- unload_model(kind='all') marks this caller's running chat load_model
  jobs cancelled and names each in an unload, as the per-kind unload
  does after unslothai#14089, so freeing the GPU also stops a load in flight.
- get_job on a queue id whose video starts while its place in the queue
  is read now returns that video, not 'submitted' with a stale position.
AhmedXN and others added 2 commits October 17, 2026 23:36
… 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.
danielhanchen and others added 14 commits October 18, 2026 08:19
# Conflicts:
#	studio/backend/core/inference/gpu_arbiter.py
Etherll added a commit to Etherll/unsloth that referenced this pull request Oct 18, 2026
danielhanchen added a commit that referenced this pull request Oct 19, 2026
…cks takes and cancels by id (#14080)

Includes #14075 (Studio: clearer audio.cpp errors, cleaner Speak/Clone,
reproducible takes); review the non-merge commits from 14e6b65 to
HEAD (skipping #14075's own fix commits that came in by merge), or `git
diff dfa58e0..HEAD` against #14075's head.

## Summary

An agent using Unsloth Studio over MCP could not tell when a music
duration was clamped or an option was dropped, got bare error text from
audio.cpp failures, had no way to check a finished take, and could not
stop an audio run (`cancel` said "Audio runs cannot be cancelled"). This
adds those four things to the audio routes and the MCP tools.

## Changes

Audio routes:

- `/audio/run` answers with `applied` (the music `duration_s` actually
used) and `warnings` (`"duration_s 600 clamped to 240"`, plus one
`Ignored option <name>` line per entry in `ignored_options`). Clip rows
carry `voice_id` and `source_clip_id`, and Separate stem rows carry
`source_clip_id`.
- `/audio/run` takes an optional `cancel_id`. `POST /audio/cancel
{"cancel_id": ...}` stops that run the way a client disconnect does: it
answers 499 and saves nothing. The key is namespaced as `("audio", id)`,
so a chat `cancel_id` cannot stop an audio run. The run registers its id
before any model switch, so a cancel sent while a cold model is still
loading stops the run once the load ends, before anything is generated.
A cancel that arrives while the clips are being saved removes the clips
the run made, including an Edit source recording it saved (one an
earlier run kept, or one another Edit now plays, stays; an Edit's source
handoff and this cleanup share a lock), and still answers 499. A second
run under a `cancel_id` that a running audio run holds gets 409, so one
cancel never stops two runs. A cancel that arrives before the run starts
is kept for 30 s.
- New `POST /audio/analyze` measures an upload, history clip or saved
voice: duration, integrated loudness (BS.1770-4, gated), true peak (4x
oversampled), clipped samples (runs of 3+ identical samples at full
scale that the waveform lands on or leaves more steeply than a smooth
peak could: PCM rounds a clean peak to a flat top of L samples that it
leaves by at most about ((L + 1) / (L - 1))² quantization steps, so the
limit is twice that, using the WAV's own sample width (for 32-bit PCM
the float32 spacing near full scale, 2^-24). Clean 16-bit tones from 1
Hz to 2 kHz at 0.99-1.0 of full scale count 0 (400 random tones), and a
2% overdrive counts from 10 Hz to 1 kHz, in 8-bit too, where a clean
tone within 1% of full scale also reads as clipped because 8-bit is too
coarse to tell the two apart) and the span that holds sound (a final
partial 20 ms frame counts, so a 6 ms beep has a span). With
`expected_text` it transcribes with the resident speech-to-text model
(or the default) and returns `match_score`, 1 minus the word error rate,
or null when the two texts are too long to align (over 50 million word
pairs, about a quarter second of numpy work). Nothing is saved. Clips
over 10 minutes get 413. The measurements are in
`core/inference/audio_metrics.py`, which uses numpy only and walks the
audio in chunks: a 10-minute 48 kHz stereo clip needs about 21 MiB of
working memory on top of the decoded audio, and clipping runs are judged
per chunk, so even audio at full scale every other sample stays at a few
MiB. Transcript scoring runs off the event loop.
- An audio.cpp runtime that dies or goes silent mid-request on generate,
separate or music now raises a 500 with code `runtime_stopped` and the
message "The audio runtime stopped: <reason>. Try again; if it fails
again, load the model again." Paths and tokens are removed from the
reason. A failure that #14075 already classified (out of memory and so
on) is re-raised unchanged.

MCP tools:

- `generate_audio` returns `applied`, `warnings`, `ignored_options` and
`cancel_id`. It accepts a `cancel_id` and makes one (`mcp-<hex>`) when
omitted. A reused id that is still running or was cancelled in the last
30 s is refused.
- When the loaded music model makes variations one at a time
(`variations.how == "sequential"` in status), `generate_audio` sends
them take by take under one `group_id`, reusing take 1's seed, as the
Audio page does. A cancel between takes stops before the next POST and
keeps the finished takes. A take that fails after earlier takes
succeeded becomes a warning instead of losing the finished clips.
- `cancel(kind="audio", id=<cancel_id>)` stops a run: between takes it
stops locally, otherwise it posts to `/api/inference/audio/cancel`.
- Audio route failures with a known code now start with a `[code]` tag
and end with what to do next, from `AUDIO_HINTS` in
`studio_mcp/errors.py`. For example `[out_of_memory]` suggests
`device='cpu'` and lists the smaller variants when the error body
carries them (the `/v1` error envelope that `generate_audio` reads keeps
only the code, so there the hint stays generic), and `[runtime_stopped]`
says to retry once and then reload the model.
- `transcribe` gains `speakers` (labels each segment's speaker; it needs
a diarizing model and always uses the stored-audio route) and
`expected_text` (adds `match_score`).
- New `analyze_audio` tool wraps `/audio/analyze`. It is not marked
read-only, because inline audio or a path is uploaded to Unsloth Studio
first. If the speech-to-text model is not downloaded, the 409 hint says
to run `transcribe` once or leave out `expected_text`.
- `studio_status` lists the active music model's `duration_s` min, max
and default per mode as `audio_music`, so an agent can see the clamp
range before it asks for a duration.
- `studio/MCP.md` documents `analyze_audio` and the new `transcribe`
arguments. Its `cancel` row and the "Audio runs cannot be cancelled"
sentence are left alone here: #14081 rewrites that row into a
kind-agnostic form and #14089 removes the sentence, and those PRs own
those lines. The audio kind is documented in the `cancel` tool's own
docstring.

One small edit lands on #14075's code (the only edit outside this PR's
own files, in its own commit):

- d46103b: `_CODES` in `audio_cpp_failures.py` gains
`runtime_stopped`, so the worker and orchestrator keep that code when
they rebuild a failure.

## Testing

New tests:

- `tests/test_audio_metrics.py`: a -20 dBFS 1 kHz sine measures -23.0
LUFS and -20.0 dBTP within 0.05; hard clipping is detected and clean
full-scale 10 Hz, 100 Hz and 1 kHz sines are not, also as 16-bit WAVs at
10 Hz and 40 Hz and at 50 Hz and 0.999 of full scale, while a 10%
overdriven 10 Hz WAV is, and so is an overdriven 100 Hz 8-bit WAV; 8-bit
clipping counts on both rails; small chunk sizes give exactly the
one-pass numbers; padded silence gives the expected span; silence gives
`None`; cross-checks against pyloudnorm and jiwer when installed.
- `tests/test_audio_analyze_route.py`: metrics, `match_score` with a
stubbed transcriber, the speech-to-text 409, non-WAV input through
transcode, on both mounts.
- `tests/test_audio_edit_route.py`: a cancel during the save removes the
source recording the run saved (with or without a kept output) and keeps
one an earlier run saved or another Edit now plays.
- `tests/test_audio_run_cancel.py`: two concurrent runs with ids A and
B; cancelling A gives A 499 and B 200; a chat `/cancel` with id A stops
nothing; a cancel sent during a slow model load gives 499 and never
starts generation; a cancel sent while the clip saves gives 499 and
removes the saved clip; a second run under a live `cancel_id` gets 409.
- `tests/test_audio_run_extras.py`: `applied`, clamp and ignored-option
warnings, `voice_id` and `source_clip_id` on clip rows.
- `tests/test_audio_runtime_stopped.py`: generate, separate and music
map a mid-request stop to `runtime_stopped` with no path or token in the
message; an attached `out_of_memory` passes through unchanged; the code
survives the worker, orchestrator, route and `/v1` envelope.
- `tests/test_mcp_audio_takes.py`, `tests/test_mcp_audio_reports.py`,
`tests/test_mcp_audio_hints.py`: take-by-take runs and cancel during and
between takes, reused id refusal, batch mode as one request, reported
fields, and `[code]` hints.

Existing MCP contract tests (`test_mcp_server.py`,
`test_mcp_tool_contract.py`, `test_mcp_no_host_paths.py`,
`test_mcp_tools_audio.py`, `test_mcp_tools_status.py`) are updated for
the new tool, the `audio` cancel kind and the new output fields.

Results on c7d6ade (Linux, CPU):

- Every test file this PR touches (25 files, including
`test_audio_run_route.py` and `test_audio_edit_route.py`) plus
`test_audio_edit_requests.py` and `test_audio_gallery.py`: 1035 passed.
- On 2e46efe, all `tests/test_mcp_*.py`: 1475 passed, 3 skipped, 3
failed. The 3 failures are in `test_mcp_images.py` and fail the same way
on #14075's head (a transformers / huggingface-hub version mismatch in
the test venv).
- A live check on an earlier head: with a dead audio runtime injected on
the first request, a fresh agent driving the MCP tools got
`[runtime_stopped]`, retried once as the hint says, and got its clip.
- Negative controls: without the new except branches the three
runtime_stopped cases raise the bare runtime error; with
`runtime_stopped` removed from `_CODES` the orchestrator drops the code;
without the namespaced cancel key `/audio/cancel` stops nothing and a
chat `/cancel` would stop the audio run; without the run-length rule a
2-sample burst counts as clipping; with the cancel registered only after
the model switch (the previous code), the slow-load cancel test times
out because the run goes on to generate; without the after-save check
the save-time cancel answers 200 and keeps the clip.

The first commit (14e6b65) is the shared one-name-per-line reshape of
`test_mcp_server.py`, byte-identical to the same commit in the sibling
MCP PRs, so their tool-name additions merge cleanly.

```bash
cd studio/backend
python -m pytest tests/test_audio_metrics.py tests/test_audio_analyze_route.py tests/test_audio_run_cancel.py tests/test_audio_run_extras.py tests/test_audio_runtime_stopped.py tests/test_mcp_audio_takes.py tests/test_mcp_audio_reports.py tests/test_mcp_audio_hints.py tests/test_mcp_server.py tests/test_mcp_tool_contract.py tests/test_mcp_no_host_paths.py tests/test_mcp_tools_audio.py tests/test_mcp_tools_status.py -q
```

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Daniel Han <[email protected]>
# Conflicts:
#	studio/backend/routes/inference.py
# Conflicts:
#	studio/MCP.md
#	studio/backend/studio_mcp/loading.py
#	studio/backend/studio_mcp/tools/jobs.py
#	studio/backend/studio_mcp/tools/models.py
# Conflicts:
#	studio/backend/tests/test_mcp_tools_loading.py
@danielhanchen
danielhanchen merged commit e2a214b into unslothai:main Oct 19, 2026
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