Skip to content

PerformerAttention

PerformerAttention(
    channels: int,
    heads: int,
    head_channels: Optional[int] = 64,
    kernel: Callable[[array], array] = relu,
    qkv_bias: bool = False,
    attn_out_bias: bool = True,
    dropout: float = 0.0,
)

Bases: Module

The linear scaled attention mechanism from the "Rethinking Attention with Performers" paper, as in PyG.

Queries and keys are mapped by a fixed random orthogonal projection followed by kernel (plus \(10^{-3}\)), which makes the attention linear in the number of nodes. The projection matrix is a frozen parameter that can be redrawn with redraw_projection_matrix().

Parameters:

Name Type Description Default
channels int

Size of each input sample.

required
heads int

Number of attention heads.

required
head_channels Optional[int]

Size of each attention head. Default: 64

64
kernel Callable[[array], array]

Kernel of the generalized attention. Default: nn.relu

relu
qkv_bias bool

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

False
attn_out_bias bool

Whether the output projection has a bias. Default: True

True
dropout float

Dropout probability of the attention output. Default: 0.0

0.0

Example:

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

attn = PerformerAttention(channels=16, heads=2, head_channels=8)
x = mx.random.normal((2, 5, 16))
mask = mx.ones((2, 5), dtype=mx.bool_)
>>> attn(x, mask).shape
(2, 5, 16)

Methods:

Name Description
redraw_projection_matrix

Draws a new random projection matrix, as recommended in the paper

__call__

Computes the attention.

Source code in mlx_graphs/nn/attention/performer.py
def __init__(
    self,
    channels: int,
    heads: int,
    head_channels: Optional[int] = 64,
    kernel: Callable[[mx.array], mx.array] = nn.relu,
    qkv_bias: bool = False,
    attn_out_bias: bool = True,
    dropout: float = 0.0,
):
    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
    self.kernel = kernel
    self.num_rows = int(head_channels * math.log(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)
    self.attn_out = nn.Linear(inner_channels, channels, bias=attn_out_bias)
    self.dropout = nn.Dropout(dropout)
    self.projection_matrix = orthogonal_matrix(self.num_rows, head_channels)
    self.freeze(keys=["projection_matrix"], recurse=False)

redraw_projection_matrix

redraw_projection_matrix()

Draws a new random projection matrix, as recommended in the paper to improve the approximation of the attention.

Source code in mlx_graphs/nn/attention/performer.py
def redraw_projection_matrix(self):
    """Draws a new random projection matrix, as recommended in the paper
    to improve the approximation of the attention."""
    self.projection_matrix = orthogonal_matrix(self.num_rows, self.head_channels)

__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] (e.g. from to_dense_batch()).

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

Source code in mlx_graphs/nn/attention/performer.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]``
            (e.g. from :func:`~mlx_graphs.utils.to_dense_batch`).
        mask: Optional boolean mask of shape ``[batch_size, num_nodes]``,
            ``True`` for real nodes.

    Returns:
        An array of shape ``[batch_size, num_nodes, channels]``.
    """
    B, N = x.shape[:2]

    def split(t):
        return t.reshape(B, N, self.heads, self.head_channels).transpose(0, 2, 1, 3)

    q, k, v = split(self.q(x)), split(self.k(x)), split(self.v(x))
    if mask is not None:
        v = mx.where(mask[:, None, :, None], v, 0.0)
    out = linear_attention(self._feature_map(q), self._feature_map(k), v)
    out = out.transpose(0, 2, 1, 3).reshape(B, N, -1)
    return self.dropout(self.attn_out(out))

from mlx_graphs.nn.attention import PerformerAttention · mlx_graphs/nn/attention/performer.py