Skip to content

MessagePassing

MessagePassing(
    aggr: Union[ScatterAggregations, List[Union[str, Any]], Any] = "add",
    aggr_kwargs: Optional[Dict[str, Any]] = None,
)

Bases: Module

Base class for creating Message Passing Neural Networks (MPNNs) [1].

Inherit this class to build arbitrary GNN models based on the message passing paradigm. This implementation is inspired from PyTorch Geometric [2].

Parameters:

Name Type Description Default
aggr Union[ScatterAggregations, List[Union[str, Any]], Any]

Aggregation strategy used to aggregate messages. Either:

  • a reduction of scatter(): "add" (or "sum"), "mean", "max", "min", "mul", "var", "std" or "median". These use scatter() directly, and the fused SpMM kernels for "add", "mean", "max" and "min";
  • an Aggregation instance, or the name of one (e.g. "softmax", "powermean" or "lstm"), stored in self.aggr_module. As in PyG, "softmax" is SoftmaxAggregation (one output per node), not the per-message normalization of scatter(..., "softmax"). A name given with aggr_kwargs (even a scatter reduction) also builds its aggregation module, with these arguments;
  • a list of names and/or aggregations, combined with MultiAggregation (concatenated along the last axis by default), stored in self.aggr_module. As in PyG, only layers built for it accept concatenated aggregations (supports_concat_aggr, e.g. SAGEConv and GENConv, which size their projection accordingly, or layers without a projection after aggregating); the others raise a ValueError, and accept a list combined without changing the size (aggr_kwargs={"mode": "sum"}).

Default: "add"

'add'
aggr_kwargs Optional[Dict[str, Any]]

Arguments used to build the aggregation module from a name or a list (e.g. {"mode": "sum"} for a list). Default: None

None

Methods:

Name Description
propagate

Computes messages from neighbors, aggregates them and updates

message_and_aggregate

Fused message + aggregate as one sparse x dense matmul.

message

Computes messages between connected nodes.

aggregate

Aggregates the messages using the self.aggr strategy, or

update_nodes

Updates the final embeddings given the aggregated messages.

Source code in mlx_graphs/nn/message_passing.py
def __init__(
    self,
    aggr: Union[ScatterAggregations, List[Union[str, Any]], Any] = "add",
    aggr_kwargs: Optional[Dict[str, Any]] = None,
):
    super().__init__()
    if aggr == "sum":  # PyG's name of "add"
        aggr = "add"
    if (
        isinstance(aggr, str)
        and aggr in get_args(ScatterAggregations)
        # scatter's "softmax" normalizes the messages (one output per
        # edge): as an aggregation it means SoftmaxAggregation, as in PyG.
        and aggr != "softmax"
        # arguments are only taken by aggregation modules
        and not aggr_kwargs
    ):
        # Plain reductions go straight to `scatter` (and to the fused
        # kernels when possible), without an aggregation module.
        self.aggr = aggr
    else:
        from mlx_graphs.nn.aggr import Aggregation, MultiAggregation
        from mlx_graphs.nn.aggr.resolver import aggregation_resolver

        if isinstance(aggr, (list, tuple)):
            self.aggr_module = MultiAggregation(list(aggr), **(aggr_kwargs or {}))
            self.aggr = [str(a) for a in aggr]
            module = self.aggr_module
            if (
                not self.supports_concat_aggr
                and module.mode == "cat"
                and len(module.aggrs) > 1
            ):
                raise ValueError(
                    f"{type(self).__name__} does not support a list of "
                    "aggregations whose outputs are concatenated: its "
                    "layers expect the size of one aggregation (as in "
                    "PyG). Combine them without changing the size, e.g. "
                    "aggr_kwargs={'mode': 'sum'} ('mean', 'max', ...), or "
                    "use a layer that supports it, such as SAGEConv or "
                    "GENConv."
                )
        elif isinstance(aggr, (str, Aggregation)):
            try:
                self.aggr_module = aggregation_resolver(aggr, **(aggr_kwargs or {}))
            except ValueError:
                raise ValueError(
                    "Invalid aggregation function.",
                    f"Available values are {get_args(ScatterAggregations)}, "
                    "a list of them, or an Aggregation",
                ) from None
            self.aggr = str(aggr)
        else:
            raise ValueError(
                "Invalid aggregation function.",
                f"Available values are {get_args(ScatterAggregations)}, "
                f"a list of them, or an Aggregation (got {type(aggr).__name__})",
            )
    self.num_nodes = None

propagate

propagate(
    edge_index: array,
    node_features: Union[array, Tuple[array, array]],
    message_kwargs: Optional[Dict] = None,
    aggregate_kwargs: Optional[Dict] = None,
    update_kwargs: Optional[Dict] = None,
) -> array

Computes messages from neighbors, aggregates them and updates the final node embeddings.

Parameters:

Name Type Description Default
edge_index array

Graph representation of shape [2, num_edges]

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

Input node features/embeddings. Can be either an array or a tuple of arrays, for distinct src and dst node features. With a tuple (src, dst), edge_index[0] indexes src and edge_index[1] indexes dst, and the output has one row per dst node.

required
message_kwargs Optional[Dict]

Arguments to pass to the message method

None
aggregate_kwargs Optional[Dict]

Arguments to pass to the aggregate method

None
update_kwargs Optional[Dict]

Arguments to pass to the update_nodes method

None
Source code in mlx_graphs/nn/message_passing.py
def propagate(
    self,
    edge_index: mx.array,
    node_features: Union[mx.array, Tuple[mx.array, mx.array]],
    message_kwargs: Optional[Dict] = None,
    aggregate_kwargs: Optional[Dict] = None,
    update_kwargs: Optional[Dict] = None,
) -> mx.array:
    """Computes messages from neighbors, aggregates them and updates
    the final node embeddings.

    Args:
        edge_index: Graph representation of shape `[2, num_edges]`
        node_features: Input node features/embeddings.
            Can be either an array or a tuple of arrays, for distinct src and dst
            node features. With a tuple ``(src, dst)``, ``edge_index[0]``
            indexes ``src`` and ``edge_index[1]`` indexes ``dst``, and the
            output has one row per ``dst`` node.
        message_kwargs: Arguments to pass to the `message` method
        aggregate_kwargs: Arguments to pass to the `aggregate` method
        update_kwargs: Arguments to pass to the `update_nodes` method
    """
    message_kwargs = message_kwargs or {}
    aggregate_kwargs = aggregate_kwargs or {}
    update_kwargs = update_kwargs or {}
    if not (isinstance(edge_index, mx.array) and edge_index.shape[0] == 2):
        raise ValueError("Edge index should be an array with shape (2, |E|)")
    if isinstance(node_features, tuple):
        if len(node_features) != 2 or not all(
            isinstance(array, mx.array) for array in node_features
        ):
            raise ValueError(
                "Invalid shape for `node_features`, should be a tuple of 2 mx.array"
            )
    else:
        if not isinstance(node_features, mx.array):
            raise ValueError(
                "Invalid shape for `node_features`, should be an `mx.array`,",
                f"found {type(node_features)}",
            )

    # Messages are aggregated onto destination nodes, so the output has one
    # row per destination node. For a (src, dst) tuple (bipartite graphs,
    # e.g. author -> paper) that is the size of the dst features.
    self.num_nodes = (
        node_features if isinstance(node_features, mx.array) else node_features[1]
    ).shape[0]

    if self._can_fuse(edge_index, node_features, message_kwargs, aggregate_kwargs):
        # shapes: (|N| -> |N|), no per-edge message array
        aggregated = self.message_and_aggregate(
            edge_index=edge_index,
            node_features=node_features,
            **message_kwargs,
        )
        return self.update_nodes(aggregated=aggregated, **update_kwargs)

    src_features, dst_features = get_src_dst_features(edge_index, node_features)
    dst_idx = edge_index[1]

    # shapes: (|E| -> |E|)
    messages = self.message(
        src_features=src_features,
        dst_features=dst_features,
        **message_kwargs,
    )

    # shapes: (|E| -> |N|)
    aggregated = self.aggregate(
        messages=messages,
        indices=dst_idx,
        **aggregate_kwargs,
    )

    # shapes: (|N| -> |N|)
    output = self.update_nodes(
        aggregated=aggregated,
        **update_kwargs,
    )

    return output

message_and_aggregate

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

Fused message + aggregate as one sparse x dense matmul.

Computes, for every node i, aggr_{j -> i} edge_weights[j -> i] * x_j (aggr = add, mean, max or min, per feature; 0 for nodes without neighbours), the same result as the default message() followed by aggregate(), without building the per-edge message array. Used by layers decorated with fused_message_passing(); override it to provide a custom fused implementation.

Parameters:

Name Type Description Default
edge_index array

Graph representation of shape [2, num_edges]

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

Node features, or a (src, dst) tuple (only the source features are used).

required
edge_weights Optional[array]

Optional weights: one scalar per edge, or, for multi-head features of shape [num_nodes, heads, channels], an array of shape [num_edges, heads] with one scalar per edge and head (e.g. attention coefficients).

None
Source code in mlx_graphs/nn/message_passing.py
def message_and_aggregate(
    self,
    edge_index: mx.array,
    node_features: Union[mx.array, Tuple[mx.array, mx.array]],
    edge_weights: Optional[mx.array] = None,
    **kwargs,
) -> mx.array:
    """Fused ``message`` + ``aggregate`` as one sparse x dense matmul.

    Computes, for every node ``i``,
    ``aggr_{j -> i} edge_weights[j -> i] * x_j`` (``aggr`` = add, mean,
    max or min, per feature; 0 for nodes without neighbours), the same
    result as the
    default :meth:`message` followed by :meth:`aggregate`, without
    building the per-edge message array. Used by layers decorated with
    :func:`fused_message_passing`; override it to provide a custom fused
    implementation.

    Args:
        edge_index: Graph representation of shape `[2, num_edges]`
        node_features: Node features, or a ``(src, dst)`` tuple
            (only the source features are used).
        edge_weights: Optional weights: one scalar per edge, or, for
            multi-head features of shape ``[num_nodes, heads, channels]``,
            an array of shape ``[num_edges, heads]`` with one scalar per
            edge and head (e.g. attention coefficients).
    """
    x = node_features[0] if isinstance(node_features, tuple) else node_features
    weights = edge_weights
    if weights is not None and weights.size == edge_index.shape[1]:
        weights = weights.reshape(-1)  # one scalar per edge
    if self.aggr in ("max", "min"):
        return self._fused_extremum(edge_index, x, weights)
    return self._fused_spmm(edge_index, x, weights)

message

message(src_features: array, dst_features: array, **kwargs) -> array

Computes messages between connected nodes.

By default, returns the features of source nodes. Optional edge_weights can be directly integrated in kwargs

Parameters:

Name Type Description Default
src_features array

Source node embeddings

required
dst_features array

Destination node embeddings

required
edge_weights

Array of scalars with shape (num_edges,) or (num_edges, 1) used to weigh neighbor features during aggregation. For multi-head source features of shape (num_edges, heads, channels), an array of shape (num_edges, heads) weighs each head separately. Default: None

required
**kwargs

Optional args to compute messages

{}
Source code in mlx_graphs/nn/message_passing.py
def message(
    self, src_features: mx.array, dst_features: mx.array, **kwargs
) -> mx.array:
    """Computes messages between connected nodes.

    By default, returns the features of source nodes.
    Optional ``edge_weights`` can be directly integrated in ``kwargs``

    Args:
        src_features: Source node embeddings
        dst_features: Destination node embeddings
        edge_weights: Array of scalars with shape (num_edges,) or (num_edges, 1)
            used to weigh neighbor features during aggregation. For
            multi-head source features of shape (num_edges, heads, channels),
            an array of shape (num_edges, heads) weighs each head separately.
            Default: ``None``
        **kwargs: Optional args to compute messages
    """
    edge_weights = kwargs.get("edge_weights", None)
    if edge_weights is None:
        return src_features
    if edge_weights.size == src_features.shape[0]:
        # one scalar per edge, broadcast over all feature axes
        shape = (-1,) + (1,) * (src_features.ndim - 1)
        return edge_weights.reshape(shape) * src_features
    # one scalar per edge and head
    shape = edge_weights.shape + (1,) * (src_features.ndim - edge_weights.ndim)
    return edge_weights.reshape(shape) * src_features

aggregate

aggregate(messages: array, indices: array, **kwargs) -> array

Aggregates the messages using the self.aggr strategy, or self.aggr_module when aggr is a list or an aggregation module.

Parameters:

Name Type Description Default
messages array

Computed messages

required
indices array

Indices representing the nodes that receive messages

required
**kwargs

Optional args to aggregate messages

{}
Source code in mlx_graphs/nn/message_passing.py
def aggregate(self, messages: mx.array, indices: mx.array, **kwargs) -> mx.array:
    """Aggregates the messages using the `self.aggr` strategy, or
    `self.aggr_module` when `aggr` is a list or an aggregation module.

    Args:
        messages: Computed messages
        indices: Indices representing the nodes that receive messages
        **kwargs: Optional args to aggregate messages
    """
    if isinstance(self.aggr, str) and "aggr_module" not in self:
        return scatter(messages, indices, self.num_nodes, self.aggr)
    return self.aggr_module(messages, indices, dim_size=self.num_nodes)

update_nodes

update_nodes(aggregated: array, **kwargs) -> array

Updates the final embeddings given the aggregated messages.

Parameters:

Name Type Description Default
aggregated array

aggregated messages

required
**kwargs

optional args to update messages

{}
Source code in mlx_graphs/nn/message_passing.py
def update_nodes(self, aggregated: mx.array, **kwargs) -> mx.array:
    """Updates the final embeddings given the aggregated messages.

    Args:
        aggregated: aggregated messages
        **kwargs: optional args to update messages
    """
    return aggregated

from mlx_graphs.nn import MessagePassing · mlx_graphs/nn/message_passing.py