Skip to content

perf(studio): keep the MLX GPU warm for a bounded time after generation - #12721

Merged
danielhanchen merged 2 commits into
unslothai:mainfrom
Lyxot:perf/mlx-gpu-keep-warm
Oct 5, 2026
Merged

danielhanchen merged 2 commits into
unslothai:mainfrom
Lyxot:perf/mlx-gpu-keep-warm

Conversation

@Lyxot

@Lyxot Lyxot commented Oct 5, 2026

Copy link
Copy Markdown
Collaborator

What changes

After a generation finishes, the MLX worker submits a tiny GPU operation every half second while idle, for up to 60 seconds. Unloading or resetting the model clears the window. UNSLOTH_MLX_GPU_KEEP_WARM=0 disables it; it is on by default.

Why

Apple GPUs drop their clock within a second or two of going idle and take several requests to ramp back up. A chat turn that follows a short pause therefore starts on a slow GPU; on small models the first requests after idle were measured up to 35% slower.

Measured

Unsloth Studio over HTTP, Qwen3.5-2B 4-bit, 1K-token prompt, 256 generated tokens, 3 s pause between requests, same build with the variable off and on:

time to first token decode
off 389 ms 228.4 tok/s
on 376 ms (-3.3%) 229.2 tok/s

One "off" block and two "on" blocks of four requests each.

Trade-off

Idle power use is higher for up to 60 seconds after each generation. It does not make the model's computation faster; it only avoids the ramp.

Validation

python -m pytest studio/backend/tests/test_mlx_worker_audio_commands.py -q

@Lyxot
Lyxot requested a review from danielhanchen as a code owner October 5, 2026 05:31
@Lyxot
Lyxot force-pushed the perf/mlx-gpu-keep-warm branch from d540721 to 879bddd Compare October 5, 2026 05:37
@Lyxot Lyxot added the MLX label Oct 5, 2026
@Lyxot

Lyxot commented Oct 5, 2026

Copy link
Copy Markdown
Collaborator Author

Staging run for head 879bddd122 (same commit, in my fork: Lyxot#132):

@shimmyshimmer

Copy link
Copy Markdown
Member

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

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 5a1785bfcf (this PR's 879bddd12)

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

Codex Review: Didn't find any major issues. Keep it up!

Reviewed commit: 5a1785bfcf

No triage reaction was recorded on the mirror

Verdict

The round converged at mirror 5a1785bfcf (this PR's 879bddd12).

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 d4bfbd9 into unslothai:main Oct 5, 2026
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.

3 participants