Repository navigation
perf(studio): prefill MLX loads in the planned step while experts are on disk - #14466
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.
# 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.
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 |
|
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". |
# Conflicts: # studio/frontend/scripts/check-bundle-budget.ts [skip ci]
|
@codex review |
1 similar comment
|
@codex review |
[skip ci]
|
@codex review |
1 similar comment
|
@codex review |
…e mlx-vlm route [skip ci]
|
Codex Review: Didn't find any major issues. You're on a roll. 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". |
|
pre-commit.ci run |
…t settings settles
# Conflicts: # studio/frontend/scripts/check-bundle-budget.ts
|
@codex review |
1 similar comment
|
@codex review |
|
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". |
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
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.Performance
Paired A/Bs on the same documents, 8K prompt, step 2048 vs the planned 8192 (with unslothai/unsloth-zoo#1919):
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 -q854 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: