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
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:
- 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.
- 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
(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.
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)))
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])
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.
The loss is the usual skip-gram objective:
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}")
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.
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_clusterinstalled. The same code is inexamples/metapath2vec_dblp.py.
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}")
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}")
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_lengthcan be at mostlen(metapath). - Add reverse edges. Walks only follow the stored direction, so for an
APA-style path you need both
author → paperandpaper → 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.