In MLX to get the results of computation, the main thread has to wait for results from GPU threads with blocking APIs like mx::eval and mx::synchronize.
This causes a few problems:
- For scripting languages like Node.js, all operations are supposed to be non-blocking, when calling blocking APIs like
mx.eval, the whole process "freezes" and you can not even terminate it with Ctrl-C.
- It is impractical to integrate MLX into a GUI app: you are not supposed to wait for an event synchronously in the GUI thread, doing so results in UI lags.
- It is very hard to stop a generation: when the main thread is blocked at
mx.eval, it would be challenge to tell the script to stop the generation after mx.eval is done when the script itself also runs in the main thread.
So it would be necessary to be able to wait for evaluation asynchronously, for example await mx.asyncEval(array) in Node.js. To be able to do so we would need a few changes in MLX:
- Make the C++
mx::async_eval API return the synchronizer event.
- Make the
Event movable.
- Make it safe to wait for the synchronizer event in any thread. (I believe it is already so but I want confirmation from MLX team.)
Implementing the asynchronously waitable async_eval API in language bindings would be:
- Return a
Promise in the API.
- Wait for the synchronizer event in a new thread.
- Resolve the
Promise in the main thread after the event is signaled.
In MLX to get the results of computation, the main thread has to wait for results from GPU threads with blocking APIs like
mx::evalandmx::synchronize.This causes a few problems:
mx.eval, the whole process "freezes" and you can not even terminate it with Ctrl-C.mx.eval, it would be challenge to tell the script to stop the generation aftermx.evalis done when the script itself also runs in the main thread.So it would be necessary to be able to wait for evaluation asynchronously, for example
await mx.asyncEval(array)in Node.js. To be able to do so we would need a few changes in MLX:mx::async_evalAPI return the synchronizer event.Eventmovable.Implementing the asynchronously waitable
async_evalAPI in language bindings would be:Promisein the API.Promisein the main thread after the event is signaled.