Skip to content

Linear solvers

Choosing a linear solver

Everything shipped is pure JAX — jit/vmap-native, differentiable (Krylov on lax.custom_linear_solve, Newton on lax.custom_root), receives the assembler's BCOO operator directly (no densification), and composes with the periodic reduction and every parametric/inverse path. Pick by structure:

structure solver notes
SPD (Poisson, elasticity, mass) cg cheapest per iteration
non-symmetric (advection, SUPG) bicgstab / gmres bicgstab with jacobi() is the default
iterative preconditioner (inner Krylov, block/Schur) fgmres flexible right preconditioning — Saad, SISSC 14(2), 1993
symmetric indefinite (Stokes/Biot saddle, biharmonic) minres monotone residual, O(1) memory — Paige & Saunders, SINUM 12(4), 1975
complex-symmetric (A = Aᵀ, not Aᴴ: time-harmonic eddy-current/A–V, Helmholtz, RCWA) cocg CG's short recurrence over the bilinear form xᵀy — O(n) memory and one matvec per step where gmres needs a (restart, n) basis. Only valid when the operator really is complex-symmetric; it can break down where CG cannot — van der Vorst & Melissen, IEEE Trans. Magn. 26(2), 1990
SPD, batched/GPU-heavy chebyshev inner-product free (no reductions) — Golub & Varga 1961
indefinite lu sparse-direct; vmaps on every backend — host/cudss/pardiso factor once for a batch against one matrix, the default device backend factors each system (jno.setup(lu_stack=k) stacks k per call)
cuSolver refuses it, or is slow lu(backend="host") SuperLU on the host, driven from the device — same answer, same gradients. Often faster than cuSolver, and runs meshes it rejects
shift-invert eigs, or a constant-operator transient lu(backend="cudss") NVIDIA cuDSS. Fastest per solve — caches the symbolic plan on the sparsity, so it survives a change of values. Needs the optional stack
a Newton loop (or no GPU / a factorization too big for device memory) lu(backend="pardiso") Intel MKL PARDISO, multithreaded CPU. Fastest factorization — a Newton step reuses the analysis. x86-64
a Newton march (the tangent changes every iteration) lu(backend="host", reuse=False) the host factorization cache keys on the operator, so a never-repeating tangent fills it and leaks a factorization a step; reuse=False drops each one
small systems / coarse blocks dense LAPACK, vmap-native

jNO warns you when this applies

jno.fem detects a saddle system structurally at build time — a field whose own test function never meets its own trial function contributes no diagonal block — and fem.solve() warns, naming the field, when it is about to use the matrix-free default on one. It warns rather than refuses: a 2-D saddle of moderate size does solve acceptably that way.

Passing linear= or precond= silences it, since that is the deliberate choice it asks for. The detection is structural, so it holds in every mode with no tangent to assemble, and it fires under jit/vmap/grad — which matters, because the runtime residual guard needs a concrete residual and steps aside on a tracer, leaving a transformed solve otherwise unguarded.

Warm starts — what a starting point actually buys

A starting point is set on the fields, u.initialize(u0) (see the FEM guide: number, nodal array or formula). It is free to give and easy to misjudge, so here is the rule, measured. A Krylov solve has to cover the distance from its initial residual down to rtol. A warm start removes the decades it already starts below, so the fraction of iterations saved is a ratio of logarithms — not a ratio of errors:

\[\text{saved} \;\approx\; \frac{\log_{10}(1/\varepsilon)}{\log_{10}(1/\texttt{rtol})}\]

with ε the relative error of the guess. At rtol = 1e-10, a guess good to 1 % removes one fifth of the work — and a guess good to 10 % removes one tenth, which is usually not worth arranging.

Jacobi-CG, 2-D diffusion with a 10× conductivity blob, 791 DOFs, rtol = 1e-10

Cold (x0 = 0) is 85 iterations. Two initial errors of the same norm were compared: a smooth one (a low-frequency field) and a rough one (white noise).

rel. error ε smooth x0 rough x0 law predicts
3e-01 78 93 81
1e-01 74 90 76
1e-02 67 85 68
1e-03 61 76 59
1e-04 52 67 51
1e-06 35 53 34

The law tracks the smooth column to within 1–3 iterations across five decades. The rough column does not follow it at all: a rough guess accurate to 1 % costs exactly what a cold start costs, and a rough guess at 30 % is worse than starting from zero.

The spectrum of the initial error matters, not its norm. Krylov convergence is governed by how the error is distributed over the spectrum (Greenbaum, Iterative Methods for Solving Linear Systems, SIAM 1997, ch. 3), and a guess that is pointwise close but rough injects high-frequency error the method must then remove. This is why the previous solve in a sweep or a time step is such a good warm start — it is smooth, and it is wrong in the same modes the operator is about to correct.

A neural surrogate is a poor warm start, measured

The tempting idea — train a network to predict the solution, feed it as x0 — does not clear the bar.

On the sweep above, against a cold start: an MLP predicting DOF values directly came in at −2 % (i.e. slower than cold, its output being spectrally rough), and predicting POD coefficients instead — whose output is smooth by construction, being a combination of smooth modes — recovered only +5 %. Both lost to the trivial baseline of reusing the nearest stored snapshot (+9 %), which costs nothing to build.

The arithmetic is why, and it is not an engineering problem: at a realistic surrogate accuracy of 1e-2 to 1e-3 the law caps the prize at 20–30 %, and collecting it needs an output that is smooth as well as accurate. Reach for a warm start where a nearby solve already exists — a continuation sweep (jno.solve.continuation, which warm-starts for you), a transient step (which warm-starts automatically), or a Newton loop. Those are smooth by construction and free.

A learned subspace is worth far more than a learned point

The failure above is a failure of regression, not of learning. Fit a network to predict a point and it optimises the wrong norm; CG minimises ‖e‖_A, and an L2 fit is blind to how the error sits on the spectrum. Give it a subspace instead and there are two much better things to do with it, both already expressible with the slots on this page.

1. Solve in the subspace rather than regressing into it. The A-orthogonal projection U(UᵀAU)⁻¹Uᵀb is the provably best starting point from span(U) — and it is exactly what fem.solve(basis=U) computes, certificate included.

2. Put the subspace in the preconditioner, as a coarse-space correction M⁻¹ = diag⁻¹ + U(UᵀAU)⁻¹Uᵀ (Nicolaides, SINUM 24(2), 1987, 355; Frank & Vuik, SISC 23(2), 2001, 442). This needs no new API — precond= takes a bare ctx -> applier:

def coarse_jacobi(U):                       # Jacobi + a coarse solve on span(U)
    def spec(ctx):
        AU   = jnp.stack([ctx.A @ U[:, j] for j in range(U.shape[1])], axis=1)
        Einv = jnp.linalg.inv(U.T @ AU)
        dinv = 1.0 / ctx.diag()
        return lambda v: dinv * v + U @ (Einv @ (U.T @ v))
    return spec

u = fem.solve(linear=jno.solve.cg(), precond=coarse_jacobi(U), basis=None)

Same problem, same rank-8 POD subspace, iterations against a cold Jacobi-CG

what the subspace is used for saved
MLP regressing DOF values → x0 −2.7 %
MLP regressing POD coefficients → x0 +3.9 %
nearest stored snapshot → x0 +8.6 %
basis=U (A-optimal projection) → x0 +18.0 %
coarse-space preconditioner +27.5 %
both together +39.8 %

The L2-fitted network's energy-norm error was 17–77× larger than the A-optimal projection from the very same subspace — the whole gap between the first rows and the fourth is the wrong norm, not a weak network.

And the two are different in kind — only one improves with size
h DOFs cold x0 saves coarse-space saves
0.060 377 60 21.7 % 21.7 %
0.040 791 86 17.4 % 25.6 %
0.030 1394 113 17.7 % 28.3 %
0.022 2522 151 17.2 % 29.8 %

A warm start is a constant offset — it removes decades of residual and the log law fixes the fraction, so it stays flat under refinement. A coarse space removes the slow modes from the spectrum, so its benefit grows with the problem. Prefer it wherever the subspace is worth building at all.

Scope, since this was measured on one problem class: SPD + CG, a rank-8 POD subspace from snapshots, a 10× conductivity contrast. Non-symmetric and saddle-point systems are not covered here, the rank/cost trade-off is unexplored (each application costs two n × k products and a k × k solve), and POD alone already delivers the table — a learned subspace has to beat POD to earn its place, which is not shown.

Two that are not Ax = b on a square, definite operator

minres and lstsq cover the cases the table's other rows cannot, and both take a jno.solve.LinearOperator (or a BCOO, or a dense array) directly — no FEM required:

op = jno.solve.LinearOperator(K)          # K symmetric but INDEFINITE — cg cannot be used
x  = jno.solve.minres(tol=1e-12)(op, b)   # rel-resid 7.3e-13

xl = jno.solve.lstsq(A, b, atol=1e-12, btol=1e-12)   # A RECTANGULAR (80 x 30), min ‖Ax − b‖
xd = jno.solve.lstsq(A, b, damp=0.5)                 # + Tikhonov damp²‖x‖² — ill-posed inverses

Checked against dense oracles

minres on a spectrum straddling zero (eigenvalues in [-3, -0.5] ∪ [0.5, 3]) reaches a 7.3e-13 relative residual, where cg has no convergence theory at all. lstsq matches numpy.linalg.lstsq to 7.5e-13, and with damp=0.5 matches the Tikhonov normal equations (AᵀA + damp²I)x = Aᵀb to 5.1e-12.

Direct backends

Four lu backends, and the choice is not obvious — the fastest one depends on which phase your problem repeats.

Pick by the phase that repeats

A Newton loop re-factorizes every iteration → PARDISO (220× over SuperLU, vs cuDSS's 115×). A shift-invert eigensolve or constant-operator transient re-solves against one factorization → cuDSS, ~11× faster per solve and it takes a whole block of right-hand sides at once.

There is deliberately no auto: which wins depends on hardware jNO cannot inspect. Install both with pip install jax-numerical-operators[fem].

Which backend lu() means

With no backend=, jno.solve.lu() is "cudss" on a GPU where cuDSS is installed and float64 is on, and "device" everywhere else.

So is a parametric form solved with no linear= at all. cuSolver's spsolve is a QR, and against cuDSS it loses by more with every size: one parametric solve on an RTX 3070 took 280 ms against 11 ms at 7.6 k P2 dofs, 2.4 s against 36 ms at 13 k P1 elasticity dofs, and over 240 s against 0.13 s at 49 k P2 dofs.

The answers and every derivative mode agree to round-off (tests/test_default_direct_solve.py). The solve's log line names the backend that ran; backend="device" asks for cuSolver by name.

backend="host" — SuperLU on the host

factors on the HOST (SuperLU) and drives it from the device; same answer and same gradients (wrapped in custom_linear_solve, transpose via SuperLU trans="T").

Measured faster where cuSolver also works — Stokes 21,839 DOFs 0.27 s vs 1.67 s, H(curl) 17,072 complex DOFs 13.3 s vs 36.4 s — and it runs meshes cuSolver rejects (Stokes 26,908, H(curl) 26,154, both of which fail on GPU). Affordable because a direct solve factorises once: the operator crosses PCIe once, not per iteration. Read the win as cuSolver's sparse LU is weak, not GPUs lose — see the row below

backend="cudss" — NVIDIA cuDSS

NVIDIA cuDSS — the fastest direct backend wherever it runs, because it separates the symbolic plan from the numeric factorization and jNO caches on the sparsity, so the plan survives a change of values. Against backend="host" on an RTX 3070 (fp64 at 1/64 rate — the unfavourable card): Stokes saddle factorization 3.4 ms vs 79.9 ms, lap3d 50³ 576 ms vs 64,856 ms, and 64.7× per Newton step at n=64,000. Also factors the Stokes saddle cuSolver calls singular, with smaller residuals.

Needs the optional stack (nvmath-python, cudss, cupy); raises a clear ImportError otherwise.

Fill-in still governs 3-D (69×→218× nnz growth at lap3d 20³–40³), so it moves the ceiling and makes device memory the binding constraint — it is not a substitute for a preconditioner.

Two things happen automatically: a block right-hand side (n, k) is solved in one call (measured 2.7× at k=4 to 5.4× at k=16 over the same factorization solved column by column — this is what the shift-invert eigensolver's block Krylov sweep needs), and an exactly symmetric operator is factored as LDLᵀ instead of general LU (1.41× faster, 1.38× less peak device memory on lap3d 40³).

Symmetry is tested to within a few ulps rather than bitwise — an assembled FEM tangent for a symmetric form is symmetric only up to assembly round-off (a vector element block contracts components in a different order for (a,i),(b,j) than for (b,j),(a,i), measured 0.25 ulps), so a bitwise rule sent every vector and coupled problem down the general-LU branch.

Within the gate the two triangles are averaged, a correction bounded by the asymmetry it removes and therefore no larger than the round-off already in the matrix; outside it nothing is touched.

The margin is not a knife-edge: the weakest genuine asymmetry that can be constructed — an advection coefficient of 1e-12, meaningless beside the Laplacian — is already 191 ulps. Measured end-to-end on a 3-D vector tangent, general → symmetric is 1.07–1.13× at 3.4k–11.8k DOFs (growing with size) and 1.10–1.62× on lap3d 20³–50³.

The rest of the rule stands: symmetry is still tested and SPD is never inferred — a matrix symmetric only to ~1e-15 would otherwise be silently factored as (A+Aᵀ)/2, and a wrong SPD guess returns NaN.

A replaced pivot is first given iterative refinement against the true matrix (Wilkinson 1963 — the remedy cuDSS's own docs prescribe), so a zero-pivot-but-nonsingular operator or a marginally conditioned saddle is solved (refined to ~1e-10 per solve, one SpMV per step) rather than refused; a genuinely singular operator — one whose refinement residual will not contract — still raises: cuDSS signals it through neither an exception nor a NaN, returning a finite plausible vector instead.

A factor call with the values the slot's factors already came from runs no factorisation (one compare on the device): a constant operator solved at every step of a march, or a frozen auxiliary solve inside an optimisation step, is factored once.

backend="pardiso" — Intel MKL PARDISO

Intel MKL PARDISO, multithreaded CPU. The fastest factorization of the four, and like cuDSS it splits symbolic analysis from numeric factorization, so a Newton step reuses the analysis. On lap3d 50³ (n=125,000) against single-threaded SuperLU's 65,212 ms: factorization 298 ms, Newton re-factorization 296 ms — 220×, where cuDSS reaches 115×. Its adjoint is cheaper too — Aᵀx = b comes from the same factorization rather than a second one.

An exactly symmetric operator uses LDLᵀ (1.9× on lap3d 50³, 13× on a saddle), which needs the upper triangle with an explicit diagonal — without that a saddle's constraint rows come back empty and PARDISO rejects the matrix. Like cuDSS it returns finite garbage on a singular operator, so jNO checks the perturbed-pivot count and raises. pip install jax-numerical-operators[pardiso], x86-64

A direct backend can return finite garbage on a singular operator

Neither cuDSS nor PARDISO signals singularity through an exception or a NaN — both return a finite, plausible-looking vector. jNO checks (the refinement residual for cuDSS, the perturbed-pivot count for PARDISO) and raises instead.

Host SuperLU (backend="host", and the default lu() / newton(direct=True) on the CPU, which is JAX's spsolve calling scipy) fails in three different ways, depending on pivoting luck:

  • it aborts ("failed to factorize matrix at line 413 in file …/dpanel_bmod.c", after a burst of BLAS "On entry to DTRSV parameter number 6 had an illegal value" lines printed from C, which jNO cannot suppress). fem.solve turns this into a RuntimeError naming a singular / structurally rank-deficient operator, its size, SuperLU's own message and the same hints the cuDSS error gives. Measured on a three-field u–p–s saddle with continuous P1 stress (a known-incompatible space, singular by construction) at 3334 DOFs.
  • splu (backend="host") reports Factor is exactly singular. That is named the same way, with the exact matrix size.
  • JAX's spsolve answers an exactly singular matrix with NaN. The Newton verdict then reports a non-finite residual and points at a singular tangent, not at max_steps.

The same form at 2582 DOFs or fewer factors without complaint and returns a finite answer that is wrong in the null space. Nothing per-solve detects that, because detecting it would cost a residual product on every solve.

Inside a Newton solve the convergence verdict catches it only if the wrong null-space component also stops the residual from falling. A consistent singular system can still converge, with an arbitrary null-space component. Outside Newton, check ‖Ax − b‖ yourself, or use cuDSS or PARDISO, which check. Naming the error costs nothing on a successful solve, because it runs only on the failure path.

Forms that share an operator — one factorisation

Several forms that differ only in their load — one per drive, load case, incident direction or sample — have the same operator.

When one evaluation (a jno.core loss, a crux.eval([...]) list) solves several of them with the same solver spec, jNO factorizes once: every member's system is assembled, the first member's matrix takes the whole block of right-hand sides, and each member gets its column back. cuDSS and PARDISO take the block in one call, for the forward solve and the adjoint alike; host SuperLU reuses its cached factorization.

Nothing is passed to ask for it. Each column is still checked against its own member's matrix by the residual gate, so two forms that only looked alike raise instead of sharing a wrong factorization. Likewise, a solve (or an integral) that an expression refers to several times is evaluated once per evaluation.

Batched solves and operator storage — jno.setup(lu_stack=, matvec_format=)

Every lu backend has a vmap rule, so jax.jacrev / jax.jacfwd through a solve and a vmap over solves work on all four. host, cudss and pardiso factor once for a batch against one matrix and solve the whole block of right-hand sides in one call — the choice for Jacobians and sensitivities.

The default device backend (cuSolver) takes one right-hand side, so it factors every system: one per call by default, or k per block-diagonal call with jno.setup(__file__, lu_stack=k) (or lu_stack = k under [jno] in .jno.toml). A larger k measured faster, but cuSolver allocates for the fill-in of all k systems, so the right k depends on the problem and the card; too large fails with a cuSolver allocation error, never a wrong answer.

The iterative solvers apply a sparse operator as cuSPARSE CSR or as split COO, chosen by timing both on the running device, once per operator size class (matvec_format="auto", the default). jno.setup(__file__, matvec_format="csr") or "coo" (or [jno] matvec_format) forces one — for reproducible timings, or to rule the choice out while debugging.

Complex problems

Complex problems are assembled as one real 2n system over the stacked [Re; Im] state — the real-equivalent block [[A_r, -A_i], [A_i, A_r]] — at assembly rather than at solve time.

A complex transient is therefore an ordinary transient block (the slots configure its per-step solve as above, and theta / adaptive / exponential all apply), and a complex steady problem is an ordinary linear system: the linear / precond slots and a start work on it: A.initialize(a0) with a complex a0 fills both real parts for you. Its default solver stays sparse-direct, not the matrix-free BiCGStab real elliptic systems get — the real-equivalent block is indefinite for Helmholtz/PML, where Jacobi-BiCGStab does not converge.

Two exceptions keep a dedicated path: a complex-native preconditioner (ams) solves A_r + i·A_i directly rather than the block, so the Re/Im legs are retained for it; and lu(backend="cudss") on a complex-symmetric operator factors the n×n complex matrix with LDLᵀ inside the program instead of the real 2n block.

Bloch (quasi-periodic) ties

A Bloch (quasi-periodic) tie fuses like everything else. Its complex prolongation P cannot reduce the Re/Im legs independently, but on the fused [Re; Im] state the same tie is the real prolongation B(P) = [[P_r, -P_i], [P_i, P_r]], and the ordinary real congruence B(P)ᵀ A B(P) equals the Hermitian reduction P^H A_c P the Bloch space requires.

Consequences: solve_fn=, the linear/precond slots and x0= all apply to a Bloch problem (each used to be silently discarded by a dedicated block routine); a Bloch tie composes with a complex transient (the quasi-periodic plane-wave march, previously a dtype crash); and a real weak form with a Bloch tie is promoted to the complex path automatically — the phase makes the field complex anyway, and the real path's bilinear Pᵀ A P is not a Galerkin projection for a complex P (measured 8.1 rel-L2 off the Hermitian answer on a manufactured mode, with the tie itself satisfied exactly).

A coupled (multi-field) complex steady system — coupled Helmholtz-type equations — takes the same Re/Im split through the coupled assembler: one fused real 2n block over [Re_all; Im_all], with fem.offsets still listing the per-field blocks of the recombined complex solution. Scope: steady and linear (a complex nonlinear coupled form and a complex coupled transient refuse, as everywhere).

Essential values on a complex form must be real. The two legs share one Dirichlet row set, which imposes Re u = g with Im u = 0 — right for a real g, and the usual case (the complexity lives in the operator and the source).

A complex g is not expressible there: pinning Im u = g_i would need the imaginary leg's rows zeroed rather than set to identity, and the symmetric elimination's known-column lift is cross-leg (the real equation needs A_r[:,j] g_r - A_i[:,j] g_i, which no per-leg elimination produces). It raises a clear error. Carry the complex part in the operator or the source.

adapt= composes with a complex transient too: the stacked [Re; Im] halves transfer across each remesh as a doubled field layout, the modulus |u| drives the remesh metric (refining on Re alone would miss a rotating phase), and the saved frames come back complex. A criterion= is refused there by name: it would be assembled against the stacked real state, whose halves it cannot tell apart. Drop it to remesh on the modulus.

Not yet supported (clear errors): a Bloch tie on a real transient march (the phase forces a complex field — make the problem complex, or use a plain tie) or on a nonlinear form (complex nonlinear forms are not wired).