Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio MLX images: release MLX's buffer cache after each generation (#14795)

Daniel Han7c26a1c86538
diff --git a/studio/backend/core/inference/mlx_diffusion_backend.py b/studio/backend/core/inference/mlx_diffusion_backend.py
index cd83775ad08..9a6f3fb9b7b 100644
--- a/studio/backend/core/inference/mlx_diffusion_backend.py
+++ b/studio/backend/core/inference/mlx_diffusion_backend.py
@@ -361,6 +361,19 @@ def vae_tiling_needed(width: int, height: int, free_bytes: Optional[int]) -> boo
return untiled_decode_bytes(width, height) > free_bytes
+def release_buffer_cache(mx: Any) -> None:
+ """Synchronize, then clear MLX's buffer cache (clearing with work in flight can free buffers the GPU still writes).
+ Best effort: runs in cleanup paths and must not mask the caller's exception."""
+ try:
+ mx.synchronize()
+ except Exception as exc: # noqa: BLE001
+ logger.debug("mlx_diffusion.drain_skipped: %s", exc)
+ try:
+ mx.clear_cache()
+ except Exception as exc: # noqa: BLE001
+ logger.debug("mlx_diffusion.clear_cache_skipped: %s", exc)
+
+
class MfluxRuntime:
"""The only code that imports mlx / mflux. Tests replace it with a fake (``backend.runtime_factory``)."""
@@ -433,8 +446,9 @@ class MfluxRuntime:
callback = _StepCallback()
model.callbacks.register(callback)
cancelled = False
+ image = None
try:
- result = model.generate_image(
+ image = model.generate_image(
seed = int(seed),
prompt = prompt,
negative_prompt = negative_prompt,
@@ -442,7 +456,7 @@ class MfluxRuntime:
width = int(width),
height = int(height),
guidance = guidance,
- )
+ ).image
except StopImageGenerationException as exc:
# The unwound mflux frames hold the model; uncleared, it survives unload().
drop_exception_frames(exc)
@@ -456,9 +470,11 @@ class MfluxRuntime:
model.callbacks.in_loop.remove(callback)
except (AttributeError, ValueError):
pass
+ # Cached activations are idle system RAM on unified memory; live weights are untouched.
+ release_buffer_cache(mx)
if cancelled:
raise MlxCancelled("cancelled")
- return result.image
+ return image
def free_working_set_bytes(self) -> Optional[int]:
"""Metal's recommended working set minus what MLX holds live now (the resident model), or None."""
@@ -511,9 +527,9 @@ class MfluxRuntime:
gc.collect()
try:
import mlx.core as mx
- mx.clear_cache()
except Exception: # noqa: BLE001
- pass
+ return
+ release_buffer_cache(mx)
def supports_guidance(self, model: Any) -> bool:
return bool(getattr(getattr(model, "model_config", None), "supports_guidance", False))
diff --git a/studio/backend/tests/test_mlx_diffusion_backend.py b/studio/backend/tests/test_mlx_diffusion_backend.py
index 20005d09f31..6fb5f2fcae2 100644
--- a/studio/backend/tests/test_mlx_diffusion_backend.py
+++ b/studio/backend/tests/test_mlx_diffusion_backend.py
@@ -1754,3 +1754,117 @@ def test_the_mlx_plan_names_the_base_the_load_will_read(monkeypatch, tmp_path):
assert recorder.calls[-1]["base_repo"] == BASE
mb.MlxDiffusionBackend().download_plan(str(local), gguf_filename = gguf, base_repo = BASE)
assert recorder.calls[-1]["base_repo"] == BASE
+
+
[email protected]("outcome", ["done", "cancelled", "failed"])
+def test_the_runtime_releases_mlx_buffer_cache_after_every_generation(monkeypatch, outcome):
+ """Freed activations otherwise sit in MLX's buffer cache, i.e. in system RAM, until unload."""
+ mx = pytest.importorskip("mlx.core")
+ pytest.importorskip("mflux.utils.exceptions")
+
+ class _Registry:
+ """The two members of mflux's CallbackRegistry the runtime touches."""
+
+ def __init__(self):
+ self.in_loop = []
+
+ def register(self, callback):
+ self.in_loop.append(callback)
+
+ cleared = []
+ real_clear = mx.clear_cache
+ monkeypatch.setattr(mx, "clear_cache", lambda: (cleared.append(1), real_clear()))
+
+ class _Image:
+ image = "png"
+
+ class _Model:
+ callbacks = _Registry()
+
+ def generate_image(self, **kwargs):
+ latents = mx.zeros((2, 2))
+ for t in range(kwargs["num_inference_steps"]):
+ for cb in self.callbacks.in_loop:
+ cb.call_in_loop(t, kwargs["seed"], kwargs["prompt"], latents, None, None)
+ if outcome == "failed":
+ raise RuntimeError("boom")
+ return _Image()
+
+ def on_step(done):
+ if outcome == "cancelled" and done == 2:
+ raise mb.MlxCancelled("cancelled")
+
+ runtime = mb.MfluxRuntime()
+ kwargs = dict(
+ prompt = "p",
+ negative_prompt = None,
+ seed = 1,
+ steps = 3,
+ width = 64,
+ height = 64,
+ guidance = None,
+ on_step = on_step,
+ )
+ model = _Model()
+ if outcome == "done":
+ assert runtime.generate(model, **kwargs) == "png"
+ else:
+ with pytest.raises(mb.MlxCancelled if outcome == "cancelled" else RuntimeError):
+ runtime.generate(model, **kwargs)
+ assert cleared == [1]
+ assert model.callbacks.in_loop == []
+
+
+def test_every_mlx_cache_clear_goes_through_the_drain():
+ """The only ``clear_cache`` call is inside ``release_buffer_cache``, right after its synchronize."""
+ import ast
+ import inspect
+
+ tree = ast.parse(inspect.getsource(mb))
+ sites = []
+ for func in ast.walk(tree):
+ if not isinstance(func, (ast.FunctionDef, ast.AsyncFunctionDef)):
+ continue
+ for node in ast.walk(func):
+ if (
+ isinstance(node, ast.Call)
+ and isinstance(node.func, ast.Attribute)
+ and node.func.attr == "clear_cache"
+ ):
+ sites.append(func.name)
+ assert sites == ["release_buffer_cache"]
+
+
+def _recording_mx(sync_error = None, clear_error = None):
+ events = []
+
+ class _Mx:
+ @staticmethod
+ def synchronize(stream = None):
+ events.append("synchronize")
+ if sync_error is not None:
+ raise sync_error
+
+ @staticmethod
+ def clear_cache():
+ events.append("clear_cache")
+ if clear_error is not None:
+ raise clear_error
+
+ return _Mx, events
+
+
+def test_release_buffer_cache_drains_before_clearing():
+ mx, events = _recording_mx()
+ mb.release_buffer_cache(mx)
+ assert events == ["synchronize", "clear_cache"]
+
+
+def test_release_buffer_cache_never_replaces_the_callers_exception():
+ mx, events = _recording_mx(sync_error = RuntimeError("sync"), clear_error = RuntimeError("clear"))
+ with pytest.raises(ValueError, match = "generation failed"):
+ try:
+ raise ValueError("generation failed")
+ finally:
+ mb.release_buffer_cache(mx)
+ assert events == ["synchronize", "clear_cache"]