Skip to content

MultiheadAttentionBlock

MultiheadAttentionBlock(
    channels: int, heads: int = 1, layer_norm: bool = True, dropout: float = 0.0
)

Bases: Module

The Multihead Attention Block (MAB) from the "Set Transformer: A Framework for Attention-based Permutation-Invariant Neural Networks" paper, as in PyG.

\[ \mathrm{MAB}(\mathbf{x}, \mathbf{y}) &= \mathrm{LayerNorm}(\mathbf{h} + \mathrm{ReLU}(\mathbf{h}\mathbf{W})) \\ \mathbf{h} &= \mathrm{LayerNorm}(\mathbf{x} + \mathrm{Multihead}(\mathbf{x}, \mathbf{y}, \mathbf{y})) \]

Parameters:

Name Type Description Default
channels int

Size of each input sample.

required
heads int

Number of attention heads. Default: 1

1
layer_norm bool

Whether to apply layer normalization. Default: True

True
dropout float

Dropout probability of the attention weights. Default: 0.0

0.0

Methods:

Name Description
__call__

Attends from x ([B, N, channels]) to y (`[B, M,

Source code in mlx_graphs/nn/aggr/utils.py
def __init__(
    self,
    channels: int,
    heads: int = 1,
    layer_norm: bool = True,
    dropout: float = 0.0,
):
    super().__init__()
    self.channels = channels
    self.heads = heads
    self.dropout = dropout
    self.attn = MultiheadAttention(channels, heads, dropout=dropout)
    self.lin = nn.Linear(channels, channels)
    self.layer_norm = layer_norm
    if layer_norm:
        self.layer_norm1 = nn.LayerNorm(channels)
        self.layer_norm2 = nn.LayerNorm(channels)

__call__

__call__(
    x: array,
    y: array,
    x_mask: Optional[array] = None,
    y_mask: Optional[array] = None,
) -> array

Attends from x ([B, N, channels]) to y ([B, M, channels]); x_mask and y_mask are True for real rows.

Source code in mlx_graphs/nn/aggr/utils.py
def __call__(
    self,
    x: mx.array,
    y: mx.array,
    x_mask: Optional[mx.array] = None,
    y_mask: Optional[mx.array] = None,
) -> mx.array:
    """Attends from ``x`` (``[B, N, channels]``) to ``y`` (``[B, M,
    channels]``); ``x_mask`` and ``y_mask`` are ``True`` for real rows."""
    out = self.attn(x, y, y, key_mask=y_mask)
    if x_mask is not None:
        out = mx.where(x_mask[..., None], out, 0.0)
    out = out + x
    if self.layer_norm:
        out = self.layer_norm1(out)
    out = out + nn.relu(self.lin(out))
    if self.layer_norm:
        out = self.layer_norm2(out)
    return out

from mlx_graphs.nn.aggr import MultiheadAttentionBlock · mlx_graphs/nn/aggr/utils.py