Skip to content

Studio: keep the MLX chat context when an image or video model takes the GPU - #15358

Merged
danielhanchen merged 7 commits into
unslothai:mainfrom
Lyxot:studio-mlx-swap-kv
Oct 27, 2026
Merged

danielhanchen merged 7 commits into
unslothai:mainfrom
Lyxot:studio-mlx-swap-kv

Conversation

@Lyxot

@Lyxot Lyxot commented Oct 26, 2026

Copy link
Copy Markdown
Collaborator

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_kv saves before the media acquire, gpu_arbiter._evict_chat promotes the save once it really unloads that model, llama_keepwarm holds 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.
  • Serialization: each entry is one safetensors file. The arrays are the tensors, and the cache object layout is pickled into the metadata with the arrays pulled out by persistent_id. This round-trips every cache class (mlx-lm and mlx-vlm KV, rotating, quantized, TurboQuant, CacheList, recurrent ArraysCache) without a codec per class. mlx-lm's own save_prompt_cache resolves class names in mlx-lm's module only, so mlx-vlm caches would come back as the wrong type. Unpickling admits only classes from mlx, mlx_lm, mlx_vlm and unsloth_zoo.mlx.
  • A restore happens only when a fingerprint matches exactly: the model, the size and mtime of its weight and JSON files, the mlx / mlx-lm / mlx-vlm versions, the load route, KV quant bits / TurboQuant, the KV window, int8 prefill, the prefill step and the load arguments. A distributed load never saves.
  • New worker commands 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's save_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 new mlx_prompt_cache_root(), removed if the save fails or is abandoned.

Studio wiring (second commit)

  • chat_swap_kv picks the saver for the resident chat model: llama-server slots for GGUF as before, otherwise the orchestrator when it serves an MLX model.
  • _evict_chat reads the MLX identity before unloading the orchestrator model and commits the pending save after it.
  • The orchestrator branch of the load route now passes the backend to note_model_loaded (off the event loop), and restore_kv_resume hands an MLX manifest to restore_prompt_cache_for_resume. A GGUF reload still drops an MLX stash, and an MLX reload still drops a GGUF one.
  • Deleting an MLX manifest also removes its directory, and the startup sweep removes leftover MLX save directories.

Risks and tradeoffs

  • Only the newest turn per store is kept, not every LRU entry, to keep the save inside the budget and the disk use small.
  • For mlx-vlm models the restore matches what the live process had: a turn shorter than the 2048-token snapshot step only has its replay snapshot, so the next turn re-reads that conversation with or without this change.
  • An abandoned save stops at the parent. The worker finishes the file it is writing, so the eviction's unload can wait for that one write past the budget. Reaching this needs a cache of hundreds of GB.
  • The restore waits on _gen_lock, so if a /v1 generation 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.
  • MLX idle auto-unload is out of scope; the idle loop only unloads GGUF today.

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_chat with a fake MLX orchestrator. Every one of 17 hand-written mutations of the guarded code fails the test that owns it.

cd studio/backend
python -m pytest -q tests/test_mlx_inference_backend.py tests/test_mlx_worker_audio_commands.py tests/test_swap_kv_resume.py tests/test_openai_auto_switch.py tests/test_gpu_init_crash_message.py
# 1623 passed, 1 skipped

Real worker on Apple Silicon (M3 Max): chat, save, kill the worker, reload, restore, next turn.

  • Qwen3-0.6B: the next turn read 116 of 158 prompt tokens from the restored cache, and its greedy reply matched a run from an empty cache exactly.
  • Qwen3.5-0.8B (mlx-vlm, hybrid layers), 3.6k-token turn: 2048 tokens reused, the same as a process that was never unloaded.

Live Unsloth Studio (API only): MLX chat turn, then POST /api/inference/images/load with Tongyi-MAI/Z-Image-Turbo, then reload the chat model and send the next turn.

image load phases: ['downloading', 'saving_chat_context'], evicted: Qwen/Qwen3-0.6B
Media swap: kept the chat slot KV for restore on reload
Restored the saved MLX prompt cache onto the reloaded model
turn 2 usage: prompt_tokens 3664, cached_tokens 3630   (Qwen3-0.6B)
turn 2 usage: prompt_tokens 3662, cached_tokens 2048   (Qwen3.5-0.8B)

The save directories were gone after the restore.

Lyxot added 2 commits October 26, 2026 19:22
…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.
@Lyxot
Lyxot requested a review from danielhanchen as a code owner October 26, 2026 11:26
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 26, 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-27T08:02:20.569313Z
We couldn’t complete this review. Comment @codex review to try again.
5359b47 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 26, 2026
@Lyxot

Lyxot commented Oct 27, 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".

@Lyxot

Lyxot commented Oct 27, 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 added a commit to Imagineer99/unsloth that referenced this pull request Oct 27, 2026
@danielhanchen
danielhanchen merged commit 20f3ac0 into unslothai:main Oct 27, 2026
55 of 56 checks passed
danielhanchen added a commit to Etherll/unsloth that referenced this pull request Oct 28, 2026
## 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]>
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.

2 participants