Skip to content

from_pyg

from_pyg(data: Data) -> GraphData

Converts a torch_geometric.data.Data object to a mlx_graphs.data.GraphData.

The attributes are renamed as follows:

  • x -> node_features
  • edge_attr -> edge_features
  • edge_weight -> edge_weights
  • y -> node_labels if it has one entry per node (and the graph has more than one node), graph_labels otherwise

Every other tensor attribute (e.g. train_mask, pos) is converted to an mx.array and kept under the same name, and plain Python scalars and strings are carried over as they are. num_nodes is always set explicitly, so isolated nodes are preserved. float64 tensors become float32 arrays.

torch and torch_geometric are optional dependencies, imported when the function is called.

Parameters:

Name Type Description Default
data Data

The PyG graph to convert. It must have an edge_index.

required

Returns:

Type Description
GraphData

The converted graph.

Example:

from torch_geometric.datasets import KarateClub

graph = from_pyg(KarateClub()[0])
# GraphData(
#     edge_index(shape=(2, 156), int64)
#     node_features(shape=(34, 34), float32)
#     node_labels(shape=(34,), int64)
#     train_mask(shape=(34,), bool))
graph.num_nodes
# 34
Source code in mlx_graphs/utils/pyg.py
def from_pyg(data: "Data") -> "GraphData":
    """
    Converts a :class:`torch_geometric.data.Data` object to a
    :class:`mlx_graphs.data.GraphData`.

    The attributes are renamed as follows:

    - ``x`` -> ``node_features``
    - ``edge_attr`` -> ``edge_features``
    - ``edge_weight`` -> ``edge_weights``
    - ``y`` -> ``node_labels`` if it has one entry per node (and the graph
      has more than one node), ``graph_labels`` otherwise

    Every other tensor attribute (e.g. ``train_mask``, ``pos``) is converted
    to an ``mx.array`` and kept under the same name, and plain Python scalars
    and strings are carried over as they are. ``num_nodes`` is always set
    explicitly, so isolated nodes are preserved. float64 tensors become
    float32 arrays.

    ``torch`` and ``torch_geometric`` are optional dependencies, imported when
    the function is called.

    Args:
        data: The PyG graph to convert. It must have an ``edge_index``.

    Returns:
        The converted graph.

    Example:

    .. code-block:: python

        from torch_geometric.datasets import KarateClub

        graph = from_pyg(KarateClub()[0])
        # GraphData(
        #     edge_index(shape=(2, 156), int64)
        #     node_features(shape=(34, 34), float32)
        #     node_labels(shape=(34,), int64)
        #     train_mask(shape=(34,), bool))
        graph.num_nodes
        # 34
    """
    torch, Data = _import_pyg()
    from mlx_graphs.data import GraphData

    if not isinstance(data, Data):
        raise TypeError(
            f"from_pyg expects a torch_geometric.data.Data object (got {type(data)})"
        )
    if data.edge_index is None:
        raise ValueError("The PyG graph has no `edge_index`")

    def to_mlx(tensor: Any) -> mx.array:
        return mx.array(tensor.detach().cpu().numpy())

    num_nodes = data.num_nodes
    attributes: dict[str, Any] = {}
    for key, value in data.to_dict().items():
        if key in ("edge_index", "num_nodes"):
            continue
        if isinstance(value, np.ndarray):
            value = torch.from_numpy(value)
        if isinstance(value, torch.Tensor):
            if key == "y":
                # a one-entry `y` of a single-node graph is a graph label
                per_node = value.dim() > 0 and value.shape[0] == num_nodes > 1
                key = "node_labels" if per_node else "graph_labels"
            attributes[_PYG_TO_MLX_NAMES.get(key, key)] = to_mlx(value)
        elif isinstance(value, _SCALAR_TYPES):
            attributes[key] = value

    graph = GraphData(edge_index=to_mlx(data.edge_index), **attributes)
    graph.num_nodes = num_nodes
    return graph

from mlx_graphs.utils import from_pyg · mlx_graphs/utils/pyg.py