Repository navigation
Studio: faster MLX load and reload, ready to serve when loaded - #16536
Conversation
… 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.
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. |
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.
|
Codex Review: Didn't find any major issues. Already looking forward to the next diff. Reviewed commit: ℹ️ 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". |
…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.
|
Codex Review: Didn't find any major issues. Bravo. Reviewed commit: ℹ️ 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 |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 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".
| if not self._resume_files or self._resume_files != self._resume_weight_files(): | ||
| return None |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
|
Codex Review: Didn't find any major issues. Nice work! Reviewed commit: ℹ️ 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". |
NilayYadav
left a comment
There was a problem hiding this comment.
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.
Review + reproduction evidencePinned review: I reproduced loading and reloading mlx-community/Qwen3.5-0.8B-4bit on the merge base
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.
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. |
## 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.  --------- Co-authored-by: Daniel Han <[email protected]>

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:
trust_remote_codeafter the worker had already loaded the model, which blocked the response for about 8 s on a Hub read.model_inforead inside the worker, made because a 5 s memo had expired between the two checks.adapter_config.json,tokenizer_config.json,config.json), made one after another, each with its own TLS handshake.model_inforead waiting for the stack imports to finish.Changes
One commit each, in order:
auto_mapfrom the snapshot it just opened, and the route resolvestrust_remote_codefrom 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) staysNoneand takes the Hub path as before.model_infoper worker load.pinned_hf_reachability(verdict)reuses the worker's own probe result, and a nestedshared_hub_model_info()scope shares one response across the load's checks. Both are held only for the load and closed with it.max_seq_lengthis 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.model_inforead runs on a thread whiledetect_hardwareimports the stack, and is joined beforemlx_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
--stableA/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.The Zoo PR accounts for about 1.5 s of the last column. This PR does not depend on it.
Risks and tradeoffs
utils.models.model_configbeforedetect_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 rawurllib, as the sequential reads did, so nothing imports huggingface_hub or transformers ahead of the sidecar'ssys.pathinsertion.Validation