Loading...
Searching...
No Matches
Predict.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// Predict-mean path: refreshPosteriorWeights (alpha = K^-1 y) + the
6// calculatePotential dispatcher chain. Also includes
7// calculatePosteriorMeanPrediction and usesRankOwnedMixturePosterior
8// which feed the same path.
9
11#ifdef GPR_LINALG_KOKKOS
13#endif
14#include "../PhaseTimers.h"
15
16#ifdef GPR_PREDICT_VIA_PCG
18#endif
19
23#include "CalibrationBounds.h"
24#include "Helpers.h"
26#ifdef GPR_LINALG_SCALAPACK
27#include <mpi.h>
28
33#endif
34
35#include <Eigen/Cholesky>
36#include <Eigen/Core>
37#include <algorithm>
38#include <atomic>
39#include <chrono>
40#include <cmath>
41#include <cstddef>
42#include <cstdio>
43#include <cstdlib>
44#include <map>
45#include <utility>
46#include <vector>
47
48namespace gpr {
49
50// Defined in gpr/ml/gp/EnergyGradient.cpp: running max|alpha| conditioning
51// diagnostic, updated here on the live prediction path.
52extern double g_max_abs_alpha;
53
54namespace {
55
56Eigen::VectorXd blockPrecisionLowerBounds(const EigenMatrix& factor,
57 Eigen::Index order
59 ,
61#endif
62)
63{
64 constexpr Eigen::Index block_size = 64;
65 if (order <= 2 * block_size ||
66 order > std::numeric_limits<int>::max() / block_size)
67 return {};
68 Eigen::VectorXd bounds = Eigen::VectorXd::Zero(order);
69 int rank = 0, ranks = 1;
70 Eigen::MatrixXd packed;
71#ifdef GPR_LINALG_SCALAPACK
72 if (factor.rows() == order && factor.cols() == order) state = nullptr;
73 if (state) {
74 rank = state->myrank();
75 ranks = state->nprocs();
76 packed = Eigen::MatrixXd::Zero(order, block_size);
77 const int* descriptor = state->cached_L_desc();
78 for (int column = 0; column < state->local_cols(order); ++column) {
79 const int global_column = state->global_index_for_local(
80 column, state->block_size(), state->mycol(), state->npcol());
81 if (global_column >= order) continue;
82 const Eigen::Index end =
83 std::min(order, (global_column / block_size + 1) * block_size);
84 for (int global_row = global_column; global_row < end;
85 ++global_row) {
86 if (!state->owns_global_entry(global_row, global_column))
87 continue;
88 const int row = state->local_index_for_global(
89 global_row, state->block_size(), state->myrow(),
90 state->nprow());
91 packed(global_row, global_column % block_size) =
92 state->cached_L()[row + static_cast<std::size_t>(column) *
93 descriptor[8]];
94 }
95 }
96 if (ranks > 1)
97 MPI_Allreduce(MPI_IN_PLACE, packed.data(),
98 static_cast<int>(packed.size()), MPI_DOUBLE, MPI_SUM,
99 state->world_comm());
100 }
101#endif
102 // A diagonal block of L^-1 is the inverse of the same diagonal block
103 // of L. Its column norms omit nonnegative contributions outside that
104 // block, so their lower bounds also bound diag((L L^T)^-1).
105 const Eigen::Index blocks = (order + block_size - 1) / block_size;
106 for (Eigen::Index block = rank; block < blocks; block += ranks) {
107 const Eigen::Index start = block * block_size;
108 const Eigen::Index count = std::min(block_size, order - start);
109 const Eigen::MatrixXd diagonal =
110 packed.size()
111 ? Eigen::MatrixXd(packed.block(start, 0, count, count))
112 : Eigen::MatrixXd(factor.block(start, start, count, count));
113 const Eigen::VectorXd lower =
114 detail::triangularPrecisionLowerBounds(diagonal);
115 if (lower.size() == count) bounds.segment(start, count) = lower;
116 }
117#ifdef GPR_LINALG_SCALAPACK
118 if (state && ranks > 1)
119 MPI_Allreduce(MPI_IN_PLACE, bounds.data(), static_cast<int>(order),
120 MPI_DOUBLE, MPI_SUM, state->world_comm());
121#endif
122 return bounds;
123}
124
125#ifdef GPR_LINALG_SCALAPACK
126struct PredictProfile {
127 std::atomic<long long> nanos_total{0};
128 std::atomic<long long> nanos_const{0};
129 std::atomic<long long> nanos_sexpat{0};
130 std::atomic<long long> calls{0};
131 std::atomic<bool> enabled{false};
132 ~PredictProfile()
133 {
134 if (!enabled.load(std::memory_order_relaxed)) return;
135 const double s = 1e-9;
136 std::fprintf(stderr,
137 "[predict-profile] calls=%lld total=%.6fs const=%.6fs "
138 "sexpat=%.6fs\n",
139 calls.load(), s * nanos_total.load(),
140 s * nanos_const.load(), s * nanos_sexpat.load());
141 }
142};
143
144PredictProfile& predict_profile()
145{
146 static PredictProfile pp;
147 return pp;
148}
149#endif
150
151} // namespace
152
154{
155#ifdef GPR_LINALG_KOKKOS
156 if (hasDevicePosterior()) return;
157#endif
158 // This function mimics the following MATLAB code
159 // a = L'\‍(L\‍[E_all;G_all(:)]);
161 if (rigid_deflation_.isActiveForFullOrder(R_matrix.rows()) &&
162 a.size() == rigid_deflation_.deflated_rows) {
163 a = rigid_deflation_.liftVectorZeroRigid(a);
164 }
165}
166
168 const Eigen::VectorXd& y)
169{
170#ifdef GPR_LINALG_KOKKOS
171 if (hasDevicePosterior()) {
174 a.resize(0);
175 recordHyperparameterDataTerm(static_cast<double>(y.size()),
176 device_posterior_->objectiveParts()[1]);
177 return;
178 }
179#endif
180 if (use_precision_) {
181 const EigenMatrix precision = trainingSolver().inverse();
182 const Eigen::VectorXd y_perm = permuteTrainingVector(y);
183 if (rigid_deflation_.isActiveForFullOrder(y_perm.size())) {
184 rigid_deflation_.updateTargetStats(y_perm);
185 a = rigid_deflation_.liftVectorZeroRigid(
186 precision * rigid_deflation_.projectVector(y_perm));
187 } else {
188 a.noalias() = precision * y_perm;
189 }
190 } else {
192 }
193}
194
195bool GaussianProcessRegression::usesRankOwnedMixturePosterior() const noexcept
196{
197 return false;
198}
199
200void GaussianProcessRegression::refreshPosteriorWeights(
201 const Eigen::VectorXd& y)
202{
203 ScopedPhaseTimer posterior_timer(PhaseTimers::posterior_seconds);
204 full_cartesian_training_dimension_ = -1;
205 if (sexpat_cov_func != nullptr && R_matrix.rows() == y.size() &&
206 R_indices.size() == R_matrix.rows()) {
207 const Eigen::Index dimensions =
208 3 * sexpat_cov_func->getConfInfo().atoms_mov.type.size();
209 const detail::ObservationChannelLayout channels(R_indices);
210 if (channels.completeCartesian(dimensions) &&
211 channels.repeatsCoordinates(R_matrix, dimensions))
212 full_cartesian_training_dimension_ = dimensions;
213 }
214 refreshPosteriorWeightsImpl(y);
215 prepareDescriptorPredictor();
216}
217void GaussianProcessRegression::prepareDescriptorPredictor()
218{
219 descriptor_predictor_ready_ = false;
220 if (!descriptor_predictor_enabled_ || use_hssvd_backend_ ||
221 full_cartesian_training_dimension_ < 0 || sexpat_cov_func == nullptr)
222 return;
223#ifdef GPR_LINALG_KOKKOS
225#endif
226 if (a.size() == 0 || R_matrix.rows() != a.size()) return;
227 Eigen::VectorXd l_feat;
228 Eigen::RowVectorXd mean_feat;
229 Eigen::MatrixXd Q;
230 std::vector<Eigen::MatrixXd> jac;
231 if (!buildDualDescriptors(R_matrix, l_feat, mean_feat, Q, jac)) return;
232 hssvd_l_feat_ = l_feat;
233 hssvd_mean_feat_ = mean_feat;
234 hssvd_train_qtil_ = Q;
235 hssvd_train_jtil_ = jac;
236 hssvd_dual_predict_weights_ =
239 : a;
240 descriptor_predictor_ready_ = true;
241 refreshHssvdDualForceJacobianWeights();
242}
243void GaussianProcessRegression::refreshPosteriorWeightsImpl(
244 const Eigen::VectorXd& y)
245{
246#ifdef GPR_LINALG_KOKKOS
247 if (hasDevicePosterior()) {
250 a.resize(0);
251 recordHyperparameterDataTerm(static_cast<double>(y.size()),
252 device_posterior_->objectiveParts()[1]);
254 return;
255 }
256#endif
257 // HS-SVD eigen-form posterior weights (#87). When the stable-basis backend
258 // is active, alpha = (K + sigma2 I)^{-1} y is computed from the
259 // eigendecomposition K = Psi diag(S^2) Psi^T (StableBasisND::solveNoisy),
260 // which is O(1)-conditioned regardless of the nugget -- replacing the
261 // Cholesky forward/back solve below. y is in the natural [E ; G
262 // column-major] order, matching the component-major design rows, so
263 // solveNoisy returns alpha in natural order; store it into `a` in the
264 // permuted frame the predict path (calculatePotential) unpermutes.
265 //
266 // The diagonal noise MUST match the total the Cholesky path inverts. The
267 // assembled training covariance C (CovarianceAssembly::
268 // evaluateTrainingCovarianceMatrix) is K_const + K_sexpat + sigma2 I, where
269 // sigma2 = lik_gaussian->getSigma2() is the uniform LikGaussian observation
270 // noise set on every energy AND gradient row (LikGaussian::
271 // evaluateTrainingCovarianceMatrix fills C.diagonal() with sigma2).
272 // Decompose then adds jitter_sigma2 on top via its rescue ladder. Under
273 // output standardization const_cov_fun is set to constSigma2 = 0, so
274 // K_const vanishes and the stable basis (which models only K_sexpat) is
275 // exact for the kernel; the effective nugget is sigma2 + jitter_sigma2.
276 // Passing only jitter_sigma2 under-regularizes by orders of magnitude
277 // (sigma2 >> jitter) and blows alpha up.
278 //
279 // Reset here (not just in clearHssvdBasisState): a caller that falls
280 // through to the non-HS-SVD path below on this call must not keep a
281 // calibration factor fit to a previous, now-stale basis.
282 hssvd_variance_calibration_factor_ = 1.0;
283 if (use_hssvd_backend_ && hssvd_basis_valid_ && y.size() > 0 &&
284 hssvd_basis_.rank() > 0 && hssvd_basis_.numObs() == y.size()) {
285 const double total_sigma2 = totalPosteriorNoiseVariance();
286 const StableBasisPosteriorWeights weights =
287 hssvd_basis_.noisyPosteriorWeights(y, total_sigma2);
289 : weights.alpha;
290 // Cancellation-free posterior-mean coefficients for the stable predict
291 // path (predictPotentialHssvd): p = S^2/(S^2+sigma2) (Psi^T y), in the
292 // natural [E ; G] order, never forming the large alpha.
293 hssvd_p_ = weights.reduced;
294 // Recomputed alongside hssvd_p_ so the calibration factor tracks the
295 // basis/training targets it was fit from; see StableBasisND::
296 // computeVarianceCalibrationFactor for the LOO derivation.
297 hssvd_variance_calibration_factor_ =
298 hssvd_basis_.computeVarianceCalibrationFactor(y, total_sigma2);
299 if (hssvd_dual_kernel_) {
300 hssvd_dual_predict_weights_ =
301 hssvd_basis_.leftSingularVectors() *
302 (hssvd_p_.array() /
303 hssvd_basis_.singularValues().array().square())
304 .matrix();
305 refreshHssvdDualForceJacobianWeights();
306 if (report_level >= 3) {
307 static int dbg_calls = 0;
308 if (dbg_calls++ < 4) {
309 int rk = 0, np = 1;
310#ifdef GPR_HAVE_MPI
311 int up = 0;
312 MPI_Initialized(&up);
313 if (up) {
314 MPI_Comm_rank(mpiContext().comm, &rk);
315 MPI_Comm_size(mpiContext().comm, &np);
316 }
317#endif
318 std::fprintf(
319 stderr,
320 "[DUALW] call=%d np=%d rk=%d rank=%ld nobs=%ld "
321 "sigma2=%.17g y.norm=%.17g p.norm=%.17g "
322 "S0=%.17g Smin=%.17g dualw.norm=%.17g "
323 "dualw.max=%.17g\n",
324 dbg_calls - 1, np, rk, (long)hssvd_basis_.rank(),
325 (long)hssvd_basis_.numObs(), total_sigma2, y.norm(),
326 hssvd_p_.norm(),
327 hssvd_basis_.singularValues().size() > 0
328 ? hssvd_basis_.singularValues()(0)
329 : 0.0,
330 hssvd_basis_.singularValues().size() > 0
331 ? hssvd_basis_.singularValues()(
332 hssvd_basis_.singularValues().size() - 1)
333 : 0.0,
334 hssvd_dual_predict_weights_.norm(),
335 hssvd_dual_predict_weights_.cwiseAbs().maxCoeff());
336 }
337 }
338 } else {
339 hssvd_dual_predict_weights_.resize(0);
340 hssvd_dual_force_jacobian_weights_.resize(0, 0);
341 }
342 b.resize(0);
343 return;
344 }
345#ifdef GPR_LINALG_SCALAPACK
346 if (usesRankOwnedMixturePosterior()) {
347 b.resize(0);
348 a.resize(0);
349 return;
350 }
351#endif
352#ifdef GPR_PREDICT_VIA_PCG
353 // The iterative reference solves the same regularized covariance as the
354 // direct path. Preconditioner quality controls work; acceptance requires
355 // the explicitly evaluated residual of the original system.
356 //
357 // Regularization includes jitter and the configured diagonal correction.
358 const int m = static_cast<int>(y.size());
359
360 EigenMatrix K_dense;
362 /*serial_per_rank=*/true);
363 if (jitter_sigma2 > 0.0) {
364 K_dense.diagonal().array() += jitter_sigma2;
365 }
366 if (use_correction_) {
367 const double K_sum = K_dense.diagonal().sum();
368 const double denom = 1.0 / correction_eps_ - static_cast<double>(m) * m;
369 if (std::abs(denom) > 1e-30) {
370 const double corr = K_sum * K_sum / denom;
371 K_dense.diagonal().array() += corr;
372 }
373 }
374
375 // A replicated Cholesky preconditioner supplies a numerical reference for
376 // the iterative path. Its cubic setup cost offers no factorization saving.
377 Eigen::LLT<EigenMatrix> full_llt(K_dense);
378 if (full_llt.info() != Eigen::Success) {
381 return;
382 }
383
384 const auto apply_K = [&](const Eigen::VectorXd& p) -> Eigen::VectorXd {
385 return (K_dense * p).eval();
386 };
387 const auto apply_M_inv = [&](const Eigen::VectorXd& r) -> Eigen::VectorXd {
388 return full_llt.solve(r);
389 };
390
391 linalg::PCGSettings pcg_settings;
392 pcg_settings.rtol = 1e-12;
393 pcg_settings.max_iterations = static_cast<int>(2 * m);
394 auto pcg_result =
395 linalg::preconditioned_cg(apply_K, apply_M_inv, y, pcg_settings);
396 // An unconverged Krylov solve does not give slightly wrong representer
397 // weights; it gives weights that are unconstrained in the directions the
398 // solver never explored (Wenger et al., NeurIPS 2022,
399 // DOI 10.48550/arxiv.2205.15449). Nothing downstream carries that
400 // computational uncertainty, and the posterior variance is computed from a
401 // separate path that would report the same confidence either way, so a
402 // silent non-convergence here reads as a converged fit. Fall back to the
403 // direct solve, exactly as a failed preconditioner factorization does.
404 if (!pcg_result.converged) {
405 log_man << "PCG did not converge after " << pcg_result.iterations
406 << " iterations (relative residual "
407 << pcg_result.final_residual
408 << "); falling back to the direct solve\n";
411 return;
412 }
413 a = permuteTrainingVector(pcg_result.x);
414 b.resize(0);
415 // LOO calibration from the same factor the mean used: q = diag(K^-1)
416 // as the column norms of L^-1, alpha = the natural-order PCG solution
417 // (the median z^2 is order-free). Previously this branch never set the
418 // factor, so the dense backend reported 1.0 while the stable basis
419 // reported the statistic.
420 if (m >= 2) {
421 const EigenMatrix L_dense = full_llt.matrixL();
422 const Eigen::VectorXd q =
424 L_dense, EigenMatrix::Identity(m, m));
425 if (q.size() == pcg_result.x.size()) {
426 hssvd_variance_calibration_factor_ =
427 looVarianceCalibrationFactor(pcg_result.x, q);
428 }
429 }
430#else
433 // Calibration uses the same alpha and inverse diagonal on every backend.
434 // Both vectors share the factor's training permutation; the median is
435 // independent of that ordering.
436 if (a.size() >= 2 && hasTrainingCholeskyFactor(a.size())) {
437 if (rigid_deflation_.isActiveForFullOrder(a.size())) {
438 const Eigen::VectorXd a_full = a + rigid_deflation_.a_rigid;
439 const Eigen::VectorXd& inverse_diagonal =
441 if (inverse_diagonal.size() == a_full.size()) {
442 hssvd_variance_calibration_factor_ =
443 looVarianceCalibrationFactor(a_full, inverse_diagonal);
444 }
445 return;
446 }
447 if (training_inverse_diagonal_.size() != a.size()) {
448 int unit_calibration = looCalibrationIsUnityFromCholeskyDiagonal(
450#ifdef GPR_LINALG_SCALAPACK
451 if (training_cholesky_is_distributed_) {
452 auto& state = backend().distributed();
453 if (state.nprocs() > 1)
454 MPI_Allreduce(MPI_IN_PLACE, &unit_calibration, 1, MPI_INT,
455 MPI_MIN, state.world_comm());
456 }
457#endif
458 if (!unit_calibration) {
459 const Eigen::VectorXd bounds = blockPrecisionLowerBounds(
460 L, a.size()
462 ,
463 training_cholesky_is_distributed_ ? &backend().distributed()
464 : nullptr
465#endif
466 );
467 unit_calibration =
468 detail::precisionBoundsCertifyUnitCalibration(a, bounds);
469#ifdef GPR_LINALG_SCALAPACK
470 if (training_cholesky_is_distributed_) {
471 auto& state = backend().distributed();
472 if (state.nprocs() > 1)
473 MPI_Allreduce(MPI_IN_PLACE, &unit_calibration, 1,
474 MPI_INT, MPI_MIN, state.world_comm());
475 }
476#endif
477 }
478 if (unit_calibration) {
479 hssvd_variance_calibration_factor_ = 1.0;
480 return;
481 }
482 }
483 const Eigen::VectorXd& inverse_diagonal =
485 if (inverse_diagonal.size() == a.size()) {
486 hssvd_variance_calibration_factor_ =
487 looVarianceCalibrationFactor(a, inverse_diagonal);
488 }
489 }
490#endif
491}
492
494{
495 const Eigen::Index order = a.size();
496 if (!hasTrainingCholeskyFactor(order)) return {};
497 if (L.rows() == order && L.cols() == order) return L.diagonal();
498#ifdef GPR_LINALG_SCALAPACK
499 auto& state = backend().distributed();
500 Eigen::VectorXd diagonal = Eigen::VectorXd::Zero(order);
501 const int* descriptor = state.cached_L_desc();
502 for (int i = 0; i < order; ++i) {
503 const int owner_row = (i / state.block_size()) % state.nprow();
504 const int owner_col = (i / state.block_size()) % state.npcol();
505 if (owner_row != state.myrow() || owner_col != state.mycol()) continue;
506 const int row = state.local_index_for_global(
507 i, state.block_size(), state.myrow(), state.nprow());
508 const int column = state.local_index_for_global(
509 i, state.block_size(), state.mycol(), state.npcol());
510 diagonal(i) = state.cached_L()[row + static_cast<std::size_t>(column) *
511 descriptor[8]];
512 }
513 if (state.nprocs() > 1)
514 MPI_Allreduce(MPI_IN_PLACE, diagonal.data(), static_cast<int>(order),
515 MPI_DOUBLE, MPI_SUM, state.world_comm());
516 return diagonal;
517#else
518 return {};
519#endif
520}
521
522const Eigen::VectorXd&
524{
525#ifdef GPR_LINALG_KOKKOS
526 if (hasDevicePosterior()) {
527 if (training_inverse_diagonal_.size() != device_posterior_->order()) {
529 device_posterior_->downloadInverseDiagonal();
530 ++inverse_diagonal_builds_for_testing_;
531 }
533 }
534#endif
535 if (training_inverse_diagonal_.size() == a.size() ||
538#ifdef GPR_LINALG_SCALAPACK
539 if (training_cholesky_is_distributed_) {
541 backend().cholesky_inverse_diagonal_distributed(
542 L, static_cast<int>(a.size()));
543 } else {
544 const EigenMatrix inverse_factor =
545 L.template triangularView<Eigen::Lower>().solve(
546 EigenMatrix::Identity(a.size(), a.size()));
548 inverse_factor.colwise().squaredNorm().transpose();
549 }
550#else
551 if (rigid_deflation_.isActiveForFullOrder(a.size())) {
553 rigid_deflation_.fullInverseDiagonalFromFactor(L);
554 } else {
556 EigenMatrix::Identity(a.size(), a.size()));
557 }
558#endif
559 ++inverse_diagonal_builds_for_testing_;
561}
562
563#ifdef GPR_LINALG_SCALAPACK
564EigenMatrix GaussianProcessRegression::wholeRankCachedCholeskyFactor() const
565{
566 auto& st = backend().distributed();
567 if (st.nprocs() != 1 || !st.has_cached_L() || st.cached_n() <= 0)
568 return EigenMatrix();
569 const int n = st.cached_n();
570 const int* desc = st.cached_L_desc();
571 const int lld = desc ? std::max(desc[8], n) : n;
572 Eigen::Map<const Eigen::MatrixXd, 0, Eigen::OuterStride<>> whole(
573 st.cached_L(), n, n, Eigen::OuterStride<>(lld));
574 EigenMatrix L_whole = EigenMatrix::Zero(n, n);
575 L_whole.template triangularView<Eigen::Lower>() = whole;
576 return L_whole;
577}
578#endif
579
580void GaussianProcessRegression::refreshHssvdDualForceJacobianWeights()
581{
582 hssvd_dual_force_jacobian_weights_.resize(0, 0);
583 hssvd_dual_alpha_k_prepared_ = SexpatCF::PreparedAlphaK{};
584 const Eigen::Index ntrain = hssvd_train_qtil_.rows();
585 const Eigen::Index dfeat = hssvd_l_feat_.size();
586 if (ntrain <= 0 || dfeat <= 0 ||
587 static_cast<Eigen::Index>(hssvd_train_jtil_.size()) != ntrain)
588 return;
589
590 const Eigen::Index total_weights = hssvd_dual_predict_weights_.size();
591 if (total_weights <= ntrain || total_weights % ntrain != 0) return;
592 const Eigen::Index dof = total_weights / ntrain - 1;
593 if (dof <= 0) return;
594
595 for (const auto& Ji: hssvd_train_jtil_)
596 if (Ji.rows() != dfeat || Ji.cols() != dof) return;
597
598 if (sexpat_cov_func != nullptr &&
599 full_cartesian_training_dimension_ == dof &&
600 R_matrix.rows() == total_weights && R_matrix.cols() == dof + 1 &&
601 R_matrix.rows() >= ntrain) {
602 const Coord x_train = R_matrix.topRows(ntrain);
604 if (sexpat_cov_func->prepareAlphaK(
605 x_train, hssvd_dual_predict_weights_.head(ntrain),
606 hssvd_dual_predict_weights_, prepared)) {
607 hssvd_dual_alpha_k_prepared_ = std::move(prepared);
608 }
609 }
610
611 hssvd_dual_force_jacobian_weights_ = descriptorForceJacobianWeights(
612 hssvd_dual_alpha_k_prepared_, hssvd_train_jtil_,
613 hssvd_dual_predict_weights_);
614}
615
616Eigen::MatrixXd GaussianProcessRegression::descriptorForceJacobianWeights(
617 const SexpatCF::PreparedAlphaK& alpha_k,
618 const std::vector<Eigen::MatrixXd>& train_jtil,
619 const Eigen::VectorXd& predict_weights) const
620{
621 const Eigen::Index ntrain = static_cast<Eigen::Index>(train_jtil.size());
622 const Eigen::Index dfeat = hssvd_l_feat_.size();
623 Eigen::MatrixXd weights = Eigen::MatrixXd::Zero(ntrain, dfeat);
624 if (ntrain <= 0 || predict_weights.size() % ntrain != 0) return weights;
625 const Eigen::Index dof = predict_weights.size() / ntrain - 1;
626
627 // Each inverse-distance feature row is +du/dx_a on atom a and -du/dx_a
628 // on a moving partner b, so its weight is (w_a - w_b) . du/dx_a / l_k.
629 // The predictor contracts that difference with a compensated sum; a
630 // plain J^T w here cancels the translation part of large weights only
631 // to rounding, and the Hessian would no longer differentiate the mean.
632 if (alpha_k.valid && alpha_k.num_train == ntrain) {
633 if (alpha_k.cutoff_rows.empty() &&
634 static_cast<Eigen::Index>(alpha_k.pairs.size()) == dfeat &&
635 static_cast<Eigen::Index>(alpha_k.c_p_train.size()) ==
636 ntrain * dfeat) {
637 for (Eigen::Index i = 0; i < ntrain; ++i)
638 for (Eigen::Index k = 0; k < dfeat; ++k)
639 weights(i, k) = alpha_k.c_p_train[static_cast<std::size_t>(
640 i * dfeat + k)] /
641 hssvd_l_feat_(k);
642 return weights;
643 }
644 if (static_cast<Eigen::Index>(alpha_k.cutoff_rows.size()) == ntrain &&
645 static_cast<Eigen::Index>(alpha_k.cutoff_gradient_weights.size()) ==
646 ntrain) {
647 // Cutoff rows hold only the pairs present at each geometry; an
648 // absent pair is a zero row of the dense Jacobian.
650 sexpat_cov_func->getConfInfo(),
651 sexpat_cov_func->farFieldRadius());
652 if (static_cast<Eigen::Index>(keys.size()) != dfeat)
653 throw std::logic_error(
654 "descriptor pair vocabulary does not match its length "
655 "scales");
656 std::map<std::pair<Eigen::Index, Eigen::Index>, Eigen::Index>
657 feature;
658 for (Eigen::Index k = 0; k < dfeat; ++k)
659 feature.emplace(keys[static_cast<std::size_t>(k)], k);
660 for (Eigen::Index i = 0; i < ntrain; ++i) {
661 const auto& row =
662 alpha_k.cutoff_rows[static_cast<std::size_t>(i)];
663 const auto& contracted =
664 alpha_k
665 .cutoff_gradient_weights[static_cast<std::size_t>(i)];
666 for (std::size_t j = 0; j < row.size(); ++j) {
667 const Eigen::Index k =
668 feature.at({row[j].first, row[j].second});
669 weights(i, k) = contracted[j] / hssvd_l_feat_(k);
670 }
671 }
672 return weights;
673 }
674 }
675
676 for (Eigen::Index i = 0; i < ntrain; ++i) {
677 const Eigen::MatrixXd& Ji = train_jtil[static_cast<std::size_t>(i)];
678 Eigen::RowVectorXd gi = Eigen::RowVectorXd::Zero(dfeat);
679 for (Eigen::Index c = 0; c < dof; ++c) {
680 const double wG = predict_weights(ntrain + c * ntrain + i);
681 gi.noalias() += wG * Ji.col(c).transpose();
682 }
683 weights.row(i) = gi;
684 }
685 return weights;
686}
687
689 const Eigen::VectorXd& y)
690{
691#ifdef GPR_LINALG_KOKKOS
692 if (hasDevicePosterior()) {
695 a.resize(0);
696 recordHyperparameterDataTerm(static_cast<double>(y.size()),
697 device_posterior_->objectiveParts()[1]);
698 return;
699 }
700#endif
701 // This function mimics the following MATLAB code
702 // b = L\‍[E_all;G_all(:)];
703 const Eigen::VectorXd y_perm = permuteTrainingVector(y);
704 if (rigid_deflation_.isActiveForFullOrder(y_perm.size())) {
705 rigid_deflation_.updateTargetStats(y_perm);
706 b = trainingSolver().whiten(rigid_deflation_.projectVector(y_perm));
707 } else {
708 b = trainingSolver().whiten(y_perm);
709 }
710 recordHyperparameterDataTerm(static_cast<double>(y.size()), b.dot(b));
711}
712
714{
715#ifdef GPR_LINALG_KOKKOS
716 if (predictDevicePosterior(image1, false)) return;
717#endif
718 if (atomic_environment_model_) {
719 calculateAtomicEnvironmentPotential(image1);
720 return;
721 }
722 // NOTE: C is a truncated covariance!
723
724 Index_t N_im = image1.R.rows();
725 Index_t D = image1.R.cols();
726 EigenMatrix R_mod;
727 Eigen::VectorXd R_mod_ind;
728 EigenMatrix KK;
729 Eigen::VectorXd EG_R;
731
732 // [repmat(R,D+1,1),reshape(repmat(0:D,N_im,1),[],1)]
733 aux_func.assembleMatrixOfRepetitiveCoordinates(image1.R, R_mod, R_mod_ind);
734
735 // When the most recent Cholesky rescue in decomposeCovarianceMatrix fails,
736 // `a` can retain a size from a differently-sized training set. Emit NaN
737 // for energy/gradient so the caller's existing "Energy is not finite"
738 // path handles the failure cleanly; the path is wired into the SCG/dimer
739 // outer loops as a retry signal. Same NaN-fallback when the model has no
740 // training data.
741 // at all (R_matrix empty): the per-tile cross-cov assembly downstream
742 // would otherwise dereference weights[0] on a zero-size alpha.
743 if (R_matrix.rows() == 0 || a.size() == 0 || R_matrix.rows() != a.size()) {
744 const double nan = std::numeric_limits<double>::quiet_NaN();
745 image1.E.resize(1, N_im);
746 image1.G.resize(N_im, D);
747 for (Index_t i = 0; i < N_im; ++i)
748 image1.E(0, i) = nan;
749 for (Index_t i = 0; i < N_im; ++i)
750 for (Index_t j = 0; j < D; ++j)
751 image1.G(i, j) = nan;
752 ++num_of_potential_calls;
753 return;
754 }
755
756 // HS-SVD cancellation-free force path: predict energy + Cartesian forces
757 // from the stable basis (predictEnergy/Gradient on the reduced coeff p),
758 // never forming the ill-conditioned alpha = K^{-1} y. This is what makes
759 // the HS-SVD path numerically robust WITHOUT output normalization. Gated
760 // behind the backend (off by default; production path unchanged).
761 if (use_hssvd_backend_ && hssvd_basis_valid_ &&
762 hssvd_basis_.numObs() == energy_and_gradient.size() &&
763 hssvd_p_.size() > 0 && hssvd_mean_feat_.size() > 0) {
764 predictPotentialHssvd(image1);
765 return;
766 }
767 if (descriptor_predictor_ready_ && !use_hssvd_backend_ &&
768 hssvd_dual_predict_weights_.size() == R_matrix.rows() &&
769 hssvd_train_qtil_.rows() > 0) {
770 predictPotentialHssvdDual(image1);
771 return;
772 }
773
774#ifdef GPR_LINALG_SCALAPACK
775 Eigen::VectorXd a_unpermuted =
778 : a;
779 // Conditioning symptom on the live force path: alpha = K^{-1} y. With
780 // O(1-10) eV / (eV/A) targets, max|alpha| >> ~1e2 means K^{-1} is
781 // amplifying (ill-conditioned), so mu = sum alpha_i k_i cancels large
782 // terms and 1 ULP anywhere blows up. Defined in EnergyGradient.cpp.
783 if (a_unpermuted.size() > 0) {
784 const double amax = a_unpermuted.cwiseAbs().maxCoeff();
785 if (amax > g_max_abs_alpha) g_max_abs_alpha = amax;
786 }
787 Eigen::VectorXd EG_R_local = Eigen::VectorXd::Zero(R_mod.rows());
788 Eigen::VectorXd uDdim, uDdim2;
790 extractUniqueIndices(R_mod_ind, uDdim2);
791
792 auto& _pp = predict_profile();
793 if (profile_predict_mean_) {
794 _pp.enabled.store(true, std::memory_order_relaxed);
795 }
796 const auto _t0 = std::chrono::steady_clock::now();
798 R_matrix, R_mod, R_indices, uDdim, R_mod_ind, uDdim2, *const_cov_fun,
799 a_unpermuted, EG_R_local, training_cholesky_is_distributed_, true);
800 const auto _t1 = std::chrono::steady_clock::now();
801 {
802 // Alpha-K Path 2 (Schmitz/Chmiela JPCL 2022 eq.6):
803 // per-test-point per-pair predict-mean, bypassing the
804 // (D_train x D_test) accumulator sub-block loop.
805 if (use_alpha_k_predict_mean_ && sexpat_cov_func &&
806 full_cartesian_training_dimension_ == D &&
807 !sexpat_cov_func->usesManifoldChart() &&
808 !sexpat_cov_func->usesGeodesicHeatKernel()) {
809 // R_matrix is the per-observation training matrix with each
810 // training POSITION repeated (D + 1) times (one row per
811 // energy + per gradient component). Extract the unique
812 // training positions for the alpha-K predict: the first
813 // num_train_pts rows (the energy-observation slab; matches
814 // extractCoordinatesByIndex(x, ind, 0, x_loc_0)).
815 const Eigen::Index num_train_pts = R_matrix.rows() / (D + 1);
816 // a_unpermuted layout: [alpha_E (num_train_pts entries),
817 // alpha_G for d=1 (num_train_pts), ..., alpha_G for d=D
818 // (num_train_pts)]. predictMeanAlphaK indexes
819 // alpha_G_flat[d * num_train + i] -- the SAME layout.
820
821 Eigen::VectorXd alpha_k_mean = Eigen::VectorXd::Zero(R_mod.rows());
822 Eigen::VectorXd mu_E_out = Eigen::VectorXd::Zero(N_im);
823 Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic,
824 Eigen::RowMajor>
825 mu_G_out = Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic,
826 Eigen::RowMajor>::Zero(N_im, D);
827 const auto predict_full_training_set = [&]() {
828 sexpat_cov_func->predictMeanAlphaK(
829 R_matrix.topRows(num_train_pts), image1.R,
830 a_unpermuted.head(num_train_pts), a_unpermuted, mu_E_out,
831 mu_G_out);
832 };
833
834 // The training points are contracted in chunks of a fixed size
835 // that does not depend on the rank count. A chunk is evaluated
836 // whole on one rank, so its partial means are a function of its
837 // contents alone, and the chunk partials enter exact accumulators
838 // whose merge is an integer sum. The reduced mean therefore
839 // carries the same bits at every rank count, at one rank as well,
840 // which contracts every chunk itself. A training set of one chunk
841 // is the full contraction.
842 constexpr Eigen::Index kAlphaKChunk = 64;
843 const Eigen::Index chunks =
844 (num_train_pts + kAlphaKChunk - 1) / kAlphaKChunk;
845 if (chunks <= 1) {
846 predict_full_training_set();
847 } else {
848 int mpi_np = 1, mpi_rank = 0;
849 if (training_cholesky_is_distributed_) {
850 auto& alpha_st = backend().distributed();
851 alpha_st.initialize();
852 mpi_np = alpha_st.nprocs();
853 mpi_rank = alpha_st.myrank();
854 }
855 std::vector<linalg::ExactSum> mean_E(
856 static_cast<std::size_t>(N_im));
857 std::vector<linalg::ExactSum> mean_G(
858 static_cast<std::size_t>(N_im * D));
859 Eigen::VectorXd mu_E_chunk(N_im);
860 Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic,
861 Eigen::RowMajor>
862 mu_G_chunk(N_im, D);
863 Eigen::VectorXd alpha_G_flat_slice;
864 for (Eigen::Index chunk = mpi_rank; chunk < chunks;
865 chunk += mpi_np) {
866 const Eigen::Index slice_start = chunk * kAlphaKChunk;
867 const Eigen::Index slice_count = std::min<Eigen::Index>(
868 kAlphaKChunk, num_train_pts - slice_start);
869 const EigenMatrix x_train_slice =
870 R_matrix.middleRows(slice_start, slice_count);
871 const Eigen::VectorXd alpha_E_slice =
872 a_unpermuted.segment(slice_start, slice_count);
873 // Re-pack alpha_G_flat for the train-slice layout
874 // predictMeanAlphaK expects: entry
875 // [d * slice_count + i] = full alpha
876 // [d * num_train_full + (slice_start + i)].
877 alpha_G_flat_slice.resize(slice_count * (D + 1));
878 for (Eigen::Index d = 0; d <= D; ++d) {
879 alpha_G_flat_slice.segment(d * slice_count,
880 slice_count) =
881 a_unpermuted.segment(
882 d * num_train_pts + slice_start, slice_count);
883 }
884 mu_E_chunk.setZero();
885 mu_G_chunk.setZero();
886 sexpat_cov_func->predictMeanAlphaK(
887 x_train_slice, image1.R, alpha_E_slice,
888 alpha_G_flat_slice, mu_E_chunk, mu_G_chunk);
889 for (Eigen::Index m = 0; m < N_im; ++m) {
890 mean_E[static_cast<std::size_t>(m)].add(mu_E_chunk(m));
891 for (Eigen::Index d = 0; d < D; ++d)
892 mean_G[static_cast<std::size_t>(m * D + d)].add(
893 mu_G_chunk(m, d));
894 }
895 }
896 if (mpi_np > 1) {
897 backend().exact_sum_bcast(mean_E.data(),
898 static_cast<int>(mean_E.size()));
899 backend().exact_sum_bcast(mean_G.data(),
900 static_cast<int>(mean_G.size()));
901 }
902 for (Eigen::Index m = 0; m < N_im; ++m) {
903 mu_E_out(m) = mean_E[static_cast<std::size_t>(m)].value();
904 for (Eigen::Index d = 0; d < D; ++d)
905 mu_G_out(m, d) =
906 mean_G[static_cast<std::size_t>(m * D + d)].value();
907 }
908 }
909
910 // Splice mu_E + mu_G into alpha_k_mean using the column-major
911 // (m, d) layout matching image1.E / image1.G downstream.
912 for (Index_t m = 0; m < N_im; ++m) {
913 alpha_k_mean(m) += mu_E_out(m);
914 }
915 for (Index_t d = 0; d < D; ++d) {
916 for (Index_t m = 0; m < N_im; ++m) {
917 alpha_k_mean(N_im + d * N_im + m) += mu_G_out(m, d);
918 }
919 }
920 EG_R_local += alpha_k_mean;
921 } else {
922 Eigen::VectorXd tmp = Eigen::VectorXd::Zero(R_mod.rows());
924 R_matrix, R_mod, R_indices, uDdim, R_mod_ind, uDdim2,
925 *sexpat_cov_func, a_unpermuted, tmp,
926 training_cholesky_is_distributed_, true);
927 EG_R_local += tmp;
928 }
929 }
930 const auto _t2 = std::chrono::steady_clock::now();
931 if (profile_predict_mean_) {
932 const auto to_ns = [](auto a, auto b) {
933 return std::chrono::duration_cast<std::chrono::nanoseconds>(b - a)
934 .count();
935 };
936 _pp.nanos_const.fetch_add(to_ns(_t0, _t1), std::memory_order_relaxed);
937 _pp.nanos_sexpat.fetch_add(to_ns(_t1, _t2), std::memory_order_relaxed);
938 _pp.nanos_total.fetch_add(to_ns(_t0, _t2), std::memory_order_relaxed);
939 _pp.calls.fetch_add(1, std::memory_order_relaxed);
940 }
941
942 // accumulateCrossCovarianceMatVecLocal() already returns the assembled
943 // prediction vector on every rank. Reducing again here scales the final
944 // prediction by nprocs and breaks multi-rank correctness.
945 EG_R = EG_R_local;
946#else
947 // KK =
948 // gp_cov(gp,R_all2,[repmat(R,D+1,1),reshape(repmat(0:D,N_im,1),[],1)]);
949 evaluateCovarianceMatrix(R_matrix, R_mod, R_indices, R_mod_ind, KK);
950 KK = permuteTrainingRows(KK);
951
952 // EG_R = KK'*a. Compensated and the named modes share
953 // evaluateStoredProduct. Compensated mode sums each TwoProductFMA
954 // expansion with ExactSum and rounds once, so 2^54 + 1 - 2^54 stays 1
955 // and a residual below the running Neumaier correction is kept.
956 EG_R.resize(KK.cols());
957 const auto product_mode = linalg::productMode();
958 // Columns are the energy and the force components of each test point.
959 // contractPredictionMatrix runs those dots on the OpenMP team when the
960 // measured fork cost says the team is faster. Each dot keeps its own
961 // ascending index order.
962 linalg::contractPredictionMatrix(KK.data(), static_cast<int>(KK.rows()),
963 static_cast<int>(KK.cols()), a.data(),
964 EG_R.data(), product_mode);
965#endif
966
967 // E_R = EG_R(1:N_im,1);
968 image1.E.resize(1, N_im);
969 image1.E = Eigen::Map<const Eigen::RowVectorXd>(EG_R.data(), N_im);
970
971 // G_R = reshape(EG_R((N_im+1):end,1),N_im,D);
972 // EG_R stores gradient columns contiguously in column-major order, so we
973 // use a ColMajor map and assign to RowMajor G.
974 image1.G.resize(N_im, D);
975 image1.G = Eigen::Map<const Eigen::Matrix<double, Eigen::Dynamic,
976 Eigen::Dynamic, Eigen::ColMajor>>(
977 EG_R.data() + N_im, N_im, D);
978
979 ++num_of_potential_calls;
980}
981
983 Observation& image1)
984{
985 ScopedPredictTimer predict_timer;
986 if (atomic_environment_model_) {
987 calculateAtomicEnvironmentPotential(image1);
988 return;
989 }
990 if (active_posterior_) {
991 calculateActivePosteriorMean(image1);
992 return;
993 }
994 calculateBackgroundPotentialDispatched(image1);
995}
996
997void GaussianProcessRegression::calculateBackgroundPotentialDispatched(
998 Observation& image1)
999{
1000 if (atomic_environment_model_) {
1001 calculateAtomicEnvironmentPotential(image1);
1002 return;
1003 }
1004 // The trained model is in standardized output coordinates (targets
1005 // E~=(E-y_mean_)/y_scale_, G~=G/y_scale_), so the inner predicts below
1006 // return E~ and its raw-descriptor gradient. Un-normalize once after
1007 // dispatch: E = y_scale_*E~ + y_mean_, grad = y_scale_*grad~ (derived in
1008 // scripts/derive_gp_normalization.py). Variance is un-normalized in
1009 // calculateVarianceDispatched (* y_scale_^2).
1010 //
1011 // RFF-replace path: above the design cutoff the exact dual-kernel
1012 // eigensolve was skipped (rff_replaces_exact_), so the RFF model is
1013 // the only fitted model -- route the mean through it regardless of
1014 // uncertainty_mode_. Below the cutoff this is false and the
1015 // mode-specific dispatch below runs unchanged (the LAPLACE_SLICE arm
1016 // keeps its own layered-RFF fast path).
1017 if (rff_replaces_exact_ && rff_model_.isBuilt()) {
1018 calculatePotentialRFF(image1);
1019 return;
1020 }
1021 switch (uncertainty_mode_) {
1024 break;
1026 // Cheap-mean path. The dimer's mean predict gets called many
1027 // times per outer iter (rotation/translation steps) but the
1028 // variance-gated
1029 // acquisition only consults variance. Route the mean through
1030 // MAP (single Cholesky-solve on the trained model, no
1031 // M-burst) and keep calibrated Bayesian variance via the
1032 // slice cache in calculateVarianceLaplaceSlice. Mirror of the
1033 // EB pattern at line 3429.
1034 //
1035 // RFF layered path: when rff_features_ > 0 and the model is
1036 // built (buildRFFModel ran post-fit), route mean predicts
1037 // through the RFF model instead of MAP. The per-call cost
1038 // drops from O(N (D+1)) (MAP cross-cov + matvec) to
1039 // O(D_rff D) (constant in N). INLA-Delta variance is
1040 // unchanged; only the predict-mean hot path is replaced.
1041 //
1042 // calculatePotentialLaplaceSlice() (the slice mixture mean)
1043 // is kept reachable for off-dispatch benches and the unit
1044 // test fixture; it just isn't on the production hot path.
1045 if (rff_features_ > 0 && rff_model_.isBuilt()) {
1046 // The RFF model trains on the raw observation and centers
1047 // internally on its own e_ref_, so its predict already
1048 // returns PHYSICAL energies. Return before the y_mean_ /
1049 // y_scale_ un-normalization below, matching the
1050 // rff_replaces_exact_ arm above; falling through applies
1051 // the output transform a second time.
1052 calculatePotentialRFF(image1);
1053 return;
1054 }
1055 calculatePotential(image1);
1056 break;
1058 calculatePotentialSVGD(image1);
1059 break;
1061 // Empirical Bayes: use the MAP point estimate for the mean
1062 // (no Taylor correction risk on small data) but route the
1063 // variance through the LAPLACE mixture for calibrated
1064 // hyperparameter uncertainty. Carlin & Louis 2008 standard;
1065 // R-INLA's approx hyperpar.dist mode does the same.
1066 calculatePotential(image1);
1067 break;
1069 calculatePotentialBMA(image1);
1070 break;
1072 default:
1073 calculatePotential(image1);
1074 break;
1075 }
1076 // Un-normalize the standardized prediction back to physical units.
1077 if (y_scale_ != 1.0 || y_mean_ != 0.0) {
1078 if (image1.E.size() > 0)
1079 image1.E.array() = y_scale_ * image1.E.array() + y_mean_;
1080 if (image1.G.size() > 0) image1.G.array() *= y_scale_;
1081 }
1082 addPriorMeanToObservation(image1);
1083}
1084
1085namespace {
1086
1087bool stackSameCompositionQueries(const std::vector<Observation*>& queries,
1088 Observation& stacked,
1089 std::vector<Index_t>& row_counts)
1090{
1091 stacked = Observation{};
1092 row_counts.clear();
1093 Index_t total = 0;
1094 Index_t D = 0;
1095 for (Observation* q: queries) {
1096 if (q == nullptr || q->R.rows() <= 0 || q->R.cols() <= 0) return false;
1097 if (D == 0) D = q->R.cols();
1098 if (q->R.cols() != D) return false;
1099 row_counts.push_back(q->R.rows());
1100 total += q->R.rows();
1101 }
1102 if (total <= 0 || D <= 0) return false;
1103 stacked.R.resize(total, D);
1104 Index_t offset = 0;
1105 for (std::size_t i = 0; i < queries.size(); ++i) {
1106 stacked.R.block(offset, 0, row_counts[i], D) = queries[i]->R;
1107 offset += row_counts[i];
1108 }
1109 return true;
1110}
1111
1112void unstackEnergyGradient(const Observation& stacked,
1113 const std::vector<Observation*>& queries,
1114 const std::vector<Index_t>& row_counts)
1115{
1116 const Index_t D = stacked.R.cols();
1117 Index_t offset = 0;
1118 for (std::size_t i = 0; i < queries.size(); ++i) {
1119 const Index_t n = row_counts[i];
1120 queries[i]->E.resize(1, n);
1121 queries[i]->G.resize(n, D);
1122 if (stacked.E.cols() >= offset + n)
1123 queries[i]->E = stacked.E.block(0, offset, 1, n);
1124 if (stacked.G.rows() >= offset + n)
1125 queries[i]->G = stacked.G.block(offset, 0, n, D);
1126 offset += n;
1127 }
1128}
1129
1130} // namespace
1131
1133 std::vector<Observation*> queries)
1134{
1135 Observation stacked;
1136 std::vector<Index_t> row_counts;
1137 if (!stackSameCompositionQueries(queries, stacked, row_counts)) return;
1139 unstackEnergyGradient(stacked, queries, row_counts);
1140}
1141
1143 std::vector<Observation*> queries)
1144{
1145 Observation stacked;
1146 std::vector<Index_t> row_counts;
1147 if (!stackSameCompositionQueries(queries, stacked, row_counts)) return;
1149 unstackEnergyGradient(stacked, queries, row_counts);
1150}
1151
1154 const double nominal_probability) const
1155{
1156 const double central_probability = 0.5 * (1.0 + nominal_probability);
1157 if (!(nominal_probability > 0.0 && nominal_probability < 1.0) ||
1158 !std::isfinite(nominal_probability) || !(central_probability < 1.0)) {
1159 throw std::invalid_argument(
1160 "LOO calibration requires a representable central Gaussian "
1161 "probability in (0, 1)");
1162 }
1163
1164#ifdef GPR_LINALG_KOKKOS
1166#endif
1167 Eigen::VectorXd weights;
1168 Eigen::VectorXd inverse_diagonal;
1169 if (use_hssvd_backend_ && hssvd_basis_valid_ &&
1170 energy_and_gradient.size() > 0 && hssvd_basis_.rank() > 0 &&
1171 hssvd_basis_.numObs() == energy_and_gradient.size()) {
1172 const double total_noise_variance = totalPosteriorNoiseVariance();
1173 weights =
1174 hssvd_basis_.solveNoisy(energy_and_gradient, total_noise_variance);
1175 inverse_diagonal =
1176 hssvd_basis_.noisyInverseDiagonal(total_noise_variance);
1177 } else if (a.size() > 0 && hasTrainingCholeskyFactor(a.size())) {
1178 weights = rigid_deflation_.isActiveForFullOrder(a.size())
1179 ? (a + rigid_deflation_.a_rigid).eval()
1180 : a;
1181 inverse_diagonal = trainingInverseDiagonalInFactorLayout();
1182 } else {
1183 throw std::runtime_error(
1184 "closed-form LOO calibration requires a trained GP posterior");
1185 }
1186 if (weights.size() == 0 || weights.size() != inverse_diagonal.size()) {
1187 throw std::runtime_error(
1188 "closed-form LOO inverse diagonal size mismatch");
1189 }
1190
1191 const double physical_variance_scale = outputVarianceScaleSquared();
1192 if (!(physical_variance_scale > 0.0) ||
1193 !std::isfinite(physical_variance_scale)) {
1194 throw std::runtime_error("posterior output variance scale is invalid");
1195 }
1196 const double quantile = math::DistributionFunctions().normalCDFInverse(
1197 central_probability, 0.0, 1.0);
1198 if (!(quantile > 0.0) || !std::isfinite(quantile))
1199 throw std::runtime_error("normal quantile is invalid");
1200
1201 std::vector<double> standardized;
1202 standardized.reserve(static_cast<std::size_t>(weights.size()));
1203 double sum = 0.0;
1204 double sumsq = 0.0;
1205 double sum_log_predictive_density = 0.0;
1206 std::size_t covered = 0;
1207 for (Eigen::Index index = 0; index < weights.size(); ++index) {
1208 const double inverse_variance = inverse_diagonal(index);
1209 const double weight = weights(index);
1210 if (!(inverse_variance > 0.0) || !std::isfinite(inverse_variance) ||
1211 !std::isfinite(weight)) {
1212 throw std::runtime_error(
1213 "closed-form LOO calibration encountered a non-positive "
1214 "inverse diagonal or non-finite weight");
1215 }
1216 // Rasmussen & Williams (2006), eq. 5.12:
1217 // y_i - mu_{-i} = alpha_i / q_i and var_{-i} = 1 / q_i.
1218 const double z = weight / std::sqrt(inverse_variance);
1219 const double physical_variance =
1220 physical_variance_scale / inverse_variance;
1221 const double log_predictive_density =
1222 -0.5 * (std::log(2.0 * M_PI * physical_variance) + z * z);
1223 if (!std::isfinite(z) || !std::isfinite(log_predictive_density))
1224 throw std::runtime_error(
1225 "closed-form LOO residual or log predictive density is "
1226 "non-finite");
1227 standardized.push_back(z);
1228 sum += z;
1229 sumsq += z * z;
1230 sum_log_predictive_density += log_predictive_density;
1231 if (std::abs(z) <= quantile) ++covered;
1232 }
1233
1234 const double count = static_cast<double>(standardized.size());
1235 const double rms = std::sqrt(sumsq / count);
1236 std::size_t calibrated_covered = 0;
1237 for (const double z: standardized)
1238 if (std::abs(z) <= quantile * rms) ++calibrated_covered;
1239
1241 report.components = standardized.size();
1242 report.nominal_probability = nominal_probability;
1243 report.empirical_coverage = static_cast<double>(covered) / count;
1244 report.calibrated_coverage =
1245 static_cast<double>(calibrated_covered) / count;
1246 report.calibration_scale = rms;
1247 report.mean_standardized_residual = sum / count;
1248 report.rms_standardized_residual = rms;
1249 report.mean_log_predictive_density = sum_log_predictive_density / count;
1250 return report;
1251}
1252
1253} // namespace gpr
Linear algebra abstraction layer for GPR hot-path operations.
@ z
Definition Enums.h:28
@ y
Definition Enums.h:28
Exact floating-point accumulator (Kulisch long accumulator).
Preconditioned conjugate gradient (PCG) solver for symmetric positive-definite systems....
#define GPR_LINALG_SCALAPACK
Definition SlateBackend.h:9
void assembleMatrixOfRepetitiveCoordinates(const gpr::Coord &coord, gpr::EigenMatrix &matrix, Eigen::VectorXd &ind)
Assemble Eigen matrix with repetitive rows based on provided set of coordinates R.
virtual void recordHyperparameterDataTerm(double, double)
linalg::BackendContext & backend() const
Eigen::VectorXd permuteTrainingVector(const Eigen::VectorXd &input) const
void calculatePotentialSVGD(Observation &image1)
Definition SVGD.cpp:87
void evaluateCovarianceMatrix(const EigenMatrix &x1, const EigenMatrix &x2, const Eigen::VectorXd &x1_ind, const Eigen::VectorXd &x2_ind, EigenMatrix &C, bool serial_per_rank=false) const
Evaluate covariance matrix between two input vectors.
const Eigen::VectorXd & trainingInverseDiagonalInFactorLayout() const
Definition Predict.cpp:523
void calculatePotentialRFF(Observation &image)
Definition RFF.cpp:58
bool predictDevicePosterior(Observation &image, bool variance)
detail::RigidDeflationState rigid_deflation_
EigenMatrix permuteTrainingRows(const EigenMatrix &input) const
LeaveOneOutCalibrationReport calibrateLeaveOneOut(double nominal_probability) const
Definition Predict.cpp:1153
Eigen::VectorXd trainingCholeskyDiagonal() const
Definition Predict.cpp:493
void calculateVarianceDispatched(Observation &image1)
void calculateVarianceBatch(std::vector< Observation * > queries)
One dispatched variance predict for B same-composition queries.
Definition Predict.cpp:1142
void calculatePotential(Observation &image1)
Calculate potential within GPR model.
Definition Predict.cpp:713
void calculatePotentialLaplace(Observation &image1)
Laplace-mixture-mean potential prediction (INLA, Rue et al. 2009).
void calculateMeanPrediction(const Eigen::VectorXd &y)
Posterior mean prediction w.r.t energy. This function mimics the following step from the MATLAB code:...
Definition Predict.cpp:688
std::shared_ptr< linalg::KokkosMolecularPosterior > device_posterior_
bool hasDevicePosterior() const noexcept
void accumulateCrossCovarianceMatVecLocal(const EigenMatrix &x1, const EigenMatrix &x2, const Eigen::VectorXd &ind_Ddim, const Eigen::VectorXd &uDdim, const Eigen::VectorXd &ind_Ddim2, const Eigen::VectorXd &uDdim2, CovFunc &cov_func, const Eigen::VectorXd &weights, Eigen::VectorXd &output, bool do_reduce=true, bool select_prediction_product=false) const
Accumulate local K(x1, x2)^T * weights contributions without materializing the full cross-covariance ...
std::unique_ptr< SexpatCF > sexpat_cov_func
void calculatePosteriorMeanPrediction()
Calculate posterior mean prediction w.r.t energy. This function mimics the following step from the MA...
Definition Predict.cpp:153
void calculatePotentialBatch(std::vector< Observation * > queries)
Definition Predict.cpp:1132
void calculatePotentialDispatched(Observation &image1)
Definition Predict.cpp:982
void extractUniqueIndices(const Eigen::VectorXd &input_ind, Eigen::VectorXd &output_ind) const
Extract unique indices from the input vector.
linalg::linop::DenseCholeskySolver trainingSolver() const
bool hasTrainingCholeskyFactor(Eigen::Index expected_rows) const noexcept
void calculatePotentialBMA(Observation &image1)
Definition BMA.cpp:121
void evaluateTrainingCovarianceMatrix(const EigenMatrix &x, const Eigen::VectorXd &x_ind, EigenMatrix &cov_matrix, bool serial_per_rank=false, bool include_constant=true, bool include_noise=true)
Evaluate training covariance matrix (gp_cov + noise covariance).
static std::vector< std::pair< Eigen::Index, Eigen::Index > > featurePairs(const AtomsConfiguration &conf_info, double far_radius)
bool isBuilt() const
Definition RFFModel.h:111
Sexpat::PreparedAlphaK PreparedAlphaK
Definition SexpatCF.h:82
Eigen::VectorXd forward_solve_mat_colwise_squared_norm(const EigenMatrix &L, const EigenMatrix &B)
Eigen::VectorXd unwhiten(const Eigen::VectorXd &b) const
Eigen::VectorXd whiten(const Eigen::VectorXd &y) const
Eigen::VectorXd quadraticDiagonal(const EigenMatrix &B) const override
diag(B^T K^{-1} B), the explained part of a posterior variance.
Auxiliary functions for CDF calculation.
double normalCDFInverse(const double p, double const mu, const double sigma)
Inverse complementary error function.
void contractPredictionMatrix(const double *column_major, int rows, int cols, const double *coefficients, double *output, ProductMode mode)
PCGResult preconditioned_cg(const std::function< Eigen::VectorXd(const Eigen::VectorXd &)> &apply_A, const std::function< Eigen::VectorXd(const Eigen::VectorXd &)> &apply_M_inv, const Eigen::VectorXd &b, const PCGSettings &settings={})
ProductMode productMode()
Gaussian-process regression, kernels, priors, and the searches that run on the surrogate.
Definition Macros.h:16
bool looCalibrationIsUnityFromCholeskyDiagonal(const Eigen::VectorXd &alpha, const Eigen::VectorXd &diagonal)
Eigen::VectorXd unpermuteVector(const Eigen::VectorXd &input, const StructuredPermutation &p)
FieldMatrixd Coord
Definition Macros.h:35
uint32_t Index_t
Definition Macros.h:17
double g_max_abs_alpha
double looVarianceCalibrationFactor(const Eigen::VectorXd &alpha, const Eigen::VectorXd &inv_diag)
Eigen::Matrix< double, EigenDynamic, EigenDynamic, EigenMatrixStorage > EigenMatrix
Definition Macros.h:20
Observation data: energy, gradient and positions.
FieldMatrixd E
static double posterior_seconds