|
| 1 | +# Shared Metal command queue (PyTorch MPS) |
| 2 | + |
| 3 | +On Apple Silicon, Quadrants and PyTorch MPS both dispatch GPU work via Metal. By default each framework creates its own `MTLCommandQueue`, which means there is no GPU-level ordering between them. Every zero-copy interop point therefore requires explicit CPU-side synchronisation (`qd.sync()` and `torch.mps.synchronize()`) to guarantee data visibility. |
| 4 | + |
| 5 | +The `external_metal_command_queue` option lets you pass PyTorch's command queue to Quadrants so that both frameworks share a single queue. Metal processes command buffers in commit order within a queue, so GPU-side ordering is automatic and the per-interop sync overhead is eliminated. |
| 6 | + |
| 7 | +## Quick start |
| 8 | + |
| 9 | +```python |
| 10 | +import quadrants as qd |
| 11 | + |
| 12 | +queue_ptr = get_mps_command_queue() # see below |
| 13 | +qd.init(arch=qd.metal, external_metal_command_queue=queue_ptr) |
| 14 | +``` |
| 15 | + |
| 16 | +Once initialised this way: |
| 17 | + |
| 18 | +- `to_torch(copy=False)` no longer calls `qd.sync()` internally. |
| 19 | +- `to_torch(copy=True)` no longer calls `torch.mps.synchronize()` after the copy. |
| 20 | +- GPU work submitted by Quadrants and by PyTorch executes in the order it was committed — no manual sync needed between the two. |
| 21 | + |
| 22 | +You can still call `qd.sync()` when you need to read results back to the CPU (e.g. `to_numpy()`); what changes is that you no longer need *both* `qd.sync()` and `torch.mps.synchronize()` at every framework boundary. |
| 23 | + |
| 24 | +## Extracting PyTorch's MTLCommandQueue |
| 25 | + |
| 26 | +PyTorch does not expose its MPS command queue through a public Python API. The following helper extracts it at runtime using `ctypes` and the Objective-C runtime, with no build-time PyTorch dependency: |
| 27 | + |
| 28 | +```python |
| 29 | +import ctypes |
| 30 | +import os |
| 31 | +import torch |
| 32 | + |
| 33 | + |
| 34 | +def get_mps_command_queue() -> int: |
| 35 | + """Return PyTorch MPS's MTLCommandQueue* as a Python int.""" |
| 36 | + # Ensure MPS is initialised |
| 37 | + torch.zeros(1, device="mps") |
| 38 | + |
| 39 | + torch_lib = os.path.join( |
| 40 | + os.path.dirname(torch.__file__), "lib", "libtorch_cpu.dylib" |
| 41 | + ) |
| 42 | + handle = ctypes.CDLL(torch_lib)._handle |
| 43 | + |
| 44 | + libdl = ctypes.CDLL(None) |
| 45 | + dlsym = libdl.dlsym |
| 46 | + dlsym.restype = ctypes.c_void_p |
| 47 | + dlsym.argtypes = [ctypes.c_void_p, ctypes.c_char_p] |
| 48 | + |
| 49 | + # at::mps::getDefaultMPSStream() -> MPSStream* |
| 50 | + func_addr = dlsym(handle, b"_ZN2at3mps19getDefaultMPSStreamEv") |
| 51 | + assert func_addr, "Cannot find getDefaultMPSStream — check PyTorch version" |
| 52 | + stream_ptr = ctypes.CFUNCTYPE(ctypes.c_void_p)(func_addr)() |
| 53 | + |
| 54 | + # MPSStream::commandBuffer() -> id<MTLCommandBuffer> |
| 55 | + cb_addr = dlsym(handle, b"_ZN2at3mps9MPSStream13commandBufferEv") |
| 56 | + assert cb_addr, "Cannot find MPSStream::commandBuffer" |
| 57 | + cb_ptr = ctypes.CFUNCTYPE(ctypes.c_void_p, ctypes.c_void_p)(cb_addr)( |
| 58 | + stream_ptr |
| 59 | + ) |
| 60 | + |
| 61 | + # [commandBuffer commandQueue] via ObjC runtime |
| 62 | + objc = ctypes.CDLL("/usr/lib/libobjc.A.dylib") |
| 63 | + sel_reg = objc.sel_registerName |
| 64 | + sel_reg.restype = ctypes.c_void_p |
| 65 | + sel_reg.argtypes = [ctypes.c_char_p] |
| 66 | + msg_send = objc.objc_msgSend |
| 67 | + msg_send.restype = ctypes.c_void_p |
| 68 | + msg_send.argtypes = [ctypes.c_void_p, ctypes.c_void_p] |
| 69 | + |
| 70 | + queue_ptr = msg_send(cb_ptr, sel_reg(b"commandQueue")) |
| 71 | + assert queue_ptr, "Failed to extract MTLCommandQueue" |
| 72 | + return queue_ptr |
| 73 | +``` |
| 74 | + |
| 75 | +The C++ symbol `_ZN2at3mps19getDefaultMPSStreamEv` has been stable since PyTorch 1.13. |
| 76 | + |
| 77 | +## Init ordering |
| 78 | + |
| 79 | +PyTorch MPS must be initialised **before** `qd.init()` so that the command queue exists when Quadrants starts: |
| 80 | + |
| 81 | +```python |
| 82 | +import torch |
| 83 | +torch.zeros(1, device="mps") # trigger MPS init |
| 84 | + |
| 85 | +import quadrants as qd |
| 86 | +queue_ptr = get_mps_command_queue() |
| 87 | +qd.init(arch=qd.metal, external_metal_command_queue=queue_ptr) |
| 88 | +``` |
| 89 | + |
| 90 | +## What changes with a shared queue |
| 91 | + |
| 92 | +| Scenario | Separate queues (default) | Shared queue | |
| 93 | +|----------|--------------------------|--------------| |
| 94 | +| `f.to_torch(copy=False)` | `qd.sync()` called internally | no sync needed | |
| 95 | +| `f.to_torch(copy=True)` | `qd.sync()` + `torch.mps.synchronize()` | no sync needed | |
| 96 | +| Quadrants kernel after torch write | manual `torch.mps.synchronize()` required | automatic (same queue) | |
| 97 | +| `f.to_numpy()` | `qd.sync()` (always needed for CPU readback) | `qd.sync()` (still needed) | |
| 98 | + |
| 99 | +## Lifetime and ownership |
| 100 | + |
| 101 | +The caller (your application) owns the command queue. Quadrants retains it for the duration of the runtime and does **not** release it on `qd.reset()`. You must keep PyTorch (and its MPS backend) alive for as long as the Quadrants runtime is active. |
| 102 | + |
| 103 | +## Fallback |
| 104 | + |
| 105 | +If extracting the queue fails (e.g. on an older PyTorch version or a non-Apple system), fall back to the default separate-queue path: |
| 106 | + |
| 107 | +```python |
| 108 | +try: |
| 109 | + queue_ptr = get_mps_command_queue() |
| 110 | +except (AssertionError, OSError): |
| 111 | + queue_ptr = 0 # 0 means "create a new queue" (the default) |
| 112 | + |
| 113 | +qd.init(arch=qd.metal, external_metal_command_queue=queue_ptr) |
| 114 | +``` |
0 commit comments