Skip to content

adjoint_solve: own linear tolerance, target-space check, refuse an unconverged solve (#769, #781, #804) - #1038

Merged
lmoresi merged 3 commits into
developmentfrom
bugfix/adjoint-solve-guards-769-781-804
Nov 12, 2026
Merged

lmoresi merged 3 commits into
developmentfrom
bugfix/adjoint-solve-guards-769-781-804

Conversation

@lmoresi

@lmoresi lmoresi commented Nov 10, 2026

Copy link
Copy Markdown
Member

Fixes #769, #781, #804. Three guards in adjoint_solve, the one method all three defects pass through: the scalar/vector form on SolverBaseClass and the Stokes saddle-point form.

#769: the adjoint's linear solve inherited the forward Newton's inexact tolerance.

  • adjoint_solve reused the SNES's KSP, so under Eisenstat-Walker it solved to EW's rtol (0.3 on a first solve) and reported converged.
  • The adjoint has no outer iteration to correct that, so the error went straight into every sensitivity. Measured on an iterating Stokes adjoint: 10% short against FD.
  • The transposed solve now runs with EW off and the KSP held to adjoint_ksp_rtol. The default is 0.1 * tolerance, the margin the solvers' own tolerance setters give a linear solve. It only tightens, never loosens.
  • Both are put back in a finally. This also removes a leak on the matrix route: base left EW's 0.3 on the KSP for every later forward solve.
  • Forward solves are unchanged. H1 checked that the next forward solve is bitwise equal to base, with the same iterations, in 29 cases at np 1 and 2.

#781: target space. A target on another space was a bare numpy broadcast error after the solve. It is now refused at entry (degree, continuity, components, mesh), with both spaces named.

#804: an unconverged forward solve.

  • adjoint_solve refuses when the last solve did not converge. Before, it returned a number 35% off with no warning.
  • The verdict is _last_solve_converged, kept apart from has_solution, which a rebuild clears.
  • It is reset at the start of every solve, so a solve that raises can't leave a stale True (H1 F1). The snapshot state setter restores it (F4).

Also, from review. The scalar/vector kernel route now uninstalls the transposed kernels in a finally, as Stokes does (F5, pre-existing).

Decision for Louis. The adjoint KSP default is now 0.1 * tolerance with EW off. That is an adjoint-only setting; forward defaults don't change. Cost: about 10× the adjoint's iterations (26 → 260 in H1's probe). The sensitivity error drops from 0.31 to 7e-8.

Tests. tests/test_0027_adjoint_solve_guards.py, 8 tests:

Review. H1's adversarial review (whole-code context, np 1 and 2, mutant tests) is posted below. Both merge conditions (F1, F2) are addressed in 269c3a0.
Follow-ups, not in this PR:

  • F3: the adjoint atol is an absolute floor, so a very small right-hand side stops early; same on base.
  • F6: the rotated route has its own direct KSP and does not read adjoint_ksp_rtol.

Checklist (UW3 Style Charter — docs/developer/UW3_STYLE_CHARTER.md)

  • I have read the Style Charter and followed it over the surrounding code (S2)
  • No drive-by refactors, renames, or "while I was here" cleanups (S9)
  • Bug fixes ship the regression test, written first, with level_* and tier_* markers (S8)
  • No hedging names (maybe_ / try_ / do_) and no commented-out code (S3, S4)
  • Every exception swallow states its sanctioned failure mode in a comment (S4)
  • New data access uses .array / mesh.X.coords — no with ....access(...), no mesh.data (S7)
  • Parallel safety considered — np2/np4 checked where swarm/mesh/solver dispatch is touched (S11). H1 ran np 1 and 2; the verdict is rank-uniform.
  • No pixi.toml / pixi.lock or other dependency changes riding in an unrelated PR
  • AI-assisted work carries the attribution line below

Underworld development team with AI support from Claude Code

🤖 Generated with Claude Code

…target space, refuse an unconverged solve (#769, #781, #804)

- #769: the transposed solve reused the forward SNES's KSP, and under
  Eisenstat-Walker it ran at EW's rtol (0.3 on a first solve) and reported
  converged. Measured: sensitivity 10% short on an iterating Stokes adjoint.
  EW is now off for the adjoint solve, and the KSP is held to
  adjoint_ksp_rtol (default 0.1 * tolerance, never looser than it was).
  Both are put back afterwards. Forward solves are unchanged.
- #781: a target on another space was a bare broadcast error after the
  solve. It is now checked at entry (degree, continuity, components, mesh),
  with both spaces named.
- #804: the adjoint of a DIVERGED solve returned a wrong number with no
  warning. adjoint_solve now refuses when the last solve did not converge.
  That verdict is kept in _last_solve_converged, apart from has_solution,
  which a rebuild clears.

tests/test_0027_adjoint_solve_guards.py: 4 tests. All fail on development
(a6eebb6; the adjoint files are unchanged at 8f0ed0a) and pass here.

Underworld development team with AI support from Claude Code

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- F1 (merge condition): a forward solve that RAISED left the previous solve's
  converged verdict standing, and an adjoint 15.5x off FD was accepted.
  _plan_picard_warmup, which every solver family runs before _build (the
  rotated path included), now sets _last_solve_converged = False. The
  solve's own verdict then replaces it.
- F2 (merge condition): matrix-route (natural-BC) tests. The adjoint KSP runs
  at <= 0.1 * tolerance (read from a monitor), its tolerances and EW flag are
  put back after the solve, and they are put back after a raise inside the
  adjoint KSP too, with the next forward solve unchanged. These cover the
  mutants that survived on the kernel route: no restore, restore outside the
  finally, and EW off without tightening.
- F4: the state setter (snapshot restore) sets the verdict from the restored
  has_solution.
- F5: the scalar/vector adjoint_solve uninstalls the transposed kernels in a
  finally, as the Stokes route does. A raise had left K^T installed for the
  next forward solve (pre-existing).
- F7: docstring. adjoint_ksp_rtol only tightens, and the rotated route does
  not read it.
- The refusal now says "no converged solve since it raised or the solver was
  restored" when the stale report would read converged.

The adjoint (0018-0027), rotated-adjoint, custom-MG adjoint, has_solution,
snapshot and homotopy tests pass (161).

Underworld development team with AI support from Claude Code

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Underworld development team with AI support from Claude Code

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Copilot AI balanced review requested due to automatic review settings November 10, 2026 12:46

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

@lmoresi

lmoresi commented Nov 10, 2026

Copy link
Copy Markdown
Member Author

Adversarial review by H1 worker (hyperion), of d5d22be, posted at its request. The merge conditions F1 and F2 are addressed in 269c3a0, with F4, F5 and F7. F3 and F6 are follow-ups.

Adversarial review: bugfix/adjoint-solve-guards-769-781-804 at d5d22be

One commit on development 8f0ed0a. It touches petsc_generic_snes_solvers.pyx (the
SolverBaseClass adjoint helpers, both adjoint_solve methods, and
_record_convergence_status) and adds tests/test_0027_adjoint_solve_guards.py.

Builds used: wt-h4r (branch) and wt-dev8f (base), PETSc 3.25.3. Probes, logs and
summaries are in runs/2026-11-10-h4review/review/:

  • probe_leak.py covers the leak, accuracy and next-forward checks;
  • probe_q3.py covers the paths that set the converged verdict;
  • mut_h4.py is the mutation plugin;
  • summ1.txt holds the probe summary;
  • batch3.out holds the test runs.

Anything marked [read] comes from reading the code and was not run.

Verdict

Approve, with two merge conditions. The fix is correct and leak-free on every
route we ran. It changes no forward solve: base and branch match bitwise on all 29
probe cases. It turns sensitivities that were 23–34 % wrong into ones accurate to
1e-7.

The converged guard has one hole. A forward solve that raises leaves the previous
True verdict standing, and the stale adjoint it then accepts is 15× off. test_0027
does not guard the tolerance restore on the matrix route, which is the route where the
restore actually matters.

Q1. Does EW-off plus setTolerances leak into the next forward solve?

No. We took snapshots at four points: after forward 1 (C0), inside the adjoint
KSP (from a monitor at its = 1), after the adjoint (C1), and after a warm and then a
cold forward solve (C2, C3). Each snapshot holds:

  • EW on/off and all seven EW parameters;
  • the outer KSP's rtol, atol, divtol and max_it;
  • the SNES tolerances;
  • the fieldsplit sub-KSP tolerances;
  • the KSP convergence-test chain and _linear_floor.

We covered 29 cases per build: Stokes on the kernel and matrix routes, rheologies lin,
power-law Newton and Picard, with and without custom FMG, with an iterating (weak)
and a default PC, at np 1 and 2, plus Poisson on both routes.

Matrix route (_solve_transposed). On the branch, C1 = C2 = C3 = C0 exactly, at
np 1 and np 2, including after a forced exception inside the adjoint KSP.

Base leaks EW's rtol = 0.3 into the KSP (C0 1e-5 → C1 0.3). That value then
survives every later forward solve: _snes_solve_with_retries saves and restores the
leaked value. The branch removes this leak.

Kernel route. The adjoint leaves two differences, the same on base and branch:

  • SNES atol goes 0 → 1e-50;
  • the convergence-test chain is dropped.

Both come from the _uninstall_adjoint_kernels rebuild. They are pre-existing, and
C3 = C0 once a forward solve has run.

Inside the adjoint, on the branch, on every route including custom MG: EW is off
and rtol = min(ksp rtol, 0.1·tol), e.g. 1e-7 at tol 1e-6 and 1e-10 at tol 1e-9. On
base, EW is on and rtol is 0.3.

Next forward solve. We compared forward 1, a warm forward 2 and a cold forward 3
between base and branch. All three are bitwise equal in every case, with identical
SNES and linear iteration counts.

Forced exception (a monitor that raises at its 1). The branch restores the
configuration fully on the matrix route, at np 1 and 2. On Stokes kernel+FMG the
forward that follows is bitwise equal to base.

#1014 interaction. The adjoint does not override or fight the composed KSP test.
linear_floor stays registered on the matrix route, but _linear_floor is None
during the adjoint. The test returns ITERATING and PETSc's native test decides:
CONVERGED_RTOL normally, and CONVERGED_ATOL in the small-b case below. The wall-clock
guard, if armed, would also apply to the adjoint KSP; that is not new here. [read]

PETSc semantics. That setUseEW(False) stops EW's pre-solve, and that
setUseEW(True) keeps the EW context, rests on two kinds of evidence:

  • measured: ew_in_adj = False, the rtol in force is ours, and ew_params is
    identical before and after;
  • not read: we did not read the PETSc source.

Q2. Is 0.1·tol the right adjoint rtol? Does it reach #1016/#1021, and can it stall?

Accuracy and cost

Accuracy is measured against a dense lstsq(Kᵀ, b) (lin, pl), or against an rtol
1e-12 adjoint (pic, where the dense K is the Picard tangent). "Error" in the table is
the relative error of μ·b or of μ.

case (np1, tol 1e-6, iterating PC) base its / error branch its / error
Stokes mat, lin 17 / 0.35 (μ 0.23) 165 / 4.8e-8
Stokes mat, power-law Newton 26 / 0.31 (μ 0.34) 260 / 7.2e-8
Stokes mat, Picard 26 / μ 0.34 260 / μ 8.6e-8
Stokes kern, power-law Newton 13 / 0.46 139 / 5.8e-8
Stokes kern, Picard 13 / μ 0.28 139 / μ 6.5e-8
Stokes mat pl, tol 1e-9 26 / 0.31 372 / 7.9e-11
Stokes mat pl, np 2 26 / 0.31 260 / 7.2e-8
Poisson kern/mat, lin/pl (no EW) bitwise equal to branch rtol 1e-7, 104–124 its

The adjoint costs about 10× more iterations than under EW, roughly the total linear
work of one forward Newton solve. That is the price of a correct answer, and 0.1·tol
is defensible:

  • it puts the adjoint error (~1e-7 at tol 1e-6) an order below the forward state's
    own error;
  • it matches the ksp_rtol = 0.1·tol that the solvers' tolerance setters derive.

The gradient differences we saw between PCs (2e-5 to 4e-4 at tol 1e-6) come from the
forward state. They disappear at tol 1e-9.

Custom MG (#1016, #1021)

Reached: yes. The kern and mat routes, with pl and pic, at np 1 and 2, all go
through _adjoint_linear_tolerance. Inside the adjoint, rtol is 1e-7 (or 1e-10) and
EW is off.

Stall: none. The FMG adjoint converges in 1 outer iteration at rtol 1e-7 and at
1e-10. No case reached max_it or DIVERGED_ITS. The iterating cases peak at 372 of
5000.

The sub-KSPs are not touched, so the velocity inner rtol stays 0.033·tol and the
pressure inner rtol 0.1·tol. The pressure inner solve is therefore no tighter than the
adjoint's outer target. With FGMRES this cost nothing measurable here. [read: the
inner reasons were not logged]

Relative to what? Small b

Fgmres measures the unpreconditioned residual and Poisson's gmres the preconditioned
one. In both cases rtol is relative to the initial residual, which is ‖b‖ because
x0 = 0.

atol is not adjusted, and it binds when b is small. Scaling the same misfit by
1e-8 gives:

case ‖b‖ adjoint stops at relative residual μ·b error
Stokes mat pl 8.6e-11 CONVERGED_ATOL after 84 its 1.1e-2 1.6e-3
Poisson 1.5e-10 CONVERGED_ATOL after 37 its 2.9e-2 2.3e-3

The adjoint is linear, so its relative accuracy should not depend on the scale of b.
Here it does, because atol = tol·1e-6 sets an absolute floor. That floor binds when
‖b‖ < atol/rtol_adj, which is 1e-5 at tol 1e-6. In an inversion, b → 0 as the misfit
is fitted, so this is where gradient accuracy matters most. The behaviour is
pre-existing and equal on base. See F3.

Q3. Is _last_solve_converged set on every forward path before an adjoint?

Each path is listed with what we found and whether we ran it or only read it.

Set correctly on these paths:

  • solve() on the four SNES families. _record_convergence_status() runs at the
    end of every one: Scalar, Vector, MultiComponent and Stokes. [read]
  • Rotated free-slip. The verdict is recorded with the rotated report before the
    linear_failure raise. [read]
  • Retries. The verdict is read after the last retry. With snes_max_it=2 and
    divergence_retries=3 the solve converged and the adjoint was accepted. [ran]
  • Picard warm-up and continuation. These run inside _snes_solve_with_retries,
    and the verdict is recorded at the end of solve(). [read]
  • estimate_difficulty. A capped probe gives DIVERGED_MAX_IT and is refused,
    with the right message. The resumed probe gives CONVERGED_FNORM_ABS and is accepted.
    Both behave the same at np 1 and np 2, with no hang. [ran]
  • _force_setup / is_setup = False. This is refused by the existing "no
    forward solve" check, and accepted after re-converging. A kernel-route adjoint's own
    rebuild clears has_solution (shown as has_solution: false after every gradient)
    but correctly keeps the verdict. That separation is the reason for the new
    attribute, and it works. [ran]
  • TranscriptAdjoint. It runs load_state and then replays solve(), so each
    replayed solve records its own verdict. test_0020 passes at np 1 and np 2. [ran]
  • yield_continuation. A reverted rung sets True for a converged state at the
    settled δ, and the model is left holding that δ, so this is consistent. [read]

Missed refusals:

  • A solve that raises. The verdict is stale True; missed refusal (F1). In
    the probe, a converged solve at η₀ = 1 is followed by changing η₀ to 2 and a
    solve() that raises inside _snes_solve_with_retries. gradient() is then
    accepted and returns -4.94e-5, while the FD at η₀ = 2 is -3.18e-6: 15.5× off.
    Real sources of such a raise are PETSc errors in snes.solve (JIT/NaN, a sub-KSP
    with error_if_not_converged), Python exceptions in callbacks, and
    KeyboardInterrupt. [ran]
  • The state setter (snapshot restore). The setter restores has_solution but
    not the verdict: missed refusal (F4). In the probe, a converged solve is
    followed by halving the fields and setting s.state = SolverStepState(False). The
    adjoint is accepted, ratio 0.18. TranscriptAdjoint is not affected because it always
    replays. [ran]
  • Rate-strengthening ladder failure. The fields are left at the last good rung m
    while the control goes back to saved_scale. The verdict is True, which is a
    mismatched state: a missed refusal. [read; edge case]

Rank uniformity. The verdict comes from snes.getConvergedReason() or the
rotated KSP reason, and both are global. The yield-continuation flags derive from
those reasons. At np 2, test_0027 passes and the difficulty probe gives the same
verdict on all ranks with no hang. [ran + read]

Target-space check (#781)

The check compares (degree, continuous, num_components) and requires the same mesh
object. A legitimate same-space target is accepted, including one built the way
adjoint._Scratch builds it (vtype passed). That is how TranscriptAdjoint and
gradient build their targets, and test_0020 and test_0021 pass.

The checked attributes (degree, continuity, components, mesh) are partition
independent, so the check cannot refuse a parallel layout that is valid.

A numpy or PETSc.Vec target was never supported: base raises AttributeError: vec,
and the branch raises AttributeError: mesh. target=(u, None) fails identically on
both. Neither is a regression.

The question asks about createVecLeft vs createVecRight on rectangular blocks. It
does not apply here: the target is a MeshVariable, and the operator is square in the
solver's own DM. [read]

Findings

F1 — Medium. A raised forward solve leaves the verdict at its previous True.

F2 — Medium (test gap). Two mutants survive test_0027:

  • norestore_tol (tolerances not put back): 4/4 pass;
  • nofinally (restore only on success): 4/4 pass.

Test 1 runs on the kernel route, whose _uninstall_adjoint_kernels rebuild resets the
KSP from options and so hides a missing restore. On the matrix route the restore is
the only thing preventing the leak; base leaks 0.3 there.

A third mutant, notight (EW off but no tightening), also passes 4/4. Without
tightening the adjoint runs at the inherited 1e-5, which meets the test's 1e-4
FD bound.

Fix:

  • add a natural-BC (matrix-route) variant of test 1 that asserts the restore;
  • add a raise-inside-the-KSP case that asserts the restore;
  • optionally, assert ksp.getTolerances()[0] <= 0.1*tol from a monitor.

Status: merge condition for the matrix-route variant.

F3 — Medium, pre-existing, follow-up. The adjoint's atol is the forward's
tol·1e-6, an absolute floor. For ‖b‖ ≲ 1e-5 (at tol 1e-6) the adjoint stops on ATOL
at a 1–3 % residual, and the sensitivity error is 0.16–0.23 %. That is the regime of
a nearly fitted misfit. Suggested fix: inside the held context, use
atol = min(atol, want·‖b‖) or 0.

F4 — Low-Medium. The state setter (snapshot restore) does not touch the verdict.
An adjoint taken after load_state without a replay is accepted on a non-solution
(ratio 0.18). Fix: reset the verdict to None or False in the setter. TranscriptAdjoint
is unaffected.

F5 — Low-Medium, pre-existing. On the scalar/vector kernel route,
SolverBaseClass.adjoint_solve calls _uninstall_adjoint_kernels outside any
finally. The Stokes route has one.

  • Measured: a raise inside the adjoint KSP on Poisson kern pl leaves the transposed
    Jacobian installed. The next cold solve takes 12 Newton / 82 linear iterations
    against 3 / 26, and its answer differs by 4.2e-7. Base behaves identically.
  • Status: it sits in the block this commit edits, and it is a fix of one line.

F6 — Low [read]. The rotated route (solve_rotated_adjoint) builds its own KSP
with ksp_rtol = tol, not 0.1·tol. It ignores adjoint_ksp_rtol, although the
docstring says the adjoint is held to it. The fix is either to pass the adjoint rtol
through or to state the exception in the docstring.

F7 — Low (doc). adjoint_ksp_rtol can only tighten, because of
min(current, want). A user who sets it looser than the inherited ksp_rtol is
silently ignored. The comment says "never looser"; the attribute's docstring should say
so too.

Observation — pre-existing. A kernel-route adjoint rebuild clears has_solution.
After any gradient() on that route, the solver no longer claims a warm start. A warm
solve() still started from the fields (0 iterations), so we saw no harm.

Attacks that failed

  • Leak into the next forward solve. None. Forward 1, 2 and 3 are bitwise equal
    between base and branch in 29/29 cases, with identical iteration counts. The
    configuration is restored exactly on the matrix route, at np 1 and 2, including
    after a raise.
  • EW parameters. Unchanged across the adjoint, all seven fields.
  • Custom MG stall at 0.1·tol and 0.1·(1e-9). 1 outer iteration. No max_it or
    DIVERGED_ITS anywhere: the iterating maximum is 372/5000.
  • Fight with One convergence reference for every solver: warm starts, the linear floor, the rotated loop (#911, #985, #924) #1014's floor test. None. The floor is inactive and the native test
    decides.
  • Rank uniformity of the guard. The verdict comes from a global reason. np 2
    probes and test_0027 at np 2 pass with no hang.
  • Wrong refusals. None found:
    • a converged solve after a diverged one is accepted;
    • a completed estimate_difficulty chain is accepted;
    • a re-solve after rebuild is accepted;
    • scratch-built targets are accepted;
    • the TranscriptAdjoint replay is accepted (test_0020, np 1 and 2).
  • test_0027 fails on base. 4/4 fail on 8f0ed0a at np 1 and np 2, and 4/4 pass
    on the branch at np 1 and np 2.
  • Mutants caught:
    • noew: test 1 fails;
    • norestore_ew: test 1 fails;
    • nocontext: test 1 fails;
    • notarget: tests 2 and 3 fail;
    • noguard: test 4 fails;
    • norecord (verdict always True): test 4 fails.

Test runs (branch vs base, the same test tree)

Serial, all equal on base and branch:

test result
0018 14 passed
0019 8 passed
0020 5 passed
0021 1 passed
0022 kernels 2 passed
0022 rotated 7 passed
0023 2 passed
0024 2 passed
0026 3 passed
0028 9 passed
1131 24 passed
1145 5 passed
0027 4 passed on the branch, 4 failed on base

np 2, the same outcome on both builds (rotated 0022, 0020, 0021, 0023, 0024 and
0028 pass on both; 1145 gives 1 passed and 4 skipped on both). Four results are not
clean passes, and each is identical on base and branch:

  • 0018: 1 failure, a tmp_path per-rank FileNotFoundError from the harness;
  • 0019: 1 failure on one rank, a zero-size max in the test;
  • 0026: rc 59 abort after 2 tests;
  • 1131: rc 124 supervisor silence timeout.

None of these is caused by the branch.

Merge conditions

  • Fix F1: a raised or interrupted forward solve must leave _last_solve_converged
    False. Add a regression test for it, e.g. monkeypatch _snapshot_numerics to raise
    and then assert that gradient refuses.
  • Fix F2: add a matrix-route (natural-BC) variant of the adjoint_solve inherits the forward solve's INEXACT Newton tolerance: every sensitivity on an iteratively-solved problem is silently short by 15-20% #769 test that asserts the
    KSP tolerances and EW come back. It is best done together with a raise inside the
    adjoint KSP.
  • Recommended in the same PR, each about one line: F5 (uninstall in finally), F4
    (reset the verdict in the state setter), F7 (a docstring note).
  • Follow-up issues: F3 (the absolute atol floor on a small adjoint RHS) and F6 (the
    rotated route's adjoint rtol).

What we could not test

  • The rotated route under the branch. It is untouched, and test_0022_rotated passes,
    but we ran no leak or accuracy probe on it, so F6 is [read].
  • The PETSc source for KSPPreSolve_SNESEW and the SNESKSPSetUseEW semantics. The
    evidence is behavioural only.
  • The yield-continuation and rate-strengthening paths. [read only]
  • The wall-clock guard firing during an adjoint.
  • The custom-MG inner sub-KSP reasons. The outer converged in 1 iteration, but the
    inner reasons were not logged.
  • np > 2. We also did not run 3-D cases or the Stokes adjoint, matrix route: the velocity multigrid is built from J's block, not J^T's #1021 fault-patch FAC hierarchy; the
    custom-FMG runs here used a plain refined box.
  • test_1131 at np 2. It hit the 600 s silence limit on both builds, so it gives no
    comparison.

Underworld development team with AI support from Claude Code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants