Skip to content

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")).

Methods:

Name Description
__call__

Runs the model on dict-valued inputs.

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.

__call__

__call__(*args, **kwargs)

Runs the model on dict-valued inputs.

Parameters:

Name Type Description Default
*args

The arguments of the original model, with node-level arrays replaced by dicts keyed by node type and edge-level arrays by dicts keyed by edge type. Other values are passed unchanged.

()
**kwargs

Keyword arguments, likewise.

{}

Returns:

Type Description

The output of the original model, with node-level arrays replaced

by dicts keyed by node type.

Source code in mlx_graphs/nn/to_hetero.py
def __call__(self, *args, **kwargs):
    """Runs the model on dict-valued inputs.

    Args:
        *args: The arguments of the original model, with node-level arrays
            replaced by dicts keyed by node type and edge-level arrays by
            dicts keyed by edge type. Other values are passed unchanged.
        **kwargs: Keyword arguments, likewise.

    Returns:
        The output of the original model, with node-level arrays replaced
        by dicts keyed by node type.
    """
    ctx, args, kwargs = self._pack(args, kwargs)
    return self._run(ctx, args, kwargs)

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