Sparse direct solvers: orderings, fill-in, and the solve pipeline#
A sparse direct solver factors A into triangular factors and then solves by
substitution. Elimination is not free in a sparse matrix. Eliminating one
unknown couples every pair of its neighbours, so the factors pick up nonzeros
where A had none. That fill-in decides how much memory the factorization
needs and how long it takes. The amount of fill depends almost entirely on the
order in which the unknowns are eliminated.
This notebook follows MATLAB’s
colamd example with
mtl5, then goes further:
The matrix. Load
west0479and look at its pattern.Orderings and fill. Reorder it four ways, factor each, and look at the factors themselves.
A symmetric problem. Show that the winning ordering depends on the matrix’s structure.
The solve pipeline. Separate analyze, factor, refactor and solve, and show what reusing the analysis saves.
It needs the notebooks extra (pip install -e ".[notebooks]") for matplotlib
and SciPy. Every number printed here is computed when the notebook runs, and CI
runs it, so the assert cells catch an ordering that stops reducing fill.
import time
import matplotlib.pyplot as plt
import numpy as np
import scipy.sparse as sp
import scipy.sparse.linalg as spla
from matplotlib.colors import ListedColormap
import mtl5
import mtl5.sparse as ms
# Chart styling: recessive axes and grid, ink for text, validated categorical hues.
SURFACE = "#fcfcfb"
INK, INK_2 = "#0b0b0b", "#52514e"
SERIES = ["#2a78d6", "#eb6834", "#1baf7a", "#eda100"]
plt.rcParams.update(
{
"figure.facecolor": SURFACE,
"axes.facecolor": SURFACE,
"axes.edgecolor": "#d8d7d2",
"axes.labelcolor": INK_2,
"axes.titlecolor": INK,
"text.color": INK,
"xtick.color": INK_2,
"ytick.color": INK_2,
"font.size": 10,
"figure.dpi": 120,
}
)
# Spy figures render at this resolution, so that each matrix row gets about
# two pixels: a pattern drawn below one pixel per row smears neighbours together.
SPY_DPI = 200
def spy(ax, M, title, color=SERIES[0]):
# MATLAB-style spy plot of an MTL5 or SciPy sparse matrix, drawn as an image
# with one cell per matrix entry, so two nonzeros never overlap. Markers
# sized in points (matplotlib's ax.spy) span several rows at this scale.
# Every STORED entry is drawn, including ones whose value is exactly zero:
# storage and work are spent on them.
S = (ms.to_scipy(M) if not sp.issparse(M) else M).tocoo()
pattern = np.zeros(S.shape, dtype=bool)
pattern[S.row, S.col] = True
ax.imshow(pattern, cmap=ListedColormap([SURFACE, color]), interpolation="none")
ax.set_title(f"{title}\nnz = {S.nnz:,}", fontsize=9)
ax.set_xticks([])
ax.set_yticks([])
def best_time(fn, repeats=5):
# Best wall time of `repeats` calls, in milliseconds, and the last result.
best, out = float("inf"), None
for _ in range(repeats):
t = time.perf_counter()
out = fn()
best = min(best, time.perf_counter() - t)
return best * 1e3, out
print("mtl5", mtl5.__version__, "| orderings:", ms.orderings())
mtl5 5.25.0 | orderings: ['amd', 'colamd', 'rcm', 'nd', 'natural']
1. The matrix#
west0479 is a Harwell-Boeing test matrix of order 479. It models an
eight-stage Westerberg chemical distillation column, and it is unsymmetric.
The file in data/ is the one Matrix Market distributes; data/README.md
gives the source.
The file stores 1910 entries, and 22 of them are explicit zeros. A stored zero
still occupies a slot in the factorization, so drop the zeros first.
MATLAB’s load west0479 reports 1887 nonzeros, which differs from the 1888
here by a single entry.
A_file = mtl5.io.mm_read("data/west0479.mtx")
S = ms.to_scipy(A_file)
stored, explicit_zeros = S.nnz, int((S.data == 0).sum())
S.eliminate_zeros()
A = ms.from_scipy(S)
n = A.shape[0]
print(f"order {n}, {stored} stored entries, {explicit_zeros} explicit zeros -> nnz(A) = {A.nnz}")
assert A.nnz == stored - explicit_zeros == 1888
fig, ax = plt.subplots(figsize=(5, 5.2), dpi=SPY_DPI)
spy(ax, A, "west0479")
plt.show()
order 479, 1910 stored entries, 22 explicit zeros -> nnz(A) = 1888
The eight column stages are visible as repeated blocks along the diagonal, coupled by a few long-range entries.
2. Orderings and fill-in#
mtl5.sparse.splu factors a column-permuted matrix with threshold partial
pivoting:
The column permutation comes from the fill-reducing ordering, chosen before
any arithmetic. The row permutation comes from pivoting, chosen during the
factorization for numerical stability. mtl5.sparse.ordering(A, name) returns
the column permutation on its own, so you can look at it before factoring.
Ordering |
What it minimizes |
Natural fit |
|---|---|---|
|
nothing: the identity |
a baseline |
|
approximate minimum degree on the pattern of \(A^TA\) |
LU and QR of unsymmetric matrices: the fill of LU with partial pivoting is bounded by the Cholesky factor of \(A^TA\) |
|
approximate minimum degree on the pattern of \(A + A^T\) |
Cholesky and \(LDL^T\), and LU of matrices with a nearly symmetric pattern and a strong diagonal |
|
bandwidth (reverse Cuthill-McKee) |
banded or profile storage; not fill directly |
A permutation moves entries but never changes how many there are:
ORDERINGS = ["natural", "colamd", "amd", "rcm"]
perms = {o: ms.ordering(A, o) for o in ORDERINGS}
fig, axes = plt.subplots(2, 2, figsize=(9.5, 10), dpi=SPY_DPI)
for ax, o, c in zip(axes.flat, ORDERINGS, SERIES):
spy(ax, S[:, perms[o]], f"A[:, p] ({o})", color=c)
plt.tight_layout()
plt.show()
assert all(S[:, p].nnz == A.nnz for p in perms.values())
The factors are where the orderings differ. Since #126 every factor object
exposes L, U, row_perm and col_perm, so the fill can be counted and
looked at, not just inferred from .nnz.
b = S @ np.ones(n)
lus, rows = {}, []
for o in ORDERINGS:
ms_factor, lu = best_time(lambda o=o: ms.splu(A, ordering=o))
x = lu.solve(b).to_numpy()
rows.append((o, lu.L.nnz, lu.U.nnz, lu.nnz, lu.nnz / A.nnz, ms_factor, np.abs(x - 1).max()))
lus[o] = lu
header = ("ordering", "nnz(L)", "nnz(U)", "nnz(L+U)", "fill", "factor", "max|x-1|")
print("{:>8} {:>8} {:>8} {:>9} {:>6} {:>9} {:>9}".format(*header))
for o, nl, nu, nlu, ratio, t, err in rows:
print(f"{o:>8} {nl:8,} {nu:8,} {nlu:9,} {ratio:5.1f}x {t:7.2f}ms {err:9.1e}")
# Fill regressions fail CI here. The solution check uses an absolute error: west0479
# is badly conditioned, so 1e-9 is what a backward-stable solve delivers on it.
assert lus["colamd"].nnz < lus["natural"].nnz / 2
assert lus["colamd"].nnz < min(lus["amd"].nnz, lus["rcm"].nnz)
assert all(err < 1e-7 for *_, err in rows)
ordering nnz(L) nnz(U) nnz(L+U) fill factor max|x-1|
natural 13,218 7,354 20,572 10.9x 1.32ms 1.4e-09
colamd 3,000 3,744 6,744 3.6x 0.73ms 1.3e-10
amd 5,561 6,019 11,580 6.1x 1.27ms 1.2e-10
rcm 3,626 5,465 9,091 4.8x 0.61ms 6.8e-11
Every ordering solves the system to the same accuracy. What they change is the
cost: colamd cuts the factors to about a third of the natural ordering’s
fill. This is MATLAB’s spy(lu(A)) against spy(lu(A(:,p))):
def pattern(M):
# The stored pattern with every value set to 1, so that adding two patterns
# cannot cancel an entry or drop a stored zero.
S = ms.to_scipy(M).tocsr()
return sp.csr_matrix((np.ones(S.nnz), S.indices, S.indptr), shape=S.shape)
fig, axes = plt.subplots(2, 2, figsize=(9.5, 10), dpi=SPY_DPI)
for ax, o, c in zip(axes.flat, ORDERINGS, SERIES):
lu = lus[o]
LU = pattern(lu.L) + pattern(lu.U) # the diagonals overlap: L + U - I
assert LU.nnz == lu.nnz - n
spy(ax, LU, f"L + U - I ({o})", color=c)
plt.tight_layout()
plt.show()
Some of those stored entries are exactly zero: the elimination cancelled them. They are still fill. The solver allocated them and computed them, and their positions are fixed by the pattern alone. The count and the plots therefore include them:
for o in ("natural", "colamd"):
lu = lus[o]
zeros = int((ms.to_scipy(lu.L).data == 0).sum() + (ms.to_scipy(lu.U).data == 0).sum())
print(f"{o:>8}: {lu.nnz:6,} stored in L and U, {zeros:5,} of them exactly zero")
natural: 20,572 stored in L and U, 3,276 of them exactly zero
colamd: 6,744 stored in L and U, 81 of them exactly zero
The factors also satisfy the identity exactly as documented. Reconstructing
A from them is a direct check that the permutations are the ones returned:
lu = lus["colamd"]
L, U = ms.to_scipy(lu.L), ms.to_scipy(lu.U)
PAQ = S[lu.row_perm][:, lu.col_perm]
rel = spla.norm(L @ U - PAQ) / spla.norm(S)
print(f"||A[row_perm][:, col_perm] - L U|| / ||A|| = {rel:.1e}")
print(f"num_perturbed = {lu.num_perturbed}")
assert lu.num_perturbed == 0 and rel < 1e-14
||A[row_perm][:, col_perm] - L U|| / ||A|| = 6.7e-19
num_perturbed = 0
Comparing with MATLAB and SciPy#
MATLAB’s page reports 15,918 nonzeros for lu(A) and 5,920 for
lu(A(:,p)). Two things make the raw counts differ from the ones above:
Counting. MATLAB’s single-output
lureturnsL + U - I, so each diagonal entry is counted once.Lhere stores its unit diagonal, so subtractnto compare.Pivoting. MATLAB, SciPy (SuperLU) and mtl5 (Gilbert-Peierls LU) pick different pivots and break ties differently, so the factors differ. The natural ordering is the most sensitive, because without fill reduction every pivot choice spreads further.
What carries over between implementations is the size of the effect: column minimum degree cuts the fill roughly threefold.
matlab = {"natural": 15918, "colamd": 5920}
scipy_spec = {"natural": "NATURAL", "colamd": "COLAMD"}
print(f"{'ordering':>8} {'mtl5':>8} {'SciPy':>8} {'MATLAB':>8} nnz(L+U-I)")
counts = {}
for o in ("natural", "colamd"):
f = spla.splu(S.tocsc(), permc_spec=scipy_spec[o])
counts[o] = (lus[o].nnz - n, f.L.nnz + f.U.nnz - n, matlab[o])
print(f"{o:>8} {counts[o][0]:8,} {counts[o][1]:8,} {counts[o][2]:8,}")
for name, i in (("mtl5", 0), ("SciPy", 1), ("MATLAB", 2)):
print(f"{name:>6}: colamd cuts fill {counts['natural'][i] / counts['colamd'][i]:.1f}x")
ordering mtl5 SciPy MATLAB nnz(L+U-I)
natural 20,093 17,482 15,918
colamd 6,265 5,914 5,920
mtl5: colamd cuts fill 3.2x
SciPy: colamd cuts fill 3.0x
MATLAB: colamd cuts fill 2.7x
KLU: factor only what has to be factored#
KLU (Davis and Palamadai Natarajan, 2010) does not order and factor the whole matrix. It first permutes A to block triangular form, B = P·R·A·Q, using a Dulmage–Mendelsohn decomposition. Here R is the row scaling. B is block upper triangular, so solving with it needs only the diagonal blocks factored: the blocks above them enter the block back-substitution as they are, and they never fill.
ms.klu exposes that structure rather than a single L and U, which it does
not have:
row_perm,col_permandrow_scalegive P, Q and R;block_startsgives the block boundaries, andBthe permuted matrix;block(i)gives diagonal block i’s ownL,U,row_permandcol_perm.
Reordering each diagonal block by its own pivots shows everything KLU stores
for west0479:
k = ms.klu(A)
starts, sizes = k.block_starts, np.diff(k.block_starts)
B = ms.to_scipy(k.B).tocsr()
blocks = [k.block(i) for i in range(k.nblocks)]
# Order each diagonal block by its own pivots: B's diagonal blocks then equal L_i U_i.
R = np.concatenate([starts[i] + blk["row_perm"] for i, blk in enumerate(blocks)])
C = np.concatenate([starts[i] + blk["col_perm"] for i, blk in enumerate(blocks)])
B2 = B[R][:, C].tocoo()
block_of = np.repeat(np.arange(k.nblocks), sizes)
upper = block_of[B2.row] < block_of[B2.col]
assert not np.any(block_of[B2.row] > block_of[B2.col]) # block upper triangular
# Everything KLU stores: the off-diagonal blocks of B, and L_i + U_i - I per block.
rows, cols = [B2.row[upper]], [B2.col[upper]]
for i, blk in enumerate(blocks):
LU = (pattern(blk["L"]) + pattern(blk["U"])).tocoo()
rows.append(starts[i] + LU.row)
cols.append(starts[i] + LU.col)
Bi = B[starts[i] : starts[i + 1], starts[i] : starts[i + 1]].toarray()
Li, Ui = ms.to_scipy(blk["L"]).toarray(), ms.to_scipy(blk["U"]).toarray()
Bi_p = Bi[blk["row_perm"]][:, blk["col_perm"]]
assert np.abs(Li @ Ui - Bi_p).max() <= 1e-12 * np.abs(Bi).max()
r_all, c_all = np.concatenate(rows), np.concatenate(cols)
stored = sp.csr_matrix((np.ones(len(r_all)), (r_all, c_all)), shape=(n, n))
fig, axes = plt.subplots(1, 2, figsize=(9.5, 5.2), dpi=SPY_DPI)
spy(axes[0], k.B, f"B = P R A Q: {k.nblocks} diagonal blocks", color=SERIES[0])
spy(axes[1], stored, "KLU's factors + off-diagonal blocks", color=SERIES[1])
plt.tight_layout()
plt.show()
singletons = int((sizes == 1).sum())
print(f"{k.nblocks} blocks: {singletons} of size 1, largest {sizes.max()}")
print(
f"KLU stores {stored.nnz:,} entries; splu(colamd) stores L + U - I = {lus['colamd'].nnz - n:,}"
)
assert stored.nnz == k.nnz - n + int(upper.sum())
assert stored.nnz < lus["colamd"].nnz - n
assert singletons > 100 and sizes.max() < n
166 blocks: 159 of size 1, largest 308
KLU stores 4,762 entries; splu(colamd) stores L + U - I = 6,265
Most of west0479 is not coupled at all: more than a hundred of its rows
are 1×1 blocks, whose factor is the matrix entry itself. Only one block, of
308 rows, needs a real sparse LU, and KLU orders it with AMD on its own. The
entries above the diagonal blocks are stored as they are, with no fill. That
is why KLU stores fewer entries than the best whole-matrix ordering. It is
also why KLU is the solver for circuit matrices, which are highly reducible
in the same way.
3. A symmetric problem: a different winner#
colamd won above because west0479 is unsymmetric. Now take the 2-D Poisson
matrix on an 80 × 80 grid: 6,400 unknowns, symmetric positive definite.
Here \(A + A^T\) is just the pattern of \(A\), so
amdorders the true elimination graph.colamdorders \(A^TA\) instead. For a symmetric \(A\) that is the pattern of \(A^2\), which couples neighbours of neighbours. It is a denser graph than the one the factorization actually eliminates.Because the matrix is SPD, Cholesky applies too: it needs no pivoting and stores only
L.
P = mtl5.generators.poisson2d(80, 80)
SP = ms.to_scipy(P).tocsr()
N = P.shape[0]
print(f"poisson2d(80, 80): n = {N:,}, nnz(A) = {P.nnz:,}")
lu_p, chol_p = {}, {}
print(f"{'ordering':>8} {'LU nnz':>10} {'LU factor':>10} {'Cholesky nnz':>13} {'Chol factor':>12}")
for o in ORDERINGS:
t_lu, lu_p[o] = best_time(lambda o=o: ms.splu(P, ordering=o), repeats=3)
t_ch, chol_p[o] = best_time(lambda o=o: ms.cholesky(P, ordering=o), repeats=3)
print(f"{o:>8} {lu_p[o].nnz:10,} {t_lu:8.1f}ms {chol_p[o].nnz:13,} {t_ch:10.1f}ms")
assert lu_p["amd"].nnz < lu_p["colamd"].nnz < lu_p["natural"].nnz
assert chol_p["amd"].nnz < chol_p["natural"].nnz / 3
poisson2d(80, 80): n = 6,400, nnz(A) = 31,680
ordering LU nnz LU factor Cholesky nnz Chol factor
natural 1,024,158 65.8ms 512,079 62.5ms
colamd 389,594 29.8ms 194,797 28.0ms
amd 241,532 17.1ms 120,766 15.1ms
rcm 701,680 42.4ms 350,840 32.8ms
The ranking has flipped: amd gives the least fill, and colamd is now
second. The Cholesky factors show why the orderings differ. They are drawn here
for a 24 × 24 grid, where the structure is visible at this size. natural keeps
the fill inside a band as wide as the grid, and fills the band completely.
rcm does the same inside a profile that narrows toward both ends. amd eliminates in an order that never lets
fill accumulate in one place:
small = mtl5.generators.poisson2d(24, 24)
fig, axes = plt.subplots(1, 3, figsize=(14, 5.2), dpi=SPY_DPI)
for ax, o, c in zip(axes, ("natural", "rcm", "amd"), (SERIES[0], SERIES[3], SERIES[2])):
L = ms.cholesky(small, ordering=o).L
spy(ax, L, f"Cholesky L ({o}, n = 576)", color=c)
plt.tight_layout()
plt.show()
That gives a rule of thumb, which the factorizations’ default ordering=
arguments already follow:
Matrix |
Factorization |
Ordering (default) |
|---|---|---|
symmetric positive definite |
|
|
symmetric indefinite |
|
|
unsymmetric |
|
|
unsymmetric, nearly symmetric pattern, strong diagonal |
|
try |
a narrow band or profile is the goal |
any |
|
When in doubt, measure: ms.splu(A, ordering=o).nnz for each o in
ms.orderings() costs a few factorizations and settles it.
4. The solve pipeline#
A direct solve has four stages, and they have very different costs:
Ordering. A fill-reducing permutation, from the pattern alone.
Symbolic analysis. The structure of the factors (elimination tree, column counts), again from the pattern alone.
Numeric factorization. The arithmetic. For LU this includes pivoting.
Solve. Two triangular substitutions per right-hand side.
Constructing a factor object runs stages 1 to 3. solve() runs stage 4, and is
cheap enough to call for many right-hand sides. refactor(A_new) reruns
only stage 3, for a matrix with the same pattern. It reuses the ordering,
the symbolic structure and, for LU, the pivot sequence.
lu = lu_p["amd"]
t_factor, _ = best_time(lambda: ms.splu(P, ordering="amd"), repeats=3)
t_refactor, _ = best_time(lambda: lu.refactor(P), repeats=3)
t_solve, _ = best_time(lambda: lu.solve(np.ones(N)), repeats=10)
print(f"factor (stages 1-3) {t_factor:7.2f} ms")
print(f"refactor (stage 3) {t_refactor:7.2f} ms {t_factor / t_refactor:4.1f}x cheaper")
print(f"solve (stage 4) {t_solve:7.2f} ms {t_factor / t_solve:4.0f}x cheaper")
factor (stages 1-3) 17.39 ms
refactor (stage 3) 6.73 ms 2.6x cheaper
solve (stage 4) 0.39 ms 45x cheaper
refactor() is built for problems whose values change while the pattern
stays fixed: implicit time stepping, Newton iterations, circuit transients,
parameter sweeps. Here twenty steps of \((A + c_k I)\,x = b\) are solved two ways.
In the first, each step is factored from scratch. In the second, one factor
object is refactored at every step.
eye = sp.identity(N, format="csr")
systems = [(SP + 0.1 * k * eye).tocsr() for k in range(1, 21)]
assert all(
np.array_equal(M.indptr, SP.indptr) and np.array_equal(M.indices, SP.indices) for M in systems
), "refactor() needs the same sparsity pattern at every step"
mats = [ms.from_scipy(M) for M in systems]
rhs = [M @ np.ones(N) for M in systems]
def run_fresh():
return [ms.splu(M, ordering="amd").solve(r) for M, r in zip(mats, rhs)]
def run_reuse():
lu = ms.splu(mats[0], ordering="amd") # the initial factorization is timed too
out = []
for M, r in zip(mats, rhs):
lu.refactor(M) # the first step refactors the same values: one wasted refactor
out.append(lu.solve(r))
return out
# Both workloads do a factorization and a solve per step. Running one always
# first would hand the other a warm cache and allocator, so the rounds
# alternate which goes first, and each method's best round is reported, as in
# the other timings. The solutions are checked after the timers.
t_fresh = t_reuse = float("inf")
for round_ in range(3):
order = (run_fresh, run_reuse) if round_ % 2 == 0 else (run_reuse, run_fresh)
for fn in order:
t = time.perf_counter()
out = fn()
elapsed = time.perf_counter() - t
if fn is run_fresh:
t_fresh, fresh = min(t_fresh, elapsed), out
else:
t_reuse, reused = min(t_reuse, elapsed), out
residuals = [
np.linalg.norm(Ms @ x.to_numpy() - r) / np.linalg.norm(r)
for Ms, r, x in zip(systems + systems, rhs + rhs, fresh + reused)
]
print(f"20 steps, factor each step: {t_fresh * 1e3:6.0f} ms")
print(f"20 steps, refactor: {t_reuse * 1e3:6.0f} ms ({t_fresh / t_reuse:.1f}x faster)")
print(f"worst relative residual: {max(residuals):.1e}")
assert max(residuals) < 1e-12
20 steps, factor each step: 352 ms
20 steps, refactor: 163 ms (2.2x faster)
worst relative residual: 5.5e-15
The reused pivot sequence is also refactor()’s limit. The pivots were chosen
for the first matrix’s values. If the values drift far enough that one of
those pivots becomes small, the refactored solve loses accuracy. refactor()
does not re-pivot for you. A cheap residual check, as above, is how you notice,
and a fresh splu() is the remedy.
Summary#
Fill-in, not the nonzeros of
A, decides the cost of a direct solve, and the elimination order decides the fill.Choose the ordering for the structure:
colamdfor unsymmetric LU and QR,amdfor symmetric factorizations,rcmwhen a narrow band is the goal. The defaults follow this.The factors are inspectable.
L,U,row_permandcol_permsatisfyA[row_perm][:, col_perm] == L @ U. KLU exposes its block triangular form instead:B, the BTF permutations and each block’s factors throughblock(i). For plots without matplotlib,mtl5.io.spy(M, "file.png")writes the pattern to a PNG.Analysis is a one-time cost when the pattern is fixed: use
refactor(), and keepsolve()for each new right-hand side.
Still to come in the sparse direct guide (#125): choosing a factorization, and
mixed-precision direct solves (a float32 factor refined with
mtl5.mixed.iterative_refine).
API reference: mtl5.io.mm_read, mtl5.sparse.splu, mtl5.sparse.cholesky, mtl5.sparse.ordering, mtl5.sparse.orderings, mtl5.sparse.colamd, mtl5.sparse.amd, mtl5.sparse.rcm, mtl5.sparse.to_scipy.