Skip to content

MetaPath2Vec

Warning

This tutorial is experimental and requires mlx_cluster>=0.1.2 to be installed.

Goal: learn node embeddings for a heterogeneous graph (a graph with several node types) using meta-path guided random walks, first on a toy graph you can inspect by hand, then on the DBLP citation network.

Concepts: heterogeneous graphs, meta-paths, skip-gram with negative sampling, MetaPath2Vec

MetaPath2Vec pipeline: on DBLP (4,057 authors, 14,328 papers, 7,723 terms, 20 conferences, edges in both directions), mlx_cluster.metapath_random_walk samples 5 walks of 50 steps per author along the APCPA meta-path; pos_sample cuts them into windows of 7 nodes and neg_sample draws 5 negatives per window with random nodes of the right type; one 128-dimensional Embedding for authors, papers and conferences is trained without labels with the skip-gram loss and Adam for 5 epochs; a Linear layer on the frozen author embeddings predicts the 4 research areas and is scored by test accuracy; the notebook first runs the same steps on a toy graph of 6 authors, 6 papers and 2 venues with the APVPA meta-path

Why not just Node2Vec?

Node2Vec learns embeddings by running random walks and training nodes that appear close together in a walk to have similar vectors. On a heterogeneous graph (authors, papers and venues, say) a plain random walk has two problems:

  1. It ignores what the edges mean. A walk wanders between types at random, so the "context" of an author is an arbitrary mix of papers, venues and other authors.
  2. Frequent types take over. If there are far more papers than venues, walks mostly bounce between papers, and venues barely show up in anyone's context.

metapath2vec (Dong et al., KDD 2017) fixes both by forcing walks to follow a meta-path: a fixed sequence of edge types such as

author --writes--> paper --published_in--> venue --publishes--> paper --written_by--> author

(APVPA for short). Every walk alternates through those types in that order, so two authors are in each other's context when they publish at the same venue. That is the notion of similarity this meta-path encodes. A different meta-path, e.g. APA (co-authorship), would encode a different one.

import mlx.core as mx
import mlx.nn as nn
import mlx.optimizers as optim
import numpy as np

from mlx_graphs.algorithms import MetaPath2Vec

mx.random.seed(0)
np.random.seed(0)

A toy graph

Six authors, six papers and two venues. Authors 0–2 write papers 0–2, which appear at venue 0; authors 3–5 write papers 3–5, which appear at venue 1.

Edges are stored per edge type as (src, rel, dst) -> [2, num_edges], with node ids local to each type (the same format as HeteroGraphData.edge_index_dict). Walks only move along edges in their stored direction, so each relation is added in both directions: writes / written_by and published_in / publishes.

writes = mx.array(
    [
        [0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5],  # author
        [0, 1, 1, 2, 2, 0, 3, 4, 4, 5, 5, 3],  # paper
    ]
)
published_in = mx.array(
    [
        [0, 1, 2, 3, 4, 5],  # paper
        [0, 0, 0, 1, 1, 1],  # venue
    ]
)
edge_index_dict = {
    ("author", "writes", "paper"): writes,
    ("paper", "written_by", "author"): writes[::-1],
    ("paper", "published_in", "venue"): published_in,
    ("venue", "publishes", "paper"): published_in[::-1],
}

metapath = [
    ("author", "writes", "paper"),
    ("paper", "published_in", "venue"),
    ("venue", "publishes", "paper"),
    ("paper", "written_by", "author"),
]

Step 1: meta-path random walks

The walks are sampled by mlx_cluster.metapath_random_walk, which runs on the CPU or on Metal. Step l of a walk follows edge type metapath[l % len(metapath)], picking a random neighbor of that type. Because APVPA ends at the type it starts from (author), it is cyclic and walks can be longer than the meta-path: they just go around again.

Let's sample two walks of 8 steps from author 0, and print the type of each position next to the node id:

from mlx_cluster import build_metapath_csr, metapath_node_types, metapath_random_walk

csr = build_metapath_csr(edge_index_dict, metapath)
nodes, _ = metapath_random_walk(csr, mx.array([0, 0]), walk_length=8, stream=mx.cpu)
types = metapath_node_types(metapath, walk_length=8)

for walk in nodes.tolist():
    print(" -> ".join(f"{t[0].upper()}{n}" for t, n in zip(types, walk)))
A0 -> P1 -> V0 -> P1 -> A0 -> P1 -> V0 -> P0 -> A2
A0 -> P0 -> V0 -> P1 -> A0 -> P1 -> V0 -> P2 -> A1

Every walk follows A → P → V → P → A → …, and since the two groups never share a venue, walks from author 0 never reach authors 3–5.

If a node has no neighbor of the next required type (an author with no papers, say), the walk stops there and the remaining positions are -1.

Step 2: from walks to training pairs (skip-gram)

MetaPath2Vec cuts every walk into overlapping context windows of context_size nodes. In each window, the first node is paired with the other context_size - 1 nodes, and the model learns to give those pairs a high dot product. A walk of walk_length + 1 nodes gives walk_length + 2 - context_size windows.

All node types on the meta-path share one embedding table (authors first, then papers, then venues here), so pos_sample returns global row indices into that table. Windows that run into dead-end padding are dropped.

model = MetaPath2Vec(
    edge_index_dict,
    embedding_dim=16,
    metapath=metapath,
    walk_length=12,
    context_size=5,
    walks_per_node=10,
    num_negative_samples=5,
    use_gpu=False,  # set to True to sample walks with Metal
)
print("Node types:", model.node_types)
print("Nodes per type:", model.num_nodes_dict)
print("Embedding table:", model.embedding.weight.shape)

pos = model.pos_sample(mx.array([0]))
print("Positive windows:", pos.shape)
print(pos[:3])
Node types: ['author', 'paper', 'venue']
Nodes per type: {'author': 6, 'paper': 6, 'venue': 2}
Embedding table: (14, 16)
Positive windows: (90, 5)
array([[0, 7, 12, 7, 1],
       [0, 6, 12, 7, 1],
       [0, 7, 12, 6, 2]], dtype=int64)

Step 3: negative samples, by type

Only learning "these pairs are close" would let every embedding collapse to the same vector. Negative sampling adds random pairs that should be far apart.

MetaPath2Vec uses heterogeneous negative sampling: a negative walk starts at the real start node, and every other position gets a random node of the type the meta-path puts there. So an author is contrasted with random papers at paper positions and random venues at venue positions. These are harder, more informative negatives than random nodes of any type.

neg = model.neg_sample(mx.array([0]))
# walks_per_node * num_negative_samples times as many as for positives
print("Negative windows:", neg.shape)
print(neg[:3])
Negative windows: (450, 5)
array([[0, 10, 12, 9, 3],
       [0, 10, 12, 10, 3],
       [0, 7, 13, 8, 0]], dtype=int64)

The loss is the usual skip-gram objective:

\[ \mathcal{L} = -\log \sigma(\mathbf{z}_u^\top \mathbf{z}_v) \;-\; \sum_{n} \log \sigma(-\mathbf{z}_u^\top \mathbf{z}_n) \]

for positive pairs \((u, v)\) and negative pairs \((u, n)\), averaged over the batch.

Step 4: training

model.dataloader(batch_size) goes over every node of the start type (authors) once per epoch and yields (pos, neg) for each mini-batch:

optimizer = optim.Adam(learning_rate=0.05)
loss_and_grad = nn.value_and_grad(model, model.loss)

for epoch in range(50):
    losses = []
    for pos, neg in model.dataloader(batch_size=6):
        loss, grads = loss_and_grad(pos, neg)
        optimizer.update(model, grads)
        mx.eval(model.parameters(), optimizer.state)
        losses.append(loss.item())
    if epoch % 10 == 0 or epoch == 49:
        print(f"Epoch {epoch:2d} | loss {np.mean(losses):.4f}")
Epoch  0 | loss 1.4065
Epoch 10 | loss 1.1389
Epoch 20 | loss 1.1430
Epoch 30 | loss 1.1360
Epoch 40 | loss 1.1326
Epoch 49 | loss 1.1203

Step 5: using the embeddings

model(node_type) returns the embeddings of one node type (or model(node_type, ids) for some of them). The cosine similarity between authors should show two blocks: authors who publish at the same venue are close, the others far apart.

emb = model("author")
emb = emb / mx.linalg.norm(emb, axis=1, keepdims=True)
print(np.round(np.asarray(emb @ emb.T), 2))
[[ 1.    0.6   0.8  -0.83 -0.84 -0.8 ]
 [ 0.6   1.    0.61 -0.78 -0.59 -0.61]
 [ 0.8   0.61  1.   -0.8  -0.67 -0.72]
 [-0.83 -0.78 -0.8   1.    0.68  0.65]
 [-0.84 -0.59 -0.67  0.68  1.    0.73]
 [-0.8  -0.61 -0.72  0.65  0.73  1.  ]]

A real dataset: DBLP

DBLP has 4,057 authors, 14,328 papers, 7,723 terms and 20 conferences. Each author is labeled with one of four research areas (database, data mining, AI, information retrieval). Its edge types are named (src, "to", dst).

We train on the APCPA meta-path (author → paper → conference → paper → author) without using any labels. Then, to see what the embeddings learned, we fit a logistic regression on the frozen author embeddings of the training split and measure its accuracy at predicting the research area.

These cells are not executed in the docs. Run them locally on a Mac with mlx_cluster installed. The same code is in examples/metapath2vec_dblp.py.

from mlx_graphs.datasets import DBLP

data = DBLP()[0]
print(data.num_nodes)
print(list(data.edge_index_dict))
Loading DBLP data ... Downloading DBLP raw data ... Downloading /Users/vinaypandya/mlx_projects/mlx-graphs/docs/source/tutorials/notebooks/.mlx_graphs_data/DBLP/raw/DBLP_processed.zip?dl=1 from https://www.dropbox.com/s/yh4grpeks87ugr2/DBLP_processed.zip?dl=1...
100%|██████████| 258M/258M [00:03<00:00, 73.8MB/s] 
Extracting file to /Users/vinaypandya/mlx_projects/mlx-graphs/docs/source/tutorials/notebooks/.mlx_graphs_data/DBLP/raw
Done
Processing DBLP raw data ... Done
Saving processed DBLP data ... Done
{'author': 4057, 'paper': 14328, 'term': 7723, 'conference': 20}
[('author', 'to', 'paper'), ('paper', 'to', 'author'), ('paper', 'to', 'term'), ('paper', 'to', 'conference'), ('term', 'to', 'paper'), ('conference', 'to', 'paper')]
dblp_metapath = [
    ("author", "to", "paper"),
    ("paper", "to", "conference"),
    ("conference", "to", "paper"),
    ("paper", "to", "author"),
]

model = MetaPath2Vec(
    data.edge_index_dict,
    embedding_dim=128,
    metapath=dblp_metapath,
    walk_length=50,
    context_size=7,
    walks_per_node=5,
    num_negative_samples=5,
    num_nodes_dict=data.num_nodes,
    use_gpu=True,
)
optimizer = optim.Adam(learning_rate=0.01)
loss_and_grad = nn.value_and_grad(model, model.loss)

for epoch in range(5):
    losses = []
    for pos, neg in model.dataloader(batch_size=128):
        loss, grads = loss_and_grad(pos, neg)
        optimizer.update(model, grads)
        mx.eval(model.parameters(), optimizer.state)
        losses.append(loss.item())
    print(f"Epoch {epoch} | loss {np.mean(losses):.4f}")
Epoch 0 | loss 1.0923
Epoch 1 | loss 1.0183
Epoch 2 | loss 1.0009
Epoch 3 | loss 0.9921
Epoch 4 | loss 0.9884
def mask_to_index(mask):
    return mx.array(np.flatnonzero(np.asarray(mask)), dtype=mx.int64)


train_idx = mask_to_index(data.author_train_mask)
test_idx = mask_to_index(data.author_test_mask)
labels = data.node_labels_dict["author"].astype(mx.int64)

# Frozen, standardized author embeddings
emb = mx.stop_gradient(model("author"))
emb = (emb - emb[train_idx].mean(axis=0)) / (emb[train_idx].std(axis=0) + 1e-6)

clf = nn.Linear(emb.shape[1], 4)
clf_optimizer = optim.Adam(learning_rate=0.01)


def clf_loss(clf):
    logits = clf(emb[train_idx])
    return nn.losses.cross_entropy(logits, labels[train_idx], reduction="mean")


clf_loss_and_grad = nn.value_and_grad(clf, clf_loss)
for _ in range(300):
    _, grads = clf_loss_and_grad(clf)
    clf_optimizer.update(clf, grads)
    mx.eval(clf.parameters(), clf_optimizer.state)

test_acc = (clf(emb[test_idx]).argmax(axis=-1) == labels[test_idx]).mean().item()
print(f"Test accuracy: {test_acc:.3f}")
Test accuracy: 0.882

Tips

  • Pick the meta-path for the similarity you want. APCPA groups authors by venue, APA by co-authorship, APTPA (via terms) by vocabulary.
  • Long walks need a cyclic meta-path, one that ends at the type it starts from. Otherwise walk_length can be at most len(metapath).
  • Add reverse edges. Walks only follow the stored direction, so for an APA-style path you need both author → paper and paper → author.
  • Only start-type nodes start walks. Other types are embedded through the walks that pass through them. Types the meta-path never visits get no embedding.
  • Sampling on the GPU (use_gpu=True) pays off on large graphs. On tiny ones the CPU is often just as fast.