Repository navigation
feat(studio): MLX PLE and expert offload in Unsloth Studio - #14326
Conversation
…g the model The MLX memory estimate sizes the KV cache by running the language tower, built from config with random weights, on dummy tokens and reading only cache shapes. Model code evaluates mid-forward (mlx-vlm's glm5_next and qwen4_exp call async_eval per chunk or layer), which materialized every random weight: opening GLM-5.3-Flash's settings, or picking a KV dtype for Qwen3.8-Flash-Next, used tens of GB before any load. The probes now run with mx.eval and mx.async_eval deferred on their own thread; cache plans are unchanged.
…e weights on unsloth_zoo builds a text model mlx-lm cannot build (DeepSeek V4, and V4.1 whose Engram layers mlx-lm refuses) through mlx-vlm, but the estimate asked mlx-lm and so could not size either. The shard choice, quantization, whole-model and probe-tower builds and the known-fallback tables now follow the zoo's _mlx_vlm_only_text_model; the drafter estimate and generation settings keep the route Studio serves the model on, which stays text.
Adds mlx_ple_offload / mlx_expert_offload to the load and memory-estimate requests: null or "off" keeps the weights resident, a fraction in (0, 1] reads that share of the PLE tables / routed experts from disk through unsloth_zoo's FastMLXModel.from_pretrained(ple_offload=, expert_offload=). The memory estimate prices the offload with unsloth_zoo's own eligibility (offload.offloadable on the lazily loaded checkpoint, nothing evaluated) and footprint formula (offload_plan.offload_footprint), so experts the runtime keeps resident are never priced as offloaded. The load reports what unsloth_zoo actually applied (mlx_*_offload, *_requested, *_reason, mlx_offload_disk_bytes on load and status), fits its context to that, reloads without offload when unsloth_zoo refuses it for the load, and passes no knobs to an unsloth_zoo that cannot offload. A changed offload request reloads the model, and a CLI reattach keeps it.
mlx_ple_offload / mlx_expert_offload now default to auto (null or "auto"); "off" keeps the weights in memory and a fraction is applied as given. Auto applies unsloth_zoo's 50/50 rule to Unsloth Studio's own pricing: the context may take at most half of what the resident weights leave, and the least offload that fits the rest is taken (PLE tables first, then experts). The decision is the same in the memory estimate and the load. The load hands it to unsloth_zoo through from_pretrained(offload_plan=), so it is made on the checkpoint unsloth_zoo resolved and downloaded. Loads Studio does not price (distributed, adapters, an explicit dtype) keep auto off. A load whose estimate prices an offload fits its context inside unsloth_zoo's offload safety margin. The estimate reports the fractions it priced. The load, already-loaded and status responses warn when auto put weights on disk.
Per-model overrides now store `mlx_ple_offload` and `mlx_expert_offload`, so a model reloaded by auto-switch, `/models/load` or the picker keeps the offload the user chose. The payload takes `/load`'s values (null or "auto" for Auto, "off", or the fraction read from disk) and storage keeps only "off" or a fraction, Auto being the default. A save that omits a knob keeps the stored value, as the `engine_*` fields already do, so a client that predates the knobs does not clear them. Sending null or "auto" clears that knob alone: naming a knob is content, not the legacy "no fields means forget".
The estimate now lists mlx_offloadable, the parts unsloth_zoo's offload can read from disk for the checkpoint (its PLE tables, its routed experts), so the model settings show the offload controls only where they apply. Pricing builds the checkpoint lazily, and mlx-vlm imports a checkpoint's own model_file unconditionally (mlx-lm gates it on trust_remote_code), so pricing now refuses such a checkpoint instead of running its code.
… report it as one field
unsloth_zoo now takes a single offload= (a knob, a {ple, experts} dict, or a callable planner) and turns auto off under a load it cannot offload. The backend passes it that way, and the load, status and estimate payloads carry one nested mlx_offload object in place of the flat per-part fields. The CLI resends a resident's requested knobs from it.
The model config page offers PLE Offload and Expert Offload (Auto, Off, or 25-100% on disk) when the estimate reports the part offloadable, shows what Auto chose or why a part was not offloaded, and notes the on-disk share on the Weights line. The knobs are stored per model (schema 12), synced with the server overrides, sent with /load and the memory estimate, and compared by their requested values when matching a resident load.
… the MLX estimate mlx-vlm reads a deepseek_v41 model's Engram tables row by row from the checkpoint and never holds them (unsloth_zoo keeps them unread at load), yet the MLX estimate priced every shard byte as resident, overstating DeepSeek-V4.1-Flash by tens of GB. The estimate now leaves those tables out, at the width each path prices them, except when the load quantizes at runtime and so makes them resident.
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 |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 0b23e339d4
ℹ️ 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".
|
The memory estimate for an MLX model is also served on hosts without MLX (Linux and Windows browsing an MLX repo, and the CPU runners), and the new offload pricing now imports |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: e6c410772b
ℹ️ 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".
| retains_history = ( | ||
| not getattr(config, "is_vision", False) or mlx_vlm_snapshot_store_available() | ||
| ), |
There was a problem hiding this comment.
Price forced-VLM offload with the load's cache reserve
When a text model is routed through mlx-vlm for speculative decoding on an installation where mlx_vlm_snapshot_store_available() is false, this expression still sets retains_history=True solely because config.is_vision is false, while the actual load passes False because use_vlm is true. For loads near the planner threshold, the estimate therefore subtracts the prompt-cache reserve that the runtime does not retain and can report/price a larger automatic disk-offload fraction than the subsequent load applies; derive this value from the resolved loader route as the load path does.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 894880a: the estimate now drops the history reserve on any mlx-vlm route, a speculative text load included, matching the load.
[skip ci]
[skip ci]
…e mlx-vlm route [skip ci]
|
@codex review |
1 similar comment
|
@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 |
1 similar comment
|
@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". |
|
pre-commit.ci run |
…t settings settles
… on disk (unslothai#14466) Stacked on unslothai#14326 (MLX PLE and expert offload in Unsloth Studio). Only the last four commits are new here. It uses unslothai/unsloth-zoo#1918 (batch prefill step) and unslothai/unsloth-zoo#1919 (layer-at-a-time prefill); with an unsloth_zoo that lacks them, each path keeps its current step and grid. ## Summary With MoE experts read from disk, every prefill step re-reads the offloaded experts, so a larger step reads them fewer times per prompt. unsloth_zoo's offload planner already chooses that step (up to 8192, by the offloaded bytes re-read per prompt token), but Unsloth Studio pinned the planner to its own 2048 chunk, dropped the result and generated at 2048. Loads with experts on disk now prefill in the planned step, while prompt-cache reuse stays exact on mlx-vlm's 2048 grid. ## What changed - **Planned step:** - An auto offload plan lets the planner choose the step when experts may go to disk, pricing each candidate step as a load prefilling in it, and returns it. - When the load puts experts on disk, every generation path prefills in that step: mlx-lm single and batch, mlx-vlm single and audio input, and unsloth_zoo's batch generation when it takes a step. The memory estimate, the post-load context fit and the drafter fit price the same step. - Loads with resident experts, hand-set offload fractions and loads Unsloth Studio does not price keep the runtime's own step. - **Prefix reuse stays on mlx-vlm's grid:** - When unsloth_zoo runs every layer of a window as mlx-vlm-step sub-calls (`wide_prefill_step`), a session snapshots on mlx-vlm's step: boundaries inside a window are copied by the layers as they pass them (`capture_prefill_rows`), all-or-nothing over the cache entries. - A prefix-reuse session prefills in the planned window only where that holds and KV runtime quantization is off. Otherwise it prefills in mlx-vlm's step, so reuse never falls back to a coarser 8192 grid. - mlx-vlm prefills every prompt row but the last in chunks, so a resumed turn answers exactly as an unreused one when both chunk on the same grid. - **Under a KV window,** the planned window stays off for prefix-reuse sessions. Past a rotating window, mlx-vlm's Qwen3-VL derives position ids from the cache's write index once per forward, so a planned-window forward and mlx-vlm's steps would see different positions. Hybrid families build caches without a limit and keep the planned window. ## Performance Paired A/Bs on the same documents, 8K prompt, step 2048 vs the planned 8192 (with unslothai/unsloth-zoo#1919): | model | machine | time to first token | decode | peak memory | greedy tokens | |---|---|---|---|---|---| | Qwen3.8-Flash-Next-4bit, PLE + 75% of experts on disk | M5 Pro 48 GB | 41.2 -> 20.0 s (×0.49, se 0.005) | ×1.02 | 25.1 -> 26.8 GiB (priced by the estimate) | identical 4/4 | | Qwen3-VL-30B-A3B 3bit, experts offloaded | M3 Max 128 GB | 13.9 -> 7.6 s (×0.57) | ×1.00 | 5.7 -> 6.3 GiB | identical 4/4 | | Qwen3.6-35B-A3B 8bit, experts offloaded | M3 Max 128 GB | 16.0 -> 6.8 s (×0.51) | ×1.07 | 13.4 -> 14.1 GiB | identical 4/4 | Prefix reuse on Flash-Next, a 1K-token follow-up turn after a 9.7-15.7K first turn: resuming from in-window snapshots on the 2048 grid instead of the 8192 grid cuts time to first token from 17.7 s to 14.1 s (re-prefilled rows 5.5K -> 2.4K). ## Validation ```bash cd studio/backend python -m pytest tests/test_memory_estimate.py tests/test_mlx_inference_backend.py tests/test_mlx_vlm_prompt_cache.py -q ``` 854 passed. The same 16 tests fail on the head of unslothai#14326 without these commits (local environment and checkpoint pricing), and none fail newly. New tests cover: - the planner's step choice on the route the load takes; - the step reaching each generation path; - snapshot capture inside a window, all-or-nothing; - the window being refused under KV runtime quantization or a KV window. --------- Co-authored-by: Nilay Yadav <[email protected]> Co-authored-by: Daniel Han <[email protected]> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Requires unslothai/unsloth-zoo#1893, which adds
FastMLXModel.from_pretrained(offload=...). GLM-5.3-Flash and DeepSeek-V4.1-Flash also need unslothai/unsloth-zoo#1892 to load at all.Stacked on #14325. That PR keeps the MLX memory estimate from allocating the model and sizes DeepSeek V4 / V4.1 on the route unsloth_zoo loads them. Without it, opening Run Settings for GLM-5.3-Flash exhausts memory and the DeepSeek checkpoints get no estimate, so Auto cannot decide for them. Its two commits come first in this branch; the offload work starts at "feat(studio): load and price MLX PLE and expert offload", and the diff shrinks to these seven commits once #14325 merges.
Summary
Unsloth Studio can now load MLX models whose PLE tables or routed MoE experts stay in the checkpoint on disk. Auto is the default: a model that fits is loaded exactly as before. One that does not fit has the least offload that makes it fit applied automatically, with a warning. This lets a 128 GB Mac load models such as GLM-5.3-Flash (204 GB) and DeepSeek-V4.1-Flash (239 GB). Per-model controls let a user force a part off or set its on-disk share.
What changed
Load and estimate API
LoadRequestandEstimateMemoryRequesttakemlx_offload: a knob for both parts or a{ple, experts}object. Each knob isnullor"auto"(the default),"off", or a fraction in (0, 1].offload=. For Auto it passes a callable, so the decision is made on the checkpoint unsloth_zoo actually resolved and downloaded, before any weight is read.mlx_offloadobject. It holds what was requested, what was applied, the reason a part was not offloaded, and the bytes read from disk.mlx_offloadable, the parts this checkpoint can offload, so the UI shows controls only where they apply.Auto decision
Per-model settings
mlx_ple_offloadandmlx_expert_offloadare stored per model (schema 12) and synced with server overrides, so auto-switch,/models/loadand the picker keep the user's choice.Estimate correctness
deepseek_v41model's Engram tables from disk row by row. The estimate leaves them out at the width each path prices them, except when the load quantizes at runtime and so makes them resident. Before this, DeepSeek-V4.1-Flash was overstated by about 57 GiB.model_filewithout asking, so pricing now refuses such a checkpoint instead of running its code.Screenshots
Run Settings with the unsloth-zoo branches of #1893 and #1892 installed, on a 128 GB M3 Max. The checkpoints are only priced here, never loaded; opening each panel left the server at about 3.6 GB.
Validation
Backend tests cover the request and response shape, the Auto decision against the estimate, override storage and legacy saves, reload on a changed request, refusal fallback, and Engram pricing.
Frontend:
Mutation checks: every added backend guarantee has a hand-written mutation that its test catches.
Live checks ran on an isolated Unsloth Studio on an M5 Pro 48 GB, loading Qwen3.8-Flash-Next with no knobs and no context:
Large models loaded through the same unsloth_zoo path on the M3 Max (numbers in the unsloth-zoo PR):
Risks and tradeoffs