Skip to content

fused_message_passing

fused_message_passing(
    cls=None,
    *,
    format: FusedFormat = "auto",
    allow_message_override: bool = False,
)

Class decorator: lets a MessagePassing layer fuse message and aggregate into a single sparse x dense matmul (SpMM).

With the decorator, MessagePassing.propagate() calls MessagePassing.message_and_aggregate() instead of gathering one message per edge and scattering them. This never materialises the [num_edges, features] message array, which is what limits gather-scatter on large graphs.

The fused path is used only when it gives the same result; otherwise the layer silently falls back to gather-scatter. It falls back when:

  • mlx_cluster (with spmm_coo) is not installed,
  • fused message passing is disabled (set_fused_message_passing()),
  • aggr is not "add", "mean", "max" or "min" (i.e. it is a list or an aggregation module; max/min also need a recent mlx-cluster),
  • any message/aggregate kwarg other than edge_weights is set (e.g. edge_features), since messages are then no longer a weighted sum of neighbour features,
  • the layer is a subclass of a decorated layer that overrides message() or aggregate() without also overriding message_and_aggregate().

Parameters:

Name Type Description Default
format FusedFormat

"coo" works directly on edge_index. "csr" sorts the graph once (cached per edge_index) and uses a faster, deterministic, atomic-free kernel. "auto" (default) starts with "coo" and switches to "csr" when the sort pays off: immediately for graphs with at least a million edges, and once the same edge_index array has been used a few times otherwise (e.g. full-batch training).

'auto'
allow_message_override bool

a layer that overrides message() or aggregate() is rejected by default, because the fused kernel would ignore those overrides. Pass True only if the override reduces to the default edge_weights * x_j / scatter whenever the extra kwargs are None (e.g. GINConv).

False

Note

Cached conversions are looked up by the identity of the edge_index array. Build a new array instead of modifying an edge_index in place (edge_index[0, 3] = 5) between calls, or call clear_csr_cache() after doing so.

@fused_message_passing
class MyConv(MessagePassing):
    ...


@fused_message_passing(format="csr")
class MyOtherConv(MessagePassing):
    ...
Source code in mlx_graphs/nn/message_passing.py
def fused_message_passing(
    cls=None,
    *,
    format: FusedFormat = "auto",
    allow_message_override: bool = False,
):
    """Class decorator: lets a :class:`MessagePassing` layer fuse ``message``
    and ``aggregate`` into a single sparse x dense matmul (SpMM).

    With the decorator, :meth:`MessagePassing.propagate` calls
    :meth:`MessagePassing.message_and_aggregate` instead of gathering one
    message per edge and scattering them. This never materialises the
    ``[num_edges, features]`` message array, which is what limits
    gather-scatter on large graphs.

    The fused path is used only when it gives the same result; otherwise the
    layer silently falls back to gather-scatter. It falls back when:

    * ``mlx_cluster`` (with ``spmm_coo``) is not installed,
    * fused message passing is disabled (:func:`set_fused_message_passing`),
    * ``aggr`` is not ``"add"``, ``"mean"``, ``"max"`` or ``"min"`` (i.e. it
      is a list or an aggregation module; max/min also need a recent
      mlx-cluster),
    * any message/aggregate kwarg other than ``edge_weights`` is set
      (e.g. ``edge_features``), since messages are then no longer a weighted
      sum of neighbour features,
    * the layer is a subclass of a decorated layer that overrides
      ``message()`` or ``aggregate()`` without also overriding
      ``message_and_aggregate()``.

    Args:
        format: ``"coo"`` works directly on ``edge_index``. ``"csr"`` sorts
            the graph once (cached per ``edge_index``) and uses a faster,
            deterministic, atomic-free kernel. ``"auto"`` (default) starts
            with ``"coo"`` and switches to ``"csr"`` when the sort pays off:
            immediately for graphs with at least a million edges, and once
            the same ``edge_index`` array has been used a few times
            otherwise (e.g. full-batch training).
        allow_message_override: a layer that overrides ``message()`` or
            ``aggregate()`` is rejected by default, because the fused kernel
            would ignore those overrides. Pass ``True`` only if the override
            reduces to the default ``edge_weights * x_j`` / scatter whenever
            the extra kwargs are ``None`` (e.g. ``GINConv``).

    .. note::
        Cached conversions are looked up by the identity of the
        ``edge_index`` array. Build a new array instead of modifying an
        ``edge_index`` in place (``edge_index[0, 3] = 5``) between calls, or
        call :func:`clear_csr_cache` after doing so.

    .. code-block:: python

        @fused_message_passing
        class MyConv(MessagePassing):
            ...


        @fused_message_passing(format="csr")
        class MyOtherConv(MessagePassing):
            ...
    """
    if format not in get_args(FusedFormat):
        raise ValueError(f"format must be 'auto', 'coo' or 'csr', got {format!r}")

    def wrap(klass):
        if not (isinstance(klass, type) and issubclass(klass, MessagePassing)):
            raise TypeError(
                "@fused_message_passing can only decorate MessagePassing subclasses."
            )
        overrides = [
            name
            for name in ("message", "aggregate")
            if getattr(klass, name) is not getattr(MessagePassing, name)
        ]
        custom_fused = (
            klass.message_and_aggregate is not MessagePassing.message_and_aggregate
        )
        if overrides and not custom_fused and not allow_message_override:
            raise TypeError(
                f"{klass.__name__} overrides {' and '.join(overrides)}(), which the "
                "fused SpMM kernel would ignore. Implement message_and_aggregate(), "
                "or pass allow_message_override=True if the override reduces to "
                "the default when only edge_weights are given."
            )
        klass._fused_format = format
        return klass

    return wrap(cls) if cls is not None else wrap

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