Mixed precision: a narrow factor, refined#
The factorization is the expensive part of a direct solve: it holds the most
memory and does almost all of the arithmetic. Iterative refinement lets that
part run in a narrow precision while the answer keeps the accuracy of a wide
one. Factor in float32, then correct the solution with residuals computed in
float64:
Each pass removes most of the remaining error, as long as the narrow factor is a good enough approximation of \(A\). The idea is old: Wilkinson analysed it in 1963 and Moler in 1967. It came back when hardware made single precision much faster than double (Langou et al., SC’06), and Carson and Higham (SIAM J. Sci. Comput. 40(2), 2018) extended it to three precisions and to GMRES-based refinement, which this page uses at the end.
In mtl5 it is one call, mtl5.mixed.iterative_refine(A, M, b): A and b
are float64, and M is any sparse direct factorization (or an ILU(0) or
IC(0) preconditioner), in either precision. This page measures what it buys
and where it stops working. The page is executed when the documentation is
built, and the assert statements check the claims the prose makes.
import time
import numpy as np
import scipy.sparse as sp
import scipy.sparse.linalg as spla
import mtl5
import mtl5.sparse as ms
iterative_refine = mtl5.mixed.iterative_refine
def best_ms(fn, repeats=3):
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
def fwd_err(x, x_true):
return np.abs(x - x_true).max() / np.abs(x_true).max()
Getting float64 accuracy from a float32 factor#
The test problem is the 2-D Poisson matrix from the
SPD example, with a random solution. The precision of a
factorization follows the dtype of the matrix it is given, so a float32 copy
of \(A\) gives a float32 factor.
k = 64
A = mtl5.generators.poisson2d(k, k)
S = ms.to_scipy(A)
n = S.shape[0]
x_true = np.random.default_rng(0).standard_normal(n)
b = S @ x_true
chol64 = ms.cholesky(A)
chol32 = ms.cholesky(ms.from_scipy(S.astype(np.float32)))
print(chol64)
print(chol32)
x64 = chol64.solve(b).to_numpy()
x32 = chol32.solve(b.astype(np.float32)).to_numpy().astype(np.float64)
x_ir, info = iterative_refine(A, chol32, b, rel_tol=1e-15)
print(f"float64 factor, direct solve: forward error {fwd_err(x64, x_true):.1e}")
print(f"float32 factor, direct solve: forward error {fwd_err(x32, x_true):.1e}")
print(f"float32 factor + float64 refining: forward error {fwd_err(x_ir, x_true):.1e}")
print(info)
assert fwd_err(x32, x_true) > 1e-7 # float32's unit roundoff is 6e-8
assert info["converged"] and info["iters"] <= 5
assert fwd_err(x_ir, x_true) < 2 * fwd_err(x64, x_true)
mtl5.sparse.SparseCholesky_f64(n=4096, ordering='amd', nnz=67200)
mtl5.sparse.SparseCholesky_f32(n=4096, ordering='amd', nnz=67200)
float64 factor, direct solve: forward error 2.6e-15
float32 factor, direct solve: forward error 1.4e-06
float32 factor + float64 refining: forward error 1.4e-15
{'iters': 3, 'rel_residual': 2.10905197504417e-16, 'converged': True}
A few refinement steps take the float32 answer from about six correct digits
to the accuracy of the float64 solve.
info reports what happened:
itersis the number of corrections applied.rel_residualis \(\|b - Ax\|_\infty / \|b\|_\infty\) for the returned \(x\).convergedis true whenrel_tolwas met.rel_toldefaults to 0, which disables the test: refinement then runs until the residual stops improving forpatienceconsecutive steps (default 3), or formax_itersteps (default 20), and reportsconverged=Falseeven when it reached thefloat64floor. Pass arel_tolwhen you want the flag to mean something.
The returned \(x\) is always the best iterate seen, so a generous max_iter
never makes the answer worse.
What it buys#
The float32 factor stores its values in half the bytes. Both factors have
the same pattern, so their index arrays are the same size, and the total
saving is somewhat less than half:
assert chol64.nnz == chol32.nnz # same ordering, same pattern
print(f"factor values: float64 {chol64.nnz * 8 / 1e6:.2f} MB, float32 {chol32.nnz * 4 / 1e6:.2f} MB")
factor values: float64 0.54 MB, float32 0.27 MB
Time is a different matter. Here are both factorizations, and the solve phases, on a \(128 \times 128\) grid:
k2 = 128
A2 = mtl5.generators.poisson2d(k2, k2)
S2 = ms.to_scipy(A2)
b2 = S2 @ np.ones(S2.shape[0])
A2_32 = ms.from_scipy(S2.astype(np.float32))
print(f"{'':>16} {'factor f64':>11} {'solve f64':>10} {'factor f32':>11} {'refine':>8}")
for name, factor in (("cholesky", ms.cholesky), ("supernodal_ldlt", ms.supernodal_ldlt)):
t64, f64 = best_ms(lambda: factor(A2))
t32, f32 = best_ms(lambda: factor(A2_32))
ts, _ = best_ms(lambda: f64.solve(b2))
tr, (x, inf) = best_ms(lambda: iterative_refine(A2, f32, b2, rel_tol=1e-15))
assert inf["converged"]
print(f"{name:>16} {t64:9.1f}ms {ts:8.1f}ms {t32:9.1f}ms {tr:6.1f}ms ({inf['iters']} corrections)")
factor f64 solve f64 factor f32 refine
cholesky 65.9ms 1.1ms 53.2ms 4.4ms (4 corrections)
supernodal_ldlt 32.8ms 1.2ms 31.6ms 4.6ms (4 corrections)
On the CPU that built this page, the float32 factorization is not much
faster than the float64 one, and refinement adds a few solves. The sparse
factorizations here spend their time on index handling and scattered memory
access, not on wide arithmetic, so halving the width of the values does not
halve the time. Mixed precision pays off when:
memory is the limit. The factor is the largest object in a direct solve. Half the bytes of values can be the difference between a problem that fits and one that does not.
bandwidth is the limit. Each solve streams the whole factor from memory. With many right-hand sides, or repeated solves inside a Newton or time-stepping loop, the narrow factor moves half the bytes.
narrow arithmetic is much faster than wide. That is true of SIMD units, of GPUs, and of accelerators built around narrow number formats, such as Stillwater’s KPU. Splitting the work so that the factorization runs in the narrow format and the residual stays in
float64on the host is the patterniterative_refineis designed for.
When it fails: conditioning#
Refinement converges when the narrow factor is close enough to \(A\) that each
correction removes more error than it introduces. The rule of thumb is
\(\kappa(A)\,u_{\text{factor}} < 1\), where \(u\) is the unit roundoff of the
factor’s precision: \(6 \times 10^{-8}\) for float32, so \(\kappa(A)\) up to
about \(10^7\).
To see the limit, take the grid Laplacian with Neumann boundaries. It is singular, because the constant vector is in its nullspace, and adding \(\varepsilon I\) makes it SPD with smallest eigenvalue exactly \(\varepsilon\). Its largest is below 8 (no row sum of absolute values exceeds 8), so \(\kappa \approx 8/\varepsilon\), and \(\varepsilon\) dials in the conditioning.
The sweep also records whether the shift survives the cast to float32.
The diagonal entries are 2, 3 and 4. A shift rounds away when it is below
half the spacing of float32 numbers at that entry: \(1.2 \times 10^{-7}\) for
the entries 2 and 3, and \(2.4 \times 10^{-7}\) for 4. Between those, the shift
survives on some diagonal entries only. Below \(1.2 \times 10^{-7}\) it
survives on none: the float32 matrix is then the singular Laplacian itself,
and its factor’s last pivot is rounding noise rather than \(\varepsilon\). That is the
\(\kappa\,u_{\text{factor}} < 1\) limit made concrete. Whether Cholesky even
completes on such a matrix depends on the sign of that noise, so the sweep
falls back to supernodal_ldlt, which accepts a pivot of either sign, when
Cholesky raises.
T = sp.diags([-1.0, 2.0, -1.0], [-1, 0, 1], shape=(k, k)).tolil()
T[0, 0] = T[-1, -1] = 1.0 # Neumann ends
T = T.tocsr()
eye = sp.identity(k, format="csr")
neumann = (sp.kron(T, eye) + sp.kron(eye, T)).tocsr()
assert abs(neumann @ np.ones(n)).max() == 0 # singular: constants are in the nullspace
def shifted(eps):
return (neumann + eps * sp.identity(n, format="csr")).tocsr()
def factor32(M):
M32 = ms.from_scipy(M.astype(np.float32))
try:
return ms.cholesky(M32)
except RuntimeError: # a negative rounding-noise pivot
return ms.supernodal_ldlt(M32)
print(f"{'kappa':>8} {'shift kept':>10} {'factor':>16} {'corrections':>11} {'converged':>9} "
f"{'fwd err, refined':>17} {'fwd err, f64 direct':>20}")
sweep = {}
for eps in [1e-1, 1e-3, 1e-5, 1e-6, 1e-7, 1e-8, 1e-10]:
M = shifted(eps)
rhs = M @ x_true
# True only if the shift survives on every diagonal entry.
kept = bool((M.astype(np.float32).diagonal() != neumann.diagonal().astype(np.float32)).all())
f32 = factor32(M)
x, inf = iterative_refine(ms.from_scipy(M), f32, rhs, rel_tol=1e-14, max_iter=50)
x_d = ms.cholesky(ms.from_scipy(M)).solve(rhs).to_numpy()
sweep[eps] = (inf, fwd_err(x, x_true), fwd_err(x_d, x_true), f32, kept)
print(f"{8 / eps:8.0e} {str(kept):>10} {type(f32).__name__:>16} {inf['iters']:11d} "
f"{str(inf['converged']):>9} {fwd_err(x, x_true):17.1e} {fwd_err(x_d, x_true):20.1e}")
# The shift survives the cast down to eps = 1e-6, and refinement converges on all of those.
assert all(sweep[e][4] and sweep[e][0]["converged"] for e in (1e-1, 1e-3, 1e-5, 1e-6))
for e in (1e-7, 1e-8, 1e-10): # below 1.2e-7 the shift survives on no entry
assert (shifted(e).astype(np.float32).diagonal() == neumann.diagonal().astype(np.float32)).all()
# Well past the limit, it fails.
assert not any(sweep[e][0]["converged"] for e in (1e-8, 1e-10))
# Where it converges, the forward error is within kappa times the achieved
# relative residual (with a factor 10 of slack for mixing the 2-norm kappa
# with the infinity-norm residual).
for eps, (inf, err_refined, *_) in sweep.items():
if inf["converged"]:
assert err_refined < 10 * (8 / eps) * inf["rel_residual"], (eps, err_refined)
kappa shift kept factor corrections converged fwd err, refined fwd err, f64 direct
8e+01 True SparseCholesky_f32 3 True 6.8e-16 1.5e-15
8e+03 True SparseCholesky_f32 3 True 2.0e-14 7.4e-15
8e+05 True SparseCholesky_f32 5 True 1.8e-10 3.4e-13
8e+06 True SparseCholesky_f32 7 True 6.1e-11 6.9e-12
8e+07 False SparseCholesky_f32 12 True 3.8e-09 6.1e-11
8e+08 False SparseCholesky_f32 33 False 9.1e-04 4.2e-10
8e+10 False SparseCholesky_f32 8 False 1.3e-02 2.7e-08
Three things to read off the table:
While the shift survives the cast, refinement converges. It needs more steps as \(\kappa\) grows, because each step removes a smaller fraction of the error. The forward error grows with \(\kappa\) too. A residual bounds it, but only through the conditioning: \(\|x - x_*\| / \|x_*\| \le \kappa(A)\, \|b - Ax\| / \|b\|\), and the refined errors stay within that bound. They are not always as small as the
float64direct solve’s: refinement drives the residual to thefloat64level, and a small residual guarantees no more than the bound.Just past the limit, it may still converge, by luck. At \(\kappa \approx 8 \times 10^7\) the
float32factor is of the singular matrix, and whether refinement converges depends on how the rounding noise in its last pivot happens to fall. Do not rely on it.Well past it, refinement stalls. The corrections no longer contract,
convergedstays false, and the answer can be several orders of magnitude worse than thefloat64solve. Always pass arel_toland checkinfo["converged"]: a stalled refinement raises no error.
What to do instead: GMRES with the narrow factor#
The float32 factor is still a good preconditioner at those condition
numbers, even when it is too poor to drive plain refinement: it is wrong only
in the few directions that the shift was supposed to fix, and GMRES finds
those in a few iterations. Carson and Higham’s GMRES-based refinement uses it
that way: GMRES, run in float64, preconditioned by the narrow factor. The
same factor rescues both stalled cases:
for eps in (1e-8, 1e-10):
M = shifted(eps)
rhs = M @ x_true
_, err_refined, err_direct, f32, _ = sweep[eps]
P = spla.LinearOperator(
(n, n), matvec=lambda r, f=f32: f.solve(np.ravel(r).astype(np.float32)).to_numpy().astype(np.float64)
)
x, gm_info = spla.gmres(M, rhs, M=P, rtol=1e-14, restart=50, maxiter=20)
print(f"kappa {8 / eps:.0e}: GMRES info = {gm_info}, forward error {fwd_err(x, x_true):.1e} "
f"(refinement alone {err_refined:.1e}, float64 direct {err_direct:.1e})")
assert gm_info == 0
assert fwd_err(x, x_true) < 10 * err_direct
kappa 8e+08: GMRES info = 0, forward error 1.2e-09 (refinement alone 9.1e-04, float64 direct 4.2e-10)
kappa 8e+10: GMRES info = 0, forward error 5.7e-09 (refinement alone 1.3e-02, float64 direct 2.7e-08)
GMRES costs more per iteration than a refinement step, so use plain refinement while it converges and fall back to GMRES when it does not.
When it fails: underflow, and scaled=True#
A second failure has nothing to do with conditioning. float32 cannot
represent magnitudes much below \(10^{-38}\), and the residuals of a problem
whose data is that small underflow when they are cast into the float32
correction solve. Refinement then stalls at float32 accuracy, even on a
well-conditioned matrix.
scaled=True divides each residual by its norm before the correction solve,
and multiplies the correction back in float64. Only the shape of the
correction passes through the narrow factor; its size stays in float64.
tiny = 1e-40
b_tiny = b * tiny
for scaled in (False, True):
x, inf = iterative_refine(A, chol32, b_tiny, rel_tol=1e-14, scaled=scaled)
print(f"scaled={scaled!s:>5}: converged={inf['converged']!s:>5}, "
f"forward error {fwd_err(x, x_true * tiny):.1e}")
if scaled:
assert inf["converged"] and fwd_err(x, x_true * tiny) < 1e-13
else:
assert not inf["converged"] and fwd_err(x, x_true * tiny) > 1e-7
scaled=False: converged=False, forward error 4.2e-06
scaled= True: converged= True, forward error 2.4e-15
Scaling costs one extra pass over the residual per step. It matters most for
number formats with a much narrower exponent range than float32, such as
fp16 or the 8-bit formats. Those are available for dense matrices through
mtl5.mixed.lu_iterative_refine(A, b, working="fp16", scaled=True).
Scaling normalizes the residual, not the matrix. The factor still has to
represent \(A\), and its solve has to produce \(A^{-1}r/\|r\|\) without
overflowing. When the entries of \(A\) themselves sit near the edge of the
narrow format’s range, rescale the system first (multiply \(A\) and \(b\) by a
power of two that brings \(A\) to order one) or use a float64 factor.
Summary#
Situation |
What to use |
|---|---|
\(\kappa(A) \lesssim 10^7\), memory or bandwidth bound |
|
\(\kappa(A)\) larger, or refinement does not converge |
|
\(b\) near the bottom of the narrow format’s range |
|
\(A\) itself near the edge of the narrow format’s range |
rescale \(A\) and \(b\) first, or a |
the narrow factorization fails, or the cast makes \(A\) singular |
a |
none of the above, and time is the only concern on a CPU |
a |
mtl5.mixed.lu_iterative_refine(A, b, working=...) does the same for dense
matrices. Its factor can be in f32, fp16, fp8, a posit, a fixed-point or
a logarithmic format, which makes it the place to explore how narrow a factor
can get before refinement gives up.
API reference: mtl5.mixed.iterative_refine(), mtl5.mixed.lu_iterative_refine(), mtl5.sparse.cholesky(), mtl5.sparse.supernodal_ldlt(), mtl5.sparse.from_scipy().