Skip to content

Studio: faster MLX load and reload, ready to serve when loaded - #16536

Merged
NilayYadav merged 16 commits into
unslothai:mainfrom
Lyxot:feat/mlx-load-experience
Nov 3, 2026
Merged

NilayYadav merged 16 commits into
unslothai:mainfrom
Lyxot:feat/mlx-load-experience

Conversation

@Lyxot

@Lyxot Lyxot commented Nov 3, 2026

Copy link
Copy Markdown
Collaborator

Problem

On the MLX backend, loading a model in Unsloth Studio or reloading it with new settings took about 38 s for a 4B model, even when its weights were already in the page cache. Most of that time was not loading: the server and the worker waited on Hub round trips one after another, then paid fixed waits. A changed context length always started a fresh worker that read the weights again. The first request after a load also hit code paths the load had not warmed.

Tracing a reload on Qwen3.5-4B-4bit showed where the time went:

  • Resolving trust_remote_code after the worker had already loaded the model, which blocked the response for about 8 s on a Hub read.
  • A second reachability probe and a second model_info read inside the worker, made because a 5 s memo had expired between the two checks.
  • A fixed 2 s memory settle that a new MLX worker gains nothing from: it first reads memory seconds after spawn, after the old worker's memory is back.
  • Transformers activation's three raw Hub reads (adapter_config.json, tokenizer_config.json, config.json), made one after another, each with its own TLS handshake.
  • The first model_info read waiting for the stack imports to finish.

Changes

One commit each, in order:

  1. trust_remote_code from the loaded files. The worker reports the auto_map from the snapshot it just opened, and the route resolves trust_remote_code from that instead of reading the Hub again. Resolution order is unchanged (stored value, value used, YAML, then this answer). Anything the snapshot cannot speak for (adapters, precision folders, substituted repos, an unreadable config) stays None and takes the Hub path as before.
  2. One reachability answer and one model_info per worker load. pinned_hf_reachability(verdict) reuses the worker's own probe result, and a nested shared_hub_model_info() scope shares one response across the load's checks. Both are held only for the load and closed with it.
  3. No memory settle on MLX when no figure is expected. With an expected free-memory figure, or on CUDA, the settle runs as before.
  4. Warm the resident batch at load. Before reporting loaded, the backend serves three real replies through the batch the Studio requests take: greedy twice, then sampled. Greedy runs twice because a scope settles what its first reply imported only the next time it opens. Afterwards it clears the prompt cache, keeps the drafter's cache headroom, and restores the MLX RNG state.
  5. Shrink a pinned context in the worker that holds the weights. An idle MLX load whose only change is a smaller pinned max_seq_length is applied in place. Anything that a fresh load could plan differently takes the fresh path: a wider or auto context, applied offload, KV quantization, a stretched or refused drafter. So does any refusal by the worker.
  6. Overlap the worker's Hub reads. Activation's three reads start together, at the same time as the worker's reachability probe. The first model_info read runs on a thread while detect_hardware imports the stack, and is joined before mlx_refusal. Each answer is used once, by the read that would have made it, and only for the same URL and credential. So the requests and the answers are unchanged, and nothing outlives the worker. Offline and local-path loads start nothing.

Results

Qwen3.5-4B-4bit on an M3 Max, a live server driven over real HTTP, with every Hub read online. Each column comes from two --stable A/B pairs, run in opposite orders. Commits 1-5 and commit 6 were measured in separate runs; the same 1-5 build measured 29.93 s and 27.91 s to load across those runs.

main commits 1-5 + commit 6 and unslothai/unsloth-zoo#2371
load 38.72 s 29.93 s 20.92 s
reload, new settings 38.07 s 25.27 s 15.86 s
reload, smaller pinned context 38.47 s 4.78 s 4.03 s
first-request TTFT 0.27 s 0.19 s 0.18 s
second-request TTFT 0.17 s 0.18 s 0.16 s

The Zoo PR accounts for about 1.5 s of the last column. This PR does not depend on it.

Risks and tradeoffs

  • Hub freshness is unchanged. No Hub revision check is skipped and no cached load goes offline. The reads in commit 6 are the same requests made a few seconds earlier, inside the same worker process.
  • Early imports. The worker now imports utils.models.model_config before detect_hardware. I checked that this import pulls in no ML stack (no torch, transformers, huggingface_hub, or mlx) and does not touch the hardware singleton. The activation threads use raw urllib, as the sequential reads did, so nothing imports huggingface_hub or transformers ahead of the sidecar's sys.path insertion.
  • Narrowing in place (commit 5) covers only the case where the existing allocation is provably enough. Everything else reloads.
  • Test share. The tests are a large share of the diff. Each test fails when the behavior it covers is broken on purpose.

Validation

cd studio/backend
python -m pytest tests/test_mlx_load_trust_from_snapshot.py tests/test_mlx_reload_skips_redundant_waits.py tests/test_mlx_load_warm_and_narrow.py tests/test_mlx_load_hub_reads_ahead.py -q
# 44 passed
  • Per commit: each commit passes its own tests at that commit.
  • Mutation checks: the new tests catch 53 of 55 deliberate breakages. The two survivors are the warm-up skip for a load with no batch, and a reserved worker.
  • Live checks: the end-to-end A/B runs above. A live run caught a dispatcher that dropped the worker's narrowing reply, and a served context length that read the old attribute; both are fixed in commit 5.

Lyxot added 6 commits November 3, 2026 16:13
… loaded

The load response blocked on a Hub read for up to 14 s after the worker was ready. The worker now reads the snapshot it just opened. An adapter, a precision folder or a bitsandbytes substitution still takes the Hub path, since their files do not answer for the requested repo.
…LX load

The worker probed reachability, then probed again 17 s later once the memo's 5 s lifetime had passed, and read model info repeatedly. The probe's verdict is now pinned for the load, and nested model info scopes join the open one.
…o wait for

The fixed 2 s wait protected a reading nothing takes yet: the new worker first reads memory seconds after its imports, past the old worker's reclaim. A caller's expected figure is still waited for.
…loaded

The warm-up generation misses the resident batch path, so a first request still built its kernels and ran first-use checks. A load now serves short replies through that batch, keeping the RNG and leaving no prompt cache behind. Checks keyed by a prompt's length still run on the request that reaches them. The GPU keep-warm also starts at load, so the first request does not meet an idle GPU.
…eights

A reload that only pins a smaller context no longer replaces the worker and reads the weights again. A wider or auto context, an applied offload, KV quantization, a stretched or refused drafter, or any other changed setting still takes a fresh load, since a fresh load could plan those differently, and a worker that declines is replaced as usual.
…ports

Transformers activation made three raw Hub reads one after another, each paying its own TLS handshake, and the first model_info read waited for the stack imports to finish. Both now start early on threads, and each answer is consumed by the read that would have made it, so the requests and the answers are unchanged.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 3, 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 ✅ Completed 2026-11-03T15:57:26.335460Z 66af336 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.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

Lyxot added 2 commits November 3, 2026 18:11
An MLX load's checks share one model_info response, and the first read can happen before the load's rejected-token scope opens. A credential that read refused, then recovered anonymously, never reached that scope, so the load kept the refused token for its weight downloads. Each shared answer now records whether it rejected the credential and replays that into the scope of the caller that reuses it.
A preferred drafter refused at the larger context may fit the smaller one, but narrowing in place kept whichever alternative had attached. Any drafter fallback now takes a fresh load, which plans the drafter again.
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Already looking forward to the next diff.

Reviewed commit: 9f2b8284bc

ℹ️ 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 added 2 commits November 3, 2026 18:49
…ontroller

The drafter's controller learns from every reply whether drafting pays, and the warm-up's replies ran on it while kernels were still cold. On a slow machine that taught it to stop drafting, so the first real replies decoded without the drafter. The warm-up now runs on a copy of the controller, as Zoo's own speculative warm-up uses a throwaway one, and the load-event test expects the warm-up's own RNG-preserving block.
load_model now also calls on_prior_worker_released when it narrows the context in the held worker, which has no teardown to wait for, so the source-order check reads the fresh path's call.
@NilayYadav NilayYadav self-assigned this Nov 3, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Nov 3, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Bravo.

Reviewed commit: 1d118e5a27

ℹ️ 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".

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@NilayYadav

Copy link
Copy Markdown
Collaborator

@codex review

1 similar comment
@NilayYadav

Copy link
Copy Markdown
Collaborator

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 66af336ffa

ℹ️ 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".

Comment on lines +6545 to +6546
if not self._resume_files or self._resume_files != self._resume_weight_files():
return None

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Verify the Hub revision before accepting in-place narrowing

When a loaded Hub repo's main advances and the parent's capability/tier probes are cached, this fingerprint can still match: _resume_weight_files() only stats local files, and ModelConfig.from_identifier() can observe the new model_info.sha without downloading anything or updating refs/main. A smaller-context reload then reports success while continuing to serve the old weights, whereas the previous fresh-worker path would resolve the updated revision. The added fingerprint check detects overwritten local checkpoints but does not establish remote freshness; compare the resolved Hub SHA with the loaded snapshot, or fall back to a fresh load when it cannot be verified.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not changing this: it needs the repo's main to move mid-session, and narrowing then keeps serving the revision the user already loaded, which is what a context change should do. A deliberate refresh still goes through a normal load.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Nov 3, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Nov 3, 2026
@unslothai unslothai deleted a comment from Lyxot Nov 3, 2026
@unslothai unslothai deleted a comment from Lyxot Nov 3, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Nov 3, 2026
@unslothai unslothai deleted a comment from Lyxot Nov 3, 2026
@unslothai unslothai deleted a comment from Lyxot Nov 3, 2026
@unslothai unslothai deleted a comment from Lyxot Nov 3, 2026
@unslothai unslothai deleted a comment from Lyxot Nov 3, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 66af336ffa

ℹ️ 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".

@NilayYadav NilayYadav left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you for the PR! The goal of this PR is to make MLX model loads and reloads in Studio much faster by removing waits that are not loading work. As a summary, this PR resolves trust_remote_code from the files the worker already opened, shares one Hub reachability verdict and one model_info answer per load, overlaps the worker's Hub reads with its imports, skips the memory settle on MLX when no figure is expected, warms the batch path before reporting loaded, and applies a smaller pinned context inside the worker that already holds the weights.

I pushed two small fixes on top: the Hub read-ahead now skips an existing local checkpoint directory (it was sending three Hub requests carrying the local folder name), and narrowing in place now falls back to a fresh load when the weight files changed since the load. No blocking findings remain.

Reviewers Severity Finding
1/15 Low The worker side of narrow_context has no direct test; dropping that branch would silently lose the speedup
1/15 Low Two tests match source strings and break on refactors without a behaviour change
1/15 Low The pre-kill free memory sample is unused on MLX now that the settle is skipped

None of these block the merge; they are small follow ups.

@NilayYadav

Copy link
Copy Markdown
Collaborator

Review + reproduction evidence

Pinned review: 66af336ff. 2 findings, fixed in ed8f43a and 66af336.

I reproduced loading and reloading mlx-community/Qwen3.5-0.8B-4bit on the merge base 24d65c19d (Apple Silicon Mac, two clean installs, same MLX 0.32.4 / mlx-lm 0.32.2 / zoo 2026.11.1):

  • Before (run): reload to a smaller context took 53.5 s and 114.3 s, a wider reload 44.5 s and 65.0 s. With the change reverted, the new tests fail at assert events == ["gate_up", *warmed] and 44 tests fail plus 5 errors in the backend suite.
  • PR head (run): reload to a smaller context took 1.9 s and 2.8 s (the same worker, served context 2048 then 1024), a wider reload 25.9 s and 29.9 s, first-request TTFT 0.12-0.32 s against 0.21-0.88 s. Replies were identical on both sides.

PR 16536 before/after

5 seconds after asking for a smaller context, the merge base chat still shows Select model while the PR already shows the model at 2.0k (19.4 s vs 1.4 s for the reload). Both end at 2048.

  • macOS 15 and macOS 26 runners with real MLX: 633 passed (2 torch-only audio tests need torch and are skipped there on main too). Linux, Windows and the Playwright smoke are green.
  • A local checkpoint directory no longer triggers Hub requests for its name (3 requests before, 0 after), and narrowing reloads when the weight files changed.

Conclusion: real and fixed; the reload with a smaller context is about 20x to 40x faster here and wider reloads are faster too; plain loads were within run to run noise on this machine.

@NilayYadav
NilayYadav merged commit 81dc73a into unslothai:main Nov 3, 2026
danielhanchen added a commit that referenced this pull request Nov 19, 2026
## Summary

Unsloth Studio's Run settings offered GGUF models controls that MLX
models either lacked or accepted and silently ignored. This PR wires
every Run setting MLX can honour through the load path end to end: the
Run settings panel, the load request, the memory estimate, chat
admission, the resident-model match and OpenAI-compatible API overrides.
Controls that only make sense for llama-server stay hidden for MLX: GPU
layers and tensor split, mmap/mlock, checkpoints and extra server
arguments.

The Vision-off memory saving needs unslothai/unsloth-zoo#2600. With an
older unsloth-zoo the new load argument is ignored. Vision off then
stops image input but frees no memory.

## Changes

- **Vision.**
  - Turning Vision off on an MLX VLM stops image input.
- It also asks unsloth-zoo not to read the vision tower and projector at
all (`drop_vision_weights`). Where the load cannot skip them, it frees
them after the load (both need the unsloth-zoo change).
- The memory estimate, offload plan and context fit price such a load
without those weights.
  - Adapters and audio-input models keep vision.
- **Reasoning Budget and its message.**
- Every MLX reply path (mlx-lm, mlx-vlm, batched rows) adds a logits
processor. Once the budget is spent inside the reasoning block, it
forces the message and closes the block, as llama-server's
`--reasoning-budget` does. A budget of 0 closes the block as soon as it
opens.
- A budgeted mlx-vlm reply decodes without the drafter, because the
processor cannot follow a draft.
- **Micro-batch Size (`n_ubatch`).**
- Sets the MLX prefill step (tokens per prefill forward) on every path.
- The mlx-vlm prompt-cache grid follows it per load, so prompt reuse
stays shape-stable.
- With experts read from disk, the offload planner's chunk caps it, and
the estimate prices the same step.
- **Batch Size (`n_batch`).** Caps the tokens one batched prefill
forward takes across requests, like llama.cpp's logical batch. Unset
keeps the current behaviour of prefilling every waiting row at once.
- **Cache RAM.**
- The MLX prompt cache was fixed at 15% of the Metal working set, and it
comes out of the memory the context fit uses. Its size is now
selectable:
    - blank keeps the default;
    - 0 disables the cache;
- llama.cpp's `-1` (unlimited) loads as the default, because MLX shares
one memory pool with the model.
- A cache that takes the whole budget now reports that nothing fits,
instead of skipping the fit.
- **Applying settings in place.** A load that changes only the reasoning
budget, Batch Size or a smaller prompt cache updates the loaded worker
instead of reloading the weights. It extends the existing in-place
context narrowing path (#16536).
- A larger prompt cache or any other setting still reloads, because it
changes memory the load gave its context.
- The retune also refreshes the batching capabilities a reasoning budget
decides.
- **Echo and reload rules.** The MLX load echoes each setting, so a
reselected configuration matches the resident model. A changed setting
reloads unless it can be applied in place.

## Risks

- The memory estimate is priced on the assumption that the unsloth-zoo
change is present. With an older unsloth-zoo, a Vision-off estimate can
be lower than what the load actually holds.
- A budgeted mlx-vlm reply gives up speculative decoding, by design.

## Validation

Peak memory of a load with Vision off:

| Model | Vision on | Vision off |
|---|---|---|
| Qwen2.5-VL-3B | 2.86 GiB | 1.62 GiB |
| LFM2.5-VL-1.6B | 1.39 GiB | 0.61 GiB |
| GLM-4.6V-Flash | 6.31 GiB | 4.65 GiB |

The memory estimate is within 0.01 GiB of the measured peak.

Live `/load` timings on Qwen3.5-0.8B-4bit:

| Change | Path | Time |
|---|---|---|
| Full load | fresh | 14.2 s |
| Reasoning budget, Batch Size or a smaller Cache RAM | in place | 0.9
to 2.7 s |
| Smaller context and a budget | in place | 0.9 s |
| Larger Cache RAM or a Micro-batch change | full reload | 12 to 14 s |

Cache RAM checked live:
- Cache RAM 0 disables the cache.
- 512 MiB gives a 0.54 GB cache budget.
- The panel hydrates from the loaded model, and Reload stays disabled
while the settings match.

```bash
# backend
python -m pytest -q studio/backend/tests/test_memory_estimate.py studio/backend/tests/test_mlx_inference_backend.py studio/backend/tests/test_mlx_load_warm_and_narrow.py studio/backend/tests/test_multi_model_primary_fit.py studio/backend/tests/test_openai_auto_switch.py
# frontend
node --experimental-strip-types --test tests/chat-load-request-one-builder.test.ts tests/non-gguf-parallel-slots-baseline.test.ts tests/resident-config-match.test.ts tests/tensor-parallel-row-gating.test.ts tests/vision-toggle-gating.test.ts
npm run build
```


## UI before / after

Run settings for unsloth/Qwen2.5-VL-3B-Instruct with Advanced settings
on, merge base 14111b6 (BEFORE) vs PR head 304f61e (AFTER). These
rows only render on Apple Silicon, so the platform response
(`/api/health` `device_type`) was set to `mac` on both sides
identically. AFTER adds Vision, Batch Size, Micro-batch Size, Cache RAM,
Reasoning Budget and Reasoning Budget Message.

![MLX Run settings before and
after](https://raw.githubusercontent.com/danielhanchen/unsloth-staging-2/pr-media/pr/18426/pr18426_before_after_q-802134cfd353.png)

---------

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

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants