Skip to content

feat(studio): MLX PLE and expert offload in Unsloth Studio - #14326

Merged
danielhanchen merged 34 commits into
unslothai:mainfrom
Lyxot:mlx-moe-ple-offload
Oct 22, 2026
Merged

danielhanchen merged 34 commits into
unslothai:mainfrom
Lyxot:mlx-moe-ple-offload

Conversation

@Lyxot

@Lyxot Lyxot commented Oct 20, 2026

Copy link
Copy Markdown
Collaborator

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

  • LoadRequest and EstimateMemoryRequest take mlx_offload: a knob for both parts or a {ple, experts} object. Each knob is null or "auto" (the default), "off", or a fraction in (0, 1].
  • The backend passes the request to unsloth_zoo's 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.
  • Load, status and already-loaded responses carry one nested mlx_offload object. It holds what was requested, what was applied, the reason a part was not offloaded, and the bytes read from disk.
  • The memory estimate reports mlx_offloadable, the parts this checkpoint can offload, so the UI shows controls only where they apply.

Auto decision

  • Shared pricing: the memory estimate and the load use Unsloth Studio's own pricing, with unsloth_zoo's eligibility and footprint formula. Experts the runtime would keep resident are never priced as offloaded.
  • Context rule: the context may take at most half of what the resident weights leave. The planner then takes the least offload that fits the rest, PLE first and then experts.
  • Unset context: when experts would leave memory, the context first shrinks to 8K, matching unsloth_zoo's rule.
  • Loads Unsloth Studio does not price keep Auto off: distributed loads, adapters, and an explicit dtype.
  • Refusals: a load that unsloth_zoo refuses to offload, for example with runtime quantization, reloads without offload.

Per-model settings

  • Stored overrides: mlx_ple_offload and mlx_expert_offload are stored per model (schema 12) and synced with server overrides, so auto-switch, /models/load and the picker keep the user's choice.
  • Older clients: a save that omits a knob keeps the stored value, so a client that predates these knobs does not clear them.
  • Model config page: one Disk Offload row, laid out like the GGUF GPU Memory row and placed just above Chat Template. Default leaves offload to Auto. Manual shows an Experts on Disk and a PLE on Disk slider, 0–100% in 5% steps, each with an Auto step below 0% (off). They start from what Auto would pick for the current settings. The row appears only for checkpoints with something to offload, or a saved choice. Why a part was not offloaded is noted under it, and the on-disk share is shown on the Weights line.

Estimate correctness

  • DeepSeek V4.1 Engram: mlx-vlm reads a deepseek_v41 model'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.
  • Checkpoint code: pricing builds the checkpoint lazily. mlx-vlm imports a checkpoint's own model_file without 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.

GLM-5.3-Flash-4bit, Default GLM-5.3-Flash-4bit, Manual, experts 100%
Auto puts 77% of the experts on disk and fits the context at 8K (81.5 GiB). All experts on disk: weights drop to 32.6 GiB and the context fits up to 48K. Only an experts slider, since GLM has no PLE.
DeepSeek-V4.1-Flash-MLX-2bit, Default Qwen3.8-Flash-Next-4bit, Manual Dense model (Llama-3.2-3B)
Auto puts 59% of the experts on disk; the Engram tables are not counted as resident. Both parts offloadable: Manual starts each slider at Auto's choice. The left end of a slider is Auto, then 0% (off). Nothing to offload, so there is no Disk Offload row.

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:

    • tsc is clean.
    • The offload-related frontend tests pass (10 files, 503 tests), including the Default/Manual and slider conversions.
    • The startup bundle budget is raised by the measured growth: +7,439 B raw / +1,869 B transfer against main.
  • 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:

    • Auto chose PLE 1.0 + experts 0.863 at the native 262K context. This was measured before the 8K-first rule.
    • The estimate (30.8 GiB) and the load made the same decision, and the load read 100.1 GiB from disk.
    • Load and status responses carried the offload warning, chat was coherent, and the peak process-tree footprint was 17.9 GiB.
    • A fixed fraction (PLE 1.0 + experts 0.75, 8K context) also loaded live. The estimate was 32.0 GiB, the load applied both parts, chat was coherent, and the peak process-tree footprint was 26.2 GiB.
  • Large models loaded through the same unsloth_zoo path on the M3 Max (numbers in the unsloth-zoo PR):

    Model Footprint, experts fully on disk
    GLM-5.3-Flash-4bit 21 GiB
    DeepSeek-V4-Flash-4bit 9.7 GiB
    DeepSeek-V4.1-Flash-MLX-2bit 8.1 GiB
python -m pytest -q studio/backend/tests/test_memory_estimate.py studio/backend/tests/test_memory_contract.py studio/backend/tests/test_mlx_inference_backend.py studio/backend/tests/test_openai_auto_switch.py tests/studio/test_cli_attach_load_knobs.py

Risks and tradeoffs

  • Auto changes behavior only for models that would not otherwise fit. For those, generation is disk-bound, several times slower than resident, and the load response warns about it.
  • Different offload settings mean different loads. A resident model whose offload request differs from a new one is reloaded rather than reused.

Lyxot added 9 commits October 20, 2026 16:49
…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.
@Lyxot
Lyxot requested a review from danielhanchen as a code owner October 20, 2026 09:13
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 20, 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-22T10:19:29.540576Z
We couldn’t complete this review. Comment @codex review to try again.
894880a 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 commented Oct 20, 2026

Copy link
Copy Markdown
Collaborator Author

@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: 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".

@danielhanchen

Copy link
Copy Markdown
Member

(Python 3.13, l-r) fails on this PR in two estimate tests, including TestEstimateMemoryRoute.test_mlx_model_is_priced_and_itemized:

routes/inference.py:22526: in _estimate
    mlx_offload, mlx_offloadable = _mlx_estimate_offload(
routes/inference.py:15925: in _mlx_estimate_offload
    offload = mlx_resolve_offload(
core/inference/mlx_inference.py:2722: in mlx_memory_budget
    import mlx.core as mx
E   ModuleNotFoundError: No module named 'mlx'

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 mlx.core on that path. Guarding _mlx_estimate_offload so it reports no offload when MLX is not importable (or not on Apple Silicon) keeps the estimate working everywhere, and the existing test then covers that branch.

@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: 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".

Comment on lines +16006 to +16008
retains_history = (
not getattr(config, "is_vision", False) or mlx_vlm_snapshot_store_available()
),

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 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 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Fixed in 894880a: the estimate now drops the history reserve on any mlx-vlm route, a speculative text load included, matching the load.

@danielhanchen

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Something went wrong. Try again later by commenting “@codex review”.

Failed to sample tokens
ℹ️ 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

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Something went wrong. Try again later by commenting “@codex review”.

Failed to sample tokens
ℹ️ 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

Copy link
Copy Markdown
Member

pre-commit.ci run

@danielhanchen
danielhanchen merged commit 9880bc0 into unslothai:main Oct 22, 2026
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 22, 2026
… 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>
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