Skip to content

GATv2Conv

GATv2Conv(
    node_features_dim: Union[int, Tuple[int, int]],
    out_features_dim: int,
    heads: int = 1,
    concat: bool = True,
    bias: bool = True,
    negative_slope: float = 0.2,
    dropout: float = 0.0,
    edge_features_dim: Optional[int] = None,
    add_self_loops: bool = True,
    fill_value: SelfLoopFillValue = "mean",
    **kwargs,
)

Bases: MessagePassing

Graph Attention Network convolution layer with dynamic attention.

Modification of GATConv based off of "How Attentive are Graph Attention Networks?" paper.

The layer also works on bipartite graphs (e.g. author -> paper in a heterogeneous graph): pass node_features as a (src_features, dst_features) tuple and, if the two sides have different feature sizes, node_features_dim as a (src_dim, dst_dim) tuple. The output has one row per destination node.

Parameters:

Name Type Description Default
node_features_dim Union[int, Tuple[int, int]]

Size of input node features, or a (src_dim, dst_dim) tuple for bipartite graphs

required
out_features_dim int

Size of output node embeddings

required
heads int

Number of attention heads

1
concat bool

Whether to use concat of heads or mean reduction

True
bias bool

Whether to use bias in the node projection

True
negative_slope float

Slope for the leaky relu

0.2
dropout float

Probability p for dropout

0.0
edge_features_dim Optional[int]

Size of edge features

None
add_self_loops bool

Whether to add a self-loop to every node, as in PyG (existing self-loops are replaced by it). Not supported on bipartite (src_features, dst_features) inputs. Default: True

True
fill_value SelfLoopFillValue

Edge features of the added self-loops, if edge_features are given: a constant, or the reduction ("mean", "add", "max", "min" or "mul") of the features of the incoming edges of each node. Default: "mean"

'mean'

Example:

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

conv = GATv2Conv(16, 32, heads=2, concat=True)
edge_index = mx.array([[0, 1, 2, 3, 4], [0, 0, 1, 1, 3]])
node_features = mx.random.uniform(low=0, high=1, shape=(5, 16))

h = conv(edge_index, node_features)

>>> h.shape
(5, 64)

Methods:

Name Description
__call__

Computes the forward pass of GATConv.

Source code in mlx_graphs/nn/conv/gatv2_conv.py
def __init__(
    self,
    node_features_dim: Union[int, Tuple[int, int]],
    out_features_dim: int,
    heads: int = 1,
    concat: bool = True,
    bias: bool = True,
    negative_slope: float = 0.2,
    dropout: float = 0.0,
    edge_features_dim: Optional[int] = None,
    add_self_loops: bool = True,
    fill_value: SelfLoopFillValue = "mean",
    **kwargs,
):
    kwargs.setdefault("aggr", "add")
    super(GATv2Conv, self).__init__(**kwargs)

    self.out_features_dim = out_features_dim
    self.heads = heads
    self.concat = concat
    self.negative_slope = negative_slope
    # read by to_hetero, which rejects self-loops on bipartite edge types
    self._add_self_loops = add_self_loops
    self.fill_value = fill_value

    # Weights
    if isinstance(node_features_dim, int):
        src_dim = dst_dim = node_features_dim
    else:
        src_dim, dst_dim = node_features_dim
    self.W_src = Linear(src_dim, heads * out_features_dim, bias=False)
    self.W_dst = Linear(dst_dim, heads * out_features_dim, bias=False)

    # Attention is applied in message() during message passing stage.
    self.att = glorot((1, heads, out_features_dim))

    if bias:
        bias_shape = (heads * out_features_dim) if concat else (out_features_dim)
        self.bias = mx.zeros(bias_shape)

    if dropout > 0.0:
        self.dropout = nn.Dropout(dropout)

    if edge_features_dim is not None:
        self.edge_lin_proj = Linear(
            edge_features_dim, heads * out_features_dim, bias=False
        )
        self.edge_att = glorot((1, heads, out_features_dim))

__call__

__call__(
    edge_index: array,
    node_features: Union[array, Tuple[array, array]],
    edge_features: Optional[array] = None,
) -> array

Computes the forward pass of GATConv.

Parameters:

Name Type Description Default
edge_index array

input edge index of shape [2, num_edges]

required
node_features Union[array, Tuple[array, array]]

input node features, or a (src_features, dst_features) tuple for bipartite graphs

required
edge_features Optional[array]

edge features

None

Returns:

Type Description
array

computed node embeddings

Source code in mlx_graphs/nn/conv/gatv2_conv.py
def __call__(
    self,
    edge_index: mx.array,
    node_features: Union[mx.array, Tuple[mx.array, mx.array]],
    edge_features: Optional[mx.array] = None,
) -> mx.array:
    """Computes the forward pass of GATConv.

    Args:
        edge_index: input edge index of shape `[2, num_edges]`
        node_features: input node features, or a ``(src_features,
            dst_features)`` tuple for bipartite graphs
        edge_features: edge features

    Returns:
        mx.array: computed node embeddings
    """
    H, C = self.heads, self.out_features_dim

    if isinstance(node_features, tuple):
        src_x, dst_x = node_features
    else:
        src_x = dst_x = node_features
    if self._add_self_loops:
        if dst_x is not src_x:
            raise ValueError(
                f"{type(self).__name__} cannot add self-loops on a bipartite "
                "graph ((src_features, dst_features) input): set "
                "add_self_loops=False."
            )
        edge_index, edge_features, removed_loops = attention_self_loops(
            edge_index, src_x.shape[0], edge_features, self.fill_value
        )
    src_feats = self.W_src(src_x).reshape(-1, H, C)
    dst_feats = self.W_dst(dst_x).reshape(-1, H, C)

    edge_feats = (
        self._compute_edge_features(edge_features)
        if edge_features is not None
        else None
    )
    # Tie the Metal score path to the existing fused message-passing mode.
    score = (
        gatv2_edge_scores
        if self._can_fuse(edge_index, src_feats, None, None)
        else _reference_scores
    )
    alpha = score(
        src_feats, dst_feats, self.att, edge_index, self.negative_slope, edge_feats
    )
    if self._add_self_loops:
        # the input self-loops are replaced by the added ones
        alpha = mx.where(removed_loops[:, None], -float("inf"), alpha)
    node_features = self._softmax_aggregate(
        edge_index=edge_index,
        logits=alpha,
        node_features=(src_feats, dst_feats),
        dropout=self.dropout if "dropout" in self else None,
    )

    if self.concat:
        node_features = node_features.reshape(
            -1, self.heads * self.out_features_dim
        )
    else:
        node_features = mx.mean(node_features, axis=1)

    if "bias" in self:
        node_features = node_features + self.bias

    return node_features

from mlx_graphs.nn import GATv2Conv · mlx_graphs/nn/conv/gatv2_conv.py