Repository navigation
Studio: keep the MLX chat context when an image or video model takes the GPU - #15358
Conversation
…nload The MLX worker can now write the newest turn of each prompt cache store (the mlx-lm LRU and the mlx-vlm snapshot store) to disk and load it back after the same model loads again. Arrays go into one safetensors file per entry and the cache object layout is pickled into its metadata, so every cache class round-trips; unpickling admits only MLX cache classes. A fingerprint of the weight files and the KV-affecting load settings must match for a restore. The orchestrator drives both through new worker commands.
…takes the GPU When Keep chat context across unloads is on and an image or video load is about to evict an MLX chat model, the swap now saves the MLX worker's prompt cache the way it saves llama-server slots for a GGUF chat model. _evict_chat promotes the save with the identity it reads before unloading the orchestrator model, and the next load of the same MLX model restores it, so the next turn reads the conversation from the cache instead of prefilling it again. An MLX save is deleted with its own directory, and leftover save directories are swept at startup.
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
@codex review |
|
Codex Review: Something went wrong. Try again later by commenting “@codex review”. ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
|
@codex review |
|
Codex Review: Something went wrong. Try again later by commenting “@codex review”. ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
…und and protect the save like llama-slots [skip ci]
## 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 unslothai#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 (unslothai#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. ```bash 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: ```text 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 ``` --------- Co-authored-by: Daniel Han <[email protected]>
Summary
#14108 made Unsloth Studio keep a GGUF chat model's context when an image or video load takes the GPU: the slots are saved before the eviction and restored when the same model loads again, as long as "Keep chat context across unloads" is on. An MLX chat model did not get this. Its prompt cache lives in the inference worker subprocess, which the eviction kills, so the next turn after an image or video generation re-read the whole conversation.
This PR gives MLX chat models the same behavior through the same path:
chat_swap_kvsaves before the media acquire,gpu_arbiter._evict_chatpromotes the save once it really unloads that model,llama_keepwarmholds it as the reload stash, and the next load of that model restores it. The "saving chat context" load phase, the 45 s save budget, the setting and the frontend are unchanged.What changed
MLX worker (first commit)
MLXInferenceBackend.save_prompt_cache_for_resume(directory)writes the newest turn of each prompt cache store: the last entry of the mlx-lm LRU (including one held over the LRU budget), and for mlx-vlm the newest turn's boundary snapshot plus its replay snapshot.restore_prompt_cache_for_resume(manifest)inserts them back into the stores.persistent_id. This round-trips every cache class (mlx-lm and mlx-vlm KV, rotating, quantized, TurboQuant,CacheList, recurrentArraysCache) without a codec per class. mlx-lm's ownsave_prompt_cacheresolves class names in mlx-lm's module only, so mlx-vlm caches would come back as the wrong type. Unpickling admits only classes frommlx,mlx_lm,mlx_vlmandunsloth_zoo.mlx.save_prompt_cache/restore_prompt_cache, answered by request id in both command loops (a backend without a prompt cache, or a batch with rows in flight, answers with an error rather than leaving the parent to time out). The orchestrator'ssave_prompt_cache_for_resume(should_abort)/restore_prompt_cache_for_resume(manifest)send them under_gen_lock. Each save gets its own directory under the newmlx_prompt_cache_root(), removed if the save fails or is abandoned.Studio wiring (second commit)
chat_swap_kvpicks the saver for the resident chat model: llama-server slots for GGUF as before, otherwise the orchestrator when it serves an MLX model._evict_chatreads the MLX identity before unloading the orchestrator model and commits the pending save after it.note_model_loaded(off the event loop), andrestore_kv_resumehands an MLX manifest torestore_prompt_cache_for_resume. A GGUF reload still drops an MLX stash, and an MLX reload still drops a GGUF one.Risks and tradeoffs
_gen_lock, so if a/v1generation starts between the load being published and the restore, the load response waits for it. The Studio chat UI waits for the load response before it chats.Validation
Tests for the save and restore round trip on real mlx-lm caches (newest entry only, fingerprint mismatches refused, replay flags kept, the over-budget entry), the unpickler refusals, the worker replies, the orchestrator's directory cleanup, and the swap flow through the real
_evict_chatwith a fake MLX orchestrator. Every one of 17 hand-written mutations of the guarded code fails the test that owns it.Real worker on Apple Silicon (M3 Max): chat, save, kill the worker, reload, restore, next turn.
Live Unsloth Studio (API only): MLX chat turn, then
POST /api/inference/images/loadwith Tongyi-MAI/Z-Image-Turbo, then reload the chat model and send the next turn.The save directories were gone after the restore.