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
15 changes: 15 additions & 0 deletions fork.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,21 @@ def:
globs:
- "mlx/compile.cpp"
- "tests/compile_tests.cpp"
- title: "Freed Python compiled functions leave every thread cache"
description: |
The Python binding keys the traces of `mx.compile(fun)` by the address of `fun`. Upstream,
`PyCompiledFun` keeps the cache of the thread that called it last, and its destructor
erases the key only from that cache. Each call records its trace in the cache of the
calling thread, so a trace from another thread stayed after the free. The trace kept its
arrays alive, and a later compile of a callable at the same address replayed it without a
new trace. The destructor now erases the key from every live thread cache through the
registry above, before it releases `fun`, and `PyCompiledFun` no longer keeps a cache.
The test `test_compile_free_erases_every_thread_cache` calls a compiled function on two
threads, frees it on the thread that called it last, and compiles the same callable
again on the other thread. It expects a new trace there. (PR #44)
globs:
- "python/src/transforms.cpp"
- "python/tests/test_compile.py"
- title: "Integer floor_divide tests"
description: |
The fork keeps its regression tests for integer `floor_divide` from PR #32. Upstream
Expand Down
15 changes: 9 additions & 6 deletions python/src/transforms.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -416,7 +416,6 @@ struct PyCompiledFun {
nb::object captured_inputs;
nb::object captured_outputs;
bool shapeless;
mx::detail::CompileCacheWeakPtr cache;

// Data to attach to the compiled function that contains the python output
// structure and the number of arrays in said structure.
Expand Down Expand Up @@ -452,14 +451,11 @@ struct PyCompiledFun {
fun_id(reinterpret_cast<std::uintptr_t>(fun.ptr())),
captured_inputs(std::move(other.captured_inputs)),
captured_outputs(std::move(other.captured_outputs)),
shapeless(other.shapeless),
cache(other.cache) {
shapeless(other.shapeless) {
other.fun_id = 0;
};

nb::object call_impl(const nb::args& args, const nb::kwargs& kwargs) {
cache = mx::detail::compile_cache();

// Flat array inputs
std::vector<mx::array> inputs;

Expand Down Expand Up @@ -593,7 +589,14 @@ struct PyCompiledFun {
~PyCompiledFun() {
nb::gil_scoped_acquire gil;

mx::detail::compile_erase(cache, fun_id);
// The compiled function can be called on any thread, and each call
// records its trace in the cache of the calling thread. Erase the key from
// every live thread cache, and do it before fun is released so that no
// new callable can get this address while a trace for it is still cached.
// A moved-from object has fun_id 0 and no traces.
if (fun_id != 0) {
mx::detail::compile_erase(fun_id);
}
fun.reset();
captured_inputs.reset();
captured_outputs.reset();
Expand Down
60 changes: 60 additions & 0 deletions python/tests/test_compile.py
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,66 @@ def worker():
raise errors[0]
self.assertEqual(len(traces), 2)

def test_compile_free_erases_every_thread_cache(self):
# Each call of a compiled function records its trace in the cache of
# the calling thread. When the function is freed, its entry must go
# from every thread cache, not only from the cache of the thread that
# called it last. Otherwise a later compile of the same callable (so
# the same id) on another thread gets the old tape and is not traced
# again.
traces = []

def fun(x):
traces.append(1)
return x + 1

holder = {"fn": mx.compile(fun)}
traced = threading.Event()
released = threading.Event()
errors = []
worker_traces = []

def worker():
try:
# Make the default stream of this thread first. A trace is
# cached under the default stream of the calling thread, and
# the first op of a new thread makes that stream. A trace
# recorded before it exists never matches a later call.
mx.default_stream(mx.default_device())
# Record a trace in the cache of this thread. The second call
# must use it, which shows that this thread finds the entry.
mx.eval(holder["fn"](mx.array([1.0])))
mx.eval(holder["fn"](mx.array([1.0])))
worker_traces.append(len(traces))
traced.set()
self.assertTrue(released.wait(10))
# The same callable, so the same id.
fn = mx.compile(fun)
mx.eval(fn(mx.array([1.0])))
except Exception as e:
errors.append(e)
finally:
traced.set()
mx.clear_streams()

# The worker has to outlive the release. On exit it would tear down
# its cache anyway.
thread = threading.Thread(target=worker)
thread.start()
self.assertTrue(traced.wait(10))
# Call the function last on this thread, then free it here.
mx.eval(holder["fn"](mx.array([1.0])))
holder.clear()
gc.collect()
released.set()
thread.join()

if errors:
raise errors[0]
self.assertEqual(worker_traces, [1])
# One trace on each thread, and one more on the worker after the free.
self.assertEqual(len(traces), 3)

def test_compile_grad(self):
def loss_fn(x):
return mx.exp(x).sum()
Expand Down
Loading