Skip to content

feat(studio): idle auto-unload an MLX chat model - #15680

Merged
danielhanchen merged 5 commits into
unslothai:mainfrom
Lyxot:mlx-idle-unload
Oct 28, 2026
Merged

danielhanchen merged 5 commits into
unslothai:mainfrom
Lyxot:mlx-idle-unload

Conversation

@Lyxot

@Lyxot Lyxot commented Oct 28, 2026

Copy link
Copy Markdown
Collaborator

Summary

Unsloth Studio's chat idle auto-unload only freed a primary GGUF model. An MLX chat model loaded on a Mac stayed resident forever, holding unified memory after the configured idle TTL even when it was loaded by an API client. This PR extends the idle loop to an MLX primary with the same rules as GGUF: it is freed after the TTL when no request is in flight or queued, a UI-loaded model stays resident when "Only unload models loaded by the API" is on, and the next request reloads it through the existing idle-reload path. With "Keep chat context across unloads" on, its prompt cache is saved before the unload and restored on reload, like GGUF slots.

Changes

  1. Idle auto-unload an MLX chat model (llama_keepwarm.py, orchestrator.py, routes/inference.py)
    • When no GGUF is loaded, the idle loop treats the orchestrator's active model as the primary if it is an MLX chat model. Speech models (TTS/STT) are excluded because the reload path skips their audio preflights.
    • The reload stash uses the shape the auto-switch reload branch already consumes: (model id, no quant, advertised id), so saved overrides are looked up under the same key.
    • UI-load provenance (_loaded_by_user_action) is now recorded on the orchestrator for a model it holds. The orchestrator clears it whenever it publishes a new load, so loads that bypass the load route (preview, auto-switch) never inherit a stale pin.
  2. Reload an idle-unloaded MLX model as MLX on a cold resolver index (routes/inference.py, llama_keepwarm.py)
    • local_target_is_gguf assumes GGUF for a repo id missing from the acting account's resolver snapshot. A managed account whose own scan was never built gets an empty snapshot while the stash is global, so the reload would read GGUF overrides and run GGUF-only request checks. The idle loop now records that the stash it wrote is MLX (stash_is_mlx(identity), valid only for that exact stash), and the reload branch uses that fact before the index heuristic.
  3. Keep the MLX chat context across an idle auto-unload (llama_keepwarm.py)
    • With keep-KV on, the loop calls the orchestrator's save_prompt_cache_for_resume(should_abort) (added in Studio: keep the MLX chat context when an image or video model takes the GPU #15358) in place of the GGUF slot save. It reuses the loop's existing manifest handling: a save dropped by a late request or a setting change deletes its files, and the reload restores through note_model_loaded(backend) → restore_kv_resume.

GGUF idle unload is unchanged. The in-worker MLX GPU keep-warm timer (#12721) never stamps the parent's idle clock and is ended by the unload command, so the two don't interact.

Risks / tradeoffs

  • Keep-KV defaults to on, so an idle MLX unload now writes the prompt cache to disk before freeing the model.
  • The save holds the lifecycle gate up to the orchestrator's 120s save timeout. This is the same shape as the GGUF idle save. A request that arrives meanwhile aborts the save and cancels the unload.
  • A failed orchestrator unload is still treated as freed, matching the GGUF branch, which also ignores its unload result.

Validation

Unit tests next to the existing idle-loop tests in tests/test_openai_auto_switch.py. They cover: the unload being blocked by in-flight work; unload, stash and reload of an API-loaded MLX primary with the prompt cache saved, restored and its files removed; a cold-index precondition; a save dropped after it was written; stash-format ownership; UI-pinned, non-MLX and speech-model orchestrator models staying loaded; and every orchestrator load publish clearing the UI pin.

cd studio/backend
python -m pytest tests/test_openai_auto_switch.py tests/test_swap_kv_resume.py tests/test_mlx_worker_audio_commands.py tests/test_keyless_api_access.py tests/test_scheduled_tasks.py -q -p no:cacheprovider
# 1208 passed, 1 skipped

Each new test was mutation-checked against the production line it guards (17 mutations, all caught).

Live, on Apple Silicon with mlx-community/Qwen2.5-0.5B-Instruct-4bit, a 60s TTL and "API only" on:

API-loaded model: freed after ~60s idle, MLX worker shut down
model-less /v1/chat/completions: reloaded the stashed model and answered
UI-loaded model: still resident 105s past the TTL
keep-KV on: idle save + restore logged; the same 2836-token turn after reload reported cached_tokens 2835

Lyxot added 3 commits October 28, 2026 14:10
The keep-warm idle loop only watched llama.cpp, so a primary MLX model held its unified memory indefinitely. It now frees an MLX primary on the same TTL, with the same in-flight and queued-request checks, the same "only unload models loaded by the API" pin, and the same reload stash, so the next request loads it back. Slot KV save stays llama-server only; MLX speech models stay loaded because the stash reload skips their audio preflights.

The UI-load pin for an MLX primary now lives on the orchestrator: the /load route sets it, and every orchestrator load publish clears it, so preview and auto-switch loads never inherit an earlier pin.
…ver index

The auto-switch reload of an idle-unloaded model classified its id with local_target_is_gguf, which reads a repo id missing from the acting account's resolver snapshot as GGUF. An MLX model stashed under its repo id could then reload with its saved overrides read as GGUF, its alias and provenance written to the llama backend, and GGUF-only request checks applied. The idle loop now records that the model it freed ran on MLX, and the reload trusts that before the index.
With "Keep chat context across unloads" on, the idle loop now saves an MLX chat model's prompt cache through the orchestrator before unloading it, as it already saved llama-server slots for a GGUF model. The next load of the same model restores it through the reload path that already restores a cache kept across a media swap, so the first turn after an idle reload does not re-read the conversation.
@Lyxot
Lyxot requested a review from danielhanchen as a code owner October 28, 2026 06:12
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 28, 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-28T07:25:02.123267Z
We couldn’t complete this review. Comment @codex review to try again.
c38c620 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.

@Lyxot Lyxot added the MLX label Oct 28, 2026
@Lyxot

Lyxot commented Oct 28, 2026

Copy link
Copy Markdown
Collaborator Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

An unknown error occurred
ℹ️ 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 danielhanchen self-assigned this Oct 28, 2026
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 28, 2026
danielhanchen added a commit that referenced this pull request Oct 28, 2026
…ugh run_pwsh (#15758)

## Summary

`Repo tests (CPU, studio)` fails on main, so it is red on every recent
staging CI run (#15680, #15696, #15716, #15723 and others). Of its 6
failures, 4 are tests that no longer match intentional changes; this PR
fixes those. The other 2 are real product slips on the login screen and
are fixed separately.

**Media picker contracts (3 failures).** #15726 lined the Images, Audio
and Video model pickers up with Chat:
- The picker now uses `className="ml-1.5 max-w-full overflow-hidden
!pl-2.5 !pr-1.5 !h-[var(--studio-chat-control-height,34px)]"`.
- It no longer sets a `triggerLabelClassName` override.

`tests/studio/test_desktop_reliability_frontend_contract.py` still
pinned the old class string and the old label override, and counted two
scaled `!h-[calc(34px*var(--ui-space-scale,1))]` literals on the Images
and Video pages (and one on Audio) that are now the shared token:

```
images-page.tsx states 1 scaled !h-34px, not 2
assert 'className="!h-[34px] max-w-full gap-1 ...' in header
```

**PowerShell spawn (1 failure).**
`tests/python/test_installer_compile_bytecode.py:271` (from #15646)
starts PowerShell with `subprocess.run`.
`tests/studio/test_pwsh_calls_use_the_shared_runner.py` forbids that,
because direct spawns share one PowerShell startup cache across xdist
workers and can die at startup.

## Change

- **`test_desktop_reliability_frontend_contract.py`:**
- The Images and Audio header contracts assert the new picker class
(`_MEDIA_PICKER_CLASS`), and that the label is not overridden, so the
trigger reads like Chat's.
- The scale table's `!h-34px` counts drop to what the pages still state
literally: Images 1, Audio 0, Video 1. The "no bare `!h-[34px]`" half of
that check is unchanged.
- New test `test_the_media_pickers_take_chats_scaled_control_height`:
all three pages use the picker class, and `index.css` still defines
`--studio-chat-control-height` as `calc(Npx * var(--ui-space-scale,
1))`. This keeps the original point of the scale check, a pill that
grows with the UI scale, attached to the token the height now comes
from.
- **`test_installer_compile_bytecode.py`:** the PowerShell case runs
through `run_pwsh` from `tests/_shared/unsloth_pwsh_runner.py`, with the
same argv and keyword arguments.

## Testing

- These three files: 80 passed (pwsh is installed here, so the
PowerShell cases really ran). On main, the same tests fail 4.
- **Sabotage:** with `--studio-chat-control-height` changed to a bare
`33px`, the new scaling test fails.
@danielhanchen

Copy link
Copy Markdown
Member

Review record for #15680, carried over from the mirror it was reviewed on: danielhanchen/unsloth-staging-review#586.

Findings are quoted as posted and attributed to the account that posted them. The reactions shown are the triage recorded on the mirror; none were re-applied here. Commits are named as the mirror's, with this PR's equivalent where one was found.

Round 1: reviewed mirror 87e5001e3f (this PR's d7094993a)

chatgpt-codex-connector[bot] (on the mirror)

Codex Review: Didn't find any major issues. Hooray!

Reviewed commit: 87e5001e3f

No triage reaction was recorded on the mirror

Verdict

The round converged at mirror 87e5001e3f (this PR's d7094993a).

This is the review as it stood at that commit. Anything pushed to this PR afterwards was not part of it.

@danielhanchen
danielhanchen merged commit 5379524 into unslothai:main Oct 28, 2026
6 of 51 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants