Conjugate Gradient and Tree Preconditioners
Gaussian elimination is exact but suffers from fill; Gauss-Seidel is cheap per step but converges slowly. Iterative Krylov methods sit in between: each iteration costs one multiplication by ( time) and the number of iterations depends on the condition number. For Laplacians the condition number can be reduced dramatically by preconditioning with a spanning tree, and the quality of a tree as a preconditioner is measured by a combinatorial quantity, its total stretch. This lesson implements conjugate gradient, measures how its iteration count grows, and shows tree preconditioning at work.
Conjugate gradient
For a symmetric positive (semi)definite and in its range, conjugate gradient (CG; Hestenes and Stiefel, 1952) builds iterates in the Krylov space that minimize the error in the -norm, , over that whole space, using only a three-term recurrence:
conjugate_gradient(M, b, tolerance)
1 x ← 0; r ← b; p ← r (r is the residual b − M x)
2 while ‖r‖ > tolerance · ‖b‖
3 q ← M p (the only matrix-vector product)
4 α ← (rᵀr) / (pᵀq)
5 x ← x + α p; r_new ← r − α q
6 β ← (r_newᵀ r_new) / (rᵀr)
7 p ← r_new + β p; r ← r_new
8 return xFor a Laplacian with every Krylov vector is orthogonal to , so CG works on the range of and converges to with no grounding needed.
Convergence. Since is optimal over polynomials of degree in , comparing with a scaled Chebyshev polynomial gives
so iterations reach relative error , against for simple methods like Richardson or Jacobi. CG also terminates exactly after at most as many steps as has distinct nonzero eigenvalues (in exact arithmetic).
For a grid, and , so and CG needs iterations: total, the same as nested dissection. For an expander, and CG is fast. The hard cases are graphs that are badly conditioned and have no small separators.
import numpy as np
import scipy.sparse as sp
def grid_laplacian(k):
n = k * k
rows, cols = [], []
for i in range(k):
for j in range(k):
v = i * k + j
if j + 1 < k: rows.append(v); cols.append(v + 1)
if i + 1 < k: rows.append(v); cols.append(v + k)
A = sp.coo_matrix((np.ones(len(rows)), (rows, cols)), shape=(n, n))
A = (A + A.T).tocsr()
return sp.diags(np.asarray(A.sum(axis=1)).ravel()) - A
def cg(L, b, tol=1e-8, maxit=10000):
x = np.zeros_like(b); r = b.copy(); p = r.copy(); rr = r @ r
for it in range(1, maxit + 1):
q = L @ p
alpha = rr / (p @ q)
x += alpha * p; r -= alpha * q
rr_new = r @ r
if np.sqrt(rr_new) <= tol * np.linalg.norm(b):
return x, it
p = r + (rr_new / rr) * p; rr = rr_new
return x, maxit
print(" k n kappa = lambda_n/lambda_2 CG iterations R_eff(corner, corner)")
for k in [8, 16, 32, 64]:
L = grid_laplacian(k)
n = k * k
lam2 = 2 - 2 * np.cos(np.pi / k) # grid = path x path
lamn = 2 * (2 + 2 * np.cos(np.pi / k))
b = np.zeros(n); b[0], b[-1] = 1, -1
x, its = cg(L, b)
print(f"{k:3} {n:6} {lamn / lam2:22.1f} {its:13} {x[0] - x[-1]:20.4f}") k n kappa = lambda_n/lambda_2 CG iterations R_eff(corner, corner)
8 64 50.5 16 2.7290
16 256 206.2 41 3.6085
32 1024 828.7 86 4.4903
64 4096 3318.8 174 5.3726
Each doubling of quadruples and and roughly doubles the iteration count: growth, as the bound predicts.
In C++
CG on a grid Laplacian stored implicitly (no matrix at all: is computed from the grid structure), reporting the residual every few iterations.
#include <cmath>
#include <cstdio>
#include <vector>
const int K = 40, N = K * K;
void apply_L(const std::vector<double>& x, std::vector<double>& y) {
for (int i = 0; i < K; ++i)
for (int j = 0; j < K; ++j) {
int v = i * K + j;
double s = 0;
int deg = 0;
if (i > 0) { s += x[v - K]; ++deg; }
if (i + 1 < K) { s += x[v + K]; ++deg; }
if (j > 0) { s += x[v - 1]; ++deg; }
if (j + 1 < K) { s += x[v + 1]; ++deg; }
y[v] = deg * x[v] - s;
}
}
double dot(const std::vector<double>& a, const std::vector<double>& b) {
double s = 0;
for (int i = 0; i < N; ++i) s += a[i] * b[i];
return s;
}
int main() {
std::vector<double> b(N, 0.0), x(N, 0.0), r, p, q(N);
b[0] = 1.0; b[N - 1] = -1.0; // unit current between opposite corners
r = b; p = r;
double rr = dot(r, r), nb = std::sqrt(dot(b, b));
for (int it = 1; it <= 1000; ++it) {
apply_L(p, q);
double alpha = rr / dot(p, q);
for (int i = 0; i < N; ++i) { x[i] += alpha * p[i]; r[i] -= alpha * q[i]; }
double rr_new = dot(r, r);
double rel = std::sqrt(rr_new) / nb;
if (it % 25 == 0 || rel < 1e-10) std::printf("iteration %3d: relative residual %.2e\n", it, rel);
if (rel < 1e-10) break;
for (int i = 0; i < N; ++i) p[i] = r[i] + rr_new / rr * p[i];
rr = rr_new;
}
std::printf("R_eff between opposite corners of the %dx%d grid: %.6f\n", K, K, x[0] - x[N - 1]);
}iteration 25: relative residual 2.19e-01
iteration 50: relative residual 4.14e-02
iteration 75: relative residual 3.05e-04
iteration 100: relative residual 1.44e-07
iteration 120: relative residual 6.98e-11
R_eff between opposite corners of the 40x40 grid: 4.774312
The residual does not fall monotonically at a fixed rate; CG adapts to the spectrum, and its convergence accelerates once it has "resolved" the smallest eigenvalues.
Preconditioning
If is a matrix that is easy to solve with and close to , run CG on the equivalent system (in practice: one solve with per iteration; this is preconditioned CG). The relevant condition number becomes the relative condition number
and PCG needs iterations. The ideal preconditioner is a sparse graph whose Laplacian is spectrally close to : exactly what a spectral sparsifier is.
Spanning trees as preconditioners (Vaidya, 1991). A tree is solved in linear time (leaf elimination), and , so . The upper side is controlled by the stretch: for an edge of , , where is the tree path (for unweighted graphs, the tree distance between the endpoints). One shows , the total stretch, so (Boman and Hendrickson, 2003) and PCG needs iterations; Spielman and Woo (2009) improved this to using the fact that the trace bounds how many eigenvalues can be large.
Low-stretch spanning trees. Every graph has a spanning tree of total stretch (Alon, Karp, Peleg and West, 1995), improved to (Elkin, Emek, Spielman and Teng, 2005) and (Abraham and Neiman, 2012), computable in nearly linear time. These trees are the first ingredient of the nearly-linear-time solvers of the next lesson. A careless tree can be terrible, as the next experiment shows.
On an unweighted grid, plain CG is hard to beat: every spanning tree of the grid has total stretch , larger than . Trees shine when the weights make the system ill-conditioned, as in finite-element and image problems where conductances span many orders of magnitude. The program gives the edges of a grid conductances between and and compares plain CG, the diagonal (Jacobi) preconditioner, the maximum-weight spanning tree (Kruskal on decreasing weights) and a random spanning tree. Weighted stretch is computed as , the tree's resistance between the ends of times the edge's conductance. Tree solves use a sparse direct factorization, which has no fill on a tree.
import numpy as np
import scipy.sparse as sp
import scipy.sparse.linalg as spla
k = 16
n = k * k
edges = [(i * k + j, i * k + j + 1) for i in range(k) for j in range(k - 1)] + \
[(i * k + j, (i + 1) * k + j) for i in range(k - 1) for j in range(k)]
rng = np.random.default_rng(2005)
w = 10.0 ** rng.uniform(-3, 3, len(edges)) # conductances over six orders of magnitude
def lap(ids):
u = np.array([edges[e][0] for e in ids]); v = np.array([edges[e][1] for e in ids]); ww = w[ids]
A = sp.coo_matrix((np.r_[ww, ww], (np.r_[u, v], np.r_[v, u])), shape=(n, n)).tocsr()
return (sp.diags(np.asarray(A.sum(axis=1)).ravel()) - A).tocsc()
def spanning_tree(order):
parent = list(range(n))
def find(a):
while parent[a] != a:
parent[a] = parent[parent[a]]; a = parent[a]
return a
T = []
for e in order:
a, b = find(edges[e][0]), find(edges[e][1])
if a != b:
parent[a] = b; T.append(e)
return T
def total_stretch(T):
# stretch of e = w_e * (tree resistance between its ends) = w_e * R_T(u, v)
LT = lap(T)[1:, 1:].tocsc()
lu = spla.splu(LT)
s = 0.0
for e, (u, v) in enumerate(edges):
b = np.zeros(n); b[u] += 1; b[v] -= 1
x = np.zeros(n); x[1:] = lu.solve(b[1:])
s += w[e] * (x[u] - x[v])
return s
def pcg(L, b, solve_B, tol=1e-8):
x = np.zeros(n); r = b.copy(); z = solve_B(r); p = z.copy(); rz = r @ z
for it in range(1, 20000):
q = L @ p
a = rz / (p @ q)
x += a * p; r -= a * q
if np.linalg.norm(r) <= tol * np.linalg.norm(b):
return it
z = solve_B(r); rz_new = r @ z
p = z + (rz_new / rz) * p; rz = rz_new
def tree_solver(T):
lu = spla.splu(lap(T)[1:, 1:].tocsc())
def solve(r):
z = np.zeros(n); z[1:] = lu.solve(r[1:]); return z - z.mean()
return solve
L = lap(np.arange(len(edges)))
b = np.random.default_rng(0).standard_normal(n); b -= b.mean()
dinv = 1 / L.diagonal()
print(f"{k}x{k} grid, {len(edges)} edges, conductances from 1e-3 to 1e3")
print(f" {'no preconditioner:':22} {'':26} CG iterations {pcg(L, b, lambda r: r.copy()):5}")
print(f" {'Jacobi (diagonal):':22} {'':25} PCG iterations {pcg(L, b, lambda r: dinv * r - (dinv * r).mean()):5}")
for name, order in [("maximum-weight tree", np.argsort(-w, kind="stable")),
("random spanning tree", np.random.default_rng(1).permutation(len(edges)))]:
T = spanning_tree(order)
print(f" {name + ':':22} total stretch {total_stretch(T):10.0f}, PCG iterations {pcg(L, b, tree_solver(T)):5}")16x16 grid, 480 edges, conductances from 1e-3 to 1e3
no preconditioner: CG iterations 1186
Jacobi (diagonal): PCG iterations 423
maximum-weight tree: total stretch 308, PCG iterations 17
random spanning tree: total stretch 14831957, PCG iterations 2896
The maximum-weight tree keeps the strong edges, so every non-tree edge is weak relative to the tree path around it and the total stretch stays near : 17 iterations instead of over a thousand. A random tree is a disaster, because it routes strong edges through weak tree edges and its stretch is astronomical. Stretch, not the number of edges, is what a tree preconditioner must control.
Test yourself
How many CG iterations suffice to reach relative error on ?
- with
- always
Why does CG work on a singular Laplacian when ?
- It doesn't
- All Krylov vectors stay orthogonal to , so CG runs on the range of , where is positive definite
- Because is invertible
- Because CG ignores the matrix
What is the total stretch of a spanning tree of an unweighted graph ?
- The diameter of
- The sum over edges of of the distance between and in
- The number of leaves
- The number of non-tree edges
Which bound on PCG iterations with a spanning-tree preconditioner did Spielman and Woo prove?