Skip to content

to_hetero_with_bases

to_hetero_with_bases(
    module: Module,
    metadata: Metadata,
    num_bases: int,
    in_channels: Optional[dict[str, int]] = None,
    input_map: Optional[dict[str, str]] = None,
    input_dims: Optional[dict[NodeType, int]] = None,
) -> ToHeteroModel

Converts a homogeneous GNN model into its heterogeneous equivalent via the basis-decomposition technique of the "Modeling Relational Data with Graph Convolutional Networks" paper (PyG's to_hetero_with_bases).

Every message passing layer \(f_{\theta}^{(\ell)}\) is copied num_bases times, and every edge type \(r\) gets learned coefficients \(a^{(\ell)}_{r,b}\) (edge_type_weight). Message passing runs on one graph made of all node and edge types:

\[ \mathbf{h}^{(\ell)}_v = \sum_{b=1}^{B} f_{\theta_b}^{(\ell)} ( \mathbf{h}^{(\ell - 1)}_v, \{ a^{(\ell)}_{r,b} \cdot \mathbf{h}^{(\ell - 1)}_w : w \in \mathcal{N}^{(r)}(v), r \in \mathcal{R} \}), \]

where every message of an edge of type \(r\) is scaled by \(a^{(\ell)}_{r,b}\) (message() of the copies is wrapped, and the fused SpMM path is disabled for them). The number of parameters grows with num_bases instead of with the number of edge types, which helps with many relations. Unlike to_hetero(), the other modules (Linear, normalizations, ...) are shared by all node types, and all node types need the same number of features: give in_channels (with input_dims) to project node-level inputs of every type to a common size first, with one bias-free linear layer per node type (PyG's LinearAlign).

The converted model is called and returns its outputs like to_hetero()'s. Layers must not add self-loops (the messages would not belong to any edge type) and must compute their messages with message().

Parameters:

Name Type Description Default
module Module

The homogeneous model to convert (copied).

required
metadata Metadata

The node types and edge types of the graph, e.g. data.metadata().

required
num_bases int

The number of bases (copies of every message passing layer).

required
in_channels Optional[dict[str, int]]

Optional {argument name: size}: node-level arguments (e.g. {"node_features": 64}) whose features are projected to size per node type before running the model.

None
input_map Optional[dict[str, str]]

Optional {argument name: "node" | "edge"}, see to_hetero().

None
input_dims Optional[dict[NodeType, int]]

Number of input features per node type, needed with in_channels (MLX has no lazy input sizes).

None

Returns:

Type Description
ToHeteroModel

Example:

from mlx_graphs.nn import GraphSAGE, to_hetero_with_bases

model = to_hetero_with_bases(
    GraphSAGE(32, 32, num_layers=2, out_features_dim=4),
    data.metadata(),
    num_bases=3,
    in_channels={"node_features": 32},
    input_dims=data.num_node_features,
)
out = model(data.edge_index_dict, data.node_features_dict)
Source code in mlx_graphs/nn/to_hetero.py
def to_hetero_with_bases(
    module: nn.Module,
    metadata: Metadata,
    num_bases: int,
    in_channels: Optional[dict[str, int]] = None,
    input_map: Optional[dict[str, str]] = None,
    input_dims: Optional[dict[NodeType, int]] = None,
) -> ToHeteroModel:
    r"""Converts a homogeneous GNN model into its heterogeneous equivalent via
    the basis-decomposition technique of the `"Modeling Relational Data with
    Graph Convolutional Networks" <https://arxiv.org/abs/1703.06103>`_ paper
    (PyG's ``to_hetero_with_bases``).

    Every message passing layer :math:`f_{\theta}^{(\ell)}` is copied
    ``num_bases`` times, and every edge type :math:`r` gets learned
    coefficients :math:`a^{(\ell)}_{r,b}` (``edge_type_weight``). Message
    passing runs on one graph made of all node and edge types:

    .. math::
        \mathbf{h}^{(\ell)}_v = \sum_{b=1}^{B} f_{\theta_b}^{(\ell)} (
        \mathbf{h}^{(\ell - 1)}_v, \{ a^{(\ell)}_{r,b} \cdot
        \mathbf{h}^{(\ell - 1)}_w : w \in \mathcal{N}^{(r)}(v), r \in
        \mathcal{R} \}),

    where every message of an edge of type :math:`r` is scaled by
    :math:`a^{(\ell)}_{r,b}` (``message()`` of the copies is wrapped, and the
    fused SpMM path is disabled for them). The number of parameters grows with
    ``num_bases`` instead of with the number of edge types, which helps with
    many relations. Unlike :func:`to_hetero`, the other modules (``Linear``,
    normalizations, ...) are shared by all node types, and all node types
    need the same number of features: give ``in_channels`` (with
    ``input_dims``) to project node-level inputs of every type to a common size
    first, with one bias-free linear layer per node type (PyG's
    ``LinearAlign``).

    The converted model is called and returns its outputs like
    :func:`to_hetero`'s. Layers must not add self-loops (the messages would
    not belong to any edge type) and must compute their messages with
    :meth:`~mlx_graphs.nn.MessagePassing.message`.

    Args:
        module: The homogeneous model to convert (copied).
        metadata: The node types and edge types of the graph, e.g.
            ``data.metadata()``.
        num_bases: The number of bases (copies of every message passing layer).
        in_channels: Optional ``{argument name: size}``: node-level arguments
            (e.g. ``{"node_features": 64}``) whose features are projected to
            ``size`` per node type before running the model.
        input_map: Optional ``{argument name: "node" | "edge"}``, see
            :func:`to_hetero`.
        input_dims: Number of input features per node type, needed with
            ``in_channels`` (MLX has no lazy input sizes).

    Returns:
        A :class:`ToHeteroModel`.

    Example:

    .. code-block:: python

        from mlx_graphs.nn import GraphSAGE, to_hetero_with_bases

        model = to_hetero_with_bases(
            GraphSAGE(32, 32, num_layers=2, out_features_dim=4),
            data.metadata(),
            num_bases=3,
            in_channels={"node_features": 32},
            input_dims=data.num_node_features,
        )
        out = model(data.edge_index_dict, data.node_features_dict)

    References:
        `PyG's to_hetero_with_bases <https://pytorch-geometric.readthedocs.io/
        en/latest/modules/nn.html#torch_geometric.nn.
        to_hetero_with_bases_transformer.to_hetero_with_bases>`_
    """
    return ToHeteroModel(
        module,
        metadata,
        input_map=input_map,
        input_dims=input_dims,
        num_bases=num_bases,
        in_channels=in_channels,
    )

from mlx_graphs.nn import to_hetero_with_bases · mlx_graphs/nn/to_hetero.py