Use the covariance operator layer and the Krylov solvers

The covariance operator layer in gpr/linalg/linop answers four questions about a covariance matrix \(K\) without fixing how: \(K^{-1}y\), \(\log\det K\), \(y^{T}K^{-1}y\) and the diagonal of \(B^{T}K^{-1}B\). A dense Cholesky solver is the default. A Krylov solver gives the same answers from matrix-vector products. This guide builds a small covariance, solves it both ways, reads the cost model that chooses between them, and shows how to select the Krylov objective on a GP.

Status: implemented, C++ only. The dense solver is on by default. The Krylov objective is opt-in. The layer has no command-line flag, TOML key, C function or Python name. See Methods: the linear solve for the measured record and for what was not measured.

What the layer holds

Header

Contents

gpr/linalg/linop/Operator.h

SymmetricOperator, DenseOperator, ShiftedOperator, CallbackOperator

gpr/linalg/linop/Preconditioner.h

partialPivotedCholesky, PivotedCholeskyPreconditioner, schurResidualTraces

gpr/linalg/linop/Krylov.h

batchConjugateGradients, Lanczos quadrature, probes, LanczosVarianceCache

gpr/linalg/linop/CovarianceSolver.h

CovarianceSolver, DenseCholeskySolver, KrylovCovarianceSolver

gpr/linalg/linop/CostModel.h

denseObjectiveFlops, planKrylovObjective

The names live in gpr::linalg::linop. A KrylovCovarianceSolver takes the full covariance \(K\) as an operator and the added diagonal \(s\), the noise and jitter, so that \(K-\operatorname{diag}(s)\) is the positive semi-definite part that the preconditioner pivots on.

Solve one system both ways

The program builds a squared-exponential Gram matrix on 80 points in three dimensions, adds a noise of 0.05 to the diagonal, and compares the Krylov answers with a dense Cholesky factor. The tolerances are the ones that the unit test LinopKrylovTest.KrylovSolverMeetsTheObjectiveTolerance uses. The quadratic form must agree within tol.objective. The log determinant, a stochastic estimate, must agree within four times twice that tolerance. The probe seed is fixed, so the run is repeatable.

#include <Eigen/Cholesky>
#include <Eigen/Core>
#include <cmath>
#include <cstdio>
#include <limits>
#include <memory>

#include "gpr/linalg/linop/CostModel.h"
#include "gpr/linalg/linop/CovarianceSolver.h"
#include "gpr/linalg/linop/Krylov.h"
#include "gpr/linalg/linop/Operator.h"
#include "gpr/linalg/linop/Preconditioner.h"

namespace linop = gpr::linalg::linop;

int main()
{
    const Eigen::Index n = 80;
    const double length = 0.5;
    const double noise_value = 5e-2;
    const Eigen::Index rank = 20;
    const std::uint64_t probe_seed = 43;

    // Points spread over a cube of side 4.
    const Eigen::MatrixXd x =
        4.0 * (0.5 * (linop::standardNormalProbes(n, 3, 37).array().tanh() + 1.0));
    Eigen::MatrixXd kernel(n, n);
    for (Eigen::Index i = 0; i < n; ++i)
        for (Eigen::Index j = 0; j < n; ++j)
            kernel(i, j) = std::exp(-(x.row(i) - x.row(j)).squaredNorm() /
                                    (2.0 * length * length));
    const Eigen::VectorXd noise = Eigen::VectorXd::Constant(n, noise_value);
    Eigen::MatrixXd full = kernel;
    full.diagonal() += noise;
    const Eigen::VectorXd y = linop::standardNormalProbes(n, 1, 41);

    // Dense reference.
    const Eigen::LLT<Eigen::MatrixXd> llt(full);
    const double dense_quadratic = y.dot(llt.solve(y));
    const double dense_logdet =
        2.0 * llt.matrixLLT().diagonal().array().log().sum();

    // Krylov solver on the same operator.
    auto K = std::make_shared<linop::DenseOperator>(full);
    linop::KrylovCovarianceSolver solver(K, noise);
    linop::KrylovTolerances tol;
    tol.objective = 0.5;
    tol.gradient = 0.5;
    tol.inverse_trace_weight = 0.5 * noise.minCoeff();
    const bool prepared = solver.prepare(
        y, rank, tol, std::numeric_limits<double>::infinity(), probe_seed);
    if (!prepared) {
        std::printf("budget exhausted\n");
        return 1;
    }
    const double quadratic_error =
        std::abs(solver.inverseQuadratic(y) - dense_quadratic);
    const double logdet_error =
        std::abs(solver.logDeterminant() - dense_logdet);
    std::printf("order %ld, preconditioner rank %ld, probes %ld\n",
                static_cast<long>(solver.order()),
                static_cast<long>(solver.rank()),
                static_cast<long>(solver.probes()));
    std::printf("quadratic form error %.3f (tolerance %.1f)\n", quadratic_error,
                tol.objective);
    std::printf("log determinant error %.3f (tolerance %.1f)\n", logdet_error,
                8.0 * tol.objective);
    if (quadratic_error > tol.objective) return 1;
    if (logdet_error > 8.0 * tol.objective) return 1;
    std::printf("krylov solve within tolerance\n");
    return 0;
}
order 80, preconditioner rank 20, probes <n>
quadratic form error <s> (tolerance 0.5)
log determinant error <s> (tolerance 4.0)
krylov solve within tolerance

prepare returns false when the work runs past the flop budget. The caller then asks the dense backend, as the GP does.

Read the cost model

The cost model compares operation counts. It has no cut-off in the matrix order. The inputs are the order, the cost of one operator action, the noise floor, the pivot residual curve and the tolerance. This program plans one objective evaluation for the matrix above with a small noise and with a large noise, and prints which route is cheaper. The pivot residual curve comes from the Schur traces of the dense factor, as it does inside the GP.

#include <Eigen/Cholesky>
#include <Eigen/Core>
#include <cmath>
#include <cstdio>

#include "gpr/linalg/linop/CostModel.h"
#include "gpr/linalg/linop/Krylov.h"
#include "gpr/linalg/linop/Operator.h"
#include "gpr/linalg/linop/Preconditioner.h"

namespace linop = gpr::linalg::linop;

static bool krylov_is_cheaper(const Eigen::MatrixXd& kernel, double noise_value,
                              double tolerance)
{
    const Eigen::Index n = kernel.rows();
    const Eigen::Index hyperparameters = 4;
    const Eigen::Index probes = 2;
    Eigen::MatrixXd full = kernel;
    full.diagonal().array() += noise_value;
    const Eigen::LLT<Eigen::MatrixXd> llt(full);
    const linop::DenseOperator K(full);

    linop::KrylovObjectiveInputs in;
    in.order = n;
    in.hyperparameters = hyperparameters;
    in.matvec_flops = K.applyFlops(1);
    in.column_flops = static_cast<double>(n);
    in.noise_floor = noise_value;
    in.relative_tolerance = tolerance;
    in.probes = probes;
    in.residual_trace = linop::schurResidualTraces(llt.matrixL());

    const double dense = linop::denseObjectiveFlops(n, hyperparameters);
    const linop::KrylovPlan plan = linop::planKrylovObjective(in);
    std::printf("noise %.0e tolerance %.0e: dense %.3e flops, krylov %.3e flops "
                "at rank %ld -> %s\n",
                noise_value, tolerance, dense, plan.flops,
                static_cast<long>(plan.rank),
                plan.flops < dense ? "krylov" : "dense");
    return plan.flops < dense;
}

int main()
{
    const Eigen::Index n = 200;
    const double length = 0.5;
    const Eigen::MatrixXd x =
        4.0 * (0.5 * (linop::standardNormalProbes(n, 3, 37).array().tanh() + 1.0));
    Eigen::MatrixXd kernel(n, n);
    for (Eigen::Index i = 0; i < n; ++i)
        for (Eigen::Index j = 0; j < n; ++j)
            kernel(i, j) = std::exp(-(x.row(i) - x.row(j)).squaredNorm() /
                                    (2.0 * length * length));

    const bool small_noise = krylov_is_cheaper(kernel, 1e-6, 1e-3);
    const bool large_noise = krylov_is_cheaper(kernel, 10.0, 10.0);
    if (small_noise || !large_noise) return 1;
    std::printf("cost model compared\n");
    return 0;
}
noise 1e-06 tolerance 1e-03: dense <s> flops, krylov <s> flops at rank <n> -> dense
noise 1e+01 tolerance 1e+01: dense <s> flops, krylov <s> flops at rank <n> -> krylov
cost model compared

Small noise keeps the dense factor. The condition number is large, so CG needs many iterations. Large noise and a loose tolerance plan Krylov. The same two regimes are asserted in ObjectiveBackend.PlanFollowsNoiseAndToleranceAtOneOrder. For the real covariance of the 16_oxirane refit (order 820) the test comment records that “CG cannot beat the factor there, at any rank”.

Select the backend on a GP

The hyperparameter objective of a GP uses the dense solver unless a C++ caller asks otherwise. The choice is made on a configured GaussianProcessRegression instance.

using Backend = gpr::GaussianProcessRegression::ObjectiveBackend;
gp.setObjectiveBackend(Backend::Auto);                // the cost model chooses
gp.setObjectiveBackend(Backend::Krylov, /*rank=*/8);  // force Krylov
gp.setObjectiveBackend(Backend::Dense);               // exact, the default
const auto plan = gp.objectivePlan();                 // order, rank, flop counts
const Backend used = gp.lastObjectiveBackend();       // what the last call used

A negative rank throws std::invalid_argument. Auto plans the Krylov route from the pivot residual of the last dense factor. The Krylov path falls back to dense when the model uses a correction term, the HS-SVD solver, Hutchinson probes, a principled or kernel nugget, a manifold chart or the geodesic heat kernel, or when the added diagonal is not positive (krylovAddedDiagonal in gpr/ml/gp/KrylovObjective.cpp). The HS-SVD solver is on by default in the library, so the Krylov path applies only where HS-SVD is off. The Krylov objective carries stochastic error. Judge the choice by the oracle count of the whole search, not only by the objective timing.

What to expect

  • On the matrix orders that GPRidge searches produce, no search-level gain from the Krylov backend is recorded. The earlier improve/linop-core branch gave identical search counts to develop. The landed layer has no recorded 44-cell result.

  • The dense solver answers bit for bit as the backend did before the layer existed (LinopKrylovTest.DenseSolverIsTheBackendCallForCall).

  • The Lanczos variance cache (LOVE) works and is tested, but no production path calls it.