#4040·omlx

First forward after 2 s of idle stalls ~900 ms when iogpu.wired_limit_mb is unset

Author: torarnvCreated Sep 27, 2026Updated Sep 30, 2026

Summary

On an M1 Ultra serving a 42 GB model, the first forward pass of a request costs 800–1000 ms whenever no forward ran for 2 s or more. The next forward costs 25 ms. Agent turns leave gaps that long between requests all the time, so most requests pay this in TTFT.

The cost scales with resident GPU memory, about 12–22 ms per GB. A wired limit changes which command pays it:

  • Unwired: the first command that reads the weights pays, once the weights have gone 2 s unread. A trivial GPU command in the gap doesn't prevent it.
  • Wired: the first GPU command of any kind pays, once the GPU has gone 2 s without work. A trivial GPU command every 0.5 s prevents it completely.

oMLX runs unwired by default. Since bf48d988 ("fix: avoid setting MLX wired limit for default Metal cap"), _apply_metal_wired_limit skips mx.set_wired_limit when iogpu.wired_limit_mb is 0, and 0 is the macOS default. The thread in #1745 shows that bf48d988 didn't fix #1745, and 8da6d974 did.

Setup

  • Apple M1 Ultra, 64 GB, macOS 27.0
  • max_recommended_working_set_size 51.8 GB, iogpu.wired_limit_mb 0
  • mlx 0.32.2, mlx-lm 0.32.0
  • Model: lmstudio-community/Qwen3-Coder-Next-MLX-4bit, 41.8 GB active after load

Reproducer

idle_gpu_probe.py (at the end of this issue) loads a model or holds plain buffers, sleeps for a range of idle times, and then times GPU commands. The columns:

  • idle (s) is the sleep before the row.
  • wake forward (ms) is a one-token forward pass, the first command after the sleep.
  • repeat forward (ms) is the same forward again right away.
  • wake probe (ms) is a trivial mx.eval(mx.zeros(1) + 1), the first command after the sleep. It reads no held memory.
  • --keepalive N runs the trivial command every N seconds during the sleep.
  • --wired-gb N calls mx.set_wired_limit. It works with the sysctl at 0, as long as N stays below max_recommended_working_set_size.

Results

Each cell below gives the range of two runs.

The model runs used --forward-first:

idle (s) unwired unwired, keepalive 0.5 s wired 50 GB wired 50 GB, keepalive 0.5 s
0.5 48 46 51–52 43–45
1.0 51–77 46–49 52 44–45
2.0 862–984 873–968 619–797 40–43
3.0 940–942 809–971 623–958 44–49
5.0 941–945 993–1009 — 42–43
7.0 958–992 962–974 — 48–50
15.0 — 977–1012 — —

The values are wake forward in ms. repeat forward stayed at 20–27 ms in every run. The first run was cut short before the higher idle times, which is why some cells are empty. The tables leave out each run's first row, which is the first forward after load and cost 850–4600 ms.

The runs without a model show wake probe in ms:

idle (s) no memory held no memory held, wired 42 GB, unwired 42 GB, wired
0.5–1.0 1–3 2–3 1–3 3–4
2.0–7.0 6–10 7–11 30–43 470–620

The cost grows with the memory held, and a wired limit makes a trivial command pay the full cost. Unwired, a trivial command pays only 30–43 ms, and the full cost moves to the first forward. Running the forward after the trivial commands instead of first gives the same numbers: 44–48 ms below 2 s of idle and 840–925 ms from 2 s on.

Why default wiring was removed

In #1745, a user with Memory Guard on saw decode drop from ~85 to ~14 tok/s. The log showed oMLX raising the wired limit to 96 GB with the sysctl unset. bf48d988 removed that call on the guess that it caused the slowdown. The reporter tested the build with bf48d988, and decode stayed just as slow. The next release candidate added 8da6d974 ("avoid MLX telemetry in active memory guard ticks"), and that build brought decode back to 82–86 tok/s. Nobody has tested a build with 8da6d974 and the wiring restored. In our runs, wired decode ran at 21 ms per forward against 25 ms unwired.

Proposal

  1. When iogpu.wired_limit_mb is unset, wire the model's memory again, up to max_recommended_working_set_size. Pick a value that leaves the OS headroom, in line with the reasoning in #2184.
  2. While a model is loaded, submit a trivial GPU command whenever the engine has gone about 1 s without GPU work. With the memory wired, that removes the stall. Unwired, it does nothing, so it only helps together with the first change.
  3. Before merging, rerun the #1745 benchmark (Memory Guard on, balanced tier, a Qwopus MTP model) with the wiring restored to confirm the decode slowdown doesn't come back.
idle_gpu_probe.py
python
# SPDX-License-Identifier: Apache-2.0
"""Measure how long the first GPU command takes after the GPU sits idle.

oMLX traces show the first command of a request stalling 700-900 ms when the
server idled for 14 s or more, while back-to-back commands take 0.3 ms. This
script reproduces the pattern outside oMLX: hold some GPU memory, sleep, then
time a trivial eval. Comparing a large and a small allocation tells a stall
tied to resident memory apart from one any GPU work pays after idle.

Examples::

    # Real model weights, as oMLX holds them.
    python scripts/idle_gpu_probe.py --model ~/LLMs/lmstudio-community/Qwen3-Coder-Next-MLX-4bit

    # Plain buffers of the same size, then a small one.
    python scripts/idle_gpu_probe.py --alloc-gb 42
    python scripts/idle_gpu_probe.py --alloc-gb 1

    # Same, with the wired limit raised (needs iogpu.wired_limit_mb set).
    python scripts/idle_gpu_probe.py --alloc-gb 42 --wired-gb 50

    # Keep the GPU busy with a trivial command every 2 s while idle.
    python scripts/idle_gpu_probe.py --alloc-gb 42 --keepalive 2

    # Make the forward pass the first command after idle, as a request is.
    python scripts/idle_gpu_probe.py --model ~/LLMs/... --forward-first
"""

import argparse
import os
import statistics
import time

import mlx.core as mx


def _ms(start: float) -> float:
    return (time.perf_counter() - start) * 1000.0


def trivial_probe() -> float:
    start = time.perf_counter()
    mx.eval(mx.zeros(1) + 1)
    return _ms(start)


def allocate(gigabytes: float) -> list[mx.array]:
    """Hold ``gigabytes`` of GPU memory in 1 GB buffers the GPU has written."""
    chunk = 1024**3 // 2  # float16 elements per GB
    arrays = []
    remaining = gigabytes
    while remaining > 0:
        size = int(chunk * min(1.0, remaining))
        array = mx.ones((size,), dtype=mx.float16)
        mx.eval(array)
        arrays.append(array)
        remaining -= 1.0
    return arrays


def load_model(path: str):
    from mlx_lm import load

    model, _ = load(os.path.expanduser(path))
    return model


def forward_probe(model) -> float:
    start = time.perf_counter()
    mx.eval(model(mx.array([[1]])))
    return _ms(start)


def idle(seconds: float, keepalive: float) -> None:
    if keepalive <= 0:
        time.sleep(seconds)
        return
    deadline = time.monotonic() + seconds
    while True:
        remaining = deadline - time.monotonic()
        if remaining <= 0:
            return
        time.sleep(min(keepalive, remaining))
        if deadline - time.monotonic() > 0:
            trivial_probe()


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
    source = parser.add_mutually_exclusive_group()
    source.add_argument("--model", help="load these weights with mlx_lm.load")
    source.add_argument(
        "--alloc-gb", type=float, default=0.0, help="hold this many GB instead"
    )
    parser.add_argument(
        "--wired-gb",
        type=float,
        default=0.0,
        help="call mx.set_wired_limit with this many GB (0 leaves it unset)",
    )
    parser.add_argument(
        "--sleeps",
        default="0.5,1,2,3,5,7,10,15,20,30",
        help="comma-separated idle times in seconds",
    )
    parser.add_argument("--repeats", type=int, default=2)
    parser.add_argument(
        "--keepalive",
        type=float,
        default=0.0,
        help="run a trivial GPU command every N seconds while idle",
    )
    parser.add_argument(
        "--forward-first",
        action="store_true",
        help="run the forward pass before the trivial commands (needs --model)",
    )
    args = parser.parse_args()
    if args.forward_first and not args.model:
        parser.error("--forward-first needs --model")

    info = mx.metal.device_info() if hasattr(mx, "metal") else mx.device_info()
    print(
        f"device: {info.get('device_name', '?')}, "
        f"recommended working set "
        f"{info.get('max_recommended_working_set_size', 0) / 1024**3:.1f}GB"
    )
    if args.wired_gb > 0:
        previous = mx.set_wired_limit(int(args.wired_gb * 1024**3))
        print(f"wired limit: {previous / 1024**3:.1f}GB -> {args.wired_gb:.1f}GB")
    else:
        print("wired limit: unset")

    model = None
    held: list[mx.array] = []
    start = time.perf_counter()
    if args.model:
        model = load_model(args.model)
        print(f"loaded model in {_ms(start) / 1000.0:.1f}s")
        forward_probe(model)
    elif args.alloc_gb > 0:
        held = allocate(args.alloc_gb)
        print(f"allocated {args.alloc_gb:.1f}GB in {_ms(start) / 1000.0:.1f}s")
    print(
        f"active memory: {mx.get_active_memory() / 1024**3:.1f}GB, "
        f"keepalive: {f'every {args.keepalive}s' if args.keepalive > 0 else 'off'}"
    )

    for _ in range(3):
        trivial_probe()
    warm = [trivial_probe() for _ in range(20)]
    print(f"warm trivial probe: median {statistics.median(warm):.2f}ms\n")

    # Each step is (column name, legend text, function returning ms).
    wake_probe = (
        "wake probe",
        "first command after idle, a trivial zeros(1) + 1 that reads no held memory",
        trivial_probe,
    )
    repeat_probe = (
        "repeat probe",
        "the trivial command again, with the GPU awake",
        trivial_probe,
    )
    steps = [wake_probe, repeat_probe]
    if model is not None:
        run_forward = lambda: forward_probe(model)  # noqa: E731
        repeat_forward = (
            "repeat forward",
            "the forward pass again, right after the one before it",
            run_forward,
        )
        if args.forward_first:
            wake_forward = (
                "wake forward",
                "first command after idle, a one-token forward pass over the weights",
                run_forward,
            )
            steps = [wake_forward, repeat_forward, repeat_probe]
        else:
            forward = (
                "forward",
                "one-token forward pass over the weights, after the probes",
                run_forward,
            )
            steps = [wake_probe, repeat_probe, forward, repeat_forward]

    columns = ["idle (s)"] + [f"{name} (ms)" for name, _, _ in steps]
    widths = [len(column) for column in columns]
    print(f"  {columns[0]}: time the GPU sits unused before the row")
    for column, (_, description, _) in zip(columns[1:], steps):
        print(f"  {column}: {description}")
    print("\n" + "  ".join(columns))
    for seconds in (float(s) for s in args.sleeps.split(",")):
        for _ in range(args.repeats):
            idle(seconds, args.keepalive)
            values = [seconds] + [run() for _, _, run in steps]
            cells = [f"{value:>{width}.1f}" for value, width in zip(values, widths)]
            print("  ".join(cells), flush=True)

    # Keeps the buffers alive until every probe has run.
    del held


if __name__ == "__main__":
    main()