Repository navigation
Description
Describe the bug
A compiled function that is called from more than one thread leaves its entries in every thread's compile cache except the last caller's when it is freed. A later mx.compile of a callable that lands at the same address (CPython reuses freed addresses almost every time) then matches the stale entry on those threads and runs the old trace, with the arrays the old function captured. The result is silently wrong outputs, with no error.
This is related to #3940 (a function freed off its tracing thread), but it is a different path. Here the function is freed on the thread that called it last, so the erase reaches that one cache. The other callers' caches still keep the entry. It reproduces on 0.32.4 (latest release) on Metal and with mx.set_default_device(mx.cpu).
To Reproduce
import queue, threading
import mlx.core as mx
class Scale:
def __init__(self, w): self.w = mx.array(w)
def f(self, x): return x * self.w
jobs = queue.Queue()
def worker(): # a long-lived thread (its compile cache lives on)
while True:
fn, out = jobs.get(); out.put(fn())
threading.Thread(target=worker, daemon=True).start()
def on_worker(fn):
out = queue.Queue(); jobs.put((fn, out)); return out.get()
x = mx.array(1.0)
wrong = 0
for i in range(50):
c = mx.compile(Scale(float(i)).f)
got = on_worker(lambda: c(x).item()) # 1. call it on the worker thread
c(x).item() # 2. then on the main thread (the last caller)
wrong += got != i
del c # 3. free it: only the main thread's entry is erased
print("wrong on the worker thread:", wrong, "of 50")Expected behavior
0 of 50 wrong. On MLX 0.32.4 it prints 47-49 of 50 (M3 Ultra, macOS). The count is 0 if step 2 is removed, or if each thread calls its own mx.compile of the same callable.
Cause (from reading the source)
- The compile cache is per thread (
thread_localincompile_cache_unsafe(),mlx/compile.cpp). It is keyed byfun_id, the address of the Python callable (python/src/transforms.cpp). PyCompiledFun::call_implsetscache = mx::detail::compile_cache()on every call, so it remembers only the thread that called it last.~PyCompiledFuncallscompile_erase(cache, fun_id), so only that thread's entry is removed. Entries in other threads' caches stay, keyed by an address a new callable can get.CompileCache::findmatches onfun_id, input shapes/dtypes, constants and stream. A new function with the same signature matches the stale entry and runs the dead function's tape and constants.
The C++ compile(fun) overload looks similar: its deleter erases only from the cache of the thread that created it.
Suggested fix
Have PyCompiledFun record every cache it inserted into (e.g. a deduplicated set of weak pointers) and erase fun_id from each of them in its destructor. Alternatively, key entries by a unique per-function id instead of the callable's address, so a stale entry can never be matched again; it would still leak until its thread exits.
Desktop:
- OS: macOS 27.0.1
- MLX: 0.32.4 (pip)
- Apple M3 Ultra
Impact seen: an inference server whose worker threads and main thread share a model's compiled layer functions. After a recompile (new cache format) or loading a new model, a thread that had called the old functions ran their traces with the old weights. This showed up as rare wrong tokens in tests. The workaround is one compiled function per calling thread.
Activity
KavinP21 commentedon Nov 22, 2026
Hey, I reproduced the bug on my Mac. It looks like the compiled function only remembers the last thread's cache. I have a fix for this and will open a PR shortly.