Skip to content

Studio: report free memory on Mac as what is actually free - #10224

Merged
oobabooga merged 9 commits into
unslothai:mainfrom
NilayYadav:fix-apple-unified-free-vram
Sep 4, 2026
Merged

oobabooga merged 9 commits into
unslothai:mainfrom
NilayYadav:fix-apple-unified-free-vram

Conversation

@NilayYadav

Copy link
Copy Markdown
Collaborator

On Apple Silicon, free GPU memory is worked out as total system memory minus what the GPU is using, so memory the rest of the machine is using does not count. On a 24 GB Mac with 10 GB in use, Settings shows 23.6 GB free on the same screen where the memory row says 11 GB is available, and the training method picker offers LoRA where only QLoRA fits.

Free is now what a new allocation can actually get, capped by the Metal working set. Tested on a Mac through the running app: free memory went from 23.64 to 10.86 GB, and models from 3 to 7 GB went from LoRA to QLoRA.

@NilayYadav
NilayYadav force-pushed the fix-apple-unified-free-vram branch from 0fc33f6 to 378b120 Compare September 2, 2026 20:13
@NilayYadav

Copy link
Copy Markdown
Collaborator Author

GitHub Actions reproduction

Reproduced on a real Apple Silicon runner (macos-15, arm64, 7.00 GB unified, Metal max_recommended_working_set_size 4.67 GB). Both branches are fresh upstream main plus a byte-identical probe (sha256 ef39c36d639a09fe…); the only difference between them is this PR.

on a 7.00 GB machine with 3.12 GB available without the PR with the PR
get_gpu_memory_info()["free_gb"] 7.00 GB 3.10 GB
vs. what the OS says is available overstated by 3.88 GB 0.00 GB
vs. the Metal working set (4.67 GB) over by 2.33 GB within
free after another process takes 1.09 GB 7.00 GB, unmoved 2.95 GB, moves with the host
3 GB model, ctx 4096 (needs 4.5 GB) offers LoRA offers QLoRA
4 GB model, ctx 4096 (needs 6.0 GB) offers LoRA offers QLoRA
Settings → Resources device row vram_free_gb: None → 7.00 GB shown 3.50 GB shown
Resources tab vs. training-method picker 7.00 GB vs 3.50 GB 3.50 GB vs 3.50 GB, agreed

The last two rows are a second defect found while reviewing this PR and fixed in 0eeb685. get_visible_gpu_utilization() published no vram_free_gb for Apple, so /api/system fell back to total - used — the exact arithmetic this PR removes — and that is the number the Resources tab renders. Measured on a 24 GB M5 Pro through main._get_cached_system_gpu_info with 11.62 GB available:

before:  /api/system/hardware  gpu.vram_free_gb = 11.43
         /api/system  devices[0].vram_free_gb   = 23.62
after:   /api/system/hardware  gpu.vram_free_gb = 11.41
         /api/system  devices[0].vram_free_gb   = 11.41

So Settings showed 23.62 GB free on the same screen whose picker had already downgraded to QLoRA on 11.43 GB. Both endpoints now serve the same number.

One limit worth stating: min(psutil available, working set) is a floor, not a capacity. macOS reclaims compressed and file-backed pages, so MLX can allocate past it — measured on the 24 GB M5 Pro, MLX held 18 GB with psutil reporting 11.56 GB available. The error is now conservative (a QLoRA suggestion where LoRA would have fit) instead of an OOM partway through a run, and it matches what LlamaCppBackend._apple_unified_budget_bytes already does. This is noted in the helper's docstring.

@NilayYadav

Copy link
Copy Markdown
Collaborator Author

@codex review

Two things changed since you last saw this branch, so please review the whole diff rather than just the newest commit:

  1. 0eeb685 fixes a second defect found in review: get_visible_gpu_utilization() published no vram_free_gb for Apple, so /api/system fell back to total - used and the Settings → Resources tab kept showing the overstated figure while the training-method picker used the corrected one.
  2. main.py now prefers a producer-reported vram_free_gb over recomputing total - used. Please check that against fix(studio): report Vulkan GPUs in system UI #7476, which added reported_free_vram as the fallback — I believe the Vulkan paths are numerically unchanged because used = total - free there, and test_system_gpu_info_still_derives_free_when_the_probe_reports_none pins the subtraction for producers that report no free, but that precedence flip is the riskiest part of the change.

Please keep reviewing until you converge — if a round finds nothing blocking, say so explicitly.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. What shall we delve into next?

Reviewed commit: 2c26ac9537

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

@NilayYadav

Copy link
Copy Markdown
Collaborator Author

Settings → System, before and after

Two isolated installs on this Mac (M5 Pro, 24 GB unified, Metal working set 17.76 GB): merge base c9f98dbd5 against head 2c26ac953. Same machine, same scene, nothing mocked.

PR 10224 Settings before/after

The two sides are comparable — the RAM tile reads 6.39 GiB free on the left and 6.34 GiB free on the right — so the VRAM figure is the only thing that moved:

Settings → System before after
RAM tile 6.39 GiB free 6.34 GiB free
VRAM tile 23.1 GiB free 6.67 GiB free
GPU devices row 0.88 GiB used · 23.1 GiB free · 24 GiB total 0.34 GiB used · 6.67 GiB free · 24 GiB total
/api/system devices[0].vram_free_gb 23.12 6.67
/api/system/hardware gpu.vram_free_gb 23.12 6.67

Before, the panel claims 23.1 GiB of VRAM is free three inches under its own RAM tile saying 6.39 GiB is free. After, the VRAM tile and the GPU row agree with the RAM tile.

Training method the picker offers (ctx 4096, estimate = size × 1.5), from the same two servers:

model before after
3 GB, 4 GB LoRA LoRA
5, 6, 7, 8, 10, 13 GB LoRA QLoRA

Both endpoints agree with each other on both sides, which is the point: on the merge base they were wrong together, and now they are right together. They disagreed only at this PR's first commit, which corrected the picker's endpoint but not the tab's — closed by 0eeb685.

@danielhanchen

Copy link
Copy Markdown
Member

Confirmed this hits hardware.py where Apple free memory is still total minus allocated, and main.py where that subtraction is preferred over a reported free, so the Resources tab and the training method picker disagree. Will get this reviewed.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 3, 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-09-03T21:48:56.615166Z f3fd8f5 New commits
ℹ️ 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.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: c94f5d08cd

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

recommended = int(device_info.get("max_recommended_working_set_size") or 0)
except Exception:
recommended = 0
return min(free, recommended) if recommended > 0 else free

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Subtract the existing MLX working set from the cap

When MLX already holds memory and host-available RAM exceeds the remaining Metal headroom, this treats the entire max_recommended_working_set_size as additional free memory even though it caps the total GPU working set. For example, an 11 GB cap with 8 GB already allocated and 10 GB host-available reports 10 GB free rather than at most 3 GB; /api/system/hardware then feeds that overstatement into training-method selection and can still choose LoRA that exceeds the Metal limit. Pass the current allocation into this calculation and bound free by max(0, recommended - allocated).

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Correct, and fixed in e74ef62. The Metal header documents recommendedMaxWorkingSetSize as a threshold on "the total size of all resources (texture and buffers) and heaps", so it bounds what the GPU already holds as well as the next allocation. _apple_unified_free_bytes now takes the AGX in-use bytes and returns min(host available, max(0, recommended - allocated)); the two bounds stay independent because psutil available on macOS is free + inactive pages, which already excludes the resident GPU pages. On a 24 GB Mac with a 17.76 GB working set, 8 GB resident and 14 GB host available, free goes from 14 GB to 9.76 GB. test_mlx_free_is_the_working_set_headroom_not_the_whole_cap covers that case and test_mlx_free_is_zero_once_the_working_set_is_spent covers an overcommitted working set.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Reversing my earlier agreement here. I implemented this in e74ef62 and have reverted it in 6fbeeac.

Two things make the subtraction wrong. max_recommended_working_set_size is a per-process budget, not a device-wide one: that is how torch.mps.set_per_process_memory_fraction applies it, and Metal's companion currentAllocatedSize is documented as this process's resources. A fresh MLX training worker therefore starts with an empty working set, so its ceiling is the whole value.

And the counter I was subtracting is the wrong quantity anyway. AGX PerformanceStatistics carries both "Alloc system memory" and "In use system memory", and they are far apart: a captured M4 Pro sample reads 5043453952 allocated against 650788864 in use. nvtop deliberately reads "Alloc system memory" for device-wide allocation and notes that currentAllocatedSize is process-local. "In use system memory" is a whole-device active subset, so charging it against a per-process budget let another application's GPU work decide this process's training method, while a model whose weights were allocated but idle would not be charged at all.

Concretely, on the 24 GB machine in this PR with a 17.76 GB working set, 14 GB host available and 8 GB device-wide in use, the subtraction reported 9.76 GB and picked QLoRA for an 8 GB model at 4096 context, where 14 GB and LoRA were correct.

Head is back to min(host available, max_recommended_working_set_size), which is what this PR proposed. test_mlx_free_is_not_reduced_by_whole_device_gpu_use pins it: free must not move when device-wide GPU use does. It fails against e74ef62.

@Imagineer99 Imagineer99 self-assigned this Sep 3, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: e74ef625a0

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

recommended = 0
if recommended <= 0:
return free
return min(free, max(0, recommended - max(0, int(allocated_bytes or 0))))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Bound free memory by the MLX allocator limit

On Apple hosts where the other two bounds exceed 85% of the recommended working set, this reports memory that the training process cannot allocate: core/training/worker.py sets mx.set_memory_limit(int(rec_bytes * 0.85)), while the training-method policy compares its estimate directly with this value. A model whose estimated usage falls between that allocator limit and the reported value can therefore be assigned LoRA and then fail during loading or training; include the configured 85% allocator ceiling as an additional bound.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Not taking this one. Three reasons.

mx.set_memory_limit is documented as "a guideline for the maximum memory usage during graph evaluation", and allocations raise only "if the memory limit is exceeded and there is no more RAM (including swap when available)" (https://ml-explore.github.io/mlx/build/html/python/_autosummary/mlx.core.set_memory_limit.html). MLX's own default is 1.5x the recommended working set, so the worker's 0.85x is a tuning choice, not a ceiling an allocation bounces off.

The window you describe predates this PR and this PR narrows it. On main, Apple free_gb is total - allocated, so a 24 GB Mac with 17.76 GB recommended reports about 23.6 GB free against the worker's 15.1 GB limit. After this PR and e74ef62 it reports min(host available, 17.76 - allocated), about 16 GB on the same idle machine. The gap goes from roughly 8.5 GB to under 1 GB.

The 0.85 factor belongs where it is set, not in the shared probe. get_gpu_summary().vram_free_gb also feeds the Resources tab and GGUF inference fit, and llama.cpp Metal never calls set_memory_limit, so folding a training-only factor in would understate free for every other consumer. The policy that would need it already multiplies model size by 1.5 and again by a context scale before comparing, so the training path is not reading free unpadded.

@oobabooga

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Breezy!

Reviewed commit: e74ef625a0

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

@oobabooga

Copy link
Copy Markdown
Member

macOS runner probe of the free-memory path

e74ef625a bounds the Apple figure by the working set headroom instead of the whole cap. recommendedMaxWorkingSetSize is a threshold on the total size of every resident Metal resource, not headroom for one more allocation (MTLDevice.h: "Performance may be improved by keeping the total size of all resources (texture and buffers) and heaps less than this threshold"), so capping at the whole value reports memory the GPU has already spent. On a 24 GB Mac with a 17.76 GB working set, 8 GB resident and 14 GB host available, that reported 14 GB free where 9.76 GB fits, and the training method picker reads that number.

Ran the real path unmocked on a macos-15 runner (run), at PR head e74ef625a:

device_info keys: ['architecture', 'device_name', 'max_buffer_length',
                   'max_recommended_working_set_size', 'memory_size', 'resource_limit']
recommended working set  = 4.667 GB
agx stats                = {}
psutil total             = 7.000 GB
psutil available         = 3.064 GB
free_gb                  = 3.064
vram_free_gb (device 0)  = 3.07
main (total - allocated) = 7.000 GB

max_recommended_working_set_size is present and positive, the summary and the per-device figure agree, free stays inside both bounds, and main would have called the whole machine free.

One gap that runner cannot close: it is a paravirtualized GPU (Apple Paravirtual device) with no AGXAccelerator ioreg node, so _read_apple_gpu_stats() returns {} and the subtraction runs with allocated = 0. The allocated > 0 branch is covered by unit tests only. @NilayYadav if you can re-run your before/after on the M5 Pro with a model loaded, that exercises it. Your posted numbers imply AGX in-use was about 0.36 GB on an idle machine and that available was the binding bound at 10.86 GB, so with nothing loaded the head should still read 10.86 GB.

I also declined the follow-up review comment asking for a further 0.85 * max_recommended_working_set_size bound. mx.set_memory_limit is documented as a guideline that raises only once RAM and swap are both gone, and MLX's own default is 1.5x the recommended working set, so the worker's 0.85 is a tuning choice rather than a ceiling. The same free figure also feeds the Resources tab and aggregateUsableFreeVramGb, which applies its own reserve, so a training-only factor does not belong in the shared probe.

@oobabooga

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@oobabooga

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Swish!

Reviewed commit: 6fbeeacd0c

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

@oobabooga

oobabooga commented Sep 3, 2026 •

Copy link
Copy Markdown
Member

Thanks @NilayYadav. I checked this on an M1 Mac mini and the overstatement is real. On that machine main reports 7.99 GB free, while actually allocating drove host-available down to 0.76 GB. The figure this PR computes was achievable with a small margin.

I pushed f3fd8f5 on top. The stack gate accepts mlx >= 0.22.0, and mlx below 0.30 only has mx.metal.device_info(). The working set cap was therefore silently never applied on that M1 until the helper tried both names.

Two things worth recording. torch.mps.recommended_max_memory() returns the identical value on every machine I tested, so reading it through MLX is a convenience rather than a requirement. GitHub's macOS runners cannot settle any of this: their paravirtual GPU let me allocate 8 GB on a 7 GB machine without host-available moving, which scores main's formula as fine. I did not exercise the full training flow on a real Mac with a model already loaded.

@oobabooga
oobabooga merged commit e46b723 into unslothai:main Sep 4, 2026
49 of 50 checks passed
@Imagineer99

Copy link
Copy Markdown
Member

Before merge, I ran a pinned macOS A/B using the same probe. The base run reproduced the incorrect free-memory reporting, while the PR run at e74ef625 passed all cases, including API propagation and the unchanged CPU fallback. Later commits added broader M1/older-MLX handling, but this confirms the core fix was working before merge.

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.

4 participants