Skip to content

feat(core): add macOS memory guardrails for large resident models - #2909

Merged
inureyes merged 5 commits into
mainfrom
feature/issue-2883-macos-memory-guardrails
Nov 9, 2026
Merged

inureyes merged 5 commits into
mainfrom
feature/issue-2883-macos-memory-guardrails

Conversation

@inureyes

@inureyes inureyes commented Nov 9, 2026 •

Copy link
Copy Markdown
Member

The fit check compared a load against total RAM and Metal's working set, neither of which says what macOS can give now without compressing or swapping. This adds the "available now" figure and the guardrails built on it.

Behavior

  • mlxcel inspect and --estimate-memory print, on macOS, total RAM, Metal working set, available now and the reserve of max(7 GiB, 15% of RAM), and warn with numbers when weights + KV + activations exceed available-now minus the reserve. The FITS verdict is unchanged and nothing is refused. Strict mode was left out.
  • The server logs phys_footprint and compressed bytes after load, and /metrics exports them with MLX active/cache and wired-weight gauges. Off macOS these families are absent.
  • MLXCEL_WIRE_WEIGHTS=1 mlocks evaluated weights in 1 GiB chunks, re-reading the system wired total after each chunk and unwiring the one that crosses RAM minus the reserve. It needs a small new bridge call returning an array's host address, used only for mlock and zero unless the array is row or column contiguous. Multimodal towers and repacks made at the first token are not wired.
  • The qwen4_exp PLE row cache stops growing before crossing the reserve, charging each step with its bookkeeping and reusing one query for 250 ms. The prompt-cache stores are not gated: entries exist before insert and a byte budget bounds them, so there is no step to refuse.
  • mlxcel_core::host_memory holds the reusable figure and AvailabilityGate for feat(moe): SSD expert streaming arena for MoE checkpoints larger than unified memory #2882 and feat(models): prompt-cache snapshots for qwen4_exp, then mid-prompt checkpoints for model-owned recurrent families #2885.

Measure-then-keep

Timed runs and the soak are deferred to a quiet machine, so MLXCEL_WIRE_WEIGHTS stays off, MLXCEL_WIRED_LIMIT keeps its default, and no load is refused. docs/macos-memory.md says nothing has been measured.

Verification

  • Unit tests for the arithmetic, gate, wiring policy, report text and metrics; a real mlock of an evaluated MLX buffer.
  • mlxcel inspect of the OptiQ checkpoint printed the new section (no warning on this 512 GB host, so the warning path is unit-tested only). That run predates the review fix for double-counted speculative pages, which is covered by a fixed-input test and was confirmed against vm_stat.
  • Short server run of qwen3.5-4b-4bit with wiring on: 2.20 GiB wired, footprint in the log and /metrics.
  • Clippy on both library crates, cargo check --bin mlxcel --no-default-features --features metal,accelerate, fmt, make verify-env-var-docs, bash -n and --dry-run of the script. Shellcheck is not installed. Linux was not compiled here.

Unverified acceptance criteria

  • Soak results on 128 GB and 64 GB machines: the script is committed but not run (deferred, hardware absent on this host).
  • MLXCEL_WIRE_WEIGHTS soak criterion: deferred, not adopted as a default.
  • Docs criterion: reserve and switches are documented, "what was measured" is pending.

Closes #2883

The fit check compared against total RAM and Metal's working set, neither of which says what macOS can give now without compressing or swapping.

Add mlxcel_core::host_memory: the available-now figure (free + purgeable + min(inactive + speculative, file-backed)), the reserve of max(7 GiB, 15% of RAM), the process footprint, and AvailabilityGate for stores that grow in steps. inspect and --estimate-memory print these on macOS and warn with numbers, never refusing. The server logs the footprint after load and exports it on /metrics. MLXCEL_WIRE_WEIGHTS=1 optionally mlocks the evaluated weights, default off. The qwen4_exp PLE row cache now stops growing before crossing the reserve.

scripts/macos_memory_soak.sh is committed but not run, so the soak numbers are pending and all defaults are unchanged. Validated with unit tests, a real inspect of the OptiQ checkpoint, and a short server run with wiring on.

Refs #2883
@inureyes inureyes added status:review Under review type:enhancement New features, capabilities, or significant additions priority:medium Medium priority area:core mlxcel-core: MLX FFI, primitives, KV cache, layers platform:macos macOS (Apple Silicon) specific labels Nov 9, 2026
The kernel's vm_statistics64 free_count already includes speculative pages, as vm_stat's own subtraction shows, so the available-now figure counted them twice. On this host that overstated it by 25 GiB, which could suppress the load warning and let the row cache grow past the reserve. Subtract them when mapping the kernel counters.

The soak script now cleans up on normal exit and SIGHUP, runs dd in the background so a signal stops a write at once, removes the write file before waiting on the server, and bounds that wait. It refuses a port that already answers, clears inherited wiring variables for baseline runs, skips the write when no first token arrived, and treats reasoning deltas as the first token.

Validated with host_memory unit tests, clippy on mlxcel-core, bash -n, --dry-run, and a cleanup trap exercise on sleep children. The soak was not run.

Refs #2883
@inureyes

inureyes commented Nov 9, 2026

Copy link
Copy Markdown
Member Author

Implementation Review Summary

Intent

macOS "available now" figure, reserve, footprint reporting, optional weight wiring and gated row cache growth, with defaults unchanged.

Findings Addressed

  • free_count already includes speculative pages, so available-now counted them twice (25 GiB on the review host; raw counters compared with vm_stat) (HIGH)
  • Soak script left the write file, server and sampler behind on SIGHUP or an untrapped exit; a signal during dd waited for the write; a slow server delayed file removal (HIGH)
  • Soak measured whatever already answered on its port, inherited MLXCEL_WIRED_LIMIT and MLXCEL_WIRE_WEIGHTS in baseline runs, and wrote the file with no first token; a reasoning-only stream gave no TTFT (HIGH)

Remaining Items

  • array_data_address plus nbytes is only exact for row or column contiguous arrays. Registered checkpoint tensors are, so this is not reachable today (MEDIUM)
  • mlxcel_weights_wired_bytes reports the last load only and stays set after the model drops; wired pages are released when MLX frees the buffer, not when the array drops (MEDIUM)

Verification

  • All stated requirements implemented (soak results deferred)
  • No placeholder/mock code remaining
  • Integrated into project code flow
  • Project conventions followed
  • Existing modules reused where applicable
  • No unintended structural changes
  • Tests pass (host_memory unit tests and mlxcel-core clippy after the fixes; non-macOS gates inspected, not compiled)

`array_data_address` plus `array_nbytes` describes an array's bytes only when the array is contiguous. A strided view spans more memory than its element count, and with a negative stride its address is not the start of the range, so `MLXCEL_WIRE_WEIGHTS` could wire the wrong pages.

The bridge now returns 0 unless the array is row or column contiguous, and the existing zero-address filter drops those arrays from the wiring pass.

Validated with the `weight_wiring` tests, including a new check on a column slice and a row slice, plus lib and test clippy with metal and accelerate.

Refs #2883
@inureyes

inureyes commented Nov 9, 2026

Copy link
Copy Markdown
Member Author

Security and performance review of the memory guardrails: no CRITICAL or HIGH findings.

Fixed: array_data_address now returns 0 for arrays that are neither row nor column contiguous, so a strided view is skipped instead of wiring a wrong range. Covered by a new test in weight_wiring_tests.rs.

Checked with no change needed:

  • mlock: the system wired total is re-read after each 1 GiB chunk and a chunk that crosses RAM minus the reserve is unwired. A failed mlock, including one from RLIMIT_MEMLOCK, is counted and logged with its errno; earlier chunks stay wired and are reported.
  • /metrics: no new endpoint. The new gauges are per-process only (no host figures) and sit behind the existing API key check.
  • Cost: process_footprint runs once per scrape and once after load. host_statistics64 is limited to one query per 250 ms in AvailabilityGate, and only at row-cache slab boundaries. Neither runs per token.

Open, LOW or MEDIUM, not fixed here:

  • MEDIUM: wired source buffers replaced by a first-token repack, or released on unload, can stay wired in the MLX buffer cache until it is cleared. Bounded by the ceiling and only with MLXCEL_WIRE_WEIGHTS=1.
  • LOW: mlxcel_weights_wired_bytes reflects the last load only and is not cleared on unload.
  • LOW: when the page size or the first host query fails, wiring returns without a log line.
  • LOW: permuted contiguous arrays and strided views are left unwired and are not counted in requested_bytes.

The PR added documentation pages and environment variable rows but no CHANGELOG entry. The Unreleased Added section now describes the available-now figure and reserve, the footprint metrics, the optional weight wiring, the row cache growth gate and the unrun soak script, and states that nothing was measured and no default changed.

Validation: cargo fmt --check, make verify-env-var-docs, host_memory, weight_wiring, execution::memory_availability and ple_cache test selectors, clippy --lib --tests, and cargo check --bin mlxcel --no-default-features all pass.

Refs #2883
@inureyes inureyes added status:done Completed and removed status:review Under review labels Nov 9, 2026
@inureyes
inureyes marked this pull request as ready for review November 9, 2026 16:33
@inureyes
inureyes merged commit 2153227 into main Nov 9, 2026
13 checks passed
@inureyes
inureyes deleted the feature/issue-2883-macos-memory-guardrails branch November 9, 2026 16:33
inureyes added a commit that referenced this pull request Nov 10, 2026
## Summary

Records the timing and memory measurements that #2908, #2906, #2912, #2909, #2911 and #2918 deferred to a quiet host, in `docs/benchmark_results/qwen4-exp-deferred-measurements-m3ultra-2026-11-10.md` (Mac Studio M3 Ultra, 512 GB, `main` @ `60a3270c`).

- Native MTP (#2880, #2917): 1.30x / 1.10x / 1.76x (code / prose / enumeration) for the OptiQ 2-bit target with the bf16 split head, 1.38x / 1.00x / 1.74x for the 4-bit target with its embedded head.
- SSD expert streaming (#2882): decode 42.8 tok/s resident, 23.0 at a 24 GB arena (89.8% hit), 18.3 at 8 GB (74.9% hit). Router sync costs 8.0 s per run at both sizes, more than the I/O wait. Output identical across arms.
- External PLE (#2881): 31 GB less resident (78.5 to 47.3 GB), same TTFT at 4K and 32K, identical output in every mode.
- Prompt-cache second turn (#2885): 0.51 to 0.60 s cached vs 15.1 s (16K) and 28.6 to 28.9 s (32K) after a reset, byte-identical in 10/10 repetitions.
- macOS memory soak (#2883): 0 compressions and 0 swap-outs in every setting. A 512 GB host cannot show the eviction the issue targets.

## Script changes

- `scripts/bench_speculative.sh`: new `flashnext` and `flashnext4` pairings.
- `scripts/macos_memory_soak.sh`: send the `model` field (every request got HTTP 400 without it), and default `--out` gets a `-wire-weights` suffix under `--wire-weights` so it no longer overwrites the plain run.

## Not covered

A Mac with less memory than the checkpoint, the `prepare-expert-stream` contiguous file, and streaming combined with the external PLE table.

Refs #2880, #2881, #2882, #2883, #2885, #2917
@inureyes inureyes added this to the 0.9 milestone Nov 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:core mlxcel-core: MLX FFI, primitives, KV cache, layers platform:macos macOS (Apple Silicon) specific priority:medium Medium priority status:done Completed type:enhancement New features, capabilities, or significant additions

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(core): macOS memory guardrails for large resident models (available-memory preflight, idle compression, optional wiring)

1 participant