Skip to content

LCMAggregation

LCMAggregation(
    node_features_dim: int, out_features_dim: int, project: bool = True
)

Bases: Aggregation

The Learnable Commutative Monoid aggregation from the "Learnable Commutative Monoids for Graph Neural Networks" paper, as PyG's LCMAggregation.

The elements of each set are (optionally) projected, then combined in a balanced binary tree whose binary operator is a symmetrized GRU cell, in \(\mathcal{O}(\log |\mathcal{V}|)\) depth:

\[ \mathbf{y} = \frac{1}{2}\left(\mathrm{GRU}(\mathbf{a}, \mathbf{b}) + \mathrm{GRU}(\mathbf{b}, \mathbf{a})\right) \]

Sets are padded with zeros to the size of the largest set.

Parameters:

Name Type Description Default
node_features_dim int

Size of each input sample.

required
out_features_dim int

Size of each output sample.

required
project bool

Whether to apply a linear projection followed by a ReLU before the aggregation. Required if the two sizes differ. Default: True

True

Example:

import mlx.core as mx
from mlx_graphs.nn.aggr import LCMAggregation

aggr = LCMAggregation(16, 32)
x = mx.random.normal((6, 16))
index = mx.array([0, 0, 1, 1, 1, 2])
>>> aggr(x, index).shape
(3, 32)

Methods:

Name Description
aggregate

Aggregates x.

Source code in mlx_graphs/nn/aggr/misc.py
def __init__(
    self, node_features_dim: int, out_features_dim: int, project: bool = True
):
    super().__init__()
    if node_features_dim != out_features_dim and not project:
        raise ValueError(
            "Inputs of 'LCMAggregation' must be projected if "
            "`node_features_dim != out_features_dim`"
        )
    self.node_features_dim = node_features_dim
    self.out_features_dim = out_features_dim
    self.project = project
    if project:
        self.lin = nn.Linear(node_features_dim, out_features_dim)
    self.gru_cell = nn.GRU(out_features_dim, out_features_dim)

aggregate

aggregate(
    x: array,
    index: array,
    dim_size: int,
    max_num_elements: Optional[int] = None,
    **kwargs,
) -> array

Aggregates x.

Parameters:

Name Type Description Default
x array

Array of shape [num_elements, node_features_dim].

required
index array

Set of each element.

required
dim_size int

Number of sets.

required
max_num_elements Optional[int]

Only the first max_num_elements elements of each set (in input order) are used. Default: None

None
Source code in mlx_graphs/nn/aggr/misc.py
def aggregate(
    self,
    x: mx.array,
    index: mx.array,
    dim_size: int,
    max_num_elements: Optional[int] = None,
    **kwargs,
) -> mx.array:
    """Aggregates ``x``.

    Args:
        x: Array of shape ``[num_elements, node_features_dim]``.
        index: Set of each element.
        dim_size: Number of sets.
        max_num_elements: Only the first ``max_num_elements`` elements of
            each set (in input order) are used. Default: ``None``
    """
    if x.ndim != 2:
        raise ValueError(
            f"LCMAggregation requires two-dimensional inputs (got {x.ndim})"
        )
    if self.project:
        x = nn.relu(self.lin(x))
    layout = DenseLayout(index, x.shape[0], dim_size, max_num_elements)
    if layout.size == 0:
        return mx.zeros((dim_size, self.out_features_dim), dtype=x.dtype)
    x = layout.to_dense(x).transpose(1, 0, 2)  # [size, num_sets, features]
    num_features = x.shape[-1]

    for _ in range(math.ceil(math.log2(x.shape[0]))):
        remainder = None
        if x.shape[0] % 2 == 1:
            x, remainder = x[:-1], x[-1:]
        left_right = x.reshape(-1, 2, dim_size, num_features)
        right_left = left_right[:, ::-1]
        out = self.gru_cell(
            left_right.reshape(-1, 1, num_features),
            right_left.reshape(-1, num_features),
        )
        out = out.reshape(-1, 2, dim_size, num_features).mean(axis=1)
        if remainder is not None:
            out = mx.concatenate([out, remainder], axis=0)
        x = out
    return x[0]

from mlx_graphs.nn.aggr import LCMAggregation · mlx_graphs/nn/aggr/misc.py