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:
- The model is deep-copied. Every
MessagePassinglayer 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. aGraphSAGEused inside a bigger model) are rewritten recursively. - 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. - 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 withaggr. 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 |
Source code in mlx_graphs/nn/to_hetero.py
874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 | |
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
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.Sequentialstarting with aLinear,SAGEConv,GraphConv,GATConv,GATv2Conv, andGINConv/GCNConvwhen 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 withoutinput_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_indexbefore 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);
GCNConvand 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.
|
required |
aggr
|
str
|
How to combine the outputs of the edge types sharing a
destination node type: |
'sum'
|
input_map
|
Optional[dict[str, str]]
|
Optional |
None
|
input_dims
|
Optional[dict[NodeType, int]]
|
Optional number of input features per node type, e.g.
|
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
Source code in mlx_graphs/nn/to_hetero.py
1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 | |
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:
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.
|
required |
num_bases
|
int
|
The number of bases (copies of every message passing layer). |
required |
in_channels
|
Optional[dict[str, int]]
|
Optional |
None
|
input_map
|
Optional[dict[str, str]]
|
Optional |
None
|
input_dims
|
Optional[dict[NodeType, int]]
|
Number of input features per node type, needed with
|
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)
References
Source code in mlx_graphs/nn/to_hetero.py
1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 | |
from mlx_graphs.nn import to_hetero · mlx_graphs/nn/to_hetero.py