Skip to content

About

Graph Neural Network library made for Apple Silicon

Resources

Contributing

Stars

230 stars

Watchers

8 watching

Forks

Repository files navigation

mlx-graphs

Fast graph neural networks on Apple Silicon

PyPI Python 3.10+ macOS on Apple Silicon License: MIT Built on MLX Discord

Documentation · Quickstart · Benchmarks · Examples · Contributors · Discord

MLX-graphs is a library for Graph Neural Networks (GNNs) on Apple Silicon, built on Apple's MLX. It runs message passing on your Mac's GPU with fused sparse kernels, which PyTorch Geometric lacks on MPS.

On an M5 Pro, mlx-graphs trains GNNs 5.6× faster than PyTorch Geometric on MPS and 5.8× faster than on CPU, with the same accuracy (median of 35 benchmarks on 12 datasets, up to 58×).

Left: time of PyG on MPS and on CPU relative to mlx-graphs: 12× and 6.7× for one layer on 2 million edges, 5.3× and 7.4× per epoch of node classification, 5.6× and 2.9× per epoch of graph classification. Right: mean test accuracy of mlx-graphs, PyG on MPS and PyG on CPU: 79.2%, 79.0% and 78.9% in node classification, 68.8%, 69.2% and 68.9% in graph classification

Apple M5 Pro, 64 GB · mlx 0.32.4 · PyTorch 2.15 · PyTorch Geometric 2.8.1 · same models, data and hyperparameters in every framework, 3 seeds. See benchmarks for the details.

Installation

pip install mlx-graphs

Features

  • Fast GNN training and inference on Apple Silicon. Message passing runs on the Mac's GPU through MLX and fused sparse kernels: neighbours are aggregated with one sparse x dense matmul (SpMM) instead of building a [num_edges, features] message array, including for the attention layers (one SpMM per head): 5–6× faster training than PyTorch Geometric on the same Mac, see the benchmarks.
  • A PyG-style API. MessagePassing, GraphData / batching, datasets, transforms and utilities follow PyTorch Geometric's design, so porting a PyG model is mostly mechanical. from_pyg / to_pyg convert graphs both ways.
  • Scalability to large graphs. With unified memory, the whole memory of the Mac is available to the GPU, and fused message passing keeps the peak memory of a layer close to the size of its inputs and outputs.

What's included

Names and signatures follow PyTorch Geometric; see Coming from PyTorch Geometric.

Layers, models, datasets, loaders and utilities (click to expand)
Convolutions GCNConv, SAGEConv, GINConv, GINEConv, GATConv, GATv2Conv, TransformerConv, GraphConv, GeneralConv, SGConv, SSGConv, APPNP, ChebConv, TAGConv, ARMAConv, MixHopConv, GCN2Conv, FAConv, AGNNConv, LEConv, LGConv, MFConv, ClusterGCNConv, GENConv, PNAConv, CGConv, NNConv, ResGatedGraphConv, GatedGraphConv, FiLMConv, EdgeConv, DynamicEdgeConv, DirGNNConv, SimpleConv, GeneralizedRelationalConv
Heterogeneous to_hetero, to_hetero_with_bases, HeteroConv, HANConv, HGTConv, RGCNConv, FastRGCNConv, RGATConv, HeteroDictLinear, HeteroGraphData
Graph transformers GPSConv, SGFormer, Polynormer, MultiheadAttention, PerformerAttention; positional encodings AddRandomWalkPE, AddLaplacianEigenvectorPE, RWSEEncoder, LapPEEncoder
Point clouds / meshes PointNetConv (PointConv), PointTransformerConv, PPFConv, XConv, SplineConv, GMMConv, FeaStConv; fps (Metal kernel), voxel_grid, graclus, nearest, avg_pool / max_pool; transforms SamplePoints, FixedPoints, NormalizeScale, RandomRotate, RandomJitter, RandomScale, FaceToEdge, Cartesian, Distance, Polar, PointPairFeatures; datasets ModelNet (10 / 40), ShapeNet
Temporal graphs TemporalData, TemporalDataLoader, TGNMemory, LastNeighborLoader, TemporalEncoding, JODIEDataset, TGB datasets (TGBLinkPropPredDataset, TGBNodePropPredDataset) with the official negative samples and TGBEvaluator
Molecules and 3D SchNet, DimeNet, DimeNetPlusPlus, AttentiveFP; datasets QM9, ZINC, MoleculeNet; from_smiles / to_smiles (with rdkit)
Models GCN, GraphSAGE, GIN, GAT, PNA, EdgeCNN, MLP, DeepGCNLayer, LINKX, LightGCN, GAE / VGAE / ARGA / ARGVA, DeepGraphInfomax, RECT_L, LabelPropagation, CorrectAndSmooth, knowledge-graph embeddings (TransE, DistMult, ComplEx, RotatE), Node2Vec
Aggregations aggr="sum", "mean", "max", ... or lists of them, and the modules SoftmaxAggregation, PowerMeanAggregation, MultiAggregation, DegreeScalerAggregation, QuantileAggregation, MedianAggregation, StdAggregation, VarAggregation, LSTMAggregation, GRUAggregation, SortAggregation, SetTransformerAggregation, GraphMultisetTransformer, DeepSetsAggregation, MLPAggregation, EquilibriumAggregation, LCMAggregation, ...
Pooling / readout global_{add,mean,max,sort}_pool, TopKPooling, SAGPooling, EdgePooling, ASAPooling, MemPooling, PANPooling (with PANConv), GraphUNet, dense pooling (dense_diff_pool, dense_mincut_pool, DMoNPooling) with DenseGCNConv, DenseSAGEConv, DenseGINConv, DenseGraphConv, AttentionalAggregation, Set2Set, JumpingKnowledge, knn_graph, radius_graph
Normalization BatchNorm, LayerNorm, InstanceNorm, GraphNorm, PairNorm, DiffGroupNorm, MessageNorm, GraphSizeNorm, MeanSubtractionNorm, HeteroBatchNorm, HeteroLayerNorm
Loaders and samplers Dataloader, NeighborLoader and LinkNeighborLoader (homogeneous and heterogeneous), HGTLoader, ClusterData / ClusterLoader, GraphSAINT samplers, ShaDowKHopSampler, RandomNodeLoader, ImbalancedSampler, DynamicBatchSampler, DataListLoader, DenseDataLoader; temporal neighbor sampling (time_attr, temporal_strategy); FeatureStore / GraphStore backends, incl. on-disk MemmapFeatureStore
Datasets Planetoid, CitationFull, Amazon, Coauthor, WikiCS, WebKB, WikipediaNetwork, Actor, HeterophilousGraphDataset, OGB (incl. OGBMAG), TU datasets, GNNBenchmarkDataset, LRGB, JODIE, QM7b, superpixels, Elliptic, MovieLens, IMDB, DBLP, FB15k-237, WordNet18, Karate Club, Reddit, Reddit2, Flickr, Yelp, AmazonProducts, PPI, fake datasets, Temporal Graph Benchmark (TGB)
Transforms Compose, ToUndirected, AddSelfLoops, NormalizeFeatures, RandomNodeSplit, RandomLinkSplit, GCNNorm, SIGN, VirtualNode, LineGraph, TwoHop, KNNGraph, LocalDegreeProfile, FeaturePropagation, SVDFeatureReduction, ToDense, ... (32 in all)
Metrics LinkPredMRR, LinkPredHitRatio, LinkPredNDCG, LinkPredMAP, LinkPredPrecision, LinkPredRecall, LinkPredF1 and more, roc_auc_score, average_precision_score
Utilities scatter, softmax, degree, subgraph, k_hop_subgraph, negative_sampling, dropout_edge, to_dense_batch, to_dense_adj, get_laplacian, get_ppr, homophily, assortativity, coalesce, to_undirected, graph generators, from_pyg / to_pyg, from_networkx / to_networkx, from_scipy_sparse_matrix, ...

Every layer was checked against PyG with copied weights (outputs and gradients), and the models by training them in both frameworks on the same data: see Validation against PyG.

Benchmarks vs PyTorch Geometric

Apple M5 Pro (64 GB), PyG 2.8.1 / PyTorch 2.15 on MPS and CPU; same models, hyperparameters and data in every framework, 3 seeds.

Faster

Speedups against PyG on MPS (the CPU numbers are in the figures):

  • One layer (forward + backward, 2M edges): 9–31× faster for GCN, GraphSAGE, GIN and GAT, with up to 3.3× less memory; ~3× for GATv2.
  • Node classification (8 datasets, Cora to ogbn-arxiv): 1.6–58× faster per epoch, median 5.3×. PyG's GraphSAGE runs out of memory (16 GB) on Coauthor Physics; mlx-graphs needs 4.7 GB.
  • Graph classification (MUTAG, PROTEINS, NCI1, DD, batching included): 2.7–11× faster.
Speed figures (click to expand) Time of one forward and backward pass of GCN, GraphSAGE, GIN, GAT and GATv2, relative to mlx-graphs, for mlx-graphs, PyG on MPS and PyG on CPU, on random graphs of 100 thousand, 500 thousand and 2 million edges Time per training epoch of full-batch node classification with GCN, GraphSAGE and GAT on eight datasets, for mlx-graphs, PyG on MPS and PyG on CPU

Same results

Speed only matters if the models learn the same thing. The training loss of mlx-graphs and PyG follows the same curve at every epoch, and the test accuracies match within the spread between seeds (mean over node classification: 79.2% for mlx-graphs, 79.0% / 78.9% for PyG on MPS / CPU).

Loss and accuracy figures (click to expand) Training loss per epoch of GCN, GraphSAGE and GAT on eight node classification datasets, mlx-graphs, PyG on MPS and PyG on CPU overlaid: the curves coincide Test accuracy of GCN, GraphSAGE and GAT on eight node classification datasets, mean and range over 3 seeds, for mlx-graphs, PyG on MPS and PyG on CPU

The same figures for graph classification, peak memory and absolute timings are on the benchmarks page of the docs and in results.md, which also has every number as a table. How the comparison is made is in benchmarks/pyg_comparison. To reproduce on your Mac:

pip install -e '.[benchmarks]'
python benchmarks/pyg_comparison/run.py && python benchmarks/pyg_comparison/plot.py

Usage

Tutorial guides

We provide some notebooks to practice mlx-graphs.

Runnable scripts are in examples/, e.g. node_classification.py and link_prediction.py.

Training a model

import mlx.core as mx
import mlx.nn as nn
import mlx.optimizers as optim
import numpy as np

from mlx_graphs.datasets import PlanetoidDataset
from mlx_graphs.nn import GCN

graph = PlanetoidDataset("cora")[0]
train = mx.array(np.nonzero(np.array(graph.train_mask))[0])
labels = graph.node_labels

model = GCN(graph.num_node_features, 64, num_layers=2, out_features_dim=7, dropout=0.5)
# bias_correction=True: the same update rule as torch.optim.Adam
optimizer = optim.Adam(learning_rate=0.01, bias_correction=True)


def loss_fn(model):
    logits = model(graph.edge_index, graph.node_features)
    return nn.losses.cross_entropy(logits[train], labels[train], reduction="mean")


loss_and_grad = nn.value_and_grad(model, loss_fn)
for epoch in range(200):
    loss, grads = loss_and_grad(model)
    optimizer.update(model, grads)
    mx.eval(model.parameters(), optimizer.state)

Tip

Create MLX's Adam/AdamW with bias_correction=True. MLX's default (no bias correction) takes much larger first steps than PyTorch's Adam; in our runs it cost GAT about 4 points of accuracy on Cora.

Writing a layer

New GNN layers subclass MessagePassing, which runs the message passing on your Mac's GPU so you only write the GNN logic. See the Writing your own layers guide.

Example: a GraphSAGE layer with edge weights (click to expand)
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)

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.

Contributing

We are at an early stage of the development of the lib, which means your contributions can have a large impact! Everyone is welcome to contribute, just open an issue 📝 with your idea 💡 and we'll work together on the implementation ✨. New layers and datasets are especially welcome.

See CONTRIBUTING.md for the development setup, tests and pull request guidelines.

Contributors

mlx-graphs is built by its community. Thank you to everyone who has contributed code, reviews, issues and ideas! 🙏

Avatars of the mlx-graphs contributors

Your avatar shows up here automatically once your first pull request is merged: see Contributing to get started.

About

Graph Neural Network library made for Apple Silicon

Resources

Contributing

Stars

230 stars

Watchers

8 watching

Forks

Releases

Packages

Used by

Contributors

Languages