Skip to content

Metal buffer COUNT ratchets in size-churning servers: free()-to-cache never decrements num_resources_ #4889

Open

Description

@nunez

Summary

MetalAllocator::free() decrements num_resources_ only when it releases a buffer
(get_cache_memory() >= max_pool_size_, allocator.cpp free path); every buffer that goes
into the cache keeps its count. A cache hit (reuse_from_cache) neither increments nor
decrements, so with stable sizes the count is flat. But when a workload churns distinct
allocation sizes
, every freed buffer parks in the cache (count stays live) and every new
miss allocates a fresh buffer and num_resources_++. The count therefore ratchets upward
even though byte memory is flat, until the next new allocation throws
[metal::malloc] Resource limit (499000) exceeded — a fatal, unrecoverable state for a
long-running server.

Critically, the allocator's own reclaim safety valve (mem_required >= gc_limit_,
allocator.cpp:135) never fires on machines where the working set is far below
recommendedMaxWorkingSetSize()
— precisely the big-RAM Macs (64–512 GB) that run
always-on inference servers. On those machines the only path that ever decrements the count
is an explicit clear_cache() — which MLX itself only runs at interpreter exit. Long-running
hosts that never call mx.metal.clear_cache() between jobs have no escape.

The #3849 discussion (mx.compile variant retention) and mlx-lm #1641/#1185/#1845 (per-token
array leaks) are different leak sites. This is a different mechanism: no leak at all —
every array is freed and evaluated — the count itself never comes back down.

Environment

  • MLX 0.32.x (observed at lib/mlx-src 0.32.5 pre-release 64ea011c), mlx-c 56b2d39
  • M3 Ultra, 512 GB, macOS 26.x — sysctl iogpu.rsrc_limit: unknown oid → 499000 fallback
  • Host: Zig/OpenAI-compatible inference server (mlx-serve) + a BEAM NIF embedding the engine,
    serving TTS + streaming ASR + decision calls 24/7

Evidence from a live 24/7 server (not a leak)

  • Crash signature after hours of traffic: [metal::malloc] Resource limit (499000) exceeded;
    byte memory at ~74 GB active against a ~440 GB gc_limit_ — the pressure-reclaim arm is
    literally unreachable on this box.
  • Traffic profile: TTS (~400–800 distinct activation sizes per voice/length) and ASR (size
    depends on audio length) — cache hits are rare, so nearly every free is a new cache entry
    and nearly every allocation is a new buffer.
  • ASR on-demand load/unload cycled ~1,300×/day (weights = hundreds of distinct-size buffers
    per load).
  • A mx.metal.clear_cache() after every job stops the growth and the crashes (the server's
    media runner already cleared per job; the NIF lane that didn't was the one that latched).
  • The failure is count-based, not byte-based: mlx_get_active_memory/get_cache_memory are
    modest; raising max_pool_size_ (via set_cache_limit) does not help and worsens it
    (buffers stay cached longer → more ratchet).

Why the design makes it invisible-but-fatal

num_resources_ has no public accessor, so hosts can only see the ceiling via the throw. The
free()/recycle_to_cache asymmetry means the counter tracks "buffers ever allocated into
the cache without a pressure-evict"
— on big-RAM servers, everything.

Proposed fix (any of)

  1. On a cache hit, decrement num_resources_ — a reused buffer replaces a fresh
    allocation one-for-one, so the count could track live + most-recently-reusable buffers
    rather than every size ever seen (symmetric with the miss path's ++).
  2. Or evict LRU cache entries when num_resources_ approaches the limit even with no byte
    pressure — today the count only drops via the throw-path reclaim or full clear_cache().
  3. And/or expose the live count (mx.metal.active_resource_count() — also wanted in How can the Metal resource limit be queried or configured on macOS? #3849)
    so hosts can schedule clears before the cliff instead of after a fatal throw.

Workaround (deployed)

Per-job mx.metal.clear_cache() (the documented server-side pattern), plus one retry-after-
clear on the resource-limit message for hosts that can't clear between every job. Happy to
turn the workload into a small standalone repro (alternating-size alloc/free loop under a low
set_cache_limit with clear_cache disabled) if useful.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions