Skip to content

RGCNConv

RGCNConv(
    node_features_dim: Union[int, Tuple[int, int]],
    out_features_dim: int,
    num_relations: int,
    num_bases: Optional[int] = None,
    root_weight: bool = True,
    bias: bool = True,
    **kwargs,
)

Bases: MessagePassing

Relational graph convolution layer from "Modeling Relational Data with Graph Convolutional Networks" paper.

\[ \mathbf{h}_i = \mathbf{W}_{\textrm{root}} \mathbf{x}_i + \sum_{r \in \mathcal{R}} \bigoplus_{j \in \mathcal{N}_r(i)} \mathbf{W}_r \mathbf{x}_j, \]

where \(\mathcal{R}\) is the set of relations (edge types), \(\mathcal{N}_r(i)\) are the neighbors of node \(i\) under relation \(r\) and \(\bigoplus\) denotes the aggregation function, set by default to mean, i.e. \(\frac{1}{|\mathcal{N}_r(i)|} \sum_{j \in \mathcal{N}_r(i)}\).

With num_bases set, the relation weights share a small set of basis matrices \(\mathbf{V}_b\) (basis decomposition), which reduces the number of parameters when there are many relations:

\[ \mathbf{W}_r = \sum_{b=1}^{B} a_{rb} \mathbf{V}_b \]

The layer also works on bipartite graphs: 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.

Note

Small inputs are aggregated in one shot into a dense [num_nodes, num_relations, node_features_dim] array. When that array would be both larger than the per-edge features and larger than RGCNConv.dense_max_elements elements, the layer instead loops over the relations, each time using only the edges of that relation, so memory stays proportional to the number of edges and nodes. Both paths give the same result.

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
num_relations int

Number of relations (edge types)

required
num_bases Optional[int]

If set, uses basis decomposition with this number of bases. Default: None

None
root_weight bool

Whether to add the transformed features of the node itself to the output. Default: True

True
bias bool

Whether to add a learnable bias to the output. Default: True

True
**kwargs

Arguments of MessagePassing, e.g. aggr ("mean" by default, or "add", "max", "min")

{}

Example:

import mlx.core as mx
from mlx_graphs.nn.conv.rgcn_conv import RGCNConv

conv = RGCNConv(16, 32, num_relations=3, num_bases=2)

edge_index = mx.array([[0, 1, 2, 3, 4], [0, 0, 1, 1, 3]])
edge_type = mx.array([0, 0, 1, 2, 2])
node_features = mx.random.uniform(low=0, high=1, shape=(5, 16))

h = conv(edge_index, node_features, edge_type)

>>> h.shape
(5, 32)

Methods:

Name Description
__call__

Computes the forward pass of RGCNConv.

Source code in mlx_graphs/nn/conv/rgcn_conv.py
def __init__(
    self,
    node_features_dim: Union[int, Tuple[int, int]],
    out_features_dim: int,
    num_relations: int,
    num_bases: Optional[int] = None,
    root_weight: bool = True,
    bias: bool = True,
    **kwargs,
):
    kwargs.setdefault("aggr", "mean")
    super(RGCNConv, self).__init__(**kwargs)

    if self.aggr == "softmax":
        raise ValueError("RGCNConv does not support the 'softmax' aggregation.")
    if not isinstance(self.aggr, str) or "aggr_module" in self:
        raise ValueError(
            "RGCNConv only supports a single scatter aggregation "
            "('add', 'mean', 'max', 'min', ...), not a list or an Aggregation "
            f"module (got {self.aggr!r})."
        )
    if num_relations < 1:
        raise ValueError(f"num_relations must be positive, got {num_relations}")
    if num_bases is not None and num_bases < 1:
        raise ValueError(f"num_bases must be positive, got {num_bases}")

    if isinstance(node_features_dim, int):
        src_dim = dst_dim = node_features_dim
    else:
        src_dim, dst_dim = node_features_dim

    self.node_features_dim = node_features_dim
    self.out_features_dim = out_features_dim
    self.src_features_dim = src_dim
    self.num_relations = num_relations
    self.num_bases = num_bases

    # Weights are stored as [..., in, out] (applied as `x @ weight`), the same
    # layout as PyG's RGCNConv.
    if num_bases is not None:
        self.weight = _glorot((num_bases, src_dim, out_features_dim))
        self.comp = _glorot((num_relations, num_bases))
    else:
        self.weight = _glorot((num_relations, src_dim, out_features_dim))

    if root_weight:
        self.root = _glorot((dst_dim, out_features_dim))

    if bias:
        self.bias = mx.zeros((out_features_dim,))

__call__

__call__(
    edge_index: array,
    node_features: Union[array, Tuple[array, array]],
    edge_type: array,
) -> array

Computes the forward pass of RGCNConv.

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_type array

Relation of each edge, integer array of shape [num_edges] with values in [0, num_relations)

required

Returns:

Type Description
array

The computed node embeddings, one row per destination node

Source code in mlx_graphs/nn/conv/rgcn_conv.py
def __call__(
    self,
    edge_index: mx.array,
    node_features: Union[mx.array, Tuple[mx.array, mx.array]],
    edge_type: mx.array,
) -> mx.array:
    """Computes the forward pass of RGCNConv.

    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_type: Relation of each edge, integer array of shape `[num_edges]`
            with values in ``[0, num_relations)``

    Returns:
        mx.array: The computed node embeddings, one row per destination node
    """
    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 edge_type.ndim != 1 or edge_type.shape[0] != edge_index.shape[1]:
        raise ValueError(
            "`edge_type` should have shape [num_edges], "
            f"found {edge_type.shape} for {edge_index.shape[1]} edges."
        )

    if isinstance(node_features, tuple):
        src_features, dst_features = node_features
    else:
        src_features = dst_features = node_features

    self.num_nodes = dst_features.shape[0]

    # shape: [num_relations, src_dim, out_features_dim]
    weight = self.weight
    if self.num_bases is not None:
        weight = (self.comp @ weight.reshape(self.num_bases, -1)).reshape(
            self.num_relations, self.src_features_dim, self.out_features_dim
        )

    if self._use_dense_path(self.num_nodes, edge_index.shape[1]):
        out = self._aggregate_dense(edge_index, src_features, edge_type, weight)
    else:
        out = self._aggregate_per_relation(
            edge_index, src_features, edge_type, weight
        )

    if "root" in self:
        out = out + dst_features @ self.root

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

    return out

from mlx_graphs.nn import RGCNConv · mlx_graphs/nn/conv/rgcn_conv.py