Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 36 additions & 10 deletions omlx/engine_pool.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@
validate_ane_prefill,
)
from .scheduler import SchedulerConfig
from .utils.fatal import exit_if_gpu_submissions_ignored
from .utils.metal_sync import unreleased_graphics_bytes
from .utils.model_loading import dflash_batched_requested, dflash_batched_supported
from .utils.proc_memory import get_phys_footprint
Expand Down Expand Up @@ -3152,6 +3153,38 @@ async def _unload_engine(self, model_id: str, *, local_only: bool = False) -> No
if cancelled:
raise asyncio.CancelledError

async def _metal_sync_clear_cache(self, model_id: str) -> None:
"""Run ``mx.synchronize()`` + ``mx.clear_cache()`` tolerating a pending
Metal command-buffer error left behind by a failed prefill.

A prefill that OOMs on Metal leaves a pending error on the command
buffer, and the first ``mx.synchronize()`` during teardown re-raises
it. That first raise consumes the pending error, so a single retry
succeeds and the settle barrier / memory release can still run
(#3737/#4344); otherwise memory accounting leaks and every later load
is refused with 507 until restart.

Catch ONLY ``RuntimeError`` whose message contains
"Command buffer execution failed"; any other exception propagates
unchanged. Honour fatal GPU-submission errors first via
``exit_if_gpu_submissions_ignored`` (which exits the process) before
logging and retrying once.
"""
loop = asyncio.get_running_loop()
run = lambda: (mx.synchronize(), mx.clear_cache())
try:
await loop.run_in_executor(get_mlx_executor(), run)
except RuntimeError as e:
if "Command buffer execution failed" not in str(e):
raise
exit_if_gpu_submissions_ignored(e)
logger.warning(
f"Metal command-buffer error on synchronize/clear_cache while "
f"unloading '{model_id}': {e}; the pending error was consumed "
f"by the raise, retrying once"
)
await loop.run_in_executor(get_mlx_executor(), run)

async def _stop_and_unload_engine(
self, model_id: str, *, local_only: bool = False
) -> None:
Expand Down Expand Up @@ -3254,9 +3287,7 @@ async def _stop_and_unload_engine(
# still referenced by in-flight command buffers. See issue #300.
gc.collect()
loop = asyncio.get_running_loop()
await loop.run_in_executor(
get_mlx_executor(), lambda: (mx.synchronize(), mx.clear_cache())
)
await self._metal_sync_clear_cache(model_id)

# RAM Engram tables share MLX buffers with CPU views, so their packed
# bytes are included in both admission and Metal unload settlement.
Expand Down Expand Up @@ -3336,9 +3367,7 @@ async def _stop_and_unload_engine(
)
await asyncio.sleep(0.5)
gc.collect()
await loop.run_in_executor(
get_mlx_executor(), lambda: (mx.synchronize(), mx.clear_cache())
)
await self._metal_sync_clear_cache(model_id)

# Release memory tracking AFTER barrier
self._current_model_memory = max(0, self._current_model_memory - resident_size)
Expand Down Expand Up @@ -3372,10 +3401,7 @@ async def _stop_and_unload_engine(
)
for _ in range(3):
gc.collect()
await loop.run_in_executor(
get_mlx_executor(),
lambda: (mx.synchronize(), mx.clear_cache()),
)
await self._metal_sync_clear_cache(model_id)
await asyncio.sleep(1.0)
active_after = mx.get_active_memory()
if active_after > self._current_model_memory + 5 * 1024**3:
Expand Down
76 changes: 76 additions & 0 deletions tests/test_engine_pool.py
Original file line number Diff line number Diff line change
Expand Up @@ -4371,6 +4371,82 @@ def test_other_entries_serving_in_use_lease_counts(self, pool_with_loaded_model)
entry_b.in_use = 1
assert pool._other_entries_serving("model-a") is True

@pytest.mark.asyncio
async def test_unload_survives_metal_command_buffer_error(
self, pool_with_loaded_model
):
"""#3737/#4344: a Metal-OOM prefill leaves a pending command-buffer
error that mx.synchronize() re-raises during teardown. The first raise
consumes that pending error, so the synchronize/clear_cache retry
succeeds: no exception escapes the unload and memory accounting is
still released, instead of leaking so every later load 507s.
"""
pool = pool_with_loaded_model
est_size = pool._entries["model-a"].estimated_size # 5GB
initial_memory = pool._current_model_memory

# First synchronize raises the pending OOM error; the retry succeeds.
oom_error = RuntimeError(
"[METAL] Command buffer execution failed: Insufficient Memory "
"(00000008:kIOGPUCommandBufferCallbackErrorOutOfMemory)"
)

with (
patch("omlx.engine_pool.mx") as mock_mx,
patch("omlx.engine_pool.get_mlx_executor", return_value=None),
patch("omlx.engine_pool.get_phys_footprint", return_value=0),
patch("asyncio.sleep", new_callable=AsyncMock),
):
# Pre-unload 10GB -> 5GB after unload (5GB freed >= 3GB tolerance).
mock_mx.get_active_memory = MagicMock(
side_effect=[10 * 1024**3, 5 * 1024**3]
)
# First synchronize raises the pending OOM error; the retry
# (side_effect exhausted) returns a sentinel and succeeds.
mock_mx.synchronize = MagicMock(side_effect=[oom_error, None])
mock_mx.clear_cache = MagicMock()

# (a) No exception escapes the unload.
await pool._unload_engine("model-a")

# (b) Memory accounting was released by the resident size.
assert pool._entries["model-a"].engine is None
assert pool._current_model_memory == initial_memory - est_size

@pytest.mark.asyncio
async def test_unload_exits_on_submissions_ignored(
self, pool_with_loaded_model
):
"""#3737/#4344: a fatal 'GPU submissions ignored' Metal error must
still exit the process even during teardown: exit_if_gpu_submissions_ignored
is honoured (fatal_exit called) before any retry, so the process is
terminated rather than leaving memory accounting leaked.
"""
pool = pool_with_loaded_model
sub_ignored = RuntimeError(
"[METAL] Command buffer execution failed: GPU submissions ignored "
"(00000008:kIOGPUCommandBufferCallbackErrorSubmissionsIgnored)"
)

with (
patch("omlx.engine_pool.mx") as mock_mx,
patch("omlx.engine_pool.get_mlx_executor", return_value=None),
patch("omlx.engine_pool.get_phys_footprint", return_value=0),
patch("asyncio.sleep", new_callable=AsyncMock),
patch("omlx.utils.fatal.fatal_exit", side_effect=SystemExit) as fatal_exit,
):
mock_mx.get_active_memory = MagicMock(return_value=0)
mock_mx.synchronize = MagicMock(side_effect=[sub_ignored])
mock_mx.clear_cache = MagicMock()

# exit_if_gpu_submissions_ignored() calls fatal_exit() which raises.
with pytest.raises(SystemExit):
await pool._stop_and_unload_engine("model-a")

# The fatal-exit hook was invoked with the error before any retry.
fatal_exit.assert_called_once()
assert str(sub_ignored) in str(fatal_exit.call_args.args[0])


class TestEnginePoolInUseLease:
"""Tests for the acquire-vs-use in-use lease (#1667).
Expand Down
Loading