diff --git a/fork.yaml b/fork.yaml index 376a8bc9db..61152f06a8 100644 --- a/fork.yaml +++ b/fork.yaml @@ -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 diff --git a/python/src/transforms.cpp b/python/src/transforms.cpp index 223e232e29..0397ca0447 100644 --- a/python/src/transforms.cpp +++ b/python/src/transforms.cpp @@ -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. @@ -452,14 +451,11 @@ struct PyCompiledFun { fun_id(reinterpret_cast(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 inputs; @@ -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(); diff --git a/python/tests/test_compile.py b/python/tests/test_compile.py index 7436e58cd2..12daa0347b 100644 --- a/python/tests/test_compile.py +++ b/python/tests/test_compile.py @@ -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()