Loading...
Searching...
No Matches
Krylov.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// Copyright (c) gpridge developers
3// See LICENSE for details.
4
5#include "Krylov.h"
6
7#include <Eigen/Cholesky>
8#include <Eigen/Eigenvalues>
9#include <cmath>
10#include <limits>
11#include <numbers>
12#include <stdexcept>
13
14namespace gpr::linalg::linop {
15
16namespace {
17
18std::uint64_t splitmix64(std::uint64_t& state)
19{
20 std::uint64_t z = (state += 0x9E3779B97F4A7C15ULL);
21 z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9ULL;
22 z = (z ^ (z >> 27)) * 0x94D049BB133111EBULL;
23 return z ^ (z >> 31);
24}
25
26double unitOpen(std::uint64_t bits)
27{
28 return (static_cast<double>(bits >> 11) + 0.5) * 0x1.0p-53;
29}
30
31} // namespace
32
35 const Eigen::MatrixXd& B,
36 const BatchSolveSettings& settings)
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}
106
107namespace {
108
109template <typename F>
110double lanczosQuadrature(const BatchSolve& solve, Eigen::Index column, F f)
111{
112 const auto s = static_cast<std::size_t>(column);
113 const auto& a = solve.step[s];
114 const auto& b = solve.update[s];
115 const Eigen::Index k = static_cast<Eigen::Index>(a.size());
116 if (k == 0) return std::numeric_limits<double>::quiet_NaN();
117 Eigen::VectorXd diagonal(k);
118 Eigen::VectorXd off(std::max<Eigen::Index>(k - 1, 0));
119 for (Eigen::Index i = 0; i < k; ++i) {
120 const auto u = static_cast<std::size_t>(i);
121 diagonal(i) = 1.0 / a[u];
122 if (i > 0) diagonal(i) += b[u - 1] / a[u - 1];
123 if (i + 1 < k) off(i) = std::sqrt(b[u]) / a[u];
124 }
125 Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> eigen;
126 eigen.computeFromTridiagonal(diagonal, off, Eigen::ComputeEigenvectors);
127 if (eigen.info() != Eigen::Success ||
128 !(eigen.eigenvalues().array() > 0.0).all())
129 return std::numeric_limits<double>::quiet_NaN();
130 const Eigen::VectorXd first = eigen.eigenvectors().row(0).transpose();
131 double sum = 0.0;
132 for (Eigen::Index i = 0; i < k; ++i)
133 sum += first(i) * first(i) * f(eigen.eigenvalues()(i));
134 return solve.initial_norm(column) * sum;
135}
136
137} // namespace
138
139double lanczosLogQuadrature(const BatchSolve& solve, Eigen::Index column)
140{
141 return lanczosQuadrature(solve, column,
142 [](double x) { return std::log(x); });
143}
144
145double lanczosSquaredLogQuadrature(const BatchSolve& solve, Eigen::Index column)
146{
147 return lanczosQuadrature(solve, column, [](double x) {
148 const double l = std::log(x);
149 return l * l;
150 });
151}
152
153Eigen::MatrixXd standardNormalProbes(Eigen::Index rows, Eigen::Index cols,
154 std::uint64_t seed)
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}
170
171Eigen::Index probesForStandardError(double sample_variance, double target,
172 Eigen::Index taken)
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}
181
182double sampleVariance(const Eigen::VectorXd& draws)
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}
189
190double conjugateGradientIterations(double kappa, double tolerance)
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}
198
200 const Eigen::VectorXd& start)
201 : K_(K)
202{
203 if (start.size() != K.order())
204 throw std::invalid_argument("Lanczos start vector has the wrong order");
205 next_norm_ = start.norm();
206 if (!(next_norm_ > 0.0) || !std::isfinite(next_norm_))
207 throw std::invalid_argument("Lanczos start vector must be nonzero");
208 next_ = start / next_norm_;
209 Q_.resize(K.order(), 0);
210}
211
212bool LanczosVarianceCache::extend()
213{
214 const Eigen::Index n = K_.order(), k = steps();
215 if (exhausted_ || k >= n) return false;
216 Q_.conservativeResize(n, k + 1);
217 Q_.col(k) = next_;
218 Eigen::MatrixXd w;
219 K_.apply(Q_.col(k), w);
220 const double a = Q_.col(k).dot(w.col(0));
221 alpha_.push_back(a);
222 Eigen::VectorXd v = w.col(0);
223 for (int pass = 0; pass < 2; ++pass)
224 v.noalias() -= Q_ * (Q_.transpose() * v);
225 const double b = v.norm();
226 beta_.push_back(b);
227 flops_ += K_.applyFlops(1) + 8.0 * static_cast<double>(n * (k + 1));
228 if (!(b > std::numeric_limits<double>::epsilon() * std::abs(a))) {
229 exhausted_ = true;
230 next_.setZero();
231 next_norm_ = 0.0;
232 return true;
233 }
234 next_ = v / b;
235 next_norm_ = b;
236 return true;
237}
238
239LanczosVarianceCache::Quadratic LanczosVarianceCache::evaluate(
240 const Eigen::MatrixXd& C, double lambda_min) const
241{
242 const Eigen::Index k = steps(), m = C.cols();
243 Quadratic out;
244 out.value = Eigen::VectorXd::Zero(m);
245 out.error_bound = C.colwise().squaredNorm().transpose() / lambda_min;
246 if (k == 0) return out;
247 Eigen::MatrixXd T = Eigen::MatrixXd::Zero(k, k);
248 for (Eigen::Index i = 0; i < k; ++i) {
249 T(i, i) = alpha_[static_cast<std::size_t>(i)];
250 if (i + 1 < k)
251 T(i, i + 1) = T(i + 1, i) = beta_[static_cast<std::size_t>(i)];
252 }
253 const Eigen::LLT<Eigen::MatrixXd> llt(T);
254 if (llt.info() != Eigen::Success) return out;
255 const Eigen::MatrixXd G = Q_.transpose() * C;
256 const Eigen::MatrixXd Y = llt.solve(G);
257 out.value = (G.array() * Y.array()).colwise().sum().transpose();
258 Eigen::MatrixXd R = C - Q_ * G;
259 const double last = exhausted_ ? 0.0 : beta_.back();
260 R.noalias() -= (last * next_) * Y.row(k - 1);
261 out.error_bound = R.colwise().squaredNorm().transpose() / lambda_min;
262 out.flops = 6.0 * static_cast<double>(C.rows() * k * m) +
263 static_cast<double>(k * k * k) / 3.0 +
264 4.0 * static_cast<double>(k * k * m);
265 return out;
266}
267
269 const Eigen::MatrixXd& C, double tolerance, double lambda_min,
270 double flop_budget)
271{
272 if (C.rows() != K_.order() || !(lambda_min > 0.0))
273 throw std::invalid_argument("invalid Lanczos variance query");
274 const double start_flops = flops_;
275 double spent_on_queries = 0.0;
276 Quadratic out = evaluate(C, lambda_min);
277 spent_on_queries += out.flops;
278 // Double the basis between checks so evaluation stays a fixed fraction
279 // of the Lanczos work.
280 Eigen::Index target = std::max<Eigen::Index>(1, steps());
281 while (!(out.error_bound.maxCoeff() <= tolerance)) {
282 target = std::min<Eigen::Index>(K_.order(), 2 * target);
283 const double step_flops =
284 K_.applyFlops(1) + 8.0 * static_cast<double>(K_.order() * target);
285 bool grew = false;
286 while (steps() < target) {
287 if (flops_ - start_flops + spent_on_queries + step_flops >
288 flop_budget)
289 break;
290 if (!extend()) break;
291 grew = true;
292 }
293 if (!grew) break;
294 out = evaluate(C, lambda_min);
295 spent_on_queries += out.flops;
296 if (exhausted_ || steps() >= K_.order()) break;
297 }
298 out.within_tolerance = out.error_bound.maxCoeff() <= tolerance;
299 out.flops = flops_ - start_flops + spent_on_queries;
300 return out;
301}
302
303} // namespace gpr::linalg::linop
@ z
Definition Enums.h:28
@ x
Definition Enums.h:28
Quadratic quadraticDiagonal(const Eigen::MatrixXd &C, double tolerance, double lambda_min, double flop_budget)
Definition Krylov.cpp:268
LanczosVarianceCache(const SymmetricOperator &K, const Eigen::VectorXd &start)
Definition Krylov.cpp:199
Eigen::Index steps() const noexcept
Definition Krylov.h:106
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
BatchSolve batchConjugateGradients(const SymmetricOperator &K, const PivotedCholeskyPreconditioner &P, const Eigen::MatrixXd &B, const BatchSolveSettings &settings)
Definition Krylov.cpp:33
double conjugateGradientIterations(double kappa, double tolerance)
Definition Krylov.cpp:190
double lanczosLogQuadrature(const BatchSolve &solve, Eigen::Index column)
Definition Krylov.cpp:139
double sampleVariance(const Eigen::VectorXd &draws)
Definition Krylov.cpp:182
Eigen::Index probesForStandardError(double sample_variance, double target, Eigen::Index taken)
Definition Krylov.cpp:171
double lanczosSquaredLogQuadrature(const BatchSolve &solve, Eigen::Index column)
Definition Krylov.cpp:145
Eigen::MatrixXd standardNormalProbes(Eigen::Index rows, Eigen::Index cols, std::uint64_t seed)
Definition Krylov.cpp:153
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