The limits of depth: oversmoothing, oversquashing and heterophily
Diagnose oversmoothing, oversquashing and heterophily in deep graph networks, and compare spectral, rewiring and residual techniques using measured experiments.
After this lesson you can
- Derive the spectral energy decay bound and recognize the role of negative modes.
- Bound long-range Jacobian sensitivity and explain oversquashing.
- Interpret graph curvature, resistance and rewiring costs.
- Measure homophily and distinguish heterophily from optimization issues.
- Compare deep graph architectures using validation and measured diagnostics.
Before you start
More reach, three distinct problems
A message-passing layer extends the receptive field by one hop. Stacking many seems natural for distant dependencies, but an accuracy drop does not identify its cause. States may become indistinguishable; distant information may pass through a bottleneck; or mixing neighbors may erase a signal when labels differ. Unstable optimization and insufficient data are other explanations. Choosing a remedy requires measuring representations, sensitivity and task performance, not just counting layers.
The figure computes exactly the linear dynamics it displays, without training. The residual option uses ; initial input uses . The latter illustrates input injection, not the whole GCNII model. The graph clips tiny values to a positive floor to use a logarithmic scale.
Oversmoothing and the spectrum
For a connected undirected graph, add loops and write , and . Its normalized Laplacian is . The Dirichlet energy of is
Oversmoothing is the loss of relevant differences between representations through repeated propagation. For this particular linear dynamic, converges to the projection onto . In an irregular graph the limiting rows are proportional to , not necessarily equal. Energy is zero when the rows normalized by match. Small energy is a diagnostic, not proof the task has failed: it depends on the required signal.
Proof
By symmetry, with an orthonormal basis. If , energy after layers is . Each factor is at most , which can be taken outside the sum. Connectivity makes eigenvalue of simple; loops eliminate periodicity and guarantee . The result does not assert exact decay of every signal with the same slope: it depends on which modes are present.
∎Loops do not ensure all eigenvalues of are nonnegative. In with one loop per node, its spectrum is , with multiplicity four, and . Thus , but a signal in the last mode loses energy by factor in one layer, not . Replacing by without checking the upper end of the spectrum would give a false bound.
In networks with weights and activations, this linear proof does not transfer automatically: nonlinearities, weights and bias change the assumptions. Results on nonlinear limits are subtler; see the survey by Rusch, Bronstein and Mishra. Constant energy or low accuracy alone also does not reveal whether the optimizer converges.
Sensitivity and bottlenecks
Oversquashing occurs when growing amounts of information from distant nodes must be compressed into fixed-width states, especially across few links. Let and suppose each layer’s Jacobian block satisfies for a submultiplicative norm. The chain rule and triangle inequality give
The base is . If it holds at , summing over gives . The bound requires control of all local derivatives, including self terms and normalizations; it cannot be attributed to any MPNN without that assumption. A small bound certifies small sensitivity under it, but a large bound does not guarantee a trained network uses the signal. Width and weight magnitude matter too. See the analyses of Topping et al. and Di Giovanni et al..
The figure directly calculates for a linear channel without learned weights. Adding a link also changes normalization degrees, so some sensitivities can decrease even as others rise. The virtual node appears as V and is included in propagation, but bars correspond to the nine original nodes. This example illustrates topology; it does not prove rewiring improves a task or prevents all compression.
Curvature, resistance and rewiring
Balanced Forman curvature is a local quantity defined per edge in an unweighted simple graph. For , it counts common neighbors , neighbors of each endpoint participating in chordless squares, , and the maximum degeneracy of those squares. If either endpoint has degree one, the definition is zero. Otherwise:
where the last term is zero if there are no squares. In it is ; in a chordless square, ; in a six-cycle, . In two cliques joined by one edge, the bridge has curvature . These figures are checked with the downloadable code and follow the definition of Topping et al.. A negative edge is a local clue, not a universal equivalence between curvature and predictive error.
The figure uses 18 Cora papers, identified by their indices in Planetoid: they are the first 18 nodes in the breadth-first search up to distance two from node 1 in the examined copy. The undirected induced subgraph is taken and degrees and cycles recomputed there. Thickness highlights the selected edge; color encodes sign. Position comes from networkx.spring_layout with seed 8 and only organizes the drawing. Do not extrapolate curvature from this crop to the same edges in the full graph.
Effective resistance measures connectivity through alternative paths in an electrical network. A unit-weight bridge has value one; edges with parallel paths have lower resistance. Algebraic connectivity and Cheeger’s inequality relate global expansion and cuts, but neither indicator is identical to a trained model’s gradient.
Rewiring adds or removes links to modify information flow. SDRF selects edges by curvature and FoSR uses a first-order spectral approximation. A virtual node connects every node with a global aggregate; it reduces distance, but compresses information again into a shared vector. Shortcuts can accelerate smoothing or destroy useful structure: measure both effects and preserve original edge type where relevant. FoSR combines rewiring and a relational architecture precisely to distinguish new from original links.
Another option is propagation on an auxiliary expander graph: with bounded degree it can have edges and small diameter, allowing distant nodes to communicate without connecting every pair. Expander Graph Propagation combines local steps with propagation on that auxiliary structure. How nodes are associated with the expander and randomness in that association are part of the model; an index-dependent assignment can break permutation invariance unless transformed consistently. Greater expansion can improve reach while accelerating mixing, so compare state energy alongside the task and do not interpret the expander as a guarantee against oversquashing in every trained network.
Homophily and model choice
Edge homophily is the fraction of links whose endpoints share a label. Node homophily averages each node’s fraction of same-class neighbors, with an explicit convention for isolates. They differ when degrees are unequal. Adjusted homophily compares the observed fraction with , where is the fraction of edge endpoints in class : when the denominator is positive. That adjustment partially avoids confusing class imbalance with homophily.
Heterophily does not imply neighbors are useless. If one class systematically connects to another, neighbor composition may predict the label. Separating self from neighbor information and combining multiple hops helps preserve that possibility; a high-pass filter can also help. A U-shaped accuracy curve on an SBM depends on signal, training and protocol: it is not a universal law. Platonov et al. found duplicates causing train/test leakage in Squirrel and Chameleon and built new datasets; they also found strong results with conventional GNNs on the heterophilous graphs they evaluated.
In each of eleven synthetic graphs of 60 nodes and two balanced classes, same-class edge probability is and cross-class probability is . Scalar features contain class signal plus normal noise. A perceptron with six hidden units trains on 40 nodes and is evaluated on the other 20: directly, after averaging ego and neighbors, and with ego and neighbor mean as separate inputs. These are small classifiers with one seed per point; edges cross the split and the protocol is transductive. The curves do not measure uncertainty across graphs or reproduce benchmark results.
Depth with diagnosis
Techniques for deep GNNs address different problems. A residual helps optimization, but does not by itself prevent a contractive iteration from smoothing. Jumping Knowledge retains information from multiple depths; PairNorm normalizes dispersion; DropEdge randomly changes connectivity. GCNII combines initial residual and near-identity transformation: a typical form mixes before multiplying by and applying an activation. The architecture and evidence are described in Chen et al..
Measure normalized energy, effective rank of the state matrix and Jacobian sensitivity between relevant pairs simultaneously. A state matrix can have low energy and still contain a useful direction, or high rank without encoding the label. Separate validation and test; do not select a technique by best test result. A virtual node that improves a long-range task may worsen another if its signal depends on the altered topology.
Lab: verify the negative mode
import numpy as np
A=np.block([[np.zeros((3,3)),np.ones((3,3))],[np.ones((3,3)),np.zeros((3,3))]])
A+=np.eye(6)
degrees=A.sum(axis=1); S=A/np.sqrt(np.outer(degrees,degrees)); L=np.eye(6)-S
q=np.array([1,1,1,-1,-1,-1],dtype=float)
energy=lambda X: float(X.T@L@X)
print('espectro',np.linalg.eigvalsh(S).round(6).tolist())
print('energías',energy(q),energy(S@q),'factor',energy(S@q)/energy(q))
assert np.allclose(S@q,-.5*q) and np.isclose(energy(S@q)/energy(q),.25)Now construct two four-node cliques joined by an edge. Effective rank uses entropy of normalized singular values of centered states: it depends on that centering choice. For the nonlinear network we use a fixed hyperbolic tangent, not a trained network.
def norm_adj(n,edges):
A=np.eye(n)
for u,v in edges: A[u,v]=A[v,u]=1
d=A.sum(1); return A/np.sqrt(np.outer(d,d))
edges=[(i,j) for start in (0,4) for i in range(start,start+4) for j in range(i+1,start+4)]+[(3,4)]
P=norm_adj(8,edges); L=np.eye(8)-P
X=np.array([[-1,-.8],[-1,.2],[-1,.9],[-1,-.3],[1,.8],[1,-.7],[1,.4],[1,-.2]])
def diagnostic(H):
e=float(np.trace(H.T@L@H)); s=np.linalg.svd(H-H.mean(0),compute_uv=False)
p=s/s.sum() if s.sum()>0 else s
rank=float(np.exp(-sum(v*np.log(v) for v in p if v>0))) if s.sum()>0 else 0.
return round(e,6),round(rank,6)
linear=X.copy(); nonlinear=X.copy()
for k in range(1,9):
linear=P@linear; nonlinear=np.tanh(P@nonlinear)
if k in (1,4,8): print('capa',k,'lineal',diagnostic(linear),'tanh',diagnostic(nonlinear))Sensitivity of an output to an input can also be checked using central finite differences. The linear model permits comparison with the exact power; for tanh the derivative depends on input. The shortcut changes normalization of all endpoints it connects.
def forward_scalar(x,M,k,activation=False):
for _ in range(k): x=M@x; x=np.tanh(x) if activation else x
return x
def finite_difference(x,M,k,u,v,activation=False,eps=1e-5):
e=np.zeros_like(x); e[u]=eps
return (forward_scalar(x+e,M,k,activation)[v]-forward_scalar(x-e,M,k,activation)[v])/(2*eps)
x=np.linspace(-1,1,8); shortcut=norm_adj(8,edges+[(1,6)])
for name,M in [('original',P),('atajo',shortcut)]:
numeric=finite_difference(x,M,4,7,0)
exact=np.linalg.matrix_power(M,4)[0,7]
nonlinear_fd=finite_difference(x,M,4,7,0,True)
print(name,'lineal',round(numeric,8),'exacta',round(float(exact),8),'tanh',round(nonlinear_fd,8))
assert np.isclose(numeric,exact,atol=1e-9)This curvature implementation counts chordless squares; it accepts edges in one direction and symmetrizes them. To run it in your local notebook you can also download curvatura.py.
def curvature(n,edges):
adj=[set() for _ in range(n)]
for i,j in edges: adj[i].add(j); adj[j].add(i)
out={}
for i,j in edges:
i,j=min(i,j),max(i,j); di,dj=len(adj[i]),len(adj[j])
if min(di,dj)==1: out[i,j]=0.; continue
tri=len(adj[i]&adj[j]); left=adj[i]-adj[j]-{j}; right=adj[j]-adj[i]-{i}
links={(u,v) for u in left for v in right if v in adj[u]}
a={u for u,v in links}; b={v for u,v in links}
gamma=max([sum(u==x for x,y in links) for u in a]+[sum(v==y for x,y in links) for v in b]+[0])
square=(len(a)+len(b))/(gamma*max(di,dj)) if gamma else 0.
out[i,j]=2/di+2/dj-2+2*tri/max(di,dj)+tri/min(di,dj)+square
return out
square=[(0,1),(1,2),(2,3),(3,0)]
clique=[(i,j) for i in range(4) for j in range(i+1,4)]
print('K4',round(curvature(4,clique)[0,1],6),'C4',curvature(4,square)[0,1],'puente',curvature(8,edges)[3,4])
assert np.isclose(curvature(4,clique)[0,1],4/3) and curvature(4,square)[0,1]==1 and curvature(8,edges)[3,4]==-1labels=np.array([0,0,0,0,1,1]); ee=[(0,1),(1,2),(2,3),(3,0),(0,4),(1,5),(4,5)]
neighbors=[[] for _ in labels]
for u,v in ee: neighbors[u].append(v); neighbors[v].append(u)
h_edge=np.mean([labels[u]==labels[v] for u,v in ee])
h_node=np.mean([np.mean(labels[ns]==labels[i]) for i,ns in enumerate(neighbors) if ns])
ends=np.array([len(neighbors[i]) for i in range(len(labels))]); proportions=[ends[labels==c].sum()/ends.sum() for c in (0,1)]
baseline=sum(p*p for p in proportions); adjusted=(h_edge-baseline)/(1-baseline)
print('aristas',round(h_edge,6),'nodos',round(h_node,6),'ajustada',round(adjusted,6))
assert np.isclose(adjusted,.3)FoSR’s first-order score proposes connecting pairs with opposite-sign components of the second eigenvector, adjusted by degree. In this small example we recompute the eigenvector exactly and compare algebraic connectivity before and after. The paper uses an efficient approximation; this cell illustrates the score, not the full implementation or a guarantee of improvement on every graph.
A=np.zeros((8,8))
for u,v in edges: A[u,v]=A[v,u]=1
def laplacian_normalized(A):
d=A.sum(1)
return np.eye(len(A))-A/np.sqrt(np.outer(d,d))
values,vectors=np.linalg.eigh(laplacian_normalized(A));degree=A.sum(1)
scaled=vectors[:,1]/np.sqrt(1+degree)
score=np.outer(scaled,scaled);score[A>0]=np.inf;np.fill_diagonal(score,np.inf)
u,v=np.unravel_index(np.argmin(score),score.shape)
new=A.copy();new[u,v]=new[v,u]=1
before=float(values[1]);after=float(np.linalg.eigvalsh(laplacian_normalized(new))[1])
print('atajo',int(u),int(v),'lambda2 antes y después',round(before,6),round(after,6))
assert not A[u,v] and np.isclose(before,.11338247516251201) and np.isclose(after,.23240812075600165)Local lab: depth on real data
Download profundidad.py. With PyTorch, PyTorch Geometric and CUDA it compares GCN, residual, Jumping Knowledge and GCNII at 2, 4, 8, 16, 32 and 64 layers. Cora uses its public split; Roman-empire uses the first of its ten official masks. In each case features and connectivity of the full graph are available during propagation, while loss uses only training nodes: this is transductive evaluation.
python profundidad.py --dataset cora --root dataset/Planetoid --epochs 50 --output cora.json
python profundidad.py --dataset roman --root dataset/HeterophilousGraphDataset --epochs 50 --output roman.json
The code uses 32 channels, dropout 0.5, Adam, gradient clipping and selection of the best state by validation accuracy. Jumping Knowledge classifier parameters grow with depth because it concatenates states; the four variants do not have the same parameter count. Energy and effective rank are computed per layer in evaluation mode and saved in JSON. Effective rank uses entropy of centered singular values; energy uses the renormalized Laplacian and is divided by node count. They are diagnostic tools, not classification metrics. Test is calculated once per model after epoch selection. Repeat seeds and masks to evaluate variation, and separate training from decomposition time for performance comparisons.
In our Cora run with seed 42 and 50 epochs per variant, test accuracy after validation selection was:
| Layers | GCN | Residual | JK | GCNII |
|---|---|---|---|---|
| 2 | 0.791 | 0.794 | 0.802 | 0.803 |
| 4 | 0.641 | 0.789 | 0.785 | 0.793 |
| 8 | 0.512 | 0.698 | 0.767 | 0.804 |
| 16 | 0.316 | 0.430 | 0.783 | 0.834 |
| 32 | 0.226 | 0.211 | 0.775 | 0.831 |
| 64 | 0.223 | 0.230 | 0.779 | 0.807 |
The 64-layer GCNII completed 50 epochs and validation selected epoch 16; the selected state produced finite accuracy. The table describes this seed and budget, not a universal ranking or causal proof that every drop comes from smoothing. JK has a larger head. Per-layer energy comparison in the JSON helps investigate the mechanism alongside gradients and sensitivity; it does not replace those controls.
With the same budget and first Roman-empire split, test accuracies were:
| Layers | GCN | Residual | JK | GCNII |
|---|---|---|---|---|
| 2 | 0.292 | 0.600 | 0.396 | 0.407 |
| 4 | 0.165 | 0.570 | 0.403 | 0.433 |
| 8 | 0.161 | 0.448 | 0.432 | 0.387 |
| 16 | 0.154 | 0.299 | 0.462 | 0.377 |
| 32 | 0.166 | 0.174 | 0.468 | 0.327 |
| 64 | 0.167 | 0.181 | 0.452 | 0.274 |
Many variants selected the last epoch, indicating this budget does not establish convergence. Hyperparameters were not searched per variant and the ten splits were not averaged: these numbers are an execution check and diagnostic of this protocol, not a reproduction of the Roman-empire paper’s method ranking.
Local lab: reach and rewiring
NeighborsMatch asks a root to recover the label of the leaf whose neighbor count matches the root’s. The paper uses trees directed toward the root and provides those numbers as one-hot vectors to isolate transport. At depth four there are 16 leaves and the original work samples 16 000 training examples; its optimization budget is considerably larger than the example below.
Download alcance.py and checkpoint.py into the same folder to build a reproducible variant with undirected trees, 16 000 training examples and 2000 validation and test examples respectively. Each leaf gets a distinct count and label; the root query selects the count and the target is the corresponding label. The same five-layer network is compared on the tree, four edges chosen by the FoSR score, and a virtual node. The spectral variant computes the second eigenvector exactly at each step, while original FoSR approximates it by power iteration; selection is deterministic and does not use labels. This is a variant of the problem and algorithm, not a reproduction of the published table.
python alcance.py --depth 4 --train 16000 --val 2000 --test 2000 --epochs 50 --output neighborsmatch.json
The program uses CUDA by default; --device cpu runs the same architecture on one CPU thread. In that case CUDA memory is zero and does not represent RAM used. Record the device, since times and numerical rounding may change.
In a CPU run with seed 42, batch 128 and 50 epochs per variant, validation selection produced the following results. Random accuracy among 16 labels is .
| Variant | Validation accuracy | Test accuracy |
|---|---|---|
| Tree | 0.0735 | 0.0660 |
| Four shortcuts | 0.0770 | 0.0635 |
| Virtual node | 0.0975 | 0.1105 |
Best epochs were 6, 6 and 46; corresponding training accuracy was 0.0691, 0.0687 and 0.1329. With this architecture and budget, the virtual node exceeds chance on this split, while shortcuts show no test improvement. This is one seed and a synthetic problem: it does not demonstrate general superiority or identify the cause by itself. Recorded times were approximately 259, 267 and 367 seconds respectively, under shared load and excluding data generation.
For a real LRGB dataset, download peptidos.py. The program uses Peptides-func splits, predicts ten labels and selects by validation mean average precision. Variants share model, input and budget: original, one approximately spectral-scored edge, and a virtual node. Spectral iteration is lazy to prevent the negative end dominating by magnitude; new edges are added to the same relation, so this is not the full relational FoSR architecture. Bond types are omitted to keep the example compact and consistent across variants. Rewiring preprocessing must be measured in addition to training. As in the previous program, --device cpu permits one CPU thread instead of CUDA and zero CUDA memory does not measure RAM.
Both programs save a checkpoint per epoch alongside their JSON and retain results of completed variants. Each variant has its own .<variante>.checkpoint file retaining final and best weights. To resume an interruption, repeat the same command and output path; the state includes the optimizer and random generators. Use different paths if changing batch size, splits or budget.
python peptidos.py --root dataset/LRGB --epochs 50 --output peptides.json
In a run of 50 epochs per variant, seed 42 and batch 32, the official splits of 10 873, 2331 and 2331 molecules were used. Results are mean average precision across ten labels:
| Variant | Validation AP | Test AP |
|---|---|---|
| Original graph | 0.5065 | 0.4911 |
| Spectral shortcut | 0.5061 | 0.4793 |
| Virtual node | 0.5155 | 0.4875 |
Best epochs were 50, 48 and 48. The baseline selected the last epoch, so this budget does not show convergence. The virtual node obtained higher validation AP, but the original had the highest test result for this seed: one run cannot establish a general ordering. CPU times were approximately 993, 1006 and 1249 seconds for training, validation and test; they exclude loading and prior rewiring and were measured under shared load.
In a separate one-thread CPU measurement, after loading all three splits, preparing all their copies took 4.09 s for the original, 17.91 s for the spectral shortcut and 2.97 s for the virtual node. Variants were measured in that order and may benefit from warm caches; these are one-pass times, not a stable hardware characterization. Rewiring added 30 844 directed edges in total: in 113 of 15 535 graphs it did not add the pair, due to implementation conditions. The virtual node added 4 689 718 directed edges, showing that shortening paths can also greatly increase message cost.
A better result with shortcuts does not by itself identify a cause: the virtual node can aggregate information and also change the problem, while rewiring can accelerate mixing. Also compare sensitivity, per-layer energy, parameter count, preparation cost and metrics on independent splits.
Exercises
Step 1 of 3. Which basis simultaneously represents the Laplacian and propagation?
Step 1 of 3. What is the initial derivative of node v with respect to node u?
import numpy as np
def balanced_forman_curvature(edge_index):
pass