Skip to content

Latest release: v0.6.1

Graph neural networks,
fast on Apple silicon

MLX-graphs is a library for Graph Neural Networks (GNNs) built upon Apple's MLX, with the API of PyTorch Geometric.

pip install mlx-graphs

5.6×faster than PyTorch Geometric on the GPU (MPS)
5.8×faster than PyTorch Geometric on the CPU
58×faster at best, over 35 training benchmarks
31×faster at best for one GNN layer than PyG on the Mac's GPU (M5 Pro)

Faster than PyG, at the same accuracy

On a Mac, MLX-graphs trains GNNs 5.6× faster than PyTorch Geometric on the GPU (MPS) and 5.8× faster than PyTorch Geometric on the CPU, and the models reach the same accuracy (medians over 35 training benchmarks, up to 58× faster). See the benchmarks.

Time of PyG on MPS and on CPU relative to mlx-graphs for one layer, node classification and graph classification, and the test accuracy of each framework Time of PyG on MPS and on CPU relative to mlx-graphs for one layer, node classification and graph classification, and the test accuracy of each framework

Features

  • Fast GNN training and inference on Apple Silicon


    MLX-graphs has been designed to run fast on Apple Silicon chips. All GNN operations fully leverage the GPU and CPU hardware of Macs thanks to the efficient low-level primitives available within the MLX core library, and message passing aggregates neighbours with fused sparse kernels. On an M5 Pro, one GNN layer runs up to 31× faster than PyTorch Geometric on the Mac's GPU (MPS). See the benchmarks.

  • Scalability to large graphs


    With unified memory architecture, objects live in a shared memory accessible by both the CPU and GPU. This setup allows Macs to leverage their entire memory capacity for storing graphs. Consequently, Macs equipped with substantial memory can efficiently train GNNs on large graphs, spanning tens of gigabytes, directly using the Mac's GPU, and features larger than the memory stay on disk in a memory-mapped feature store. See the large graphs guide.

  • PyTorch Geometric's API, on MLX


    The layers, models, samplers and loaders, transforms and datasets of PyG are available under the same names: mini-batch training with NeighborLoader and ClusterLoader, heterogeneous models with to_hetero, temporal graphs with TGN, graph transformers with GPSConv, point clouds with PointNetConv, and hierarchical pooling. Each was checked against PyG. See Coming from PyG.

  • Multi-device


    Unified memory eliminates the need for time-consuming device-to-device transfers. This architecture also enables specific operations to be run explicitly on either the CPU or GPU without incurring any overhead, facilitating more efficient computation and resource utilization.

Example usage

This library has been designed to build GNNs with ease and efficiency. Building new GNN layers is straightforward by implementing the MessagePassing class. This approach ensures that all operations related to message passing are properly handled and processed efficiently on your Mac's GPU. As a result, you can focus exclusively on the GNN logic, without worrying about the underlying message passing mechanics.

Here is an example of a custom GraphSAGE convolutional layer that considers edge weights:

import mlx.core as mx
from mlx_graphs.nn.linear import Linear
from mlx_graphs.nn.message_passing import MessagePassing, fused_message_passing


@fused_message_passing  # aggregate with one SpMM instead of gather-scatter
class SAGEConv(MessagePassing):
    def __init__(self, node_features_dim: int, out_features_dim: int, bias: bool = True):
        super().__init__(aggr="mean")
        self.neigh_proj = Linear(node_features_dim, out_features_dim, bias=False)
        self.self_proj = Linear(node_features_dim, out_features_dim, bias=bias)

    def __call__(self, edge_index: mx.array, node_features: mx.array, edge_weights: mx.array) -> mx.array:
        # Message passing directly on GPU. The default message is
        # edge_weights * source features, which the fused kernel computes.
        neigh_features = self.propagate(
            edge_index=edge_index,
            node_features=node_features,
            message_kwargs={"edge_weights": edge_weights},
        )
        return self.self_proj(node_features) + self.neigh_proj(neigh_features)


# 3 nodes, 3 weighted edges, 8 features -> 16
edge_index = mx.array([[0, 1, 2], [1, 2, 0]])
conv = SAGEConv(8, 16)
out = conv(edge_index, mx.random.normal((3, 8)), mx.array([1.0, 0.5, 2.0]))
print(out.shape)  # (3, 16)

Layers that override message() with something other than a weighted sum of neighbour features (e.g. attention computed per edge) simply drop the decorator, and propagate gathers per-edge messages and scatters them.

Write your own layers

Tutorials

Notebooks that train complete models, most of them side by side with PyTorch Geometric. All tutorials

Graph classification

Classify the MUTAG molecules with a GCN, mini-batches and global pooling.

beginnergraph-level

Node2Vec

Node embeddings from biased random walks on Cora, sampled on the GPU, compared with PyG.

embeddings

Mini-batch training on large graphs

Train on ogbn-arxiv one subgraph at a time with NeighborLoader, ClusterLoader and GraphSAINT.

scalingsamplers

Link prediction

Split edges without leakage, train a GCN encoder and dot-product decoder, rank with LinkPred metrics.

edge-levelvs PyG

Heterogeneous graphs with to_hetero

Turn a homogeneous GraphSAGE or GAT into a heterogeneous model on DBLP, as in PyG.

heterogeneousvs PyG

Graph transformers with GPS

GPSConv with random-walk encodings on Peptides-func, plus Performer, SGFormer and Polynormer.

transformersvs PyG