Custom GPU kernels¶
This guide is for you if you wrote a layer and one of its operations on edges is slow. It shows how to write that operation as a Metal kernel with mx.fast.metal_kernel, give it gradients with mx.custom_function, and plug it into a MessagePassing layer with a fallback. The worked example is a real fused graph operation; all the code on this page comes from docs/snippets/edge_dot_kernel.py, which runs its checks and its benchmark with python docs/snippets/edge_dot_kernel.py. The test suite runs the same checks (tests/docs/test_edge_dot_kernel.py).
The API used here is the one of MLX 0.32. mlx-graphs ships two such kernels, which are longer versions of the same recipe: gatv2_edge_scores.py (GATv2's attention logits) and csr_softmax_spmm.py (softmax over each node's edges fused with the weighted sum).
When a custom kernel is worth it¶
A message passing layer written with MLX operations gathers the features of both ends of every edge, computes one message per edge, then scatters the messages to their destinations:
- the gathers build arrays of shape
[num_edges, features], written to and read back from memory, often several of them; on a graph with 2 million edges and 64 features, each one is 512 MB in float32; - the scatter adds the messages of all edges into the rows of their destinations, with atomic additions on the GPU, which collide on high-degree nodes;
- the backward pass does the same in reverse.
Two cases are already covered without a kernel of your own:
- The message is a weighted sum of neighbor features (
edge_weight * x_j, mean, sum): decorate the layer with@fused_message_passing, which aggregates with one sparse-dense matrix product and never builds the message array. See Writing your own layers. - The attention of GAT, GATv2 and TransformerConv: the built-in layers already use the two kernels above.
Write a kernel when the expensive part is something else, typically a per-edge quantity computed from the features of both ends (a score, a distance, a gate) that the layer needs before its weighted sum. The kernel computes it directly from the node features, so the [num_edges, features] intermediates never exist.
The example: a per-edge dot product¶
Dot-product attention (TransformerConv, graph transformers) scores every edge (src, dst) with
The reference implementation is two gathers and a reduction:
def edge_dot_reference(q: mx.array, k: mx.array, edge_index: mx.array) -> mx.array:
"""score[e] = <q[dst[e]], k[src[e]]>, with MLX operations."""
src, dst = edge_index[0], edge_index[1]
return (q[dst] * k[src]).sum(axis=-1) # two [num_edges, channels] gathers
It is correct on any device and differentiable by MLX, so it serves as the fallback and as the ground truth for the tests.
The Metal kernels¶
mx.fast.metal_kernel takes the body of a Metal function; MLX generates the signature from input_names and output_names, and gives each input x a x_shape array (and x_strides, x_ndim when the body uses them). Inside the body, thread_position_in_grid, thread_index_in_simdgroup and the other Metal attributes are available.
The forward kernel gives each edge one SIMD group of 32 threads: each thread multiplies a strided slice of the channels, and simd_sum adds the 32 partial sums. The backward kernel computes grad_q[dst] += g * k[src] and grad_k[src] += g * q[dst] for every edge. Several edges share a node, so it adds with atomic_fetch_add_explicit, which requires atomic_outputs=True:
SIMD_WIDTH = 32 # threads of an Apple GPU SIMD group
THREADGROUP = (256, 1, 1)
FORWARD = """
// One SIMD group per edge: each lane sums a strided slice of the channels.
const uint edge = thread_position_in_grid.x / 32;
const uint lane = thread_index_in_simdgroup;
const uint num_edges = edge_index_shape[1];
const uint channels = q_shape[1];
const ulong src = edge_index[edge];
const ulong dst = edge_index[num_edges + edge];
float acc = 0.0f;
for (uint c = lane; c < channels; c += 32) {
acc += q[dst * channels + c] * k[src * channels + c];
}
acc = simd_sum(acc); // reduce the 32 partial sums
if (lane == 0) {
score[edge] = acc;
}
"""
BACKWARD = """
// d score / d q[dst] = k[src] and d score / d k[src] = q[dst], scaled by
// the incoming gradient. Several edges share a node: add atomically.
const uint edge = thread_position_in_grid.x / 32;
const uint lane = thread_index_in_simdgroup;
const uint num_edges = edge_index_shape[1];
const uint channels = q_shape[1];
const ulong src = edge_index[edge];
const ulong dst = edge_index[num_edges + edge];
const float g = cotangent[edge];
for (uint c = lane; c < channels; c += 32) {
atomic_fetch_add_explicit(
&grad_q[dst * channels + c], g * k[src * channels + c],
memory_order_relaxed);
atomic_fetch_add_explicit(
&grad_k[src * channels + c], g * q[dst * channels + c],
memory_order_relaxed);
}
"""
@lru_cache(maxsize=1) # build (and compile) each kernel once
def _kernels():
forward = mx.fast.metal_kernel(
name="edge_dot",
input_names=["q", "k", "edge_index"],
output_names=["score"],
source=FORWARD,
ensure_row_contiguous=True,
)
backward = mx.fast.metal_kernel(
name="edge_dot_backward",
input_names=["q", "k", "edge_index", "cotangent"],
output_names=["grad_q", "grad_k"],
source=BACKWARD,
ensure_row_contiguous=True,
atomic_outputs=True, # outputs are `device atomic<float>*`
)
return forward, backward
metal_kernel returns a callable. Every time you make one, MLX creates a new Metal library, which it may compile: build each kernel once (lru_cache here) and call it many times.
Gradients with mx.custom_function¶
MLX cannot differentiate through a Metal kernel. Wrap the forward call in mx.custom_function and define its vector-Jacobian product with the backward kernel. The VJP receives the inputs (primals), the cotangent of the output and the output itself, and returns one gradient per input:
@mx.custom_function
def _edge_dot_metal(q, k, edge_index):
forward, _ = _kernels()
num_edges = edge_index.shape[1]
return forward(
inputs=[q, k, edge_index],
grid=(num_edges * SIMD_WIDTH, 1, 1), # total threads, not threadgroups
threadgroup=THREADGROUP,
output_shapes=[(num_edges,)],
output_dtypes=[mx.float32],
)[0]
@_edge_dot_metal.vjp
def _edge_dot_metal_vjp(primals, cotangent, output):
q, k, edge_index = primals
_, backward = _kernels()
num_edges = edge_index.shape[1]
grad_q, grad_k = backward(
inputs=[q, k, edge_index, cotangent],
grid=(num_edges * SIMD_WIDTH, 1, 1),
threadgroup=THREADGROUP,
output_shapes=[q.shape, k.shape],
output_dtypes=[mx.float32, mx.float32],
init_value=0, # the atomic adds accumulate into zeros
)
# No gradient for the integer edge index.
return grad_q, grad_k, mx.zeros_like(edge_index)
Things to know about the kernel call:
gridis the total number of threads along each axis (Metal'sdispatchThreads), not the number of threadgroups: herenum_edges * 32.output_shapesandoutput_dtypesare required; outputs are not initialized unless you passinit_value, which the backward kernel needs because it accumulates.templatepasses compile-time constants ([("CHANNELS", 64)]); each new value compiles a new specialization. The example reads the sizes fromq_shapeinstead.
The gradient of the backward kernel itself (second-order gradients) is not defined here; the repository's GATv2 kernel shows how to delegate it to the reference with mx.vjp.
Plugging it into a layer¶
Dispatch to the kernel only when it applies, and use the reference otherwise: on the CPU device, without Metal, for empty graphs, other dtypes or sizes the grid cannot hold:
def edge_dot(q: mx.array, k: mx.array, edge_index: mx.array) -> mx.array:
"""The Metal kernel when it applies, the MLX reference otherwise."""
if (
edge_index.ndim == 2
and 0 < edge_index.shape[1] <= (2**31 - 1) // SIMD_WIDTH
and edge_index.dtype == mx.int32
and q.dtype == k.dtype == mx.float32
and q.ndim == k.ndim == 2
and q.shape[1] == k.shape[1]
and mx.default_device().type == mx.gpu
and mx.metal.is_available()
):
return _edge_dot_metal(q, k, edge_index)
return edge_dot_reference(q, k, edge_index)
A layer then calls edge_dot like any MLX operation, normalizes the scores over each node's incoming edges with softmax, and lets propagate do the weighted sum:
class DotAttentionConv(MessagePassing):
"""Single-head dot-product graph attention, scored with `edge_dot`."""
def __init__(self, in_dim: int, out_dim: int):
super().__init__(aggr="add")
self.query = Linear(in_dim, out_dim)
self.key = Linear(in_dim, out_dim)
self.value = Linear(in_dim, out_dim)
self.scale = 1 / math.sqrt(out_dim)
def __call__(self, edge_index: mx.array, node_features: mx.array) -> mx.array:
q = self.query(node_features)
k = self.key(node_features)
v = self.value(node_features)
scores = edge_dot(q, k, edge_index) * self.scale
# softmax over the incoming edges of each destination node
weights = softmax(scores, edge_index[1], num_nodes=node_features.shape[0])
# the default message is edge_weights * source features
return self.propagate(
edge_index, v, message_kwargs={"edge_weights": weights[:, None]}
)
Testing¶
Compare values and gradients with the reference, with a random cotangent (a plain .sum() would hide errors that cancel out), on random graphs of a few sizes, on nodes without edges and on an empty graph:
def random_graph(num_nodes, num_edges, channels, seed=0):
mx.random.seed(seed)
edge_index = mx.random.randint(0, num_nodes, (2, num_edges)).astype(mx.int32)
q = mx.random.normal((num_nodes, channels))
k = mx.random.normal((num_nodes, channels))
return q, k, edge_index
def check(q, k, edge_index, atol=1e-4, rtol=1e-4):
"""Values and gradients of the kernel against the reference."""
weights = mx.random.normal((edge_index.shape[1],)) # a non-trivial cotangent
def loss(fn):
return lambda q, k: (fn(q, k, edge_index) * weights).sum()
value, grads = mx.value_and_grad(loss(edge_dot), argnums=(0, 1))(q, k)
ref_value, ref_grads = mx.value_and_grad(loss(edge_dot_reference), argnums=(0, 1))(
q, k
)
assert mx.allclose(
edge_dot(q, k, edge_index),
edge_dot_reference(q, k, edge_index),
atol=atol,
rtol=rtol,
)
assert mx.allclose(value, ref_value, atol=atol, rtol=rtol)
for grad, ref_grad in zip(grads, ref_grads):
assert mx.allclose(grad, ref_grad, atol=atol, rtol=rtol)
def run_tests():
for num_nodes, num_edges, channels in [
(50, 300, 16),
(1000, 20000, 64),
(7, 5, 100),
]:
check(*random_graph(num_nodes, num_edges, channels))
# isolated nodes: edges only between the first 10 of 100 nodes
q, k, _ = random_graph(100, 1, 32)
edge_index = mx.random.randint(0, 10, (2, 500)).astype(mx.int32)
check(q, k, edge_index)
# an empty graph falls back to the reference, which returns no scores
q, k, _ = random_graph(10, 1, 8)
empty = mx.zeros((2, 0), dtype=mx.int32)
assert edge_dot(q, k, empty).shape == (0,)
# the layer runs and is differentiable
layer = DotAttentionConv(16, 32)
x = mx.random.normal((50, 16))
edge_index = mx.random.randint(0, 50, (2, 400)).astype(mx.int32)
out = layer(edge_index, x)
grads = nn.value_and_grad(layer, lambda m: m(edge_index, x).sum())(layer)[1]
mx.eval(out, grads)
assert out.shape == (50, 32)
print("kernel matches the reference: values and gradients (atol=rtol=1e-4)")
The tolerance is 1e-4: the kernel adds the channels in a different order than MLX, and the atomic additions of the backward kernel run in an order that changes from run to run, so results differ in the last bits and are not bitwise deterministic.
Benchmarking¶
MLX evaluates lazily: time mx.eval(...), after a few warm-up calls that compile the kernel:
def timeit(fn, *args, warmup=5, iters=20):
for _ in range(warmup): # compiles the kernel, warms the caches
mx.eval(fn(*args))
start = time.perf_counter()
for _ in range(iters):
mx.eval(fn(*args)) # MLX is lazy: evaluate to time the work
return (time.perf_counter() - start) / iters * 1e3 # ms
def benchmark(num_nodes=100_000, num_edges=2_000_000, channels=64):
q, k, edge_index = random_graph(num_nodes, num_edges, channels)
mx.eval(q, k, edge_index)
def forward_backward(fn):
grad = mx.grad(lambda q, k: fn(q, k, edge_index).sum(), argnums=(0, 1))
return lambda q, k: grad(q, k)
print(f"{num_nodes:,} nodes, {num_edges:,} edges, {channels} channels")
for name, fn in [
("forward", lambda f: lambda q, k: f(q, k, edge_index)),
("forward + backward", forward_backward),
]:
kernel = timeit(fn(edge_dot), q, k)
reference = timeit(fn(edge_dot_reference), q, k)
print(
f" {name:<20} kernel {kernel:6.2f} ms reference {reference:6.2f} ms"
f" speedup {reference / kernel:4.1f}x"
)
On an Apple M5 Pro (MLX 0.32.4), python docs/snippets/edge_dot_kernel.py prints:
MLX 0.32.4, Metal available: True, Apple M5 Pro
kernel matches the reference: values and gradients (atol=rtol=1e-4)
100,000 nodes, 2,000,000 edges, 64 channels
forward kernel 2.72 ms reference 15.46 ms speedup 5.7x
forward + backward kernel 10.39 ms reference 24.79 ms speedup 2.4x
10,000 nodes, 100,000 edges, 64 channels
forward kernel 0.26 ms reference 0.86 ms speedup 3.3x
forward + backward kernel 0.41 ms reference 1.20 ms speedup 2.9x
Times vary between runs: over our runs on this machine, the forward speedup on 2 million edges was 5.5x to 5.7x and the forward + backward one 2.4x to 2.8x.
How to read it:
- The forward pass gains the most: the reference writes and reads two
[2M, 64]arrays (1 GB), the kernel only reads the node features. - With the backward pass the gain is smaller: both versions scatter-add into the node gradients, and the kernel's atomic additions collide on the same rows as the reference's.
- On small graphs, launch and Python overhead dominate both versions; measure at the sizes you train on.
Pitfalls¶
- Index dtypes: the kernel reads
int32indices. Check the dtype in the dispatch (or cast once outside the training loop); a Metal kernel reinterprets the bytes it is given, soint64indices would be read as garbage. Compute offsets inulong(src * channelsoverflows 32 bits past 2^31 elements). - Sorted or CSR layouts: kernels that walk the edges of each node (like
csr_softmax_spmm) need the edges sorted by destination with a row pointer; convert once and cache it, as the fused message passing does. - Threadgroup sizes: a threadgroup holds at most 1024 threads; keep it a multiple of the SIMD width (32), and make sure every lane of a SIMD group reaches
simd_sum(no earlyreturnfor part of a group). - Atomics: only for 32-bit types; they make floating-point sums non-deterministic. Reduce in registers or threadgroup memory first when many threads write the same address (the GATv2 kernel reduces each threadgroup's share before writing).
- Contiguity: with
ensure_row_contiguous=True(the default) MLX copies strided inputs before the call, and the body can index them as flat row-major arrays. WithFalse, usex_stridesandelem_to_loc. - Caching: build the kernel objects once (
lru_cache) instead of in every call; withtemplate, each new value is a new specialization to compile, so keep their number small. - Importable without a GPU: documentation tools and some tests import modules with
mlxreplaced by a mock. Build kernels lazily, inside functions, and avoid annotations evaluated at import time on MLX types, such asmx.array | None: that one broke the import ofcsr_softmax_spmmunder a mock until it was writtenOptional[mx.array](#214).
Heavier kernels¶
mx.fast.metal_kernel suits element-wise and per-edge work written in one Metal function. For kernels that need several passes, shared buffers or their own memory planning (sparse matrix products, random walks, graph partitioning), write an MLX C++ extension: mlx-cluster, which provides the SpMM of the fused message passing and the random walks of Node2Vec and MetaPath2Vec, is one, built on MLX's custom extensions.