CS58700 - Foundations of Deep Learning¶

Spring 2026¶

Copyright: Bruno Ribeiro and Beatrice Bevilacqua¶


Graph Representation Learning (Part 1)¶

Assumptions¶

  • Vertex ids are independent of what we are trying to predict
    • For instance, vertex ids are given at random

Understanding graphs¶

The representation and processing of graphs presents a fundamental challenge in computer science: while computers, like Turing Machines, must ultimately represent all data as sequences, graphs have structural properties that must be taken into account when we process their sequences.

  • To understand this subtle interplay between sequential representation and graph structure, consider the two extremes of permutation sensitivity.
    • Sequences exhibit complete permutation sensitivity: every reordering creates a distinct input. For instance, the sequence $[a, b, c, d]$ is fundamentally different from $[b, a, c, d]$.
    • At the opposite end of the spectrum, sets display complete permutation invariance: any reordering yields the same mathematical object, making $[a, b, c, d]$ identical under all possible rearrangements of its elements.

Graphs occupy an important middle ground, exhibiting what we can term intermediate permutation sensitivity. This balance between sequential representation and structural invariance is not merely a theoretical curiosity—it proves essential for designing effective graph learning algorithms that can recognize and preserve the fundamental properties of graph structures while processing their sequential representations and will be very important in later sections of this book.

To illustrate this intermediate permutation sensitivity, let's consider a concrete example. Consider a 6-node cycle defined by edges $(1,2)$, $(2,3)$, $(3,4)$, $(4,5)$, $(5,6)$, and $(6,1)$. This graph is isomorphic to another 6-node cycle represented by the edges $(6,2)$, $(2,3)$, $(3,4)$, $(1,6)$, $(5,1)$, and $(4,5)$. The isomorphism emerges from two distinct operations:

  1. A node permutation that swaps identifiers $6 \leftrightarrow 1$, reindexing the graph's nodes. This operation reflects the fundamental principle that node labels are arbitrary and can be reassigned without changing the graph's structure.

  2. An edge subsequence permutation, which rearranges the order of edges while preserving their internal structure (for example, swapping $(1,6)$ and $(4,5)$ without altering the adjacency relationships). This operation demonstrates how we can reorder edge sequences while maintaining the graph's connectivity pattern.

To better understand this intermediate sensitivity, let's contrast it with set-type permutations. If we were to treat edge representations as unordered sets, we could apply more drastic permutations—such as swapping individual elements within edges.

  • For instance, if we switch $4$ with $1$ only in $(3,4)$ and $(6,1)$ to yield the sequence $(1,2)$, $(2,3)$, $(3,1)$, $(4,5)$, $(5,6)$, and $(6,4)$, we would fundamentally alter the graph's structure, producing two disjoint 3-node cycles:
    • Cycle A: $(1,2) \rightarrow (2,3) \rightarrow (3,1)$.
    • Cycle B: $(4,5) \rightarrow (5,6) \rightarrow (6,4)$.

This example illustrates why graph learning algorithms must strike a delicate balance: they must be flexible enough to handle valid permutations (node relabeling and edge reordering) while being permutation-sensitive enough to preserve the graph's essential structural properties.

No description has been provided for this image

This example highlights how graphs balance positional information (e.g., node and edge order in sequences) with structural invariants (e.g., node adjacencies). To model such properties effectively, graph learning frameworks must account for two types of permutation equivariance:

  • Node permutations, which require algorithms to ignore reindexing of identifiers.
  • Edge sequence permutations, which demand stability of algorithms under certain reorderings while preserving adjacency relationships. % This duality between sequence and graph representations is central to the design of graph learning architectures, as we explore in subsequent chapters.

1. Definition of Graphs as a Collection of Sets and Sequences¶

Our previous discussion emphasized graphs as sequences with constrained permutation properties, but for now we will formalize graphs in their more familiar mathematical representation. We will go back and forth between sequence and combinatorial representations when we discuss developing effective graph learning algorithms.

A graph $G=(V,E,\mathbf{X}_V,\mathbf{X}_E)$ comprises:

  • $V=\{1,\ldots,n\}$, the set of vertices, where the specific choice of identifiers is arbitrary up to the node permutation invariance discussed earlier

  • $E\subseteq V\times V$, the set of edges, which can be viewed as either an unordered set (traditional representation) or a sequence with constrained permutation sensitivity (as previously discussed)

  • $\mathbf{X}_V$, the sequence of vertex attributes—each vertex $i\in V$ is associated with a feature vector $\mathbf{x}_i\in\mathbb{R}^{d_V}$

  • $\mathbf{X}_E$, the sequence of edge attributes—each edge $(i,j)\in E$ is endowed with a feature vector $\mathbf{x}_{ij}\in\mathbb{R}^{d_E}$

This definition naturally accommodates both the set-theoretic and sequential perspectives: while $E$ is formally defined as a set, any practical computation on $G$ requires some serialization of its edges, bringing us back to the permutation properties previously examined.

1.2. Adjacency Matrix and Adjacency Tensor¶

The adjacency matrix $A \in \mathbb{A}^{n \times n}$ is a square matrix whose elements indicate whether pairs of vertices have a relationship in some appropriate space $\mathbb{A}$.

  • In the simplest case, $\mathbb{A} = \{0,1\}$, and $A_{ij} = 1$ if there is a connection from node $i$ to $j$, and otherwise $A_{ij} = 0$ (indicating a non-edge).
  • If there are edge attributes (e.g., edge relations), then $\mathbb{A}$ is some appropriate space that represents these relations (often encoded as a binary vector) or some real-valued connection strength $\mathbb{A} \subseteq \mathbb{R}^d$. This makes the adjacency matrix into a adjacency tensor ${\bf A}$.
  • Self-loops, e.g., $A_{ii}$, will encode node attributes (self-relations).
  • For an undirected graph, keep in mind that $A$ is a symmetric matrix ($A_{ij}=A_{ji}$). For the example graph below has adjacency matrix:

$$ A = \begin{bmatrix} 0 & 1 & 0 & 0\\ 1 & 0 & 1 & 1\\ 0 & 1 & 0 & 1\\ 0 & 1 & 1 & 0 \end{bmatrix}$$

No description has been provided for this image

1.2. Graph Properties¶

1.2.1. Edge Cardinality: Dyadic and Higher-Order Relationships¶

Classical graphs primarily focus on dyadic (pairwise) relationships. However, real-world systems often require more complex representations:

Simple Graphs:

  • One edge connects exactly two nodes
  • Example: Basic friendship networks where connections are strictly pairwise

Multi-graphs:

  • Multiple edges can exist between the same pair of nodes
  • Example: Customer-product interaction networks where edges represent different actions (view, add-to-cart, purchase)

Hypergraphs:

  • Edges (hyperedges) can connect arbitrary sets of nodes
  • Captures higher-order interactions like group collaborations
  • Special case: k-uniform hypergraphs where each edge connects exactly k nodes

1.2.2. Directionality: Asymmetric vs Symmetric Relationships¶

The direction of edges fundamentally impacts information flow and learning:

Directed Graphs (Digraphs):

  • Edges have inherent direction
  • Model asymmetric relationships
  • Example: Social media follower networks
  • Important implications for graph invariance properties

Undirected Graphs:

  • Edges represent symmetric relationships
  • Example: Friendship networks where relationships are mutual
  • Simplified information flow patterns

1.2.3. Edge Attributes: Beyond Binary Connections¶

Edge attributes provide crucial relationship context:

Weighted Graphs:

  • Edges carry scalar values
  • Represent strength, distance, or capacity
  • Example: Road networks with distance weights

Labeled Edges:

  • Categorical attributes describing relationship types
  • Example: Knowledge graphs with different relation types

Vector-Attributed Edges:

  • Complex attributes as vector embeddings
  • Enable rich relationship representations

1.2.4. Homogeneity: Node and Edge Type Diversity¶

Graph homogeneity significantly impacts model architecture choices:

Homogeneous Graphs:

  • Single type of nodes and edges
  • Example: Social networks with only user nodes
  • Simpler modeling requirements

Heterogeneous Graphs:

  • Multiple node types and/or edge types
  • Example: Customer-product networks
  • Requires specialized ML architectures
  • Common in knowledge graphs

1.2.5. Connectivity: Graph Component Structure¶

Connectivity patterns influence algorithm design and application:

Connected Graphs:

  • Path exists between any pair of vertices
  • Example: Road networks with complete accessibility

Weakly Connected Graphs:

  • Connected when ignoring edge directions
  • Common in citation networks

Disconnected Graphs:

  • Multiple isolated components
  • Example: Separate community forums
  • Requires special handling in learning algorithms

1.2.6. Temporality: Static vs Dynamic Structures¶

The temporal dimension adds complexity to graph modeling:

Static Graphs:

  • Fixed structure over time
  • Example: Historical road networks

Discrete-time Dynamic Graphs:

  • Periodic structure updates
  • Example: Daily social network snapshots

Continuous-time Temporal Graphs:

  • Real-time evolution
  • Example: Live interaction networks
  • Requires specialized temporal modeling approaches

Types of graphs¶

No description has been provided for this image

Some less common graph tasks¶

No description has been provided for this image

1.3. Graph Tasks¶

Whole-graph classification task¶

No description has been provided for this image

Classical graph classification¶
  • We would like to design a function $f({\bf A})$ that produces a representation of graph ${\bf A} \in \mathbb{A}^{n\times n}$.
No description has been provided for this image

1.3.1. Whole-graph classification via end-to-end learning¶

  • Now, we would like to learn a function $f({\bf A})$ that produces a representation of graph ${\bf A} \in \mathbb{A}^{n\times n}$.
No description has been provided for this image

1.3.2.1. Node classification task (via self-supervised learning)¶

  • Given a set of node lables as training data (e.g., label $\in$ {Bot,Real user})
  • Predict labels of unlabeled nodes
    • In graphs, the boundaries between training and test data can be sometimes blurry
    • We will cover the different training and test splits in our class on Positional vs Structural Node Embeddings
No description has been provided for this image

1.3.2.2. Node classification via end-to-end learning¶

  • Assume we have a function $f: \mathbb{A}^{n\times n} \times V \to \mathbb{R}^d, d \geq 1$.
    • $f({\bf A},v)$ produces a representation of node $v \in V$ in graph ${\bf A} = \mathbb{A}^{n\times n}$.
No description has been provided for this image

1.3.3. Link prediction task¶

  • Effectively, an "edge classification" task
No description has been provided for this image

2. Definition of Graphs through Invariant Theory¶

Assumption:

  • Vertex ids are arbitrary, the output of our graph predictions should not change if we permuted them.

Theory:

A sequence of $n^2$ random variables $(X_1,\ldots,X_{n^2}) \in \mathbb{A}^{n^2}$ is said to be a graph whenever its distribution has the following property: $$ P(X_1,\ldots,X_{n^2}) = P(X_{\pi' \circ 1},\ldots,X_{\pi' \circ n^2}), $$ for $\pi' \in \Pi$, where $\Pi \subseteq \mathbb{S}_{n^2}$ is a special subset of permutations of the symmetric group $\mathbb{S}_{n^2}$ of order $n^2$.

  • The symmetric group $\mathbb{S}_k$ is the group of permutations of the elements $(1,\ldots,k)$.

More specifically, $\Pi$ is defined such that there exist a bijection between each of the $n^2$ elements in the sequence $(X_1,\ldots,X_{n^2})$ and each element in the adjacency tensor $A_{i,j}$, $i,j \in V$, and the following condition holds $$ P(A_{1,1},A_{1,2},\ldots,A_{n,n}) = P(A_{\pi \circ 1, \pi \circ1},A_{\pi \circ 1,\pi \circ 2},\ldots,A_{\pi \circ n,\pi \circ n}), \quad \forall \pi \in \mathbb{S}_n. $$

2.1. Permutation action on graphs¶

  • It is easier to define the graph permutations over the adjacency tensor $A$ using all the elements of $\mathbb{S}_n$ rather than a subgroup of $\mathbb{S}_{n^2}$.
  • A group action is the application of a group representation of an element of the group onto some object.
    • For instance, the group action "$\circ$" of permutation $\pi \in \mathbb{S}_n$ on the adjacency matrix is denoted $\pi \circ {\bf A}$ and jointly permutes the rows and columns of ${\bf A}$ according to the permutation in $\pi$.

Permutation action on the graph¶

No description has been provided for this image
  • We call ${\bf A}$ and $\pi \circ {\bf A}$ isomorphic graphs, where $\pi \in \mathbb{S}_n$ is an element of the symmetric group of order $n$ and "$\circ$" is the appropriate action (representation) over the input.

3. Graph Representation Learning¶

Learning to represent graph data effectively is critical for downstream tasks like classification, clustering, and prediction.

Two Types of Graph Representations¶

There are two fundamental approaches:

  1. Structural Representations

    • Capture the topological structure of graphs (e.g., adjacency matrices/tensors).
    • Example: A graph’s connectivity pattern encoded as a matrix or list.
  2. Positional Representations

    • Encode nodes’ relative positions in the graph.
    • Example: Low-dimensional vectors that capture proximity to other nodes (e.g., Laplacian egeinvectors, Node2Vec).

Node & Set Representations¶

  • Node-level: Vectors representing individual nodes in the graphs.
    • We will focus on node representations for now.
  • Set-level: Vectors representing sets of nodes in the graphs.
No description has been provided for this image

3.1. Structural Node Representations¶

Structural Node Embeddings¶

  • Node embeddings that are equivariant to permutations of the node ids are called structural node embeddings (Shrinivasan & R., 2020).

  • Let's consider structural node embeddings applied to the Arctic food web graph below.

  • Assume we have a permutation-equivariant function $f: \mathbb{A}^{n\times n} \to \mathbb{R}^{n \times d}$ that produces a representation of node $v \in V$ in graph ${\bf A}$.

  • Let's consider the Arctic food web graph below.

    • We have added the constraint that $f$ is equivariant to permutations of the vertex ids
      • That is, $f(\pi \circ {\bf A}) = \pi \circ f({\bf A}).$
      • Let $Z_v = f({\bf A})_v$ be the a permutation-invariant representation of node $v \in V$.
      • In the figure, representations with the same colors have the same representation vectors.
  • Node representations that are invariant to permutations are denoted structural node representations.

    • Because nodes that are structurally equivalent on the graph must get the same representations
No description has been provided for this image

3.2. Positional Node Representations¶

Consider the matrix factorizations (e.g., singular value decomposition) of the adjacency matrix $A$ and the graph Laplacian $L = D - A$, where $D$ is the degree matrix. When we apply a permutation $\pi$ to these matrices, we get:

  • $A = Z \Sigma V^T$ and $A'=(\pi \cdot A) = Z' \Sigma' (V')^T$
  • $L = D - A = U \Lambda U^T$ and $L'=(\pi \cdot L) = U' \Lambda' (U')^T$

Example of foodweb eigenvectors of the graph Laplacian $L$:

No description has been provided for this image

Q1: Are the eigenvectors of the permuted matrix $Z'$ ($U'$) guaranteed to be a permuted version of $Z$ ($U$)?

A(Yes)

B(No)

No description has been provided for this image

A1: No. Eigenvectors have two key ambiguities affecting their transformation under permutations:

  1. Sign ambiguity: If $\mathbf{z}$ is an eigenvector, then $-\mathbf{z}$ is also valid for the same eigenvalue, as $A(-\mathbf{z}) = -\lambda \mathbf{z}$ (same for $L(-\mathbf{u}) = -\lambda \mathbf{u}$). For any permutation, signs might flip unpredictably depending on how the eigenvectors are computed.

  2. Eigenspace ambiguity: Also, with repeated eigenvalues (multiplicity $k > 1$), the eigenvectors become non-unique. The eigenspace is $k$-dimensional, and any orthogonal basis within it is valid.

When $\lambda$ has multiplicity $k$, the eigenvectors after permutation relate to the original ones through an orthogonal transformation: $$[\mathbf{z}'_1, \mathbf{z}'_2, ..., \mathbf{z}'_k] = [\mathbf{z}_1, \mathbf{z}_2, ..., \mathbf{z}_k]R$$ where $R$ is a $k \times k$ orthogonal matrix ($R^TR = I$).

  • A permutation can completely redistribute values across vector components, not just flipping signs of entire vectors, but mixing components in various ways.

This explains why in graphs with isomorphic structures (like in our food web), permuting the Orca with the Lynx or the Fox with the Baleen Whale can result in $Z \neq \pi^{-1} \circ Z'$.

The graph Laplacian provides additional insights because its eigenvalues and eigenvectors have specific physical interpretations: the smallest non-zero eigenvalues reflect the graph's connectivity, while their corresponding eigenvectors can be used for spectral partitioning of the graph.

4. Graph Neural Networks (GNNs):¶

Permutation-Equivariant Node Representations (Inspired by Image Convolutions)¶

Let's start with a CNN filter:

No description has been provided for this image

4.1 Images as a lattice¶

Note that the CNN filter is applied to a constant number of inputs in the last layer.
Topologically, an image is a lattice and the convolution is a filter applied over a patch of the lattice

No description has been provided for this image

Layered representations¶

Then, we apply this convolution in layers, multiple times. Note that each pixel in the previous layer has a convolution representation in the next layer.

No description has been provided for this image

Note that in CNNs:

  • Convolutions are applied over fixed-size neighborhoods of a vertex (pixel)
  • Convolutions are permutation-sensitive

Today, we are going to explore convolutions over more complex topologies.

4.2. Can we design "convolutions" for arbitrary graphs?¶

Let $\bf A$ represent an arbitrary simple (no loops) undirected social network graph. We now illustrate how a convolution should act over the topological space of Facebook friends:

The graph neural layer applied to Bruno will act on his neighbors

No description has been provided for this image

The graph neural layer applied to one of his friends will act on her neighbors

No description has been provided for this image

Graph Neural Layer¶

Since neighborhoods have varying sizes, Graph Neural Layers require a set representation
The composition of multiple Graph Neural layers is called a Graph Neural Network

4.3. Graph Neural Networks (GNNs)¶

The representation ${\bf h}^{(k)}_v \in \mathbb{R}^{1 \times d}$, $d \in \mathbb{N}$, at layer $k$ of node $v \in V$ can be described through:

  • Its own embedding at layer $k-1$, ${\bf h}^{(k-1)}_v \in \mathbb{R}^{1 \times d'}$, $d' \in \mathbb{N}$ and
  • The embedding of its neighbors $({\bf h}^{(k-1)}_u)_{\forall u \in \mathcal{N}_v}$ where $\mathcal{N}_v$ is the set of neighbors of $v$ in $V$.

Recursion¶

The resulting filter recursion is: $$ {\bf h}^{(k)}_v = \sigma\left( {\bf h}^{(k-1)}_v {\bf W}_\text{self}^{(k)} + \text{Pooling}\left(({\bf h}^{(k-1)}_u)_{\forall u \in \mathcal{N}_v}\right) {\bf W}_\text{neigh}^{(k)} + {\bf b}^{(k)} \right), $$ where ${\bf W}_\text{self}^{(k)} \in \mathbb{R}^{d' \times d}$, ${\bf W}_\text{neigh}^{(k)} \in \mathbb{R}^{d' \times d}$, ${\bf b}^{(k)} \in \mathbb{R}^{1 \times d}$, $d'\in \mathbb{N}$ and $\text{Pooling}$ is a set representation.

Pooling Function (set representation)¶

Given a sequence (input vector) of arbitrary length $n \geq 1$ $$ {\bf x} = (x_1,\ldots,x_n) $$ a permutation $\pi$ over the integers $\{1, 2,\ldots,n\}$ is such that $\pi \circ {\bf x} = (x_{\pi^{-1}_1},\ldots,x_{\pi^{-1}_n})$ is the correspondingly permuted version of ${\bf x}$.

Pooling is such that $$ \text{Pooling}({\bf x}) = \text{Pooling}(\pi \circ {\bf x}), \quad \forall \pi \in \mathbb{S}_n, $$

See our lecture on set representations for a complete list of possible Pooling functions.

Sum pooling example:

Using sum pooling, the resulting filter recursion is: $$ {\bf h}^{(k)}_v = \sigma\left( {\bf h}^{(k-1)}_v {\bf W}_\text{self}^{(k)} + \sum_{\forall u \in \mathcal{N}_v} {\bf h}^{(k-1)}_u {\bf W}_\text{neig}^{(k)} + {\bf b}^{(k)} \right), $$ where again $\mathcal{N}_v$ are the neighbors of node $v$ in the graph.

This variant is commonly known as GraphConv in the literature, and has been thoroughly studied in Morris et al. 2019.

4.3.1. GNN Variants¶

Most existing Graph Neural Networks are a variant of the above recursion.

4.3.1.1. Graph Attention Networks¶

Graph Attention Networks (GATs) (Veličković et al., 2018) replace ${\bf h}^{(k-1)}_u$ inside the pooling with $\alpha({\bf h}^{(k-1)}_v,{\bf h}^{(k-1)}_u) {\bf h}^{(k-1)}_u$, where $\alpha(\cdot,\cdot) \in (0,1)$ is an attention mechanism (Bahdanau et al., 2015).

More generally, an edge function can also be added before the set representation function, to better represent the connection between $v$ and its neighbors: $$ {\bf h}^{(k)}_v = \sigma\left( {\bf h}^{(k-1)}_v {\bf W}_\text{self}^{(k)} + \text{Pooling}\!\left(\left(\text{edgefunc}\left({\bf h}^{(k-1)}_v,{\bf h}^{(k-1)}_u\right)\right)_{\forall u \in \mathcal{N}_v}\right) {\bf W}_\text{neig}^{(k)} + {\bf b}^{(k)} \right), $$ where GAT is just one such example.

4.3.1.2. Adding edge attributes¶

Adding edge attributes is trivial.

Consider the sum pooling example:

  • Let e[i,j] be the attribute of edge $i \to j$.
  • Directed vs undirected graphs: Note that we always assume a graph to be undirected and encode the edge direction as an attribute
  • A trivial way to add edge attributes is: $$ {\bf h}^{(k)}_v = \sigma\left( {\bf h}^{(k-1)}_v {\bf W}_\text{self}^{(k)} + \sum_{\forall u \in \mathcal{N}_v} \text{MLP}(e[u,v],{\bf h}^{(k-1)}_u) {\bf W}_\text{neig}^{(k)} + {\bf b}^{(k)} \right), $$ where again $\mathcal{N}_v$ are the neighbors of node $v$ in the graph $G$.
  • Alternative approaches include: $$ {\bf h}^{(k)}_v = \sigma\left( {\bf h}^{(k-1)}_v {\bf W}_\text{self}^{(k)} + \sum_{\forall u \in \mathcal{N}_v} \text{MLP}_\sigma(e[u,v]) \odot {\bf h}^{(k-1)}_u {\bf W}_\text{neig}^{(k)} + {\bf b}^{(k)} \right), $$ where $\text{MLP}_\sigma$ is an MLP with sigmoid activation outputs and $\odot$ is the element-wise product (Hadamard product).

5. Most-expressive Graph Representations¶

  • GNNs assign the same representation to isomorphic graphs.
    • In view of the required constraint that a GNN is invariant to permutations of the vertex ids.
  • Additional desideratum: Different representations to non-isomorphic graphs.
    • Non isomorphic graphs have different structures, so they should have different representations.
    • A downstream classifier can then push them together, if needed.

Definition (Most Expressive Graph Representation): A graph representation is most expressive if it gives the same representation to isomorphic graphs and can give different representations to non-isomorphic graphs.

Q2: Are GNNs most-expressive representations for graphs?

(A) Yes

(B) No

A2: No, there exist pairs of non-isomorphic graphs that cannot be distinguished by standard GNNs (Xu et al., 2019).

Independently of the learning procedure, certain non-isomorphic graphs will get the same representation.

Example 1: Circular Skip Link (CSL) task (Murphy et al., 2019)

No description has been provided for this image

Task: Whole-graph classification for graphs with $M$ vertices to predict skip length $L$.

A CSL graph $G(n,k)$ consists of $n$ nodes arranged in a circle, where each node is connected to its $k$ nearest neighbors on each side, plus one "skip" connection to a node at distance $k+1$ or $k+2$ depending on the graph variant.

Let's visualize two non-isomorphic CSL graphs that standard GNNs cannot distinguish.

  1. CSL Graph $G_1(n=11,L=2)$:

    • Nodes: $\{1,\ldots,11\}$
    • For node 1: connections to nodes 2, 11 (neighbors) and 3 (skip at distance $L$)
    • For node 2: connections to nodes 1, 3 (neighbors) and 4 (skip at distance $L$)
    • And so on...
  2. CSL Graph $G_2(n=11,L=3)$:

    • Nodes: $\{1,\ldots,11\}$
    • For node 1: connections to nodes 2, 11 (neighbors) and 4 (skip at distance $L$)
    • For node 2: connections to nodes 1, 3 (neighbors) and 5 (skip at distance $L$)
    • And so on...

When using standard message-passing GNNs, all nodes in both graphs receive identical representations because locally, each node has exactly the same pattern: two neighbor connections and one skip connection. The standard GNN message-passing algorithm, which underlies most GNNs, cannot detect the global structural differences between these graphs.

5.1. GNN representation power¶

  • If GNNs are not most expressive, is there a way of quantifying their expressive power?
  • Do all GNNs have the same expressive power?

We will see that we can quantify the expressive power of GNN in terms of the WL test, a well known heuristic used in graph theory to test graph isomorphism.

5.1.1. Detour: The WL test¶

Recall our desideratum, which is not obtained by standard GNNs: different representations to non-isomorphic graphs.

Obviously, if a network is able to test for graph isomorphism, then it is able to assign a unique representation to each isomorphic class.

  • But testing for graph isomorphism is not an easy problem.

The graph isomorphism problem is NP-intermediate (i.e., not known to be solvable in poly time, nor to be NP complete).

The WL test is a combinatorial heuristic to test graph isomorphism.

  • If two graphs are distinguished by the WL test, they are non-isomorphic (necessary condition for isomorphism).
  • The reverse is not true! (not a sufficient condition for isomorphism).

WL test pseudocode

Given two graphs ${\bf A}_1$, ${\bf A}_2$.

     1. In every graph, assign the same initial color to every node (or start from given node features, if present).

     2. Repeat until colors are stable:

         Update the color of every node as:

$$ c_{v, {\bf A}_1}^{(t)} = \text{HASH}( c_{v, {\bf A}_1}^{(t-1)}, \{\!\{ c_{u, {\bf A}_1}^{(t)} \}\!\}_{u \in \mathcal{N}_v})$$

$$ c_{v, {\bf A}_2}^{(t)} = \text{HASH}( c_{v, {\bf A}_2}^{(t-1)}, \{\!\{ c_{u, {\bf A}_2}^{(t)} \}\!\}_{u \in \mathcal{N}_v})$$

         If $\{\!\{ c_{u, {\bf A}_1}^{(t)} \}\!\}_{v \in {\bf A}_1} \neq \{\!\{ c_{v, {\bf A}_2}^{(t)} \}\!\}_{v \in {\bf A}_2}$ then ${\bf A}_1$ and ${\bf A}_2$ non-isomorphic.

WL test: example¶
No description has been provided for this image

Figure credit Expressive power of graph neural networks and the Weisfeiler-Lehman test

5.1.2. Implications of WL test¶

Theorem (Xu et al. 2019, Morris et al. 2019): the expressive power of GNNs is upper bounded by the WL test.

Remark: since there exist pairs of non-isomorphic graphs that are undistinguishable by the WL test, there exist pairs of non-isomorphic graphs that are undistinguishable by GNNs.

GNNs are at most as expressive as the WL test in distinguishing non-isomorphic graphs.

Let us see an example of non-isomorphic graphs that are indistinguishable by a GraphConv-based GNN.

  • We will use Pytorch Geometric for our GNN implementation.

In the environment you have in the scholar cluster install pyg as follows:

pip install -q torch-scatter -f https://data.pyg.org/whl/torch-${TORCH}.html
pip install -q torch-sparse -f https://data.pyg.org/whl/torch-${TORCH}.html
pip install -q git+https://github.com/pyg-team/pytorch_geometric.git

where TORCH is simply the version of Pytorch you have installed, which you can find with python as

import torch

print(torch.__version__)
In [1]:
# @title [RUN] Import modules

import os.path as osp

import matplotlib.cm as cm
import matplotlib.pyplot as plt
import networkx as nx
import numpy as np
import scipy.io as sio
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from scipy.special import comb
from sklearn.metrics import accuracy_score
from torch_geometric.data import InMemoryDataset
from torch_geometric.data.data import Data
from torch_geometric.loader import DataLoader
from torch_geometric.nn import GraphConv, global_add_pool
from torch_geometric.utils import to_networkx, to_undirected
In [2]:
# @title [RUN] Helper functions for plots and visualisations

def get_color(node_emb, hashmap):
    max_val = max(hashmap.values(), default=0) + 1
    crt_node_emb = np.round(node_emb, decimals=2)

    if tuple(crt_node_emb) not in hashmap:
        hashmap[tuple(crt_node_emb)] = max_val
        max_val += 1

    crt_node_emb = hashmap[tuple(crt_node_emb)]

    # Map float number to a color
    crt_color = cm.tab10(crt_node_emb, bytes=True)
    crt_color = (
        crt_color[0] / 255.0,
        crt_color[1] / 255.0,
        crt_color[2] / 255.0,
        crt_color[3] / 255.0,
    )
    return crt_color


def draw_one_graph(
    ax, edges, hash, label=None, node_emb=None, layout=None,
):

    graph = nx.Graph()
    graph.add_edges_from(zip(edges[0], edges[1]))
    node_pos = layout(graph)
    # Add colors according to node embeding
    if node_emb is not None:
        color_map = [
            get_color(node_emb[node_id], hash)
            for node_id in graph.nodes()
        ]

        nx.draw_networkx_nodes(
            graph, node_pos, node_color=color_map, nodelist=graph.nodes(), ax=ax
        )
        nx.draw_networkx_edges(graph, node_pos, ax=ax)
        nx.draw_networkx_labels(graph, node_pos, ax=ax)
    else:
        nx.draw_networkx(graph, node_pos, ax=ax)


def gallery(
    graphs,
    hash=None,
    labels=None,
    node_emb=None,
    max_fig_size=(40, 10),
    layout=nx.layout.kamada_kawai_layout,
):
    if hash is None:
        hash = {}

    num_graphs = len(graphs)
    ff, axes = plt.subplots(
        1, num_graphs, figsize=max_fig_size, subplot_kw={"xticks": [], "yticks": []}
    )
    if num_graphs == 1:
        axes = [axes]
    if node_emb is None:
        node_emb = num_graphs * [None]
    if labels is None:
        labels = num_graphs * [" "]

    for i in range(num_graphs):
        draw_one_graph(
            axes[i],
            graphs[i].edge_index.numpy(),
            hash,
            labels[i],
            node_emb[i],
            layout,
        )
        if labels[i] != " ":
            axes[i].set_title(f"Target: {labels[i]}", fontsize=28)
        axes[i].set_axis_off()

    plt.show()

Let us consider three exemplary graphs chosen from the Graph8c dataset, which contains all the possible connected non-isomorphic simple graphs with 8 nodes.

The goal is to understand whether a GraphConv-based GNN can disambiguate them.

To do so, we are going to assign a different class to each of them, and we are going to place them in our training set. A GNN can disambiguate them if and only if it can learn to correctly predict their targets.

In [3]:
# @title [RUN] `Graph8c` data retrieval
# Let's get three (selected) graphs from the Graph8c dataset from 
# “Breaking the Limits of Message Passing Graph Neural Networks”
# (https://arxiv.org/pdf/2106.04319.pdf)

!wget https://raw.githubusercontent.com/balcilar/gnn-matlang/main/dataset/graph8c/raw/graph8c.g6
--2025-02-26 08:34:32--  https://raw.githubusercontent.com/balcilar/gnn-matlang/main/dataset/graph8c/raw/graph8c.g6
185.199.108.133, 185.199.111.133, 185.199.109.133, ...tent.com)... 
Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|185.199.108.133|:443... connected.
200 OKequest sent, awaiting response... 
Length: 77819 (76K) [text/plain]
Saving to: ‘graph8c.g6.3’

graph8c.g6.3        100%[===================>]  76.00K  --.-KB/s    in 0.02s   

2025-02-26 08:34:32 (3.64 MB/s) - ‘graph8c.g6.3’ saved [77819/77819]

In [4]:
IDS = [379, 4625, 4657]


class Grapg8cDataset(InMemoryDataset):
    def __init__(self, root, transform=None, pre_transform=None):
        super(Grapg8cDataset, self).__init__(root, transform, pre_transform)
        self.data, self.slices = torch.load(self.processed_paths[0], weights_only=False)

    @property
    def raw_file_names(self):
        return ["graph8c.g6"]

    @property
    def processed_file_names(self):
        return "data.pt"

    def download(self):
        # Download to `self.raw_dir`.
        pass

    def process(self):
        # Read data into huge `Data` list.
        dataset = nx.read_graph6(self.raw_file_names[0])
        data_list = []
        for i, datum in enumerate(dataset):
            if i not in IDS:
                continue
            x = torch.ones(datum.number_of_nodes(), 1)
            edge_index = to_undirected(
                torch.tensor(list(datum.edges())).transpose(1, 0)
            )
            data_list.append(
                Data(edge_index=edge_index, x=x, y=torch.tensor(IDS.index(i)))
            )

        if self.pre_filter is not None:
            data_list = [data for data in data_list if self.pre_filter(data)]

        if self.pre_transform is not None:
            data_list = [self.pre_transform(data) for data in data_list]

        data, slices = self.collate(data_list)
        torch.save((data, slices), self.processed_paths[0])
In [5]:
ds = Grapg8cDataset(root="tmp/Graph8c")
G1, G2, G3 = ds[0], ds[1], ds[2]

What are those graphs?¶

Let us assign a different color for every different input feature.

In [6]:
gallery(
    [G1, G2, G3],
    labels=np.array([G1.y.item(), G2.y.item(), G3.y.item()]),
)
No description has been provided for this image

Now, it is time to implement our GNN and train to distinguish these three.

So far so good, it seems an easy task.

In [7]:
class MLP(nn.Module):
    """A simple feed forward neural network"""

    def __init__(self, in_dim, emb_dim, num_layers=2):
        super(MLP, self).__init__()
        layer_list = []
        layer_list.append(torch.nn.Linear(in_dim, emb_dim))

        for _ in range(num_layers - 1):
            layer_list.append(torch.nn.BatchNorm1d(emb_dim))
            layer_list.append(torch.nn.ReLU())
            layer_list.append(torch.nn.Linear(emb_dim, emb_dim))

        self.layers = torch.nn.Sequential(*layer_list)

    def forward(self, x):
        return self.layers(x)
In [8]:
class GraphConvNet(torch.nn.Module):
    def __init__(self, in_dim, emb_dim, out_dim, num_layers, num_final_layers=1):
        super(GraphConvNet, self).__init__()

        self.convs = torch.nn.ModuleList()

        for layer in range(num_layers):
            self.convs.append(
                GraphConv(
                    emb_dim if layer != 0 else in_dim,
                    emb_dim,
                )
            )

        self.pool = global_add_pool
        self.final_layers = MLP(emb_dim, out_dim, num_layers=num_final_layers)

    def forward(self, data):
        h_node = data.x
        for conv in self.convs:
            h_node = F.relu(conv(h_node, data.edge_index))
        h_graph = self.pool(h_node, data.batch)
        return self.final_layers(h_graph), h_node.detach()
In [9]:
# @title [RUN] Hyperparameters GNNs

BATCH_SIZE = 128  # @param {type:"integer"}
NUM_EPOCHS = 25  # @param {type:"integer"}
HIDDEN_DIM = 64  # @param {type:"integer"}
NUM_LAYERS = 4  # @param {type:"integer"}
LR = 0.001  # @param {type:"number"}
SEED = 42  # @param {type:"integer"}


DEVICE = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
In [10]:
# @title [RUN] Set the seed

torch.manual_seed(SEED)
np.random.seed(SEED)
In [11]:
def train(train_loader, model, optimiser, loss_fn, metric_fn):
    """Train model for one epoch"""
    model.train()

    total_loss = 0
    num_graphs = 0
    for data in train_loader:
        optimiser.zero_grad()

        data = data.to(DEVICE)
        y_hat, _ = model(data)
        loss = loss_fn(y_hat, data.y)

        loss.backward()
        optimiser.step()

        total_loss += loss.item() * len(data.y)
        num_graphs += len(data.y)

    return total_loss / num_graphs


def evaluate(loader, model, metric_fn):
    """Evaluate model on dataset"""
    y_pred, y_true = [], []
    model.eval()
    for data in loader:
        data = data.to(DEVICE)
        y_hat, _ = model(data)

        y_pred.append(y_hat.detach().cpu())
        y_true.append(data.y.detach().cpu())

    y_pred = torch.cat(y_pred, dim=0)
    y_true = torch.cat(y_true, dim=0)

    return metric_fn(y_true, y_pred)
In [12]:
def run(
    model,
    train_loader,
    loaders,
    loss_fn,
    metric_fn,
    use_scheduler=False,
    print_steps=True,
):
    """Train the model for NUM_EPOCHS epochs"""
    # Instantiate optimiser and scheduler
    optimiser = optim.Adam(model.parameters(), lr=LR)
    scheduler = (
        optim.lr_scheduler.StepLR(optimiser, step_size=DECAY_STEP, gamma=DECAY_RATE)
        if use_scheduler
        else None
    )
    curves = {name: [] for name in loaders.keys()}
    
    # Create tqdm progress bar for epochs
    from tqdm.auto import tqdm
    pbar = tqdm(range(NUM_EPOCHS), desc="Training")
    
    for epoch in pbar:
        train_loss = train(
            train_loader, model, optimiser, loss_fn, metric_fn
        )
        if scheduler is not None:
            scheduler.step()
            
        # Evaluate on all loaders
        metrics_dict = {}
        for name, loader in loaders.items():
            metric_value = evaluate(loader, model, metric_fn)
            curves[name].append(metric_value)
            metrics_dict[f"{name}_metric"] = f"{metric_value:.3f}"
        
        # Update progress bar with current metrics
        status_msg = f"loss: {train_loss:.6f}"
        for name, value in metrics_dict.items():
            status_msg += f" | {name}: {value}"
        pbar.set_postfix_str(status_msg)
    
    return curves
In [13]:
# Instantiate our models
graphconv_model = GraphConvNet(
    in_dim=ds.num_features,
    emb_dim=HIDDEN_DIM,
    out_dim=ds.num_classes,
    num_layers=NUM_LAYERS,
).to(DEVICE)
In [14]:
# Create the Dataloader
train_loader = DataLoader(ds, BATCH_SIZE, shuffle=True)
In [15]:
# Train our GNN model
_ = run(
    graphconv_model,
    train_loader,
    {"train": train_loader},
    loss_fn=F.cross_entropy,
    metric_fn=lambda x, y: accuracy_score(x, y.argmax(-1)),
)
Training:   0%|          | 0/25 [00:00<?, ?it/s]

Since the accuracy is 2/3, the GNN model is able to distinguish 2/3 of the graphs.

  • And since we had 3 graphs, it implies that 2 of them are indististinguishable.

Let us visualise our three graphs, and use a different color for every different node representation learnt by our GNN.

In [16]:
_, G1_h_nodes = graphconv_model.to("cpu")(G1)
_, G2_h_nodes = graphconv_model.to("cpu")(G2)
_, G3_h_nodes = graphconv_model.to("cpu")(G3)

stateful_hash = {}
gallery(
    [G1, G2, G3],
    hash=stateful_hash,
    labels=np.array([G1.y.item(), G2.y.item(), G3.y.item()]),
    node_emb=[G1_h_nodes.numpy(), G2_h_nodes.numpy(), G3_h_nodes.numpy()],
)
No description has been provided for this image

Our GNN model is unable to distinguish the second and the third graph!

Indeed, you can see that their nodes have the same colors, or, more precisely, these graphs have the same number of nodes having the same color.

Thus any graph representation obtained from these node representations will be the same.

We have seen that any standard GNN is at most as powerful as the WL test.

Does it mean that also the WL test is unable to distinguish these two non-isomorphic graphs?

In [17]:
hash2 = nx.weisfeiler_lehman_graph_hash(to_networkx(G2), iterations=6)
hash3 = nx.weisfeiler_lehman_graph_hash(to_networkx(G3), iterations=6)

hash2 == hash3
Out[17]:
True

Indeed, the WL test also fails to tell them apart!

Actually, GraphConv is as powerful as the WL test (Morris et al., 2019).

But note that this is not true for all GNNs, as some are even less powerful.


References¶

Srinivasan and Ribeiro, 2020. Srinivasan, B., and Ribeiro, B. On the Equivalence between Positional Node Embeddings and Structural Graph Representations. ICLR 2020.

Morris et al., 2019. Morris, C., Ritzert, M., Fey, M., Hamilton, W. L., Lenssen, J. E., Rattan, G., and Grohe, M. Weisfeiler and leman go neural: Higher-order graph neural networks. AAAI 2019

Veličković et al., 2018. Veličković, P., Cucurull, G., Casanova, A., Romero, A., Liò, P., and Bengio, Y. Graph attention Networks. ICLR 2018

Bahdanau et al., 2015. Bahdanau, D., Cho, K. H., and Bengio, Y. Neural machine translation by jointly learning to align and translate. ICLR 2015

Xu et al., 2019. Xu, K., Hu, W., Leskovec, J., and Jegelka, S. How powerful are graph neural networks? ICLR 2019

Murphy et al., 2019. Murphy, R., Srinivasan, B., Rao., V. and Ribeiro, B. Relational Pooling for Graph Representations. ICML 2019

Maron et al., 2019a. Maron, H., Ben-Hamu, H., Shamir, N., and Lipman, Y. Invariant and Equivariant Graph Networks. ICLR 2019

Maron et al., 2019b. Maron, H., Ben-Hamu, H., Segol, N., and Lipman, Y. On the Universality of Invariant Networks. ICML 2019

Maron et al., 2019c. Maron, H., Ben-Hamu, H., Serviansky, H., and Lipman, Y. Provably powerful graph networks. NeurIPS 2019

Geerts, 2020. Geerts, F. The expressive power of kth-order invariant graph networks. ArXiv Preprint

Abboud et al., 2021. Abboud, R., Ceylan, I. I., Grohe, M., and Lukasiewicz, T. The surprising power of graph neural networks with random node initialization. IJCAI-21

Sato et al., 2021. Sato, R., Yamada, M., and Kashima, H. Random features strengthen graph neural networks. SDM 2021

Chen et al., 2020. Chen, Z., Chen, L., Villar, S., Bruna, J. Can Graph Neural Networks Count Substructures? NeurIPS 2020

Bouritsas et al., 2022. Bouritsas, G., Frasca, F., Zafeiriou, S., and Bronstein, M. M. Improving graph neural network expressivity via subgraph isomorphism counting. IEEE Transactions on Pattern Analysis and Machine Intelligence 2022

Bodnar et al., 2021. Bodnar, C., Frasca, F., Otter, N., Wang, Y. G., Liò, P., Montúfar, G., and Bronstein, M. M. Weisfeiler and lehman go cellular: CW networks. NeurIPS 2021

Cotta et al., 2021. Cotta, L., Morris, C., and Ribeiro, B. Reconstruction for powerful graph representations. NeurIPS 2021

Zhang and Li, 2021. Zhang, M. and Li, P. Nested graph neural networks. NeurIPS 2021

You et al., 2021. You, J., Gomes-Selman, J., Ying, R., and Leskovec, J. Identity-aware graph neural networks. AAAI 2021.

Bevilacqua et al., 2022. Bevilacqua, B., Frasca, F., Lim, D., Srinivasan, D., Cai, C., Balamurugan, G., Bronstein, M. M., Maron, H. Equivariant Subgraph Aggregation Networks. ICLR 2022

Zhao et al., 2022. Zhao, L., Jin, W., Akoglu, L., and Shah, N. From stars to subgraphs: Uplifting any GNN with local structure awareness. ICLR 2022.

Papp et al., 2021. Papp, P. A., Martinkus, K., Faber, L., and Wattenhofer, R. Dropgnn: Random dropouts increase the expressiveness of graph neural networks. NeurIPS 2021

Frasca et al., 2022. Frasca, F., Bevilacqua, B., Bronstein, M. M., Maron, H. Understanding and Extending Subgraph GNNs by Rethinking their Symmetries. NeurIPS 2022

Quian et al., 2022. Qian, C., Rattan, G., Geerts, F., Morris, C., Niepert, M. Ordered Subgraph Aggregation Networks. NeurIPS 2022