Skip to content

Keep image and video models loaded beside chat models on Apple Silicon - #15693

Merged
danielhanchen merged 19 commits into
unslothai:mainfrom
Lyxot:feat/studio-mac-media-coresidency
Oct 28, 2026
Merged

danielhanchen merged 19 commits into
unslothai:mainfrom
Lyxot:feat/studio-mac-media-coresidency

Conversation

@Lyxot

@Lyxot Lyxot commented Oct 28, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

On Apple Silicon, Keep multiple models loaded (When they fit / Always) never let an image or video model stay beside a chat model. Loading Z-Image while a chat model was resident unloaded the chat model under When they fit and was refused under Always. In practice the Images pill could not be used with a local chat model on a Mac.

Root cause

The co-residency check had no memory reading for the MLX device: get_device() == DeviceType.MLX returned non_accelerator, so every media load was denied. Two more gaps sat behind it:

  • The default MLX (mflux) image load had no price; only the diffusers path was priced.
  • Neither llama.cpp's Metal budget nor an MLX chat load accounted for a resident media model.

What changed

Commit 1: image and video models beside a GGUF chat model

  • One pool: unified memory is priced as a single pool. Its free memory is the smaller of the Metal wired headroom and available RAM, the same readings llama.cpp's Metal fit already uses. The diffusers streaming planner is skipped for this row.
  • MLX image price: an MLX image load is priced from the quantization plan it will take, using header sizes of the GGUF, text encoder and VAE, plus the decode headroom. A RAM-rule plan stays unpriced.
  • GGUF launch beside media: a GGUF chat launch nets the media model out of its Metal budget. The media model's weights come off the working set, and its unallocated generation headroom comes off available RAM, the wired headroom and the --fit-target floor. llama.cpp then fits its context to what is left, or reports the shortfall that makes room.
  • MLX chat stays guarded: an MLX chat model allocates its KV cache as it generates, and live readings don't show that. So a media load beside one still unloads it (When they fit) or is refused (Always). An unpriced non-GGUF chat load also evicts first under Always, because past the budget unified memory pages instead of failing.

Commit 2: MLX chat models beside image and video models

  • MLX chat price: an MLX chat load is priced before launch from the Run Settings estimate. The /estimate-memory MLX branch is factored into _mlx_load_estimate for this. The price is one row (weights, KV cache and compute at the context the load will serve), plus the prompt-cache reserve when the load keeps history, plus one KV cache and one prefill compute buffer per further parallel slot (rows prefill as one batch). It joins a resident media model when that fits; otherwise it frees media models only, never kept chat models, or is refused.
  • Recorded growth: the loaded entry records what it has yet to allocate (mlx_growth) and the worker's phys_footprint at load. An image or video load beside it is charged that growth minus what the worker has already grown, so cache that live readings already show is not counted twice.
  • GGUF netting: a GGUF launch beside a media model nets the same growth out of its Metal budget. An MLX entry with no recorded price is still treated as unpriced, as before.

CUDA behaviour is unchanged. Every new path is gated on the Metal pool, and an autouse test fixture keeps the existing verdicts off the Metal paths when the suite runs on a Mac.

Risks and tradeoffs

  • Speech is not priced: Read aloud (audio.cpp) speech is still unpriced on a Mac. A speech load after an image model evicts it under When they fit.
  • Footprint credit: the credit treats any worker growth since load as cache. Lazily filled offload caches could be credited as growth.
  • media_only: it is keyed on the platform rather than on the acquire carrying an MLX price.
  • Unbounded caches stay guarded: an MLX model whose cache has no enforced limit (no cache window, no per-request budget, or batched vision rows) records no growth. A media load beside it evicts it or is refused, and if it was admitted beside media at its estimate, the load settles afterwards: When they fit unloads the media model, Always undoes the chat load with the usual refusal.
  • GGUF to MLX switch earns no credit: an outgoing llama-server's footprint mixes CPU-only buffers with Metal ones, so replacing a GGUF primary with an MLX model beside media is priced without it and may evict or refuse when tight.
  • Pricing is conservative: each further parallel slot is priced at its KV cache plus its prefill compute, the reservation keeps the widest slot count admitted until the next reload, and an MLX image reserves the tiled decode peak.
  • Failed diffusers fallback: if an img2img fallback to diffusers fails and the MLX image model is restored, it stays unpriced until it is next loaded, so a chat load beside it evicts it (When they fit) or is refused (Always).
  • Decode tiling beside chat: while a priced image model is kept on Metal, its VAE decode always tiles (unless UNSLOTH_DIFFUSION_MLX_VAE_TILING forces it off), and the renderer's free-memory reading is capped by the shared pool less chat growth. This costs some decode speed, only under When they fit / Always.

Review follow-ups

  • A replacing MLX load (primary or kept slot) is credited the outgoing MLX worker's footprint and reserved growth, since every load spawns a fresh worker.
  • Raising parallel slots beside media reloads so admission prices the extra rows.
  • A priced MLX chat load evicts or refuses media with no recorded price (loaded under Off), as the unpriced chat path does.
  • The MLX image price is dropped when the engine falls back to diffusers, and a named variant (Z-Image vs Turbo) is priced against its own base.

Validation

Targeted tests, on Apple Silicon:

tests/test_gpu_arbiter.py tests/test_gpu_residency_coexistence.py
tests/test_metal_explicit_context_guard.py tests/test_multi_model_primary_fit.py
tests/test_multi_model_always.py tests/test_non_gguf_reload_settings.py

All pass. tests/test_memory_estimate.py has 16 failures, and they are identical on main.

Mutation checks: each added test was checked against seeded defects in the code it covers, and each fails when its defect is present.

Live on an M3 Max (128 GB), with Unsloth Studio running from this branch:

  • GGUF chat: Qwen3.5-0.8B-GGUF and Z-Image-Turbo Q4_0 (MLX) stayed resident together. The local chat model called generate_image and the image rendered.
  • MLX chat: mlx-community/Qwen3.5-2B-4bit and Z-Image joined in both load orders, under When they fit and under Always. The Images pill worked with the local MLX chat model.
  • Oversized load: Qwen3-4B-4bit at 16 parallel slots, about 110 GB, was refused under Always and evicted Z-Image under When they fit.

Lyxot added 2 commits October 28, 2026 14:19
… Apple Silicon

On Apple Silicon, Keep multiple models loaded (When they fit / Always) denied every image or video model beside chat, so loading one unloaded the chat model or was refused. Unified memory is now priced as one pool: free memory is the smaller of the Metal wired headroom and available RAM, the readings llama.cpp's Metal fit already uses. An MLX image load is priced from the quantization plan it will take (header sizes of the GGUF, text encoder and VAE plus decode headroom), and the diffusers streaming check is skipped on unified memory.

A GGUF chat load beside a resident image or video model nets that model out of the Metal budget and wired headroom (its weights off the working set, its unallocated generation headroom off the live readings), so llama.cpp fits its context to what is left or reports the shortfall that makes room.

An MLX chat model allocates its KV cache as it generates, which live memory does not show, so a media load beside one still unloads it (When they fit) or is refused (Always), and an unpriced non-GGUF chat load evicts first under Always too, since past the budget unified memory pages instead of failing.
…pple Silicon

An MLX chat load on Apple Silicon is now priced before launch instead of evicting resident image and video models first. The price reuses the Run Settings estimate (the /estimate-memory MLX branch, factored into _mlx_load_estimate): weights, KV cache and compute at the context the load will serve, plus the prompt-cache reserve when the load keeps history, plus one KV cache per further parallel slot. Under When they fit and Always the load joins a resident media model when that fits in unified memory; otherwise it frees media models only (never kept chat models) or is refused.

The loaded entry records what it has yet to allocate (mlx_growth) and the worker's memory footprint at load. An image or video load beside it charges that growth less what the worker has already grown by, so cache memory that live readings already show is not charged twice. A GGUF launch beside a media model nets the same growth out of its Metal budget. An MLX model with no recorded price is still treated as unpriced, as before.
@Lyxot
Lyxot requested a review from danielhanchen as a code owner October 28, 2026 06:38
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 28, 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-28T09:00:07.554975Z
We couldn’t complete this review. Comment @codex review to try again.
003ad65 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 28, 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”.

An unknown error occurred
ℹ️ 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 28, 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”.

An unknown error occurred
ℹ️ 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 added a commit to Etherll/unsloth that referenced this pull request Oct 28, 2026
danielhanchen added a commit to Etherll/unsloth that referenced this pull request Oct 28, 2026
@danielhanchen

Copy link
Copy Markdown
Member

The (Python 3.13, g-r) shard on the staging run fails on a guard this PR trips, and it reproduces locally at 73de4cbf00 (passes on main):

FAILED studio/backend/tests/test_parallel_slots_per_load.py::test_the_unsloth_load_hands_its_requested_slots_to_the_runtime
    assert "clamp_parallel_slots" not in load_impl

The new Apple Silicon block in _load_impl (routes/inference.py) does

from core.inference.llama_server_args import clamp_parallel_slots

mlx_chat_need = await asyncio.to_thread(
    _mlx_chat_need, request, config, model_identifier, clamp_parallel_slots(_n_parallel),
)

The guard keeps the load route on the one width _resolve_parallel_slots already resolved, so every consumer in the load sees the same slot count. Passing _n_parallel straight through (or clamping inside _mlx_chat_need if it needs it) should clear it.

The other failures in that shard (test_mcp_tools_loading.py, test_mcp_tools_recipe.py, test_mcp_video_queue.py) pass locally at this head, so they look like same-worker fallout rather than something to chase separately; worth re-checking after the fix.

danielhanchen added a commit that referenced this pull request Oct 28, 2026
## Summary

`(Python 3.13, a-f)` fails on main and on every PR based on it (seen on
the #15693 and #15761 staging runs) with two stale tests. Both product
changes are intentional; the tests had not caught up.

**1.
`test_account_chat_settings.py::test_list_export_and_delete_stay_in_the_account`**

```
assert {'threads': [...Guards': True} == {'threads': []}
  Left contains 1 more item: {'threadPatchGuards': True}
```

#15685 advertises the chat-title repair guards on the thread lists
(`threadPatchGuards` on the `/chat/threads` reply). This test checks
that another account's thread stays invisible, but compared the whole
reply to `{"threads": []}`. It now asserts the thread list itself is
empty, which is the privacy claim.

**2.
`test_checkpoint_compaction.py::test_the_reachability_probe_closes_the_connection_it_opens`**

```
assert _open_archive_handles() <= before + 1
E   assert 4 <= (0 + 1)
```

#15719 keeps one WAL keeper connection per `rag.db` for the life of the
process (`storage/rag_db._ensure_wal_keeper`), holding `rag.db` plus its
`-wal` and `-shm` sidecars. The first probe in a fresh process creates
it, so the test counted the keeper's descriptors as a leak. It also
failed when run alone, not only under xdist.

The test now probes once to warm the keeper up, takes its baseline after
that, and requires no growth at all over 50 probes. That is stricter
than the old `before + 1`, and it is the leak the test exists for: one
leaked probe connection per call.

## Testing

- Both tests fail on main (`75555ccb54`) and pass with this change;
`test_account_chat_settings.py` 93 passed.
- Sabotage: replacing the `conn.close()` in
`conversation_archive.reachable()` with a no-op makes the probe test
fail with `assert 23 <= 5`.
danielhanchen added a commit to Etherll/unsloth that referenced this pull request Oct 28, 2026
danielhanchen added a commit that referenced this pull request Oct 28, 2026
)

## Summary

#15763 broke `tests/python/test_windows_setup_download_progress.py` on
main (seen on the #15693 staging run; reproduces locally wherever `pwsh`
is installed):

```
test_windows_real_download_reports_progress_while_active[node|llama|whisper]
E   assert [0.3, 5.2, 10.0, 15.0, 20.0] == [5, 10, 15, 20]
```

To let the new stall window fire on a trickling connection, #15763 reads
real HTTP responses with `read1`, which returns what one receive brings.
It also moved the progress update onto every receive, so the first
percent line now appears at 0.3% and the milestones print at whatever
receive crosses them (5.2%) instead of at the whole 1 MiB reads the
installers used before. The progress text the Windows setup scripts
relay changed shape, which is what this test pins.

## Change

`prebuilt_core.copy_response_body`:

- the chunk size is back to 1 MiB;
- on the `read1` path each read asks only for the bytes up to the next 1
MiB boundary, and progress is reported when the boundary is reached, so
the updates land exactly where whole-chunk reads put them;
- the stall window is still checked after every receive, so a trickle is
still abandoned within the window;
- plain `read` bodies (file:// mirrors, test doubles) read whole chunks
and report each one, as before #15763.

## Testing

- All 23 test files that touch the installer downloaders, main vs this
branch: the only difference in failing IDs is the three
`test_windows_real_download_reports_progress_while_active` cases, which
now pass. The 21 `tests/studio/install/test_dependency_pass_skips.py`
failures and the `tests/utils/aime_eval.py` collection error are on both
sides on this host.
- New `test_progress_on_a_real_response_lands_on_whole_chunks`: a real
local server streams 4 MiB in 48 KiB writes and progress must be updated
at exactly 1, 2, 3 and 4 MiB. It runs without `pwsh`, so Linux CI covers
the shape too.
- Sabotage: reporting progress on every receive again fails the new test
and all three PowerShell cases.
- The trickle tests from #15763 still pass (the stall is detected within
the shortened window), and a real nodejs.org download verifies (55.6 MiB
in 0.27 s).
@NilayYadav NilayYadav self-assigned this Oct 28, 2026
[skip ci]
@shimmyshimmer

Copy link
Copy Markdown
Member

Review record for #15693, carried over from the mirror it was reviewed on: danielhanchen/unsloth-staging-review#584.

Findings are quoted as posted and attributed to the account that posted them. The reactions shown are the triage recorded on the mirror; none were re-applied here. Commits are named as the mirror's, with this PR's equivalent where one was found.

Round 1: reviewed mirror 2b2827f5e (no equivalent commit found on this PR)

chatgpt-codex-connector[bot] on studio/backend/routes/inference.py (on the mirror)

@@ -11829,11 +11831,22 @@ def _chat_fit_kwargs(
             int(g): int((placement.native_required_gb / len(gpus) - credit.get(int(g), 0.0)) * 1024)
             for g in gpus
         }
-    elif policy == "fit" and not (config.is_gguf and _primary_can_retry_fit.get()):
+    elif mlx_need_mib is not None:
+        kwargs["need_mib"] = {0: int(mlx_need_mib)}

P2 Badge Credit the outgoing MLX model when checking replacement fit

On Apple Silicon, reloading an MLX model with different settings while a media model is resident charges the full new model against memory that still contains the outgoing model. can_load_alongside() also subtracts the outgoing model's unallocated cache reserve, and _outgoing_chat_credit_gb() only supplies credit for native-audio loads. Consequently, under Always, even a same-repository reload with a smaller context can be refused although it would fit after the old worker is stopped. Net out the outgoing primary's allocation and growth reserve for replacements, while retaining the full charge for alongside loads.

Useful? React with 👍 / 👎.

Accepted on the mirror

Reply from danielhanchen:

Fixed in 917fa5999: a replacing MLX load is credited the outgoing worker's footprint and reserved growth (#15693).

chatgpt-codex-connector[bot] on studio/backend/routes/inference.py (on the mirror)

@@ -18861,8 +18981,23 @@ async def _guard_training(guard_placement: _LoadPlacement):
                 )
                 if post_chat_handoff_expected_free_gb is None:
                     post_chat_handoff_expected_free_gb = chat_wait_gb
+                from core.inference.llama_server_args import clamp_parallel_slots
+
+                mlx_chat_need = await asyncio.to_thread(
+                    _mlx_chat_need,
+                    request,
+                    config,
+                    model_identifier,
+                    clamp_parallel_slots(_n_parallel),

P2 Badge Recheck coexistence when increasing MLX parallel slots

When an MLX model already resides beside an image or video model, increasing only its parallel-slot count takes _load_model_impl()'s already-loaded shortcut: it calls backend.set_parallel_slots() and returns before this admission check. Neither runtime-settings predicate compares slot counts, and _reassert_chat_claim() supplies no updated memory requirement. A model admitted at one slot can therefore be expanded to many additional KV caches without freeing media or refusing under Always, exceeding the unified-memory budget this change is intended to enforce. Apply a delta-fit check before accepting an increased slot count on the shortcut as well.

Useful? React with 👍 / 👎.

Accepted on the mirror

Reply from danielhanchen:

Fixed in 917fa5999: raising parallel slots beside media skips the already-loaded shortcut so admission prices the extra rows (#15693).

Verdict

The round did not reach a clean review on the mirror before it closed.

This is the review as it stood at that commit. Anything pushed to this PR afterwards was not part of it.

@danielhanchen
danielhanchen merged commit 556b28b into unslothai:main Oct 28, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants