Fused Message Passing on Apple Silicon
Replacing gather–multiply–scatter with sparse matrix kernels in Metal, why CSR wins on power-law graphs, and what an 8 GB M1 taught us about atomics
- GNN layers in mlx-graphs used to copy a feature row for every edge and then scatter them back. We fused that into one sparse matrix multiply (SpMM) kernel in mlx-cluster, with a full backward pass.
- Two layouts: COO (one thread per edge, atomics) and CSR (one thread per destination row, no atomics, deterministic).
- On an M4 Pro, CSR runs a 1M-edge layer about 2–8× faster than the old path and uses up to 15× less memory.
- On an M1 with a power-law graph, CSR is up to 93× faster. The reason is that it never needs a floating-point atomic, and on the M1 those get very slow when many threads hit the same “hub” node.
- The same lesson fixed one last slow spot: node degrees are now counted with integer atomics instead of float ones.
1 The problem: one copy per edge
Almost every GNN layer does the same thing. For each node, look at its neighbours, take their features (maybe scaled by an edge weight), and combine them with a sum, mean, max or min. In mlx-graphs this was written in the most direct way possible:
msgs = x[src] # gather: [E, D] — one row per edge
msgs = msgs * w[:, None] # multiply (optional edge weight)
out = scatter_add(msgs, dst) # scatter: [N, D]It’s easy to read, but the middle array has one row for every edge, not every node. A graph with 1M edges and 64 features makes a 256 MB temporary, and autograd keeps a few more of those around for the backward pass. All of it is written to memory and then read back once.
There’s a better way. The three steps together are just a sparse matrix times a dense matrix, out = A @ X, where A is the adjacency matrix. A dedicated kernel can read each neighbour’s row and add it straight into the output, so the [E, D] array never exists.
2 Two ways to store a graph: COO and CSR
A common reference point is PyG’s CUDA implementation (torch_sparse), which works with the COO format. COO and CSR are just two ways to write down the same edges.
COO (coordinate) is two parallel lists, row and col, one entry per edge. It’s what edge_index already is. CSR (compressed sparse row) sorts edges by destination and replaces the row list with a short rowptr array: node i’s neighbours live at col[rowptr[i] : rowptr[i+1]].
col[4:7], so one thread can own that whole row.The format decides how you parallelise the GPU work, and that turned out to be the most important choice in the whole project:
- COO kernel: one thread per edge. Each thread reads
x[src]and adds it intoout[dst]. Many edges share adst, so those adds have to be atomic. - CSR kernel: one thread (group) per destination row. It loops over that row’s neighbours, sums in registers, and writes
out[i]exactly once. No other thread touches that row, so no atomics are needed and the result is the same every run.
3 The kernels, and why we had to write a backward pass
MLX lets an extension define a Primitive: a class with a CPU implementation, a Metal (GPU) implementation, and the derivative rules. We built one SpMM primitive in mlx-cluster that covers both layouts, optional edge weights, and sum/mean/max/min.
Training needs gradients, and MLX can’t differentiate through a hand-written kernel on its own. So we wrote the rules ourselves:
- Gradient for X: if
out = A @ XthendX = Aᵀ @ dOut. That’s another SpMM, just with the edges reversed. - Gradient for edge weights:
dw[e] = dot(dOut[dst], X[src]), one dot product per edge. This is called SDDMM, and it got its own small kernel.
On the mlx-graphs side, a @fused_message_passing decorator lets a layer opt in. When the layer’s message is the standard “neighbour features × optional weight” pattern, propagate() skips gather/scatter and calls the kernel. Anything else (attention softmax, GINE’s edge MLP) falls back to the old path automatically. GCN, SAGE, GIN and SimpleConv are decorated today.
4 What the GPU trace says
Benchmarks tell you how much faster something is. A GPU trace tells you why. We recorded Metal GPU traces in Xcode of the same work on all three paths: GCNConv on powerlaw-1m with 64 features, two training steps (forward and backward), on an Apple M4 Pro. These traces use the final kernels, including the two CSR improvements described in the next sections.
| Old path (gather) | COO kernel | CSR kernel | |
|---|---|---|---|
| GPU time | 28.97 ms | 4.97 ms (5.8× less) | 3.92 ms (7.4× less) |
| GPU memory | 642.86 MiB | 186.64 MiB (3.4× less) | 251.03 MiB (2.6× less) |
| Command buffers | 14 | 2 | 2 |
| Compute encoders | 13 | 1 | 1 |
| Dispatch calls | 32 | 20 | 20 |
powerlaw-1m, D=64).
4.1 Where the old path’s time goes
On the old path, four kernels take 96% of the GPU time: the scatter-add (36.2%), the multiply by edge weights (34.8%) and two gathers (14.7% and 10.3%). These are exactly the kernels that create, scale and sum up the [E, D] per-edge arrays. The layer’s actual matrix multiply (steel_gemm, the linear projection) takes 0.9%.
Each of those kernels does almost no arithmetic: one multiply or one add per number it reads and writes. Xcode’s counters agree. Per encoder, instruction throughput utilisation stays between about 3% and 23%, so the compute units spend most of their time waiting for data. The work is limited by memory traffic, so the way to speed it up is to move fewer bytes, not to compute faster. That’s exactly what fusing does.
Two more details stand out:
- 13 encoders down to 1. Because the old path moves hundreds of megabytes per step, MLX splits its work into many separate batches, with idle gaps in between. The fused paths fit both training steps into a single encoder.
- CSR uses more memory than COO (251 vs. 187 MiB). CSR keeps extra index arrays: the sorted copy of the graph, its transpose for the backward pass, and the long-row chunk tables. It still uses 2.6× less memory than the old path.
4.2 A profiling lesson
Our first CSR traces were misleading. They showed only the COO kernel, and CSR looked no better than COO. Two things combined. Our capture script asked MLX for the gradient alone (mx.grad), and for that loss MLX could skip the forward pass entirely, so the forward CSR kernel never ran. And at that point, CSR’s backward pass still used the COO kernel. Switching the capture to mx.value_and_grad, which forces both passes, fixed the first problem. The next two sections fix CSR itself.
5 The power-law surprise
Real graphs aren’t uniform. Citation networks, social graphs and the web follow a power law: most nodes have a handful of neighbours, and a few “hubs” have an enormous number. Our synthetic powerlaw-1m benchmark graph has exactly that shape: its busiest node has about 134,000 incoming edges.
The naive CSR kernel assigns one thread per row. A GPU kernel only finishes when its slowest thread finishes. So while almost every thread finishes after a few neighbours, the hub’s thread walks through its 134,000 neighbours one by one, and the whole kernel waits for it.
5.1 The fix: split long rows
When the CSR structure is built (once, then cached), we find every row with more than 256 neighbours and cut it into chunks of 2048 edges. Short rows still use the simple one-thread-per-row kernel. Long rows go through two extra kernels: a partial kernel where each chunk sums its piece in parallel, and a reduce kernel that adds the chunk results in a fixed order. For the biggest hub in powerlaw-1m, that’s about 66 chunks working at once instead of one thread doing all 134,000 edges.
There’s an accuracy bonus too. Adding 134,000 floats one after another builds up rounding error, because each new value is added to an ever-larger running total. Summing 2048 at a time and then combining the totals keeps those errors smaller.
6 A deterministic backward pass
The backward pass needs Aᵀ @ dOut. At first we ran it with the COO kernel and swapped indices, which put the atomics back. So we also build a transposed CSR (edges grouped by source instead of destination), with its own long-row chunks. Now the backward is also one-thread-per-row, atomic-free and gives the same answer every run.
The API stays flexible: you can still call the COO path at any time (no preprocessing needed), and CSR is an option that pays a one-time build cost which the decorator caches per graph.
7 Max and min without storing an argmax
Sum is easy. Max and min needed two tricks.
Forward (COO): Metal has no atomic float max. It does have atomic integer max. We use a standard bit trick that maps each float to an unsigned integer whose ordering matches the float ordering (flip the sign bit for positives, flip all the bits for negatives). Then atomic_fetch_max on the integers gives the float max, and a small decode kernel turns them back into floats.
Backward: the gradient flows only to the neighbour that “won” the max. Instead of saving an argmax array during the forward pass, the backward kernel recomputes it: for each edge, check whether x[src] == out[dst]. Ties get the full gradient, which matches what MLX’s own scatter-max does, and empty rows output 0.
That integer-atomic detail matters for the M1 story below.
8 Results on an M4 Pro
Every number below is forward + backward (value_and_grad), median time, on the synthetic power-law graph with 1M edges and 256 features. GAT is included as a control: its attention softmax isn’t fusable, so all three modes should match, and they do.
powerlaw-1m, D=256. Lower is better.Two things stand out. First, CSR beats COO even on the M4 Pro, by about 1.5–2× on the plain aggregations. Second, the memory savings are large and they hold for COO and CSR alike, because both remove the [E, D] arrays. On tiny graphs like Cora, the difference is just a fraction of a millisecond either way, since per-call overhead dominates there.
9 Results on an 8 GB M1, and why CSR loves power laws
Then we ran the same benchmark on an M1 MacBook with 8 GB, and the gap got much bigger.
powerlaw-1m D=16powerlaw-1m, D=16, forward + backward, measured before the integer degree fix described in the last section. Note how COO sum barely beats the old path while COO max (integer atomics) is already fast.9.1 So why is CSR so good on power-law graphs?
Take the busiest node in powerlaw-1m, with about 134,000 incoming edges. With 16 features, that means about 2.1 million additions that all land in the same 16 output slots.
Here is what each path does with that hub:
- Old path (gather +
scatter_add): MLX’s scatter uses a float atomic add per element. All of those adds target the same 16 addresses, so they queue up. On top of that it moves the full[E, D]array through memory. - COO kernel: it removes the big array, but it still issues one float atomic per edge per feature into the hub’s row. The queue is just as long. That’s why COO sum on the M1 is about 72 ms against 77 ms for the old path: it fixed the memory traffic but not the bottleneck.
- CSR kernel: no atomics at all. The hub’s 134,000 edges are split into about 66 chunks of 2048. Each chunk sums into registers that no other thread can see, and a tiny reduce kernel adds the 66 partial results. There is no queue: 2.3 ms.
On the M1, COO max takes 5 ms while COO sum takes 72 ms on the same graph. Both use one atomic per edge into the same hub. The only difference is that max uses integer atomics (thanks to the bit trick) and sum uses float atomics. Contended integer atomics are fine on the M1. Contended float atomics are the problem.
9.2 Why the M4 Pro hides this
Newer Apple GPUs handle contended float atomics much better and have more memory bandwidth, so on the M4 Pro COO only trails CSR by about 2×. The M1 shows the worst case, and its 8 GB of unified memory makes the old path’s big temporary arrays hurt more too. On uniform graphs (no hubs) the M1 gap shrinks back to roughly 2–5×. So the power-law gap is mostly about contention, not raw speed.
Mean aggregation was the most extreme case (93×) because both the old path and COO computed the node degree with another float scatter, which also piled onto the hub. CSR gets degrees for free: rowptr[i+1] - rowptr[i]. That observation led to the last fix in this release.
10 Accuracy and training
Relative error against the old path stays around 10⁻⁷ to 10⁻⁵ in float32, and max/min match exactly. To make the tests fair, we compare against a float64 reference with a tolerance that scales with the magnitude of the result. A hub that sums 134,000 values will always carry some rounding error, in any implementation. The benchmark folder also has train_compare.py, which trains the same model with both paths so you can compare loss curves side by side.
11 Counting degrees with integers
The M1 results pointed at one more float-atomic hotspot outside our kernels: counting each node’s neighbours. Mean aggregation divides a sum by that count, and GCN normalisation uses it too. Both counted by scatter-adding 1.0 per edge, so on powerlaw-1m about 134,000 float atomic adds queued on the hub’s single counter. That’s why COO mean sat at about 253 ms on the M1 (against 72 ms for COO sum), and why GCNConv was still about 180 ms even with CSR.
The fix, in this release, is to count with an int32 scatter and convert to float32 afterwards:
deg = mx.zeros((num_nodes,), dtype=mx.int32).at[index].add(1).astype(mx.float32)- In mlx-cluster,
spmm_coo(reduce="mean")counts this way.spmm_csrdoesn’t need it, because it reads degrees fromrowptr. - In mlx-graphs,
degree()counts this way whenever no edge weights are given. That speeds up every caller: mean aggregation on the gather-scatter path,scatter_max/scatter_min(which use it to find nodes with no neighbours) and unweightedGCNConv. - Nothing else changes. Counts are whole numbers, so the int32 result is exact, and the output is still float32. int32 rather than int64, because MLX’s GPU scatter doesn’t support int64. Converting back to float is one pass over the nodes with no contention, so it costs a fraction of a millisecond.
- Weighted degrees (a sum of edge weights) still use float atomics, since the weights aren’t whole numbers.
Numbers come from benchmarks/spmm/bench_fused_mp.py in mlx-graphs, run with MLX 0.32.4 on an Apple M4 Pro and an Apple M1 (8 GB). Kernels live in mlx_cluster/sparse/. Documentation: fused message passing in mlx-graphs.