Part IV · Graphs and AI

Graphs in Artificial Intelligence

Created by

Five headline AI systems, from protein folding to the model that wrote your last chatbot answer, run on graph theory you now own. This chapter shows you where the vertices and edges are hiding.

Where the graphs are hiding

You have spent twelve chapters building machinery: neighbourhoods, degrees, bipartite graphs, matchings, connectivity, planarity, flows, random graphs. This chapter leaves Diestel's book behind and asks a different question: what does modern artificial intelligence actually do with that machinery?

The answer is: more than almost any other branch of mathematics. A molecule is a graph whose vertices are atoms and whose edges are chemical bonds. A protein can be treated as a graph whose vertices are amino-acid building blocks and whose edges join the ones that sit close together in space. A road network is a weighted directed graph. A streaming service's record of who watched what is a bipartite graph. Google's index of real-world facts is a directed labelled graph with billions of edges. Even the transformer, the architecture inside large language models, can be read as a neural network operating on a complete directed graph whose vertices are the words of your sentence.

The bridge between your course and these systems is a family of models called graph neural networks. The abbreviation GNN is standard, and we will use it after this sentence: a graph neural network is a machine-learning model whose computation follows the edges of a graph. A 2024 primer in Nature Reviews Methods Primers describes GNNs as the leading approach for building predictive models on graph-structured data, with applications running from antibiotic discovery to physics simulation[1].

The plan. First we define the one operation every GNN shares, message passing, and tie it to the neighbourhood \(N(v)\) and the adjacency matrix from Chapter 1. Then we meet the three named architectures every applied paper cites. Then four readings of real systems: transformers as weighted complete digraphs, knowledge graphs as directed labelled multigraphs, recommenders as bipartite link prediction, and spectral clustering as the Laplacian matrix at work. We close with the deployed results: a new antibiotic, protein structures, faster routes in Google Maps, and a chip designed by a GNN.

One warning before we start. Nothing in this chapter is a theorem of Diestel's book. It is applied mathematics built on the book's definitions, and the citations point to the original AI papers rather than to textbook sections. Where a claim does rest on a theorem you proved, we say which chapter proved it.

This section reads a protein as a graph. What are its edges?

  1. The chemical bonds along the amino-acid chain, and nothing else
  2. Pairs of proteins that interact inside the cell
  3. Pairs of amino-acid units that sit close together in space
  4. The atoms that make up each amino acid
Answer: C. Vertices are the amino-acid building blocks and an edge records spatial proximity. Option A keeps only the chain, which is a much thinner graph; option D names things that would have to be vertices, not edges.

New notation in this chapter

Machine learning attaches numbers to vertices and edges, so we need a little notation for states, weights, and matrices. Everything else in the chapter is notation you already have.

SymbolRead it asMeaningTiny example
\(\mathbb{R}^d\)"R d"The set of lists of \(d\) real numbers. A vertex state is one such list, also called a vector.\((0.2,\,-1.5)\) is a point of \(\mathbb{R}^2\).
\(h_v^{(k)}\)"the state of \(v\) after round \(k\)"The vector of numbers vertex \(v\) carries after \(k\) rounds of message passing; \(h_v^{(0)}\) is the input data.In Figure 13.1, \(h_b^{(0)}=2\) and \(h_b^{(1)}=8\).
\(H\)"the state matrix"The matrix whose row \(v\) is the state \(h_v\); one row per vertex.5 vertices with 3 numbers each: \(H\) is a \(5\times 3\) matrix.
\(w_{uv}\)"the weight from \(u\) to \(v\)"A number attached to the ordered pair \((u,v)\); an edge weight that may differ from \(w_{vu}\).In Figure 13.2, \(w_{\text{cat},\text{sat}}=0.6\).
\(D\)"the degree matrix"The diagonal matrix with the degree \(d(v)\) in position \((v,v)\) and zeros elsewhere.For a triangle, the diagonal reads \(2,2,2\).
\(L\)"the Laplacian"\(L = D - A\): degree matrix minus adjacency matrix.For a triangle: \(2\) on the diagonal, \(-1\) off it.
\(\lambda_2\)"lambda two"The second-smallest eigenvalue of \(L\) (in this chapter only; it is not the edge-connectivity \(\lambda(G)\)).\(\lambda_2 > 0\) exactly when \(G\) is connected.

Symbols from earlier chapters get a one-clause reminder the first time they appear. The two you will see most: \(N(v)\), the neighbourhood of \(v\), meaning the set of vertices joined to \(v\) by an edge, and \(A\), the adjacency matrix, the square table with a 1 in position \((u,v)\) when \(uv\) is an edge and a 0 otherwise[2].

A graph has 6 vertices and every vertex carries a state in \(\mathbb{R}^4\). What are the dimensions of the state matrix \(H\)?

  1. \(4 \times 4\)
  2. \(6 \times 4\)
  3. \(4 \times 6\)
  4. \(6 \times 6\)
Answer: B. \(H\) has one row per vertex and one column per number in a state, so 6 rows of 4 numbers. Option C transposes it; in this chapter the row index is always the vertex.

Message passing: learning on the neighbourhood

Start with the question the definition answers. Suppose each vertex of a graph carries data: for a molecule, each atom's element and charge; for a social network, each person's profile. You want a model that predicts something about a vertex, or about the whole graph, using both the data and the wiring. How should the model read a graph?

The wrong answer is to flatten the graph into a list and feed it to an ordinary neural network. A list forces you to number the vertices, and the numbering is arbitrary. You proved in Chapter 1 that a graph's essential properties are exactly the ones preserved by isomorphism, that is, by relabelling. A model that changes its answer when you relabel the input is answering a question about your bookkeeping, not about the graph.

The right answer, which the field converged on, is a protocol run by the vertices themselves.

Definition — message-passing round

Let \(G\) be a graph in which each vertex \(v\) holds a state \(h_v^{(k)} \in \mathbb{R}^d\). One round of message passing computes, for every vertex \(v\) at the same time, \[ h_v^{(k+1)} \;=\; f\Big( h_v^{(k)},\; \sum_{u \in N(v)} h_u^{(k)} \Big), \] where \(f\) is a small neural network whose parameters are learned from data. In words: every vertex collects the current states of its neighbours, adds them up, and feeds the total together with its own current state through a learned update function. The sum can be replaced by an average, a maximum, or a weighted sum; the shape of the protocol stays the same.

Read the formula aloud once: the new state of \(v\) is a learned function of the old state of \(v\) and the sum, over all neighbours \(u\) of \(v\), of the old states of those neighbours. The graph structure enters in exactly one place, the index set \(N(v)\) under the sum. That index set is the neighbourhood defined on the first pages of this course.

Run the round several times. After one round, \(v\) knows about its neighbours. After two rounds, its neighbours' updates already contained their neighbours, so \(v\) has information from every vertex within distance 2, where distance means the length of a shortest path, as in Chapter 1. After \(k\) rounds, \(v\) has seen exactly the vertices at distance at most \(k\): the ball of radius \(k\) around \(v\). If you want one answer for the whole graph, say "is this molecule toxic?", a final readout step pools all the vertex states into a single vector.

This framework is called the message passing neural network. It was distilled in 2017 by Gilmer and colleagues, who showed that many independently invented models for predicting molecular properties were all instances of one recipe: models that "learn a message passing algorithm and aggregation procedure to compute a function of their entire input graph"[3]. A position paper from DeepMind and collaborators the following year argued the deeper point: graphs give neural networks the right relational inductive bias, meaning the assumption, wired into the architecture, that what matters is entities and their relations, not the order in which you happen to list them[4]. Because each update reads only \(N(v)\), relabelling the vertices just relabels the outputs the same way. The model respects isomorphism by construction.

Worked example

Take the graph of Figure 13.1: vertices \(a,b,c,d,e\), edges \(ab, bc, bd, ce\). Give each vertex a one-number state: \(h_a^{(0)}=1\), \(h_b^{(0)}=2\), \(h_c^{(0)}=3\), \(h_d^{(0)}=4\), \(h_e^{(0)}=5\). Run one round of the simplest possible protocol, "your new state is the sum of your neighbours' old states". Vertex \(b\) has \(N(b)=\{a,c,d\}\), so \(h_b^{(1)} = 1+3+4 = 8\). Vertex \(c\) has \(N(c)=\{b,e\}\), so \(h_c^{(1)} = 2+5 = 7\). The full result: \(2, 8, 7, 2, 3\). Note that \(d\)'s new state is 2, not 8: it uses \(b\)'s old state, because all vertices update simultaneously.

before after: sum your neighbours 1 2 3 4 5 a b c d e 2 8 7 2 3 a b c d e
Figure 13.1. One message-passing round on the graph with edges \(ab, bc, bd, ce\). Numbers inside the circles are vertex states. Vertex \(b\) (violet, with its three incident edges) collects \(1+3+4\) from \(N(b)=\{a,c,d\}\) and becomes 8. Every vertex updates from the old states at the same time.
Common mistake

Updating vertices one after another, each reading its neighbours' already updated states. That would make the outcome depend on the order you visit the vertices, which is exactly the arbitrary bookkeeping the whole design exists to remove. Message passing is synchronous: every round-\((k{+}1)\) state is computed from round-\(k\) states only.

Now the linear-algebra reading, which is the payoff of Chapter 1's matrix section[2]. Stack the states as rows of the matrix \(H\), and let \(A\) be the adjacency matrix. Row \(v\) of the product \(AH\) is, by the definition of matrix multiplication, the sum of the rows of \(H\) over all \(u\) with \(a_{vu}=1\), that is, over all neighbours of \(v\). So the sentence "everyone sums their neighbours' states" and the formula \(H \mapsto AH\) are the same statement. In our worked example \(H\) is the column \((1,2,3,4,5)\), and \(AH = (2,8,7,2,3)\). Stacking \(k\) rounds involves \(A^k\), and the entry \((u,v)\) of \(A^k\) counts the walks of length \(k\) from \(u\) to \(v\); that is why \(k\) rounds gather information along walks of length \(k\), and why a GNN with few rounds cannot see across a graph of large diameter. Depth of network and diameter of graph are the same currency.

Intuition

Message passing is structured gossip. Each round, everyone tells their friends a summary of what they currently know, and everyone folds what they hear into what they knew. After \(k\) rounds, news has travelled at most \(k\) steps. The learning part is only how each person summarizes and folds; who talks to whom is the graph, fixed and given.

Let \(G\) have edges \(ab\) and \(bc\), with states \(h_a^{(0)}=1\), \(h_b^{(0)}=2\), \(h_c^{(0)}=3\). Run one round of "your new state is the sum of your neighbours' states". What is \(h_a^{(1)}\)?

  1. 2
  2. 3
  3. 4
  4. 6
Answer: A. \(N(a)=\{b\}\), and every vertex reads round-0 states, so \(h_a^{(1)} = h_b^{(0)} = 2\). Option C is what you get by updating \(b\) first (to \(1+3=4\)) and letting \(a\) read the new value, which is the sequential mistake the round forbids.

Why does the section reject flattening a graph into a numbered list and feeding it to an ordinary neural network?

  1. Ordinary neural networks cannot accept more than a few hundred inputs
  2. A list cannot hold real numbers at the vertices
  3. Flattening keeps the edges but discards the vertex data
  4. The answer would depend on the arbitrary numbering, which relabelling must not change
Answer: D. Isomorphic graphs must get the same answer, and a numbering is bookkeeping, not structure. Because each update reads only \(N(v)\), relabelling the input just relabels the output. Input size (option A) is an engineering limit, not the reason the design was rejected.

Three ways to average your neighbours

Three named architectures dominate the applied literature. They differ in exactly one design choice: how the neighbourhood aggregate is computed. Knowing the three lets you read most GNN papers written since.

GCN (graph convolutional network; Kipf and Welling, 2017). The update multiplies the state matrix by a normalized adjacency matrix: each vertex takes a degree-weighted average of its neighbours' states, plus its own after a loop is added at every vertex, then applies a learned linear map. The authors derived the rule as "a localized first-order approximation of spectral graph convolutions"[5]: it began life in the spectral theory of the Laplacian, which we meet later in this chapter, and was simplified until only a cheap local averaging step survived. The normalization matters. Without division by degree, the states of high-degree vertices grow with every round and drown out the rest; the fix is dictated by the degree sequence, a Chapter 1 object.

GAT (graph attention network; Veličković and colleagues, 2018). Instead of fixed degree-based weights, GAT learns how much each neighbour matters. For each edge \(uv\), a small network scores how relevant \(u\)'s state is to \(v\); the scores across \(N(v)\) are scaled to be positive and sum to 1, and \(v\) takes the weighted average[6]. In graph language: GAT converts the input graph into a weighted graph whose weights \(w_{uv}\) are computed from the data, fresh at every layer. This helps when neighbourhoods are mixed in quality; in a citation network, some references matter far more than others.

GraphSAGE (Hamilton, Ying, and Leskovec, 2017). The scalability workhorse, with two changes. First, instead of using all of \(N(v)\), it samples a fixed number of neighbours, say 25, so the cost per vertex stays bounded even at a vertex of enormous degree. Second, it is trained to be inductive: it learns the aggregation function itself, not a separate stored vector per vertex, so it can "efficiently generate node embeddings for previously unseen data"[7]. Earlier methods were transductive: they memorized one fixed graph and had no answer for a vertex that arrived after training. With GraphSAGE, a user who signs up tomorrow is embedded immediately from their features and neighbourhood. This is the design change that made GNNs deployable on industrial graphs, as we will see at Pinterest below.

Two course connections. The sampled neighbourhoods of GraphSAGE are random subgraphs of the ball around \(v\), so its guarantees are statements about random subgraph approximation, kin to the probabilistic arguments of Chapter 11. And the random graph model of that chapter, independent edges with equal probability, is a useful foil here: real social and interaction graphs violate it dramatically, with heavy-tailed degree sequences and dense clustering, and all three architectures carry design scars from those violations, from GCN's normalization to GraphSAGE's sampling.

In a citation network some references matter far more than others. Which of the three architectures is designed for that, and how?

  1. GCN, by dividing each neighbour sum by the degrees
  2. GAT, by learning a weight \(w_{uv}\) for each edge from the data
  3. GraphSAGE, by sampling a fixed number of neighbours
  4. All three, since each already treats every neighbour identically
Answer: B. GAT scores how relevant each neighbour is to \(v\) and takes a weighted average, so the input becomes a weighted graph whose weights are recomputed every layer. GCN's degree normalization (option A) keeps magnitudes comparable, but two neighbours of the same vertex still count equally.

Transformers: attention is a weighted complete digraph

The transformer is the architecture inside GPT-style language models, introduced in the 2017 paper "Attention Is All You Need"[8]. Its core operation, self-attention, works like this. Every token, roughly a word piece, holds a vector. To update itself, a token computes a compatibility score with every token in the sentence, converts the scores into positive weights that sum to 1, and takes the weighted average of all the tokens' vectors.

Now read that paragraph as a graph theorist. Take the tokens as the vertex set. Every vertex aggregates from every other vertex, so the "neighbourhood" is all of \(V\): the underlying graph is the complete graph \(K^n\) on the \(n\) tokens, every pair joined, plus a loop at each vertex because a token attends to itself. The attention weights are edge weights. And since the weight token \(i\) gives to token \(j\) need not equal the weight \(j\) gives to \(i\), the right object is a weighted complete directed graph: \(n(n-1)\) ordered pairs, each carrying its own learned weight \(w_{ij}\), recomputed for every input at every layer.

This is not a loose analogy. Chaitanya Joshi's widely read essay "Transformers are Graph Neural Networks" makes it precise: a transformer is a GNN that treats a sentence as "a fully-connected graph, where each word attends to every other word", with multi-head attention as the neighbourhood aggregation function[9]. The two research communities reached the same update rule from opposite directions, and a graph attention network that happens to run on a complete graph is, in all but bookkeeping, a transformer layer[9].

1 2 3 4 the cat sat down 0.1 0.6 0.1 0.2
Figure 13.2. Self-attention as a weighted complete digraph on four tokens (position numbers inside the vertices). Drawn in full: the arcs into "sat", with weights summing to 1; the token listens hardest to "cat" (weight 0.6) and partly to itself (the loop, 0.2). The faint lines stand for the remaining pairs; every token has its own full set of incoming arcs with its own weights.
Common mistake

Assuming attention is symmetric. The weight "sat" gives to "cat" and the weight "cat" gives to "sat" are computed separately and generally differ, so the structure is a digraph, not a graph. If you model it with an undirected weighted \(K^n\) you have thrown away half the numbers.

Two refinements complete the picture. First, causal masking as orientation. In a decoder, the GPT setting, each token may only attend to earlier tokens. In graph terms you have oriented the complete graph by the token order: every arc points from an earlier token to a later one. An orientation of a complete graph by a linear order has no directed cycles, and that acyclicity is what lets generation proceed left to right, one token at a time. Second, positional encodings as graph repair. A complete graph on tokens has forgotten the word order; every vertex looks the same, which is precisely the isomorphism-invariance that helps molecules and hurts sentences. Transformers restore order by adding position information to each token's input vector[8]. On general graphs the analogous trick is to give each vertex coordinates derived from the graph's structure, and a standard choice is eigenvectors of the Laplacian, the matrix we are about to meet.

One more line worth writing down. The famous cost of attention, quadratic in the sentence length, is a statement you can prove: \(\|K^n\| = \binom{n}{2} = n(n-1)/2\), the size (number of edges) of the complete graph, doubled for direction. The engineering bottleneck of large language models is the edge count of \(K^n\) wearing a compute budget.

In Figure 13.2 the weight "cat" gives to "sat" is 0.6. In a self-attention layer with no causal mask, what does that tell you about the weight "sat" gives to "cat"?

  1. It is 0.6 as well, since attention weights are symmetric
  2. It is 0.4, because the two weights on a pair sum to 1
  3. Nothing: the two are computed separately and generally differ
  4. It must be below 0.6, since "cat" comes earlier in the sentence
Answer: C. Each ordered pair carries its own learned weight, which is exactly why the structure is a digraph. What sums to 1 is the set of weights arriving at one token, not the pair of weights on one line, so option B misreads the normalization.

A sentence has 50 tokens. Ignoring the self-loops, how many attention weights does one unmasked self-attention layer compute?

  1. 50
  2. 100
  3. 1225
  4. 2450
Answer: D. Every ordered pair of distinct tokens gets its own weight: \(n(n-1) = 50 \times 49 = 2450\). Option C is \(\binom{50}{2} = 1225\), the edge count of the undirected \(K^{50}\), which forgets that the weight from \(i\) to \(j\) differs from the one from \(j\) to \(i\). Either way the count grows like \(n^2\), which is attention's famous cost.

Knowledge graphs: facts as labelled arcs

How should a machine store the fact that Marie Curie won the Nobel Prize in Physics? Not as a sentence, which is hard to query, and not as a rigid database table, which fixes in advance what kinds of facts exist. The answer that won: store facts as edges of a graph.

Definition — knowledge graph, triple

A knowledge graph is a directed graph whose vertices are entities (people, places, proteins, products) and whose arcs carry labels naming relations. Its atomic unit is the triple (subject, predicate, object), such as (Marie Curie, won, Nobel Prize in Physics): a directed labelled arc from the subject vertex to the object vertex. Plainly: a fact is an arrow with a name on it.

The standard exchange format for such data on the web is RDF, the Resource Description Framework, a W3C standard, and its primer states the graph reading outright: triples form a directed labelled graph in which subjects and objects become vertices while predicates form the connecting arcs[10]. Since two entities can be linked by several differently labelled arcs, and direction carries meaning, the honest classification in course language is: a directed multigraph with labelled arcs, the objects Chapter 1 defined in its closing sections[2]. A survey by Hogan and seventeen co-authors frames knowledge graphs as the tool of choice for "diverse, dynamic, large-scale collections of data" where a fixed schema fits badly[11].

M P N Marie Curie Pierre Curie Nobel Prize in Physics won won married to
Figure 13.3. Three triples as a directed labelled graph. Two arcs share the target vertex, two arcs share the label "won", and the direction matters: the prize did not win Marie Curie.

The deployment that named the concept: in 2012 Google announced its Knowledge Graph under the slogan "things, not strings", arguing that search should understand entities and their relationships rather than match keywords. At launch it held more than 500 million objects and more than 3.5 billion facts about the relationships between them[12]. In course terms, a directed labelled graph with 3.5 billion arcs, powering the information boxes beside search results.

Where the machine learning enters: real knowledge graphs are incomplete. A core task is link prediction, guessing which absent arcs are probably true, done with GNNs or by placing each vertex and each relation label into \(\mathbb{R}^d\) and scoring candidate triples geometrically[11]. And querying is your Chapter 1 material wearing a suit: "which actors starred in films directed by someone born in Lisbon?" is pattern matching over directed walks, multi-hop reasoning is path-following, and whether an answer is reachable at all is a question about directed connectivity, the concern of Chapter 3. Knowledge graphs also anchor today's language models: retrieval systems walk the graph to fetch verified facts for the model to put into words[11].

Why does the chapter classify a knowledge graph as a directed multigraph with labelled arcs rather than a plain directed graph?

  1. Two entities can be joined by several arcs carrying different relation labels
  2. The same entity is the subject of many different triples
  3. Arcs carry labels, and a labelled graph is always a multigraph
  4. Relations such as "married to" hold in both directions
Answer: A. A plain digraph allows at most one arc per ordered pair, but a person and a city can be joined by "born in" and also "died in", so parallel arcs are needed. Option D needs no multigraph: the two directions are two different ordered pairs.

Recommenders: link prediction on bipartite graphs

Recommendation data is a bipartite graph by birth. One vertex class for users, one for items, an edge exactly when a user watched, bought, or rated an item, and no edges inside a class. That is the structure Diestel defines in Section 1.6, and you know its signature theorem: a graph is bipartite if and only if it contains no odd cycle[2]. The matching theory of Chapter 2, König's theorem and Hall's marriage condition, lives on exactly this class of graphs[13]: assigning items to users under constraints is a bipartite matching problem, and a recommender can be read as the machine that produces the weighted preferences such an assignment would optimize over.

What does a recommender actually compute? A prediction about missing edges. "You might like this film" means: the model believes the edge between your vertex and the film's vertex is absent from the data but present in the truth. Recommendation is link prediction on a bipartite graph, and the signal travels along walks: user \(u\) liked item \(m\), other users liked \(m\), those users liked further items, which become candidates for \(u\). Every such walk alternates sides, a fact you proved when you characterized bipartite graphs by their cycles.

u1 u2 u3 u4 m1 m2 m3 m4 m5 users movies
Figure 13.4. A user-item bipartite graph. The violet walk \(u_1 m_2 u_2 m_4\) alternates sides: \(u_2\) liked what \(u_1\) liked, and also liked \(m_4\). The dashed gold edge is the recommendation, a predicted missing edge.

Two verified landmarks show the scale this runs at. PinSage, published by Pinterest and Stanford in 2018, put GraphSAGE-style ideas into production on a graph of 3 billion vertices and 18 billion edges. Full neighbourhoods are unmanageable at that size, so PinSage "combines efficient random walks and graph convolutions": it defines a vertex's effective neighbourhood by short random walks and aggregates over the most-visited vertices[14]. This was the demonstration that GNNs work at web scale. LightGCN, from 2020, ran the opposite direction: strip the GCN down. It "learns user and item embeddings by linearly propagating them on the user-item interaction graph", removing the learned nonlinear transforms entirely, and beat heavier models on standard benchmarks[15]. The lesson for a graph theory student is satisfying: on a bipartite interaction graph, most of the predictive power is in the graph structure itself. Propagation along the edges does the work.

In the user-item graph, the recommendation signal travels along walks. A walk that starts at a user vertex and ends at a user vertex must have:

  1. Odd length
  2. Even length
  3. Length exactly 2
  4. Length at most 3
Answer: B. Every edge crosses from one class to the other, so after an odd number of steps you stand on an item; getting back to a user takes an even number. Option C is only the shortest such walk, through a single shared item, as in Figure 13.4.

The Laplacian goes to work

The question first: given data points with no labels, how do you find the natural groups? The most graph-theoretic answer in machine learning is spectral clustering, and its engine is one matrix.

Definition — graph Laplacian

Let \(G\) be a graph on \(n\) vertices, \(A\) its adjacency matrix, and \(D\) the diagonal matrix carrying the degrees \(d(v)\). The Laplacian of \(G\) is \(L = D - A\). Plainly: row \(v\) of \(L\) has the degree of \(v\) on the diagonal, a \(-1\) in the column of every neighbour of \(v\), and zeros elsewhere. Each row sums to zero, because a degree is exactly a count of neighbours.

Definition — eigenvalue, eigenvector

An eigenvector of a square matrix \(M\) is a nonzero vector \(x\) that \(M\) merely stretches: \(Mx = \lambda x\) for some number \(\lambda\), called its eigenvalue. Plainly: a direction the matrix does not turn, only scale. For the Laplacian we list the eigenvalues in increasing order \(\lambda_1 \le \lambda_2 \le \dots \le \lambda_n\).

Common mistake

Notation clash: in Chapter 1, \(\lambda(G)\) is the edge-connectivity of \(G\), the least number of edges whose deletion disconnects it. In the spectral literature, and in this chapter from here on, \(\lambda_i\) is the \(i\)-th smallest eigenvalue of \(L\). The two uses are related in spirit (both measure how robustly connected a graph is) but they are different numbers. Read \(\lambda\) by context.

The Laplacian stores a startling amount of the graph in its eigenvalues. Three facts, in increasing order of usefulness. First, \(L\) is symmetric and all its eigenvalues are at least 0. Second, 0 is always an eigenvalue: apply \(L\) to the all-ones vector, and each row sums to zero, so the result is the zero vector. Third, and this is the theorem of the section:

Theorem — components in the spectrum

For any graph \(G\), the multiplicity of the eigenvalue 0 of the Laplacian \(L\) equals the number of connected components of \(G\)[16]. In particular, \(\lambda_2 > 0\) exactly when \(G\) is connected.

Proof idea. The computation that unlocks everything is the identity \(x^{\top} L x = \sum_{uv \in E} (x_u - x_v)^2\): the Laplacian measures how much a vertex-labelling \(x\) disagrees across edges. If \(Lx = 0\) then that sum of squares is zero, so \(x\) is constant along every edge, hence constant on each connected component (walk along a path, as in Chapter 1, and the value never changes). So the vectors with \(Lx=0\) are exactly the ones built by choosing one constant per component, and there are as many independent choices as components. The full argument is short linear algebra; von Luxburg's tutorial gives it in one page[16].

Connectivity, a qualitative Chapter 1 notion, has become a number you can compute by matrix algebra. The refinement is where machine learning lives: for a connected graph, \(\lambda_2\) measures how close the graph is to disconnecting, and the eigenvector belonging to \(\lambda_2\), called the Fiedler vector, assigns each vertex a real number. Sorting or thresholding those numbers tends to split the graph along a sparse cut: few edges crossing, both sides substantial[16].

a b c d e f g h + + + + − − − −
Figure 13.5. Two dense clusters joined by two edges (gold). The Fiedler vector is positive on one cluster and negative on the other; thresholding it at zero recovers the clusters, and the gold edges are the sparse cut it finds. Here \(\lambda_2\) is small but not zero: the graph is connected, barely.

Spectral clustering turns this into an algorithm for arbitrary data. Build a similarity graph on your data points, connecting each point to its nearest neighbours. Compute the first \(k\) eigenvectors of the Laplacian, which hands every vertex \(k\) coordinates. Then run a simple geometric grouping method (\(k\)-means) in that \(k\)-dimensional space. Von Luxburg's 2007 tutorial is the standard reference; it lays out the Laplacian variants and why the method finds cluster structure that purely geometric methods miss[16]. The reason the eigenvector shows up at all is a relaxation story. The natural cut-quality objectives are computationally hard to optimize exactly, because they ask for a cut that is also balanced, and a plain minimum cut is not; allow each vertex any real number instead of a hard \(+1\) or \(-1\), and the optimization becomes an eigenvector computation whose answer is the Fiedler vector[16]. Cuts, you may recall, are the dual objects of flows, and the max-flow min-cut theorem of Chapter 6 is the exact-combinatorics counterpart of what this relaxation solves approximately[17].

Spectral ideas thread through the rest of the chapter's cast. The GCN layer began as a spectral filter and was simplified to local averaging[5]. Graph transformers attach the first few Laplacian eigenvector values to each vertex as position coordinates, the graph-world analogue of the positional encodings in the original transformer. And a small \(\lambda_2\) warns of a bottleneck: when much information must cross a sparse cut in few message-passing rounds, it gets compressed too aggressively, a failure GNN researchers call over-squashing.

A graph on 6 vertices consists of a triangle together with a disjoint path on the other 3 vertices. How many times does 0 occur as an eigenvalue of its Laplacian \(L\)?

  1. Never
  2. Once
  3. Twice
  4. Six times
Answer: C. The multiplicity of 0 counts connected components, and this graph has two. Option B is the answer for any connected graph; 0 always occurs at least once, because every row of \(L\) sums to zero.

Figure 13.5 shows two dense clusters joined by just two edges. What does the section say about \(\lambda_2\) and its eigenvector here?

  1. \(\lambda_2\) is small but positive, and thresholding its eigenvector at 0 cuts the two joining edges
  2. \(\lambda_2 = 0\), because the graph falls into two clusters
  3. \(\lambda_2\) equals the number of edges in the cut, here 2
  4. \(\lambda_2\) is negative, since the two clusters pull in opposite directions
Answer: A. The graph is connected, so \(\lambda_2 > 0\), and it is small because deleting two edges would disconnect it; the Fiedler vector is positive on one cluster and negative on the other. Option B confuses a cluster with a component: only a genuine component adds another 0.

Molecules: AlphaFold and a new antibiotic

Now the deployed systems, starting with the smallest graphs and the biggest headlines.

A molecule is a graph you can hold: atoms as vertices, bonds as edges. Figure 13.6 draws ethanol, the alcohol in wine, whose molecular graph has nine vertices and eight edges. It is a tree, which you can verify by counting: nine vertices, eight edges, connected, no cycle.

C C O H H H H H H
Figure 13.6. The molecular graph of ethanol: vertices are atoms, edges are bonds, and the whole graph is a tree. The gold subgraph is the O–H group. Substructures like this, distinguished subgraphs of the molecular graph, are what explainable chemistry models point to as their evidence.
Two facing pages of an 1860s chemistry journal, numbered 232 and 233, in dense letterpress with long footnotes and several inset diagrams.
Plate 13.A. Crum Brown's graphic notation in the Journal of the Chemical Society, 1865: atoms as circled letters, bonds as the lines between them. Item 4 on the right-hand page is succinic acid, and his footnote defends the scheme against Kekulé's and Erlenmeyer's. Sylvester took the word graph into mathematics from chemical diagrams of this kind. Alexander Crum Brown, 1865. Wikimedia Commons, public domain.

Feed graphs like this, with atom data as vertex states, into a message-passing network, and you get a molecular property predictor; this was precisely the setting in which the message-passing framework was distilled[3]. The result that made the approach famous came in 2020. A team at MIT trained a deep model of exactly this type on roughly 2,500 molecules labelled by whether they inhibit the growth of E. coli, then screened large chemical libraries in software[18]. The model surfaced a molecule the team named halicin, which killed many antibiotic-resistant bacteria in laboratory and animal tests, including strains resistant to all known antibiotics[19]. Halicin is structurally unlike existing antibiotics, and that is the point: the network judged molecules by learned structural features of the graph, not by resemblance to known drugs[19].

In the real world

The sequel made the graphs visible. In 2023, Wong, Zheng and colleagues trained ensembles on 39,312 experimentally screened compounds, predicted antibiotic activity across 12 million molecules, and then used explainable models to identify which chemical substructures drive the predictions. A substructure of a molecule is a subgraph of its molecular graph. The search produced a new structural class of antibiotics active against MRSA, the methicillin-resistant staph bacterium, validated in mouse models[20]. The model's evidence for its own prediction is a distinguished subgraph.

Proteins scale the same idea up. AlphaFold, from DeepMind, predicts a protein's three-dimensional shape from its chain of amino acids, with accuracy competitive with laboratory experiment for most proteins; the 2021 Nature paper is among the most cited scientific papers of its decade[21]. The graph content is explicit in the paper, which treats "the prediction of protein structures as a graph inference problem in 3D space in which the edges of the graph are defined by residues in proximity"[21]. Alongside a per-residue representation, the network maintains a feature vector for every ordered pair of residues: learned edge features on a complete digraph over the residues, iteratively refined so that geometry becomes consistent (if residue \(A\) sits near \(B\), and \(B\) near \(C\), the \(A\)-\(C\) edge feature must be compatible). Here is the course-language summary. The amino-acid sequence hands you a path graph, the barest connected graph there is. Folding is the discovery of the rest of the edge set.

A tall molecular model of metal plates and thin rods on a vertical support, seen through a museum display case with visitors reflected in the glass.
Plate 13.B. The surviving parts of Crick and Watson's 1953 DNA model, reassembled behind glass at the Science Museum in London. Metal plates stand for bases, thin rods for bonds. Atoms as vertices and bonds as edges is not a convenience this chapter imposed on chemistry: it is how the structure was worked out, in metal, by hand. Wikimedia Commons, public domain.

Ethanol's molecular graph has 9 vertices, 8 edges, and is connected. What follows at once?

  1. It contains exactly one cycle
  2. It has two connected components
  3. Every atom has degree at least 2
  4. It is a tree
Answer: D. Connected with \(n\) vertices and \(n-1\) edges forces no cycle, which is what a tree is; one cycle (option A) would need a ninth edge. Option C fails on the six hydrogens, each of which hangs off a single bond.

Maps and chips

Routing is the classical graph story: model the road network as a directed graph, one vertex per intersection or road segment, weight each arc by travel time, and run a shortest-path algorithm. Distance and shortest paths are Chapter 1; nothing about the algorithmic frame changed. What deep learning changed is the weights. Travel time is not a constant; it is a prediction problem that depends on traffic now and twenty minutes from now.

In the real world

In 2020, DeepMind and Google Maps put GNN-based travel-time prediction into production, improving the accuracy of estimated arrival times by up to 50% in cities including Berlin, Jakarta, São Paulo, Sydney, Tokyo, and Washington, D.C.[22] The accompanying paper explains the method: the road network is carved into "supersegments", connected chains of road segments treated as graphs on which a GNN predicts traversal times, capturing how congestion spreads along adjacent segments; deployment cut severe mispredictions by more than 40% in cities like Sydney[23].

Why must travel times be predicted jointly rather than one segment at a time? Because traffic is a flow on the network, in the sense of Chapter 6: what enters a segment must have left its neighbours, so congestion couples adjacent arcs, and delays pile up near saturated cuts. A GNN passing messages along the road graph is learning exactly those couplings. The final step is untouched theory: once the weights are set, the route you are shown is still a shortest path.

free flow rush hour s a b t 3 3 4 4 s a b t 9 3 4 4
Figure 13.7. The algorithm is still shortest-path; the learning sets the weights. In free flow the route \(s\,a\,t\) costs \(3+3=6\) and wins (green). At rush hour the learned weight on \(sa\) jumps to 9, and \(s\,b\,t\) at \(4+4=8\) becomes the shortest route.

The last stop is the hardware itself. Chip floorplanning is the task of deciding where each block of circuitry sits on the silicon die. The input is a netlist: a graph of circuit components and the wires connecting them (strictly, a hypergraph, since one wire can join several components). In 2021, Mirhoseini, Goldie and colleagues published in Nature a method that treats floorplanning as a game played by a learning agent, in which "an edge-based graph convolutional neural network" reads the netlist and guides the placement of components one by one, producing layouts in under six hours that match or beat expert human designers on power, performance, and area[24]. Google later confirmed that the method, now called AlphaChip, produced layouts used in three consecutive generations of its Tensor Processing Units, the v5e, v5p, and Trillium chips that train and serve its AI models[25]. There is a pleasing loop here: a graph neural network designs the hardware that runs graph neural networks.

The course connection runs through Chapter 4. A netlist must be realized on an essentially two-dimensional surface, and real netlists are nowhere near planar, which is why chips route wires across a limited number of stacked layers and why crossing-minimization intuition applies. Placement quality is scored partly by total wirelength, which is a property of the drawing, not of the abstract graph; the distinction between a graph and its drawing, which Chapter 4 made precise, is exactly the distinction AlphaChip's score function lives on.

What did the graph neural network change about the way Google Maps produces a route?

  1. It replaced shortest-path search with a route the network writes directly
  2. It predicts the arc weights; the route shown is still a shortest path
  3. It made the road network undirected, so a route works in both directions
  4. It removed the need to model the roads as a graph at all
Answer: B. Intersections stay vertices, roads stay weighted arcs, and the final step is the same shortest-path computation. Learning enters only in the travel times, which is why they are predicted jointly along a supersegment: congestion on one arc changes its neighbours.

What to keep

One idea organizes this whole chapter. Modern AI did not import graph theory as decoration; it rediscovered the subject's central discipline, which is to compute only with structure that survives relabelling. Message passing is the neighbourhood \(N(v)\) made executable. Attention is a weighted \(K^n\) with directions. A knowledge graph is a directed labelled multigraph with a query language. A recommendation is a predicted edge in a bipartite graph. Spectral clustering is connectivity, differentiated. When you meet the next AI system, the useful first question is the one this course has trained you to ask: what are the vertices, what are the edges, and which of its properties are isomorphism-invariant?

If you want to go deeper on the AI side, the four best entry points among this chapter's sources are the message-passing paper[3], the relational inductive bias position paper[4], Joshi's transformer essay[9], and von Luxburg's spectral clustering tutorial[16]. All four are readable with what you now know.

This section names the one discipline of graph theory that modern AI rediscovered. Which is it?

  1. Reducing every problem to a matrix computation
  2. Keeping graphs sparse so the algorithms stay fast
  3. Computing only with structure that survives relabelling of the vertices
  4. Preferring connected graphs to disconnected ones
Answer: C. Message passing, attention, and spectral clustering all read structure that does not depend on how the vertices are numbered. Matrices (option A) show up constantly, but as a tool: \(AH\) and \(L\) earn their place because they respect that same invariance.

Check your understanding

In one round of message passing (before any neighbour sampling), a graph neural network computes the new state of vertex \(v\) from the old states of exactly which vertices?

  1. All vertices at distance at most 2 from \(v\)
  2. The neighbourhood \(N(v)\), plus \(v\) itself
  3. A uniformly random subset of \(V\)
  4. The vertices of highest degree in the graph
Answer: B. One round aggregates over \(N(v)\) and combines the result with \(v\)'s own old state. Distance-2 information arrives only after a second round, and sampling (as in GraphSAGE) is an efficiency modification, not the definition.

Stack the one-number vertex states of a graph into a column \(H\), and let \(A\) be the adjacency matrix. The round "every vertex's new state is the sum of its neighbours' old states" is the same computation as which matrix product?

  1. \(H + A\)
  2. \(AH\)
  3. \(LH\), where \(L\) is the Laplacian
  4. \(HA\)
Answer: B. Row \(v\) of \(AH\) sums the rows of \(H\) over the neighbours of \(v\), by the definition of matrix multiplication meeting the definition of \(A\). The Laplacian product \(LH\) would compute degree-times-own-state minus the neighbour sum, a different (though related) operation.

After \(k\) rounds of message passing, the state of vertex \(v\) can depend on the input data of which vertices?

  1. Only \(N(v)\), no matter how large \(k\) is
  2. All of \(V\), already after one round
  3. Only vertices in the same block of a proper colouring
  4. Exactly the vertices at distance at most \(k\) from \(v\)
Answer: D. Information travels one edge per round, so after \(k\) rounds it has covered walks of length up to \(k\), reaching the ball of radius \(k\) around \(v\). This is why a shallow GNN cannot see across a graph of large diameter.

GraphSAGE is called inductive. What does that buy in practice?

  1. It learns an aggregation function, so a vertex unseen during training can be embedded from its features and neighbourhood without retraining
  2. It guarantees exact results despite sampling only some neighbours
  3. It works only on trees, where induction on subtrees applies
  4. It removes the need for vertex features entirely
Answer: A. Transductive methods memorize one vector per vertex of one fixed graph; GraphSAGE learns the function that produces the vector, so tomorrow's new user is embedded immediately. Sampling neighbours (a separate design choice) trades exactness for bounded cost, so option B is the opposite of the truth.

Viewing a transformer's self-attention layer (no causal mask) through graph theory, the tokens and their attention weights form which structure?

  1. A tree, since sentences have parse trees
  2. A bipartite graph between tokens and layers
  3. A weighted complete directed graph on the tokens, with loops
  4. A planar graph, since text is written on a page
Answer: C. Every token attends to every token including itself, and the weight from \(i\) to \(j\) generally differs from the weight from \(j\) to \(i\), so the structure is a complete digraph with loops and asymmetric weights. A parse tree is a linguistic object the model may implicitly learn; it is not the attention structure.

In a GPT-style decoder, each token may attend only to earlier tokens. In graph terms, this causal mask turns the attention structure into:

  1. A bipartite graph, split into early and late tokens
  2. A complete graph with all loops removed
  3. A spanning tree of \(K^n\)
  4. An orientation of the complete graph by token order, which contains no directed cycle
Answer: D. Every arc points from an earlier token to a later one, which is exactly an orientation of \(K^n\) by a linear order, and such an orientation is acyclic. That acyclicity is what allows generation to proceed left to right. No two-class split arises, so the bipartite option fails.

An RDF triple such as (Turing, born in, London) corresponds to which object in a knowledge graph?

  1. A directed labelled arc from the vertex "Turing" to the vertex "London"
  2. A triangle on three vertices
  3. An undirected edge, since facts are symmetric
  4. A vertex with three attributes
Answer: A. Subject and object become vertices; the predicate labels a directed arc from subject to object. Direction carries meaning (London was not born in Turing), and two entities may be joined by several differently labelled arcs, so the full structure is a directed labelled multigraph.

A movie service models its data with a vertex per user, a vertex per movie, and an edge exactly when a user rated a movie. Which statement about this graph is guaranteed?

  1. It is complete, since any user could rate any movie
  2. It is bipartite, so it contains no odd cycle
  3. It is connected, since popular movies link everyone
  4. It is planar, so it can be drawn without crossings
Answer: B. Edges only join the user class to the movie class, which is the definition of bipartite, and a graph is bipartite exactly when it has no odd cycle. Connectivity, completeness, and planarity all depend on the particular data, so none of them is guaranteed.

Let \(L = D - A\) be the Laplacian of a graph \(G\). The multiplicity of the eigenvalue 0 of \(L\) equals:

  1. The number of edges of \(G\)
  2. The chromatic number of \(G\)
  3. The number of connected components of \(G\)
  4. The maximum degree \(\Delta(G)\)
Answer: C. A vector with \(Lx=0\) must be constant on each component, because \(x^{\top}Lx\) sums the squared disagreements \((x_u-x_v)^2\) over the edges; one free constant per component gives a kernel of dimension equal to the component count. This is the entry point of spectral clustering: for a connected graph, \(\lambda_2\) measures how close \(G\) is to disconnecting.

The GCN update divides each aggregated neighbour sum by (roughly) the vertex degrees. What problem does this normalization address?

  1. It makes the graph acyclic so the update can be ordered
  2. It guarantees the graph becomes regular after one layer
  3. Without it, the states of high-degree vertices grow with every round and dominate the computation
  4. It is required for the adjacency matrix to be symmetric
Answer: C. A vertex of degree 1,000 sums a thousand neighbour states; unnormalized, its numbers dwarf those of a degree-3 vertex and grow round over round. Dividing by degree turns the sum into an average, keeping magnitudes comparable across a skewed degree sequence. The graph itself is never altered, so the other options describe nothing that happens.

Sources and further reading

  1. G. Corso, H. Stark, S. Jegelka, T. Jaakkola, R. Barzilay, "Graph neural networks", Nature Reviews Methods Primers 4, 17 (2024). nature.com/articles/s43586-024-00294-7.
  2. R. Diestel, Graph Theory, 6th ed., Springer GTM 173 (2024), §1.2 (degrees), §1.6 (bipartite graphs and the odd-cycle characterization, Prop. 1.6.1), §1.9 (the adjacency matrix), §1.10 (directed graphs and multigraphs).
  3. J. Gilmer, S. S. Schoenholz, P. F. Riley, O. Vinyals, G. E. Dahl, "Neural Message Passing for Quantum Chemistry" (2017). arXiv:1704.01212.
  4. P. W. Battaglia, J. B. Hamrick, V. Bapst, et al., "Relational inductive biases, deep learning, and graph networks" (2018). arXiv:1806.01261.
  5. T. N. Kipf, M. Welling, "Semi-Supervised Classification with Graph Convolutional Networks", ICLR 2017. arXiv:1609.02907.
  6. P. Veličković, G. Cucurull, A. Casanova, A. Romero, P. Liò, Y. Bengio, "Graph Attention Networks", ICLR 2018. arXiv:1710.10903.
  7. W. L. Hamilton, R. Ying, J. Leskovec, "Inductive Representation Learning on Large Graphs", NIPS 2017. arXiv:1706.02216.
  8. A. Vaswani, N. Shazeer, N. Parmar, J. Uszkoreit, L. Jones, A. N. Gomez, L. Kaiser, I. Polosukhin, "Attention Is All You Need" (2017). arXiv:1706.03762.
  9. C. K. Joshi, "Transformers are Graph Neural Networks", The Gradient (2020). thegradient.pub/transformers-are-graph-neural-networks.
  10. W3C, RDF 1.1 Primer, W3C Working Group Note, 24 June 2014. w3.org/TR/rdf11-primer.
  11. A. Hogan, E. Blomqvist, M. Cochez, et al., "Knowledge Graphs", ACM Computing Surveys 54(4) (2021). arXiv:2003.02320.
  12. A. Singhal, "Introducing the Knowledge Graph: things, not strings", Google Official Blog, May 16, 2012. blog.google/products/search/introducing-knowledge-graph-things-not.
  13. R. Diestel, Graph Theory, 6th ed., Springer GTM 173 (2024), §2.1 (König's theorem 2.1.1; Hall's marriage theorem 2.1.2).
  14. R. Ying, R. He, K. Chen, P. Eksombatchai, W. L. Hamilton, J. Leskovec, "Graph Convolutional Neural Networks for Web-Scale Recommender Systems", KDD 2018. arXiv:1806.01973.
  15. X. He, K. Deng, X. Wang, Y. Li, Y. Zhang, M. Wang, "LightGCN: Simplifying and Powering Graph Convolution Network for Recommendation", SIGIR 2020. arXiv:2002.02126.
  16. U. von Luxburg, "A Tutorial on Spectral Clustering", Statistics and Computing 17(4) (2007). arXiv:0711.0189.
  17. R. Diestel, Graph Theory, 6th ed., Springer GTM 173 (2024), §6.2 (the max-flow min-cut theorem 6.2.2).
  18. J. M. Stokes, K. Yang, K. Swanson, W. Jin, A. Cubillos-Ruiz, et al., "A Deep Learning Approach to Antibiotic Discovery", Cell 180 (2020). doi.org/10.1016/j.cell.2020.01.021.
  19. A. Trafton, "Artificial intelligence yields new antibiotic", MIT News, February 20, 2020. news.mit.edu/2020/artificial-intelligence-identifies-new-antibiotic-0220.
  20. F. Wong, E. J. Zheng, et al., "Discovery of a structural class of antibiotics with explainable deep learning", Nature 626 (2023). nature.com/articles/s41586-023-06887-8.
  21. J. Jumper, et al., "Highly accurate protein structure prediction with AlphaFold", Nature 596 (2021). nature.com/articles/s41586-021-03819-2.
  22. Google DeepMind, "Traffic prediction with advanced Graph Neural Networks", DeepMind blog, September 3, 2020. deepmind.google/discover/blog/traffic-prediction-with-advanced-graph-neural-networks.
  23. A. Derrow-Pinion, J. She, D. Wong, et al., "ETA Prediction with Graph Neural Networks in Google Maps", CIKM 2021. arXiv:2108.11482.
  24. A. Mirhoseini, A. Goldie, M. Yazgan, et al., "A graph placement methodology for fast chip design", Nature 594 (2021). nature.com/articles/s41586-021-03544-w.
  25. Google DeepMind, "How AlphaChip transformed computer chip design", DeepMind blog, September 26, 2024. deepmind.google/discover/blog/how-alphachip-transformed-computer-chip-design.