Skip to content

to_hetero

Conversion of homogeneous GNN models into heterogeneous ones (to_hetero).

PyG implements to_hetero by tracing forward with torch.fx and rewriting the traced graph. MLX has no such tracer, so this module uses module rewriting plus type-packed execution instead:

  1. The model is deep-copied. Every MessagePassing layer in it is replaced by a dispatcher holding one copy of the layer per edge type, and every other sub-module (Linear, normalizations, MLPs, Jumping Knowledge, ...) by a dispatcher holding one copy per node type. Sub-modules that contain message passing layers themselves (e.g. a GraphSAGE used inside a bigger model) are rewritten recursively.
  2. At call time, the per-type input dicts are packed into ordinary arrays: node-level dicts become one array with the rows of all node types concatenated (in metadata order), edge-level dicts one array with the edges of all edge types. The model's own, unchanged __call__ then runs on these arrays, so every row-wise operation in it (activations, dropout, residual sums, concatenation of features, ...) works as written.
  3. The dispatchers split the packed arrays back per type: a node-type copy runs on its node type's rows, an edge-type copy on its edges with (src_features, dst_features) (or just the features when both ends have the same type), and the outputs of edge types sharing a destination are combined with aggr. Arrays that reach a layer unchanged from the model's inputs are not split but looked up in the input dicts, so packing them never costs any memory (MLX evaluates them lazily, and they are never needed).

Classes:

Name Description
ToHeteroModel

Heterogeneous version of a homogeneous model, returned by

Functions:

Name Description
to_hetero

Converts a homogeneous GNN model into its heterogeneous equivalent, in

to_hetero_with_bases

Converts a homogeneous GNN model into its heterogeneous equivalent via

ToHeteroModel

ToHeteroModel(
    module: Module,
    metadata: Metadata,
    aggr: str = "sum",
    input_map: Optional[dict[str, str]] = None,
    input_dims: Optional[dict[NodeType, int]] = None,
    num_bases: Optional[int] = None,
    in_channels: Optional[dict[str, int]] = None,
)

Bases: Module

Heterogeneous version of a homogeneous model, returned by to_hetero().

It is called like the original model, with a dict per node-level input (keyed by node type) and per edge-level input (keyed by edge type) instead of an array, e.g. model(edge_index_dict, node_features_dict) for a model called as model(edge_index, node_features). Node-level outputs are returned as dicts keyed by node type (edge-level outputs keyed by edge type).

The rewritten copy of the original model is stored as self.module; the copy of a layer used for a type is in the layer's dispatcher, under the type's name ("author" or "author__writes__paper"), e.g. model.module.convs[0]["author__writes__paper"], or via model.module.convs[0].module_for(("author", "writes", "paper")).

Attributes:

Name Type Description
metadata Metadata

The (node_types, edge_types) the model was converted for.

Source code in mlx_graphs/nn/to_hetero.py
def __init__(
    self,
    module: nn.Module,
    metadata: Metadata,
    aggr: str = "sum",
    input_map: Optional[dict[str, str]] = None,
    input_dims: Optional[dict[NodeType, int]] = None,
    num_bases: Optional[int] = None,
    in_channels: Optional[dict[str, int]] = None,
):
    super().__init__()
    node_types, edge_types = _check_metadata(metadata)
    if num_bases is not None and num_bases < 1:
        raise ValueError(f"num_bases must be at least 1, got {num_bases}")
    if in_channels and input_dims is None:
        raise ValueError(
            "in_channels needs input_dims, the number of input features of "
            "every node type (MLX has no lazy input sizes)."
        )
    if aggr not in _AGGRS:
        raise ValueError(f"Invalid aggregation '{aggr}'. Available: {_AGGRS}")
    if input_map is not None:
        for name, level in input_map.items():
            if level not in ("node", "edge"):
                raise ValueError(
                    f"input_map values must be 'node' or 'edge', got "
                    f"{level!r} for '{name}'"
                )
    if input_dims is not None:
        missing = [t for t in node_types if t not in input_dims]
        if missing:
            raise ValueError(f"input_dims is missing node types {missing}")
        input_dims = {t: int(input_dims[t]) for t in node_types}

    self._node_types = node_types
    self._edge_types = edge_types
    self._aggr = aggr
    self._input_map = dict(input_map or {})
    self._input_dims = input_dims if num_bases is None else None
    self._num_bases = num_bases
    self._in_channels = dict(in_channels or {})
    self._signature = _call_signature(module)

    _check_layers(module, edge_types, bases=num_bases is not None)
    if num_bases is not None and self._in_channels:
        # PyG's LinearAlign: one bias-free projection per node type.
        from mlx_graphs.nn.linear import Linear

        self.align = {
            name: {t: Linear(input_dims[t], dim, bias=False) for t in node_types}
            for name, dim in self._in_channels.items()
        }
    if num_bases is None and _contains_message_passing(module):
        dst_types = {dst for _, _, dst in edge_types}
        not_updated = [t for t in node_types if t not in dst_types]
        if not_updated:
            raise ValueError(
                f"Node types {not_updated} are not the destination of any "
                "edge type, so message passing layers cannot compute new "
                "representations for them. Add reverse edge types, e.g. "
                "('paper', 'rev_writes', 'author') for "
                "('author', 'writes', 'paper')."
            )

    rewriter = _Rewriter((node_types, edge_types), aggr, num_bases)
    module = _clone(module)
    if isinstance(module, MessagePassing) or not _contains_message_passing(module):
        module = rewriter.convert(module, type(module).__name__)
    else:
        rewriter.rewrite_children(module, "")
    if rewriter.shared_arrays:
        warnings.warn(
            f"Parameters {rewriter.shared_arrays} are used directly by the "
            "model and are shared by all node types (to_hetero only copies "
            "sub-modules per type). Wrap them in a module to get one copy "
            "per type.",
            stacklevel=3,
        )
    self.module = module

    if self._input_dims is not None:
        self._dry_run()

metadata property

metadata: Metadata

The (node_types, edge_types) the model was converted for.

to_hetero

to_hetero(
    module: Module,
    metadata: Metadata,
    aggr: str = "sum",
    input_map: Optional[dict[str, str]] = None,
    input_dims: Optional[dict[NodeType, int]] = None,
) -> ToHeteroModel

Converts a homogeneous GNN model into its heterogeneous equivalent, in which node representations are learned for each node type in metadata[0] and messages are exchanged along each edge type in metadata[1], as in the "Modeling Relational Data with Graph Convolutional Networks" paper (PyG's to_hetero).

Every message passing layer \(f_{\theta}^{(\ell)}\) of the model is copied once per relation \(r\) (edge type), and every other sub-module (Linear, normalizations, MLPs, Jumping Knowledge, ...) once per node type. Message passing then computes

\[ \mathbf{h}^{(\ell)}_v = \bigoplus_{r \in \mathcal{R}} f_{\theta}^{(\ell, r)} ( \mathbf{h}^{(\ell - 1)}_v, \{ \mathbf{h}^{(\ell - 1)}_w : w \in \mathcal{N}^{(r)}(v) \}), \]

where \(\bigoplus\) is aggr. Edge types between two different node types call their layer with a (src_features, dst_features) tuple, so it must support bipartite graphs (e.g. SAGEConv, GraphConv, GATConv, GATv2Conv, GINConv; not GCNConv).

The converted model is called like the original one, with dicts instead of arrays: model(edge_index_dict, node_features_dict) for a model called as model(edge_index, node_features). Dicts keyed by node types are node-level inputs, dicts keyed by (src, rel, dst) edge types are edge-level inputs (e.g. edge_weights), and other values are passed unchanged. Node-level outputs are returned as dicts keyed by node type.

Input sizes. MLX layers have no lazy input sizes (PyG's -1), so there are two ways to handle node types with different numbers of features:

  • pass input_dims (e.g. data.num_node_features): the copies of the layers reading the input features are rebuilt for each node type's size. The homogeneous model can then be built with any input size. The layers reading the input features are found by running the model once on a tiny graph when converting it. Supported first layers: Linear, MLP, nn.Sequential starting with a Linear, SAGEConv, GraphConv, GATConv, GATv2Conv, and GINConv/GCNConv when both ends of every edge type have the same size;
  • or project every node type to a common size first (e.g. with HeteroDictLinear), and convert a model built for that size without input_dims.

How it works. PyG traces forward with torch.fx, which has no MLX counterpart. Instead, the model is copied and its layers are replaced by dispatchers holding one copy per type. At call time the dicts are packed into arrays (the rows of all node types, resp. the edges of all edge types, concatenated in metadata order) and the model's own __call__ runs on them unchanged: row-wise operations (activations, dropout, residual connections, concatenating features) just work, and the dispatchers split the arrays per type, run the copies and concatenate the results. Inputs passed unchanged to the first layers are looked up in the input dicts, so packing them costs nothing.

Initialization of the copies. As PyG, which calls reset_parameters() on every copy, the copies are re-randomized (when there are several types). Modules with a reset_parameters() method are reset with it. Most MLX modules have none, so the trainable arrays of the others are randomly permuted: for initializations drawing every entry independently (the usual uniform/normal/Glorot ones) this is a draw from the same distribution, but the copies hold the same values in different orders (not independent draws: arrays of a single value, e.g. the bias of a one-output layer, are identical in all copies), and an initialization with structure (e.g. orthogonal) is not preserved: give such modules a reset_parameters() method. Frozen arrays (buffers, e.g. batch norm running statistics) are kept.

Supported: models written in the PyG style (message passing layers, Linear/MLP/normalization modules, functional activations, dropout, residual and skip connections such as conv(edge_index, x) + lin(x)), the built-in BasicGNN models (GCN, GraphSAGE, GIN, GAT, including norm and jk), models nesting such models, edge-level arguments of the message passing layers (edge_weights, edge_features), and edge types missing from a call's edge index dict (skipped). Parameters live in model.parameters() like any MLX module (nn.value_and_grad, optimizers, save_weights).

Not supported (as in PyG, or because of the packing):

  • operations in __call__ that mix or select rows, e.g. x[:n], x.mean(axis=0), global pooling or sorting: they would act on the rows of all node types together. Do them on the output dicts instead;
  • modules (other than message passing layers) called on edge-level or graph-level values;
  • arrays stored directly on the model and used in __call__ are shared by all node types (a warning is raised); modules are copied per type;
  • control flow depending on the data, and modifying edge_index before passing it to the layers: adding or removing edges (e.g. dropout_edge) raises an error, reordering them is not detected;
  • every node type must be the destination of at least one edge type (add reverse edges); GCNConv and layers adding self-loops cannot be used with bipartite edge types;
  • if the total number of nodes equals the total number of edges, arrays with that many rows are treated as node-level.

Parameters:

Name Type Description Default
module Module

The homogeneous model to convert. It is copied, the original is left unchanged.

required
metadata Metadata

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

required
aggr str

How to combine the outputs of the edge types sharing a destination node type: "sum", "mean", "max", "min" or "mul". Default: "sum"

'sum'
input_map Optional[dict[str, str]]

Optional {argument name: "node" | "edge"} overriding the level of dict arguments (otherwise found from their keys) and telling the dry run of input_dims which required arguments are edge-level (otherwise those whose name contains "edge").

None
input_dims Optional[dict[NodeType, int]]

Optional number of input features per node type, e.g. data.num_node_features. See above. Default: None (every node type has the input size the model was built for).

None

Returns:

Type Description
ToHeteroModel

Example:

import mlx.core as mx
import mlx.nn as nn
from mlx_graphs.nn import Linear, SAGEConv, to_hetero

class GNN(nn.Module):
    def __init__(self, hidden, out):
        super().__init__()
        self.conv1 = SAGEConv(hidden, hidden)
        self.lin1 = Linear(hidden, hidden)
        self.conv2 = SAGEConv(hidden, out)
        self.lin2 = Linear(hidden, out)

    def __call__(self, edge_index, x):
        x = nn.relu(self.conv1(edge_index, x) + self.lin1(x))
        return self.conv2(edge_index, x) + self.lin2(x)

x_dict = {"author": mx.ones((4, 16)), "paper": mx.ones((5, 8))}
edge_index_dict = {
    ("author", "writes", "paper"): mx.array([[0, 1, 3], [0, 0, 4]]),
    ("paper", "rev_writes", "author"): mx.array([[0, 0, 4], [0, 1, 3]]),
    ("paper", "cites", "paper"): mx.array([[1, 2], [0, 0]]),
}
metadata = (list(x_dict), list(edge_index_dict))

# GNN(-1, ...) is not possible in MLX: give the input sizes instead
model = to_hetero(GNN(32, 4), metadata, input_dims={"author": 16, "paper": 8})
out = model(edge_index_dict, x_dict)
>>> {k: v.shape for k, v in out.items()}
{'author': (4, 4), 'paper': (5, 4)}

# Built-in models work too
from mlx_graphs.nn import GraphSAGE
model = to_hetero(
    GraphSAGE(16, 32, num_layers=2, out_features_dim=4, jk="cat"),
    metadata,
    input_dims={"author": 16, "paper": 8},
)

References

PyG's to_hetero

Source code in mlx_graphs/nn/to_hetero.py
def to_hetero(
    module: nn.Module,
    metadata: Metadata,
    aggr: str = "sum",
    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, in
    which node representations are learned for each node type in
    ``metadata[0]`` and messages are exchanged along each edge type in
    ``metadata[1]``, as in the `"Modeling Relational Data with Graph
    Convolutional Networks" <https://arxiv.org/abs/1703.06103>`_ paper (PyG's
    ``to_hetero``).

    Every message passing layer :math:`f_{\theta}^{(\ell)}` of the model is
    copied once per relation :math:`r` (edge type), and every other
    sub-module (``Linear``, normalizations, MLPs, Jumping Knowledge, ...) once
    per node type. Message passing then computes

    .. math::
        \mathbf{h}^{(\ell)}_v = \bigoplus_{r \in \mathcal{R}}
        f_{\theta}^{(\ell, r)} ( \mathbf{h}^{(\ell - 1)}_v, \{
        \mathbf{h}^{(\ell - 1)}_w : w \in \mathcal{N}^{(r)}(v) \}),

    where :math:`\bigoplus` is ``aggr``. Edge types between two different node
    types call their layer with a ``(src_features, dst_features)`` tuple, so
    it must support bipartite graphs (e.g. ``SAGEConv``, ``GraphConv``,
    ``GATConv``, ``GATv2Conv``, ``GINConv``; not ``GCNConv``).

    The converted model is called like the original one, with dicts instead
    of arrays: ``model(edge_index_dict, node_features_dict)`` for a model
    called as ``model(edge_index, node_features)``. Dicts keyed by node types
    are node-level inputs, dicts keyed by ``(src, rel, dst)`` edge types are
    edge-level inputs (e.g. ``edge_weights``), and other values are passed
    unchanged. Node-level outputs are returned as dicts keyed by node type.

    **Input sizes.** MLX layers have no lazy input sizes (PyG's ``-1``), so
    there are two ways to handle node types with different numbers of
    features:

    * pass ``input_dims`` (e.g. ``data.num_node_features``): the copies of the
      layers reading the input features are rebuilt for each node type's
      size. The homogeneous model can then be built with any input size. The
      layers reading the input features are found by running the model once
      on a tiny graph when converting it. Supported first layers:
      ``Linear``, ``MLP``, ``nn.Sequential`` starting with a ``Linear``,
      ``SAGEConv``, ``GraphConv``, ``GATConv``, ``GATv2Conv``, and
      ``GINConv``/``GCNConv`` when both ends of every edge type have the same
      size;
    * or project every node type to a common size first (e.g. with
      :class:`~mlx_graphs.nn.HeteroDictLinear`), and convert a model built for
      that size without ``input_dims``.

    **How it works.** PyG traces ``forward`` with ``torch.fx``, which has no
    MLX counterpart. Instead, the model is copied and its layers are replaced
    by dispatchers holding one copy per type. At call time the dicts are
    packed into arrays (the rows of all node types, resp. the edges of all
    edge types, concatenated in metadata order) and the model's own
    ``__call__`` runs on them unchanged: row-wise operations (activations,
    dropout, residual connections, concatenating features) just work, and the
    dispatchers split the arrays per type, run the copies and concatenate the
    results. Inputs passed unchanged to the first layers are looked up in the
    input dicts, so packing them costs nothing.

    **Initialization of the copies.** As PyG, which calls
    ``reset_parameters()`` on every copy, the copies are re-randomized (when
    there are several types). Modules with a ``reset_parameters()`` method
    are reset with it. Most MLX modules have none, so the trainable arrays of
    the others are randomly permuted: for initializations drawing every
    entry independently (the usual uniform/normal/Glorot ones) this is a
    draw from the same distribution, but the copies hold the same values in
    different orders (not independent draws: arrays of a single value, e.g.
    the bias of a one-output layer, are identical in all copies), and an
    initialization with structure (e.g. orthogonal) is not preserved: give
    such modules a ``reset_parameters()`` method. Frozen arrays (buffers,
    e.g. batch norm running statistics) are kept.

    **Supported:** models written in the PyG style (message passing layers,
    ``Linear``/MLP/normalization modules, functional activations, dropout,
    residual and skip connections such as ``conv(edge_index, x) + lin(x)``),
    the built-in :class:`~mlx_graphs.nn.BasicGNN` models (``GCN``,
    ``GraphSAGE``, ``GIN``, ``GAT``, including ``norm`` and ``jk``), models
    nesting such models, edge-level arguments of the message passing layers
    (``edge_weights``, ``edge_features``), and edge types missing from a
    call's edge index dict (skipped). Parameters live in ``model.parameters()``
    like any MLX module (``nn.value_and_grad``, optimizers, ``save_weights``).

    **Not supported** (as in PyG, or because of the packing):

    * operations in ``__call__`` that mix or select rows, e.g. ``x[:n]``,
      ``x.mean(axis=0)``, global pooling or sorting: they would act on the
      rows of all node types together. Do them on the output dicts instead;
    * modules (other than message passing layers) called on edge-level or
      graph-level values;
    * arrays stored directly on the model and used in ``__call__`` are shared
      by all node types (a warning is raised); modules are copied per type;
    * control flow depending on the data, and modifying ``edge_index`` before
      passing it to the layers: adding or removing edges (e.g.
      ``dropout_edge``) raises an error, reordering them is not detected;
    * every node type must be the destination of at least one edge type
      (add reverse edges); ``GCNConv`` and layers adding self-loops cannot be
      used with bipartite edge types;
    * if the total number of nodes equals the total number of edges, arrays
      with that many rows are treated as node-level.

    Args:
        module: The homogeneous model to convert. It is copied, the original
            is left unchanged.
        metadata: The node types and edge types of the graph, e.g.
            ``data.metadata()`` of a :class:`~mlx_graphs.data.HeteroGraphData`.
        aggr: How to combine the outputs of the edge types sharing a
            destination node type: ``"sum"``, ``"mean"``, ``"max"``,
            ``"min"`` or ``"mul"``. Default: ``"sum"``
        input_map: Optional ``{argument name: "node" | "edge"}`` overriding
            the level of dict arguments (otherwise found from their keys) and
            telling the dry run of ``input_dims`` which required arguments are
            edge-level (otherwise those whose name contains ``"edge"``).
        input_dims: Optional number of input features per node type, e.g.
            ``data.num_node_features``. See above. Default: ``None`` (every node
            type has the input size the model was built for).

    Returns:
        A :class:`ToHeteroModel`.

    Example:

    .. code-block:: python

        import mlx.core as mx
        import mlx.nn as nn
        from mlx_graphs.nn import Linear, SAGEConv, to_hetero

        class GNN(nn.Module):
            def __init__(self, hidden, out):
                super().__init__()
                self.conv1 = SAGEConv(hidden, hidden)
                self.lin1 = Linear(hidden, hidden)
                self.conv2 = SAGEConv(hidden, out)
                self.lin2 = Linear(hidden, out)

            def __call__(self, edge_index, x):
                x = nn.relu(self.conv1(edge_index, x) + self.lin1(x))
                return self.conv2(edge_index, x) + self.lin2(x)

        x_dict = {"author": mx.ones((4, 16)), "paper": mx.ones((5, 8))}
        edge_index_dict = {
            ("author", "writes", "paper"): mx.array([[0, 1, 3], [0, 0, 4]]),
            ("paper", "rev_writes", "author"): mx.array([[0, 0, 4], [0, 1, 3]]),
            ("paper", "cites", "paper"): mx.array([[1, 2], [0, 0]]),
        }
        metadata = (list(x_dict), list(edge_index_dict))

        # GNN(-1, ...) is not possible in MLX: give the input sizes instead
        model = to_hetero(GNN(32, 4), metadata, input_dims={"author": 16, "paper": 8})
        out = model(edge_index_dict, x_dict)
        >>> {k: v.shape for k, v in out.items()}
        {'author': (4, 4), 'paper': (5, 4)}

        # Built-in models work too
        from mlx_graphs.nn import GraphSAGE
        model = to_hetero(
            GraphSAGE(16, 32, num_layers=2, out_features_dim=4, jk="cat"),
            metadata,
            input_dims={"author": 16, "paper": 8},
        )

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

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 · mlx_graphs/nn/to_hetero.py