Skip to content

SGFormer

SGFormer(
    node_features_dim: int,
    hidden_features_dim: int,
    out_features_dim: int,
    trans_num_layers: int = 2,
    trans_num_heads: int = 1,
    trans_dropout: float = 0.5,
    gnn_num_layers: int = 3,
    gnn_dropout: float = 0.5,
    graph_weight: float = 0.5,
    aggregate: str = "add",
)

Bases: Module

The SGFormer model from the "SGFormer: Simplifying and Empowering Transformers for Large-Graph Representations" paper, as PyG's SGFormer.

A single-layer-style linear global attention branch (SGFormerAttention) and a GCN branch are combined, then a linear layer and a log-softmax give per-node class log-probabilities.

Note

As in PyG, the global attention runs on the zero-padded dense batch of each graph, so the padding nodes take part in the attention normalizer.

Parameters:

Name Type Description Default
node_features_dim int

Size of the input node features.

required
hidden_features_dim int

Size of the hidden node embeddings.

required
out_features_dim int

Number of classes.

required
trans_num_layers int

Number of global attention layers. Default: 2

2
trans_num_heads int

Number of attention heads. Default: 1

1
trans_dropout float

Dropout probability of the attention branch. Default: 0.5

0.5
gnn_num_layers int

Number of GCN layers. Default: 3

3
gnn_dropout float

Dropout probability of the GCN branch. Default: 0.5

0.5
graph_weight float

Weight of the GCN branch when aggregate="add" (the attention branch gets 1 - graph_weight). Default: 0.5

0.5
aggregate str

How the branches are combined: "add" (weighted sum) or "cat" (concatenation). Default: "add"

'add'

Example:

import mlx.core as mx
from mlx_graphs.nn import SGFormer

model = SGFormer(16, 32, 4)
edge_index = mx.array([[0, 1, 1, 2], [1, 0, 2, 1]])
node_features = mx.random.normal((3, 16))
>>> model(edge_index, node_features).shape
(3, 4)

Methods:

Name Description
__call__

Computes the class log-probabilities of the nodes.

Source code in mlx_graphs/nn/models/graph_transformers.py
def __init__(
    self,
    node_features_dim: int,
    hidden_features_dim: int,
    out_features_dim: int,
    trans_num_layers: int = 2,
    trans_num_heads: int = 1,
    trans_dropout: float = 0.5,
    gnn_num_layers: int = 3,
    gnn_dropout: float = 0.5,
    graph_weight: float = 0.5,
    aggregate: str = "add",
):
    super().__init__()
    self.trans_conv = _SGFormerTransModule(
        node_features_dim,
        hidden_features_dim,
        trans_num_layers,
        trans_num_heads,
        trans_dropout,
    )
    self.graph_conv = _SGFormerGraphModule(
        node_features_dim, hidden_features_dim, gnn_num_layers, gnn_dropout
    )
    self.graph_weight = graph_weight
    self.aggregate = aggregate
    if aggregate == "add":
        self.fc = nn.Linear(hidden_features_dim, out_features_dim)
    elif aggregate == "cat":
        self.fc = nn.Linear(2 * hidden_features_dim, out_features_dim)
    else:
        raise ValueError(f"Invalid aggregate type: {aggregate}")
    self.out_features_dim = out_features_dim

__call__

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

Computes the class log-probabilities of the nodes.

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, node_features_dim].

required
batch_indices Optional[array]

Graph of each node; 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), to avoid computing it on the host at every call (a GPU synchronization that also prevents mx.compile()), e.g. DenseLayout.from_sizes(batch_indices, num_nodes, num_graphs, max_num_nodes). Default: None

None

Returns:

Type Description
array

Log-probabilities of shape [num_nodes, out_features_dim].

Source code in mlx_graphs/nn/models/graph_transformers.py
def __call__(
    self,
    edge_index: mx.array,
    node_features: mx.array,
    batch_indices: Optional[mx.array] = None,
    layout: Optional[DenseLayout] = None,
) -> mx.array:
    """Computes the class log-probabilities of the nodes.

    Args:
        edge_index: Edge index of shape ``[2, num_edges]``.
        node_features: Node features of shape
            ``[num_nodes, node_features_dim]``.
        batch_indices: Graph of each node; 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`), to avoid
            computing it on the host at every call (a GPU
            synchronization that also prevents :func:`mx.compile`), e.g.
            ``DenseLayout.from_sizes(batch_indices, num_nodes,
            num_graphs, max_num_nodes)``. Default: ``None``

    Returns:
        Log-probabilities of shape ``[num_nodes, out_features_dim]``.
    """
    x1 = self.trans_conv(node_features, batch_indices, layout)
    x2 = self.graph_conv(edge_index, node_features)
    if self.aggregate == "add":
        x = self.graph_weight * x2 + (1 - self.graph_weight) * x1
    else:
        x = mx.concatenate([x1, x2], axis=1)
    return nn.log_softmax(self.fc(x), axis=-1)

from mlx_graphs.nn import SGFormer · mlx_graphs/nn/models/graph_transformers.py