Before you start: review of the earlier sessions
The thread so far. The second block of the course applies GNNs to richer data. Session 9 adds types; sessions 10–13 are the knowledge-graph, recommender and database instances of the same idea.
What this session takes from earlier ones
Those sessions in one minute each
Lecture 8 · Graph Transformers
A transformer is a GNN on the complete graph; a graph transformer re-injects the real graph via tokens, positional encodings, and attention biases — and the positional encodings must respect the symmetries (sign/basis) of whatever spectral object they come from.
\(P\): positional encodings (one row per node); \(C\): edge / shortest-path biases \(c_{ij}\). Setting \(C_{ij}=-\infty\) for non-edges recovers neighbourhood-restricted attention (GAT-like).
Lecture 4 · A General Perspective on GNNs
A GNN layer is "message, then order-free aggregation (including yourself)"; architectures differ in how neighbours are weighted, and depth must be matched to the receptive field you need because too many layers smooth everything into one vector.
GCN is the special case \(\alpha_{vu}=1/|N(v)|\) (fixed); GAT learns \(e_{vu}=a(\mathbf{W}\mathbf{h}_u,\mathbf{W}\mathbf{h}_v)\).
Lecture 1 · Introduction — Machine Learning with Graphs
A graph model must work for any number of nodes and give the same answer no matter how the nodes are numbered — everything else is a design choice about what the nodes and edges mean.
A homogeneous graph is the special case \(|R| = |T| = 1\). Permutation: relabelling nodes with a permutation matrix \(P\) turns \(A\) into \(PAP^\top\); a graph-level model \(f\) must satisfy \(f(PAP^\top, PX) = f(A, X)\).
Lecture 5 · GNN Augmentation and Training
Choose the computation graph deliberately (features, virtual nodes, sampling), pick the head that matches the task level, and split so that information from validation/test can never leak into training through message passing.
Warm-up: answer these before you read on
In what sense is a transformer a GNN? from Lecture 8
Each token aggregates messages (values) from all other tokens with attention weights; that is message passing on the complete graph with attention as the aggregation weights.
Where does GAT put its parameters that GCN does not have? from Lecture 4
In the attention mechanism: a learned function of the pair (node, neighbour) that produces the aggregation weights, instead of fixed degree-based weights.
Name the three task levels and one concrete example of each. from Lecture 1
Node level (classify a protein's function), link level (recommend a product to a user), graph level (predict a molecule's toxicity).
When would you add a virtual node? from Lecture 5
When the graph is too sparse for messages to travel, e.g. long chains; the virtual node connects to everything, so any two nodes are two hops apart.
More questions from every session you have reached, with spaced repetition: the cumulative review.
In short
Real graphs mix kinds of things: authors and papers, users and items and queries, drugs and proteins and diseases. A heterogeneous graph has node types and edge types; the key unit is the relation type \((\text{source type},\ \text{edge type},\ \text{target type})\), e.g. (Author, writes, Paper).
You could just add one-hot "type" features and use an ordinary GNN. You need a heterogeneous model when different types have different feature shapes (a 4-dim author vs a 5-dim paper) or when relations mean genuinely different interactions ("translate to French" ≠ "translate to Chinese").
The core idea: model each relation type separately. R-GCN gives each relation its own weight matrix, normalises per relation, sums everything plus a self-loop. That blows up the parameter count, so we regularise with block-diagonal or basis-decomposed weights. The general design space adds per-relation messages and two-stage aggregation; the Heterogeneous Graph Transformer (HGT) makes attention type-aware by factorising weights by node type and edge type.
The picture: one R-GCN update
How to read it (hover a step)
- A's in-neighbours arrive along edges of different relation types \(r_1,r_2,r_3\) (colours). Messages flow only along edge direction.
- Each relation type has its own weight matrix \(\mathbf{W}_r^{(l)}\). Messages are normalised by the number of neighbours of that relation: \(c_{v,r}=|N_v^r|\).
- All relation-specific messages are summed…
- …together with a self-loop message \(\mathbf{W}_0^{(l)}\mathbf{h}_A^{(l)}\), then passed through \(\sigma\).
1 · What makes a graph heterogeneous
Two node types (paper, author) × two edge types (like, cite) already give 8 possible relation types: (Paper, Cite, Paper), (Author, Cite, Paper), (Paper, Like, Author), … We describe an edge by its relation type rather than just its edge type, because the relation captures the interaction between edge and endpoints.
\(\tau(v)\): node type; \(\phi(u,v)\): edge type; \(r(u,v)\): relation type. Other definitions exist; all describe graphs with node and edge types.
Examples: biomedical KGs (node: Migraine; relation: (fulvestrant, Treats, Breast Neoplasms)); event graphs (flight UA689, Origin, LAX); e-commerce (user, item, query, location; purchase, visit, search) — where types have different feature spaces; academic graphs (author, paper, venue, field; publish, cite).
Types can be one-hot features. So when do we really need a heterogeneous model?
(1) Different feature shapes: a 4-dim author vector and a 5-dim paper vector can't share one weight matrix without padding hacks. (2) Different interaction semantics: a single shared \(W\) forces "cites" and "is written by" to transform messages the same way, adjusted only by a feature bit. A heterogeneous model is more expressive — at the price of more computation, storage and implementation complexity. Don't use it by reflex.
2 · Relational GCN (R-GCN)
Start from GCN. On a directed graph with one relation, pass messages only along edge direction. With several relation types, use different weights for different relation types, plus a self-loop:
As message + aggregation: message from each neighbour of relation \(r\): \(\mathbf{m}_{u,r}=\frac{1}{c_{v,r}}\mathbf{W}_r\mathbf{h}_u\); self-message \(\mathbf{m}_v=\mathbf{W}_0\mathbf{h}_v\); aggregation = sum, then activation.
Scalability: the parameter explosion
Each relation has \(L\) matrices of size \(d^{(l+1)}\times d^{(l)}\). Parameters grow linearly with the number of relations — knowledge graphs have hundreds or thousands — so overfitting becomes a problem. Two regularisers:
- Block-diagonal matrices: make \(\mathbf{W}_r\) sparse with \(B\) blocks. Parameters drop from \(d^{(l+1)}\!\times d^{(l)}\) to \(B\times\frac{d^{(l+1)}}{B}\times\frac{d^{(l)}}{B}\). Limitation: only nearby dimensions interact.
- Basis / dictionary learning: share weights across relations: \(\mathbf{W}_r=\sum_{b=1}^{B}a_{rb}\,\mathbf{V}_b\), with shared basis matrices \(\mathbf{V}_b\). Each relation learns only \(B\) scalars \(\{a_{rb}\}\).
3 · R-GCN for node classification and link prediction
Entity / node classification: use the final layer \(\mathbf{h}_A^{(L)}\in\mathbb{R}^k\) as class scores for node A.
Link prediction with relation types: score a triple with a relation-specific function, e.g. \(f_r(\mathbf{h}_E,\mathbf{h}_A)=\mathbf{h}_E^\top\mathbf{W}_r\mathbf{h}_A\). Split edges as in Lecture 5, but per relation type: each relation's homogeneous subgraph gets its own training-message / training-supervision / validation / test edges.
Training
- Score the supervision edge \((E,r_3,A)\) with R-GCN embeddings.
- Create a negative edge by corrupting the tail: \((E,r_3,B)\), \((E,r_3,D)\). Negatives must not be existing message or supervision edges — \((E,r_3,C)\) is not a negative.
- Score negatives; optimise cross-entropy: \(\ell=-\log\sigma(f_{r_3}(h_E,h_A))-\log(1-\sigma(f_{r_3}(h_E,h_B)))\).
Evaluation (ranking)
For validation edge \((E,r_3,D)\): score it and every candidate \((E,r_3,v)\) that is not a known edge; get its rank \(RK\). Report Hits@k \(=\mathbb{1}[RK\le k]\) and reciprocal rank \(1/RK\) (averaged: MRR). Higher is better.
Benchmark: ogbn-mag
From the Microsoft Academic Graph: papers (736k), authors (1.1M), institutions (9k), fields of study (60k); relations affiliated-with, writes, cites, has-topic. Task: predict each paper's venue (349 classes) from its 128-dim word2vec features and the graph. Time-based split: train before 2018, test after. R-GCN is a strong baseline; SOTA methods (e.g. SeHGNN) combine ComplEx embeddings (next lecture) with simplified GCNs.
4 · The heterogeneous GNN design space
- Message: one message function per relation type: \(\mathbf{m}_u^{(l)}=\text{MSG}_r^{(l)}(\mathbf{h}_u^{(l-1)})\), e.g. \(\mathbf{W}_r^{(l)}\mathbf{h}_u^{(l-1)}\), where \(r=(u,e,v)\).
- Aggregation, two-stage: within each relation, then across relations: \(\mathbf{h}_v^{(l)}=\text{AGG}_{all}\big(\text{AGG}_r(\{\mathbf{m}_u:u\in N_r(v)\})\big)\), e.g. Concat over relations of Sum within a relation.
- Layer connectivity: pre/post-processing MLPs per node type: \(\mathbf{h}_v=\text{MLP}_{T(v)}(\mathbf{h}_v)\); skip connections, normalisation.
- Graph manipulation: feature augmentation (degree within each relation or across the full graph); neighbour/subgraph sampling within each relation type (so every type is covered) or across the full graph.
- Prediction heads: per node type \(\mathbf{W}_{T(v)}^{(H)}\), per relation \(\text{Linear}_r(\text{Concat}(\mathbf{h}_u,\mathbf{h}_v))\), and graph-level AGG over per-type heads.
5 · Heterogeneous Graph Transformer (HGT)
Can we adapt GAT? GAT can't represent different node and edge types, and a separate attention network per relation type is too expensive. HGT uses Transformer-style scaled dot-product attention, \(\text{softmax}(QK^\top/\sqrt{d_k})V\), and decomposes the weights by type:
- Key and query projections depend on the node types: \(K(s)=\text{K-Linear}_{\tau(s)}(H[s])\), \(Q(t)=\text{Q-Linear}_{\tau(t)}(H[t])\).
- An edge-type matrix sits in between: \(\text{ATT-head}(s,e,t)=K(s)\,W^{ATT}_{\phi(e)}\,Q(t)^\top\).
- Messages similarly: \(\text{M-Linear}_{\tau(s)}(H[s])\,W^{MSG}_{\phi(e)}\).
With 3 node types and 2 edge types: 3 node weight matrices + 2 edge matrices, instead of 3×2×3 = 18 relation-type matrices. On ogbn-mag HGT uses far fewer parameters than R-GCN and performs better.
The mathematics, step by step
A heterogeneous graph has several kinds of nodes and edges, and the formulas of this session are the earlier ones with an extra index for the kind. The work is in keeping track of that index and of how many parameters it costs. The cards define the object, give the R-GCN layer, count its parameters with and without sharing, and define the ranking metrics used for link prediction.
Symbols used in this session
| symbol | meaning | what kind of object |
|---|---|---|
| \(\tau(v)\) | type of node \(v\) (author, paper, …) | an element of the set of node types |
| \(\phi(u,v)\) | type of the edge from \(u\) to \(v\) (writes, cites, …) | an element of the set of edge types |
| \(r=(\tau(u),\phi(u,v),\tau(v))\) | relation type: source type, edge type, target type | a triple |
| \(R\) | the set of relation types | finite set |
| \(N_v^r\) | neighbours of \(v\) under relation \(r\) | set of nodes |
| \(c_{v,r}\) | normalisation constant, \(|N_v^r|\) | whole number |
| \(\mathbf W_r^{(l)},\ \mathbf W_0^{(l)}\) | weight matrix of relation \(r\) in layer \(l\); weight matrix for the node itself | \(d\times d\) matrices (parameters) |
| \(\mathbf V_b,\ a_{rb}\) | shared basis matrices and the coefficients that mix them into \(\mathbf W_r\) | \(d\times d\) matrices; real numbers |
| \(\text{rank}_i\) | position of the correct answer of query \(i\) among all candidates, 1 = best | whole number ≥ 1 |
1A heterogeneous graph
In words. A graph plus two labelling functions: one gives every node a type, the other gives every edge a type. The relation type of an edge is the triple (type of its source, its own type, type of its target).
Why it has this form. The triple matters because the same edge type can connect different kinds of nodes ('likes' from a user to a post or to a page), and messages along them should be treated differently. A homogeneous graph is the special case with one node type and one edge type. Nodes of different types usually have features of different dimensions, so each type first gets its own linear map into a common dimension.
Watch out. Edge types are directed even when the underlying fact is symmetric; without reverse relations a paper never hears from the venue it was published in.
2The R-GCN layer
In words. For each relation separately, average the vectors of the neighbours reached through that relation and transform the average with that relation's own matrix. Add the results over all relations, add the node's own transformed vector, apply the non-linearity.
Why it has this form. It is the GCN layer of Lecture 3 with one weight matrix per relation instead of one for all. The inner sum divided by \(c_{v,r}\) is a mean over the neighbours of one relation; normalising per relation keeps a relation with a thousand neighbours from drowning a relation with two. The outer sum over \(r\) treats the relations as separate channels that are added at the end.
Watch out. Each relation has its own matrix in every layer. A relation seen on only a few edges gets a full \(d\times d\) matrix trained on almost no data, which over-fits (next card).
3Counting and sharing parameters
In words. Instead of learning a free matrix for every relation, learn a small number \(B\) of basis matrices shared by all relations, and for each relation only \(B\) numbers saying how to mix them.
Why it has this form. A free \(d\times d\) matrix has \(d^2\) entries, so \(|R|\) relations cost \(|R|d^2\) per layer: the count grows with every relation added. With a basis, the \(d^2\)-sized objects no longer multiply with \(|R|\); a relation costs only its \(B\) coefficients. Rare relations borrow statistical strength from frequent ones through the shared \(\mathbf V_b\). The alternative, block-diagonal matrices with \(B\) blocks of size \(d/B\), costs \(|R|\cdot B\cdot(d/B)^2=|R|d^2/B\) and keeps relations independent but lets only coordinates inside a block interact.
Watch out. Sharing is a restriction: with a basis, all relation matrices lie in a \(B\)-dimensional family. If two relations need genuinely unrelated transformations and \(B\) is too small, accuracy suffers.
4Ranking metrics for link prediction
In words. For each test edge, score the true target against many wrong candidates and note the position of the true one. MRR averages one over that position; Hits@\(k\) is the share of queries whose true answer is in the top \(k\).
Why it has this form. For a test edge \((u,r,v)\) there is one right answer and very many wrong ones, so accuracy is uninformative: what matters is how near the top the right answer is. The reciprocal in MRR makes the difference between rank 1 and rank 2 (0.5) count far more than between rank 100 and rank 200 (0.005), which matches how a ranked list is used. Hits@\(k\) is the cruder question 'would it appear on the first page?'. Negatives are the same head and relation with other tails, excluding tails that are themselves true edges.
Watch out. Ranks are only comparable when the number and choice of negatives is the same. A rank of 3 among 100 sampled negatives is not a rank of 3 among all entities.
5Heterogeneous attention (HGT): parameters per type, not per triple
In words. The attention score of an edge is built from three pieces: a key map chosen by the source node's type, a small matrix chosen by the edge type, and a query map chosen by the target node's type.
Why it has this form. One matrix per relation triple would again cost a number of matrices equal to the number of triples. Decomposing the triple into its three parts needs only one matrix per node type and one per edge type, and a triple that is rare still gets well-trained pieces, because its node types and edge type each appear in other triples. \(\mu\) is one learned number per triple that says how important the relation is overall. The scores of all incoming edges of \(t\) then go through one softmax, as in Lecture 8.
Watch out. The formula is one attention head for one edge; the message itself is decomposed the same way, and the result is added to the target's previous vector through a type-specific linear map.
Check yourself
Questions from the lecture, in order. Answer each one in your head (or on paper) before you open it. If one stumps you, follow the link to the walkthrough block it comes from.
Check yourself: with \(T\) node types and \(E\) edge types, how many relation types are possible? show answer
\(T\cdot E\cdot T\). Real graphs use only some of them.
Check yourself: if there is only one relation and \(\mathbf{W}_0=\mathbf{W}_r\), what does R-GCN become? show answer
GCN with a self-loop on a directed graph, mean over in-neighbours.
from The R-GCN layer
Check yourself: why pool each node type separately at graph level? show answer
A graph with 1,000 papers and 3 authors would otherwise have its author signal averaged away.
from Design space: layers, graph manipulation and prediction heads
Check yourself: for a graph with 4 node types and 4 edge types (like ogbn-mag), how many relation-type matrices would unfactorised attention need in the worst case, and how many does HGT need per head? show answer
\(4\cdot4\cdot4=64\) vs. about \(4+4\) groups of matrices: K-, Q-, M-Linear per node type plus \(W^{ATT}\), \(W^{MSG}\) per edge type.
from Summary
Lecture walkthrough reference · slide by slide · opens on demand
The whole lecture in order, grouped by topic. Every drawing on the slides is redrawn here as a clean figure (click the step buttons where a figure has them), the heading of each block links to the matching pages of the official PDF, and the Review section after the walkthrough ties this session to the earlier ones. Read this and you do not need the deck.
- Why graphs with types?
- Definition and real examples
- Type or feature? When you really need a heterogeneous model
- From GCN to directed graphs to many relations
- The R-GCN layer
- Scalability: block-diagonal and basis weights
- Using R-GCN: node classification and link prediction setup
- Training R-GCN for link prediction
- Evaluating link prediction by ranking: Hits@k and reciprocal rank
- Benchmark: ogbn-mag, and R-GCN summary
- Design space: heterogeneous message and aggregation
- Design space: layers, graph manipulation and prediction heads
- Attention recap: from GAT to Transformer-style attention
- HGT: decomposing attention by node type and edge type
- Summary
Why graphs with types? slides 5-9 ↗
Slide 5 sets the goal. Until now every graph had one edge type: all edges meant the same thing. Many real graphs have several node types and several edge types; these are called heterogeneous graphs. The lecture covers three ways to learn on them: Relational GCNs (R-GCN), the design space for heterogeneous GNNs, and the Heterogeneous Graph Transformer (HGT).
Slides 6–8 build one small example step by step. The same drawing of about ten nodes is coloured in two ways:
- Slide 6, 2 node types: red nodes are papers (type A), blue nodes are authors (type B).
- Slide 7, 2 edge types: yellow edges are Like, green edges are Cite.
- Slide 8 combines both: a graph can have multiple types of nodes and edges at the same time.
Slide 9 counts what this gives. An edge connects a start node and an end node, each of which can be a paper or an author, and the edge itself can be Like or Cite. So there are \(2\times 2\times 2 = 8\) possible relation types:
(Paper, Cite, Paper), (Paper, Like, Paper), (Paper, Cite, Author), (Paper, Like, Author), (Author, Cite, Author), (Author, Like, Author), (Author, Cite, Paper), (Author, Like, Paper).
A relation type is the triple (node_start, edge, node_end). We use the relation type to describe an edge, rather than only the edge type, because the relation type better captures the interaction between nodes and edges. "Cite" from a paper to a paper is a different act from "Cite" from an author to a paper, even though the edge label is the same.
Check yourself: with \(T\) node types and \(E\) edge types, how many relation types are possible? show answer
\(T\cdot E\cdot T\). Real graphs use only some of them.
Definition and real examples slides 10-13 ↗
Slide 10 gives the formal definition. A heterogeneous graph is
\[ G=(V,E,\tau,\phi) \]- Nodes with node types: \(v\in V\); the node type of \(v\) is \(\tau(v)\).
- Edges with edge types: \((u,v)\in E\) (an edge is described as a pair of nodes); the edge type of \((u,v)\) is \(\phi(u,v)\).
- The relation type of edge \((u,v)\) is the tuple \(r(u,v)=\big(\tau(u),\ \phi(u,v),\ \tau(v)\big)\).
Other definitions of heterogeneous graphs exist, but they all describe graphs with node types and edge types.
Slides 11–13 show that many real graphs are heterogeneous:
- Slide 11, biomedical knowledge graphs: example node Migraine; example relation (fulvestrant, Treats, Breast Neoplasms); example node type Protein; example edge type Causes. The figure is a dense graph with nodes coloured by type (drug, disease, protein, …).
- Slide 11, event graphs: example node SFO; example relation (UA689, Origin, LAX); node type Flight; edge type Destination.
- Slide 12, e-commerce graph: node types User, Item, Query, Location, …; edge types Purchase, Visit, Guide, Search, …. The figure shows users on the left, items in the middle (shoes, bags) and queries on the right. Important: different node types can have different feature spaces (a user profile vector and an item image vector need not have the same length or meaning).
- Slide 13, academic graph: node types Author, Paper, Venue, Field, …; edge types Publish, Cite, …. The figure links two authors to venues (KDD, ICML, AAAI) and venues to fields (Mining, Vision, Machine Learning). A standard benchmark comes from the Microsoft Academic Graph.
Can two nodes be linked by several edges of different types? Yes. A heterogeneous graph is in general a multigraph: an author can both "write" and "cite" the same paper, and each edge is handled by its own relation.
Type or feature? When you really need a heterogeneous model slides 14-16 ↗
Slide 14 makes an important observation: we could also treat node and edge types as features. For example, append a one-hot indicator: feature [1, 0] to each author node and [0, 1] to each paper node. In the same way, give edges a one-hot edge-type feature. Then the heterogeneous graph reduces to a standard graph, and any ordinary GNN can run on it.
So when do we need a heterogeneous graph? Slide 15 gives two cases:
- Different node or edge types have different shapes of features. An author node has a 4-dim feature, a paper node a 5-dim feature. One shared weight matrix cannot take inputs of different sizes.
- Different relation types represent different types of interactions. (English, translate, French) and (English, translate, Chinese) need different models: the transformation of a message should depend on the relation, not just be shifted by an extra feature bit.
There are many ways to convert a heterogeneous graph into a standard (homogeneous) graph, so the choice is a modelling decision.
Slide 16 states the trade-off. A heterogeneous graph is a more expressive representation: it captures different types of interactions between entities. But it also comes with costs: it is more expensive (computation, storage) and has a more complex implementation.
From GCN to directed graphs to many relations slides 18-23 ↗
Slide 18 recalls the GCN layer (Kipf and Welling, ICLR 2017):
\[ \mathbf{h}_v^{(l)}=\sigma\Big(\mathbf{W}^{(l)}\sum_{u\in N(v)}\frac{\mathbf{h}_u^{(l-1)}}{|N(v)|}\Big). \]As message + aggregation: the message of neighbour \(u\) is \(\mathbf{W}^{(l)}\mathbf{h}_u^{(l-1)}/|N(v)|\); the aggregation is the sum over \(u\in N(v)\) followed by \(\sigma\).
Slides 19–20 extend GCN step by step. Start with a directed graph with one relation. The input graph has six nodes A–F; A is the target node. How do we update A's representation? Answer (slide 20): only pass messages along the direction of edges. The computation graph of A therefore uses only A's in-neighbours (B, C, D), then their in-neighbours, and so on. The figure shows this tree: A at the left, boxes (neural networks) in the middle, and the in-neighbours of in-neighbours on the right.
Slide 21 asks: what if the graph has multiple relation types? The graph now has coloured, directed edges: B→A and D→A with relation \(r_1\), C→A with \(r_2\), C→B and E→C with \(r_3\), F→C with \(r_2\), F→E with \(r_1\).
Slide 22 gives the idea: use different neural network weights for different relation types: weights \(\mathbf{W}_{r_1}\) for \(r_1\), \(\mathbf{W}_{r_2}\) for \(r_2\), \(\mathbf{W}_{r_3}\) for \(r_3\). Slide 23 draws the resulting computation graph of A: each edge in the tree passes through the box with the colour of its relation, so a message coming over an \(r_2\) edge is transformed by \(\mathbf{W}_{r_2}\), and so on; then A aggregates.
Intuition: in ordinary GCN, every neighbour "speaks the same language". In R-GCN, each relation is a different channel with its own translator \(\mathbf{W}_r\). A citation and an authorship can now change A's embedding in different directions.
The R-GCN layer slides 24-26 ↗
Slide 24 adds a self-loop to GCN, so a node keeps its own information:
\[ \mathbf{h}_v^{(l)}=\sigma\Big(\sum_{u\in N(v)}\mathbf{W}^{(l)}\frac{\mathbf{h}_u^{(l-1)}}{|N(v)|}+\mathbf{W}^{(l)}\mathbf{h}_v^{(l-1)}\Big). \]Slide 25: now introduce a set of neural networks, one per relation type: a weight for rel_1, …, a weight for rel_N, plus a weight for the self-loop. The figure shows each weight acting on the star of neighbours that use that relation.
Slide 26 gives the definition of the Relational GCN:
\[ \mathbf{h}_v^{(l+1)}=\sigma\Big(\sum_{r\in R}\ \sum_{u\in N_v^r}\frac{1}{c_{v,r}}\mathbf{W}_r^{(l)}\mathbf{h}_u^{(l)}+\mathbf{W}_0^{(l)}\mathbf{h}_v^{(l)}\Big),\qquad c_{v,r}=|N_v^r|. \]Here \(R\) is the set of relations, \(N_v^r\) the neighbours of \(v\) under relation \(r\), and \(c_{v,r}\) the node degree within the relation. Written as message + aggregation:
- Message from each neighbour of a given relation: \(\mathbf{m}_{u,r}^{(l)}=\frac{1}{c_{v,r}}\mathbf{W}_r^{(l)}\mathbf{h}_u^{(l)}\).
- Self-loop message: \(\mathbf{m}_v^{(l)}=\mathbf{W}_0^{(l)}\mathbf{h}_v^{(l)}\).
- Aggregation: sum over messages from neighbours and the self-loop, then apply the activation: \(\mathbf{h}_v^{(l+1)}=\sigma\big(\mathrm{Sum}(\{\mathbf{m}_{u,r}^{(l)},u\in N(v)\}\cup\{\mathbf{m}_v^{(l)}\})\big)\).
Why normalise per relation, not by total degree? If node \(v\) has 100 "cites" neighbours and 2 "written-by" neighbours, a total-degree average would drown the two authors. Normalising each relation separately gives each relation channel its own averaged voice, and then the channels are added.
Check yourself: if there is only one relation and \(\mathbf{W}_0=\mathbf{W}_r\), what does R-GCN become? show answer
GCN with a self-loop on a directed graph, mean over in-neighbours.
Scalability: block-diagonal and basis weights slides 27-29 ↗
Slide 27 points at the cost. Each relation has \(L\) matrices \(\mathbf{W}_r^{(1)},\mathbf{W}_r^{(2)},\dots,\mathbf{W}_r^{(L)}\), and each \(\mathbf{W}_r^{(l)}\) has size \(d^{(l+1)}\times d^{(l)}\), where \(d^{(l)}\) is the hidden dimension in layer \(l\). So the number of parameters grows rapidly with the number of relations. Knowledge graphs can have thousands of relations, and many relations have few edges, so overfitting becomes an issue. Two methods regularise \(\mathbf{W}_r^{(l)}\):
(1) Block-diagonal matrices (slide 28). Key insight: make the weights sparse. Use a block-diagonal \(\mathbf{W}_r\): the figure shows a square matrix with a few small dense blocks on the diagonal and zeros elsewhere. With \(B\) blocks, the parameter count drops from
\[ d^{(l+1)}\times d^{(l)}\quad\text{to}\quad B\times\frac{d^{(l+1)}}{B}\times\frac{d^{(l)}}{B}. \]Limitation: only nearby neurons/dimensions can interact through \(\mathbf{W}\). Dimension 1 can never influence dimension \(d\) in one layer.
(2) Basis / dictionary learning (slide 29). Key insight: share weights across different relations. Represent each relation's matrix as a linear combination of basis transformations:
\[ \mathbf{W}_r=\sum_{b=1}^{B}a_{rb}\cdot\mathbf{V}_b, \]where the basis matrices \(\mathbf{V}_b\) are shared across all relations and \(a_{rb}\) is the importance weight of matrix \(\mathbf{V}_b\) for relation \(r\). Now each relation only needs to learn \(\{a_{rb}\}_{b=1}^{B}\), which is \(B\) scalars.
Intuition: the \(\mathbf{V}_b\) are a small vocabulary of "basic transformations", and each relation is a recipe that mixes them. Rare relations borrow statistical strength from frequent ones, because they share the same \(\mathbf{V}_b\).
Using R-GCN: node classification and link prediction setup slides 30-34 ↗
Slide 30, entity/node classification. Goal: predict the label of a given node. R-GCN uses the representation of the final layer. If we predict the class of node A from \(k\) classes, take the final layer (prediction head) \(\mathbf{h}_A^{(L)}\in\mathbb{R}^k\); each entry of \(\mathbf{h}_A^{(L)}\) represents the probability of that class (in practice, after a softmax).
Slide 31, link prediction: make predictions using pairs of node embeddings, \(\hat{y}_{uv}=f(\mathbf{h}_u^{(L)},\mathbf{h}_v^{(L)})\). What are the options for \(f\)? Slide 32 recalls the simplest one, the dot product \(\hat{y}_{uv}=(\mathbf{h}_u^{(L)})^\top\mathbf{h}_v^{(L)}\). It only applies to 1-way prediction: it predicts whether an edge exists, but it cannot say which relation the edge has.
Slide 33 recalls the transductive link-prediction split from earlier lectures. The figure shows one 5-node graph whose edges are split into four groups:
- At training time: use training message edges to predict training supervision edges.
- At validation time: use training message edges and training supervision edges to predict validation edges.
- At test time: use training message, training supervision and validation edges to predict test edges.
Slide 34 adds relations. Every edge also has a relation type, and this is independent of the 4 categories. In a heterogeneous graph, the homogeneous graph formed by each single relation is split into the 4 categories on its own: training message / training supervision / validation / test edges for \(r_1\), …, the same for \(r_n\). Then the pieces are merged: all training message edges of all relations form the training message set, and so on. This guarantees that every relation, even a rare one, appears in every split.
Why split per relation? A random split over all edges could, by chance, put almost all edges of a rare relation into the test set, so the model would never learn it.
Training R-GCN for link prediction slides 35-37 ↗
The running graph (slides 35–42) is the six-node graph from slide 21 plus an \(r_3\) edge from E to A. Slide 35 assumes \((E,r_3,A)\) is the training supervision edge and all other edges are training message edges. Use R-GCN to score \((E,r_3,A)\):
- Take the final-layer embeddings \(\mathbf{h}_E^{(L)}\) and \(\mathbf{h}_A^{(L)}\in\mathbb{R}^d\).
- Use a relation-specific score function \(f_r:\mathbb{R}^d\times\mathbb{R}^d\to\mathbb{R}\). One example: \(f_{r_3}(\mathbf{h}_E,\mathbf{h}_A)=\mathbf{h}_E^\top\mathbf{W}_{r_3}\mathbf{h}_A\), with \(\mathbf{W}_{r_3}\in\mathbb{R}^{d\times d}\).
The bilinear form with a matrix per relation solves the "1-way" problem of the dot product: each relation has its own notion of compatibility.
Slides 36–37 give the training procedure:
- Use R-GCN to score the training supervision edge \((E,r_3,A)\).
- Create a negative edge by perturbing the supervision edge: corrupt the tail of \((E,r_3,A)\), e.g. \((E,r_3,B)\) or \((E,r_3,D)\). Note: negative edges must not belong to the training message edges or training supervision edges. For example, \((E,r_3,C)\) is not a negative edge, because it is a real message edge.
- Use the GNN model to score the negative edge.
- Optimise a standard cross-entropy loss (as in Lecture 6):
where \(\sigma\) is the sigmoid. The first term maximises the score of the training supervision edge; the second minimises the score of the negative edge.
Evaluating link prediction by ranking: Hits@k and reciprocal rank slides 38-42 ↗
Slide 38 explains evaluation at validation time (test time is the same). We want to predict the validation edge \((E,r_3,D)\) (dashed in the figure). At validation time, the training message edges and training supervision edges are all existing edges (solid lines). Intuition: the score of \((E,r_3,D)\) should be higher than the score of every \((E,r_3,v)\) that is not in the training message or supervision edges, e.g. \((E,r_3,B)\).
Slide 39 lists the steps:
- Calculate the score of \((E,r_3,D)\).
- Calculate the score of all the negative edges \(\{(E,r_3,v)\mid v\in\{B,F\}\}\). A and C are excluded, since \((E,r_3,A)\) and \((E,r_3,C)\) belong to training message and supervision edges.
- Obtain the ranking \(RK\) of \((E,r_3,D)\) among these scores.
- Calculate the metrics:
- Hits@k \(=\mathbb{1}[RK\le k]\). Higher is better.
- Reciprocal rank \(=1/RK\). Higher is better.
Slides 40–42 work through three outcomes, listing the three scores from highest to lowest:
- Slide 40: order D, B, F. \(RK=1\), Hits@2 = 1, reciprocal rank \(=1/1\).
- Slide 41: order B, D, F. \(RK=2\), Hits@2 = 1, reciprocal rank \(=1/2\).
- Slide 42: order B, F, D. \(RK=3\), Hits@2 = 0, reciprocal rank \(=1/3\).
Averaging the reciprocal rank over all validation edges gives the mean reciprocal rank (MRR); averaging Hits@k gives the fraction of validation edges ranked in the top \(k\).
Why rank instead of classify? In a real graph almost all pairs are non-edges, so accuracy is meaningless. Ranking asks the practical question: "if I show the top \(k\) candidates, is the true one among them?" Hits@k is coarse (it ignores where inside the top \(k\)); MRR is smooth but dominated by the top positions.
Excluding known edges from the candidate list is called the filtered setting. Without it, a model would be punished for ranking another true edge, such as \((E,r_3,A)\), above \((E,r_3,D)\).
Benchmark: ogbn-mag, and R-GCN summary slides 43-47 ↗
Slides 43–46 present a standard benchmark, ogbn-mag, built from the Microsoft Academic Graph (MAG) [Wang et al., Quantitative Science Studies 2020].
- Slide 43, four types of entities: papers (736k nodes), authors (1.1m nodes), institutions (9k nodes), fields of study (60k nodes).
- Slide 44, four directed relations: an author is "affiliated with" an institution; an author "writes" a paper; a paper "cites" a paper; a paper "has a topic of" a field of study. The schema figure shows the four vertex types with these edges; the paper vertex carries properties (features, year, label).
- Slide 45, prediction task: each paper has a 128-dimensional word2vec feature vector. Given the content, references, authors and author affiliations, predict the venue of each paper. This is a 349-class classification problem, since 349 venues are considered. The split is time-based: training papers were published before 2018, test papers after 2018.
Slide 46 shows the leaderboard rows. The SOTA method at rank 1, SeHGNN (with ComplEx embeddings), has test accuracy 0.5719 ± 0.0012 and validation accuracy 0.5917 ± 0.0009 with 8,371,231 parameters. An R-GCN baseline (NeighborSampling with R-GCN aggregation, rank 21) has test accuracy 0.4678 ± 0.0067 and validation accuracy 0.4761 ± 0.0068 with 154,366,772 parameters. SeHGNN combines ComplEx knowledge-graph embeddings (next lecture) with a simplified GCN.
Notice the parameter counts: the R-GCN baseline uses about 18 times more parameters and is about 10 accuracy points worse. Much of R-GCN's size comes from per-relation weights and per-node embeddings.
Slide 47 summarises R-GCN:
- Relational GCN is a graph neural network for heterogeneous graphs.
- It can perform entity classification as well as link prediction.
- The ideas extend easily into RGNN variants: RGraphSAGE, RGIN, RGAT, etc. (keep the per-relation weights, change the aggregator).
- Benchmark: ogbn-mag, predicting paper venues.
Why a time-based split? It mimics the real use case (predict the venue of new papers from old data) and is harder than a random split, because topics and venues drift over time.
Design space: heterogeneous message and aggregation slides 49-53 ↗
Slide 49 asks how to extend the general GNN design space (from Lectures 4–5) to heterogeneous graphs. Recall its five parts: (1) message, (2) aggregation, (3) layer connectivity, (4) graph augmentation, (5) learning objective. The figure shows two stacked GNN layers, each with message and aggregation.
(1) Message. Slide 50 recalls the homogeneous version: message function \(\mathbf{m}_u^{(l)}=\mathrm{MSG}^{(l)}(\mathbf{h}_u^{(l-1)})\); each node creates a message that will be sent to other nodes later; example: a linear layer \(\mathbf{m}_u^{(l)}=\mathbf{W}^{(l)}\mathbf{h}_u^{(l-1)}\).
Slide 51, heterogeneous message computation. Observation: a node can receive multiple types of messages, and the number of message types equals the number of relation types. Idea: create a different message function for each relation type:
\[ \mathbf{m}_u^{(l)}=\mathrm{MSG}_r^{(l)}\big(\mathbf{h}_u^{(l-1)}\big),\qquad r=(u,e,v), \]where \(r\) is the relation between the node \(u\) that sends the message, the edge type \(e\), and the node \(v\) that receives it. Example: a linear layer \(\mathbf{m}_u^{(l)}=\mathbf{W}_r^{(l)}\mathbf{h}_u^{(l-1)}\).
(2) Aggregation. Slide 52 recalls: each node aggregates the messages from its neighbours, \(\mathbf{h}_v^{(l)}=\mathrm{AGG}^{(l)}(\{\mathbf{m}_u^{(l)},u\in N(v)\})\), e.g. Sum, Mean or Max; for example \(\mathbf{h}_v^{(l)}=\mathrm{Sum}(\{\mathbf{m}_u^{(l)},u\in N(v)\})\).
Slide 53, heterogeneous aggregation. Observation: each node can receive multiple types of messages, and several neighbours can belong to each message type. Idea: a 2-stage aggregation:
\[ \mathbf{h}_v^{(l)}=\mathrm{AGG}_{all}^{(l)}\Big(\mathrm{AGG}_r^{(l)}\big(\{\mathbf{m}_u^{(l)},u\in N_r(v)\}\big)\Big). \]- Within each message type, aggregate the messages that belong to that relation type with \(\mathrm{AGG}_r^{(l)}\).
- Then aggregate across the relation types with \(\mathrm{AGG}_{all}^{(l)}\).
- Example: \(\mathbf{h}_v^{(l)}=\mathrm{Concat}\big(\mathrm{Sum}(\{\mathbf{m}_u^{(l)},u\in N_r(v)\})\big)\): sum within each relation, concatenate across relations.
R-GCN is one point in this space: linear per-relation messages, mean within each relation (via \(1/c_{v,r}\)), sum across relations.
Design space: layers, graph manipulation and prediction heads slides 54-59 ↗
(3) Layer connectivity. Slide 54 recalls: add skip connections and pre/post-process layers. The figure stacks MLP layers (pre-process), GNN layers (with a skip connection) and MLP layers (post-process). Pre-processing layers matter when encoding node features is necessary, e.g. when nodes represent images or text. Post-processing layers matter when reasoning or transformation over node embeddings is needed, e.g. graph classification or knowledge graphs. In practice, adding these layers works great.
Slide 55, heterogeneous pre/post-process layers: use MLP layers per node type. Since the output of a GNN is node embeddings, \(\mathbf{h}_v^{(l)}=\mathrm{MLP}_{T(v)}(\mathbf{h}_v^{(l)})\), where \(T(v)\) is the type of node \(v\). This is exactly how different feature shapes (slide 15) are handled: a 4-dim author vector and a 5-dim paper vector go through their own pre-process MLPs into one common hidden size. Other successful designs are also encouraged: skip connections, batch/layer normalisation, ….
(4) Graph manipulation. Slide 56 recalls: if the input graph lacks features, use feature augmentation. For structure: if the graph is too sparse, add virtual nodes or edges; if too dense, sample neighbours during message passing; if too large, sample subgraphs to compute embeddings (covered later in "Scaling up GNNs").
Slide 57, heterogeneous version. Feature manipulation: two common options, compute graph statistics (e.g. node degree) within each relation type, or across the full graph (ignoring relation types). Structure manipulation: neighbour and subgraph sampling are also common; two options again, sample within each relation type (this ensures neighbours of every type are covered) or sample across the full graph.
(5) Prediction heads. Slide 58 recalls the homogeneous heads:
- Node level: \(\hat{y}_v=\mathrm{Head}_{node}(\mathbf{h}_v^{(L)})=\mathbf{W}^{(H)}\mathbf{h}_v^{(L)}\).
- Edge level: \(\hat{y}_{uv}=\mathrm{Head}_{edge}(\mathbf{h}_u^{(L)},\mathbf{h}_v^{(L)})=\mathrm{Linear}(\mathrm{Concat}(\mathbf{h}_u^{(L)},\mathbf{h}_v^{(L)}))\).
- Graph level: \(\hat{y}_G=\mathrm{Head}_{graph}(\{\mathbf{h}_v^{(L)}\in\mathbb{R}^d,\forall v\in G\})\).
Slide 59 makes each one type-aware:
- Node level, one head per node type: \(\hat{y}_v=\mathrm{Head}_{node,T(v)}(\mathbf{h}_v^{(L)})=\mathbf{W}_{T(v)}^{(H)}\mathbf{h}_v^{(L)}\).
- Edge level, one head per relation: \(\hat{y}_{uv}=\mathrm{Head}_{edge,r}(\mathbf{h}_u^{(L)},\mathbf{h}_v^{(L)})=\mathrm{Linear}_r(\mathrm{Concat}(\mathbf{h}_u^{(L)},\mathbf{h}_v^{(L)}))\).
- Graph level: pool each node type separately, then aggregate: \(\hat{y}_G=\mathrm{AGG}\big(\mathrm{Head}_{graph,i}(\{\mathbf{h}_v^{(L)}\in\mathbb{R}^d,\forall T(v)=i\})\big)\).
Check yourself: why pool each node type separately at graph level? show answer
A graph with 1,000 papers and 3 authors would otherwise have its author signal averaged away.
Attention recap: from GAT to Transformer-style attention slides 61-64 ↗
Slide 61 recalls Graph Attention Networks (GAT):
\[ \mathbf{h}_v^{(l)}=\sigma\Big(\sum_{u\in N(v)}\alpha_{vu}\mathbf{W}^{(l)}\mathbf{h}_u^{(l-1)}\Big). \]The \(\alpha_{vu}\) are attention weights: not all of a node's neighbours are equally important. Attention is inspired by cognitive attention: \(\alpha_{vu}\) focuses on the important parts of the input and fades out the rest; the network should devote more computing power to that small but important part. Question: can we adapt GAT for heterogeneous graphs?
Slide 62: HGT uses scaled dot-product attention, proposed in the Transformer:
\[ \mathrm{Attention}(Q,K,V)=\mathrm{softmax}\Big(\frac{QK^\top}{\sqrt{d_k}}\Big)V, \]with query \(Q\), key \(K\), value \(V\), each of shape (batch_size, dim). They are obtained by linear layers on the input: \(Q=\text{Q\_Linear}(X)\), \(K=\text{K\_Linear}(X)\), \(V=\text{V\_Linear}(X)\). The diagram shows the pipeline MatMul → Scale → Mask (optional) → SoftMax → MatMul.
Slide 63 [Hu et al., WWW 2020] recalls GAT on a homogeneous graph in this notation. \(H^{(l)}\) is the \(l\)-th layer representation, and for target node \(t\):
\[ H^{(l)}[t]\leftarrow\underset{\forall s\in N(t),\,\forall e\in E(s,t)}{\mathrm{Aggregate}}\big(\mathrm{Attention}(s,t)\cdot\mathrm{Message}(s)\big). \]The figure shows source nodes \(s_1,\dots\) around target \(t\). The question in red: how do we take the relation type (node_s, edge, node_e) into the attention computation?
Slide 64 writes the (homogeneous) mutual attention as Transformer heads: for head \(i\),
\[ \text{ATT-head}^i(s,t)=\big(K^i(s)\,Q^i(t)^\top\big),\quad K^i(s)=\text{K-Linear}^i\big(H^{(l-1)}[s]\big),\quad Q^i(t)=\text{Q-Linear}^i\big(H^{(l-1)}[t]\big). \]This is a set of neural networks for the attention score of each edge: the source is projected to a key, the target to a query, and their dot product scores the edge.
HGT: decomposing attention by node type and edge type slides 65-70 ↗
Slide 65 gives the motivation. GAT is unable to represent different node and edge types. The R-GCN fix, introducing a set of neural networks for each relation type (node_s, edge, node_e), is too expensive for attention. Slide 67 shows that first attempt explicitly: keys and queries indexed by the edge's relation,
\[ \text{ATT-head}^i(s,e,t)=\big(K^i_{\phi(e)}(s)\,Q^i_{\phi(e)}(t)^\top\big),\quad K^i_{\phi(e)}(s)=\text{K-Linear}^i_{\phi(e)}\big(H^{(l-1)}[s]\big),\quad Q^i_{\phi(e)}(t)=\text{Q-Linear}^i_{\phi(e)}\big(H^{(l-1)}[t]\big), \]i.e. a separate set of attention networks per relation type, too expensive.
Slide 66, the innovation: decompose heterogeneous attention into a node-type-dependent and an edge-type-dependent mechanism. In the example (paper and author node types, Write and Cite edge types) the figure shows a target Paper; a Paper neighbour (via Cite) goes through K-Linear\(_{Paper}\), an Author neighbour (via Write) through K-Linear\(_{Author}\); the target goes through Q-Linear\(_{Paper}\); then the matrices ATT\(_{Cite}\) and ATT\(_{Write}\) combine key and query into scores. With 3 node types and 2 edge types this needs 3 node weight matrices and 2 edge weight matrices. Without decomposition: \(3\cdot2\cdot3=18\) relation types, so 18 weight matrices (if all relation types exist).
Slide 68, heterogeneous mutual attention:
\[ \text{ATT-head}^i(s,e,t)=\big(K^i(s)\,W^{ATT}_{\phi(e)}\,Q^i(t)^\top\big), \] \[ K^i(s)=\text{K-Linear}^i_{\tau(s)}\big(H^{(l-1)}[s]\big),\qquad Q^i(t)=\text{Q-Linear}^i_{\tau(t)}\big(H^{(l-1)}[t]\big). \]Each relation \((\tau(s),\phi(e),\tau(t))\) still gets a distinct set of projection weights, but they are composed from shared parts: \(\tau(s)\) and \(\tau(t)\) (the node types) parameterise K-Linear\(_{\tau(s)}\) and Q-Linear\(_{\tau(t)}\), which return the key and query vectors \(K(s)\), \(Q(t)\); the edge type \(\phi(e)\) directly parameterises \(W_{\phi(e)}\).
Slide 69, a full HGT layer:
\[ \widetilde{H}^{(l)}[t]=\underset{\forall s\in N(t)}{\bigoplus}\Big(\mathrm{Attention}_{HGT}(s,e,t)\cdot\mathrm{Message}_{HGT}(s,e,t)\Big). \]The attention part was just computed. HGT decomposes the message weights the same way:
\[ \mathrm{Message}_{HGT}(s,e,t)=\big\Vert_{i\in[1,h]}\ \text{MSG-head}^i(s,e,t),\qquad \text{MSG-head}^i(s,e,t)=\text{M-Linear}^i_{\tau(s)}\big(H^{(l-1)}[s]\big)\,W^{MSG}_{\phi(e)}, \]with M-Linear weights for each node type and \(W^{MSG}\) weights for each edge type; \(\Vert\) concatenates the \(h\) heads.
Slide 70, performance on ogbn-mag (predict paper venues): HGT (LADIES sampling, rank 18) has test accuracy 0.4927 ± 0.0061 and validation accuracy 0.4989 ± 0.0047 with 21,173,389 parameters, versus the R-GCN baseline at 0.4678 ± 0.0067 / 0.4761 ± 0.0068 with 154,366,772 parameters. HGT uses much fewer parameters (about 7 times fewer), even though attention is expensive to compute, and performs better than R-GCN, thanks to the weight decomposition over node and edge types.
Why does factorising work? It assumes that "how a paper presents itself as a key" does not depend much on which relation it is used in, and that each edge type is a single interaction pattern between those projections. The count grows like \(|T|+|E|\) instead of \(|T|^2|E|\).
Summary slides 71-72 ↗
Slide 71 returns to the design-space figure: heterogeneous GNNs extend GNNs by separately modelling node/relation types plus an additional AGG (the across-relation aggregation).
Slide 72 summarises the lecture:
- Heterogeneous graphs: graphs with multiple node or edge types. Key concept: the relation type (node_s, edge, node_e). Be aware that we don't always need heterogeneous graphs: one-hot type features plus an ordinary GNN can be enough.
- Learning with heterogeneous graphs. Key idea: separately model each relation type.
- Relational GCNs (per-relation weights; block-diagonal or basis regularisation; node classification and link prediction with ranking metrics).
- Design space for heterogeneous GNNs (per-relation messages, two-stage aggregation, per-type MLPs and heads, per-relation sampling).
- Heterogeneous Graph Transformer (attention with weights factorised by node type and edge type).
Check yourself: for a graph with 4 node types and 4 edge types (like ogbn-mag), how many relation-type matrices would unfactorised attention need in the worst case, and how many does HGT need per head? show answer
\(4\cdot4\cdot4=64\) vs. about \(4+4\) groups of matrices: K-, Q-, M-Linear per node type plus \(W^{ATT}\), \(W^{MSG}\) per edge type.
Not shown (no new content): slides 1,2,3,4,17,48,60 — title pages, announcements (project proposal, Colab 2, Homework 2, office hours, practice midterm) and section-divider title pages.
Review: what to keep from this session
Carried forward. Lecture 10 is the shallow version of the same relation-type idea (one embedding per relation); Lecture 11 is a two-type bipartite graph; Lectures 12–13 turn a relational database into a heterogeneous graph and run exactly these models; Lecture 15 asks how to handle relations never seen in training.
Quick self-check
Why can one-hot node types fail as a substitute for a heterogeneous model?
When node types have different feature dimensions, or when the same message operator cannot express that "writes" and "cites" should transform the neighbour differently.
What problem do basis and block-diagonal decompositions solve in R-GCN?
With many relations, one full weight matrix per relation overfits and is expensive; sharing a few basis matrices (or restricting to blocks) cuts parameters.
How are negatives chosen for heterogeneous link prediction?
Corrupt the tail (or head) of a true triple with a node of the correct type for that relation, so the negative is plausible.
Key idea
Treat each relation type (source type, edge type, target type) as its own channel of messages, aggregate within and then across channels — and share or factorise weights so the parameter count doesn't grow with every new relation.
Worked example: counting parameters
A knowledge graph with \(|R|=100\) relations; hidden size \(d=128\); \(L=2\) layers.
- Plain R-GCN: \(100\times128\times128\times2\approx3.28\text{M}\) parameters (plus self-loops).
- Basis decomposition with \(B=10\): shared \(10\times128\times128\times2\approx328\text{k}\) plus coefficients \(100\times10\times2=2\text{k}\) → ~10× fewer.
- Block-diagonal with \(B=8\) blocks: per matrix \(8\times16\times16=2048\) instead of 16,384 → 8× fewer, but dimensions only mix within 16-dim blocks.
- Ranking check: validation edge \((E,r_3,D)\) scores 0.7; candidates \((E,r_3,B)=0.9\), \((E,r_3,F)=0.4\) → rank 2 → Hits@1 = 0, Hits@2 = 1, reciprocal rank = 0.5.
In code (PyG)
from torch_geometric.nn import RGCNConv, HeteroConv, SAGEConv, HGTConv, to_hetero
conv = RGCNConv(128, 128, num_relations=100, num_bases=10) # basis decomposition
h = conv(x, edge_index, edge_type)
# Generic heterogeneous layer: one conv per relation, then aggregate across relations
hetero = HeteroConv({('author','writes','paper'): SAGEConv((-1,-1), 64),
('paper','cites','paper'): SAGEConv((-1,-1), 64),
('paper','rev_writes','author'): SAGEConv((-1,-1), 64)}, aggr='sum')
out = hetero(data.x_dict, data.edge_index_dict)
hgt = HGTConv(-1, 64, metadata=data.metadata(), heads=4)
Proof workshop: When does basis decomposition save parameters?
One problem in olympiad style. Give it fifteen minutes on paper before you open the first hint; the hints are graded, so open them one at a time.
Problem. An R-GCN layer has one \(d\times d\) matrix per relation: \(Rd^2\) parameters. With basis decomposition, \(W_r=\sum_{b=1}^Ba_{rb}V_b\). (a) Count the parameters and find for which \(B\) the decomposition is smaller. (b) Prove that the map \(r\mapsto W_r\) then has rank at most \(B\) (viewing each \(W_r\) as a vector in \(\mathbb R^{d^2}\)). (c) For \(R=100\), \(d=64\), \(B=10\): how many parameters, and what fraction of the full model?
Hint 1
Hint 2
Solution
Why it matters. Basis decomposition is a low-rank assumption on how relations differ, and it is what lets rare relations borrow strength from frequent ones. On a social graph with follows, retweets, replies and quotes, those relations are plausibly few "directions" of interaction; on a knowledge graph with thousands of relation types, rank \(B\) is a modelling claim worth testing.
Sharper lens: what typed weights add, and what they do not
Not on the slides. Three or four points where the lecture rounds something off: the exact statement, a second way to see it, and where it stops being true. Each is short and has a pointer for going further.
Typed weights are an inductive bias, not extra expressive power
Lecture 6's question has a typed version. The relational WL test refines a node's colour by the multiset of pairs (relation, neighbour colour), and R-GCN is bounded by it (Barceló et al., "Weisfeiler and Leman go relational", 2022). A homogeneous GNN whose message function sees the edge type as an input feature reaches the same bound. So one weight matrix per relation does not let the model distinguish more graphs; it changes how many examples the model needs, by not forcing "cites" and "writes" through one transformation.
This matches the empirical audit you already have in Go deeper: Lv et al. (KDD 2021) found that a GAT with a learned edge-type embedding added to the attention, about ten lines more than plain GAT, matched or beat the specialised heterogeneous architectures once all were tuned equally. Start there.
Basis decomposition is a low-rank tensor factorisation
Stack the relation matrices into one tensor \(\mathcal W\in\mathbb R^{|R|\times d\times d}\). The basis form \(W_r=\sum_ba_{rb}V_b\) says \(\mathcal W\) has rank at most \(B\) along the relation mode (a Tucker-1 factorisation; the proof workshop shows the rank bound). The block-diagonal form is a different restriction: full rank across relations, but each \(W_r\) a direct sum of small blocks.
The same problem, "one \(d\times d\) matrix per relation is too many", appears on the decoder side in Lecture 10, with the same family of answers: RESCAL keeps the full matrix, DistMult keeps only its diagonal, and ComplEx keeps a diagonal over the complex numbers. An R-GCN encoder with a DistMult decoder, the original paper's link-prediction model, applies two members of this family in sequence.
Messages follow edge direction, so add reverse relations, then remove them again
With the relation (author, writes, paper) alone, papers hear from authors and authors hear from nobody. The standard fix is a reverse relation for every relation (T.ToUndirected() on a HeteroData object creates rev_writes), which doubles \(|R|\) and is one more reason for weight sharing.
In link prediction the fix opens a leak. If \((u,r,v)\) is a supervision edge and its reverse \((v,r^{-1},u)\) is still a message edge, the answer is in the input, and the model learns to copy it. Pass rev_edge_types to RandomLinkSplit so each supervision edge takes its reverse out of the message graph. The same mistake at dataset level made FB15k and WN18 almost solvable by a rule "if \((t,r^{-1},h)\) is in training, predict \((h,r,t)\)", and led to the filtered versions FB15k-237 and WN18RR used in Lecture 10.
Lab: hands-on and practical tips
notebook · L09 heterogeneous graphs builds R-GCN from scratch, counts parameters as in the lecture's worked example, benchmarks HeteroConv and HGT on DBLP and computes Hits@k and MRR.
HeteroData edges are directed per relation. If you only store (author, writes, paper), papers hear from authors but authors never hear from papers, and on an author task the graph is invisible. Add T.ToUndirected() (creates rev_* relations) and check data.edge_types.RGCNConv(num_bases=B) when relations are many and sparse.Readings & lookup guide
lecture notes CS224W course notes (Leni Aniva, Autumn 2024 — in your course folder)
- Ch. 9 — Heterogeneous graphs (pp. 50–55)
read first Schlichtkrull et al. — Modeling Relational Data with Graph Convolutional Networks (R-GCN, ESWC 2018)
- Read: §2.1 (Eq. 2 — the layer), §2.2 (basis and block-diagonal regularisation), §4 (link prediction: R-GCN encoder + DistMult decoder — a preview of Lecture 10).
- Notice: they add inverse relations and self-loops explicitly — common practice in all KG GNNs since.
core Hu, Dong, Wang, Sun — Heterogeneous Graph Transformer (WWW 2020)
- Read: §3 (heterogeneous mutual attention, message passing, target-specific aggregation; Fig. 2), §3.4 (relative temporal encoding for dynamic graphs), §3.5 (HGSampling for web-scale graphs).
- Skim: experiments on OAG (Open Academic Graph, 179M nodes).
textbook Hamilton, GRL book — Chapter 4 (Multi-relational data and knowledge graphs)
- Reconstruction loss for multi-relational graphs, decoders (RESCAL, TransE, DistMult, ComplEx), and the expressiveness of decoders for symmetric / inverse / compositional relations.
Homework & deadlines
Homework 2 out now · due Thu 10/29
Heterogeneous message passing and R-GCN parameter counting are natural exam/homework material — practice the worked example above. Download the PDF into the course folder when released.
Colab 2 due Thu 10/22 · Colab 3 out Thu 10/22, due 11/5
Colab 3 is released with Lecture 10. Try PyG's to_hetero on OGB_MAG as preparation.
Project proposal due Tue 10/20
Self-check
A relation type is …
- an edge type
- a triple (source node type, edge type, target node type)
- a node type
- a pair of nodes
\(r(u,v)=(\tau(u),\phi(u,v),\tau(v))\).
In R-GCN, the normalisation constant \(c_{v,r}\) is …
- the degree of v
- the number of relations
- the number of v's neighbours under relation r
- learned
Normalised by node degree within the relation.
Basis decomposition reduces parameters by …
- sharing basis matrices across relations; each relation learns B coefficients
- making matrices block-diagonal
- dropping relations
- using one weight for all relations
\(W_r=\sum_b a_{rb}V_b\).
Which is a valid negative edge for supervision edge (E, r₃, A) if (E, r₃, C) is a message edge?
- (E, r₃, A)
- (E, r₃, C)
- Any edge in the graph
- (E, r₃, B) if it is not an existing edge
Negatives must not be existing message or supervision edges.
HGT keeps parameters low by …
- removing attention
- factorising weights into node-type and edge-type parts
- using one relation type
- basis decomposition only
K/Q/M linears per node type, W^ATT / W^MSG per edge type.
Flashcards (click to flip)
History & the bigger picture
- 2000s — heterogeneous information networks (Sun & Han; PathSim 2011): meta-paths like Author–Paper–Venue–Paper–Author define similarity in typed graphs. metapath2vec (2017) brought them to embeddings.
- 2017–2018 — R-GCN: the first widely used GNN for multi-relational data. 2019 — HAN (meta-path attention). 2020 — HGT, and OGB's ogbn-mag benchmark.
- 2021–2022 — "Are we really making progress?" (Lv et al., KDD 2021) showed simple homogeneous GNNs with type features often match specialised heterogeneous ones — a useful reality check.
Declaring types is declaring an ontology: which kinds of things exist and which relations are meaningful. In social data that choice is political — e.g. typing accounts as "media", "politician", "citizen" bakes a theory of the public sphere into the model. Heterogeneous GNNs make the ontology explicit and learnable per relation; homogeneous ones hide it in features. Neither is neutral.
Classic SNA bridge
| In this lecture | Classic SNA counterpart | What carried over, what changed |
|---|---|---|
| Heterogeneous graph \(G=(V,E,R,T)\) | Multiplex networks (Verbrugge 1979); multirelational blockmodels (White, Boorman & Breiger 1976) | Sociology analysed several relations on the same actors (friendship, advice, authority) from the start; the "stacked" blockmodel is a relation-specific decomposition like R-GCN's per-relation weights. |
| Relation-specific weight matrices | Relational algebra of compound relations (Boorman & White); "friend of an enemy" compositions | Composing relations was done symbolically with Boolean matrix products. R-GCN learns a continuous weight per relation but never composes them explicitly; Lecture 10's composition pattern is the learned version. |
| Meta-paths (HAN, metapath2vec) | Two-mode projections and Breiger's duality; "brokerage" through intermediaries (Gould & Fernandez 1989) | A meta-path Author–Paper–Author is a projection; a user–hashtag–user path is co-activity. Meta-paths are symbolic, interpretable channels, the natural neuro-symbolic hook in this lecture. |
| Type-aware attention (HGT) | Role-specific tie strength; differential association | HGT learns that an advice tie and a friendship tie carry different weight for different pairs of roles, the quantitative form of role theory. |
| Benchmark: ogbn-mag | Bibliometric networks (de Solla Price 1965; Garfield's citation index) | Citation and co-authorship networks were the first large heterogeneous networks sociology of science studied. They are still the benchmarks. |
Build the natural X schema (users, tweets, hashtags, URLs; follows, posts, retweets, replies, quotes, mentions) and fit both an R-GCN and a homogeneous GCN with type features on account-suspension prediction. Then inspect which relations the R-GCN weights most, and compare with a multirelational blockmodel of the same data. Agreement between the learned relation weights and the blockmodel's role structure is a result in itself.
Go deeper in the SNA course. The twelve-unit course on social network analysis in this repository gives the classic side of this lecture in full, with labs and real-data analyses: Unit 9 · Beyond pairwise: higher-order, temporal, multilayer (heterogeneous graphs: several node and edge types, kept apart).
Connecting to your research
- A natural heterogeneous schema: node types user, tweet, hashtag, URL/domain; relations follows, posts, retweets, replies-to, quotes, mentions, uses-hashtag, links-to. Retweet vs reply vs quote are exactly "different interactions" that deserve different weights (endorsement vs debate vs commentary).
- With many relation types and sparse data, use basis decomposition or HGT-style factorisation — and compare against a homogeneous GNN with type features (Lv et al.'s lesson).
- Meta-paths (user–hashtag–user, user–URL–domain–URL–user) are interpretable, sociologically meaningful channels of co-activity — a neuro-symbolic hook: learned weights over symbolic paths.
Frontier 2025–26: what changed since the slides
Frontiers · a database is a graph · message passing on hyperedges
Words & phrases
| Term | Simple meaning | Persian | In context |
|---|---|---|---|
| heterogeneousadj. | made of different kinds of parts | ناهمگن | "A heterogeneous graph has node types and edge types" |
| ontologyn. | a formal list of the kinds of things that exist in a domain and how they relate | هستیشناسی | "Declaring types is declaring an ontology" |
| relation typen. | the label on an edge that says what kind of link it is | نوع رابطه | "one weight matrix per relation type" |
| basis decompositionn. | writing many matrices as combinations of a few shared ones | تجزیه پایهای | "basis decomposition with B = 10" |
| block-diagonaladj. | zero everywhere except square blocks on the diagonal | قطریبلوکی | "block-diagonal weight matrices" |
| metapathn. | a sequence of node and edge types, such as author–paper–author | فرامسیر | "co-authorship as a metapath" |
Go deeper
- Next: Lecture 10 — knowledge graphs: shallow embeddings (TransE, DistMult, ComplEx, RotatE) for typed link prediction.
- Benchmarks reality check: Lv et al. (KDD 2021), "Are we really making much progress? Revisiting, benchmarking, and refining heterogeneous GNNs".
- Open question: how should a model generalise to a new relation type never seen in training? (Lecture 15 — KG foundation models.)