Repository navigation
adjoint_solve: own linear tolerance, target-space check, refuse an unconverged solve (#769, #781, #804) - #1038
Conversation
…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>
|
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:
|
| 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·tolthat the solvers'tolerancesetters 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_failureraise. [read] - Retries. The verdict is read after the last retry. With
snes_max_it=2and
divergence_retries=3the 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 ofsolve(). [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 clearshas_solution(shown ashas_solution: falseafter every gradient)
but correctly keeps the verdict. That separation is the reason for the new
attribute, and it works. [ran]- TranscriptAdjoint. It runs
load_stateand then replayssolve(), so each
replayed solve records its own verdict. test_0020 passes at np 1 and np 2. [ran] - yield_continuation. A reverted rung sets
Truefor 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 insnes.solve(JIT/NaN, a sub-KSP
witherror_if_not_converged), Python exceptions in callbacks, and
KeyboardInterrupt. [ran] - The
statesetter (snapshot restore). The setter restoreshas_solutionbut
not the verdict: missed refusal (F4). In the probe, a converged solve is
followed by halving the fields and settings.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 tosaved_scale. The verdict isTrue, 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.
- Effect:
adjoint_solveaccepts a stale state, and the gradient is 15.5× off FD. - Fix: set
self._last_solve_converged = Falsebefore the SNES solve. The finally in
_snes_solve_with_retriesalready runs_capture_solve_reporton the raise path,
so it can set the flag from the SNES reason there. - Status: merge condition, since it is solver.gradient() takes the adjoint of an unconverged forward solve and returns a wrong-signed number #804's own claim ("every route").
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*tolfrom 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_difficultychain 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 alwaysTrue): 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_pathper-rank FileNotFoundError from the harness; - 0019: 1 failure on one rank, a zero-size
maxin 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_numericsto raise
and then assert thatgradientrefuses. - 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 thestatesetter), 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_SNESEWand theSNESKSPSetUseEWsemantics. 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
Fixes #769, #781, #804. Three guards in
adjoint_solve, the one method all three defects pass through: the scalar/vector form onSolverBaseClassand the Stokes saddle-point form.#769: the adjoint's linear solve inherited the forward Newton's inexact tolerance.
adjoint_solvereused the SNES's KSP, so under Eisenstat-Walker it solved to EW's rtol (0.3 on a first solve) and reported converged.adjoint_ksp_rtol. The default is0.1 * tolerance, the margin the solvers' owntolerancesetters give a linear solve. It only tightens, never loosens.finally. This also removes a leak on the matrix route: base left EW's 0.3 on the KSP for every later forward solve.#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_solverefuses when the last solve did not converge. Before, it returned a number 35% off with no warning._last_solve_converged, kept apart fromhas_solution, which a rebuild clears.statesetter 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 * tolerancewith 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:
adjoint_ksp_rtol.Checklist (UW3 Style Charter — docs/developer/UW3_STYLE_CHARTER.md)
level_*andtier_*markers (S8)maybe_/try_/do_) and no commented-out code (S3, S4).array/mesh.X.coords— nowith ....access(...), nomesh.data(S7)pixi.toml/pixi.lockor other dependency changes riding in an unrelated PRUnderworld development team with AI support from Claude Code
🤖 Generated with Claude Code