Skip to content

SGFormerAttention

SGFormerAttention(
    channels: int,
    heads: int = 1,
    head_channels: Optional[int] = 64,
    qkv_bias: bool = False,
)

Bases: Module

The simple global attention mechanism from the "SGFormer: Simplifying and Empowering Transformers for Large-Graph Representations" paper, as in PyG.

Queries and keys are \(\ell_2\)-normalized and the all-pair attention is computed in linear time:

\[ \mathbf{Z} = \mathrm{diag}^{-1}\left(N + \mathbf{Q} (\mathbf{K}^{\top} \mathbf{1})\right) \left(N \mathbf{V} + \mathbf{Q} (\mathbf{K}^{\top} \mathbf{V})\right) \]

The outputs of the heads are averaged.

Parameters:

Name Type Description Default
channels int

Size of each input sample.

required
heads int

Number of attention heads. Default: 1

1
head_channels Optional[int]

Size of each attention head. Default: 64

64
qkv_bias bool

Whether the query, key and value projections have a bias. Default: False

False

Example:

import mlx.core as mx
from mlx_graphs.nn.attention import SGFormerAttention

attn = SGFormerAttention(channels=16, heads=2, head_channels=8)
x = mx.random.normal((2, 5, 16))
>>> attn(x).shape
(2, 5, 8)

Methods:

Name Description
__call__

Computes the attention.

Source code in mlx_graphs/nn/attention/sgformer.py
def __init__(
    self,
    channels: int,
    heads: int = 1,
    head_channels: Optional[int] = 64,
    qkv_bias: bool = False,
):
    super().__init__()
    if channels % heads != 0:
        raise ValueError("`channels` must be divisible by `heads`")
    if head_channels is None:
        head_channels = channels // heads
    self.heads = heads
    self.head_channels = head_channels
    inner_channels = head_channels * heads
    self.q = nn.Linear(channels, inner_channels, bias=qkv_bias)
    self.k = nn.Linear(channels, inner_channels, bias=qkv_bias)
    self.v = nn.Linear(channels, inner_channels, bias=qkv_bias)

__call__

__call__(x: array, mask: Optional[array] = None) -> array

Computes the attention.

Parameters:

Name Type Description Default
x array

Node features of shape [batch_size, num_nodes, channels].

required
mask Optional[array]

Optional boolean mask of shape [batch_size, num_nodes], True for real nodes.

None

Returns:

Type Description
array

An array of shape [batch_size, num_nodes, head_channels].

Source code in mlx_graphs/nn/attention/sgformer.py
def __call__(self, x: mx.array, mask: Optional[mx.array] = None) -> mx.array:
    """Computes the attention.

    Args:
        x: Node features of shape ``[batch_size, num_nodes, channels]``.
        mask: Optional boolean mask of shape ``[batch_size, num_nodes]``,
            ``True`` for real nodes.

    Returns:
        An array of shape ``[batch_size, num_nodes, head_channels]``.
    """
    B, N = x.shape[:2]
    shape = (B, N, self.heads, self.head_channels)
    qs, ks, vs = (lin(x).reshape(shape) for lin in (self.q, self.k, self.v))
    if mask is not None:
        vs = mx.where(mask[:, :, None, None], vs, 0.0)

    epsilon = 1e-6
    qs = mx.where(qs == 0, epsilon, qs)
    ks = mx.where(ks == 0, epsilon, ks)
    qs = qs / mx.linalg.norm(qs, axis=-1, keepdims=True)
    ks = ks / mx.linalg.norm(ks, axis=-1, keepdims=True)

    # [B, H, M, D]
    kvs = mx.einsum("blhm,blhd->bhmd", ks, vs)
    numerator = mx.einsum("bnhm,bhmd->bnhd", qs, kvs) + N * vs
    ks_sum = ks.sum(axis=1)  # [B, H, M]
    normalizer = mx.einsum("bnhm,bhm->bnh", qs, ks_sum)[..., None] + N
    return (numerator / normalizer).mean(axis=2)

from mlx_graphs.nn.attention import SGFormerAttention · mlx_graphs/nn/attention/sgformer.py