Skip to content

Kernel panic (IOGPUMemory.cpp:550) on M4 Max with large context prefill (~173K tokens) #3186

Open

Description

@kotono-amaha

Apple Feedback ID: FB22091885

This issue has been filed with Apple and is cross-referenced here for the MLX community. A fix may come from either side.

Kernel panic in IOGPUMemory.cpp:550 triggered by large Metal GPU memory allocation during MLX inference on M4 Max.

PANIC STRING:
"completeMemory() prepare count underflow" @IOGPUMemory.cpp:550

SYSTEM:

  • Hardware: Apple M4 Max (36GB unified memory)
  • macOS: 26.3 (25D125)
  • Kernel: Darwin 25.3.0 xnu-12377.81.4~5/RELEASE_ARM64_T6041

REPRODUCIBLE: Yes — confirmed twice with identical call stacks.

REPRODUCTION STEPS:

  1. Install MLX and mlx-lm via pip on Python 3.14 ARM64
  2. Load a large quantized LLM (Qwen3.5-27B Q5_K_M) via mlx_vlm.load()
  3. Construct a prompt consisting of 147 concatenated model outputs totalling approximately 173,000 tokens
  4. Call mlx_vlm.generate() with this prompt — prefill phase begins processing the full context
  5. Kernel panics during prefill, consistently at IOGPUMemory.cpp:550

ROOT COMPONENT:
com.apple.iokit.IOGPUFamily (129.3.2)

NOTES:

  • Panic does not occur with smaller prompts (under ~10,000 tokens)
  • Memory capacity is not the issue — system has 36GB and model occupies ~26GB, leaving sufficient headroom
  • Issue appears to be a GPU memory accounting state corruption triggered
    by a single contiguous Metal allocation for a very large attention computation, not an out-of-memory condition
  • Two panic logs attached with identical backtraces confirming deterministic reproducibility

Suggested mitigation for MLX:
Add a prefill token count guard in mlx_lm before the Metal allocator is called. If the prompt exceeds a safe threshold (empirically somewhere
below 173K tokens on M4 Max with 36GB), either raise a clear exception with guidance to chunk the prompt, or automatically split the prefill
into safe-sized segments. This would prevent the IOGPUFamily kernel panic without requiring a macOS fix.

Activity

  1. AlchemyHAN commented on Mar 12, 2026

    @AlchemyHAN

    I’ve run into the same issue on a MacBook M5 with 32GB RAM using the 5-bit MLX version of Qwen 3 Coder. Once the token count gets large enough, it consistently kernel panics and the system reboots to a black screen. It doesn’t look like this is limited to the M4 Max.

  2. Harperbot commented on Apr 12, 2026

    @Harperbot

    Adding a production data point. We saw 9 kernel panics in 6 days on M1 Ultra (64GB) with the completeMemory() prepare count underflow signature, which is closely related to this fPendingMemorySet race.

    Through crash forensics (breadcrumb logs written with fsync before each Metal operation), we identified two trigger paths:

    1. Daemon thread race — mlx_lm.generate() in a thread holding GPU buffers + mx.clear_cache() on main thread before thread finishes
    2. Cross-process Metal contention — two Python processes both calling MLX generate simultaneously

    We built MetalGuard (v0.4.0) as an application-level safety layer. It doesn't fix the driver bug, but it eliminates the trigger paths:

    • Thread registry + wait_for_threads() — blocks cleanup until GPU threads finish
    • Cross-process lock — prevents concurrent MLX workloads across processes
    • Breadcrumb forensics — metal_guard.breadcrumb("LOAD: model-x START") writes fsync'd lines so after a panic you can see exactly which operation triggered it
    • is_metal_oom() now detects the fPendingMemorySet signature specifically

    @yoyaku155 — if you're still seeing this on M3 Ultra, MetalGuard may help. After deploying it on our M1 Ultra pipeline (90+ model load/unload cycles per batch), we went from 9 panics/week to zero.

    pip install metal-guard

    Single file, MIT licensed: https://github.com/Harperbot/metal-guard

  3. ronm92130 commented on Apr 24, 2026

    @ronm92130

    Adding a corroborating data point from a new hardware class — Mac mini M4 base (32 GB unified memory) — with a much smaller prefill size than the original report.

    System

    • Hardware: Mac mini M4 base — 10 cores (4P + 6E), 32 GB unified memory
    • macOS: 26.4.1 (Build 25E253)
    • Kernel: Darwin 25.4.0 (xnu-12377.101.15~1/RELEASE_ARM64_T8132)
    • IOGPUFamily: 130.13
    • mlx: 0.31.2
    • mlx-lm: 0.31.3
    • Model: mlx-community/Qwen3.6-35B-A3B-4bit (hybrid 3:1 GatedDeltaNet+Attention, ~19 GB weights)

    Panic signature — exact match

    panic(cpu 8 caller 0xfffffe00513bbe28): "completeMemory() prepare count underflow" @IOGPUMemory.cpp:550
    
    Panicked task 0xfffffe1e4174a418: 367197 pages, 25 threads: pid 50218: Python
      Kernel Extensions in backtrace:
        com.apple.iokit.IOGPUFamily(130.13)[1CC2AF3D-E6EF-3DC2-B32B-8DBD8CAA09B7]
    

    Full panic log available on request (contains no sensitive data but I didn't want to paste ~2k lines here).

    Workload — ordinary throughput bench, not stress

    mlx_lm.server launched with:

    mlx_lm.server \
      --model /path/to/qwen3.6-35b-a3b-mlx4 \
      --host 127.0.0.1 --port 8080 \
      --max-tokens 8192 \
      --prompt-cache-size 65536 \
      --prompt-cache-bytes 8589934592 \
      --temp 0.7 --top-p 0.80 --top-k 20 \
      --chat-template-args '{"enable_thinking": false}'

    Then a throughput bench that issued three sequential requests via /v1/chat/completions:

    Request Prompt tokens Max-tokens Result
    1 ~1,500 2 OK, ~3.9 s wall
    2 ~11,600 2 OK, ~31.9 s wall
    3 ~23,200 2 OK, ~75.4 s wall
    (followed by 3× isolated-TG runs @ 200 max-tokens) ~25 200 OK, ~8 s each

    Kernel panic occurred approximately 8 min 16 s after mlx_lm.server started, somewhere during or after the isolated-TG runs — not during the larger 23 K prefill. The process was healthy throughout, resident memory ~20 GB (well under the 32 GB ceiling).

    What's new vs the existing reports in this thread

    1. Substantially lower token threshold. The original report notes "Panic does not occur with smaller prompts (under ~10,000 tokens)" at M4 Max. Our panic followed a 23 K prefill that completed successfully, then triggered later during short-prompt generation. So the 10 K floor on M4 Max does not hold on M4 base — the bug can be triggered after brief larger-context exposure even when current request size is tiny.

    2. New hardware class: M4 base (previously reported: M4 Max, M5 MacBook, M1 Ultra, M3 Ultra). The M4 base shares the same T8132 SoC family as higher M4s but has only 32 GB unified memory and fewer GPU cores; this rules out "only happens on high-core-count parts" as a hypothesis.

    3. New macOS build: 26.4.1 (25E253) — the M4 Max report was 26.3 (25D125) and M3 Ultra reports were 26.4 (25E246). We're on the latest 26.4.1 point release, so the bug persists through the 26.4.x line.

    4. Qwen3.6 hybrid architecture (3× GatedDeltaNet + 1× Attention per block ×10 blocks = 40 layers). KV cache pattern differs meaningfully from the dense Qwen3.5-27B and Qwen3-Coder-30B-A3B models in other reports — yet the same panic triggers. Suggests the bug isn't specific to attention-layer buffer patterns.

    Consistent with @Harperbot's two-trigger-path hypothesis

    Our panic occurred after a mix of large-prefill requests followed by rapid short-prompt generation, which is consistent with a race in Metal buffer lifecycle management rather than a single-allocation bug. No concurrent threads were calling generate() — all requests were sequential through the HTTP server, but mlx_lm.server internally spawns worker threads.

    Mitigation tried — --prompt-cache-bytes did not prevent the panic

    Ran with --prompt-cache-bytes 8589934592 (8 GiB cap) specifically hoping this would prevent unbounded KV growth per mlx-lm#615. The cap did not prevent the kernel panic. Suggests the underlying Apple-side bug is independent of prompt-cache size.

    Net operational impact

    We evaluated MLX against llama.cpp for our production serving stack. Measured throughput advantage was substantial (MLX +30-55 % on PE, +40 % on TG). However, on M4 base hardware under normal workload, MLX produced a kernel panic within 10 minutes of real traffic. llama.cpp on the same hardware, same model family, has run for weeks without incident. We are adopting llama.cpp as a result. Posting this data point in case it helps Apple / the MLX team narrow the trigger — this was not a stress test.

    Happy to share the full panic log file, redacted if needed.

  4. Harperbot commented on Apr 27, 2026

    @Harperbot

    Adding a user-space mitigation data point for anyone landing here from search.

    We open-sourced our production workaround as Harperbot/metal-guard (MIT) after hitting this twice on gemma-4-31b-it-8bit / M1 Ultra 64GB. It does not fix the underlying kext bug — that's on Apple — but it provides:

    • Subprocess inference guard with cross-model cadence + post-generation flush to narrow the race window
    • Panic cooldown gate reading DiagnosticReports/*.panic to refuse new workers above a 72h rolling threshold (avoids "panic → respawn → panic" KeepAlive cycles)
    • KNOWN_PANIC_MODELS registry with model → error_class → tier (panic / abort / degradation) so callers can choose to subprocess-isolate or hard-skip

    Install (no PyPI yet):

    pip install "git+https://github.com/Harperbot/[email protected]"
    

    Repro evidence + mitigation rationale documented in repo. Posting in case it helps anyone here while this issue sits.

  5. FelikZ commented on May 4, 2026

    @FelikZ

    mlx unusable until this get fixed - no ralph loops, no long coding session just reboots.

  6. ferraro commented on May 11, 2026

    @ferraro

    Related kernel panic on M3 Ultra (different code path, same IOGPUFamily family)

    Hitting an apparently related GPU kernel panic running MLX-backed inference via LM Studio 0.4.12 with GLM-4.5 Air 4bit MLX.

    Panic signature (different from this issue, but same kext):

    panic(cpu 0): "IOGPUGroupMemory::remove_memory_object() memory object not found"
                  @IOGPUGroupMemory.cpp:323
    

    Kext in backtrace: com.apple.iokit.IOGPUFamily(130.13) → IOGraphicsFamily(600) → IOSurface(393.5.7).

    Environment:

    • Mac Studio M3 Ultra, 256 GB unified memory
    • macOS 26.4.1 (Build 25E253), Darwin Kernel 25.4.0 RELEASE_ARM64_T6031
    • LM Studio 0.4.12, MLX backend
    • Model: GLM-4.5 Air 4bit MLX

    Frequency: 2 panics within ~16 hours under normal interactive use (2026-05-10 19:55 and 2026-05-11 11:33), reproducible signature.

    Memory was not exhausted (`Compressor Info: 0% of compressed pages limit (OK), 0 swapfiles`) — this looks like the same class of GPU-memory-accounting-state corruption you're seeing, just hitting a different teardown path (`remove_memory_object`) instead of the prefill path (`completeMemory`).

    Filing a separate Apple Feedback referencing FB22091885 — happy to attach the full panic logs here if useful for cross-referencing.

  7. air237 commented on Jul 3, 2026

    @air237

    Confirming this crash on a different, smaller configuration — which I think is a useful data point, because it argues the bug is not specifically about oversized contiguous allocations.

    System

    Panic

    panic(cpu 9 caller 0xfffffe003e89d288): "completeMemory() prepare count underflow" @IOGPUMemory.cpp:550
    Panicked task 0xfffffe20842b8e88: 10521 pages, 28 threads: pid 54067: python3.12
    Kernel Extensions in backtrace:
       com.apple.iokit.IOGPUFamily(130.15.2)[...]@0xfffffe003e857e70->0xfffffe003e89e0c3
    

    Identical signature to the OP.

    Timeline (from mlx_lm.server log)

    The mlx_lm.server was started at 2026-07-04 00:57:29 and served a mixed sequence of chat completions. Prompt sizes over its lifetime (in tokens):

    26, 38, 54, 89, 123, 211, 1202, 2775, 41707

    Timeline of the largest and the final activity:

    Time Event
    01:02:36 Prefill of a 41,707-token prompt completes; prompt cache grows to 4.11 GB (1 seq). Generation succeeds.
    01:02:46 – 01:15:18 ~7 more chat completions, all with tiny prompts (26–211 tokens). Prompt cache grows monotonically: 4.29 → 4.30 → 8.60 → 9.01 → 9.02 → 9.18 → 9.29 → 9.46 GB (2 seqs).
    01:15:18 Last successful POST /v1/chat/completions (200).
    01:16:09 Kernel panic. No new request in flight; ~51 seconds after the last successful response.

    Why this is interesting relative to the current hypothesis in this issue

    The OP hypothesis is that a single very large contiguous Metal allocation for prefill of a >170K-token prompt is what corrupts the IOGPU accounting. My reproduction does not fit that shape:

    1. The biggest prefill here was ~42K tokens, which is 4× smaller than Kernel panic (IOGPUMemory.cpp:550) on M4 Max with large context prefill (~173K tokens) #3186's 173K threshold, and it succeeded.
    2. The crash happened ~13.5 minutes after that prefill, during (or just after) a series of trivial requests (26–211 tokens each).
    3. Peak prompt-cache size was ~9.5 GB on a 48 GB unified-memory system — roughly 20% utilization, i.e. nowhere near the ~80% saturation mentioned in the closely-related Kernel panic: "completeMemory() prepare count underflow" in IOGPUMemory.cpp on macOS 26.4 M3 Ultra during MLX inference #3346.
    4. The mlx_lm.server process was long-running, accumulating prompt-cache state across many independent chats (2 concurrent sequences at the time of the crash).

    Combined with #3346 (M3 Ultra, 9 crashes in 6 days, load-heavy but not necessarily large-prompt), this looks more like a state / refcount bug that accumulates over the lifetime of a long-running MLX process, rather than a single-alloc-too-big bug. The prepare/complete refcount underflow in IOGPUMemory.cpp:550 is consistent with a slow leak/imbalance in prepare vs complete calls that eventually goes negative — not with a one-shot huge allocation.

    Suggested implications for the MLX-side mitigation

    If a prefill-token-count guard is the workaround being considered, it likely would not have prevented my crash. Possible additional angles worth investigating on the MLX side:

    • Whether every MTLBuffer / MTLCommandBuffer prepare is paired 1:1 with a complete across the prompt-cache lifecycle (especially when caches are trimmed / evicted / grown for a new sequence).
    • Whether long-lived server processes could periodically drain and rebuild the Metal command queue as a defensive measure.
    • Whether the accumulating prompt cache across independent sequences (4.11 → 9.46 GB in ~12 min here) exercises a code path different from a fresh single-prompt inference.

    Happy to gather more targeted diagnostics if useful — e.g. running with MTL_DEBUG_LAYER=1, --log-level DEBUG, or a specific reproducer script. The paniclog is 3 MB, can attach or excerpt more of it on request.

    Also relevant / same underlying kext bug, different reproducer: #3346 (M3 Ultra, closed but not fixed).

  8. ronm92130 commented on Jul 7, 2026

    @ronm92130

    Following up on my earlier M4-base data point with a controlled trigger isolation and a
    userspace workaround that held up under test
    . Same box as before (Mac mini M4 base, 32 GB,
    macOS 26.4.1 / 25E253, IOGPUFamily 130.13, mlx 0.31.2, mlx-lm 0.31.3,
    mlx-community/Qwen3.6-35B-A3B-4bit).

    Trigger isolation

    • A faithful replica of my original crashing session (sequential requests via
      /v1/chat/completions, up to 23 k-token prefills, prompt-cache hits, long idle windows)
      ran 111 minutes without a panic — 14× my original 8m16s TTC.
    • Adding two concurrent request streams + prompt-cache eviction churn (unique 12–16 k
      prompts overflowing --prompt-cache-bytes 8GiB, mixed long/short generations) panics in
      102–108 s, reproducibly (3/3 cold boots), exact IOGPUMemory.cpp:550 signature.

    So on this hardware the trigger is concurrency + buffer-lifecycle churn, not prefill
    size, not throughput, and (see below) not memory pressure.

    Single-variable attribution

    Identical crashing workload, one change per arm, pass bar = 10 fresh-server runs
    (~15–20 min each ≈ 10× median TTC) with zero panics:

    change result
    none (stock) panic ×3 @ 102–108 s
    mx.set_wired_limit never called (residency set stays empty) no panic, 10/10 runs, 4.2 h
    + also no periodic clear_cache no panic, 10/10 runs, 5.0 h
    only no periodic clear_cache (wiring intact) panic @ 99.9 s
    sysctl iogpu.disable_wired_collector=1 + debug.iogpu.metal4_disable_async_mapping=1 (wiring intact) panic @ 109.6 s
    RotatingKVCache / lower wired cap / MLX_MAX_OPS_PER_BUFFER reductions die earlier as clean userspace kIOGPUCommandBufferCallbackErrorOutOfMemory — never reach the panic

    Quant generalization: repeated with Qwen3.6-35B-A3B-6bit (27.1 GiB — rides this box's
    recommended working set): stock panics even faster (60.9 s), while the
    no-set_wired_limit variant produced zero panics across ~76 GPU-active minutes (75×
    the control TTC) despite heavy paging. Higher memory pressure accelerates the trigger but
    the protection is not quant-specific.

    Implications:

    1. The per-buffer residency-set add/remove+commit traffic enabled by set_wired_limit
      is the discriminating factor.
      With it, ~100 s to panic; without it, zero panics in
      ~9 h / 5.3 M tokens on the same workload.
    2. The panic path is synchronous (command-buffer completion): disabling the idle wired
      collector and Metal4 async mapping changed nothing.
    3. Not OOM: genuine memory exhaustion produces a clean userspace Metal error, no panic —
      consistent with the OP's "sufficient headroom remains" and with @air237's idle crash.

    Workaround

    Skipping set_wired_limit entirely (a launcher shim that no-ops it before mlx_lm.server
    starts) cost ≤3 % sequential throughput in my A/B probes (weights become pageable, so
    throughput under external memory pressure is the caveat). Happy to share the shim, the soak
    harness, and per-5-second ioclasscount telemetry (IOGPUMemory, AGXAllocation, …) for
    all runs if useful — the counters around the panics may help whoever picks up FB22091885.

    If maintainers are interested I can PR an env-gated opt-out of set_wired_limit to mlx-lm
    (note: a server-level --max-kv-size would NOT have helped here, and is silently ignored
    for make_cache architectures like the qwen3_5 hybrids).


    Full test report (methodology, pre-registered pass/fail bar, all eight arms, throughput probes, 6-bit generalization, per-run kernel-object telemetry notes) plus the launcher shim: https://gist.github.com/ronm92130/9bf97b300175be8e4f578c6e295feeaa

  9. BrunoCerberus commented on Aug 28, 2026

    @BrunoCerberus

    Data point: the set_wired_limit mitigation still holds on IOGPUFamily 162.11 / macOS 27, in production rather than a soak harness.

    Adding this because my driver version is well ahead of anything reported in this thread so far, and because I have been running @ronm92130's R1 workaround as a permanent deployment rather than a test arm.

    System

    • Mac Studio M3 Ultra, 96 GB
    • macOS 27.0 beta (26A5421a), Darwin 27.0.0, xnu-13432.1.9~3/RELEASE_ARM64_T6031
    • IOGPUFamily 162.11 (the reports above are on 129.x / 130.x)
    • mlx 0.32.2, mlx-lm 0.31.3

    Workload

    Two always-on mlx_lm.server instances: a 26B-A4B MoE chat agent on :8080 (--prompt-cache-bytes 12000000000) and a 27B dense coding model on :8081.

    This is a 24/7 messaging agent plus an agentic coding backend, so it sits squarely in the trigger profile identified above: overlapping inbound messages and scheduled cron jobs supply the concurrency, and long sessions with repeated context compaction supply the prompt-cache eviction churn. Largest observed prefill 146,838 tokens, comparable to the OP's ~173k.

    Result

    No panics. 663 requests logged across the two instances, chat instance PID unchanged for 2 days (so KeepAlive has not been quietly respawning a crashed server), host uptime 3 days, zero .panic reports.

    Implementation note

    I patch at the mlx.core module level rather than per call site. mlx_lm shares that module object, so a single assignment covers all of them, including mlx_lm/server.py which still calls it unconditionally in 0.31.3 (7 call sites in the package overall):

    import os, sys
    import mlx.core as mx
    
    def main():
        if os.environ.get("MLX_LM_DISABLE_WIRED_LIMIT") == "1":
            mx.set_wired_limit = lambda *a, **k: 0
            print("[shim] wired limit disabled", file=sys.stderr)
        from mlx_lm.server import main as server_main
        sys.argv = ["mlx_lm.server"] + sys.argv[1:]
        server_main()

    Launched from a LaunchAgent with MLX_LM_DISABLE_WIRED_LIMIT=1. To be clear for anyone landing here from search: that env var is not an mlx-lm feature, it is just this shim's own toggle.

    An early symptom worth naming

    The recognisable precursor, before anything panics, is system-wide sluggishness that scales with context length. Not the model getting slower, the whole machine. That matches the mechanism: wired pages cannot be reclaimed, so KV growth starves everything else. With wiring disabled I now see free memory dip to ~44% during heavy sessions and return to ~86% afterwards, which is exactly the reclaim that wiring prevents. If your Mac gets laggy as context fills, that is likely this same bug in its mild form.

    What this does not show

    I have not run this machine with wiring enabled on IOGPUFamily 162.11, so this is not evidence that the underlying driver bug is fixed in macOS 27. It only shows that the mitigation still works on a much newer driver. On an always-on box the cost of a positive result is a reboot, so I have not gone looking for one.

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

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions