Skip to content

perf(studio): prefill MLX loads in the planned step while experts are on disk - #14466

Merged
danielhanchen merged 51 commits into
unslothai:mainfrom
Lyxot:mlx-offload-prefill-step
Oct 22, 2026
Merged

danielhanchen merged 51 commits into
unslothai:mainfrom
Lyxot:mlx-offload-prefill-step

Conversation

@Lyxot

@Lyxot Lyxot commented Oct 21, 2026

Copy link
Copy Markdown
Collaborator

Stacked on #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

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 #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.

Lyxot added 16 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.
# Conflicts:
#	studio/backend/core/inference/mlx_memory.py
#	studio/frontend/scripts/check-bundle-budget.ts
… on disk

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 then runs each offloaded layer's wide call as 2048-token sub-steps on full expert tables, so the per-layer working set stays that of a 2048 step. unsloth_zoo's offload planner already picks that step (up to 8192, by offloaded bytes re-read per prompt token), but Studio pinned the planner to its own 2048 chunk, dropped the result and generated at 2048. On Qwen3.8-Flash-Next (PLE and 75% of experts on disk, 8K prompt, M5 Pro) prefilling in 8192 instead of 2048 cut time to first token from 45.4 s to 20.7 s (prefill 181 to 397 tok/s); decode stayed at about 14 tok/s, peak memory rose from 25.1 to 26.8 GiB (priced by the estimate), and greedy output was identical.

An auto offload plan now 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, the prompt-cache snapshot and batch-row grids, and unsloth_zoo's batch when it takes a step), and 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 Studio does not price keep the runtime's own step.

Tradeoff: while experts are on disk, vision prompt-cache snapshots sit on an 8192-token grid instead of 2048, so prefix reuse is coarser (a prompt of 8192 tokens or fewer keeps no boundary snapshot, only the replay tail). Halving time to first token outweighs it.
…filling in the planned window

With experts on disk, an MLX VLM load prefills in the planned step (8192), which put prefix-reuse snapshots on an 8192-row grid, so a follow-up turn re-prefilled up to 8191 rows. When unsloth_zoo runs every layer of each window as mlx-vlm-step sub-calls (wide_prefill_step), the session now snapshots on mlx-vlm's step: a boundary inside a window is copied by the layers as they pass it (capture_prefill_rows), all-or-nothing over the cache entries. TurboQuant sessions, older unsloth_zoo, and models that run a window whole keep the window grid. VLM batch rows, never widened, prefill on the snapshot grid.
…ly where snapshots keep mlx-vlm's grid

Snapshots now always sit on mlx-vlm's step. A session prefills in the planned step (experts on disk) only where unsloth_zoo runs it layer by layer in mlx-vlm's steps and copies snapshots inside it, and KV runtime quantization is off; otherwise it prefills in mlx-vlm's step, so reuse never falls back to the planned step's coarser grid. mlx-vlm prefills every prompt row but the last in chunks and runs the last token alone, so a resumed turn answers exactly as an unreused one when both chunk on the same grid. Paths without prefix reuse keep the planned step.
Past a rotating KV window mlx-vlm's Qwen3-VL language model 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. A prefix-reuse session now prefills in the planned window only when no KV window is installed; hybrid families build caches without a limit and keep it.
@Lyxot
Lyxot requested a review from danielhanchen as a code owner October 21, 2026 06:55
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 21, 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-10-22T16:31:23.788567Z 65be781 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 added the MLX label Oct 21, 2026
@Lyxot

Lyxot commented Oct 21, 2026

Copy link
Copy Markdown
Collaborator Author

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

# Conflicts:
#	studio/frontend/scripts/check-bundle-budget.ts

[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@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: Didn't find any major issues. You're on a roll.

Reviewed commit: de1c25f0a9

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

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: Didn't find any major issues. Already looking forward to the next diff.

Reviewed commit: 65be781f4f

ℹ️ 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
danielhanchen merged commit d0bdc7a into unslothai:main Oct 22, 2026
48 of 51 checks passed
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