TExcelTAD
Home › Spectral Graph Theory & Modern Graph Algorithms › Conjugate Gradient and Tree Preconditioners

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 LL (O(m)O(m) 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 MM and bb in its range, conjugate gradient (CG; Hestenes and Stiefel, 1952) builds iterates xkx_k in the Krylov space span⁡(b,Mb,…,Mk−1b)\operatorname{span}(b, Mb, \ldots, M^{k-1}b) that minimize the error in the MM-norm, ∥xk−x∗∥M\lVert x_k - x^* \rVert_M, over that whole space, using only a three-term recurrence:

text
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 x

For a Laplacian with b⊥1b \perp \mathbf{1} every Krylov vector is orthogonal to 1\mathbf{1}, so CG works on the range of LL and converges to L+bL^+ b with no grounding needed.

Convergence. Since xkx_k is optimal over polynomials of degree kk in MM, comparing with a scaled Chebyshev polynomial gives

∥xk−x∗∥L≤2(κ−1κ+1)k∥x∗∥L,κ=λnλ2,\lVert x_k - x^* \rVert_L \le 2\left(\frac{\sqrt\kappa - 1}{\sqrt\kappa + 1}\right)^k \lVert x^* \rVert_L, \qquad \kappa = \frac{\lambda_n}{\lambda_2},

so O(κlog⁡(1/ε))O(\sqrt\kappa\log(1/\varepsilon)) iterations reach relative error ε\varepsilon, against O(κlog⁡(1/ε))O(\kappa\log(1/\varepsilon)) for simple methods like Richardson or Jacobi. CG also terminates exactly after at most as many steps as LL has distinct nonzero eigenvalues (in exact arithmetic).

For a k×kk \times k grid, λn≈8\lambda_n \approx 8 and λ2≈π2/k2\lambda_2 \approx \pi^2/k^2, so κ=Θ(n)\kappa = \Theta(n) and CG needs O(n)O(\sqrt n) iterations: O(mn)=O(n1.5)O(m\sqrt n) = O(n^{1.5}) total, the same as nested dissection. For an expander, κ=O(1)\kappa = O(1) and CG is fast. The hard cases are graphs that are badly conditioned and have no small separators.

python · try it yourself
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 kk quadruples nn and κ\kappa and roughly doubles the iteration count: κ\sqrt\kappa growth, as the bound predicts.

In C++

CG on a grid Laplacian stored implicitly (no matrix at all: LxLx is computed from the grid structure), reporting the residual every few iterations.

cpp · try it yourself
#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 BB is a matrix that is easy to solve with and close to LL, run CG on the equivalent system B−1/2LB−1/2y=B−1/2bB^{-1/2}LB^{-1/2}y = B^{-1/2}b (in practice: one solve with BB per iteration; this is preconditioned CG). The relevant condition number becomes the relative condition number

κ(L,B)=λmax⁡(B+L)λmin⁡(B+L)=max⁡xxTLxxTBxmin⁡x⊥1xTLxxTBx,\kappa(L, B) = \frac{\lambda_{\max}(B^+L)}{\lambda_{\min}(B^+L)} = \frac{\max_x \frac{x^{\mathsf{T}} L x}{x^{\mathsf{T}} B x}}{\min_{x \perp \mathbf{1}} \frac{x^{\mathsf{T}} L x}{x^{\mathsf{T}} B x}},

and PCG needs O(κ(L,B)log⁡(1/ε))O(\sqrt{\kappa(L, B)}\log(1/\varepsilon)) iterations. The ideal preconditioner is a sparse graph HH whose Laplacian LHL_H is spectrally close to LGL_G: exactly what a spectral sparsifier is.

Spanning trees as preconditioners (Vaidya, 1991). A tree T⊆GT \subseteq G is solved in linear time (leaf elimination), and LT⪯LGL_T \preceq L_G, so λmin⁡≥1\lambda_{\min} \ge 1. The upper side is controlled by the stretch: for an edge e=uve = uv of GG, st⁡T(e)=we∑f∈PT(u,v)rf\operatorname{st}_T(e) = w_e \sum_{f \in P_T(u,v)} r_f, where PT(u,v)P_T(u, v) is the tree path (for unweighted graphs, the tree distance between the endpoints). One shows tr⁡(LT+LG)=∑est⁡T(e)=st⁡T(G)\operatorname{tr}(L_T^+ L_G) = \sum_{e} \operatorname{st}_T(e) = \operatorname{st}_T(G), the total stretch, so κ(LG,LT)≤st⁡T(G)\kappa(L_G, L_T) \le \operatorname{st}_T(G) (Boman and Hendrickson, 2003) and PCG needs O(st⁡T(G)log⁡(1/ε))O(\sqrt{\operatorname{st}_T(G)}\log(1/\varepsilon)) iterations; Spielman and Woo (2009) improved this to O(st⁡T(G)1/3log⁡(1/ε))O(\operatorname{st}_T(G)^{1/3}\log(1/\varepsilon)) 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 m1+o(1)m^{1 + o(1)} (Alon, Karp, Peleg and West, 1995), improved to O(mlog⁡2nlog⁡log⁡n)O(m\log^2 n\log\log n) (Elkin, Emek, Spielman and Teng, 2005) and O(mlog⁡nlog⁡log⁡n)O(m\log n\log\log n) (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 k×kk \times k grid has total stretch Ω(nlog⁡n)\Omega(n \log n), larger than κ\kappa. 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 16×1616 \times 16 grid conductances between 10−310^{-3} and 10310^3 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 st⁡T(e)=weRT(u,v)\operatorname{st}_T(e) = w_e R_T(u, v), the tree's resistance between the ends of ee times the edge's conductance. Tree solves use a sparse direct factorization, which has no fill on a tree.

python · try it yourself
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 mm: 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 ε\varepsilon on Lx=bLx = b?

  1. O(κlog⁡(1/ε))O(\kappa\log(1/\varepsilon))
  2. O(κlog⁡(1/ε))O(\sqrt{\kappa}\log(1/\varepsilon)) with κ=λn/λ2\kappa = \lambda_n/\lambda_2
  3. O(log⁡n)O(\log n) always
  4. O(n2)O(n^2)

Why does CG work on a singular Laplacian when b⊥1b \perp \mathbf{1}?

  1. It doesn't
  2. All Krylov vectors LjbL^j b stay orthogonal to 1\mathbf{1}, so CG runs on the range of LL, where LL is positive definite
  3. Because LL is invertible
  4. Because CG ignores the matrix

What is the total stretch of a spanning tree TT of an unweighted graph GG?

  1. The diameter of TT
  2. The sum over edges uvuv of GG of the distance between uu and vv in TT
  3. The number of leaves
  4. The number of non-tree edges

Which bound on PCG iterations with a spanning-tree preconditioner did Spielman and Woo prove?

  1. O(log⁡n)O(\log n)
  2. O(st⁡T(G)1/3log⁡(1/ε))O(\operatorname{st}_T(G)^{1/3}\log(1/\varepsilon))
  3. O(st⁡T(G)2)O(\operatorname{st}_T(G)^2)
  4. O(m)O(m)