Skip to content

Shared weighted adjoints for Gauss–Newton/Laplace and SVGD - #207

Merged
KriFos1 merged 10 commits into
Python-Ensemble-Toolbox:mainfrom
KriFos1:integration/weighted-adjoints-gn-svgd
Nov 27, 2026
Merged

KriFos1 merged 10 commits into
Python-Ensemble-Toolbox:mainfrom
KriFos1:integration/weighted-adjoints-gn-svgd

Conversation

@KriFos1

@KriFos1 KriFos1 commented Nov 26, 2026

Copy link
Copy Markdown
Contributor

Proposal

Review the combined PET implementation of #204 (LowRankGN/Laplace), #205 (weighted forecast adjoints) and #206 (SVGD) here. The merge preserves the original commits from both forks; #206 already includes #205. The original drafts remain open. @MathiasMNilsen, feedback is especially welcome on the shared derivative contract and the state-coordinate convention.

Derivative contract and entry points

  • pipt.SVGD / ("svgd", "adjoint"): DataMisfitWeights uses the member’s forward output to seed one log-likelihood VJP during the forecast. ForecastMixin assembles the returned Series by state name into (n_state, n_members). The existing full-Jacobian forecast still yields (n_data, n_state, n_members).
  • pipt.LowRankGN / ("lowrankgn", "laplace"): run_vjp(state, weights) batches the negative-log-likelihood gradient and curvature directions at one centre; full-Jacobian mode uses whitened observation directions. Damping retries are forward-only. BaseEnsemble.calc_prediction and ForecastMixin.forecast accept keyword-only member_count; [dataassim.laplace].posterior_samples defaults to ensemble.ne.
  • Both paths use DataLayout.to_frame for observation labels and check the width of every named derivative block. A singleton direction stays a vector even when there is only one observation. The forecast log_ naming convention is valid only when the PET state already holds the corresponding log coordinate; mapping a name does not transform the derivative.
  • analysis.enif.parameter_graph(name, size, options, prior_info) serves EnIF, SVGD and the Laplace prior. Both schemes remain available through the scheme factory and registry. The PR also includes the original MiniRes adjoint changes, logging helpers, configuration docs and the two additional MiniRes benchmark entries; the published baseline rows are retained.

Verification

  • Full local PET suite (Python 3.12): 897 passed, 5 xfailed, 1 xpassed. ruff check src tests and git diff --cached --check passed.
  • Linear simulator: GN’s gradient seed gives the negative of the forecast-path likelihood gradient at the same state, and the curvature products agree with the analytic Jacobian. Swapped block widths with unchanged total length are rejected.
  • MiniRes: two weighted products agree with the full adjoint and use one permeability centre simulation. Existing scheme tests cover GN restart, posterior sample counts and SVGD on known posteriors.

Companion simulator work

The external JutulDarcy implementations are under review in Python-Ensemble-Toolbox/SimulatorWrap#18 (batched) and Python-Ensemble-Toolbox/SimulatorWrap#20 (forecast-time); the OPM batched implementation is Python-Ensemble-Toolbox/SimulatorWrap#19. Sharing JutulDarcy’s trajectory implementation belongs in SimulatorWrap and is not claimed as tested by this PET suite.

KriFos1 and others added 10 commits November 26, 2026 08:33
A simulator that computes adjoints returns the sensitivity of every
observed value to the state, and the ensemble stacks these as an
(nd, nx, ne) array. A simulator in weighted-adjoint mode is handed weights
w and returns the gradient of sum_i w_i d_i per parameter instead, from one
adjoint solve per member: a Series indexed by parameter name.

_adjoint_array now takes such a Series. Each gradient is placed at its
state variable's rows by name, so a parameter list in another order than
the state cannot pair a gradient with the wrong variable. A log_ prefix is
the simulator naming the log of the variable the state holds. Gradients
that do not name the state variables one to one, or have another size, are
refused.

The simulator protocol describes the mode and the adjoint_weights callable
a caller sets on the simulator.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
A weighted adjoint is the gradient of a weighted sum of the simulator's
outputs. With the weights w = C_d^-1 (d_obs - g(x)) it is
G^T C_d^-1 (d_obs - g(x)), the gradient of the log-likelihood, at the cost
of one adjoint solve per member whatever the number of data.

DataMisfitWeights computes these weights for one member from its forward
output, reading the predictions off the output as the ensemble reads them
into pred_data so that they stay row for row with the observations. It
takes a full or a diagonal data covariance and max-min scaled data, and it
is a plain picklable object because parallel runs ship it to their workers.
A caller sets it as the simulator's adjoint_weights.

The test drives a linear simulator through AssimilationEnsemble.forecast
and compares ensemble.adjoints with H^T C_d^-1 (d_obs - H x).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
PetLogger writes a table of the run. A scheme that also wants to say what
problem it solves, what an iteration did and how the run ended had to format
those lines itself. The logger module now has the pieces:

- heading(title) and block(title, rows), a titled list of rows with their
  values lined up, and a column for symbols only when a row has one;
- items(title, rows), the same for a list that is written in parts;
- change(name, old, new), one line for a value that moved;
- format_value and format_duration, how numbers and wall times read in a log.

Nothing in the existing schemes changes; the SVGD scheme is the first user.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
When a scheme reached maxiter without converging, why_stop stayed an empty
dict. The result is a scipy OptimizeResult, and scipy cannot print one that
holds an empty dict, so printing the result of such a run raised. The stop is
now recorded as why_stop["maxiter"] = True, as the convergence criteria are.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
The graph of a state variable (a given parameter_graphs entry, or the
nearest-neighbour connectivity of its grid) was built by a method of the EnIF
analysis. It is moved unchanged to a module-level function that takes the
scheme, so that another scheme can build the same graphs; the analysis calls
it. No change in behaviour.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
scheme = "svgd" with analysis = "adjoint" (Stordal et al. 2021), registered
in SPECIAL_SCHEMES since it has no ensemble-Kalman analysis to choose. Each
iteration moves every member along the kernel-weighted average of the
members' log-posterior gradients plus the repulsion of the kernel, at the
cost of one forward and one adjoint run per member.

- The gradient of the data misfit is the simulator's weighted adjoint for the
  weights of pipt.ensembles.DataMisfitWeights, which the scheme hands to the
  simulator.
- Kernels: the p-kernel, Gaussian, inverse multiquadric and its p-variant.
- Optimizers for the step: AdaGrad (default), Adam, gradient descent, L-BFGS.
- The prior gradient comes from a sample of the prior (EnsemblePrior), or
  from a sparse factor of its inverse fitted on the graphs of the state
  (GraphPrior, prior_cov_estimate = "graph").
- The run stops when the Stein direction has become small and has stopped
  changing (stein_tol, stein_change), and it can be resumed.

docs/configuration.md lists the options; the references are added.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@KriFos1

KriFos1 commented Nov 26, 2026

Copy link
Copy Markdown
Contributor Author

The combined JutulDarcy companion is now open: Python-Ensemble-Toolbox/SimulatorWrap#21 (integrates #18 and #20 in SimulatorWrap). The two PET-facing derivative paths share the weighted solve. All 17 wrapper integration tests passed together on TINY, including the cross-path gradient, batched finite differences and SI-reference volume checks. OPM remains separate.

@KriFos1
KriFos1 merged commit bef501e into Python-Ensemble-Toolbox:main Nov 27, 2026
4 checks passed
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.

2 participants