Loading...
Searching...
No Matches
gpr::linalg::linop Namespace Reference

Classes

struct  BatchSolve
struct  BatchSolveSettings
class  CallbackOperator
class  CovarianceSolver
class  DenseCholeskySolver
 K = L L^T held in caller storage, operated on through BackendContext. More...
class  DenseOperator
 A materialised symmetric matrix; the referenced storage must outlive it. More...
class  DenseResultCache
class  KrylovCovarianceSolver
struct  KrylovObjectiveInputs
struct  KrylovPlan
struct  KrylovTolerances
 Accuracy the Krylov backend must deliver, in the objective's units. More...
class  LanczosVarianceCache
struct  PartialCholesky
class  PivotedCholeskyPreconditioner
class  ShiftedOperator
class  SymmetricOperator

Functions

double denseObjectiveFlops (Eigen::Index order, Eigen::Index hyperparameters)
double krylovObjectiveFlops (const KrylovObjectiveInputs &in, Eigen::Index rank)
KrylovPlan planKrylovObjective (const KrylovObjectiveInputs &in)
BatchSolve batchConjugateGradients (const SymmetricOperator &K, const PivotedCholeskyPreconditioner &P, const Eigen::MatrixXd &B, const BatchSolveSettings &settings)
double lanczosLogQuadrature (const BatchSolve &solve, Eigen::Index column)
double lanczosSquaredLogQuadrature (const BatchSolve &solve, Eigen::Index column)
Eigen::MatrixXd standardNormalProbes (Eigen::Index rows, Eigen::Index cols, std::uint64_t seed)
Eigen::Index probesForStandardError (double sample_variance, double target, Eigen::Index taken)
double sampleVariance (const Eigen::VectorXd &draws)
double conjugateGradientIterations (double kappa, double tolerance)
double pivotFlops (double column_flops, Eigen::Index order, Eigen::Index rank)
 Pivot cost: one column read and the update against the previous pivots.
PartialCholesky partialPivotedCholesky (const SymmetricOperator &kernel, const std::function< bool(Eigen::Index, double, double)> &keep_going)
std::vector< double > schurResidualTraces (const Eigen::MatrixXd &L)

Function Documentation

◆ batchConjugateGradients()

BatchSolve gpr::linalg::linop::batchConjugateGradients ( const SymmetricOperator & K,
const PivotedCholeskyPreconditioner & P,
const Eigen::MatrixXd & B,
const BatchSolveSettings & settings )
nodiscard

Preconditioned CG on K X = B, all columns advanced by one block apply per iteration until each meets its tolerance or the budget is spent.

Definition at line 33 of file Krylov.cpp.

37{
38 const Eigen::Index n = B.rows(), m = B.cols();
39 if (K.order() != n || P.order() != n || settings.tolerance.size() != m)
40 throw std::invalid_argument("batch CG dimension mismatch");
42 out.X = Eigen::MatrixXd::Zero(n, m);
43 out.step.assign(static_cast<std::size_t>(m), {});
44 out.update.assign(static_cast<std::size_t>(m), {});
45 Eigen::MatrixXd R = B;
46 Eigen::MatrixXd Z = P.solve(R);
47 Eigen::MatrixXd D = Z;
48 Eigen::VectorXd rz = (R.array() * Z.array()).colwise().sum().transpose();
49 out.initial_norm = rz;
50 out.residual_norm = R.colwise().norm().transpose();
51 std::vector<bool> active(static_cast<std::size_t>(m));
52 for (Eigen::Index j = 0; j < m; ++j)
53 active[static_cast<std::size_t>(j)] =
54 out.residual_norm(j) > settings.tolerance(j);
55 const double per_iteration =
56 K.applyFlops(m) + P.solveFlops(m) + 10.0 * static_cast<double>(n * m);
57 out.flops = P.solveFlops(m);
58 Eigen::MatrixXd KD;
59 for (;;) {
60 bool any = false;
61 for (const bool a: active)
62 any = any || a;
63 if (!any) {
64 out.converged = true;
65 break;
66 }
67 if (out.flops + per_iteration > settings.flop_budget) break;
68 K.apply(D, KD);
69 out.flops += per_iteration;
70 ++out.iterations;
71 for (Eigen::Index j = 0; j < m; ++j) {
72 const auto s = static_cast<std::size_t>(j);
73 if (!active[s]) continue;
74 const double curvature = D.col(j).dot(KD.col(j));
75 if (!(curvature > 0.0)) {
76 active[s] = false;
77 out.residual_norm(j) = std::numeric_limits<double>::infinity();
78 continue;
79 }
80 const double a = rz(j) / curvature;
81 out.X.col(j).noalias() += a * D.col(j);
82 R.col(j).noalias() -= a * KD.col(j);
83 out.step[s].push_back(a);
84 out.residual_norm(j) = R.col(j).norm();
85 if (out.residual_norm(j) <= settings.tolerance(j)) {
86 active[s] = false;
87 continue;
88 }
89 }
90 Z = P.solve(R);
91 for (Eigen::Index j = 0; j < m; ++j) {
92 const auto s = static_cast<std::size_t>(j);
93 if (!active[s]) continue;
94 const double rz_new = R.col(j).dot(Z.col(j));
95 const double b = rz_new / rz(j);
96 rz(j) = rz_new;
97 out.update[s].push_back(b);
98 D.col(j) = Z.col(j) + b * D.col(j);
99 }
100 }
101 for (Eigen::Index j = 0; j < m; ++j)
102 if (!(out.residual_norm(j) <= settings.tolerance(j)))
103 out.converged = false;
104 return out;
105}
Eigen::MatrixXd solve(const Eigen::MatrixXd &X) const
P^{-1} X by Woodbury.
virtual void apply(const Eigen::MatrixXd &X, Eigen::MatrixXd &Y) const =0
Y = A X, X with order() rows and any number of columns.
virtual Eigen::Index order() const =0
virtual double applyFlops(Eigen::Index rhs) const =0
Floating-point operations of one apply to rhs columns.
eon_relax_band_t eon_relax_surface_fn void eon_relax_outcome_t * out
double flop_budget
Operations after which the solve gives up unconverged.
Definition Krylov.h:28
Eigen::VectorXd tolerance
Absolute residual 2-norm each column must reach.
Definition Krylov.h:26

◆ conjugateGradientIterations()

double gpr::linalg::linop::conjugateGradientIterations ( double kappa,
double tolerance )
nodiscard

Iterations CG needs for relative K-norm error tolerance at condition number kappa: ceil(sqrt(kappa) log(2 / tolerance) / 2).

Definition at line 190 of file Krylov.cpp.

191{
192 if (!(kappa >= 1.0) || !(tolerance > 0.0) || !std::isfinite(kappa))
193 return std::numeric_limits<double>::infinity();
194 if (tolerance >= 1.0) return 1.0;
195 return std::max(
196 1.0, std::ceil(0.5 * std::sqrt(kappa) * std::log(2.0 / tolerance)));
197}

◆ denseObjectiveFlops()

double gpr::linalg::linop::denseObjectiveFlops ( Eigen::Index order,
Eigen::Index hyperparameters )
nodiscard

potrf, the explicit inverse as cholesky_inverse forms it (a triangular solve against the identity and the Gram of the result), two substitutions, and one dense contraction per hyperparameter.

Definition at line 15 of file CostModel.cpp.

16{
17 const double n = static_cast<double>(order);
18 const double factor = n * n * n / 3.0;
19 const double inverse = n * n * n + 2.0 * n * n * n;
20 const double solves = 4.0 * n * n;
21 const double contractions =
22 2.0 * n * n * static_cast<double>(hyperparameters);
23 return factor + inverse + solves + contractions;
24}

◆ krylovObjectiveFlops()

double gpr::linalg::linop::krylovObjectiveFlops ( const KrylovObjectiveInputs & in,
Eigen::Index rank )
nodiscard

Krylov cost at one preconditioner rank: pivots, the block CG on the data and the probes, and the probe contractions replacing the dense ones.

Definition at line 26 of file CostModel.cpp.

27{
28 const auto r = static_cast<std::size_t>(rank);
29 if (r >= in.residual_trace.size() || !(in.noise_floor > 0.0))
30 return std::numeric_limits<double>::infinity();
31 const double n = static_cast<double>(in.order);
32 const double m = static_cast<double>(in.probes);
33 const double rr = static_cast<double>(rank);
34 // Sum of pivotFlops over the first `rank` pivots.
35 const double pivots = rr * in.column_flops + n * rr * (rr + 1.0);
36 const double kappa =
37 1.0 + std::max(0.0, in.residual_trace[r]) / in.noise_floor;
38 const double iterations =
40 const double rhs = 1.0 + m;
41 const double per_iteration =
42 rhs * (in.matvec_flops + 4.0 * n * rr + 2.0 * rr * rr + 12.0 * n);
43 const double contractions = static_cast<double>(in.hyperparameters) *
44 (2.0 * n * n * m + 2.0 * n * m);
45 const double quadrature = m * iterations * iterations * iterations;
46 return pivots + iterations * per_iteration + contractions + quadrature;
47}
double conjugateGradientIterations(double kappa, double tolerance)
Definition Krylov.cpp:190
double column_flops
one column read while pivoting
Definition CostModel.h:29
double noise_floor
smallest added diagonal entry
Definition CostModel.h:30
std::vector< double > residual_trace
Bound on tr(A0 - F_r F_r^T) by rank r = 0, 1, ...
Definition CostModel.h:34
double matvec_flops
one operator action on one column
Definition CostModel.h:28

◆ lanczosLogQuadrature()

double gpr::linalg::linop::lanczosLogQuadrature ( const BatchSolve & solve,
Eigen::Index column )
nodiscard

e1^T log(T) e1 scaled by r0^T P^{-1} r0 for column j: the quadrature estimate of z^T P^{-1/2} log(P^{-1/2} K P^{-1/2}) P^{-1/2} z.

Definition at line 139 of file Krylov.cpp.

140{
141 return lanczosQuadrature(solve, column,
142 [](double x) { return std::log(x); });
143}
@ x
Definition Enums.h:28

◆ lanczosSquaredLogQuadrature()

double gpr::linalg::linop::lanczosSquaredLogQuadrature ( const BatchSolve & solve,
Eigen::Index column )
nodiscard

The same quadrature for log^2: its mean over Gaussian probes estimates the squared Frobenius norm of log(P^{-1/2} K P^{-1/2}), half the variance of one log det draw. Unlike a sample variance of a few draws it is a trace of a positive semi-definite matrix and does not collapse when the draws agree.

Definition at line 145 of file Krylov.cpp.

146{
147 return lanczosQuadrature(solve, column, [](double x) {
148 const double l = std::log(x);
149 return l * l;
150 });
151}

◆ partialPivotedCholesky()

PartialCholesky gpr::linalg::linop::partialPivotedCholesky ( const SymmetricOperator & kernel,
const std::function< bool(Eigen::Index, double, double)> & keep_going )
nodiscard

Greedy pivoted Cholesky. After each pivot keep_going(rank, trace, flops) decides whether to take another; pivoting also stops on a zero residual or at full rank.

Definition at line 19 of file Preconditioner.cpp.

22{
23 const Eigen::Index n = kernel.order();
24 PartialCholesky result;
25 result.residual_diagonal = kernel.diagonal();
26 result.residual_trace.push_back(result.residual_diagonal.sum());
27 const double column_flops = kernel.applyFlops(1);
28 std::vector<Eigen::VectorXd> columns;
29 while (static_cast<Eigen::Index>(columns.size()) < n) {
30 const Eigen::Index rank = static_cast<Eigen::Index>(columns.size());
31 Eigen::Index pivot = 0;
32 const double d = result.residual_diagonal.maxCoeff(&pivot);
33 if (!(d > 0.0) || !std::isfinite(d)) break;
34 if (!keep_going(rank, result.residual_trace.back(), result.flops))
35 break;
36 Eigen::VectorXd l = kernel.column(pivot);
37 for (Eigen::Index k = 0; k < rank; ++k)
38 l.noalias() -= columns[static_cast<std::size_t>(k)](pivot) *
39 columns[static_cast<std::size_t>(k)];
40 l /= std::sqrt(d);
41 for (const Eigen::Index p: result.pivots)
42 l(p) = 0.0;
43 result.residual_diagonal.array() -= l.array().square();
44 result.residual_diagonal(pivot) = 0.0;
45 result.residual_diagonal = result.residual_diagonal.cwiseMax(0.0);
46 result.pivots.push_back(pivot);
47 columns.push_back(std::move(l));
48 result.residual_trace.push_back(result.residual_diagonal.sum());
49 result.flops += pivotFlops(column_flops, n, rank);
50 }
51 result.factor.resize(n, static_cast<Eigen::Index>(columns.size()));
52 for (std::size_t k = 0; k < columns.size(); ++k)
53 result.factor.col(static_cast<Eigen::Index>(k)) = columns[k];
54 return result;
55}
virtual Eigen::VectorXd diagonal() const =0
virtual Eigen::VectorXd column(Eigen::Index j) const =0
double pivotFlops(double column_flops, Eigen::Index order, Eigen::Index rank)
Pivot cost: one column read and the update against the previous pivots.
Eigen::MatrixXd factor
order x rank
std::vector< Eigen::Index > pivots
double flops
Operations spent, counting column reads at the operator's cost.
std::vector< double > residual_trace
residual_trace[r] = tr(A0 - F_r F_r^T) after r pivots.

◆ pivotFlops()

double gpr::linalg::linop::pivotFlops ( double column_flops,
Eigen::Index order,
Eigen::Index rank )
nodiscard

Pivot cost: one column read and the update against the previous pivots.

Definition at line 13 of file Preconditioner.cpp.

14{
15 return column_flops +
16 2.0 * static_cast<double>(order) * static_cast<double>(rank + 1);
17}

◆ planKrylovObjective()

KrylovPlan gpr::linalg::linop::planKrylovObjective ( const KrylovObjectiveInputs & in)
nodiscard

The cheapest rank on the residual curve, among ranks whose pivots cost less than a full Cholesky.

Definition at line 49 of file CostModel.cpp.

50{
51 KrylovPlan best;
52 best.flops = std::numeric_limits<double>::infinity();
53 const double n = static_cast<double>(in.order);
54 for (std::size_t r = 0; r < in.residual_trace.size(); ++r) {
55 const auto rank = static_cast<Eigen::Index>(r);
56 const double rr = static_cast<double>(rank);
57 // Past the operations of a full Cholesky the pivots buy nothing a
58 // dense factor would not give exactly.
59 if (rr * in.column_flops + n * rr * (rr + 1.0) > n * n * n / 3.0) break;
60 const double flops = krylovObjectiveFlops(in, rank);
61 if (flops < best.flops) {
62 best.flops = flops;
63 best.rank = rank;
65 1.0 + std::max(0.0, in.residual_trace[r]) / in.noise_floor,
67 }
68 }
69 return best;
70}
double krylovObjectiveFlops(const KrylovObjectiveInputs &in, Eigen::Index rank)
Definition CostModel.cpp:26

◆ probesForStandardError()

Eigen::Index gpr::linalg::linop::probesForStandardError ( double sample_variance,
double target,
Eigen::Index taken )
nodiscard

Probes needed for the sample mean of draws with this sample variance to reach the standard error target; at least the draws already taken.

Definition at line 171 of file Krylov.cpp.

173{
174 if (!(target > 0.0) || !std::isfinite(sample_variance))
175 return std::numeric_limits<Eigen::Index>::max();
176 const double needed = std::ceil(sample_variance / (target * target));
177 if (needed >= static_cast<double>(std::numeric_limits<Eigen::Index>::max()))
178 return std::numeric_limits<Eigen::Index>::max();
179 return std::max(taken, static_cast<Eigen::Index>(needed));
180}

◆ sampleVariance()

double gpr::linalg::linop::sampleVariance ( const Eigen::VectorXd & draws)
nodiscard

Definition at line 182 of file Krylov.cpp.

183{
184 const Eigen::Index m = draws.size();
185 if (m < 2) return std::numeric_limits<double>::infinity();
186 const double mean = draws.mean();
187 return (draws.array() - mean).square().sum() / static_cast<double>(m - 1);
188}

◆ schurResidualTraces()

std::vector< double > gpr::linalg::linop::schurResidualTraces ( const Eigen::MatrixXd & L)
nodiscard

tr(S_r) for every r, S_r the Schur complement left by the first r rows of the lower factor L. For K = A0 + diag(s) >= A0 it bounds the residual trace of A0 under the same pivot order, at O(n^2) from a factor in hand.

Definition at line 57 of file Preconditioner.cpp.

58{
59 const Eigen::Index n = L.rows();
60 std::vector<double> traces(static_cast<std::size_t>(n + 1), 0.0);
61 long double tail = 0.0L;
62 for (Eigen::Index j = n - 1; j >= 0; --j) {
63 tail += static_cast<long double>(L.col(j).tail(n - j).squaredNorm());
64 traces[static_cast<std::size_t>(j)] = static_cast<double>(tail);
65 }
66 return traces;
67}

◆ standardNormalProbes()

Eigen::MatrixXd gpr::linalg::linop::standardNormalProbes ( Eigen::Index rows,
Eigen::Index cols,
std::uint64_t seed )
nodiscard

Standard normal draws from a fixed-seed counter generator, identical on every platform and thread count.

Definition at line 153 of file Krylov.cpp.

155{
156 Eigen::MatrixXd G(rows, cols);
157 std::uint64_t state = seed;
158 for (Eigen::Index j = 0; j < cols; ++j) {
159 for (Eigen::Index i = 0; i < rows; i += 2) {
160 const double u1 = unitOpen(splitmix64(state));
161 const double u2 = unitOpen(splitmix64(state));
162 const double radius = std::sqrt(-2.0 * std::log(u1));
163 const double angle = 2.0 * std::numbers::pi * u2;
164 G(i, j) = radius * std::cos(angle);
165 if (i + 1 < rows) G(i + 1, j) = radius * std::sin(angle);
166 }
167 }
168 return G;
169}