Skip to content

SAGEConv

SAGEConv(
    node_features_dim: Union[int, Tuple[int, int]],
    out_features_dim: int,
    bias: bool = True,
    root_weight: bool = True,
    **kwargs,
)

Bases: MessagePassing

GraphSAGE convolution layer from "Inductive Representation Learning on Large Graphs" paper.

\[ \mathbf{h}_i = \mathbf{W}_1 \mathbf{x}_i + \mathbf{W}_2 \cdot \bigoplus_{j \in \mathcal{N}(i)} \mathbf{x}_j, \]

where \(\mathbf{x}_i\) represents the input features of node \(i\), \(\bigoplus\) denotes the aggregation function, set by default to mean and \(\mathbf{h}_i\) is the computed embedding of node \(i\).

The layer also works on bipartite graphs, where messages flow from one set of nodes to another (e.g. author -> paper in a heterogeneous graph): pass node_features as a (src_features, dst_features) tuple and, if the two sets 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 whose source and destination nodes have different feature sizes

required
out_features_dim int

Size of output node embeddings

required
bias bool

Whether to use bias in the node projection

True
root_weight bool

Whether to add the projection \(\mathbf{W}_1 \mathbf{x}_i\) of the node's own features, as in PyG. Without it, the bias (if any) is added to the neighbor term. Setting conv.root_weight = False after construction, as DirGNNConv does, drops the projection and keeps its bias. Default: True

True
**kwargs

Arguments of MessagePassing, e.g. aggr (default "mean"), which can also be a list of aggregations whose outputs are concatenated, as in PyG (aggr=["mean", "max"])

{}

Example:

import mlx.core as mx
from mlx_graphs.data.data import GraphData
from mlx_graphs.nn import SAGEConv

graph = GraphData(
    edge_index = mx.array([[0, 1, 2, 3, 4], [0, 0, 1, 1, 3]]),
    node_features = mx.ones((5, 16)),
)

conv = SAGEConv(16, 32)
h = conv(graph.edge_index, graph.node_features)

>>> h
array([[1.65429, -0.376169, 1.04172, ..., -0.919106, 1.42576, 0.490938],
    [1.65429, -0.376169, 1.04172, ..., -0.919106, 1.42576, 0.490938],
    [1.05823, -0.295776, 0.075439, ..., -0.104383, 0.031947, -0.351897],
    [1.65429, -0.376169, 1.04172, ..., -0.919106, 1.42576, 0.490938],
    [1.05823, -0.295776, 0.075439, ..., -0.104383, 0.031947, -0.351897]],
    dtype=float32)

# Bipartite: 5 authors (16 features) -> 2 papers (8 features)
conv = SAGEConv((16, 8), 32)
edge_index = mx.array([[0, 1, 4], [0, 0, 1]])  # author -> paper
h_paper = conv(edge_index, (mx.ones((5, 16)), mx.ones((2, 8))))
>>> h_paper.shape
(2, 32)

Methods:

Name Description
__call__

Computes the forward pass of SAGEConv.

Attributes:

Name Type Description
root_weight bool

Whether the projection of the node's own features is added.

Source code in mlx_graphs/nn/conv/sage_conv.py
def __init__(
    self,
    node_features_dim: Union[int, Tuple[int, int]],
    out_features_dim: int,
    bias: bool = True,
    root_weight: bool = True,
    **kwargs,
):
    if isinstance(node_features_dim, int):
        src_dim = dst_dim = node_features_dim
    else:
        src_dim, dst_dim = node_features_dim

    kwargs.setdefault("aggr", "mean")
    if isinstance(kwargs["aggr"], str) and kwargs["aggr"].lower() == "lstm":
        # As in PyG: an LSTM over the neighbor features, of the same size.
        aggr_kwargs = dict(kwargs.get("aggr_kwargs") or {})
        aggr_kwargs.setdefault("node_features_dim", src_dim)
        aggr_kwargs.setdefault("out_features_dim", src_dim)
        kwargs["aggr_kwargs"] = aggr_kwargs
    super(SAGEConv, self).__init__(**kwargs)

    self.node_features_dim = node_features_dim
    self.out_features_dim = out_features_dim
    self.src_features_dim = src_dim
    self.dst_features_dim = dst_dim

    # Size of the aggregated neighbor features: a list of aggregations
    # (e.g. ``aggr=["mean", "max"]``) concatenates their outputs.
    aggr_module = self.get("aggr_module")
    if aggr_module is not None and hasattr(aggr_module, "get_out_features_dim"):
        aggr_dim = aggr_module.get_out_features_dim(src_dim)
    elif isinstance(getattr(aggr_module, "out_features_dim", None), int):
        aggr_dim = aggr_module.out_features_dim  # e.g. an LSTM aggregation
    else:
        aggr_dim = src_dim

    # Neighbor messages come from source nodes, the self term from
    # destination nodes.
    self.neigh_proj = Linear(aggr_dim, out_features_dim, bias=False)
    self.self_proj = Linear(dst_dim, out_features_dim, bias=bias)
    self._root_weight = True
    self.root_weight = root_weight

root_weight property writable

root_weight: bool

Whether the projection of the node's own features is added.

__call__

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

Computes the forward pass of SAGEConv.

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_weights Optional[array]

Edge weights leveraged in message passing. Default: None

None

Returns:

Type Description
array

The computed node embeddings, one row per destination node

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

    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_weights: Edge weights leveraged in message passing. Default: ``None``

    Returns:
        mx.array: The computed node embeddings, one row per destination node
    """
    if isinstance(node_features, tuple):
        src_features, dst_features = node_features
    else:
        src_features = dst_features = node_features

    # We follow DGL's way by applying projection on the smaller feature
    # dimension. This is only exact for aggregations that commute with a
    # linear map (sum, mean), not e.g. for max or min.
    linear_before_mp = (
        self.src_features_dim > self.out_features_dim
        and isinstance(self.aggr, str)
        and self.aggr in ("add", "mean")
        and "aggr_module" not in self
    )

    if linear_before_mp:
        neigh_features = self.propagate(
            edge_index=edge_index,
            node_features=(self.neigh_proj(src_features), dst_features),
            message_kwargs={"edge_weights": edge_weights},
        )
    else:
        neigh_features = self.propagate(
            edge_index=edge_index,
            node_features=(src_features, dst_features),
            message_kwargs={"edge_weights": edge_weights},
        )
        neigh_features = self.neigh_proj(neigh_features)

    if "self_proj" in self:
        return self.self_proj(dst_features) + neigh_features
    if "bias" in self:
        return neigh_features + self.bias
    return neigh_features

from mlx_graphs.nn import SAGEConv · mlx_graphs/nn/conv/sage_conv.py