Writing your own and diagnostics
Writing your own
User extension is duck-typed — a linear solver is any fn(A, b, *, M=None, x0=None) -> x with A a
jno.solve.LinearOperator (.mv, .T, .diag(), .bcoo, .dense()); a preconditioner is any
ctx -> (v -> M⁻¹v):
def my_precond(ctx): # ctx.A, ctx.diag(), ctx.fem
inv = 1.0 / ctx.diag()
return lambda v: inv * v
u = fem.solve(linear=jno.solve.cg(), precond=my_precond)
Calling a solver directly (outside fem.solve) takes the preconditioner as M=, which is the
application v -> M⁻¹v. A jno.precond.* spec is accepted there too and materialized against A on
the way in — jno.solve.cg()(A, b, M=jno.precond.jacobi()).
A bare callable is always the applier, never a ctx -> applier factory: as a precond= slot it
would be the factory, nothing about a callable tells the two apart, and guessing wrong would apply a
preconditioner you did not ask for. Specs that need eager preparation (form, which assembles an
auxiliary operator) require fem.solve(precond=...) — a direct call has no owning FEM.
A direct call to a Krylov solver also takes rtol= for that one call, overriding the spec's tol
(jno.solve.cg()(A, b, rtol=1e-4)) — how Newton passes its forcing term. cg, bicgstab, gmres,
fgmres, minres and cocg accept it; the other solvers raise a TypeError that says to set the
tolerance on the spec.
solve_fn= is the level below that: instead of a slot, you take the assembled system and return
the answer. jNO does nothing to it — no firewall, no convergence gate — so it is the escape hatch for
a solver that fits none of the shapes above:
u = fem.solve(solve_fn=lambda A, b: jnp.linalg.solve(A.todense(), b)) # dense LAPACK
# max|u - default| = 2.9e-10 on a 142-DOF Poisson operator
A arrives exactly as assembled — a BCOO, not a densified copy. That is deliberate: densifying is
O(n²) on an O(nnz) operator (20.5 GiB against 9.4 MiB at n=51,843), so it would make bringing a
sparse solver pointless at the sizes where you would want one. Call .todense() yourself if that is
what you need, as above.
If your callable is pure JAX it inherits jit/vmap/AD automatically. On the matrix-free nonlinear
path (newton(direct=False), picard(), or no assembled tangent) the precond spec is materialized
per Newton/Picard linearization against the JVP operator — so form, inner(...), chebyshev, a
pre-built amg, and their block_diag/triangular compositions all work; only specs that need the
assembled matrix (jacobi, an unbuilt amg) raise. The default Newton materializes the spec against
the assembled tangent instead.
Diagnostics — what the solver actually did
What a solve prints
Every build and solve logs one line each for what was built, which solver ran, and what came back:
INFO: Preprocessed mesh connectivity: 85 points, 133 triangles · h 0.0927–0.141 · worst aspect 1.38
INFO: FEM(linear, dofs=85, terms=['volume', 'dirichlet@boundary'])
INFO: solve: linear · bicgstab (matrix-free) + jacobi
INFO: solved: linear · 0.115 s · u in [0, 0.06101]
FEM(...)is the mode fixed at build and every term as jNO classified it. A boundary condition that landed nowhere is missing here.solve:is the route actually taken, including defaults you did not pass.solved:is the solution range, withALL ZERO — is the load term present?when the right-hand side was empty. A march adds its steps and the step that came closest to its tolerance:
INFO: solved: nonlinear · 0.454 s · load-path march · 40 steps over τ ∈ [0, 1] · tightest step 32 (τ=0.7949) at 82.9% of its bound · u in [0, 0.8375]
The lines cost the solve nothing it does not already pay. Nothing is added inside a traced computation: a jitted transient march compiles to the same program with or without them.
The solved: line reduces the solution on the device and moves four numbers to the host (0.3 ms against
a 63 ms solve at 73k dofs on a GPU). It skips itself when the solve is traced (jit/grad/jno.core).
It does not compute ‖Au − b‖: that is a sparse matvec, 10 % of the same solve, and the solve already
checks its own residual and raises (below). Ask for it with jno.info(sol,
context=fem). gmsh's own progress output is suppressed; its warnings are
logged as WARNING: gmsh: ….
fem.stats
After any fem.solve(), fem.stats reports what happened without changing the solve's return: mode,
dofs, wall_s (dispatch time — JAX is async; block on the result for compute time), the
linear/precond slot reprs, nonlinear (driver, final residual norm against its bound, converged
flag, and the step count — every driver reports it), linear_iterations (below), and amgx_cache
occupancy when jaxamg served the solve.
Populated on eager paths; a solve wrapped whole in jit/vmap/grad records the slots but no residuals
— reporting needs a concrete value. The convergence check below is not so limited: it fires under a
transform too.
sol = fem.solve(nonlinear=jno.solve.newton(direct=True), linear=jno.solve.lu(backend="host"))
fem.stats
# {'mode': 'nonlinear', 'dofs': 44, 'wall_s': 0.31, 'linear': 'jno.solve.lu-host(...)',
# 'precond': None, 'nonlinear': {'driver': 'newton_direct', 'residual': 1.6e-07,
# 'bound': 1.7e-06, 'steps': 3, 'converged': True}}
solve_index counts solves on the form (the first one includes tracing and compilation), and a solve
that raised still writes fem.stats, with an error entry. It used to leave the previous solve's
stats in place, and those would read as this solve's.
Krylov iterations — fem.stats["linear_iterations"]
How many iterations each linear solve took — the number that says whether a preconditioner works:
fem.solve(nonlinear=jno.solve.newton(direct=False))
fem.stats["linear_iterations"]
# {'solves': 4, 'iterations': [...], 'total': ..., 'max': ...,
# 'by': ['the newton_krylov inner Jacobi-BiCGStab']} # one count per Newton step
iterations lists each forward solve's count in the order they finished, and transpose the adjoint
solves' when a gradient ran any. breakdown: True flags a BiCGStab that stopped on one. The default
solve, cg, bicgstab, minres, fgmres, cocg, chebyshev, the matrix-free Newton's inner
Jacobi-BiCGStab and the assembled-tangent Krylov all report.
Upstream restarted gmres exposes no count and is listed under uncounted; a direct factorisation
reports None. Counts are recorded for an eager, steady, non-adaptive solve. A march records none per
step — its compiled step makes no host call, and fem.stats["march"] is its record — and neither does a
deferred node evaluated later under jno.core.
cg and bicgstab are jax.scipy's own loops, keeping the iteration count they discard: the same
arithmetic (x identical on CPU, within 1e-10 on GPU from reduction order) and the same time. The count
reaches the host through one callback per solve, a fixed ~0.08 ms (CPU) / ~0.15 ms (GPU): +7–11 % on a
790-DOF solve, unmeasurable at 46,691 DOFs.
A march records every step — fem.stats["march"]
A march (a tau= load path, an arc-length path, continuation=, a transient) records what each step
did. grid is the coordinate at each step. residual and bound are each step's final residual and
the tolerance it was judged against. step_s is each step's wall time:
| march | per-step residual | per-step time |
|---|---|---|
| load path, arc-length | ✅ | — one compiled lax.scan: only the mean wall_s / steps |
continuation= |
✅ nonlinear | ✅ every rung is materialised, so its time is real compute |
| transient, nonlinear | ✅ once evaluated | — one compiled lax.scan |
| transient, linear | — | — one compiled lax.scan |
A step inside a lax.scan is not a host-visible event, so no per-step time is reported for it rather
than an invented one. A transient solve returns a deferred node: its record says deferred=True with
the step count, dt and window until the node is evaluated eagerly (.fn()), which adds the
evaluation's wall_s and an evaluation count. Under jno.core the march runs inside a compiled
program and nothing is recorded.
A march that fails keeps its record up to and including the failing step, at the same 1-based index
the error names. jno.info(fem) renders it:
march
kind load-path march
steps 12 over τ ∈ [0, 1]
time 542 ms for the solve · mean 45.1 ms/step — includes compilation
one compiled lax.scan: a step has no wall time of its own, only the mean
convergence all 12 steps converged · tightest step 11 (τ=0.9091): residual at 45.6% of its bound
"Tightest" is the step that came closest to its bound, which is the first place to look when a finer
grid or a harder load is about to break the march. jno.info(fem, deep=True) lists every step.
A solve that did not converge raises — including the adjoint
Every linear solve is residual-checked against its own operator before it returns, and so is its
transpose — the plain fem.solve() default included. That matters because a Krylov iteration leaving on its step cap returns the last iterate
with no signal at all, so a broken solve is otherwise indistinguishable from a good one:
jax.grad(loss)(theta)
# RuntimeError: jno.solve.fgmres did not solve the system: relative residual 2.8e-02 against a
# 1e-04 gate. This is the ADJOINT (transpose) solve, not the forward one -- the solution itself is
# fine and only the GRADIENT is affected. A Krylov method can break down on A^T where it converges
# on A, so reach for a transposable-robust inner solver (jno.solve.gmres(), jno.solve.lu()) or a
# preconditioner rather than loosening the tolerance.
Where the refusal surfaces — dispatch is asynchronous
The gate is evaluated inside the traced solve, and reports through a host callback. JAX dispatch is asynchronous, so that callback has typically not run when the solve returns: the refusal appears only once something materialises the result. Measured on the same failing solve, the raise reaches the caller on the CPU backend (callbacks run inline) and is swallowed into a log line on GPU.
So the failure is recorded first and raised at a boundary that is guaranteed to exist:
| you called | when it raises |
|---|---|
fem.solve(...) |
at the call — the result is materialised and the gate drained before returning |
an eager jno.solve.cg()(A, b) |
at the call, same way |
your own jax.jit / jax.grad around a solve |
jNO has no post-execution hook there. The failure is recorded, and the raise from the callback is best-effort — it lands on some backends and not others |
The last row is a real limit, not an oversight: once the solve is inside your transform, the
library gets no callback after it executes. If you need certainty there, materialise inside the
transform-free part and let fem.solve do the checking.
Why the adjoint gets its own check
The adjoint is the half nothing used to check. lax.custom_linear_solve's transpose_solve had
no convergence test, and the eager test on the forward solve is a no-op under tracers — so the
guard was off precisely when gradients were being taken.
Measured on a 2-D strong-form Poisson operator: BiCGStab converged on A (relative residual
2.9e-05) and diverged to 5.5e+26 on Aᵀ for the same problem. The last iterate came back as
a gradient wrong by twenty orders of magnitude, and nothing anywhere raised.
Cost is one extra matvec per solve. The host round-trip that reports the failure sits in the
failing branch, so a converged solve never pays for it: 0.32 ms against 0.24 ms per call on a
small dense GMRES, and no measurable difference on the reverse pass. The fem.solve() default
got faster — 1.90 ms against 2.73 ms at 1441 DOFs — because checking from inside the trace
replaced an eager check that cost its own matvec plus a host sync.
A transient march judges every step, not just the last one
A nonlinear transient step is a Newton solve, and every one of them runs inside the march's
lax.scan — precisely where the driver's own convergence check disables itself, because it needs a
concrete residual. So the step carries its residual norms out of the scan and fem.solve() tests
them where they are concrete, against the driver's own rtol/atol:
fem.solve(nonlinear=jno.solve.newton(direct=True, rtol=1e-6, atol=1e-6))
# RuntimeError: fem.solve: the transient march did not converge at step 36 of 120 (t=0.00036):
# residual norm 3.658e+02 against the tolerance atol + rtol*||r(u_prev)|| = 1.011e-02
# (atol=1e-06, rtol=1e-06). That step is NOT a root, and every later step inherited it as its
# starting state — the whole trajectory past this point is unreliable. Globalize the per-step solve
# (jno.solve.newton(line_search=True), or damping<1), take smaller time steps (a finer
# domain(time=(...)) grid), or raise the driver's max_steps.
This is the same check the load-path march already applied, on the same
numbers; only the label and the advice differ. It covers the default θ march, jno.solve.bdf2() and
jno.solve.sdirk() (judged per stage: every stage is a Newton solve).
Why a silent transient failure is worse than it sounds
Two properties make a capped march genuinely hard to spot, both measured on a coupled melt-pool model (laser + phase change + Marangoni convection):
- It is not reproducible. Two runs of the same command reported peak melt velocities of 2.98 and 33.5 m/s — an unconverged iterate is whatever the step cap happened to leave.
- A diverged march is faster than a healthy one. Once the residual is NaN the loop
condition
||r|| > tolis False, so Newton exits on its first iteration and every remaining step is nearly free. The usual "it got slow, something is wrong" signal is inverted: the run that finished quickly was the broken one, and it returned 2e+200 K with nothing raised.
Cost is two residual evaluations per step, and only on a nonlinear block — a linear step is a linear solve with its own gate and is not judged here.
Under a transform the guard is off
Inside jax.jit/grad/vmap of a whole march the norms are themselves traced, so the test
cannot concretise and no-ops — the same trade every eager check in jNO makes. There, the
driver's max_steps is all there is.
A preconditioner is exempt — it is inexact on purpose
jno.precond.inner(jno.solve.cg(tol=1e-2, maxiter=30)) asks for two digits deliberately; that
is the whole reason the outer solver must be flexible (jno.solve.fgmres()). The gate is a
property of the call, not of the solver spec: the same cg() is checked as an outer solve
and unchecked as a preconditioner application. The convergence contract belongs to the outer
solve, and that one is still gated.
Watching a solve while it runs — log=
The lines above come before and after a solve. To follow one while it runs, give it log=:
u = fem.solve(log=True) # each Newton step
# INFO: newton step 1: residual 2.636e-03 (target 1.0e-08), forcing 1.0e-01
# INFO: newton step 2: residual 2.554e-04 (target 1.0e-08), forcing 1.0e-01
# ...
traj = fem.solve(log=100).fn() # every 100th time step and the last (a transient solve runs at .fn())
lam, X = K.eigs(mass=m, k=6, precond=jno.precond.jacobi(), log=10)
crux.solve(epochs=50_000, log=1000) # the training line every 1000 epochs
log=True reports every step, log=N every N-th step of each loop and always its last, log=False (the
default) nothing.
| Solve | What log= reports |
|---|---|
fem.solve / fdm.solve, nonlinear |
each Newton step: residual, its target, the forcing term |
a transient march (fem or fdm) |
each time step: step, t, max \|u\|, after that step's Newton lines |
fem.eigs with precond= (LOBPCG) or sigma= |
each iteration: residual and its target |
jno.core(...).solve |
the training line every N epochs (default: a tenth of the run, a thousandth above 100 000 epochs; log=False: none) |
A linear steady solve reports nothing extra (its only loop is the Krylov iteration), and neither does the non-symmetric eigensolver, whose Arnoldi iteration runs inside ARPACK.
Each solve reports only when it is given log=. A jno.fem inside a jno.core loss
(expr.integrate(fem), or a fem.solve() node) stays quiet, so the training lines stay readable; a
fem.solve(log=True) there reports its Newton steps on every epoch, before that epoch's training line.
The lines come from inside the compiled program without stopping it: each reported step writes a few
numbers into a buffer in host memory, and a reader thread prints them, so the device never waits for
Python as it would for a jax.debug.callback. Without log= nothing is added: the solve compiles to the
same program as before.
Where the time went — fem.solve(profile=True)
fem.stats says what the solver did; profile=True says how long and where. It runs the solve
inside a JAX Perfetto trace, prints the DOF count and wall time, and writes the trace to
./jno_traces for chrome://tracing or ui.perfetto.dev:
u = fem.solve(profile=True)
# [fem profile · 75 DOFs · linear] wall 82.8 ms · Perfetto trace → ./jno_traces
The same flag exists on jno.core(...).solve(profile=True) (see
Evaluation) and on jno.rcwa(...).solve(profile=True).
Profile a concrete solve
It runs eagerly, at the current parameter values. A parametric solve returns a deferred trace
node with no numeric work to time, so there is nothing to profile — and ./jno_traces is not in
the repo's .gitignore, so the trace directory will show up as untracked.