Skip to content

Studio: cap GGUF context to unified memory on Apple Silicon - #6622

Merged
danielhanchen merged 6 commits into
unslothai:mainfrom
oobabooga:studio-apple-silicon-ctx-cap
Jun 24, 2026
Merged

danielhanchen merged 6 commits into
unslothai:mainfrom
oobabooga:studio-apple-silicon-ctx-cap

Conversation

@oobabooga

Copy link
Copy Markdown
Member

Closes #5118
Closes #6529

Problem

On Apple Silicon, Studio does no context-length capping. It always launches with the model's full native context (e.g. -c 262144), regardless of available memory. On CUDA/ROCm it shrinks the context to fit VRAM; on Metal it skips that, because _get_gpu_memory() returns [] (it only knows nvidia-smi / torch.cuda).

So a GGUF load over-commits unified memory and dies on the first decode with Error: Compute error. (llama-server failing to build the Metal compute graph), even though the same model runs fine in a standalone llama.cpp Mac app. Reported on an M3 Pro / 36 GB: ~15.7 GB weights + ~16 GB KV at full context. --fit on doesn't save it (llama.cpp only shrinks context at -c 0, and layer offload can't free unified RAM).

Fix

Give the fit path a memory budget on Apple Silicon: Metal's recommended working-set (via mlx, falling back to total RAM) at 0.85, run through the same _fit_context_to_vram that CUDA and ROCm already use.

gpu_indices=None / use_fit=True stay untouched (nothing to pin on Metal), so it just ships a reduced -c with --fit on as a backstop. Explicit user contexts are honored verbatim; only the auto context is shrunk. Off Apple Silicon the budget is 0 and behavior is unchanged.

Verification

Tests in test_llama_cpp_context_fit.py cover the budget helper and the cap/floor/explicit paths; full file and the broad VRAM-fit suites pass.

Also run on real Mac runners (CI): on macos-26-arm64 the helper reads a 5.01 GB Metal working-set, budgets 4.26 GB, and caps 262144 to 39680; on macos-15-intel it returns 0 (no-op). A full model decode wasn't exercised (runner RAM too small).

@oobabooga
oobabooga requested a review from danielhanchen as a code owner June 23, 2026 22:36
@gemini-code-assist

Copy link
Copy Markdown
Contributor

Warning

You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again!

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.

pre-commit-ci Bot and others added 3 commits June 23, 2026 22:37
…e unified-memory cap

The Apple Silicon GGUF context cap mirrored the discrete-GPU auto-fit branch but
missed two protections the discrete path already applies:

- It passed the full unified-memory budget with budget_frac=1.0 without first
  reserving the flat MTP fraction the discrete path takes off via _pin_fraction.
  With an MTP draft whose KV cannot be byte-sized (e.g. Qwen3.6-MTP, unslothai#6529), the
  cap filled the whole budget and left nothing for the draft, so unified memory
  could still over-commit. Reserve _flat_mtp_reserve up front; this is a no-op
  when MTP is not engaged.

- It required _can_estimate_kv(), so a GGUF with sparse KV metadata skipped the
  cap entirely and launched at full native context. Mirror the discrete
  file-size-only fallback and floor the auto context to 4096 when the cache
  cannot be sized.

Adds regression tests for both paths.
@danielhanchen

Copy link
Copy Markdown
Member

Thanks for this, it is fixing a real issue. I confirmed the mechanism: with no discrete GPU enumerated on Apple Silicon, _get_gpu_memory() returns [], the VRAM-fit branches are skipped, and the auto context stays at the model's full native length, so the KV cache over-commits unified memory and llama-server fails at decode. The budget path addresses that.

I pushed two small follow-up commits on top of your branch to cover a couple of edge cases where the Apple branch diverged from the discrete-GPU path:

  1. Reserve the flat MTP fraction up front. The discrete path takes _flat_mtp_reserve off the budget via _pin_fraction before fitting, but the Apple branch passed the full budget with budget_frac=1.0. With an MTP draft whose KV cannot be byte-sized (for example the Qwen3.6-35B-A3B-MTP-GGUF from [Bug] No model works #6529), the cap filled the whole budget and left nothing for the draft, so unified memory could still over-commit. The Apple budget is now scaled by (1 - _flat_mtp_reserve), mirroring _pin_fraction. This is a no-op when MTP is not engaged.

  2. Floor sparse-KV-metadata loads. The branch required _can_estimate_kv(), so a GGUF whose metadata is too sparse to size the KV cache skipped the cap entirely and launched at full native context. The discrete path has a file-size-only fallback that floors to 4096 in that case, and the Apple branch now does the same.

Both come with regression tests.

I also ran a cross-OS pass to check backward compatibility and the real Metal path:

OS / arch is_apple_silicon budget result
macOS 14 + 15, Apple Silicon True working_set * 0.85 cap engages, suite green
macOS Intel False 0 no-op, suite green
Linux x64 False 0 no-op, suite green

On real Apple Silicon the helper reads max_recommended_working_set_size from MLX and returns exactly working_set * 0.85 (on the small CI runner, 4.67 GiB budgets to 3.97 GiB, matching the numbers you saw). mx.metal.is_available() and mx.device_info() are clean on mlx 0.31.2 with no deprecation warning, and the helper degrades gracefully to the psutil fallback if MLX is missing or the mx.metal namespace is removed in a future release. Off Apple Silicon the budget is 0, so the new branch is a no-op and the discrete and CPU paths are byte-for-byte unchanged.

As with your earlier run, a full model decode was not exercised on the runners (limited RAM), so this covers the budget computation, the context-fit math, and the full test suite on real hardware rather than an end-to-end Metal decode.

Condense the verbose comment blocks in the Apple budget helper, the no-GPU
Metal branch, and the context-fit tests. Comments only, no code change
(verified with ast-based comment_tools check); suite still green.
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@danielhanchen

Copy link
Copy Markdown
Member

/gemini review

@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request introduces unified-memory budget estimation and context capping for Apple Silicon (Metal) in the Llama.cpp backend. This prevents over-committing unified memory when no discrete GPU is present by capping the auto-context length based on the MLX working set size or total system RAM. Extensive unit tests have been added to verify this new behavior. There are no review comments, so I have no feedback to provide.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. More of your lovely PRs please.

Reviewed commit: 2f0bcbe3dc

ℹ️ 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 346d96d into unslothai:main Jun 24, 2026
42 of 43 checks passed
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.

[Bug] No model works [Bug] RuntimeError: llama-server returned 500 Compute Error during GGUF tool streaming on macOS aarch64

2 participants