Skip to content

GPSConv

GPSConv(
    channels: int,
    conv: Optional[Module],
    heads: int = 1,
    dropout: float = 0.0,
    act: Union[str, Callable, None] = "relu",
    act_kwargs: Optional[Dict[str, Any]] = None,
    norm: Union[str, Callable[..., Module], None] = "batch_norm",
    norm_kwargs: Optional[Dict[str, Any]] = None,
    attn_type: str = "multihead",
    attn_kwargs: Optional[Dict[str, Any]] = None,
)

Bases: Module

The general, powerful, scalable (GPS) graph transformer layer from the "Recipe for a General, Powerful, Scalable Graph Transformer" paper, as PyG's GPSConv.

The layer combines a local message passing layer (MPNN) and a global attention layer over all the nodes of each graph, each with a residual connection and a normalization, followed by a two-layer MLP:

\[ \mathbf{X}_M &= \mathrm{Norm}(\mathbf{X} + \mathrm{Dropout}(\mathrm{MPNN}(\mathbf{X}, \mathbf{A}))) \\ \mathbf{X}_T &= \mathrm{Norm}(\mathbf{X} + \mathrm{Dropout}(\mathrm{GlobalAttn}(\mathbf{X}))) \\ \mathbf{X}' &= \mathrm{Norm}(\mathbf{X}_M + \mathbf{X}_T + \mathrm{MLP}(\mathbf{X}_M + \mathbf{X}_T)) \]

Positional and structural encodings (the first part of the GPS recipe) are added to the input features beforehand, e.g. with the AddRandomWalkPE or AddLaplacianEigenvectorPE transforms and RWSEEncoder / LapPEEncoder.

The global attention is dense: it costs \(\mathcal{O}(N_{\max}^2)\) memory per graph and head, where \(N_{\max}\) is the size of the largest graph of the batch. Use attn_type="performer" for linear attention.

The dense batch of the attention is laid out from batch_indices on the host (a GPU synchronization, which also prevents mx.compile()) unless a precomputed layout is passed: see __call__() and from_sizes().

Parameters:

Name Type Description Default
channels int

Size of the input and output node features.

required
conv Optional[Module]

The local message passing layer, called as conv(edge_index, node_features, **kwargs), or None for a pure transformer.

required
heads int

Number of attention heads. Default: 1

1
dropout float

Dropout probability of the intermediate embeddings. Default: 0.0

0.0
act Union[str, Callable, None]

Activation of the MLP: a name ("relu", "gelu", ...) or a callable. Default: "relu"

'relu'
act_kwargs Optional[Dict[str, Any]]

Arguments of the activation. Default: None

None
norm Union[str, Callable[..., Module], None]

Normalization: "batch_norm", "layer_norm", "graph_norm", "instance_norm", a normalization class called as norm(channels, **norm_kwargs), or None. Graph normalizations receive batch_indices. Default: "batch_norm"

'batch_norm'
norm_kwargs Optional[Dict[str, Any]]

Arguments of the normalization. Default: None

None
attn_type str

Global attention: "multihead" (MultiheadAttention) or "performer" (PerformerAttention). Default: "multihead"

'multihead'
attn_kwargs Optional[Dict[str, Any]]

Arguments of the attention, e.g. {"dropout": 0.5} for dropout on the attention weights. Default: None

None

Example:

import mlx.core as mx
import mlx.nn as nn
from mlx_graphs.nn import GINEConv, GPSConv

mlp = nn.Sequential(nn.Linear(64, 64), nn.ReLU(), nn.Linear(64, 64))
conv = GPSConv(64, GINEConv(mlp), heads=4, attn_kwargs={"dropout": 0.5})

edge_index = mx.array([[0, 1, 2, 3], [1, 0, 3, 2]])
node_features = mx.random.normal((4, 64))
edge_features = mx.random.normal((4, 64))
batch_indices = mx.array([0, 0, 1, 1])
>>> conv(edge_index, node_features, batch_indices,
...      edge_features=edge_features).shape
(4, 64)

Methods:

Name Description
redraw_projection_matrix

Redraws the random projection of the performer attention (no-op

__call__

Computes the forward pass of GPSConv.

Source code in mlx_graphs/nn/conv/gps_conv.py
def __init__(
    self,
    channels: int,
    conv: Optional[nn.Module],
    heads: int = 1,
    dropout: float = 0.0,
    act: Union[str, Callable, None] = "relu",
    act_kwargs: Optional[Dict[str, Any]] = None,
    norm: Union[str, Callable[..., nn.Module], None] = "batch_norm",
    norm_kwargs: Optional[Dict[str, Any]] = None,
    attn_type: str = "multihead",
    attn_kwargs: Optional[Dict[str, Any]] = None,
):
    super().__init__()
    self.channels = channels
    self.conv = conv
    self.heads = heads
    self.dropout = dropout
    self.attn_type = attn_type
    attn_kwargs = attn_kwargs or {}
    if attn_type == "multihead":
        self.attn = MultiheadAttention(channels, heads, **attn_kwargs)
    elif attn_type == "performer":
        self.attn = PerformerAttention(channels, heads, **attn_kwargs)
    else:
        raise ValueError(
            f"Unknown attention type '{attn_type}'. Available: 'multihead', "
            "'performer'"
        )

    self.mlp = nn.Sequential(
        nn.Linear(channels, channels * 2),
        _resolve_act(act, act_kwargs) or (lambda x: x),
        nn.Dropout(dropout),
        nn.Linear(channels * 2, channels),
        nn.Dropout(dropout),
    )
    self.drop = nn.Dropout(dropout)

    norm_kwargs = norm_kwargs or {}
    if norm is not None:
        self.norm1 = _resolve_norm(norm, channels, norm_kwargs)
        self.norm2 = _resolve_norm(norm, channels, norm_kwargs)
        self.norm3 = _resolve_norm(norm, channels, norm_kwargs)
    self.norm_with_batch = _takes_batch(self.get("norm1"))

redraw_projection_matrix

redraw_projection_matrix()

Redraws the random projection of the performer attention (no-op for the multi-head attention).

Source code in mlx_graphs/nn/conv/gps_conv.py
def redraw_projection_matrix(self):
    """Redraws the random projection of the performer attention (no-op
    for the multi-head attention)."""
    if isinstance(self.attn, PerformerAttention):
        self.attn.redraw_projection_matrix()

__call__

__call__(
    edge_index: array,
    node_features: array,
    batch_indices: Optional[array] = None,
    layout: Optional[DenseLayout] = None,
    **kwargs: Any,
) -> array

Computes the forward pass of GPSConv.

Parameters:

Name Type Description Default
edge_index array

Edge index of shape [2, num_edges].

required
node_features array

Node features of shape [num_nodes, channels].

required
batch_indices Optional[array]

Graph of each node, of shape [num_nodes]. Attention is computed within each graph. Default: None (a single graph).

None
layout Optional[DenseLayout]

Optional precomputed dense layout of the nodes per graph (DenseLayout). By default it is computed from batch_indices on the host at every call, which synchronizes with the GPU and prevents mx.compile(). Build it once per batch and share it between layers, e.g. with DenseLayout.from_sizes(batch_indices, num_nodes, num_graphs, max_num_nodes), which needs no synchronization. Default: None

None
**kwargs Any

Additional arguments of the local message passing layer (e.g. edge_features).

{}

Returns:

Type Description
array

The updated node features, of shape [num_nodes, channels].

Source code in mlx_graphs/nn/conv/gps_conv.py
def __call__(
    self,
    edge_index: mx.array,
    node_features: mx.array,
    batch_indices: Optional[mx.array] = None,
    layout: Optional[DenseLayout] = None,
    **kwargs: Any,
) -> mx.array:
    """Computes the forward pass of GPSConv.

    Args:
        edge_index: Edge index of shape ``[2, num_edges]``.
        node_features: Node features of shape ``[num_nodes, channels]``.
        batch_indices: Graph of each node, of shape ``[num_nodes]``.
            Attention is computed within each graph. Default: ``None``
            (a single graph).
        layout: Optional precomputed dense layout of the nodes per graph
            (:class:`~mlx_graphs.nn.aggr.DenseLayout`). By default it is
            computed from ``batch_indices`` on the host at every call,
            which synchronizes with the GPU and prevents
            :func:`mx.compile`. Build it once per batch and share it
            between layers, e.g. with
            ``DenseLayout.from_sizes(batch_indices, num_nodes,
            num_graphs, max_num_nodes)``, which needs no
            synchronization. Default: ``None``
        **kwargs: Additional arguments of the local message passing
            layer (e.g. ``edge_features``).

    Returns:
        The updated node features, of shape ``[num_nodes, channels]``.
    """
    x = node_features
    hs = []
    if self.conv is not None:  # local MPNN
        h = self.conv(edge_index, x, **kwargs)
        h = self.drop(h) + x
        hs.append(self._norm("norm1", h, batch_indices))

    # global attention
    layout = _dense_layout(layout, batch_indices, x.shape[0])
    h = layout.to_dense(x)
    if isinstance(self.attn, MultiheadAttention):
        h = self.attn(h, h, h, key_mask=layout.mask)
    else:
        h = self.attn(h, layout.mask)
    h = self.drop(layout.from_dense(h)) + x
    hs.append(self._norm("norm2", h, batch_indices))

    out = sum(hs[1:], hs[0])
    out = out + self.mlp(out)
    return self._norm("norm3", out, batch_indices)

from mlx_graphs.nn import GPSConv · mlx_graphs/nn/conv/gps_conv.py