Skip to content

Polynormer

Polynormer(
    node_features_dim: int,
    hidden_features_dim: int,
    out_features_dim: int,
    local_layers: int = 7,
    global_layers: int = 2,
    in_dropout: float = 0.15,
    dropout: float = 0.5,
    global_dropout: float = 0.5,
    heads: int = 1,
    beta: float = 0.9,
    qk_shared: bool = False,
    pre_ln: bool = False,
    post_bn: bool = True,
    local_attn: bool = False,
)

Bases: Module

The Polynormer model from the "Polynormer: Polynomial-Expressive Graph Transformer in Linear Time" paper, as PyG's Polynormer.

A stack of local (GCN or GAT based) polynomial layers is followed, once _global is set to True (usually after some warm-up epochs, as in the paper), by global linear attention layers (PolynormerAttention). The output is a per-node log-softmax.

Note

Unlike PyG 2.8, the global attention layers take heads * hidden_features_dim input features, so that heads > 1 also works with _global = True (identical for heads = 1).

Parameters:

Name Type Description Default
node_features_dim int

Size of the input node features.

required
hidden_features_dim int

Size of the hidden embeddings of each head.

required
out_features_dim int

Number of classes.

required
local_layers int

Number of local layers. Default: 7

7
global_layers int

Number of global attention layers. Default: 2

2
in_dropout float

Dropout probability of the input. Default: 0.15

0.15
dropout float

Dropout probability of the local layers. Default: 0.5

0.5
global_dropout float

Dropout probability of the global layers. Default: 0.5

0.5
heads int

Number of heads. Default: 1

1
beta float

Polynormer \(\beta\). Default: 0.9

0.9
qk_shared bool

Whether queries and keys share their weights in the global attention. Default: False

False
pre_ln bool

Whether to apply a layer norm before each local layer. Default: False

False
post_bn bool

Whether to apply a batch norm after each local layer. Default: True

True
local_attn bool

Whether the local layers use GATConv (True) or GCNConv (False). Default: False

False

Example:

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

model = Polynormer(16, 32, 4, local_layers=2, global_layers=1)
model._global = True  # enable the global attention layers
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,
    local_layers: int = 7,
    global_layers: int = 2,
    in_dropout: float = 0.15,
    dropout: float = 0.5,
    global_dropout: float = 0.5,
    heads: int = 1,
    beta: float = 0.9,
    qk_shared: bool = False,
    pre_ln: bool = False,
    post_bn: bool = True,
    local_attn: bool = False,
):
    super().__init__()
    self._global = False
    self.pre_ln = pre_ln
    self.post_bn = post_bn
    self.beta = beta
    self.in_drop = nn.Dropout(in_dropout)
    self.drop = nn.Dropout(dropout)

    inner = heads * hidden_features_dim
    dims_in = [node_features_dim] + [inner] * (local_layers - 1)
    self.h_lins = [nn.Linear(d, inner) for d in dims_in]
    if local_attn:
        self.local_convs = [
            GATConv(
                d,
                hidden_features_dim,
                heads=heads,
                concat=True,
                bias=False,
                add_self_loops=False,  # as in PyG's Polynormer
            )
            for d in dims_in
        ]
    else:
        self.local_convs = [GCNConv(d, inner, add_self_loops=True) for d in dims_in]
    self.lins = [nn.Linear(d, inner) for d in dims_in]
    self.lns = [nn.LayerNorm(inner) for _ in dims_in]
    if pre_ln:
        self.pre_lns = [nn.LayerNorm(d) for d in dims_in]
    if post_bn:
        self.post_bns = [nn.BatchNorm(inner) for _ in dims_in]

    self.lin_in = nn.Linear(node_features_dim, inner)
    self.ln = nn.LayerNorm(inner)
    self.global_attn = [
        PolynormerAttention(
            # PyG passes `hidden_channels` here, which only works with
            # `heads=1` (the input has `heads * hidden_channels` features).
            channels=inner,
            heads=heads,
            head_channels=hidden_features_dim,
            beta=beta,
            dropout=global_dropout,
            qk_shared=qk_shared,
        )
        for _ in range(global_layers)
    ]
    self.pred_local = nn.Linear(inner, out_features_dim)
    self.pred_global = nn.Linear(inner, 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; the global attention is computed within each graph. Default: None (one 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; the global attention is
            computed within each graph. Default: ``None`` (one 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]``.
    """
    x = self.in_drop(node_features)
    x_local: Union[int, mx.array] = 0
    for i, local_conv in enumerate(self.local_convs):
        if self.pre_ln:
            x = self.pre_lns[i](x)
        h = nn.relu(self.h_lins[i](x))
        x = local_conv(edge_index, x) + self.lins[i](x)
        if self.post_bn:
            x = self.post_bns[i](x)
        x = self.drop(nn.relu(x))
        x = (1 - self.beta) * self.lns[i](h * x) + self.beta * x
        x_local = x_local + x

    if self._global:
        layout = _dense_layout(layout, batch_indices, x_local.shape[0])
        x_global = layout.to_dense(self.ln(x_local))
        for attn in self.global_attn:
            x_global = attn(x_global, layout.mask)
        x = self.pred_global(layout.from_dense(x_global))
    else:
        x = self.pred_local(x_local)
    return nn.log_softmax(x, axis=-1)

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