Neural networks¶
Layers, models, aggregations, normalization and pooling of mlx_graphs.nn, under the names of torch_geometric.nn.
Building blocks¶
| Class | Description |
|---|---|
Linear |
Linear layer with Xavier Glorot weight initialization and a zero bias. |
HeteroDictLinear |
Applies a separate linear layer to each node type. |
MessagePassing |
Base class for creating Message Passing Neural Networks (MPNNs) [1]. |
GraphNetworkBlock |
Implements a generic Graph Network block as defined in [1]. |
Convolution layers¶
Point cloud and mesh layers¶
Layers for point clouds and meshes, which take node positions pos (and
normals or pseudo-coordinates), e.g. from
ModelNet with
SamplePoints. PointConv is an alias
of PointNetConv.
Dense convolution layers¶
Layers on batched dense adjacency matrices [batch_size, num_nodes, num_nodes]
(e.g. from to_dense_adj or a
DenseDataLoader), called as
conv(adj, node_features, mask).
| Class | Description |
|---|---|
DenseGCNConv |
Dense version of GCNConv. |
DenseSAGEConv |
Dense version of SAGEConv (mean aggregation). |
DenseGINConv |
Dense version of GINConv. |
DenseGraphConv |
Dense version of GraphConv. |
Models¶
Ready-to-use multi-layer models, with optional normalization, dropout and Jumping Knowledge.
| Class | Description |
|---|---|
GCN |
Graph Convolutional Network from "Semi-Supervised Classification with Graph Convolutional Networks", a stack of GCNConv layers. |
GraphSAGE |
GraphSAGE from "Inductive Representation Learning on Large Graphs", a stack of SAGEConv layers. |
GIN |
Graph Isomorphism Network from "How Powerful are Graph Neural Networks?", a stack of GINConv layers, each with a two-layer MLP. |
GAT |
Graph Attention Network from "Graph Attention Networks" (or, with v2=True, "How Attentive are Graph Attention Networks?"), a stack of GATConv / GATv2Conv layers. |
MLP |
Multi-layer perceptron. |
BasicGNN |
Base class of the ready-to-use GNN models. |
PNA |
Principal Neighbourhood Aggregation network from "Principal Neighbourhood Aggregation for Graph Nets", a stack of PNAConv layers. |
Other models and building blocks:
Molecular and 3D models¶
Models for molecules, on atom types and 3D positions pos
(SchNet, DimeNet,
DimeNetPlusPlus) or on the atom and bond
features of from_smiles
(AttentiveFP), e.g. on
QM9 or MoleculeNet.
| Class | Description |
|---|---|
SchNet |
The continuous-filter convolutional neural network SchNet from the "SchNet: A Continuous-filter Convolutional Neural Network for Modeling Quantum Interactions" paper, with interaction blocks of the form |
DimeNet |
The directional message passing neural network (DimeNet) from the "Directional Message Passing for Molecular Graphs" paper. |
DimeNetPlusPlus |
DimeNet++ from the "Fast and Uncertainty-Aware Directional Message Passing for Non-Equilibrium Molecules" paper. |
AttentiveFP |
The Attentive FP model for molecular representation learning from the "Pushing the Boundaries of Molecular Representation for Drug Discovery with the Graph Attention Mechanism" paper, based on graph attention mechanisms. |
Graph auto-encoders¶
| Class | Description |
|---|---|
InnerProductDecoder |
The inner product decoder from the "Variational Graph Auto-Encoders" paper. |
GAE |
The Graph Auto-Encoder model from the "Variational Graph Auto-Encoders" paper, based on user-defined encoder and decoder models. |
VGAE |
The Variational Graph Auto-Encoder model from the "Variational Graph Auto-Encoders" paper. |
ARGA |
The Adversarially Regularized Graph Auto-Encoder model from the "Adversarially Regularized Graph Autoencoder for Graph Embedding" paper. |
ARGVA |
The Adversarially Regularized Variational Graph Auto-Encoder model from the "Adversarially Regularized Graph Autoencoder for Graph Embedding" paper. |
Label propagation¶
| Class | Description |
|---|---|
LabelPropagation |
The label propagation operator from the "Learning from Labeled and Unlabeled Data with Label Propagation" paper, in the form used by "Combining Label Propagation And Simple Models Out-performs Graph Neural Networks". |
CorrectAndSmooth |
The correct and smooth (C&S) post-processing model from the "Combining Label Propagation And Simple Models Out-performs Graph Neural Networks" paper. |
Knowledge graph embeddings¶
| Class | Description |
|---|---|
KGEModel |
Base class of the knowledge graph embedding models. |
TransE |
The TransE model from the "Translating Embeddings for Modeling Multi-Relational Data" paper. |
DistMult |
The DistMult model from the "Embedding Entities and Relations for Learning and Inference in Knowledge Bases" paper. |
ComplEx |
The ComplEx model from the "Complex Embeddings for Simple Link Prediction" paper. |
RotatE |
The RotatE model from the "RotatE: Knowledge Graph Embedding by Relational Rotation in Complex Space" paper. |
KGTripletLoader |
Iterates over mini-batches of (head_index, rel_type, tail_index) triplets. |
Normalization¶
| Class | Description |
|---|---|
BatchNormalization |
Applies batch normalization over a batch of features as described in the Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift" paper. |
HeteroBatchNormalization |
Applies batch normalization over a batch of heterogeneous features, as described in the "Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift" paper. |
InstanceNormalization |
Instance normalization over each individual example in batch of node features as described in the paper Instance Normalization: The Missing Ingredient for Fast Stylization paper. |
LayerNormalization |
Applies layer normalization over each individual example in a batch of features as described in the Layer Normalization paper. |
HeteroLayerNormalization |
Applies layer normalization over each individual example in a batch of heterogeneous features, as described in the "Layer Normalization" paper. |
GraphNormalization |
Applies graph normalization over individual graphs as described in the "GraphNorm: A Principled Approach to Accelerating Graph Neural Network Training" paper. |
PairNormalization |
Applies pair normalization over node features as described in the "PairNorm: Tackling Oversmoothing in GNNs" paper. |
GraphSizeNormalization |
Applies graph size normalization over each individual graph in a batch of node features as described in the "Benchmarking Graph Neural Networks" paper. |
MeanSubtractionNormalization |
Applies layer normalization by subtracting the mean from the inputs as described in the "Revisiting 'Over-smoothing' in Deep GCNs" paper. |
MessageNormalization |
Applies message normalization over the aggregated messages as described in the "DeeperGCNs: All You Need to Train Deeper GCNs" paper. |
DiffGroupNormalization |
The differentiable group normalization layer from the "Towards Deeper Graph Neural Networks with Differentiable Group Normalization" paper, which normalizes node features group-wise via a learnable soft cluster assignment. |
Each normalization layer is also available under its PyG name, as an alias of the same class:
| PyG name | Class |
|---|---|
BatchNorm |
BatchNormalization |
HeteroBatchNorm |
HeteroBatchNormalization |
InstanceNorm |
InstanceNormalization |
LayerNorm |
LayerNormalization |
HeteroLayerNorm |
HeteroLayerNormalization |
GraphNorm |
GraphNormalization |
PairNorm |
PairNormalization |
GraphSizeNorm |
GraphSizeNormalization |
MeanSubtractionNorm |
MeanSubtractionNormalization |
MessageNorm |
MessageNormalization |
DiffGroupNorm |
DiffGroupNormalization |
Pooling and readout¶
| Class | Description |
|---|---|
JumpingKnowledge |
Jumping Knowledge layer aggregation from "Representation Learning on Graphs with Jumping Knowledge Networks" paper. |
AttentionalAggregation |
Soft attention pooling (global attention) from "Gated Graph Sequence Neural Networks" paper. |
Set2Set |
Set2Set global pooling from "Order Matters: Sequence to Sequence for Sets" paper. |
TopKPooling |
\(\mathrm{top}_k\) pooling operator from the "Graph U-Nets", "Towards Sparse Hierarchical Graph Classifiers" and "Understanding Attention and Generalization in Graph Neural Networks" papers. |
SAGPooling |
The self-attention pooling operator from the "Self-Attention Graph Pooling" and "Understanding Attention and Generalization in Graph Neural Networks" papers. |
| Function | Description |
|---|---|
global_add_pool() |
Sums all node features to obtain a global graph-level representation. |
global_mean_pool() |
Takes the feature-wise mean value along all node features to obtain a global graph-level representation. |
global_max_pool() |
Takes the feature-wise maximum value along all node features to obtain a global graph-level representation. |
global_sort_pool() |
The global pooling operator from the "An End-to-End Deep Learning Architecture for Graph Classification" paper. |
topk() |
Selects the nodes with the highest scores in each graph. |
filter_adj() |
Keeps the edges between the nodes perm, relabeled by their position in perm. |
knn() |
Finds for each point of y the k nearest points of x. |
knn_graph() |
Computes the graph connecting each point to its k nearest points. |
radius() |
Finds for each point of y the points of x within distance r. |
radius_graph() |
Computes the graph connecting each point to the points within distance r. |
Point cloud sampling and cluster pooling (fps, voxel_grid, graclus and
nearest are also in mlx_graphs.utils):
| Function | Description |
|---|---|
fps() |
Farthest point sampling, from the "PointNet++: Deep Hierarchical Feature Learning on Point Sets in a Metric Space" paper. |
voxel_grid() |
Voxel grid pooling from the "Dynamic Edge-Conditioned Filters in Convolutional Networks on Graphs" paper: overlays a regular grid of user-defined size over a point cloud and clusters all the points within the same voxel. |
graclus() |
A greedy clustering algorithm from the "Weighted Graph Cuts without Eigenvectors: A Multilevel Approach" paper, which matches each node with one of its unmarked neighbors (the one maximizing the edge weight, if given). |
nearest() |
Assigns each point of x to its nearest point of y, in the same graph. |
avg_pool() |
Pools and coarsens a graph given by a clustering, averaging the node features and the positions of each cluster (as PyG's avg_pool). |
max_pool() |
Pools and coarsens a graph given by a clustering, taking the feature-wise maximum of the nodes of each cluster (as PyG's max_pool). |
avg_pool_x() |
Averages the features of the nodes of each cluster. |
max_pool_x() |
Takes the feature-wise maximum of the nodes of each cluster. |
Hierarchical and dense pooling¶
Dense pooling learns soft cluster assignments on dense batched graphs and
returns auxiliary losses; sparse hierarchical pooling coarsens a batch of
graphs given by edge_index and batch_indices.
| Name | Description |
|---|---|
dense_diff_pool() |
The differentiable pooling operator from the "Hierarchical Graph Representation Learning with Differentiable Pooling" paper. |
dense_mincut_pool() |
The MinCut pooling operator from the "Spectral Clustering in Graph Neural Networks for Graph Pooling" paper. |
DMoNPooling |
The spectral modularity pooling operator from the "Graph Clustering with Graph Neural Networks" paper. |
EdgePooling |
The edge pooling operator from the "Towards Graph Pooling by Edge Contraction" and "Edge Contraction Pooling for Graph Neural Networks" papers. |
UnpoolInfo |
What EdgePooling.unpool() needs to undo a pooling step. |
ASAPooling |
The Adaptive Structure Aware Pooling operator from the "ASAP: Adaptive Structure Aware Pooling for Learning Hierarchical Graph Representations" paper. |
MemPooling |
Memory based pooling layer from the "Memory-Based Graph Networks" paper, which learns a coarsened graph representation based on soft cluster assignments. |
PANPooling |
The path integral based pooling operator from the "Path Integral Based Convolution and Pooling for Graph Neural Networks" paper. |
PANConv |
The path integral based convolutional operator from the "Path Integral Based Convolution and Pooling for Graph Neural Networks" paper. |
GraphUNet |
The Graph U-Net model from the "Graph U-Nets" paper, which implements a U-Net like architecture with graph pooling and unpooling operations. |
Aggregations¶
Aggregation operators of mlx_graphs.nn.aggr (as torch_geometric.nn.aggr).
They reduce a set of elements given by an index (aggr(x, index,
dim_size)) and can be used as readouts, or passed as aggr to any
MessagePassing layer, alone or as a list (e.g.
SAGEConv(16, 32, aggr=["mean", "max"])).
| Class | Description |
|---|---|
Aggregation |
Base class of the aggregation operators, mirroring torch_geometric.nn.aggr.Aggregation. |
SumAggregation |
Sums the elements of each set. |
MeanAggregation |
Averages the elements of each set. |
MaxAggregation |
Feature-wise maximum of the elements of each set (0 for empty sets). |
MinAggregation |
Feature-wise minimum of the elements of each set (0 for empty sets). |
MulAggregation |
Feature-wise product of the elements of each set (1 for empty sets). |
VarAggregation |
Feature-wise (population) variance of the elements of each set. |
StdAggregation |
Feature-wise (population) standard deviation of the elements of each set. |
SoftmaxAggregation |
Softmax aggregation with an (optionally learnable) inverse temperature, from "DeeperGCN: All You Need to Train Deeper GCNs" paper. |
PowerMeanAggregation |
Power mean aggregation with an (optionally learnable) power, from "DeeperGCN: All You Need to Train Deeper GCNs" paper. |
MedianAggregation |
Feature-wise median of the elements of each set. |
QuantileAggregation |
Feature-wise \(q\)-th quantile of the elements of each set. |
MultiAggregation |
Applies several aggregations and combines their results, as in "Principal Neighbourhood Aggregation for Graph Nets" and "Adaptive Filters and Aggregator Fusion for Efficient Graph Convolutions" papers. |
DegreeScalerAggregation |
Combines one or more aggregations and rescales their output with one or more degree-based scalers, from "Principal Neighbourhood Aggregation for Graph Nets" paper. |
SortAggregation |
Sort pooling from "An End-to-End Deep Learning Architecture for Graph Classification" paper (DGCNN). |
DeepSetsAggregation |
Deep Sets aggregation: the elements are transformed by a network \(\phi_{\mathbf{\Theta}}\), summed, and the sum is transformed by a network \(\rho_{\mathbf{\Theta}}\), as in "Graph Neural Networks with Adaptive Readouts" paper. |
LSTMAggregation |
Aggregation with an LSTM, from the "Inductive Representation Learning on Large Graphs" paper, as PyG's LSTMAggregation. |
GRUAggregation |
Aggregation with a GRU, from the "Graph Neural Networks with Adaptive Readouts" paper, as PyG's GRUAggregation. |
SetTransformerAggregation |
Aggregation with a Set Transformer, from the "Set Transformer: A Framework for Attention-based Permutation-Invariant Neural Networks" paper, as PyG's SetTransformerAggregation. |
GraphMultisetTransformer |
The Graph Multiset Transformer pooling operator from the "Accurate Learning of Graph Representations with Graph Multiset Pooling" paper, as PyG's GraphMultisetTransformer. |
MLPAggregation |
Aggregation with a multi-layer perceptron on the concatenated elements of each set, from the "Graph Neural Networks with Adaptive Readouts" paper, as PyG's MLPAggregation. |
LCMAggregation |
The Learnable Commutative Monoid aggregation from the "Learnable Commutative Monoids for Graph Neural Networks" paper, as PyG's LCMAggregation. |
EquilibriumAggregation |
The equilibrium aggregation layer from the "Equilibrium Aggregation: Encoding Sets via Optimization" paper, as PyG's EquilibriumAggregation. |
VariancePreservingAggregation |
The variance-preserving aggregation from the "GNN-VPA: A Variance-Preserving Aggregation Strategy for Graph Neural Networks" paper, as in PyG. |
Set transformer building blocks:
| Class | Description |
|---|---|
MultiheadAttentionBlock |
The Multihead Attention Block (MAB) from the "Set Transformer: A Framework for Attention-based Permutation-Invariant Neural Networks" paper, as in PyG. |
SetAttentionBlock |
The Set Attention Block (SAB) from the "Set Transformer" paper: \(\mathrm{SAB}(\mathbf{X}) = \mathrm{MAB}(\mathbf{x}, \mathbf{y})\). |
InducedSetAttentionBlock |
The Induced Set Attention Block (ISAB) from the "Set Transformer" paper: \(\mathrm{ISAB}(\mathbf{X}) = \mathrm{MAB}(\mathbf{x}, \mathbf{h})\) with \(\mathbf{h} = \mathrm{MAB}(\mathbf{I}, \mathbf{x})\) for learnable induced points \(\mathbf{I}\). |
PoolingByMultiheadAttention |
The Pooling by Multihead Attention (PMA) layer from the "Set Transformer" paper: \(\mathrm{PMA}(\mathbf{X}) = \mathrm{MAB}(\mathbf{S}, \mathrm{ReLU}(\mathbf{X}\mathbf{W}))\) for learnable seed points \(\mathbf{S}\). |
Dense layout of grouped elements (used by the set and graph transformers):
| Class | Description |
|---|---|
DenseLayout |
Host-side layout of a set of elements grouped by index into a dense [num_sets, max_set_size, ...] array, as PyG's to_dense_batch. |
| Function | Description |
|---|---|
aggregation_resolver() |
Returns the Aggregation described by aggr, as PyG's aggregation_resolver. |
Positional encodings¶
Encodings of positions and times (torch_geometric.nn.encoding), and the
projections of the random-walk / Laplacian positional encodings used by graph
transformers such as GPSConv.
| Class | Description |
|---|---|
PositionalEncoding |
The sinusoidal positional encoding from the "Attention Is All You Need" paper, as PyG's PositionalEncoding. |
TemporalEncoding |
The time encoding from the "Do We Really Need Complicated Model Architectures for Temporal Networks?" paper, as PyG's TemporalEncoding. |
RWSEEncoder |
Projection of the random-walk structural encodings (RWSE) of the nodes, as in the GPS example of PyG (examples/graph_gps.py) and the RWSE node encoder of GraphGPS. |
LapPEEncoder |
Projection of the Laplacian eigenvector positional encodings (LapPE) of the nodes, as the linear LapPE node encoder of GraphGPS. |
Attention¶
Global attention mechanisms of mlx_graphs.nn.attention (as
torch_geometric.nn.attention), applied to dense batches of node features
[batch_size, num_nodes, channels] with a mask of the real nodes. They are
also exported by mlx_graphs.nn, as in PyG.
| Class | Description |
|---|---|
MultiheadAttention |
Multi-head scaled dot-product attention with the semantics of torch.nn.MultiheadAttention(..., batch_first=True). |
PerformerAttention |
The linear scaled attention mechanism from the "Rethinking Attention with Performers" paper, as in PyG. |
SGFormerAttention |
The simple global attention mechanism from the "SGFormer: Simplifying and Empowering Transformers for Large-Graph Representations" paper, as in PyG. |
PolynormerAttention |
The polynomial-expressive linear global attention from the "Polynormer: Polynomial-Expressive Graph Transformer in Linear Time" paper, as in PyG. |
Fused message passing¶
Layers decorated with fused_message_passing() aggregate neighbours
with a single sparse-dense matmul (SpMM) from mlx-cluster instead of
gather-scatter, so the [num_edges, features] message array is never
created. GCNConv, SAGEConv, GINConv, GATConv, GATv2Conv,
GraphConv, SGConv, APPNP, ChebConv, TAGConv and
SimpleConv use it out of the box (the attention layers aggregate with one
SpMM per head). Layers whose messages can't be fused (e.g. GINE with edge
features) fall back to gather-scatter automatically.
The default format="auto" starts with the COO kernel and switches to the
faster, deterministic CSR kernel once converting the graph pays off: right
away for graphs with a million edges or more, and after a few calls on the
same edge_index otherwise (e.g. full-batch training). Conversions are
cached by edge_index identity; call clear_csr_cache() after
modifying an edge_index in place.
import mlx_graphs.nn as gnn
# Turn it off globally, or force a format for every layer
gnn.set_fused_message_passing(True, format="csr")
# Or only for a block of code (handy for comparing both paths)
with gnn.fused_message_passing_mode(False):
reference = model(edge_index, x)
| Function | Description |
|---|---|
fused_message_passing() |
Class decorator: lets a MessagePassing layer fuse message and aggregate into a single sparse x dense matmul (SpMM). |
set_fused_message_passing() |
Globally enables/disables fused message passing. |
fused_message_passing_mode() |
Context manager version of set_fused_message_passing(). |
is_fused_message_passing_enabled() |
Whether fused message passing is enabled and the kernels are available. |
clear_csr_cache() |
Drops all cached CSR conversions used by the "auto" and "csr" formats of fused message passing. |
gcn_norm() |
Symmetric GCN normalization of a graph. |
clear_norm_cache() |
Drops the cached graph normalizations. |
Temporal graph networks¶
The TGN memory model and its building blocks (mlx_graphs.nn.models.tgn, as
torch_geometric.nn.models.tgn). See examples/tgn_jodie.py.
| Class | Description |
|---|---|
TGNMemory |
The Temporal Graph Network (TGN) memory model from the "Temporal Graph Networks for Deep Learning on Dynamic Graphs" paper, as PyG's torch_geometric.nn.TGNMemory. |
| Class | Description |
|---|---|
IdentityMessage |
The identity message function of TGN: the concatenation of the source and destination memories, the raw message and the time encoding. |
LastAggregator |
Keeps, for every node, the message with the latest timestamp (the message stored last among equal timestamps). |
MeanAggregator |
Averages the messages of every node (zeros for nodes without messages). |
TimeEncoder |
The time encoder of TGN, \(\cos(\mathbf{w} t + \mathbf{b})\). |
GRUCell |
A gated recurrent unit cell with the parameters and initialization of torch.nn.GRUCell. |
LastNeighborLoader |
Keeps, for every node, its size most recent neighbors in an ever-growing (undirected) temporal graph, as PyG's torch_geometric.nn.models.tgn.LastNeighborLoader. |
Heterogeneous models¶
to_hetero() converts a homogeneous model (e.g. a GraphSAGE, or
a model written with message passing layers, Linear layers and
activations) into a heterogeneous one, with one copy of every message passing
layer per edge type and of every other layer per node type, like PyG's
to_hetero. The converted model takes dicts keyed by node and edge types.
from mlx_graphs.nn import GraphSAGE, to_hetero
model = to_hetero(
GraphSAGE(64, 64, num_layers=2, out_features_dim=4),
data.metadata(),
input_dims=data.num_node_features, # no lazy sizes in MLX
)
out = model(data.edge_index_dict, data.node_features_dict)
| Name | Description |
|---|---|
to_hetero() |
Conversion of homogeneous GNN models into heterogeneous ones (to_hetero). |
to_hetero_with_bases() |
Converts a homogeneous GNN model into its heterogeneous equivalent via the basis-decomposition technique of the "Modeling Relational Data with Graph Convolutional Networks" paper (PyG's to_hetero_with_bases). |
ToHeteroModel |
Heterogeneous version of a homogeneous model, returned by to_hetero(). |