Skip to content

SVGD: Stein variational gradient descent with adjoint gradients - #206

Merged
KriFos1 merged 6 commits into
Python-Ensemble-Toolbox:mainfrom
MathiasMNilsen:pr/svgd
Nov 27, 2026
Merged

KriFos1 merged 6 commits into
Python-Ensemble-Toolbox:mainfrom
MathiasMNilsen:pr/svgd

Conversation

@MathiasMNilsen

Copy link
Copy Markdown
Contributor

Stacked on #205: the first two commits are that PR, and the four after them are this one.

What this adds

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.
  • The step is taken by an optimizer: AdaGrad (default), Adam, gradient descent or 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"), with the fit EnIF uses.
  • The run stops when the Stein direction has become small and has stopped changing (stein_tol, stein_change).
    A run can be resumed.
  • Compressed data (compress) and an error ensemble (emp_cov) are refused.

The options are listed in docs/configuration.md, and the references are added.

Commits besides the scheme

  • feat: helpers for writing a scheme's log as blocks of rows: heading, block, items, change,
    format_value and format_duration in ensemble/logger.py. No existing scheme changes.
  • fix: a run stopped at maxiter prints: why_stop stayed empty when a run ended on maxiter, and scipy cannot
    print an OptimizeResult that holds an empty dict. This affects every scheme.
  • refactor: parameter_graph as a function of the enif module: the graph of a state variable was built by a
    method of the EnIF analysis; it is moved unchanged to a function so that SVGD can build the same graphs.

Tests

tests/assimilation/test_svgd.py: the kernels and their repulsion against finite differences, the optimizers,
the two priors, the stopping rule, restart, the log, and the linear-Gaussian posterior being reached for several
kernel and optimizer combinations.

SVGD is left out of test_statistical_consistency.py (entry in EXCLUDED): that test's simulator returns no weighted adjoint, and SVGD needs hundreds of iterations a run. Measured on its problems with a simulator that does, and AdaGrad: within the tolerances in 1 and 2 unknowns after 300 iterations (three seeds); in 10 unknowns still converging after 1,500 (one seed: 0.3 sd off the mean, up to 1.65 times the posterior variance).

Run locally: ruff check src tests is clean; pytest -m "not slow" gives 801 passed. Seven tests in tests/optimization (test_genopt.py and one in test_ensembles.py) fail on this machine, and they fail in the same way on an untouched upstream/main; they are not related to this change.

Relation to #204

This branch conflicts with #204 in six files: CHANGELOG.md, docs/configuration.md, pipt/__init__.py,
update_schemes/analysis/enif.py, update_schemes/registry.py and tests/assimilation/test_scheme_factory.py.
Both PRs move the construction of a state variable's graph out of the EnIF analysis into a function
parameter_graph, with different signatures (parameter_graph(scheme, name, size) here,
parameter_graph(name, size, options, prior_info) there); SVGD can use either. This is opened as a draft for that
reason, and because it is stacked on #205.

🤖 Generated with Claude Code

MathiasMNilsen and others added 6 commits November 26, 2026 09:07
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 merged commit ccceaf6 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