How to add an uncertainty arm

This page is for developers. It adds one new posterior-uncertainty arm (predict-mean and variance) to gpr::GaussianProcessRegression and wires it through the solver, the two drivers, the configuration schema, the C API and the Python package. The running example is a hypothetical FOO arm. The existing arms are MAP, BMA, LAPLACE, EB, SVGD and LAPLACE_SLICE; read gpr/ml/gp/SVGD.cpp and gpr/ml/gp/BMA.cpp first, because they are the smallest complete examples.

The reasons for the arms are in the surrogate loop explanation and the theory pages. The file split of the class is in the GP module layout.

Prerequisites

  • A source checkout that builds and passes meson test (see the installation page).

  • For the benchmark step only: the scalapack pixi environment, the PET-MAD checkpoint, and a host with MPI. Step 8 lists them.

Find every site that switches on the mode

The mode is an enum class UncertaintyMode in structures/Structures.h, and several layers repeat it. List the files that name the newest enumerator, LAPLACE_SLICE, to see every layer:

cd "$GPRIDGE_ROOT"
grep -rlI LAPLACE_SLICE --include='*.cpp' --include='*.h' --include='*.py' \
    --include='*.pyi' --include='*.capnp' --include='*.f90' \
    structures managers gpr python schema fortran main.cpp main_neb.cpp | sort

The layers, with what each needs for a new arm:

Layer

File

Edit

Enumerator

structures/Structures.h

Append FOO to UncertaintyMode. Do not renumber (step 4).

Solver

gpr/ml/GaussianProcessRegression.h

Method declarations (step 1).

Solver

gpr/ml/gp/FOO.cpp, meson.build

Definitions and registration (steps 2 and 3).

Solver

gpr/ml/gp/Predict.cpp, gpr/ml/GaussianProcessRegression.cpp

A case in each of the two dispatchers (step 4).

gprn CLI

main_neb.cpp

The string-to-enumerator function and the --uncertainty-mode row of kFlagDocs.

gprd CLI

main.cpp

The --uncertainty-mode option help and the branch that calls setUncertaintyMode.

Configuration schema

schema/params.capnp, schema/params.capnp.ordinals

A new enumerant of UncertaintyMode (step 5).

TOML and binary

managers/io/TomlConfigLoader.cpp, managers/io/CapnProtoNebLoader.cpp

The string parser and the enumerator switch (step 5).

C API

gpr/capi/gpridge_c.h, gpr/capi/gpridge_c.cpp

gpr_uncertainty_mode_t and the dimer switch (step 6).

Fortran

fortran/gpridge.f90

The GPR_UQ_* constants (step 6).

Python

python/gpridge/_core.cpp, _core.pyi, surrogate.py, _calculator.py, gp/_model.py

The enum binding and the accepted names (step 7).

Not every arm needs every layer. An arm that only the C++ solver selects needs the first four rows.

Steps

1. Declare the methods

Open gpr/ml/GaussianProcessRegression.h and add the declarations beside the existing arm methods. calculatePotentialBMA, calculateVarianceBMA, calculatePotentialSVGD and calculateVarianceSVGD are the closest examples.

void calculatePotentialFOO(Observation& image1);
void calculateVarianceFOO(Observation& image1);

If the arm keeps state between calls (a cache, a sampler), forward-declare a private struct in the same header and hold it through a std::unique_ptr, as SliceLaplaceState does for slice_laplace_state_. A unique_ptr to an incomplete type needs the complete type where the destructor is compiled: include the struct’s header (for the Laplace states, gpr/ml/gp/LaplacePosteriorTypes.h) in each translation unit that destroys the GaussianProcessRegression.

2. Create the translation unit

Create gpr/ml/gp/FOO.cpp. The carved files start with the licence header, a one-paragraph description, and then the includes. gpr/ml/gp/BMA.cpp is the pattern:

// SPDX-License-Identifier: MIT
// Copyright (c) gpridge developers
// See LICENSE for details.

// FOO uncertainty arm: <one paragraph on what it computes>.

#include <Eigen/Core>

#include "../GaussianProcessRegression.h"
#include "Helpers.h"

namespace gpr {

void GaussianProcessRegression::calculatePotentialFOO(Observation& image1)
{
    // ... arm logic ...
}

void GaussianProcessRegression::calculateVarianceFOO(Observation& image1)
{
    // ... arm logic ...
}

}  // namespace gpr

The shared helpers live in gpr::detail (gpr/ml/gp/Helpers.h). Bring in the ones the arm calls with using-declarations inside the gpr namespace, as BMA.cpp does with using detail::writeBMAOutput; and EnergyGradient.cpp does with using detail::addConstantCovarianceBlock;.

3. Register the file in Meson

Add the file to the list of library sources in meson.build, in the block of gpr/ml/gp/ files:

'gpr/ml/gp/EnergyGradient.cpp',
'gpr/ml/gp/FOO.cpp',
'gpr/ml/gp/KrylovObjective.cpp',

The block is not sorted: the order is the order files were added. Any position inside the block works. A file that is not listed compiles to nothing and the link fails with an undefined reference to the new methods.

4. Add the enumerator and the dispatcher cases

Append the enumerator to UncertaintyMode in structures/Structures.h. Append it: the values are part of the C API and of the Python enum, so an existing enumerator keeps its number.

enum class UncertaintyMode {
    MAP = 0,
    BMA = 1,
    LAPLACE = 2,
    EB = 3,
    SVGD = 4,
    LAPLACE_SLICE = 5,
    FOO = 6
};

Two functions switch on uncertainty_mode_. Add a case to each.

  • calculateBackgroundPotentialDispatched in gpr/ml/gp/Predict.cpp holds the mean switch. calculatePotentialDispatched calls it after it has handled the atomic-environment model and the active posterior, and the function itself returns early on the RFF-replace path (rff_replaces_exact_). The switch produces predictions in standardized output units; the code after it computes E = y_scale_ * E + y_mean_ and scales G by y_scale_, then adds the prior mean. A case whose predict already returns physical energies must return before that step, as the LAPLACE_SLICE branch does when it uses the RFF model.

  • calculateVarianceDispatched in gpr/ml/GaussianProcessRegression.cpp holds the variance switch. It first serves a cached solve, then handles the atomic-environment model, the active posterior, the RFF-replace path and the MAP-with-HSSVD path. After the switch it multiplies the variance by y_scale_ * y_scale_ and stores the result in the variance cache.

// Predict.cpp, in calculateBackgroundPotentialDispatched
case UncertaintyMode::FOO:
    calculatePotentialFOO(image1);
    break;

// GaussianProcessRegression.cpp, in calculateVarianceDispatched
case UncertaintyMode::FOO:
    calculateVarianceFOO(image1);
    break;

A new arm is not reached while the atomic-environment, active-posterior or RFF-replace paths are in use.

5. Expose the mode in the configuration

A TOML key or a CLI value that selects the arm needs the schema, the loaders and the CLI parsers. Do these in order:

  1. Add an enumerant at the next free ordinal of the schema enum UncertaintyMode in schema/params.capnp. The schema enum has its own numbering (map @0 to eb @5), different from the C++ enum; the loaders translate. An ordinal is never reused or renumbered.

  2. Record the addition and raise currentSchemaVersion by one, as the Cap’n Proto page describes:

python scripts/check_capnp_evolution.py --write schema/params.capnp schema/params.capnp.ordinals
git diff schema/params.capnp.ordinals    # only added lines
  1. Accept the new name in the string parser of managers/io/TomlConfigLoader.cpp and add a case to the switch in managers/io/CapnProtoNebLoader.cpp.

  2. Accept the name in main_neb.cpp (the function that maps --uncertainty-mode to an enumerator) and in main.cpp, and list it in the help text of both drivers. For gprn the help text is the --uncertainty-mode row of kFlagDocs.

  3. Update the CLI reference. python scripts/gen_cli_reference.py --write regenerates the CLI reference pages from the help text, --check fails until they match, and python scripts/gen_config_reference.py --check fails until the TOML key reference matches the keys the loader reads.

6. Expose the mode in the C API and Fortran

The enum gpr_uncertainty_mode_t in gpr/capi/gpridge_c.h mirrors the C++ values for the uncertainty_mode field of gpr_dimer_config_t and gpr_neb_config_t. Add GPR_UQ_FOO = 6. In gpr/capi/gpridge_c.cpp the dimer entry point switches on the integer and needs a new case; the NEB entry point casts the integer to gpr::UncertaintyMode. Add the constant to the GPR_UQ_* block of fortran/gpridge.f90.

A new enumerator is an addition to the C ABI. Follow the versioning rules on the C API page: raise GPR_C_ABI_MINOR in the header, the abi 1.N line of abi/gpridge_c.symbols and the GPR_C_ABI_MINOR constant of the Fortran module together, and add a row to the ABI history table of that page. scripts/check_c_abi.py compares the header, the symbol list and the version.

7. Expose the mode to Python

Python selects the arm by name. The ASE-facing class takes it as a keyword:

gp = GaussianProcess(uncertainty="foo")

Five files hold the name tables and the enum:

  • python/gpridge/_core.cpp: the nb::enum_<gpr::UncertaintyMode> binding, with one .value(...) per enumerator.

  • python/gpridge/_core.pyi: the UncertaintyMode stub class.

  • python/gpridge/surrogate.py: the name-to-enum table returned by Surrogate._enum_tables.

  • python/gpridge/_calculator.py: the mode_map dictionary and the error for an unknown uncertainty_mode string, which lists the valid names.

  • python/gpridge/gp/_model.py: the uncertainty parameter of GaussianProcess: its docstring, the branch that builds the Surrogate, and the error text for an unknown name.

GaussianProcess(uncertainty”laplace”)= selects the layered Laplace-slice path, not the plain LAPLACE mode. Give a new arm its own name in the accepted list, and keep Surrogate as the interface that exposes every switch of the arm.

8. Run the benchmark fixture

The scaling fixture is the d016 PET-MAD dimer case. Its inputs, bench_data/petmad/d016_pos.con, d016_direction.dat and d016_params.bin, are in the repository. The PET-MAD checkpoint is not; fetch it first:

pixi run -e petmad-assets prepare-petmad-model

scripts/bench_scalapack_real_scaling.sh builds a ScaLAPACK tree (build-scalapack-real), runs the case at the rank counts in GPR_SCALAPACK_PETMAD_RANKS (default 8 16) and writes logs under bench_data/scalapack_scaling/raw. Each log header records the host, the commit, the thread settings and the SHA-256 of the inputs. GPR_UNCERTAINTY_MODE selects the mode the script passes to gprd; its default is map.

GPR_SCALAPACK_PETMAD_RANKS="8" GPR_UNCERTAINTY_MODE=map \
    pixi run -e scalapack bash scripts/bench_scalapack_real_scaling.sh

Run the same command on the parent commit and compare outer iterations and wall time between the two sets of logs. The new arm only runs when the input selects it.

9. Add a unit test

Create a test file under tests/gpr/ml/ and register it in tests/meson.build next to test_bma_dispatch, which registers tests/gpr/ml/BayesianModelAveragingDispatchTest.cpp. That file is the pattern for a dispatch test: it builds a small fixture from reference inputs, selects the mode, and checks three properties of the new methods.

  • The mean and gradient are finite and the arm does not silently fall back to MAP.

  • The variance is non-negative and at least the MAP variance where the arm adds hyperparameter uncertainty.

  • The mean agrees with a reference arm in a regime where both are accurate.

tests/gpr/ml/laplace/SteinVariationalTest.cpp (test_stein_variational) is the unit test for the sampler behind SVGD.

10. Document the arm

Add the file to the diagram and the file table of GP module layout, and write the derivation in a page under docs/orgmode/explanation/. Name the new mode in the --uncertainty-mode text and in Choose GP settings.

Common pitfalls

  • Helper not found. A call to addConstantCovarianceBlock, writeBMAOutput or another gpr::detail helper needs a using detail::X; line in the gpr namespace of the new file.

  • Linker error on ~GaussianProcessRegression. The arm’s state struct is incomplete where the destructor is compiled; include the header that defines it (step 1).

  • Added allocation on the hot path. Per-iteration state (a new std::vector, an MPI handle created per call) shows up in the scaling fixture of step 8.

  • A mode that works from the C++ driver and fails from Python or the C API was not added to all the layers of the table at the top.