Skip to content

fix(studio): MLX memory estimate no longer allocates the model, and sizes DeepSeek V4 / V4.1 - #14325

Merged
danielhanchen merged 2 commits into
unslothai:mainfrom
Lyxot:mlx-estimate-fixes
Oct 20, 2026
Merged

danielhanchen merged 2 commits into
unslothai:mainfrom
Lyxot:mlx-estimate-fixes

Conversation

@Lyxot

@Lyxot Lyxot commented Oct 20, 2026

Copy link
Copy Markdown
Collaborator

Problem

Opening a model's Run Settings in Unsloth Studio runs the MLX memory estimate. On some models this exhausted memory before anything was loaded. On others it returned no estimate at all.

  • GLM-5.3-Flash: the estimate grew past 12 GiB of MLX memory, and was killed by the OS when uncapped.
  • Choosing a KV dtype: this ran a second probe that passed 7 GiB, even on Qwen3.8-Flash-Next, whose bf16 estimate stays at 0.6 GiB.
  • DeepSeek-V4-Flash and DeepSeek-V4.1-Flash: no estimate (unsizable).

Root causes

  1. The weightless probes evaluate. The cache plan (_probe) and the KV-quant check (_asking_the_architecture) work in three steps:

    • they build the language tower from config with random-init weights;
    • they run a forward pass on dummy tokens;
    • they read the cache's shapes.

    This stays lazy only while nothing evaluates. Some model code evaluates mid-forward:

    • mlx-vlm's glm5_next calls mx.async_eval(output) per chunk;
    • qwen4_exp's decode path calls mx.async_eval(hidden), which the KV-quant probe's one-token call reaches.

    Each such call materializes every random weight it depends on.

  2. The estimate asked a different loader than unsloth_zoo uses. unsloth_zoo loads a text model through mlx-vlm when mlx-lm cannot build it (_mlx_vlm_only_text_model). The estimate always asked mlx-lm:

    • DeepSeek V4: mlx-lm has no deepseek_v4 module.
    • DeepSeek V4.1: mlx-lm's ModelArgs refuse its Engram layers.

Changes

  • weightless_forward() replaces mx.eval / mx.async_eval, once and under a lock, with wrappers. The wrappers do nothing while the calling thread is inside a probe; per-thread depth means generation and other requests on other threads evaluate as normal. Both probes run inside it. Shapes and nbytes need no evaluation, so plans are unchanged.
  • _builds_on_mlx_vlm(config) is true for the vision route, or when unsloth_zoo's _mlx_vlm_only_text_model says mlx-vlm builds the weights. Everything that depends on how the weights are built uses it:
    • the shards read;
    • quantization;
    • the whole-model and probe-tower builds;
    • the known-fallback tables.
  • _loads_as_vision is unchanged, so the drafter estimate and generation settings still follow the route Unsloth Studio serves the model on. Such a DeepSeek model is still served as text.

Validation

Each process ran capped at 6 GiB of footprint and a 4 GiB MLX limit. Estimates are at 8K context.

Model Before After
GLM-5.3-Flash-4bit >12 GiB, killed 0.58 GiB footprint; weights 190.0, KV 7.31, compute 7.24 GiB
Qwen3.8-Flash-Next, 8-bit KV >7 GiB 0.74 GiB footprint
DeepSeek-V4-Flash-4bit unsizable weights 141.1, KV 0.45, compute 1.20 GiB
DeepSeek-V4.1-Flash-MLX-2bit unsizable weights 222.4, KV 0.04, compute 0.92 GiB*

*V4.1 needs unslothai/unsloth-zoo#1892, which routes a config mlx-lm refuses to mlx-vlm. Without it, the load itself fails too.

  • Plans are bitwise identical with and without the deferral, for bf16 and 8-bit KV. Models: Qwen3.5-4B, gemma-4-e4b, gemma-4-26b-a4b, Qwen3.6-35B-A3B, Llama-3.2-3B.
  • Route change: 15 of 440 cached configs now take a different route, and none of those 15 could be built on mlx-lm.
  • Tests: the new tests were mutation-checked.
python -m pytest -q studio/backend/tests/test_memory_estimate.py -k "weightless or served_as_text"

Known limits

  • The V4.1 weight figure still includes 57 GiB of Engram tables that the load leaves on disk. The MLX offload change prices that.
  • Model code that calls .item() / .tolist() on a weight-dependent value would still evaluate. None of the models checked do this.

Lyxot added 2 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.
@Lyxot
Lyxot requested a review from danielhanchen as a code owner October 20, 2026 08:50
@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 ✅ Completed 2026-10-20T09:21:11.535811Z c989be3 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

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Can't wait for the next one!

Reviewed commit: c989be3fe7

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

@Lyxot

Lyxot commented Oct 20, 2026

Copy link
Copy Markdown
Collaborator Author

Review and CI check complete at c989be3fe7.

  • Codex: Didn't find any major issues on c989be3fe7, with no unresolved review threads.
  • CI: the upstream runs here were stuck pending, so CI ran on a staging PR in the fork with the same head commit and this PR's merge base as its base: 40 passed, 2 skipped, 0 failed.
  • Changes during the review: none. The head is unchanged since the PR was opened.

@danielhanchen danielhanchen self-assigned this Oct 20, 2026
@danielhanchen
danielhanchen merged commit 0753958 into unslothai:main Oct 20, 2026
debojyoti-dev pushed a commit to debojyoti-dev/unsloth that referenced this pull request Oct 22, 2026
…#14326)

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 unslothai#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 unslothai#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 unslothai#1893 and unslothai#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%
|
|---|---|
| <img
src="https://raw.githubusercontent.com/Lyxot/unsloth/316e447a9cfe788fcb25922cdf71dffede7ff865/mlx-disk-offload/1_glm_default_auto_offload.jpg"
width="360"> | <img
src="https://raw.githubusercontent.com/Lyxot/unsloth/316e447a9cfe788fcb25922cdf71dffede7ff865/mlx-disk-offload/2_glm_manual_experts_100.jpg"
width="360"> |
| 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) |
|---|---|---|
| <img
src="https://raw.githubusercontent.com/Lyxot/unsloth/316e447a9cfe788fcb25922cdf71dffede7ff865/mlx-disk-offload/3_deepseek_v41_default_auto_offload.jpg"
width="260"> | <img
src="https://raw.githubusercontent.com/Lyxot/unsloth/316e447a9cfe788fcb25922cdf71dffede7ff865/mlx-disk-offload/4_flash_next_manual_two_sliders.jpg"
width="260"> | <img
src="https://raw.githubusercontent.com/Lyxot/unsloth/316e447a9cfe788fcb25922cdf71dffede7ff865/mlx-disk-offload/5_dense_model_no_offload_row.jpg"
width="260"> |
| 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 |

```bash
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.

---------

Co-authored-by: Nilay Yadav <[email protected]>
Co-authored-by: Daniel Han <[email protected]>
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.

2 participants