"In the random graph, order emerges from chaos - the giant component appears suddenly, like a phase transition in physics, when the average degree crosses one."
- Bela Bollobas
Overview
Random graphs are probability distributions over graph-valued random variables. They provide the mathematical framework for reasoning about networks whose structure is not fully known or arises from stochastic processes - exactly the situation we face with the internet, social networks, protein interaction maps, and the implicit graphs inside neural networks.
This section develops four canonical random graph models - Erdos-Renyi , Watts-Strogatz small-world, Barabasi-Albert scale-free, and the Stochastic Block Model - from their definitions through their phase transitions, spectral properties, and connections to modern machine learning. We close with graphons, the measure-theoretic limit objects that unify all dense random graph models and form the mathematical foundation of graph neural network universality theory.
The central theme is emergence: how global structure (giant components, communities, power-law degree distributions) arises from simple local rules, and how this emergence can be detected, quantified, and exploited by ML algorithms.
Prerequisites
- Probability theory: expectation, variance, concentration inequalities - Probability Foundations
- Graph Laplacians and spectral graph theory - Spectral Graph Theory
- Graph Neural Networks (for the ML applications) - Graph Neural Networks
- Basic combinatorics: binomial coefficients, Stirling's approximation
Companion Notebooks
| Notebook | Description |
|---|---|
| theory.ipynb | Interactive simulations of all four models, phase transitions, spectral laws |
| exercises.ipynb | 8 graded problems from threshold functions to graphon estimation |
Learning Objectives
After completing this section, you will:
- Define and sample from , , Watts-Strogatz, Barabasi-Albert, and SBM
- State the giant component phase transition theorem and prove the critical threshold
- Derive the Poisson degree distribution of in the sparse regime
- Compute clustering coefficient and average path length for small-world graphs
- Derive the power-law degree distribution via mean-field preferential attachment
- State the Kesten-Stigum threshold for community detection in the SBM
- Apply Wigner's semicircle law and Davis-Kahan to spectral clustering of random graphs
- Define graphons, the cut metric, and explain how graphons arise as limits of dense graph sequences
- Connect random graph theory to GNN benchmark design, graph generation, and LLM attention structure
- Identify and fix the most common mistakes in applying random graph models
Table of Contents
- 1. Intuition
- 2. Probability on Graphs: Formal Setup
- 3. Erdos-Renyi Model
- 4. Watts-Strogatz Small-World Model
- 5. Barabasi-Albert Scale-Free Model
- 6. Stochastic Block Model
- 7. Spectral Properties of Random Graphs
- 8. Graphons: The Infinite-Size Limit
- 9. Applications in Machine Learning
- 10. Common Mistakes
- 11. Exercises
- 12. Why This Matters for AI (2026 Perspective)
- 13. Conceptual Bridge
1. Intuition
1.1 What Is a Random Graph?
A random graph is not a single graph but a probability distribution over graphs. When we write , we mean: take labeled vertices; independently include each of the possible edges with probability . The specific graph is a sample from this distribution.
This is a powerful abstraction. Real-world networks - social graphs, citation networks, protein-protein interaction maps, the web - cannot be written down in closed form. They arise from complex processes involving millions of actors. Random graph models capture the statistical regularity of these networks without requiring knowledge of every individual edge.
Key insight: Many properties of real-world networks can be characterized by just a few parameters (average degree, clustering coefficient, community structure), and random graph models are the mathematical objects that interpolate between these summary statistics and the full combinatorial structure of the graph.
For AI and ML, random graphs matter in at least three ways:
- Benchmark generation: We generate synthetic graphs from random models to test GNN algorithms across controlled conditions (the GraphWorld framework uses SBM).
- Graph generation models: GRAN, GDSS, and DiGress learn to sample from distributions over graphs - essentially learning a graphon.
- Network analysis: Training data graphs (social networks, citation networks, knowledge graphs) have structure that random graph models help characterize and exploit.
1.2 Why Random Graphs Matter for AI
The connection between random graphs and modern AI is deeper than benchmark generation:
Transformer attention is a random graph. In a language model with tokens and sparse attention, the attention pattern defines a random-looking bipartite graph. The connectivity of this graph determines information flow - whether distant tokens can influence each other and how quickly information propagates. Results from random graph theory (connectivity thresholds, small-world phenomena) directly predict when transformers can or cannot capture long-range dependencies.
GNN expressiveness depends on graph structure. The WL hierarchy and GIN's expressiveness guarantees depend on what graphs the model will see. If training graphs are sampled from an SBM, the GNN faces a specific community detection problem that has known information-theoretic limits - limits that bound what no GNN can achieve regardless of architecture.
Overparameterized networks are sparse graphs. The lottery ticket hypothesis says that dense networks contain sparse subnetworks (tickets) that train just as well. These sparse subnetworks have random-graph-like structure: they appear near the percolation threshold of the dense network.
Graphons = graph neural network limits. The mathematical theory of graphons (limit objects of dense graph sequences) is the same theory that gives GNNs their universality results. A GNN that is continuous in the cut metric topology of graphons is provably expressive on all graphs in the same graphon equivalence class.
1.3 The Four Canonical Models
THE FOUR CANONICAL RANDOM GRAPH MODELS
========================================================================
Model Parameters Key property
---------------------------------------------------------------------
Erdos-Renyi n, p (or n, m) Phase transition at p = 1/n
G(n,p) Independent edges Poisson degree distribution
Thresholds for all monotone props
Watts-Strogatz n, k, \beta High clustering + short paths
Small-World Ring lattice + Models social/neural networks
random rewiring Navigability (Kleinberg)
Barabasi-Albert n, m_0, m Power-law degree distribution
Scale-Free Preferential Hubs, robustness to random failure
attachment Most real-world networks
Stochastic k, n_1,...,n_k, B Community structure
Block Model Block membership Kesten-Stigum threshold
(SBM) + probability matrix Benchmark for GNN node classif.
========================================================================
Each model captures one dominant feature of real-world networks:
- ER captures mathematical tractability and threshold phenomena
- WS captures the small-world property (short paths, high clustering)
- BA captures heterogeneity (a few highly-connected hubs, many low-degree nodes)
- SBM captures community structure (dense intra-community, sparse inter-community)
Real networks typically exhibit several of these properties simultaneously. Hybrid models (e.g., SBM with degree correction, or preferential attachment with community structure) better match empirical data.
1.4 Historical Timeline: 1959-2026
RANDOM GRAPH THEORY: 1959-2026
========================================================================
1959 Erdos & Renyi introduce G(n,m); first random graph paper
1960 Erdos & Renyi prove giant component phase transition
1961 Erdos & Renyi prove connectivity threshold p = log(n)/n
1984 Bollobas writes first comprehensive textbook on random graphs
1995 Chung & Lu: random graphs with given expected degrees
1998 Watts & Strogatz: small-world networks (Nature, ~36,000 cites)
1999 Barabasi & Albert: scale-free networks (Science, ~50,000 cites)
2001 Lovasz & Szegedy begin graphon theory (published 2006)
2001 Girvan & Newman: modularity and community detection
2007 Lovasz & Szegedy: limits of dense graph sequences (JCTB)
2011 Mossel, Neeman, Sly: Kesten-Stigum threshold (stochastic proof)
2014 Abbe & Sandon: exact recovery threshold for SBM
2015 You, Ying, Leskovec: GraphRNN graph generation
2018 Keriven & Peyre: graphon neural networks
2020 GraphWorld: benchmark generation via SBM
2022 Rusch, Bronstein, Mishra: gradient over-squashing theory
2023 DiGress: discrete diffusion for graph generation
2024 Graphon attention transformers (sparse attention limits)
2026 Graphon-based GNN universality: completeness results
========================================================================
1.5 Phase Transitions: The Central Metaphor
The most striking feature of random graphs is the phase transition: a sudden, dramatic change in global structure as a parameter crosses a critical threshold. This is not merely a quantitative change but a qualitative one - the graph transitions from one phase (many small components) to another (one giant component plus small components).
Physical analogy: In ferromagnetism, a material transitions from disordered (many small magnetic domains) to ordered (one aligned domain) as temperature drops below the Curie point. The mathematics is identical: both are percolation phase transitions.
The critical exponent phenomenon: Near the critical point , the giant component has size - a polynomial intermediate between the subcritical and supercritical regimes. This scaling is a universal critical exponent that appears in many other combinatorial and physical phase transitions.
For AI: Phase transitions in random graphs correspond to phase transitions in learning. A GNN trained to detect community structure in SBMs undergoes a computational phase transition at the Kesten-Stigum threshold - above it, polynomial-time algorithms succeed; below it, no efficient algorithm can (conditional on computational hardness conjectures). This is the rigorous mathematical statement of why some graph learning problems are fundamentally hard.
2. Probability on Graphs: Formal Setup
2.1 Graph Probability Spaces
Let denote the set of all labeled graphs on vertex set . A random graph model is a probability measure on .
Definition (Random Graph): A random graph on vertices is a random variable taking values in , defined on some probability space .
The key examples:
(Erdos-Renyi): Each edge is included independently with probability . The probability of a specific graph with edges is:
(fixed-edge): Uniform over all graphs with exactly edges:
Equivalence: and with have the same asymptotic behavior for most properties. More precisely, conditioned on having exactly edges is .
Graph properties as events: A graph property is a set of graphs closed under isomorphism (it depends only on structure, not labeling). We study the event and its probability as .
2.2 With High Probability (w.h.p.)
Definition (w.h.p.): We say satisfies property with high probability (w.h.p.) if:
This is distinct from "always" - there will always be rare samples that violate the property. But in the limit, the measure of the failure set goes to zero.
Notation conventions:
- :
- :
- : for constants
- :
Example (Isolated vertices): In with , the probability that vertex is isolated is . The expected number of isolated vertices is . For , this expected number is , and the actual number of isolated vertices is 0 w.h.p.
Markov's inequality (First Moment Method): If and , then w.h.p. (since ). This proves upper bounds on the probability of properties.
Second moment method: If , then w.h.p. (Paley-Zygmund inequality: ). This proves lower bounds.
2.3 Monotone Properties and Threshold Functions
Definition (Monotone property): A graph property is monotone increasing if whenever and (additional edges), then . Examples: connectivity, containing a triangle, having a giant component.
Theorem (Bollobas-Thomason, 1987): Every non-trivial monotone graph property has a threshold function such that:
The proof uses the noise sensitivity / sharp threshold theory: monotone properties exhibit sharp transitions (the window where goes from near-0 to near-1 is wide) due to the influence of edges being approximately equal.
For AI: Sharp thresholds are the theoretical explanation for why GNN performance can change dramatically as graph density or community strength crosses a critical value. A model that performs at 90% accuracy might drop to random guessing when a graph parameter decreases by a factor of 2.
2.4 First and Second Moment Methods
These are the two workhorses for proving w.h.p. statements.
First Moment (Upper Bound):
To show holds w.h.p., find a "bad event" and show :
Second Moment (Lower Bound):
To show w.h.p. (where counts copies of some structure):
Paley-Zygmund inequality:
Expanding: , so we need to bound correlations between pairs of copies.
Example (Triangles): Let = number of triangles in .
- For :
The triangle threshold is : for , no triangles w.h.p.; for , triangles exist w.h.p.
3. Erdos-Renyi Model
3.1 Definitions: G(n,p) and G(n,m)
The Erdos-Renyi model is the simplest and most mathematically tractable random graph model. Its beauty lies in the complete independence of edges, which makes exact calculations feasible.
Definition : The random graph on where each edge is independently present with probability .
Statistics:
- for each vertex
Definition : The random graph on drawn uniformly from all graphs with exactly edges.
Regime classification (by average degree ):
| Regime | range | range | Largest component |
|---|---|---|---|
| Subcritical | |||
| Critical | |||
| Supercritical | |||
| Connected | (whole graph) |
For AI: When analyzing message passing in sparse GNNs on ER graphs, the regime determines whether information can flow globally. Below criticality (), most nodes are in isolated small components - the GNN can only see local structure. Above criticality, there's a giant component enabling global information flow.
3.2 Degree Distribution: Poisson Limit
Theorem (Poisson Degree Distribution): In with , the degree of a fixed vertex satisfies:
Proof sketch: where are i.i.d. The sum of independent Bernoullis with success probability converges to Poisson() by the law of small numbers (Poisson limit theorem).
Generating function approach: The probability generating function of is:
Consequences of Poisson degree distribution:
- Exponential tail: - degrees are concentrated near
- Max degree: (sublinear in )
- No hubs: Unlike scale-free networks, ER graphs have no nodes with degree
Contrast with scale-free: Power-law degree distributions have polynomial tails and allow hubs with degree . This is why real networks (preferential attachment) look so different from ER.
3.3 Giant Component Phase Transition
This is the central theorem of random graph theory - one of the most beautiful results in all of combinatorics.
Theorem (Erdos-Renyi, 1960): Let be a constant and . Let denote the size of the largest connected component of .
-
Subcritical (): w.h.p., where . In particular, .
-
Critical (): in distribution (scaling limit is Brownian motion related).
-
Supercritical (): w.h.p., where is the unique solution in to:
The second-largest component has size .
The survival probability : The equation has a probabilistic interpretation. Think of each vertex independently joining the giant component with probability . A vertex joins if it has at least one neighbor that also joins. If neighbors join with probability , and there are neighbors, the probability of having at least one joining neighbor is - hence the fixed-point equation.
Derivation via branching processes: A key technique is to compare component exploration with a branching process. Starting from vertex , reveal its neighbors one by one. Each neighbor independently has additional neighbors (in the limit). This is a Galton-Watson branching process with offspring distribution .
A Galton-Watson process with mean offspring survives (generates an infinite tree) with probability satisfying . Below (mean offspring ), the process dies out almost surely - hence subcritical. Above , there's a positive probability of survival - hence the giant component.
Size of the giant component:
| (fraction in giant) | |
|---|---|
| 0.5 | 0 (subcritical) |
| 1.0 | 0 (critical, but scaling) |
| 1.5 | 0.583 |
| 2.0 | 0.797 |
| 3.0 | 0.940 |
| 5.0 | 0.993 |
For AI: GNN expressiveness on random graphs undergoes a similar phase transition. In the subcritical regime, the WL algorithm (and GINs) see disconnected local neighborhoods - they cannot distinguish non-isomorphic components. In the supercritical regime, the global component provides rich structural information.
3.4 Connectivity Threshold
Theorem (Erdos-Renyi, 1961): Let for a constant . Then:
In particular:
- If : is disconnected w.h.p.
- If : is connected with probability
- If : is connected w.h.p.
Proof sketch (upper bound via first moment):
Let = number of components of size . The bottleneck is (isolated vertices). A vertex is isolated iff none of its potential edges are present:
Expected isolated vertices: .
By a Poisson approximation argument, in distribution, so:
Connectivity fails iff or there's a larger isolated component. One shows larger components disappear before isolated vertices, so connectivity threshold isolated vertex disappearance threshold.
Sharp threshold: The window is - any diverging suffices. This is an unusually sharp threshold (polynomial-width thresholds are more common).
3.5 Subgraph Counts and Triangle Thresholds
Definition: A subgraph count for a fixed graph is number of labeled copies of in .
Expectation:
For dense subgraphs, this simplifies to .
Threshold for : By the first and second moment methods, w.h.p. iff , where:
is the maximum 2-core density of .
Triangle threshold: For (triangle), , so threshold is .
| Subgraph | | | | Threshold | |-------------|-------|-------|---------|----------------| | Edge | 2 | 1 | 1/2 | | | Path | 3 | 2 | 2/3 | | | Triangle | 3 | 3 | 1 | | | 4-clique | 4 | 6 | 3/2 | | | 5-clique | 5 | 10 | 2 | |
Janson's inequality: Provides exponential concentration for subgraph counts when is large:
where sums over pairs sharing at least one edge.
3.6 Diameter and Distances
Theorem: In with (supercritical), the diameter of the giant component is:
w.h.p. More precisely, .
Why? The giant component behaves like a random tree with branching factor . Starting from any node, the neighborhood of radius has size . It reaches when , i.e., .
Characteristic path length: This diameter is the mathematical explanation for the six degrees of separation phenomenon. With (Facebook) and (100 friends), the diameter is - indeed about 4-6 hops.
Contrast with small-world: In the ring lattice (before rewiring), diameter is - linear. Watts-Strogatz introduces just fraction of random rewirings to drop this to while maintaining high clustering.
3.7 Spectral Properties of G(n,p)
Expected adjacency matrix: , a rank-1 perturbation of .
Spectral decomposition: Write . The fluctuation matrix is a Wigner matrix (symmetric, zero-diagonal, i.i.d. entries above diagonal).
Theorem (Furedi-Komlos, 1981): For with constant, the eigenvalues of satisfy:
- (outlier, corresponding to the average degree direction )
- are in w.h.p.
The bulk eigenvalues follow Wigner's semicircle law with radius .
For spectral clustering: The spectral gap determines how easily we can detect the leading eigenvector (which encodes the community structure in SBM).
4. Watts-Strogatz Small-World Model
4.1 Construction and Parameters
The Watts-Strogatz (WS) model was introduced in 1998 to explain a paradox: real-world networks (social, neural, power grid) have both high clustering AND short path lengths. Regular lattices have high clustering but long paths; ER random graphs have short paths but low clustering. WS interpolates between them.
Construction (Watts-Strogatz, 1998):
- Start with a ring lattice: nodes arranged in a circle, each connected to nearest neighbors ( on each side). Assume .
- Rewire: For each edge with in the ring, with probability replace with a uniformly random node (avoiding duplicate edges).
Parameters:
- : number of nodes
- : initial degree (even integer, typically )
- : rewiring probability
- : regular ring lattice (high clustering, long paths)
- : approximately ER random graph (low clustering, short paths)
- -: small-world regime (high clustering, short paths!)
For AI: Neural network connection graphs and attention patterns often exhibit small-world structure. The feedforward layers of transformers have short path lengths (like random graphs) while local attention heads maintain clustered connections (like lattices). Understanding this structure informs efficient attention design.
4.2 Clustering Coefficient
Definition: The local clustering coefficient of vertex with degree is:
the fraction of 's possible neighbor-pairs that are also connected.
Global clustering coefficient: (average over vertices).
Ring lattice (): Each vertex has neighbors (the on each side of the ring). Neighbors of include all nodes within distance . A pair of 's neighbors are connected iff they are within distance of each other.
For large , the fraction of connected neighbor pairs is approximately:
WS model: For small , the clustering coefficient is approximately:
This is because a triangle involving requires all three edges to survive rewiring, and each edge survives with probability .
Random graph (): For ER with :
Key observation: For small (say ), - still very high, close to the lattice value.
4.3 Average Path Length
Ring lattice (): The shortest path between two nodes separated by positions in the ring is . The average path length is approximately , which grows linearly with .
WS model (): The average path length drops dramatically with rewiring. Even a tiny introduces long-range shortcuts that drastically reduce path lengths.
Heuristic analysis (Newman-Watts): The typical inter-component distance after rewiring is:
where for large . For , the path length transitions from to .
Numerical example (, ):
| 0 | 0.667 | 50 |
| 0.001 | 0.660 | 20 |
| 0.01 | 0.640 | 8 |
| 0.1 | 0.528 | 5 |
| 0.5 | 0.195 | 4 |
| 1.0 | 0.010 | 3 |
The small-world regime (-) achieves high and low simultaneously.
4.4 The Small-World Regime
Watts-Strogatz property: A graph is said to have the small-world property if:
- (much more clustered than ER)
- (path length comparable to ER)
These two conditions are simultaneously satisfied for WS with .
Empirical validation:
Watts and Strogatz validated the model against three real networks:
| Network | ||||||
|---|---|---|---|---|---|---|
| Film actors | 225,226 | 61 | 0.79 | 0.00027 | 3.65 | 2.99 |
| Power grid (W. US) | 4,941 | 2.67 | 0.080 | 0.005 | 18.7 | 12.4 |
| C. elegans neural | 282 | 14 | 0.28 | 0.05 | 2.65 | 2.25 |
All three networks have high clustering (much above ER random graph level) but short average path lengths (comparable to ER). This is the hallmark of small-world structure.
4.5 Navigability and Kleinberg's Grid
Watts and Strogatz showed that small-world graphs have short paths, but Kleinberg (2000) asked: can nodes find these short paths using only local information?
Kleinberg's model: Start with a 2D grid of nodes. Each node has edges to all grid neighbors within distance (local structure) plus one long-range link to node chosen with probability proportional to .
Theorem (Kleinberg, 2000):
- If (exponent matches grid dimension): greedy routing finds paths of length w.h.p.
- If : any decentralized algorithm requires steps for some .
Interpretation: The power-law exponent (where is the grid dimension) uniquely enables efficient decentralized navigation. Real social networks approximate this condition, explaining how people can navigate social networks in few steps even with only local knowledge.
For AI: This connects to hierarchical attention in transformers. FlashAttention-2 and related methods achieve efficient attention by exploiting the fact that attention scores decay with token distance - a continuous analog of Kleinberg's inverse power-law long-range links.
4.6 Social Network Evidence
Small-world structure has been empirically validated across many domains:
- Social networks: Milgram's 1967 experiment found ~6 hops between strangers in the US; Facebook (2016) found average path length 3.57 for 1.6 billion users.
- Neural connectomes: C. elegans (302 neurons), mouse visual cortex, human brain fMRI networks all show high clustering and short paths.
- Internet topology: ASN-level and router-level graphs exhibit small-world properties.
- Citation networks: Academic citation graphs have -, well above the ER baseline.
Limitations: WS does not generate power-law degree distributions. Real networks often exhibit BOTH small-world AND scale-free properties - requiring hybrid models.
5. Barabasi-Albert Scale-Free Model
5.1 Preferential Attachment
The Barabasi-Albert (BA) model was introduced in 1999 to explain a universal observation: degree distributions in real-world networks follow a power law with -. This is incompatible with the exponential tails of ER's Poisson distribution.
The explanation: networks grow over time, and new nodes prefer to attach to high-degree nodes. This "rich get richer" mechanism generates hubs.
Construction (Barabasi-Albert):
- Start with nodes with arbitrary connections.
- At each time step :
- Add one new node
- Connect to existing nodes, chosen independently with probability proportional to their current degree:
The denominator (handshaking lemma).
Why "preferential attachment"? This mimics real-world network growth:
- Web pages link to popular pages (already have many in-links)
- Scientists cite highly-cited papers
- Airports add routes to hubs
For AI: GNN training graphs from large knowledge bases (Wikidata, Freebase) exhibit scale-free degree distributions. GNN aggregation functions must handle this heterogeneity - a degree-10 node and a degree-1000 node require different treatment.
5.2 Power-Law Degree Distribution
Theorem (Barabasi-Albert, 1999; rigorous: Bollobas et al., 2001): For , as , the degree distribution satisfies:
This is a power law with exponent :
Scale-free: A distribution is called scale-free if for some . Scale-free means the distribution looks the same at all scales (self-similar under rescaling).
Moments: For :
- iff
- iff
For BA with : mean degree is finite, but variance diverges. This has profound implications:
- No effective epidemic threshold: diseases spread to the whole network for any transmission rate
- Robustness to random failure: removing random nodes rarely disconnects the graph (most nodes have low degree)
- Vulnerability to targeted attack: removing the few hubs disconnects the graph immediately
5.3 Mean-Field Analysis
Mean-field derivation: Let be the degree of node at time . Treating as a continuous variable and taking expectations:
Since (each new node adds edges, contributing to total degree sum):
Solution: With initial condition (node added at time with initial edges):
Degree distribution from mean-field: Node has degree at time iff , i.e., . Since nodes are added uniformly at rate 1 per step:
Therefore:
This reproduces the power law , consistent with the rigorous result.
Hub formation: The oldest nodes grow fastest (degree ). Node added at time has degree at time - a hub with degree.
5.4 Robustness and Fragility
Random failure: If each node is independently removed with probability , what is the critical above which the giant component disappears?
For a network with degree distribution , the critical fraction for percolation is determined by the Molloy-Reed criterion:
For scale-free networks with (including BA with ): , so this criterion always holds. No matter how many nodes are randomly removed, a giant component persists (in infinite networks). In finite BA networks, the giant component persists for close to 1.
Targeted attack: If the highest-degree nodes are removed first, the network is highly vulnerable. Removing even 5% of the highest-degree nodes can destroy the giant component of a BA network.
Implication for AI: Neural network pruning that removes random weights (random failure) is much safer than pruning by magnitude (targeted attack) - magnitude-based pruning could inadvertently target the "hubs" of the implicit neural network graph.
5.5 Scale-Free Networks in the Wild
Evidence for scale-free: Many networks show approximate power-law degree distributions:
- World Wide Web: ,
- Internet (AS-level):
- Protein-protein interaction:
- Actor collaboration:
Controversy (2019): Broido & Clauset (2019) argued that true power laws are rare - most claimed scale-free networks fit log-normal or other heavy-tailed distributions better. The debate continues, but the practical point stands: real networks have much heavier degree tails than ER Poisson.
GNN implications: Degree-heterogeneous graphs require careful normalization in GCN-style aggregation. GraphSAGE's neighborhood sampling provides approximate uniformity; PNA (Principal Neighbourhood Aggregation) uses multiple aggregators (mean, max, std) to handle degree heterogeneity robustly.
6. Stochastic Block Model
6.1 Definition and Parameters
The Stochastic Block Model (SBM) is the canonical random graph model for community structure. It is the workhorse of GNN benchmark generation and the model for which information-theoretic limits of community detection are fully understood.
Definition (SBM): Given parameters:
- : number of nodes
- : number of communities/blocks
- : community assignment vector
- : symmetric block probability matrix (B_{rs} = probability of edge between community and )
The SBM generates a random graph by independently including each edge with probability .
Symmetric SBM (planted partition): All communities have equal size ; (within-community) and for (between-community), with .
Sparse SBM: , with constants. This is the regime studied in information-theoretic limits.
Why SBM matters for AI: Node classification on real graphs (citation networks, social networks) essentially asks: given an observed graph with node features, recover the community labels . SBM provides the ground truth for studying when this is possible and what algorithms can achieve it.
6.2 Community Detection: Information-Theoretic Limits
Three regimes for symmetric 2-block SBM (, equal communities):
With , :
-
Exact recovery ( large enough): Recover exactly (up to global permutation) with high probability. Threshold: .
-
Weak recovery / detection: Identify communities better than chance (correlated with ground truth). Threshold (Kesten-Stigum): .
-
Impossible: Below the Kesten-Stigum threshold, no algorithm can do better than random guessing.
Kesten-Stigum threshold: The SNR condition can be rewritten as:
The left side is the signal-to-noise ratio: measures community signal, measures noise (average degree). When SNR , the noise overwhelms the signal.
Spectral interpretation: The second eigenvalue of the adjacency matrix satisfies . The spectral radius of the noise (Wigner semicircle) is . The signal eigenvalue emerges from the noise bulk iff , i.e., - slightly different from KS due to different normalization, but same qualitative conclusion.
For GNNs: GNNs trained on SBM graphs face exactly this detection problem. Below the Kesten-Stigum threshold, no GNN - regardless of depth, width, or architecture - can reliably classify nodes into communities. This is the hard limit on what graph learning can achieve.
-block SBM: For communities, the threshold generalizes. The second eigenvalue of determines the computational threshold.
6.3 Degree-Corrected SBM
Real-world networks have heterogeneous degree distributions within communities. The DC-SBM adds degree parameters:
Definition (DC-SBM): Node has a degree parameter . The probability of edge is:
Under DC-SBM, the expected degree of node is . Choosing for some power law generates a scale-free SBM combining community structure with hub-spoke topology.
Why DC-SBM matters: Citation networks and social networks have communities AND degree heterogeneity. Standard spectral clustering fails on DC-SBM because high-degree nodes dominate the leading eigenvectors. Regularized spectral clustering or normalized Laplacian-based methods are needed.
6.4 SBM as GNN Benchmark Generator
GraphWorld (2022): A Google framework that generates GNN benchmarks by sampling SBM parameters from a distribution over:
- Number of communities
- Community sizes (balanced or Zipf-distributed)
- Within-block density
- Between-block density
By sampling pairs across and below the Kesten-Stigum threshold, GraphWorld generates benchmarks that are systematically hard or easy for GNNs.
Result: Different GNN architectures excel in different SBM regimes:
- GCN: best for homophilic SBM (dense intra-community)
- GraphSAGE: robust across densities
- GIN: best near the Kesten-Stigum threshold (maximally expressive)
- MixHop: best for heterophilic SBM (dense inter-community)
This validates the theoretical prediction that no single GNN architecture dominates all graph types.
7. Spectral Properties of Random Graphs
7.1 Wigner's Semicircle Law
Wigner's semicircle law is a fundamental result in random matrix theory that describes the bulk eigenvalue distribution of random symmetric matrices.
Setup: Let where is a real symmetric random matrix with:
- Diagonal entries
- Off-diagonal entries i.i.d. with mean 0 and variance
Theorem (Wigner, 1955): The empirical spectral distribution of :
converges weakly in probability to the semicircle law:
Support: - all eigenvalues of lie in this interval asymptotically.
For : The adjacency matrix centered and scaled: has bulk eigenvalues following the semicircle law on (with ).
The outlier eigenvalue comes from the mean matrix - it pokes out of the bulk.
For SBM: The adjacency matrix of an SBM decomposes as where is the block-structured mean matrix (rank ) and is a Wigner-like noise matrix. The outlier eigenvalues of emerge from the semicircle bulk and encode the community structure, provided the signal-to-noise ratio exceeds the Kesten-Stigum threshold.
7.2 Spectral Gap and Community Detection
Spectral algorithm for SBM:
- Compute the leading eigenvectors of (or normalized Laplacian )
- Form the embedding matrix
- Run -means on rows of to recover community assignments
Why does this work? For the planted partition SBM with and :
- Leading eigenvalue: ... (using -block symmetric SBM)
- Second eigenvalue: (signal eigenvalue)
- Bulk edge:
Signal eigenvalue separates from bulk iff , which is exactly the Kesten-Stigum condition.
Davis-Kahan bound (next subsection): If signal and noise eigenvalues are separated, the eigenvectors of are close to those of , enabling accurate community recovery.
7.3 Davis-Kahan Theorem and Perturbation Bounds
Theorem (Davis-Kahan, 1970): Let where is symmetric with eigenvalue and eigenvector , and is a perturbation with . Let be the gap between and all other eigenvalues of . Then the corresponding eigenvector of satisfies:
Application to SBM: For the 2-block SBM:
- Signal gap:
- Noise: (Wigner semicircle radius)
- Angle error:
This is iff , i.e., the Kesten-Stigum condition holds. When it holds, the estimated eigenvector is close to the ground-truth community indicator vector, and -means succeeds.
For GNNs: Davis-Kahan explains why GNNs with spectral-style message passing (GCN) can do community detection above the threshold but fail below it. It also shows that adding node features (which contribute additional signal to ) can push GNNs above the threshold even when the graph structure alone is insufficient.
7.4 Laplacian Spectrum of G(n,p)
Normalized Laplacian: .
For with constant:
- Eigenvalues of lie in (always)
- always (corresponding to )
- For fixed: , - the bulk concentrates near 1
Algebraic connectivity (Fiedler value): (unnormalized Laplacian) is the Fiedler value, which controls:
- Convergence rate of random walks (mixing time )
- Robustness (edge connectivity )
- Cheeger constant approximation:
For with , : for the giant component.
8. Graphons: The Infinite-Size Limit
8.1 Dense Graph Sequences and the Cut Metric
As graph size , what is the "limit" of a sequence of dense graphs? This question leads to graphon theory - the measure-theoretic framework that unifies all dense random graph models.
Dense graph sequence: A sequence of graphs with and (constant edge density).
Cut distance: The cut norm between two symmetric functions is:
The cut metric between graphs and on the same vertex set is where is the step function encoding the adjacency of .
After quotienting by relabelings (graph isomorphisms), we get the cut distance .
8.2 Graphon Definition and Sampling
Definition (Graphon): A graphon is a symmetric measurable function .
Intuition: Think of as the "connection probability" between two abstract node types and , where node types are drawn uniformly from .
Graphon sampling: To sample an -node graph from graphon :
- Draw i.i.d. (latent node types)
- Include edge with probability , independently
Examples of graphons and their corresponding random graph models:
| Graphon | Corresponding model |
|---|---|
| (constant) | Erdos-Renyi |
| Half-graph | |
| -block SBM | |
| Product graphon (Chung-Lu style) | |
| Threshold model |
Lovasz-Szegedy theorem (2006): Every convergent sequence of dense graphs (in the cut metric) converges to a graphon. Conversely, every graphon arises as the limit of a graph sequence. The space of graphons with the cut metric is compact.
For AI: Graphons are the natural limiting objects for graph neural networks. A GNN maps graphs to outputs. If is continuous in the cut metric, then whenever in cut distance. This is precisely the condition for a GNN to be "robust" to graph size changes.
8.3 Homomorphism Densities and Graph Parameters
Homomorphism density: For graphs and , the homomorphism density is:
where counts graph homomorphisms .
Examples:
- = edge density
- = triangle density
- = 4-cycle density
Graphon version: For a graphon and graph with vertices:
Theorem (Lovasz-Szegedy): Two graphons and are equivalent (isomorphic in the graphon sense) iff for all graphs .
Graph parameters from homomorphism densities:
- Triangle density:
- Clustering coefficient: related to
For ML: Substructure counting (homomorphism density estimation) is a key primitive for graph feature extraction. Ring GNNs and structural GNNs compute approximate homomorphism densities; this is one way to understand what graph structure GNNs learn.
8.4 Graphon Neural Networks
Definition (Graphon Neural Network, Keriven & Peyre, 2019): A graphon neural network is a sequence of functions (on -node graphs) that converge to a limiting function on graphons. Formally, is a GNN architecture such that as in cut metric, .
Key result: GCN-style message passing with the propagation operator defines a graphon neural network. The discrete GCN is a finite approximation.
Universality of graphon NNs: Maron et al. (2019) show that equivariant graph networks are universal approximators on graphons - any graphon property that is measurable can be approximated to arbitrary accuracy.
Limitation: Universality on graphons is density-dependent. For SPARSE graph sequences (edge density ), graphons become trivial (the zero graphon), and a different limit theory (graphexes, local limits) is needed.
Forward reference: Graphon theory connects directly to functional analysis - the operator is an integral operator on . Spectral theory of compact operators (Hilbert-Schmidt theorem) governs its eigenvalue decomposition. -> Full treatment: Functional Analysis
9. Applications in Machine Learning
9.1 GraphWorld: Benchmark Generation from SBM
Problem: GNN papers often report results on 3-4 standard benchmarks (Cora, Citeseer, OGBN-Arxiv). These benchmarks may not represent the diversity of graph structures encountered in practice.
GraphWorld (Palowitch et al., 2022): A benchmark generation framework that:
- Parameterizes SBM space
- Samples thousands of graph instances across this parameter space
- Evaluates GNN architectures across the full parameter landscape
Key findings:
- No single GNN architecture dominates across all SBM parameters
- GCN is best on homophilic dense graphs; GIN is best near the detection threshold
- The Kesten-Stigum threshold accurately predicts when ALL GNNs fail
- Node feature quality (signal-to-noise ratio in features) often matters more than graph structure
For practitioners: When evaluating a GNN, generate benchmarks from an SBM sweep to characterize the algorithm's operating regime, rather than relying on a few fixed benchmarks.
9.2 Graph Generation: GRAN, GDSS, DiGress
Graph generation models learn to sample new graphs from a distribution. Framed probabilistically: learn a distribution that matches a target distribution .
GRAN (Graph Recurrent Attention Networks, 2019): Generates graphs node-by-node, at each step attending to previously generated nodes. The attention mechanism implicitly models preferential attachment - recently added high-degree nodes attract more attention, reproducing scale-free structure.
GDSS (Jo et al., 2022): Score-based diffusion model for graphs. Joint diffusion over node features and edge features. Samples new graphs by reversing a diffusion process that gradually adds noise. The score function implicitly learns the SBM-like block structure of training graphs.
DiGress (Vignac et al., 2022): Discrete diffusion - adds/removes edges following a Markov process. Denoising model is a graph transformer that learns to predict the original edge from the noised version. DiGress can generate molecular graphs and large social networks by learning implicit graphon structure.
Random graph theory connection: Graph generation is essentially graphon estimation. Given samples from (real graphs), estimate the underlying graphon such that sampling from approximates . The approximation quality is measured by the cut metric .
9.3 LLM Attention as a Random Graph Process
Attention graph: In a transformer with layers and heads, the attention pattern at layer , head defines a complete directed graph on tokens where edge weight is the attention score .
Sparse attention = random graph: Sparse attention mechanisms (Longformer, BigBird, Reformer) explicitly sparsify the attention graph, keeping only edges rather than . The sparsification pattern is often random or pseudo-random.
Random graph analysis of attention:
- Connectivity: Is the sparse attention graph connected? If not, information cannot flow between disconnected components. ER theory predicts connectivity iff expected degree .
- Small-world: BigBird combines local window attention (ring lattice) with random global tokens (rewiring) and special tokens (hubs). This exactly matches the Watts-Strogatz construction!
- Expander properties: Expander graphs (high spectral gap) are the best sparse graphs for information flow. Ramanujan graphs achieve the optimal spectral gap - this motivates expander-based sparse attention.
Result: The random graph structure of sparse attention patterns determines the theoretical expressiveness of the transformer. An attention graph that is disconnected or has large diameter cannot capture long-range dependencies regardless of the weight values.
9.4 Lottery Ticket Hypothesis and Sparse Subgraphs
Lottery Ticket Hypothesis (Frankle & Carlin, 2019): A randomly initialized dense network contains sparse subnetworks ("winning tickets") that, when trained in isolation from the same initialization, achieve comparable accuracy to the dense network.
Random graph framing: Think of the neural network as a random graph where:
- Nodes = neurons
- Edges = weights (including the weight value)
- Sparsification = edge removal
The winning ticket is a sparse subgraph that retains the connectivity and flow properties of the dense graph. Random graph percolation theory describes when sparse subgraphs retain giant component connectivity.
Percolation interpretation: If we randomly retain each edge with probability (magnitude-based pruning approximation), the network retains its giant component iff , where is the percolation threshold. For ER-like neural network graphs, where is the original edge density.
Practical implication: Networks can be pruned to 90%+ sparsity (i.e., ) while retaining performance, consistent with the existence of a giant percolating subgraph at such densities for typical neural network width/depth ratios.
9.5 Social Network Analysis at Scale
Community detection at scale: For billion-node graphs (Facebook, Twitter), exact SBM community detection is computationally infeasible. In practice:
- Louvain algorithm: Greedy modularity maximization,
- Label propagation: Message-passing on the graph, converges in steps
- GraphSAGE + semi-supervised: Use a few labeled nodes (community labels) to train GNN
Random graph models as null models: When analyzing a real social network, we ask: "Is the observed community structure more than what we'd expect by chance?" We compare to an ER null model with the same degree sequence (configuration model) and test whether the observed modularity exceeds the null expectation.
Link prediction: Predicting missing edges in a social graph using random graph models. Under ER: (same for all pairs). Under SBM: - within-community edges are more likely. GNNs for link prediction learn to approximate this block-structured probability.
10. Common Mistakes
| # | Mistake | Why It's Wrong | Fix |
|---|---|---|---|
| 1 | Confusing and | has random edge count; has exactly edges - they agree asymptotically but differ in finite samples | Use when you want independence; when you want exact count control |
| 2 | Assuming ER is a good null model for all real graphs | ER lacks clustering, hubs, and communities - major features of real networks | Use configuration model (fixed degree sequence) or SBM as null model |
| 3 | Saying Barabasi-Albert generates power law with any exponent | BA always gives ; only extensions (fitness, rewiring) change | Use generalized preferential attachment for |
| 4 | Confusing clustering coefficient with transitivity | Local CC averages over vertices; global transitivity = triangles / paths of length 2. They differ when degree distribution is heterogeneous | Use transitivity for global property; local CC for per-node property |
| 5 | Thinking the Kesten-Stigum threshold is a computational limit | KS is an information-theoretic limit - it bounds what ANY algorithm can do, not just efficient ones. The computational hardness (SDP vs AMP) is a separate question | Distinguish between information-theoretic and computational thresholds |
| 6 | Applying graphon theory to sparse graphs | Graphons describe the limit of DENSE sequences (constant edge density). Sparse graphs () have trivial graphon limits (the zero function) | Use local weak limits (Benjamini-Schramm) or graphex theory for sparse sequences |
| 7 | Equating "scale-free" with "power law" | Scale-free means the DEGREE distribution is a power law. Many other distributions (log-normal, Pareto) look similar. Broido & Clauset (2019) show many claimed scale-free networks don't pass rigorous power-law tests | Use maximum likelihood to fit and compare competing distributions (power law, log-normal, exponential) |
| 8 | Ignoring the giant component when computing path lengths | Average path length on a disconnected graph is undefined (infinite) or meaningless without restricting to the giant component | Always compute path lengths within the largest connected component |
| 9 | Assuming WS small-world is scale-free | WS generates Poisson-like degree distributions (each node rewires independently). It has small-world property but NOT scale-free | Combine WS with preferential attachment for small-world + scale-free |
| 10 | Using the adjacency matrix spectrum directly for SBM clustering when graph is sparse | For sparse SBM, the adjacency matrix eigenvalues don't separate cleanly (semicircle radius comparable to signal). Use regularized Laplacian or Bethe-Hessian instead | Replace with or Bethe-Hessian |
| 11 | Treating the WS model as a generative process for new nodes | WS is defined on a fixed set of nodes with rewiring - it does not define how to add new nodes. It's not a growing network model | Use BA for growing network models; use WS for fixed-size networks |
| 12 | Forgetting that graphon equivalence classes ignore node labels | Two graphons and are equivalent if one is a measure-preserving relabeling of the other. Most graph statistics depend only on the graphon equivalence class | Work with homomorphism densities (relabeling-invariant) when comparing graphons |
11. Exercises
Exercise 1 * - Phase Transition Simulation
Simulate the Erdos-Renyi phase transition computationally. For nodes and with :
(a) Generate for 20 values of linearly spaced in .
(b) For each graph, compute the size of the largest connected component and the second largest .
(c) Plot and as functions of . Identify the phase transition point visually.
(d) Overlay the theoretical prediction satisfying . Compute numerically (Newton's method or bisection) for each .
(e) Compute and plot . What happens to the second-largest component at criticality? Explain from branching process theory.
Exercise 2 * - Degree Distribution Analysis
(a) Generate with and . Compute the empirical degree distribution and overlay the theoretical PMF.
(b) Generate a BA graph with and . Compute the empirical degree distribution on a log-log scale and fit a power law using linear regression on the tail (). Report the estimated exponent .
(c) Compare the two distributions using a Q-Q plot. What are the key structural differences?
(d) Compute the maximum degree in each model. Derive theoretically why for ER and for BA.
Exercise 3 * - Small-World Analysis
Implement the Watts-Strogatz model from scratch.
(a) Build the ring lattice: nodes, each connected to nearest neighbors.
(b) For , rewire each edge independently with probability . Compute and for each value.
(c) Plot normalized clustering coefficient and normalized average path length on the same plot (both on log scale for ). Identify the small-world regime.
(d) Verify that for small . What does this formula say about how clustering degrades with rewiring?
Exercise 4 ** - Stochastic Block Model and Community Detection
(a) Sample an SBM with , equal communities, , . Use (above Kesten-Stigum threshold).
(b) Apply spectral clustering: compute the second eigenvector of the adjacency matrix, threshold at 0 (positive = community 1, negative = community 2), and compute accuracy (fraction of correctly classified nodes, up to community permutation).
(c) Repeat with (near threshold) and (below threshold). How does accuracy vary?
(d) The Kesten-Stigum threshold for 2-block SBM is . Verify your experimental results are consistent with this threshold.
(e) *** Implement the belief propagation algorithm (AMP / approximate message passing) for the 2-block SBM and compare accuracy to spectral clustering near the threshold.
Exercise 5 ** - Wigner's Semicircle Law
(a) Generate a Wigner matrix where has i.i.d. entries, for .
(b) Plot the empirical spectral distribution (histogram of eigenvalues) for each . Overlay the theoretical semicircle density for .
(c) Now set where is the centered adjacency matrix of with , . Plot the empirical spectral distribution. Identify the outlier eigenvalue corresponding to the average degree.
(d) For the SBM with 2 communities (, , ): plot the eigenvalue spectrum of . Identify which eigenvalues encode community structure and which are bulk noise.
Exercise 6 ** - Graphon Estimation
(a) Generate a sequence of SBM graphs with , communities, and block matrix .
(b) For each graph, sort vertices by community label (oracle information) and display the sorted adjacency matrix as a heatmap. Does it converge to the block graphon as grows?
(c) Without oracle labels: apply spectral clustering to estimate community labels, then display the sorted (estimated) adjacency matrix. Measure the cut distance between the estimated and true graphon.
(d) Implement the "histogram graphon estimator": divide into bins and estimate by averaging edges within each bin. Compute the error .
Exercise 7 *** - Giant Component Critical Window
This exercise studies the fine-grained behavior near the critical point .
(a) For with and , compute for 50 trials each. Plot the distribution of vs .
(b) Observe that the distribution has a universal shape (independent of for large ). This is the Brownian excursion limit - the critical window scaling is for the component size and for the window width.
(c) Compute the mean and standard deviation of as functions of . Show that the mean crosses 0 near but the transition is smooth (not a jump) at finite .
(d) Compare to the predicted infinite- limit: for , for some constant . Verify this scaling.
Exercise 8 *** - Preferential Attachment Dynamics
(a) Implement the Barabasi-Albert preferential attachment model for nodes with edges per new node. Use the efficient alias method or linear scan for sampling.
(b) After generation, fit the degree distribution tail to a power law using maximum likelihood estimation on for suitable .
(c) Track the degree of each node over time as the network grows. Plot for nodes added at times . Verify the mean-field prediction .
(d) Implement "fitness-based" preferential attachment: where is a fixed fitness. Compare the resulting degree distribution to standard BA. Does the power-law exponent change?
(e) Simulate a targeted attack: iteratively remove the highest-degree node. Plot the size of the giant component as a function of fraction of nodes removed. Compare to random removal. What fraction of nodes must be targeted to destroy the giant component?
12. Why This Matters for AI (2026 Perspective)
| Concept | Impact on AI/ML |
|---|---|
| ER Phase Transition | Connectivity threshold determines information flow in GNNs on sparse graphs; GCN cannot aggregate across disconnected components, giving a hard limit on performance |
| Poisson Degree Distribution | Most GNN benchmark graphs (Cora, Citeseer) have near-Poisson degrees; GCN's symmetric normalization is optimal for Poisson-degree graphs but suboptimal for scale-free |
| Kesten-Stigum Threshold | Hard information-theoretic limit on community detection; no GNN can exceed this on SBM data regardless of architecture, depth, or width |
| Scale-Free Networks | Real knowledge graphs (Wikidata, Freebase) are scale-free; hub nodes with degree dominate GCN aggregation - require degree-aware normalization or degree-bucketing |
| Small-World Structure | Transformer attention graphs have small-world properties; BigBird/Longformer mimic WS construction (local window + random long-range); designing optimal sparse attention = finding optimal WS parameters |
| Graphons | Theoretical foundation for GNN universality; GNNs that are continuous in cut metric topology can generalize across graph sizes; graphon theory predicts which graph properties a GNN can and cannot learn |
| Graphon Neural Networks | First provably universal GNN framework; used to prove that message-passing GNNs cannot distinguish non-isomorphic graphs with identical WL certificates |
| Spectral Gap | Controls convergence rate of GNN over-smoothing (energy decays at rate ); higher Fiedler value -> faster smoothing -> shallower optimal depth |
| Davis-Kahan | Explains why spectral GNNs (GCN) succeed above community detection threshold and fail below; same theorem underlies learning theory for graph classification |
| Wigner Semicircle | Bulk eigenvalue distribution of noise in graph learning; signal from community structure must exceed semicircle radius to be learnable - same condition as Kesten-Stigum |
| Configuration Model | Null model for testing GNN hypotheses: does the GNN learn graph structure, or just degree sequence? Test by evaluating on configuration model graphs with same degree sequence |
| Random Graph Generation | DiGress, GDSS, GRAN all learn distributions over graphs - effectively learning graphons. Quality measured by cut distance between learned and true graphon |
13. Conceptual Bridge
Backward: What This Builds On
Random graph theory synthesizes several branches of mathematics developed in earlier sections:
From Spectral Graph Theory (04): The Laplacian eigenvalues studied there take on probabilistic meaning here - for random graphs, they become random variables following the Wigner semicircle law. The spectral gap that controls mixing time in deterministic graphs now becomes a random quantity whose distribution determines community detectability.
From Probability Theory (07-Probability-Statistics): All threshold results (giant component, connectivity, community detection) use first and second moment methods, Chernoff bounds, and the Poisson limit theorem. Branching process theory is the probabilistic tool that gives the exact threshold equation .
From Graph Neural Networks (05): The SBM community detection problem IS the node classification problem that GNNs solve in practice. The Kesten-Stigum threshold gives the hard limit on what any GNN can achieve, while Davis-Kahan shows why spectral GNNs succeed above this threshold.
Forward: What This Enables
Functional Analysis (12): The graphon operator is a Hilbert-Schmidt operator on . Its spectral theory - the Hilbert-Schmidt theorem giving a countable orthonormal eigenfunction expansion - is the infinite-dimensional generalization of the adjacency matrix eigendecomposition. This is the full treatment of graphon operators.
Graph Algorithms (07): Random graph models motivate efficient algorithms: spectral clustering (from SBM theory), Louvain community detection (from modularity theory), and link prediction (from random graph null models). The average-case complexity of graph problems is analyzed using random graph models.
Information Theory (09): The Kesten-Stigum threshold is an information-theoretic limit - it follows from a channel capacity argument. The mutual information between the community labels and the observed graph is zero below the threshold, making recovery impossible regardless of computation. This connects random graphs to channel coding theory.
POSITION IN CURRICULUM
========================================================================
04 Spectral Graph Theory
| Laplacians, eigenvalues, Cheeger inequality
|
+--> 05 Graph Neural Networks
| GCN, GAT, GIN, MPNN, expressiveness
|
+--> 06 Random Graphs <=== YOU ARE HERE
|
+- Erdos-Renyi: phase transitions, thresholds
+- Watts-Strogatz: small-world, navigation
+- Barabasi-Albert: scale-free, preferential attachment
+- SBM: communities, Kesten-Stigum threshold
+- Spectral theory: semicircle law, Davis-Kahan
+- Graphons: infinite limits, universality
|
v
07 Graph Algorithms
|
v
12 Functional Analysis <-- graphon operators T_W
Hilbert-Schmidt theory, L^2 spectral decomposition
========================================================================
The central insight of this section - that random graph models are not merely toy examples but rigorous frameworks for understanding real network behavior - carries forward into every domain where graphs appear. In machine learning, understanding when community structure is detectable, when information can flow across a sparse graph, and when a graph distribution can be learned from samples are fundamental questions with precise mathematical answers, and those answers come from random graph theory.
<- Back to Graph Theory | Next: Graph Algorithms ->
Appendix A: Branching Process Theory
A.1 Galton-Watson Branching Processes
A Galton-Watson process is a model of population growth where each individual independently produces offspring according to a fixed offspring distribution .
Formal definition: Let (a single ancestor). At generation , if , each of the individuals produces offspring independently according to :
where i.i.d.
Mean offspring: .
Probability generating function (PGF): .
Extinction probability: The probability of ultimate extinction satisfies .
Theorem (Extinction):
- If : (certain extinction)
- If : (positive survival probability )
Connection to ER: For with , exploring the component of a vertex proceeds like a branching process where each node has offspring (unexplored neighbors). The giant component probability satisfies:
exactly the fixed-point equation .
A.2 Multi-Type Branching Processes
For the SBM with communities, the local neighborhood exploration is a multi-type branching process where the type of an individual is its community label.
Offspring matrix: = expected number of type- offspring from a type- parent.
For the symmetric 2-block SBM with , :
Survival theorem: The multi-type branching process survives iff , where is the spectral radius.
Eigenvalues of : , .
- Giant component exists iff , i.e., (average degree condition).
- Community detection possible iff the "community eigenvalue" ... but this is not quite right. The actual condition involves the non-backtracking matrix.
Non-backtracking operator: The correct spectral condition for SBM community detection uses the non-backtracking (Hashimoto) operator on directed edges. The eigenvalue of corresponding to community structure is , and the bulk spectral radius is . Community detection is possible iff:
i.e., - precisely the Kesten-Stigum threshold.
A.3 Critical Branching Processes
At criticality (Poisson offspring with ), the branching process has a different behavior:
Yaglom's theorem: Conditioned on survival to generation , the population converges in distribution to an Exponential(1) random variable:
For the ER critical window: At , the largest component has size and there are such components. The component size distribution follows Yaglom's theorem for the critical Poisson branching process, but rescaled by .
Appendix B: Configuration Model
B.1 Definition
The configuration model generates a random graph with a prescribed degree sequence .
Construction:
- Give vertex exactly "half-edges" (stubs)
- Pair up all half-edges uniformly at random
- Each pairing creates an edge
Result: A random multigraph (may have self-loops and multi-edges) with the given degree sequence.
Properties:
- For degree sequences with bounded maximum degree: the number of self-loops and multi-edges is - a simple graph w.h.p.
- Conditioned on simplicity: uniform over all simple graphs with the given degree sequence
Why use it? The configuration model is the correct null model for testing graph hypotheses. Instead of comparing to ER (wrong degree distribution), compare to configuration model (same degree distribution, no other structure). If a property (e.g., high clustering) exceeds what configuration model predicts, it's genuinely structural, not just a degree artifact.
B.2 Giant Component in Configuration Model
For the configuration model with degree distribution :
Molloy-Reed criterion: A giant component exists iff:
Interpretation: The excess degree distribution governs the branching factor of the exploration process. The process is supercritical (giant component exists) iff the mean of exceeds 1, which is .
For scale-free networks: With , diverges when . Hence the Molloy-Reed criterion is always satisfied for BA-style scale-free networks - a giant component exists for arbitrarily sparse scale-free graphs.
For ER: (Poisson), so and . Molloy-Reed: - exactly the ER threshold.
B.3 Clustering in Configuration Model
For the configuration model:
as (for fixed degree distribution). The configuration model has vanishing clustering coefficient - it's locally tree-like.
Real networks vs. configuration model: Comparing observed clustering to tests for genuine clustering beyond degree effects. Small-world networks have - they have clustering not explained by degree distribution alone.
Appendix C: Percolation Theory
C.1 Bond Percolation on Graphs
Bond percolation: Given a graph and probability , independently retain each edge with probability . Let denote the resulting random subgraph.
Site percolation: Independently retain each vertex with probability .
Critical probability: The percolation threshold is the infimum of for which has an infinite component (on infinite graphs) or a giant component of size (on finite graphs).
On the integer lattice : Exact thresholds:
- : (must keep all edges)
- (square lattice): exactly (by self-duality)
- : ; harder to compute exactly
On ER graphs: Bond percolation on with retention probability gives . The percolation threshold is , so the giant component survives iff , i.e., .
C.2 Connection to Neural Network Pruning
Neural network weight pruning is isomorphic to bond percolation:
- Dense network graph (neurons = nodes, weights = edges)
- Pruning mask with (retention probability)
- Pruned network must retain computational connectivity
For the network to maintain its computational capacity, it must retain a giant component. The percolation threshold gives the minimum retention rate.
Structured pruning: Head pruning in transformers (removing entire attention heads) is site percolation on the attention head graph. Magnitude pruning selects edges by weight magnitude - approximately bond percolation with fraction of weights retained.
Lottery ticket connection: A winning lottery ticket is precisely a giant percolating subgraph that retains the "signal paths" of the original network. The existence of such subgraphs at high sparsity () is guaranteed by percolation theory for sufficiently wide networks.
C.3 Expanders and Optimal Percolation
Expander graph: A -regular graph on nodes with spectral gap . Large spectral gap means fast mixing and high robustness.
Percolation on expanders: For a -regular expander, the percolation threshold is for bounded-degree expanders. The giant component after percolation at has size for small .
Implication for sparse attention: Expander-based sparse attention (using Ramanujan graphs with spectral gap ) achieves:
- edges (efficient)
- diameter (short paths)
- Maximum spectral gap (optimal information flow)
- Robust to random edge removal (good percolation threshold)
This is why expanders are theoretically optimal sparse attention patterns, even if not used in practice due to implementation complexity.
Appendix D: Threshold Functions - Complete Table
| Property | Threshold | Window width | Notes |
|---|---|---|---|
| Contains an edge | First property to appear | ||
| Contains a triangle | threshold | ||
| Contains | |||
| Contains | |||
| Giant component | Phase transition | ||
| Connectivity | (sharp!) | Very sharp threshold | |
| Diameter | |||
| Contains Hamiltonian cycle | Same as connectivity! | ||
| Planarity loss | Planarity threshold | ||
| Chromatic number | Problem-dependent | Varies | Open for exact |
Sharp vs. coarse thresholds:
A threshold is sharp if the transition from probability 0 to probability 1 occurs in a window of width . Connectivity and Hamiltonian cycles have sharp thresholds (window width ).
A threshold is coarse if the window is . Most subgraph appearance thresholds are coarse - the probability transitions from to over a multiplicative constant change in .
Friedgut's theorem (1999): Every monotone property has a sharp threshold OR can be reduced to a "small" property. Most natural properties (connectivity, -colorability) have sharp thresholds. This is the technical statement of the Bollobas-Thomason heuristic.
Appendix E: Random Geometric Graphs
E.1 Definition
A random geometric graph is constructed by:
- Placing nodes uniformly at random in (or another metric space)
- Connecting two nodes iff their Euclidean distance is
Properties:
- Soft threshold for connectivity: - same scaling as ER
- High clustering: Nodes close to each other share many common neighbors (geometric constraint) - as with fixed
- Bounded degree distribution: All degrees in
- No long-range edges: Maximum edge length , giving large diameter for small
For AI: Random geometric graphs model sensor networks, robotic swarms, and spatial point processes. They also model attention in vision transformers where tokens correspond to image patches at geometric positions - nearby patches should have high attention, distant patches low.
E.2 Comparison to Other Models
| Property | ER | WS | BA | Geometric |
|---|---|---|---|---|
| Degree dist. | Poisson | Poisson-like | Power law | Bounded |
| Clustering | Low | High | Low | Very high |
| Path length | ||||
| Spatial | No | No | No | Yes |
| Community struct. | None | None | None | Implicit (spatial) |
E.3 Connection to Kernel Methods
The random geometric graph adjacency matrix is a kernel matrix:
with kernel (indicator kernel).
More generally, kernel random graphs use for a kernel function . This is a graphon with for node types .
For attention: The softmax attention matrix is a random kernel matrix where the "positions" are query/key vectors. Random graph theory for kernel random graphs directly applies to study information flow in attention layers.
Appendix F: Network Motifs and Subgraph Statistics
F.1 Network Motifs
Definition: A network motif is a subgraph pattern that occurs significantly more often in a real network than in random graphs with the same degree sequence (configuration model null).
Common motifs:
- Feedforward loop (3-node DAG): overrepresented in gene regulatory networks
- Bifan (2->2->2 bipartite): common in neural circuits
- Clique (, ): overrepresented in social networks
Detection: For each candidate subgraph , compare (density in real graph) to (expected density under null model). Z-score : motif. Z-score : anti-motif.
For GNNs: Motif counting is a proxy for what GNNs learn. Standard MPNNs (GCN, GraphSAGE) can count triangles but not 4-cycles. Higher-order GNNs (OSAN, subgraph GNNs) can count richer motif sets. The motif profile of a graph determines which GNN architecture is most suitable.
F.2 Triangle Counting at Scale
Exact triangle count: For dense graphs, using matrix multiplication in (matrix multiplication exponent). For sparse graphs (), algorithms run in .
Approximate counting: For massive graphs (), use streaming algorithms or random sampling:
- Wedge sampling: Count triangles by sampling paths of length 2 and checking closure
- DOULION: Sample edges independently with probability ; count triangles in subgraph; scale by
Expected triangle count in : .
Concentration: For , by Azuma-Hoeffding (Lipschitz condition), concentrates around its mean with standard deviation .
Appendix G: Information-Theoretic Limits
G.1 Mutual Information and Detection
The detection problem: Given , recover (up to global flip).
Impossible regime: Below the Kesten-Stigum threshold, the mutual information in the limit. This means the graph contains literally no information about the community labels that could be extracted by any algorithm.
Formal statement: For , , :
The normalization is because both and grow with ; the mutual information per node goes to 0.
Above threshold: For :
where is the Bayes-optimal overlap and is binary entropy.
G.2 Exact Recovery Threshold
For the exact recovery problem (recover exactly, not just correlate with it), the threshold is higher:
Theorem (Abbe-Sandon, 2015): For the 2-block SBM with , :
This is the CHI-squared divergence condition between the Poisson distributions with means and .
The three thresholds:
- Impossible: - no algorithm can detect communities
- Weak recovery: - algorithms exist to partially recover
- Exact recovery: - algorithms exist for exact recovery
These thresholds become relevant for GNN practitioners when designing tasks: is the community detection problem in your benchmark achievable at all? Which threshold regime does it fall in?
Appendix H: Practical Algorithms
H.1 Spectral Clustering Pipeline for SBM
INPUT: Adjacency matrix A of SBM graph with k communities
OUTPUT: Community assignments \sigma
1. REGULARIZE: Compute A_reg = A + \tau/n * 11^T (small ridge)
(Prevents leading eigenvector being dominated by high-degree nodes)
2. NORMALIZE: Compute L_sym = D^{-1/2} A_reg D^{-1/2}
3. EIGENVECTORS: Compute top k eigenvectors U \in R^{n\timesk} of L_sym
4. NORMALIZE ROWS: Let U_row = U / ||u_i||_2 (spherical projection)
5. k-MEANS: Run k-means on rows of U_row, get cluster labels \sigma
6. RETURN: \sigma (up to global permutation)
COMPLEXITY: O(n*k/\epsilon^2) for sparse graphs (k power iterations)
ACCURACY: Achieves min error rate above Kesten-Stigum threshold
H.2 Louvain Community Detection
The Louvain algorithm maximizes modularity , a measure of community quality:
Phase 1 (local optimization): For each node , move to the neighboring community that maximizes . Repeat until no improvement.
Phase 2 (aggregation): Collapse each community into a supernode. Edge weights between supernodes = total edges between original communities. Apply Phase 1 to the collapsed graph.
Repeat until no further improvement.
Complexity: empirically - the fastest practical community detection algorithm.
Limitation: Modularity has a resolution limit: communities smaller than edges may not be detected. For fine-grained community structure, use alternatives (Infomap, hierarchical spectral methods).
H.3 Fast Giant Component Detection
def giant_component_fraction(A, n):
"""Compute giant component size via BFS."""
visited = [False] * n
max_component = 0
for start in range(n):
if visited[start]:
continue
# BFS from start
queue = [start]
visited[start] = True
component_size = 0
while queue:
v = queue.pop(0)
component_size += 1
for u in range(n):
if A[v][u] and not visited[u]:
visited[u] = True
queue.append(u)
max_component = max(max_component, component_size)
return max_component / n
For sparse adjacency lists (CSR format), BFS runs in - linear in the graph size.
End of 06 Random Graphs notes.
Appendix I: Advanced Topics in Random Graphs
I.1 Local Weak Convergence (Benjamini-Schramm)
For sparse graph sequences where edge density , graphon theory breaks down. The correct limit theory uses local weak convergence.
Definition (Benjamini-Schramm limit): A sequence of graphs converges in the local weak sense to a random rooted graph if for every rooted graph and every :
where is the ball of radius around in .
For : The local weak limit is the Galton-Watson tree with Poisson() offspring distribution - an infinite random tree. This confirms the "locally tree-like" structure of sparse ER graphs.
For BA networks: The local weak limit involves correlated degree distributions due to preferential attachment - the limiting tree is not a Galton-Watson tree but a Polya urn tree.
For SBM: The local weak limit is a multi-type Galton-Watson tree where the types are community labels. This is the probabilistic foundation of the belief propagation algorithm for community detection.
I.2 Random Regular Graphs
Definition: A -regular random graph on vertices is a graph chosen uniformly at random among all -regular simple graphs on vertices.
Construction (configuration model): Give each vertex stubs, pair uniformly at random, condition on simplicity.
Spectral properties: For -regular random graphs, the eigenvalues are in w.h.p. The Alon-Boppana bound says for any -regular graph. A Ramanujan graph achieves equality: .
Alon conjecture (proved by Friedman, 2008): Almost all -regular random graphs are Ramanujan:
for any fixed .
For AI: Expanders (near-Ramanujan regular graphs) provide the optimal sparse attention pattern:
- edges per node (linear total edges)
- Diameter (short paths)
- Spectral gap (fast mixing)
I.3 Random Hypergraphs
Real-world networks often have higher-order interactions - a chemistry reaction involves multiple molecules simultaneously. Hypergraphs capture this.
Definition: A hypergraph where edges can contain any number of vertices.
Random -uniform hypergraph : Each -subset of is an edge independently with probability .
Phase transition: The giant component threshold for occurs at (average degree 1). The analysis uses a multi-type branching process.
For AI: Simplicial complex neural networks (SCNNs) and topological data analysis (TDA) use higher-order graph structure. Random simplicial complexes (random clique complexes of ER graphs) model the topological structure of neural network activation spaces.
I.4 Dynamic Random Graphs
Real networks evolve over time. Several models capture network dynamics:
Forest Fire model (Leskovec et al., 2007): A new node contacts a random "ambassador" and copies some of its links. Exhibits densification (average degree increases over time) and shrinking diameter - both observed in real growing networks.
Copying model: Each new node copies existing edges from a random source node. This generates power-law degree distributions similar to BA but with different exponent depending on copy probability.
Edge dynamics: Instead of just adding edges, allow edge rewiring, deletion, and creation. Models temporal networks (who talked to whom at time ). The temporal analog of clustering coefficient and path length requires time-respecting paths.
For AI: Training data graphs (social networks, citation graphs) evolve over time. Distribution shift in graph ML often comes from temporal evolution of the underlying random graph model. A GNN trained on a 2019 citation graph may fail on a 2024 citation graph if the graph generative process has changed.
Appendix J: Mathematical Proofs
J.1 Proof: Giant Component Threshold (Upper Bound)
We prove: for , all components have size w.h.p.
Proof: Let = number of connected components of size exactly in with .
The probability that a specific set of vertices forms a component involves:
- The internal graph on being connected: probability
- No edges from to : probability
By union bound:
using Cayley's formula ( labeled trees on vertices, each connected tree is a spanning tree of its component).
For and :
(using Stirling: , )
For : (since has , , - it's a maximum at ). Let .
Summing over :
By Markov's inequality, the total number of vertices in components of size is , so the maximum component size is .
J.2 Proof: Poisson Degree Distribution
Claim: For with , .
Proof via PGF: The degree where i.i.d.
PGF of :
Taking :
which is the PGF of .
Since PGF convergence (for ) implies distributional convergence (by continuity theorem for generating functions), .
Multivariate extension: For distinct vertices , their degrees are jointly Poisson in the limit, with joint PGF:
where for all . But the joint distribution is NOT independent Poisson (edges between and contribute to both and ). For fixed , the correlation between degrees of and is , so they are asymptotically independent.
J.3 Proof sketch: Davis-Kahan Theorem
Simplified version: Let where has eigenvalue and unit eigenvector . Let be the unit eigenvector of corresponding to eigenvalue nearest to . Let (gap to other eigenvalues).
Claim: (assuming ).
Proof: Decompose where , , and .
From : .
Project onto : .
All eigenvalues of are at distance from (which is close to ):
Therefore:
This gives the Davis-Kahan bound.
Appendix K: Notation Reference
| Symbol | Meaning | First appears |
|---|---|---|
| Erdos-Renyi random graph, vertices, edge prob | 3.1 | |
| ER graph with exactly edges | 3.1 | |
| Size of largest connected component | 3.3 | |
| Giant component fraction, | 3.3 | |
| Local clustering coefficient of vertex | 4.2 | |
| Average path length | 4.3 | |
| Preferential attachment probability of vertex | 5.1 | |
| Stochastic Block Model | 6.1 | |
| SBM block probability matrix | 6.1 | |
| Community assignment | 6.1 | |
| Spectral radius of matrix | App. A.2 | |
| Wigner semicircle measure | 7.1 | |
| Cut metric between graphs and | 8.1 | |
| Graphon | 8.2 | |
| Homomorphism density of in | 8.3 | |
| Graphon integral operator, | 8.4 | |
| With high probability (probability ) | 2.2 | |
| Asymptotic notation | 2.2 | |
| Large deviation function for ER | 3.3 | |
| Probability generating function | App. A.1 | |
| Excess degree distribution | App. B.2 |
<- Back to Graph Theory | Next: Graph Algorithms ->
Appendix L: Worked Examples
L.1 Computing the Giant Component Fraction
Problem: For with , find the theoretical fraction of vertices in the giant component.
Solution: We need satisfying .
Define . We need .
- (trivial solution - subcritical regime would have this as the only root)
- ; (slope at 0 is positive)
- is concave for , so there is one non-trivial root
Newton's method: Starting from :
- (overshoot, try smaller)
Using bisection between 0.7 and 0.95:
So - about 89.2% of vertices are in the giant component.
Interpretation: At average degree 2.5, the network is well into the supercritical regime. The vast majority of vertices are connected in one giant component, leaving only about 10.8% in small satellite components.
L.2 Kesten-Stigum Threshold Calculation
Problem: For the 2-block SBM with and , determine: (a) Is community detection possible? (b) Can we achieve exact recovery?
Solution:
(a) Detection (weak recovery): Kesten-Stigum threshold:
OK - Detection is possible.
SNR .
(b) Exact recovery: Need (scaled threshold for logarithmic degree regime).
, .
OK - Exact recovery is achievable.
Interpretation: With and , we have a relatively easy community detection problem - both detection and exact recovery are achievable. Spectral clustering should work well here.
L.3 Small-World Parameter Calculation
Problem: Design a WS graph on nodes that approximates the C. elegans neural connectome: , , .
Solution:
Step 1: Initial ring lattice has .
Step 2: Target clustering . Using :
Step 3: Verify path length at . Using the WS approximation where for large :
This is too small - the approximation breaks down at large . Numerically, for , , which is reasonably close to the target .
Conclusion: WS parameters produce a graph close to C. elegans in both clustering and path length, validating the small-world model.
L.4 Graphon Estimation from Data
Problem: Given a graph with 100 nodes known to be sampled from a 3-block SBM, estimate the graphon.
Procedure:
-
Run spectral clustering with to get estimated community labels .
-
Sort vertices by : reorder adjacency matrix so community 1 nodes come first, then community 2, then community 3.
-
Estimate block probabilities: For communities :
- Construct step-function graphon:
(piecewise constant on divided into blocks)
- Evaluate quality: Compute cut distance where is the true graphon. The cut distance converges to 0 as .
Error bound: For a -block SBM, the best graphon estimator achieves error in cut distance (minimax optimal). With and , expected cut distance - substantial estimation uncertainty.
Appendix M: Connections to Statistical Physics
M.1 Random Graphs and Spin Glasses
The Stochastic Block Model community detection problem is isomorphic to the ferromagnetic Ising model on the graph:
- Community labels correspond to spin states
- Edges within communities are "ferromagnetic" (prefer aligned spins)
- Edges between communities are "antiferromagnetic" (prefer anti-aligned)
The Kesten-Stigum threshold corresponds to the Nishimori temperature in the disordered Ising model - the temperature at which the magnetization (overlap with ground truth) first becomes nonzero.
Belief propagation = Cavity method: The belief propagation algorithm for community detection in SBM is the Bethe approximation applied to the Ising model. Near the KS threshold, BP is asymptotically optimal - no polynomial-time algorithm can do better.
M.2 Percolation and Statistical Mechanics
Bond percolation on is a model in statistical mechanics. Its critical phenomena:
- Order parameter:
- Critical exponent: with (exact, 2D)
- Correlation length: with (exact, 2D)
For ER graphs: with critical exponent 1 (mean-field universality class, since ER has "infinite dimension").
Conformal invariance (2D percolation): Near criticality, 2D percolation is conformally invariant - the scaling limit is described by SLE (Schramm-Loewner Evolution). This deep connection between combinatorics and complex analysis has no direct ML application yet, but illustrates the richness of the field.
M.3 Free Energy and the Replica Method
The replica method is a non-rigorous but powerful physics technique for computing expectations over random graphs.
For the SBM community detection problem, the free energy (log-partition function) per vertex is:
where and is the log-likelihood of the community assignment.
The replica calculation predicts the exact phase diagram of the SBM - both the KS threshold and the exact recovery threshold - and was later made rigorous using interpolation methods (Guerra, Talagrand).
ML connection: Free energy calculations in statistical physics are the rigorous foundation of variational inference in machine learning. The Bethe free energy (used in belief propagation) is the physics analog of the ELBO (evidence lower bound) in variational autoencoders.
End of 06-Random-Graphs notes.
Appendix N: Extended Exercise Solutions
N.1 Solution Notes for Exercise 1 (Phase Transition)
Key implementation details:
The fixed-point equation can be solved numerically via Newton's method:
Starting from (one step of Picard iteration), Newton's method converges in 5-10 iterations for .
For : the only fixed point is (return 0). For : there are two fixed points (0 and the positive root); return the positive root.
Expected results table:
| Theoretical | Simulated (variance) | |
|---|---|---|
| 0.5 | 0 | |
| 0.8 | 0 | |
| 1.0 | 0 (but scaling) | |
| 1.5 | 0.583 | |
| 2.0 | 0.797 | |
| 2.5 | 0.892 | |
| 3.0 | 0.940 |
Why peaks at criticality: The second-largest component size peaks at (size ) because this is where the giant component is just forming - there are many large components competing. For , the giant component absorbs everything, leaving only satellites.
N.2 Solution Notes for Exercise 4 (Community Detection)
Spectral algorithm implementation:
def spectral_community_detection(A, k=2):
"""Spectral clustering for SBM community detection."""
n = A.shape[0]
# Compute degree matrix and normalized Laplacian
d = A.sum(axis=1)
D_inv_sqrt = np.diag(1.0 / np.sqrt(d + 1e-10))
L_sym = np.eye(n) - D_inv_sqrt @ A @ D_inv_sqrt
# Eigendecomposition (smallest eigenvalues = community structure)
eigvals, eigvecs = np.linalg.eigh(L_sym)
# Second eigenvector (first non-trivial)
u2 = eigvecs[:, 1]
# Threshold at 0
labels = (u2 > 0).astype(int)
return labels
def community_accuracy(labels_est, labels_true):
"""Fraction correct, up to global flip."""
acc1 = np.mean(labels_est == labels_true)
acc2 = np.mean(labels_est == (1 - labels_true))
return max(acc1, acc2)
Expected accuracy table:
| SNR = | Regime | Expected accuracy | |
|---|---|---|---|
| Well above KS | 0.95-0.99 | ||
| Below KS | (random) | ||
| Below KS | (random) | ||
| Just above KS | 0.55-0.65 |
N.3 Solution Notes for Exercise 8 (Preferential Attachment)
Efficient alias sampling for preferential attachment:
The naive approach (linear scan to sample proportional to degree) is per edge, giving total. For large , use the alias method:
- Maintain a list of pairs for all existing nodes
- Use the alias method to sample from this distribution in per sample
- After adding new edges, update the alias table in per step
Alternatively, use the Vose-Walker alias method which supports updates efficiently.
Simpler approach: Maintain a binary indexed tree (Fenwick tree) over cumulative degrees. Sampling is per edge, updating is per edge, giving total.
Power law fit: Maximum likelihood estimator for power-law exponent on data with :
For BA with and : expect for .
Appendix O: Further Reading
O.1 Textbooks
-
Bollobas, B. (2001). Random Graphs (2nd ed.). Cambridge University Press.
- The definitive mathematical treatment; covers ER theory exhaustively.
-
Janson, S., Luczak, T., Rucinski, A. (2000). Random Graphs. Wiley.
- More accessible than Bollobas; covers first and second moment methods thoroughly.
-
Lovasz, L. (2012). Large Networks and Graph Limits. AMS.
- The definitive treatment of graphon theory by its creator.
-
Durrett, R. (2007). Random Graph Dynamics. Cambridge University Press.
- Dynamical random graphs and their applications to epidemics and social networks.
O.2 Foundational Papers
-
Erdos, P., Renyi, A. (1960). On the evolution of random graphs. Magyar Tud. Akad. Mat. Kutato Int. Kozl., 5, 17-61.
-
Watts, D.J., Strogatz, S.H. (1998). Collective dynamics of 'small-world' networks. Nature, 393, 440-442.
-
Barabasi, A.-L., Albert, R. (1999). Emergence of scaling in random networks. Science, 286, 509-512.
-
Lovasz, L., Szegedy, B. (2006). Limits of dense graph sequences. J. Combin. Theory Ser. B, 96, 933-957.
-
Mossel, E., Neeman, J., Sly, A. (2015). Reconstruction and estimation in the planted partition model. Probab. Theory Related Fields, 162, 431-461.
-
Abbe, E., Sandon, C. (2015). Community detection in the stochastic block models by spectral methods. arXiv:1503.00609.
O.3 ML-Specific Papers
-
Palowitch, J. et al. (2022). GraphWorld: Fake Graphs Bring Real Insights for GNNs. KDD 2022.
-
Keriven, N., Peyre, G. (2019). Universal Invariant and Equivariant Graph Neural Networks. NeurIPS 2019.
-
Vignac, C. et al. (2022). DiGress: Discrete Denoising diffusion for graph generation. ICLR 2023.
-
Rusch, T.K., Bronstein, M.M., Mishra, S. (2023). A survey on oversmoothing in graph neural networks. arXiv:2303.10993.
-
Broido, A.D., Clauset, A. (2019). Scale-free networks are rare. Nature Communications, 10, 1017.
<- Back to Graph Theory | Next: Graph Algorithms ->
Appendix P: Summary of Key Inequalities
P.1 Concentration Inequalities for Random Graphs
Markov's inequality: For non-negative :
Chebyshev's inequality:
Chernoff bound (Poisson random variables): For :
Paley-Zygmund inequality: For non-negative with finite second moment:
Azuma-Hoeffding (Martingale concentration): If is a martingale with :
For random graph properties: reveal edges one at a time. Each edge revelation changes the property value by at most (Lipschitz constant of the property). Azuma-Hoeffding gives concentration of order around the mean.
McDiarmid's inequality (Bounded differences): If changes by at most when one edge is added/removed:
Applications: triangle count ( per edge change), largest clique (), chromatic number ().
P.2 Spectral Inequalities
Perron-Frobenius: For non-negative irreducible , and the leading eigenvector has all positive entries.
Courant-Fischer (Min-Max): The -th eigenvalue of symmetric satisfies:
Weyl's theorem: For symmetric and :
Bauer-Fike: If is diagonalizable with condition number , eigenvalue perturbations are bounded by . For symmetric : (always), recovering Weyl's theorem.
Cheeger inequality: For graph Laplacian , the Cheeger constant satisfies:
This is the fundamental connection between algebraic (spectral gap) and geometric (cut quality) properties of graphs.
<- Back to Graph Theory | Next: Graph Algorithms ->
Appendix Q: Quick Reference Card
RANDOM GRAPH QUICK REFERENCE
========================================================================
ERDOS-RENYI G(n,p)
------------------
- Average degree: np
- Degree dist: Poisson(np) as n->\infty
- Giant component: exists iff p > 1/n -> fraction \beta(c) w/ c=np
- Connectivity: w.h.p. iff p \geq ln(n)/n
- Diameter: ~ log(n)/log(np) when connected
- Clustering: ~ p -> 0 (locally tree-like)
WATTS-STROGATZ (n, k, \beta)
-------------------------
- Degree: \approx k (Poisson-like spread from rewiring)
- Clustering: C(0)(1-\beta)^3 where C(0) \approx 3/4 for large k
- Path length: O(log n) for any \beta > 0
- Small-world: \beta \in [1/(nk), 0.3] gives C\ggC_ER and L\approxL_ER
BARABASI-ALBERT (n, m)
-----------------------
- Degree dist: P(k) ~ 2m^2/k^3 (power law \gamma=3)
- Max degree: ~ m\sqrtn (oldest node)
- Diameter: ~ log(n)/log(log(n))
- Clustering: C ~ (log n)^2/n -> 0 (no clustering!)
STOCHASTIC BLOCK MODEL SBM(n,k,\sigma,B)
-------------------------------------
- KS threshold: (a-b)^2 = 2(a+b) for 2-block, p=a/n, q=b/n
- Exact recovery: (\sqrta - \sqrtb)^2 = 2 for log-degree regime
- Spectral alg: works above KS threshold
- GNN limit: No GNN beats KS threshold on SBM data
GRAPHONS W:[0,1]^2->[0,1]
-------------------------
- Dense graph limit: every dense G-sequence converges to a graphon
- Sampling: draw \xi^i~U[0,1]; edge (i,j) w.p. W(\xi^i,\xi_j)
- ER graphon: W(x,y) = p (constant)
- SBM graphon: W(x,y) = B_{\lceilkx\rceil,\lceilky\rceil} (step function)
- Operator: T_W h(x) = \int_0^1 W(x,y)h(y)dy (Hilbert-Schmidt)
========================================================================