Loading...
Searching...
No Matches
LaplaceSlice.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// Slice-Laplace and PSIS-Laplace posterior caches plus the matched
6// predict / variance entrypoints. Includes the INLA-Delta cache, the
7// fit-from-scratch helper, and the calculatePotentialLaplace
8// dispatcher that the main predict path delegates to.
9
12#include "../LaplaceINLA.h"
16#include "Helpers.h"
19#ifdef GPR_LINALG_SCALAPACK
20#include <mpi.h>
21
24#endif
25
26#include <Eigen/Cholesky>
27#include <Eigen/Core>
28#include <algorithm>
29#include <chrono>
30#include <cmath>
31#include <cstddef>
32#include <limits>
33#include <memory>
34#include <utility>
35#include <vector>
36
37namespace gpr {
38
39using detail::addConstantCovarianceBlock;
40using detail::reduce_laplace_factor_vectors_in_grid_order;
41using detail::symmetrizeObservedInformation;
42using detail::writeBMAOutput;
43using detail::writePredictionVectorToObservation;
44
45bool GaussianProcessRegression::ensureSliceLaplacePosterior()
46{
47 // Route to the PSIS-Laplace path when use_psis_laplace_ is set.
48 // Same cache, same downstream predict, different sampler. The
49 // PSIS path produces the same SliceLaplaceState shape (theta /
50 // alpha / L per sample) plus the per-sample importance weights
51 // and the Pareto k_hat diagnostic.
52 if (use_psis_laplace_) return ensurePsisLaplacePosterior();
53
54 // Reuse the LAPLACE-CCD arm's stamp/signature so the slice cache and
55 // the CCD cache invalidate at the same boundaries (training-data
56 // change, theta_* shift, kernel-state mutation, MPI rank change).
57 // Mirrors ensureLaplacePosterior structurally.
58 const LaplacePosteriorStamp stamp = currentLaplacePosteriorStamp();
59 if (!stamp.validForPosterior()) {
60 slice_laplace_state_.reset();
61 return false;
62 }
63 if (slice_laplace_state_ && slice_laplace_state_->valid &&
64 slice_laplace_state_->stamp.matches(stamp)) {
65 return true;
66 }
67
68 if (R_matrix.size() == 0 || sexpat_cov_func == nullptr) {
69 slice_laplace_state_.reset();
70 return false;
71 }
72 const Eigen::VectorXd theta_init = packInlaHyperparameters();
73 if (theta_init.size() == 0 || !theta_init.allFinite()) {
74 slice_laplace_state_.reset();
75 return false;
76 }
77 Eigen::VectorXd y_train = energy_and_gradient;
78 if (y_train.size() == 0) {
79 slice_laplace_state_.reset();
80 return false;
81 }
82
83 // Snapshot kernel state; both log-target and alpha_fn mutate
84 // (magn, ls, sigma2) per slice step. Restored at scope exit so
85 // MAP-path callers see the original kernel.
86 laplace::ScopedKernelState fit_guard(*sexpat_cov_func, sigma2,
87 lik_gaussian.get());
88 const bool saved_theta_includes_noise = theta_includes_likelihood_noise_;
89
90 // log-target: -NLML(theta). evaluateEnergyLocalOnly does an Eigen
91 // LLT internally (no MPI collectives). Slice burst must be local-
92 // per-rank like the SVGD per-particle oracle in
93 // fitSVGDFromScratch -- the slice chain on rank k diverges from
94 // rank k+1, so a collective inside the target would deadlock.
95 auto log_target = [this, &y_train](const Eigen::VectorXd& theta) {
96 const double e =
98 if (!std::isfinite(e)) {
99 return std::numeric_limits<double>::quiet_NaN();
100 }
101 return -e; // log p(theta | y) = -NLML
102 };
103
104 // Each accepted sample forms its own covariance and factorization.
105 // The resulting factors define the sampled posterior variances.
106 std::vector<EigenMatrix> L_per_sample;
107 auto alpha_fn = [this, &y_train,
108 &L_per_sample](const Eigen::VectorXd& theta) {
109 setParameters(theta);
110 EigenMatrix C_local;
112 /*serial_per_rank=*/true);
113 if (jitter_sigma2 > 0.0) {
114 C_local.diagonal().array() += jitter_sigma2;
115 }
116 Eigen::LLT<EigenMatrix> llt(C_local);
117 if (llt.info() != Eigen::Success) {
118 return Eigen::VectorXd(); // signals failure to the sampler
119 }
120 EigenMatrix L = llt.matrixLLT().template triangularView<Eigen::Lower>();
121 L_per_sample.push_back(L);
122 return Eigen::VectorXd(llt.solve(y_train));
123 };
124
125 // Distribute M slice chains round-robin across MPI ranks. Each rank runs an
126 // independent slice chain (different seed = different sample
127 // trajectory; chains are independent by construction) producing
128 // ~M / mpi_size samples; an Allgatherv at the end collects them
129 // into the global cache. Per-rank wall on the slice burst drops
130 // from M * burst to (M / mpi_size) * burst -- ideal mpi_size-x
131 // speedup since chains have no cross-dependencies.
132 int mpi_rank = 0;
133 int mpi_size = 1;
134#ifdef GPR_LINALG_SCALAPACK
135 int mpi_up = 0;
136 MPI_Initialized(&mpi_up);
137 if (mpi_up) {
138 MPI_Comm_rank(mpiContext().comm, &mpi_rank);
139 MPI_Comm_size(mpiContext().comm, &mpi_size);
140 }
141#endif
142
143 const int M_total = std::max(1, slice_laplace_opts_.n_samples);
144 const int M_per_rank =
145 (M_total + mpi_size - 1) / mpi_size; // ceil(M / mpi_size)
146
147 laplace::SliceSamplerOptions per_rank_opts = slice_laplace_opts_;
148 per_rank_opts.n_samples = M_per_rank;
149 // Distinct seed per rank so chains diverge into different parts of
150 // the posterior.
151 per_rank_opts.seed = slice_laplace_opts_.seed +
152 static_cast<std::uint64_t>(mpi_rank) * 1009ULL;
153
154 laplace::SliceSampler sampler(per_rank_opts);
155 laplace::SliceSamplerState sampler_state;
156 const bool ok_local =
157 sampler.sample(theta_init, log_target, alpha_fn, sampler_state);
158 fit_guard.restore();
159 theta_includes_likelihood_noise_ = saved_theta_includes_noise;
160
161 bool any_failed =
162 !ok_local || sampler_state.theta_samples.empty() ||
163 sampler_state.alpha_cache.size() != sampler_state.theta_samples.size();
164
165#ifdef GPR_LINALG_SCALAPACK
166 if (mpi_up && mpi_size > 1) {
167 // OR-reduce per-rank failure flag so any rank's failure aborts
168 // the whole Allgather (avoids gathering uninitialised buffers).
169 int local_fail = any_failed ? 1 : 0;
170 int global_fail = 0;
171 MPI_Allreduce(&local_fail, &global_fail, 1, MPI_INT, MPI_MAX,
172 mpiContext().comm);
173 any_failed = (global_fail != 0);
174 }
175#endif
176
177 if (any_failed) {
178 slice_laplace_state_.reset();
179 return false;
180 }
181
182#ifdef GPR_LINALG_SCALAPACK
183 if (mpi_up && mpi_size > 1) {
184 const Eigen::Index p = theta_init.size();
185 const Eigen::Index n = y_train.size();
186 // Stack all M_per_rank theta and alpha samples into contiguous
187 // buffers, then Allgatherv into the global stack. Use Allgather
188 // (fixed M_per_rank per rank) -- the M_total = M_per_rank *
189 // mpi_size convention pads up to the next multiple of mpi_size
190 // so all ranks contribute the same count. The trailing
191 // overshoot (if M_total > slice_laplace_opts_.n_samples) is
192 // accepted; it just gives a slightly larger cache than asked.
193 std::vector<double> theta_send(static_cast<size_t>(M_per_rank) *
194 static_cast<size_t>(p));
195 std::vector<double> alpha_send(static_cast<size_t>(M_per_rank) *
196 static_cast<size_t>(n));
197 for (int k = 0; k < M_per_rank; ++k) {
198 const auto& theta_k = sampler_state.theta_samples[k];
199 const auto& alpha_k = sampler_state.alpha_cache[k];
200 std::copy(theta_k.data(), theta_k.data() + p,
201 theta_send.data() + static_cast<size_t>(k) * p);
202 std::copy(alpha_k.data(), alpha_k.data() + n,
203 alpha_send.data() + static_cast<size_t>(k) * n);
204 }
205
206 std::vector<double> theta_recv(static_cast<size_t>(M_per_rank) *
207 static_cast<size_t>(mpi_size) *
208 static_cast<size_t>(p));
209 std::vector<double> alpha_recv(static_cast<size_t>(M_per_rank) *
210 static_cast<size_t>(mpi_size) *
211 static_cast<size_t>(n));
212 MPI_Allgather(theta_send.data(), static_cast<int>(M_per_rank * p),
213 MPI_DOUBLE, theta_recv.data(),
214 static_cast<int>(M_per_rank * p), MPI_DOUBLE,
215 mpiContext().comm);
216 MPI_Allgather(alpha_send.data(), static_cast<int>(M_per_rank * n),
217 MPI_DOUBLE, alpha_recv.data(),
218 static_cast<int>(M_per_rank * n), MPI_DOUBLE,
219 mpiContext().comm);
220
221 const int M_global = M_per_rank * mpi_size;
222 sampler_state.theta_samples.clear();
223 sampler_state.alpha_cache.clear();
224 sampler_state.theta_samples.reserve(M_global);
225 sampler_state.alpha_cache.reserve(M_global);
226 for (int k = 0; k < M_global; ++k) {
227 Eigen::VectorXd theta_k(p);
228 Eigen::VectorXd alpha_k(n);
229 std::copy(theta_recv.data() + static_cast<size_t>(k) * p,
230 theta_recv.data() + static_cast<size_t>(k + 1) * p,
231 theta_k.data());
232 std::copy(alpha_recv.data() + static_cast<size_t>(k) * n,
233 alpha_recv.data() + static_cast<size_t>(k + 1) * n,
234 alpha_k.data());
235 sampler_state.theta_samples.push_back(std::move(theta_k));
236 sampler_state.alpha_cache.push_back(std::move(alpha_k));
237 }
238 }
239#endif
240
241 // L_samples: kept LOCAL only (per rank), not Allgathered (each L is
242 // n x n doubles -- gathering across
243 // ranks would cost mpi_size * M_per_rank * n^2 bytes Bcast, which
244 // dominates the slice burst itself at PET-MAD scale). Each rank
245 // owns L's for its OWN slice samples (theta_samples indices
246 // [mpi_rank * M_per_rank, (mpi_rank+1) * M_per_rank)) and computes
247 // its piece of the within-sample variance during predict, then
248 // Reduce-averages across ranks. theta/alpha are globally
249 // available everywhere; L's are partitioned.
250 auto state = std::make_unique<SliceLaplaceState>();
251 state->stamp = stamp;
252 state->theta_samples = std::move(sampler_state.theta_samples);
253 state->alpha_samples = std::move(sampler_state.alpha_cache);
254 state->L_samples = std::move(L_per_sample);
255 state->n_target_evals = sampler_state.n_target_evals;
256 state->n_accepted = sampler_state.n_accepted;
257 state->n_stuck = sampler_state.n_stuck;
258 state->n_steps = sampler_state.n_steps;
259 state->valid = true;
260 slice_laplace_state_ = std::move(state);
261 return true;
262}
263
264bool GaussianProcessRegression::ensurePsisLaplacePosterior()
265{
266 // PSIS-Laplace path: replaces the slice burst with K importance
267 // samples drawn from the standard Laplace proposal q(theta) =
268 // N(theta_MAP, H^{-1}). PSIS smooths the upper tail of the
269 // weights and reports k_hat as the reliability diagnostic. SymPy
270 // proof of the weighted LOTV identity used downstream:
271 // python/tests/test_sympy_psis_laplace.py (P1-P6).
272 //
273 // Same cache-validity machinery as the slice path so the same
274 // invalidation triggers (training-data, theta_*, kernel-state,
275 // MPI rank) wipe both.
276 const LaplacePosteriorStamp stamp = currentLaplacePosteriorStamp();
277 if (!stamp.validForPosterior()) {
278 slice_laplace_state_.reset();
279 return false;
280 }
281 if (slice_laplace_state_ && slice_laplace_state_->valid &&
282 slice_laplace_state_->stamp.matches(stamp)) {
283 return true;
284 }
285
286 if (R_matrix.size() == 0 || sexpat_cov_func == nullptr) {
287 slice_laplace_state_.reset();
288 return false;
289 }
290 const Eigen::VectorXd theta_map = packInlaHyperparameters();
291 if (theta_map.size() == 0 || !theta_map.allFinite()) {
292 slice_laplace_state_.reset();
293 return false;
294 }
295 Eigen::VectorXd y_train = energy_and_gradient;
296 if (y_train.size() == 0) {
297 slice_laplace_state_.reset();
298 return false;
299 }
300
301 // Hessian H = -d^2 log p(theta | y) / dtheta^2 |_{theta_MAP}.
302 // Use the same assembleExactHessian path the LAPLACE-CCD arm
303 // uses (Williams-Rasmussen 5.9 directional curvature with
304 // polarisation-identity recovery of the off-diagonal entries).
305 const int p_dim = static_cast<int>(theta_map.size());
306 Eigen::VectorXd y_for_curv =
308 Eigen::MatrixXd H;
309 if (!assembleExactHessian(R_indices, R_matrix, y_for_curv, p_dim, H)) {
310 slice_laplace_state_.reset();
311 return false;
312 }
313 if (!symmetrizeObservedInformation(H)) {
314 slice_laplace_state_.reset();
315 return false;
316 }
317
318 // Snapshot kernel state; log_target / alpha_fn mutate the kernel
319 // per-sample and the dtor restores at scope exit.
320 laplace::ScopedKernelState fit_guard(*sexpat_cov_func, sigma2,
321 lik_gaussian.get());
322 const bool saved_theta_includes_noise = theta_includes_likelihood_noise_;
323
324 auto log_target = [this, &y_train](const Eigen::VectorXd& theta) {
325 const double e =
327 if (!std::isfinite(e)) {
328 return std::numeric_limits<double>::quiet_NaN();
329 }
330 return -e; // log p(theta | y) = -NLML(theta)
331 };
332
333 std::vector<EigenMatrix> L_per_sample;
334 auto alpha_fn = [this, &y_train,
335 &L_per_sample](const Eigen::VectorXd& theta) {
336 setParameters(theta);
337 EigenMatrix C_local;
339 /*serial_per_rank=*/true);
340 if (jitter_sigma2 > 0.0) {
341 C_local.diagonal().array() += jitter_sigma2;
342 }
343 Eigen::LLT<EigenMatrix> llt(C_local);
344 if (llt.info() != Eigen::Success) return Eigen::VectorXd();
345 EigenMatrix L = llt.matrixLLT().template triangularView<Eigen::Lower>();
346 L_per_sample.push_back(L);
347 return Eigen::VectorXd(llt.solve(y_train));
348 };
349
350 // Distribute the K samples across MPI ranks the same way the
351 // slice burst does: each rank draws K_per_rank samples with a
352 // distinct RNG seed (rank * 1009 offset), evaluates them locally,
353 // then Allgathers theta + alpha + log_w. L_samples stay local
354 // (memory: avoid mpi_size * K_per_rank * n^2 Bcast).
355 int mpi_rank = 0;
356 int mpi_size = 1;
357#ifdef GPR_LINALG_SCALAPACK
358 int mpi_up = 0;
359 MPI_Initialized(&mpi_up);
360 if (mpi_up) {
361 MPI_Comm_rank(mpiContext().comm, &mpi_rank);
362 MPI_Comm_size(mpiContext().comm, &mpi_size);
363 }
364#endif
365
366 // Sample distribution: random IS draws split across ranks for
367 // ideal scaling; deterministic axial grid runs the same K = 1 +
368 // 2 p samples on every rank (no Allgather, no per-rank seed
369 // offset) so the predict variance is bit-stable across np. The
370 // np-fragility of the random PSIS path was traced to the rank
371 // seed offset producing different sample sets at np=4 vs np=16
372 // that fired the variance gate on different points. With a
373 // deterministic grid every rank computes the SAME 9 NLML values
374 // and gets the SAME variance gate decision -- np-reproducible by
375 // construction.
376 const bool deterministic = psis_laplace_opts_.deterministic_axial_grid;
377 const int K_total = std::max(1, psis_laplace_opts_.n_samples);
378 const int K_per_rank =
379 deterministic ? K_total : (K_total + mpi_size - 1) / mpi_size;
380
381 laplace::PsisLaplaceOptions per_rank_opts = psis_laplace_opts_;
382 per_rank_opts.n_samples = K_per_rank;
383 per_rank_opts.seed = deterministic
384 ? psis_laplace_opts_.seed
385 : (psis_laplace_opts_.seed +
386 static_cast<std::uint64_t>(mpi_rank) * 1009ULL);
387
388 laplace::PsisLaplace sampler(per_rank_opts);
389 laplace::PsisLaplaceState psis_state;
390 const bool ok_local =
391 sampler.fit(theta_map, H, log_target, alpha_fn, psis_state);
392
393 fit_guard.restore();
394 theta_includes_likelihood_noise_ = saved_theta_includes_noise;
395
396 bool any_failed =
397 !ok_local || !psis_state.valid || psis_state.theta_samples.empty();
398
399#ifdef GPR_LINALG_SCALAPACK
400 if (mpi_up && mpi_size > 1) {
401 int local_fail = any_failed ? 1 : 0;
402 int global_fail = 0;
403 MPI_Allreduce(&local_fail, &global_fail, 1, MPI_INT, MPI_MAX,
404 mpiContext().comm);
405 any_failed = (global_fail != 0);
406 }
407#endif
408
409 if (any_failed) {
410 slice_laplace_state_.reset();
411 return false;
412 }
413
414 auto state = std::make_unique<SliceLaplaceState>();
415 state->stamp = stamp;
416 state->theta_samples = std::move(psis_state.theta_samples);
417 state->alpha_samples = std::move(psis_state.alpha_samples);
418 state->L_samples = std::move(L_per_sample);
419
420#ifdef GPR_LINALG_SCALAPACK
421 if (!deterministic && mpi_up && mpi_size > 1) {
422 const Eigen::Index p_h = theta_map.size();
423 const Eigen::Index n_y = y_train.size();
424 // Allgather theta, alpha, and log-weights across ranks. Same
425 // pattern as the slice path.
426 std::vector<double> theta_send(static_cast<size_t>(K_per_rank) *
427 static_cast<size_t>(p_h));
428 std::vector<double> alpha_send(static_cast<size_t>(K_per_rank) *
429 static_cast<size_t>(n_y));
430 std::vector<double> logw_send(static_cast<size_t>(K_per_rank));
431 for (int k = 0; k < K_per_rank; ++k) {
432 const auto& theta_k = state->theta_samples[k];
433 const auto& alpha_k = state->alpha_samples[k];
434 std::copy(theta_k.data(), theta_k.data() + p_h,
435 theta_send.data() + static_cast<size_t>(k) * p_h);
436 if (alpha_k.size() == n_y) {
437 std::copy(alpha_k.data(), alpha_k.data() + n_y,
438 alpha_send.data() + static_cast<size_t>(k) * n_y);
439 }
440 logw_send[k] = psis_state.log_weights_raw[k];
441 }
442 std::vector<double> theta_recv(static_cast<size_t>(K_per_rank) *
443 static_cast<size_t>(mpi_size) *
444 static_cast<size_t>(p_h));
445 std::vector<double> alpha_recv(static_cast<size_t>(K_per_rank) *
446 static_cast<size_t>(mpi_size) *
447 static_cast<size_t>(n_y));
448 std::vector<double> logw_recv(static_cast<size_t>(K_per_rank) *
449 static_cast<size_t>(mpi_size));
450 MPI_Allgather(theta_send.data(), static_cast<int>(K_per_rank * p_h),
451 MPI_DOUBLE, theta_recv.data(),
452 static_cast<int>(K_per_rank * p_h), MPI_DOUBLE,
453 mpiContext().comm);
454 MPI_Allgather(alpha_send.data(), static_cast<int>(K_per_rank * n_y),
455 MPI_DOUBLE, alpha_recv.data(),
456 static_cast<int>(K_per_rank * n_y), MPI_DOUBLE,
457 mpiContext().comm);
458 MPI_Allgather(logw_send.data(), K_per_rank, MPI_DOUBLE,
459 logw_recv.data(), K_per_rank, MPI_DOUBLE,
460 mpiContext().comm);
461
462 const int K_global = K_per_rank * mpi_size;
463 state->theta_samples.clear();
464 state->alpha_samples.clear();
465 state->theta_samples.reserve(K_global);
466 state->alpha_samples.reserve(K_global);
467 std::vector<double> log_w_global(K_global);
468 for (int k = 0; k < K_global; ++k) {
469 Eigen::VectorXd theta_k(p_h);
470 Eigen::VectorXd alpha_k(n_y);
471 std::copy(theta_recv.data() + static_cast<size_t>(k) * p_h,
472 theta_recv.data() + static_cast<size_t>(k + 1) * p_h,
473 theta_k.data());
474 std::copy(alpha_recv.data() + static_cast<size_t>(k) * n_y,
475 alpha_recv.data() + static_cast<size_t>(k + 1) * n_y,
476 alpha_k.data());
477 log_w_global[k] = logw_recv[k];
478 state->theta_samples.push_back(std::move(theta_k));
479 state->alpha_samples.push_back(std::move(alpha_k));
480 }
481 // Re-normalise weights across the global K. PSIS k_hat is
482 // computed locally on each rank's K_per_rank; for the cache
483 // we re-derive it from the global weights.
484 state->sample_weights = laplace::selfNormalisedWeights(log_w_global);
485 std::vector<double> w_sorted = state->sample_weights;
486 std::sort(w_sorted.begin(), w_sorted.end(), std::greater<double>());
487 const int M_pareto = std::min(std::max(K_global / 5, 4), K_global - 1);
488 state->k_hat = laplace::estimateParetoKHat(w_sorted, M_pareto);
489 } else
490#endif
491 {
492 state->sample_weights = std::move(psis_state.weights);
493 state->k_hat = psis_state.k_hat;
494 }
495 state->psis_reliable = (state->k_hat <= psis_laplace_opts_.k_hat_threshold);
496 state->n_target_evals = psis_state.n_target_evals;
497 // Stash the upper Cholesky of the hyperparameter Hessian H = U^T U
498 // computed at theta_MAP. Consumed by the Laplace-driven skip-SCG
499 // predicate (computeLaplaceSkipScgShiftNorm) so the predicate has
500 // access to ||H^-1 g_new||_H without needing a separate
501 // ensureDeltaMethodLaplacePosterior fit. Cheap (one p x p LLT,
502 // p = O(10)) and reuses H already assembled above.
503 {
504 Eigen::LLT<Eigen::MatrixXd> llt_H(H);
505 if (llt_H.info() == Eigen::Success) {
506 state->hessian_chol_U = llt_H.matrixU();
507 }
508 }
509 state->valid = true;
510 slice_laplace_state_ = std::move(state);
511 return true;
512}
513
514bool GaussianProcessRegression::runSliceLaplacePredict(Observation& image1,
515 bool want_variance)
516{
517 if (!ensureSliceLaplacePosterior()) return false;
518 if (!slice_laplace_state_ || !slice_laplace_state_->valid) return false;
519
520 const Index_t N_im = static_cast<Index_t>(image1.R.rows());
521 const Index_t D = static_cast<Index_t>(image1.R.cols());
522 EigenMatrix R_mod;
523 Eigen::VectorXd R_mod_ind;
524 aux::AuxiliaryFunctionality aux_func;
525 aux_func.assembleMatrixOfRepetitiveCoordinates(image1.R, R_mod, R_mod_ind);
526
527 const Eigen::Index n_query = R_mod.rows();
528 const Eigen::Index expected = static_cast<Eigen::Index>(N_im) * (D + 1);
529 if (n_query != expected) return false;
530
531 // Snapshot kernel state; per-sample setParameters mutates and we
532 // restore at scope exit so subsequent MAP-path predicts see the
533 // original kernel.
534 laplace::ScopedKernelState predict_guard(*sexpat_cov_func, sigma2,
535 lik_gaussian.get());
536
537 const auto& thetas = slice_laplace_state_->theta_samples;
538 const auto& alphas = slice_laplace_state_->alpha_samples;
539 const std::size_t M = thetas.size();
540 if (M == 0 || alphas.size() != M) return false;
541
542 // Per-sample posterior weights. Slice arm leaves sample_weights
543 // empty -> treat as uniform 1/M (the unweighted LOTV form). PSIS
544 // arm provides the importance weights from N(theta_MAP, H^{-1});
545 // sympy proof of the weighted LOTV identity P2/P3 in
546 // python/tests/test_sympy_psis_laplace.py.
547 const auto& w_in = slice_laplace_state_->sample_weights;
548 std::vector<double> w(M);
549 if (w_in.size() == M) {
550 std::copy(w_in.begin(), w_in.end(), w.begin());
551 } else {
552 std::fill(w.begin(), w.end(), 1.0 / static_cast<double>(M));
553 }
554
555 // Per-sample mean: mu_k = K_train_query(theta_k)^T * alpha_k.
556 // Weighted posterior predictive mean = sum_k w_k mu_k.
557 // For variance: also accumulate sum_k w_k mu_k^2 so we can form
558 // the between-sample variance Var_theta[mu(theta)] in one pass.
559 Eigen::VectorXd mu_sum = Eigen::VectorXd::Zero(n_query);
560 Eigen::VectorXd mu_sq_sum =
561 want_variance ? Eigen::VectorXd::Zero(n_query) : Eigen::VectorXd();
562
563 // Alpha-K mean accumulator (Schmitz/Chmiela JPCL 2022 eq.6) for the
564 // !want_variance branch. The variance branch needs K_train_query
565 // materialised in the within-sample triangular solve below, so it
566 // keeps the mat-vec form for cache reuse. Mirrors the MAP alpha-K
567 // branch; same SexpAt + ConstantCF split.
568 const Index_t D_im = D;
569 const Eigen::Index num_train_pts =
570 (D_im > 0) ? R_matrix.rows() / (D_im + 1) : R_matrix.rows();
571 const bool alpha_k_slice_mean =
572 !want_variance && sexpat_cov_func != nullptr && num_train_pts > 0 &&
573 full_cartesian_training_dimension_ == D_im &&
574 R_matrix.rows() == num_train_pts * (D_im + 1);
575
576 for (std::size_t k = 0; k < M; ++k) {
577 if (thetas[k].size() == 0 || alphas[k].size() == 0) continue;
578 setParameters(thetas[k]);
579
580 Eigen::VectorXd mu_k(n_query);
581 if (alpha_k_slice_mean && alphas[k].size() == R_matrix.rows()) {
582 // SexpAt alpha-K contraction.
583 Eigen::VectorXd mu_E_out = Eigen::VectorXd::Zero(N_im);
584 Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic,
585 Eigen::RowMajor>
586 mu_G_out = Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic,
587 Eigen::RowMajor>::Zero(N_im, D);
588 sexpat_cov_func->predictMeanAlphaK(
589 R_matrix.topRows(num_train_pts), image1.R,
590 alphas[k].head(num_train_pts), alphas[k], mu_E_out, mu_G_out);
591 // ConstantCF contribution via the existing accumulator.
592 Eigen::VectorXd uDdim, uDdim2;
594 extractUniqueIndices(R_mod_ind, uDdim2);
595 Eigen::VectorXd const_contrib = Eigen::VectorXd::Zero(n_query);
597 R_matrix, R_mod, R_indices, uDdim, R_mod_ind, uDdim2,
598 *const_cov_fun, alphas[k], const_contrib);
599 // Splice SexpAt mu_E / mu_G into the (E_0..E_{N-1},
600 // G_{m=0,d=0}, ..., G_{m=N-1,d=D-1}) layout.
601 mu_k.setZero();
602 for (Index_t m = 0; m < N_im; ++m) {
603 mu_k(m) = mu_E_out(m) + const_contrib(m);
604 }
605 for (Index_t d = 0; d < D; ++d) {
606 for (Index_t m = 0; m < N_im; ++m) {
607 const Eigen::Index idx = N_im + d * N_im + m;
608 mu_k(idx) = mu_G_out(m, d) + const_contrib(idx);
609 }
610 }
611 } else {
612 EigenMatrix K_train_query;
614 K_train_query);
615 // K_train_query is (n_train x n_query); align dims with alpha_k.
616 if (K_train_query.rows() != alphas[k].size()) continue;
617 mu_k = K_train_query.transpose() * alphas[k];
618 }
619 if (mu_k.size() != n_query) continue;
620
621 mu_sum += w[k] * mu_k;
622 if (want_variance) mu_sq_sum.array() += w[k] * mu_k.array().square();
623 }
624
625 const Eigen::VectorXd mu_avg = mu_sum;
626
627 if (want_variance) {
628 // Law-of-total-variance estimator:
629 // Var(y* | y) = E_theta[ Var(y* | y, theta) ]
630 // + Var_theta[ E(y* | y, theta) ]
631 // The first term (within-sample) needs K(theta_k)^-1 k_cross
632 // per cached theta per query point; computed via two triangular
633 // solves on the cached L_k held per local sample. The second term is
634 // the between-sample mean variance.
635 //
636 // Within-sample term is partitioned across MPI ranks: each
637 // rank owns L_samples for its M_per_rank local slice samples
638 // and contributes its piece of the average; MPI_Allreduce
639 // sum + divide by M_global gives the global average. Between-
640 // sample term uses the global theta/alpha already Allgathered, so
641 // each rank can compute it independently.
642 const auto& L_local = slice_laplace_state_->L_samples;
643 const std::size_t M_local = L_local.size();
644
645 // Local within-sample accumulator. Each rank's L_local[i]
646 // corresponds to global theta_samples[mpi_rank * M_per_rank + i]
647 // (per the partitioning convention in ensureSliceLaplacePosterior).
648 Eigen::VectorXd within_sample_local = Eigen::VectorXd::Zero(n_query);
649 int mpi_rank = 0;
650 int mpi_size = 1;
651#ifdef GPR_LINALG_SCALAPACK
652 int mpi_up = 0;
653 MPI_Initialized(&mpi_up);
654 if (mpi_up) {
655 MPI_Comm_rank(mpiContext().comm, &mpi_rank);
656 MPI_Comm_size(mpiContext().comm, &mpi_size);
657 }
658#endif
659 // Deterministic-grid mode: every rank holds ALL M samples
660 // (no rank partition; each rank has the same L_local), so
661 // the within-sample loop iterates ALL M samples on every
662 // rank. The kernel evaluation runs distributed (do_reduce =
663 // true) with consistent iteration counts across ranks. The
664 // trailing Allreduce on within_sample_local is skipped --
665 // all ranks already compute the same value redundantly.
666 const bool deterministic_layout =
667 use_psis_laplace_ && psis_laplace_opts_.deterministic_axial_grid;
668 const std::size_t M_per_rank =
669 deterministic_layout
670 ? M
671 : (M + static_cast<std::size_t>(mpi_size) - 1) /
672 static_cast<std::size_t>(mpi_size);
673 const std::size_t local_base =
674 deterministic_layout
675 ? 0
676 : static_cast<std::size_t>(mpi_rank) * M_per_rank;
677
678 std::vector<linalg::ExactSum> within_sample_exact(
679 static_cast<std::size_t>(n_query));
680 for (std::size_t i = 0; i < M_local; ++i) {
681 const std::size_t k_global = local_base + i;
682 if (k_global >= M) break;
683 const auto& theta_k = thetas[k_global];
684 const auto& L_k = L_local[i];
685 if (theta_k.size() == 0 || L_k.rows() == 0) continue;
686 setParameters(theta_k);
687
688 // Cross-cov K(X_train, X_query; theta_k): n_train x n_query.
689 EigenMatrix K_train_query;
691 K_train_query);
692
693 // Within-sample variance per query point:
694 // sigma2_k(x*) = k(x*, x*; theta_k)
695 // - k_cross^T K(theta_k)^-1 k_cross
696 // Compute K(theta_k)^-1 k_cross via two triangular solves
697 // on cached L_k. Then take per-column squared norms of the
698 // intermediate forward-solve vector for the quadratic
699 // term: ||L^-1 k_cross||^2 = k_cross^T K^-1 k_cross.
700 const EigenMatrix beta =
701 L_k.template triangularView<Eigen::Lower>().solve(
702 K_train_query);
703 // Per query point j: k_diag(j) - sum_i beta(i,j)^2
704 const Eigen::VectorXd quad_form =
705 beta.colwise().squaredNorm().transpose();
706
707 // Diagonal kernel evaluation at the query points.
708 EigenMatrix K_query_query;
709 evaluateTrainingCovarianceMatrix(R_mod, R_mod_ind, K_query_query,
710 /*serial_per_rank=*/true);
711 Eigen::VectorXd k_diag = K_query_query.diagonal();
712 removeKernelNuggetFromDiagonal(R_mod, k_diag);
713
714 const Eigen::VectorXd sigma2_k = (k_diag - quad_form).cwiseMax(0.0);
715 const double wk = w[k_global];
716 for (Eigen::Index j = 0; j < n_query; ++j) {
717 within_sample_exact[static_cast<std::size_t>(j)].addProduct(
718 wk, sigma2_k(j));
719 }
720 }
721
722#ifdef GPR_LINALG_SCALAPACK
723 if (!deterministic_layout && mpi_up && mpi_size > 1) {
724 linalg::exact_sum_bcast(within_sample_exact.data(),
725 static_cast<int>(n_query), mpiContext());
726 }
727#endif
728 for (Eigen::Index j = 0; j < n_query; ++j) {
729 within_sample_local(j) =
730 within_sample_exact[static_cast<std::size_t>(j)].value();
731 }
732 // Weights already contain the 1/M factor (uniform when slice,
733 // PSIS-normalised when PSIS) so the within_sample_local sum is
734 // already the weighted average after Allreduce.
735 Eigen::VectorXd within_sample_avg = within_sample_local;
736
737 // Between-sample variance: sum_k w_k mu_k^2 - (sum_k w_k mu_k)^2.
738 // Sympy proof: test_P2_weighted_LOTV_identity_K3.
739 Eigen::VectorXd between_sample =
740 mu_sq_sum - mu_avg.array().square().matrix();
741 between_sample = between_sample.cwiseMax(0.0);
742
743 Eigen::VectorXd var_avg = within_sample_avg + between_sample;
744 var_avg = var_avg.cwiseMax(0.0); // clip round-off negatives
745 writeBMAOutput(var_avg, N_im, D, image1);
746 } else {
747 writeBMAOutput(mu_avg, N_im, D, image1);
748 }
749 return true;
750}
751
753 Observation& image1)
754{
755 if (!runSliceLaplacePredict(image1, /*want_variance=*/false)) {
756 calculatePotential(image1);
757 return;
758 }
759 ++num_of_potential_calls;
760}
761
763 Observation& image1)
764{
765 if (!runSliceLaplacePredict(image1, /*want_variance=*/true)) {
766 calculateMapVarianceInTrainingUnits(image1);
767 return;
768 }
769}
770
772 const Coord& positions, const Eigen::VectorXd& targets,
773 const Eigen::VectorXd& theta, const funcmin::MapObjectiveConfig& penalty,
774 double target_scale, bool use_ties)
775{
776 fitted_hyperparameter_density_.reset();
777 if (!retain_fitted_hyperparameter_density_) return;
778 slice_laplace_state_.reset();
779 if (failedOptimizer || sexpat_cov_func == nullptr ||
780 lik_gaussian == nullptr || positions.rows() <= 0 ||
781 positions.cols() <= 0 ||
782 targets.size() != positions.rows() * (positions.cols() + 1) ||
783 !positions.allFinite() || !targets.allFinite() || !theta.allFinite() ||
784 !(target_scale > 0.0) || !std::isfinite(target_scale) ||
785 hyperparameter_objective_mode_ != HyperparameterObjectiveMode::NLML ||
786 use_hssvd_backend_ || use_correction_ || robust_nu_ > 0.0 ||
787 use_chem_factorized_hyper_ || rff_features_requested_ > 0 ||
788 rff_auto_ || sexpat_cov_func->usesManifoldChart() ||
789 sexpat_cov_func->geodesicHeatKernel() != nullptr ||
790 atoms_config.pair_cutoff > 0.0 ||
791 !funcmin::mapParametersInDomain(theta, penalty)) {
792 return;
793 }
794 const Eigen::Index covariance_count =
795 sexpat_cov_func->combineParameters().size();
796 const Eigen::Index length_count = covariance_count - 1;
797 if (theta.size() != covariance_count &&
798 !(lik_gaussian->getOptimizeSigma2() &&
799 theta.size() == covariance_count + 1)) {
800 return;
801 }
802 auto density = std::make_unique<FittedHyperparameterDensity>();
803 density->parameter_group.assign(static_cast<std::size_t>(theta.size()), -1);
804 std::vector<Eigen::Index> columns(static_cast<std::size_t>(theta.size()),
805 -1);
806 const bool tied = use_ties && lengthScaleTiesActive(length_count);
807 for (Eigen::Index i = 0; i < theta.size(); ++i) {
808 const Eigen::Index leader =
809 tied && i > 0 && i <= length_count
810 ? 1 + length_scale_ties_.leader[static_cast<std::size_t>(i - 1)]
811 : i;
812 const bool masked =
813 penalty.active_parameters.size() ==
814 static_cast<std::size_t>(theta.size()) &&
815 !penalty.active_parameters[static_cast<std::size_t>(leader)];
816 const bool fixed =
817 penalty.parameter_lower.size() == theta.size() &&
818 penalty.parameter_upper.size() == theta.size() &&
819 penalty.parameter_lower(leader) == penalty.parameter_upper(leader);
820 if (masked || fixed) continue;
821 // An interior Gaussian approximation has no free coordinate on a box
822 // face.
823 if ((penalty.parameter_lower.size() == theta.size() &&
824 !(theta(i) > penalty.parameter_lower(i))) ||
825 (penalty.parameter_upper.size() == theta.size() &&
826 !(theta(i) < penalty.parameter_upper(i)))) {
827 return;
828 }
829 auto& column = columns[static_cast<std::size_t>(leader)];
830 if (column < 0) column = density->free_count++;
831 density->parameter_group[static_cast<std::size_t>(i)] = column;
832 }
833 if (density->free_count == 0) return;
834 density->positions = positions;
835 density->targets = targets;
836 density->theta = theta;
837 density->posterior_theta = theta;
838 density->posterior_theta(0) += 2.0 * std::log(target_scale);
839 if (theta.size() > covariance_count)
840 density->posterior_theta(theta.size() - 1) +=
841 2.0 * std::log(target_scale);
842 density->penalty = penalty;
843 density->configuration = atoms_config;
844 // The fit is finished; retain its kernel state without distance scratch.
845 sexpat_cov_func->clearDistanceCache();
846 density->kernel = std::make_unique<SexpatCF>(*sexpat_cov_func);
847 density->kernel->setParameters(theta.head(covariance_count));
848 density->likelihood_sigma2 = lik_gaussian->getSigma2();
849 density->learn_likelihood_noise = lik_gaussian->getOptimizeSigma2();
850 density->constant_sigma2 =
851 const_cov_fun ? const_cov_fun->getConstSigma2() : 0.0;
852 density->jitter_sigma2 = jitter_sigma2;
853 density->target_scale = target_scale;
854 density->principled_nugget = principled_nugget_;
855 density->kappa_max = kappa_max_;
856 density->model_profile = model_profile_;
857 fitted_hyperparameter_density_ = std::move(density);
858}
859
861 bool retain) noexcept
862{
863 retain_fitted_hyperparameter_density_ = retain;
864 if (!retain) fitted_hyperparameter_density_.reset();
865}
866
868 Eigen::MatrixXd& information, Eigen::MatrixXd& directions)
869{
870 information.resize(0, 0);
871 directions.resize(0, 0);
872 if (!fitted_hyperparameter_density_ || !sexpat_cov_func || !lik_gaussian)
873 return false;
874 const auto& density = *fitted_hyperparameter_density_;
875 const Eigen::VectorXd current = packInlaHyperparameters();
876 if (current.size() != density.posterior_theta.size() ||
877 !current.allFinite() || use_hssvd_backend_ || use_correction_ ||
878 robust_nu_ > 0.0 || rff_features_requested_ > 0 || rff_auto_ ||
879 active_posterior_ || sexpat_cov_func->usesManifoldChart() ||
880 sexpat_cov_func->usesGeodesicHeatKernel() ||
881 model_profile_ != density.model_profile ||
882 principled_nugget_ != density.principled_nugget ||
883 kappa_max_ != density.kappa_max || !density.kernel ||
884 !detail::sameSexpatGeometry(sexpat_cov_func->getConfInfo(),
885 density.kernel->getConfInfo(),
886 sexpat_cov_func->farFieldRadius(),
887 density.kernel->farFieldRadius()) ||
888 !detail::sameSexpatGeometry(atoms_config, density.configuration)) {
889 return false;
890 }
891 const double epsilon = 64.0 * std::numeric_limits<double>::epsilon();
892 for (Eigen::Index i = 0; i < current.size(); ++i) {
893 if (std::abs(current(i) - density.posterior_theta(i)) >
894 epsilon * std::max(1.0, std::abs(density.posterior_theta(i))))
895 return false;
896 }
897 const auto same_scale = [epsilon](double a, double b) {
898 return std::isfinite(a) && std::isfinite(b) &&
899 std::abs(a - b) <= epsilon * std::max(std::abs(a), std::abs(b));
900 };
901 const double scale2 = density.target_scale * density.target_scale;
902 if ((!density.learn_likelihood_noise &&
903 !same_scale(lik_gaussian->getSigma2(),
904 density.likelihood_sigma2 * scale2)) ||
905 !same_scale(jitter_sigma2, density.jitter_sigma2 * scale2) ||
906 !same_scale(const_cov_fun ? const_cov_fun->getConstSigma2() : 0.0,
907 density.constant_sigma2 * scale2)) {
908 return false;
909 }
910 Eigen::MatrixXd selected =
911 Eigen::MatrixXd::Zero(density.theta.size(), density.free_count);
912 for (Eigen::Index i = 0; i < density.theta.size(); ++i) {
913 const Eigen::Index group =
914 density.parameter_group[static_cast<std::size_t>(i)];
915 if (group >= 0) selected(i, group) = 1.0;
916 }
917 std::unique_ptr<GaussianProcessRegression> objective;
918#if defined(GPR_HAVE_MPI) || defined(GPR_LINALG_SCALAPACK)
919 const auto communication = mpiContext();
920 if (communication.comm != linalg::kMpiCommNull) {
921 objective = std::make_unique<GaussianProcessRegression>(
922 std::make_shared<linalg::MpiCommunicator>(communication.comm));
923 }
924#endif
925 if (!objective) objective = std::make_unique<GaussianProcessRegression>();
926 objective->sexpat_cov_func = std::make_unique<SexpatCF>(*density.kernel);
927 objective->atoms_config = density.configuration;
928 objective->model_profile_ = density.model_profile;
929 objective->use_hssvd_backend_ = false;
930 objective->use_hssvd_objective_contractions_ = false;
931 objective->principled_nugget_ = density.principled_nugget;
932 objective->kappa_max_ = density.kappa_max;
933 objective->lik_gaussian->setSigma2(density.likelihood_sigma2);
934 objective->lik_gaussian->setOptimizeSigma2(density.learn_likelihood_noise);
935 objective->const_cov_fun->setConstSigma2(density.constant_sigma2);
936 objective->jitter_sigma2 = density.jitter_sigma2;
937 objective->scalapack_block_size_ = scalapack_block_size_;
938 objective->scalapack_nprow_ = scalapack_nprow_;
939 objective->configureDistributedTrainingGrid();
940 objective->setParameters(density.theta);
941 EigenMatrix rows;
942 Eigen::VectorXd indices;
944 auxiliary.assembleMatrixOfRepetitiveCoordinates(density.positions, rows,
945 indices);
946 objective->is_decomposed_succesfully =
947 objective->decomposeCovarianceMatrix(rows, indices);
948 if (!objective->is_decomposed_succesfully) return false;
949 objective->calculateMeanPrediction(density.targets);
950 Eigen::MatrixXd hessian;
951 if (!objective->assembleHessianInDirections(indices, rows, density.targets,
952 selected, hessian)) {
953 return false;
954 }
955 // The selected prior penalty is separable; disjoint tie groups preserve
956 // its diagonal reduced Hessian. The kernel's intrinsic prior is in hessian.
957 for (Eigen::Index j = 0; j < selected.cols(); ++j)
959 density.theta, selected.col(j), density.penalty);
960 if (!symmetrizeObservedInformation(hessian)) return false;
961 information = std::move(hessian);
962 directions = std::move(selected);
963 return true;
964}
965
966bool GaussianProcessRegression::ensureLaplaceDeltaCache()
967{
968 // INLA Gaussian-mode delta-method variance cache (Rue 2009 sec
969 // 3.2; GPstuff INLA mode 0 'gaussian'). Stores at theta_MAP:
970 // - U_H : upper-triangular Cholesky of the Hessian H = U^T U
971 // - dalpha_dtheta[j] = -K^{-1} (dK/dtheta_j) alpha for j=1..p
972 // Per-call delta variance per query x*:
973 // g(x*)_j = k_cross(X, x*; theta_MAP)^T dalpha_dtheta[j]
974 // delta_var = ||U^{-T} g||^2
975 // (Drops the (dk_cross/dtheta)^T alpha term; this is exact for
976 // noise hyperparameters and a controlled approximation for
977 // length-scale hyperparameters in the sharply-peaked-posterior
978 // regime that the Laplace approximation already assumes.)
979 //
980 // Cache is keyed on the same LaplacePosteriorStamp as the slice/
981 // PSIS path so it invalidates on training-data, theta_MAP, kernel
982 // state, or MPI rank changes.
983
984 const LaplacePosteriorStamp stamp = currentLaplacePosteriorStamp();
985 if (!stamp.validForPosterior()) {
986 slice_laplace_state_.reset();
987 return false;
988 }
989 if (slice_laplace_state_ && slice_laplace_state_->valid &&
990 slice_laplace_state_->delta_method &&
991 slice_laplace_state_->stamp.matches(stamp)) {
992 return true;
993 }
994
995 if (R_matrix.size() == 0 || sexpat_cov_func == nullptr) {
996 slice_laplace_state_.reset();
997 return false;
998 }
999 const Eigen::VectorXd theta_map = packInlaHyperparameters();
1000 if (theta_map.size() == 0 || !theta_map.allFinite()) {
1001 slice_laplace_state_.reset();
1002 return false;
1003 }
1004 const Eigen::Index p = theta_map.size();
1005
1006 // Need MAP-side training Cholesky L and alpha (b). Both are
1007 // populated by the standard MAP fit path. If they are missing,
1008 // call calculateMeanPrediction to populate b.
1009 if (energy_and_gradient.size() == 0) {
1010 slice_laplace_state_.reset();
1011 return false;
1012 }
1013 const bool factor_ready =
1015 if (b.size() != activeFactorOrder(energy_and_gradient.size()) ||
1016 !factor_ready) {
1017 // The MAP factor can live in the owned distributed solve slot.
1018 // Reconstruct it only when that factor is absent or belongs to
1019 // another model.
1020 if (!factor_ready && R_matrix.rows() > 0) {
1022 }
1024 slice_laplace_state_.reset();
1025 return false;
1026 }
1028 }
1029 if (b.size() == 0 || !is_decomposed_succesfully) {
1030 slice_laplace_state_.reset();
1031 return false;
1032 }
1033
1034 // Hessian H = -d^2 log p(theta | y) / dtheta^2 |_{theta_MAP}.
1035 Eigen::MatrixXd H;
1037 static_cast<int>(p), H)) {
1038 slice_laplace_state_.reset();
1039 return false;
1040 }
1041 if (!symmetrizeObservedInformation(H)) {
1042 slice_laplace_state_.reset();
1043 return false;
1044 }
1045
1046 // Cholesky H = U^T U, with jitter retry for borderline-PD H.
1047 Eigen::LLT<Eigen::MatrixXd> llt_H(H);
1048 if (llt_H.info() != Eigen::Success) {
1049 double jitter = 1.0e-9;
1050 bool ok = false;
1051 while (jitter <= 1.0e-3) {
1052 Eigen::MatrixXd Hj = H;
1053 Hj.diagonal().array() += jitter;
1054 llt_H.compute(Hj);
1055 if (llt_H.info() == Eigen::Success) {
1056 ok = true;
1057 break;
1058 }
1059 jitter *= 10.0;
1060 }
1061 if (!ok) {
1062 slice_laplace_state_.reset();
1063 return false;
1064 }
1065 }
1066 const Eigen::MatrixXd U_H = llt_H.matrixU();
1067
1068 // dK/dtheta_j on training cov. calculateGradOfCovMatrix returns
1069 // the analytical kernel partials in log-space (matching the SCG
1070 // gradient convention). Note: this uses the value-only cov
1071 // gradient; for derivative-augmented training observations the
1072 // partial w.r.t. the value-block dominates and the derivative-
1073 // block correction is small in the well-conditioned regime
1074 // (sympy proof D2: delta method is the leading O(sigma^2) Taylor
1075 // term, higher-order corrections are O(sigma^4)).
1076 laplace::ScopedKernelState fit_guard(*sexpat_cov_func, sigma2,
1077 lik_gaussian.get());
1078 setParameters(theta_map);
1079 // calculateGradOfCovMatrix returns FieldMatrixd (RowMajor) per
1080 // parameter; the matvec dKj * b works regardless of storage
1081 // since Eigen handles mixed-layout binary ops.
1082 std::vector<FieldMatrixd> dK_dtheta;
1083 {
1084 Coord R_train_coord = R_matrix;
1085 Coord R_train_coord_copy = R_matrix;
1086 sexpat_cov_func->calculateGradOfCovMatrix(
1087 R_train_coord, R_train_coord_copy, dK_dtheta);
1088 }
1089
1090 // dalpha/dtheta_j = -L^{-T} L^{-1} (dK/dtheta_j alpha).
1091 // Cached training Cholesky L gives both solves in O(N^2) each.
1092 std::vector<Eigen::VectorXd> dalpha_dtheta;
1093 dalpha_dtheta.reserve(dK_dtheta.size());
1094 const Eigen::Index n_train = b.size();
1095 const auto L_lower = L.template triangularView<Eigen::Lower>();
1096 const auto L_upper_T =
1097 L.transpose().template triangularView<Eigen::Upper>();
1098 for (std::size_t j = 0; j < dK_dtheta.size(); ++j) {
1099 const FieldMatrixd& dKj = dK_dtheta[j];
1100 if (dKj.rows() != n_train || dKj.cols() != n_train) {
1101 // Kernel partial dim mismatch (likely a derivative-aware
1102 // kernel that uses a different layout); fall back to MAP.
1103 slice_laplace_state_.reset();
1104 return false;
1105 }
1106 const Eigen::VectorXd v = dKj * b; // (dK/dtheta_j) alpha
1107 const Eigen::VectorXd t = L_lower.solve(v); // L^{-1} v
1108 Eigen::VectorXd dalpha_j = L_upper_T.solve(t); // L^{-T} L^{-1} v
1109 dalpha_j *= -1.0;
1110 dalpha_dtheta.push_back(std::move(dalpha_j));
1111 }
1112 fit_guard.restore();
1113
1114 auto state = std::make_unique<SliceLaplaceState>();
1115 state->stamp = stamp;
1116 state->delta_method = true;
1117 state->theta_samples = {theta_map};
1118 state->alpha_samples = {b};
1119 state->L_samples = {L};
1120 state->hessian_chol_U = U_H;
1121 state->dalpha_dtheta = std::move(dalpha_dtheta);
1122 state->valid = true;
1123 slice_laplace_state_ = std::move(state);
1124 return true;
1125}
1126
1127void GaussianProcessRegression::calculateVarianceLaplaceDelta(
1128 Observation& image1)
1129{
1130 // Step 1: standard MAP within-sample variance (writes per-query
1131 // variance into image1.E and image1.G). This is the sigma^2 at
1132 // theta_MAP, accounting for the GP's epistemic uncertainty given
1133 // a fixed theta.
1134 calculateMapVarianceInTrainingUnits(image1);
1135
1136 // Step 2: add the delta-method between-sample variance from the
1137 // INLA Gaussian quadrature. Cheap analytical formula -- per-query
1138 // cost is p matvecs of size n_train against cached
1139 // dalpha/dtheta_j vectors plus a p^2 quadratic form via U_H.
1140 if (!ensureLaplaceDeltaCache()) {
1141 // Cache build failed (e.g. derivative-aware kernel partial
1142 // not supported); fall back to within-sample-only variance,
1143 // already written by calculateVariance above.
1144 return;
1145 }
1146 const auto& state = *slice_laplace_state_;
1147 const std::size_t p = state.dalpha_dtheta.size();
1148 if (p == 0) return;
1149
1150 // Cross-covariance K(X_train, X_query; theta_MAP). Reuse the
1151 // standard predict path to assemble.
1152 Index_t N_im = static_cast<Index_t>(image1.R.rows());
1153 Index_t D = static_cast<Index_t>(image1.R.cols());
1154 EigenMatrix R_mod;
1155 Eigen::VectorXd R_mod_ind;
1156 aux::AuxiliaryFunctionality aux_func;
1157 aux_func.assembleMatrixOfRepetitiveCoordinates(image1.R, R_mod, R_mod_ind);
1158
1159 laplace::ScopedKernelState predict_guard(*sexpat_cov_func, sigma2,
1160 lik_gaussian.get());
1161 setParameters(state.theta_samples[0]);
1162
1163 EigenMatrix K_train_query;
1164 evaluateCovarianceMatrix(R_matrix, R_mod, R_indices, R_mod_ind,
1165 K_train_query);
1166
1167 // Layout note: K_train_query is (n_train x n_query). The query
1168 // axis (columns) is what assembleMatrixOfRepetitiveCoordinates
1169 // lays out as (N_im energies, then N_im * D gradient components,
1170 // col-major) -- so the first N_im entries of delta_var (a
1171 // n_query-length vector) are the per-atom energy variance and
1172 // the trailing N_im * D entries are the per-atom-component
1173 // gradient variance. The gate consumes image1.E only, but
1174 // image1.G is updated alongside for consistency with the slice/
1175 // PSIS predict path's writeBMAOutput convention.
1176 const Eigen::Index n_query = K_train_query.cols();
1177
1178 // g matrix (n_query x p): g(:, j) = K_train_query^T dalpha_dtheta[j].
1179 // Per-query g_q is a p-vector; delta_var_q = ||U_H^{-T} g_q||^2.
1180 Eigen::MatrixXd G(n_query, p);
1181 for (std::size_t j = 0; j < p; ++j) {
1182 const auto& da = state.dalpha_dtheta[j];
1183 if (da.size() != K_train_query.rows()) return;
1184 G.col(static_cast<Eigen::Index>(j)) = K_train_query.transpose() * da;
1185 }
1186
1187 // Solve U_H^T u = g(q, :) for each query q. Equivalently, solve
1188 // the entire (n_query x p) system at once: U_H^T U_dummy^T = G^T,
1189 // i.e. (U_H_lower) X = G^T -> X has same shape as G^T (p x n_q).
1190 // Then delta_var(q) = ||X(:, q)||^2.
1191 //
1192 // Conditioning gate + magnitude cap on the DELTA variance
1193 // correction (see GaussianProcessRegression::setDeltaUHMinDiag /
1194 // setDeltaMaxRatio docstring). H = U_H^T U_H; min(diag(U_H)) is a
1195 // lower bound on sqrt(lambda_min(H)). When that bound is below
1196 // delta_uh_min_diag_, H is effectively singular along some theta
1197 // direction and the Mahalanobis form g^T H^{-1} g is not a
1198 // trustworthy variance estimate -> we leave delta_var = 0 (MAP
1199 // variance unchanged downstream). Otherwise compute the
1200 // correction and clip per-query to delta_max_ratio_ * magnSigma2
1201 // so even a marginal H cannot push the corrected variance past a
1202 // physically sensible cap.
1203 const auto U_H_T_lower = state.hessian_chol_U.transpose()
1204 .template triangularView<Eigen::Lower>();
1205 Eigen::VectorXd delta_var = Eigen::VectorXd::Zero(n_query);
1206 const double min_uh_diag =
1207 state.hessian_chol_U.diagonal().cwiseAbs().minCoeff();
1208 if (!(delta_uh_min_diag_ > 0.0) || min_uh_diag >= delta_uh_min_diag_) {
1209 const Eigen::MatrixXd X =
1210 U_H_T_lower.solve(G.transpose()); // (p x n_q)
1211 delta_var = X.colwise().squaredNorm().transpose(); // (n_query)
1212 delta_var = delta_var.cwiseMax(0.0);
1213 if (delta_max_ratio_ > 0.0 && sexpat_cov_func != nullptr) {
1214 const double magn = sexpat_cov_func->getMagnSigma2();
1215 const double cap = delta_max_ratio_ * std::max(magn, 1e-12);
1216 if (std::isfinite(cap)) {
1217 delta_var = delta_var.cwiseMin(cap);
1218 }
1219 }
1220 }
1221
1222 // Add delta_var to image1.E (energy variance per atom) and
1223 // image1.G (gradient variance per atom-component). The gate
1224 // currently only consults image1.E but image1.G stays consistent.
1225 // Layout follows the BMA writer: first N_im entries = energy,
1226 // next N_im * D entries = gradient (col-major).
1227 if (delta_var.size() < static_cast<Eigen::Index>(N_im)) return;
1228 for (Index_t i = 0; i < N_im; ++i) {
1229 image1.E(0, i) += delta_var(static_cast<Eigen::Index>(i));
1230 }
1231 if (delta_var.size() == static_cast<Eigen::Index>(N_im) * (D + 1)) {
1232 for (Index_t i = 0; i < N_im; ++i) {
1233 for (Index_t d = 0; d < D; ++d) {
1234 const Eigen::Index idx = static_cast<Eigen::Index>(N_im) +
1235 static_cast<Eigen::Index>(d) *
1236 static_cast<Eigen::Index>(N_im) +
1237 static_cast<Eigen::Index>(i);
1238 if (idx < delta_var.size()) {
1239 image1.G(i, d) += delta_var(idx);
1240 }
1241 }
1242 }
1243 }
1244}
1245
1246Eigen::MatrixXd GaussianProcessRegression::hyperparameterDirections(
1247 Eigen::Index parameter_count) const
1248{
1249 const Eigen::Index length_count =
1250 sexpat_cov_func->getLengthScaleRef().size();
1251 if (!lengthScaleTiesActive(length_count)) {
1252 return Eigen::MatrixXd::Identity(parameter_count, parameter_count);
1253 }
1254 if (parameter_count < 1 + length_count) return {};
1255 const auto& leaders = length_scale_ties_.leader;
1256 std::vector<Eigen::Index> columns(static_cast<std::size_t>(length_count));
1257 Eigen::Index free_count = 1;
1258 for (Eigen::Index t = 0; t < length_count; ++t) {
1259 if (leaders[t] == t) columns[t] = free_count++;
1260 }
1261 const Eigen::Index trailing = parameter_count - 1 - length_count;
1262 Eigen::MatrixXd directions =
1263 Eigen::MatrixXd::Zero(parameter_count, free_count + trailing);
1264 directions(0, 0) = 1.0;
1265 for (Eigen::Index t = 0; t < length_count; ++t) {
1266 directions(1 + t, columns[leaders[t]]) = 1.0;
1267 }
1268 for (Eigen::Index t = 0; t < trailing; ++t) {
1269 directions(1 + length_count + t, free_count + t) = 1.0;
1270 }
1271 return directions;
1272}
1273
1274bool GaussianProcessRegression::fitLaplaceFromScratch(LaplaceINLA& out)
1275{
1276 // Extract theta_star from the current kernel state. The Laplace
1277 // mixture over hyperparameters sits in LOG-space to match the SCG
1278 // parameterisation (SCG optimises in log-space; eigendecomposition
1279 // and CCD grid stretch the Gaussian approximation there).
1280 //
1281 // Convention: theta = (log magnSigma2, log lengthscales...) with an
1282 // optional trailing log(sigma_n^2) likelihood-noise coordinate.
1283 if (sexpat_cov_func == nullptr) return false;
1284 const Eigen::VectorXd theta_star = packInlaHyperparameters();
1285 if (theta_star.size() == 0 || !theta_star.allFinite()) return false;
1286
1287 // Hessian at MAP via polarisation on evaluateDirectionalCurvature.
1288 // Pass the actual training targets (energy_and_gradient) so the
1289 // directional oracle's `if (b.rows() != y.rows())
1290 // calculateMeanPrediction(y)` guard fires correctly when b is stale.
1291 const Eigen::MatrixXd directions =
1292 hyperparameterDirections(theta_star.size());
1293 if (report_level >= 1) {
1294 const Eigen::Index free_count = directions.cols();
1295 log_man << "[laplace-curvature] rows=" << energy_and_gradient.size()
1296 << " parameters=" << theta_star.size() << " free=" << free_count
1297 << " probes=" << free_count * (free_count + 1) / 2 << "\n";
1298 }
1299 const auto curvature_start = std::chrono::steady_clock::now();
1300 Eigen::VectorXd y_for_curv;
1301 if (energy_and_gradient.size() > 0)
1302 y_for_curv = energy_and_gradient;
1303 else if (b.size() > 0)
1304 y_for_curv = b; // solved target fallback
1305 Eigen::MatrixXd H;
1306 const bool hessian_ok = assembleHessianInDirections(
1307 R_indices, R_matrix, y_for_curv, directions, H);
1308 if (report_level >= 1) {
1309 log_man << "[laplace-curvature] seconds="
1310 << std::chrono::duration<double>(
1311 std::chrono::steady_clock::now() - curvature_start)
1312 .count()
1313 << " valid=" << hessian_ok << "\n";
1314 }
1315 if (!hessian_ok) return false;
1316 if (!symmetrizeObservedInformation(H)) return false;
1317
1318 try {
1319 out.setTheta0(theta_star);
1320 if (directions.cols() == theta_star.size()) {
1321 out.setHessian(H);
1322 } else {
1323 out.setHessian(H, directions);
1324 }
1325 // Axial-only CCD grid (1 + 2p points = 9 at p = 4) instead of
1326 // the full 1 + 2p + 2^p (= 25) grid. Drops 16 of the 25
1327 // per-call Cholesky factorisations of the full-grid
1328 // LAPLACE-mixture predict path. Its weights preserve the Gaussian
1329 // mean and covariance; higher mixed moments depend on the rule.
1330 out.buildGrid(/*f0=*/-1.0, /*include_corners=*/false);
1331 // fit() needs a KernelBuilder + y; the predict-site does that
1332 // step so the closure captures the right training data at call
1333 // time. The structural setup (theta0 + H + CCD grid) is enough
1334 // for the LAPLACE-mixture predict path.
1335 return true;
1336 } catch (const std::exception&) {
1337 return false;
1338 }
1339}
1340
1342{
1343 if (!ensureLaplacePosterior()) {
1344 calculatePotential(image1);
1345 return;
1346 }
1347
1348 Observation mean_out = image1;
1349 if (!calculateLaplacePosteriorMoments(*laplace_posterior_, image1, mean_out,
1350 nullptr)) {
1351 calculatePotential(image1);
1352 return;
1353 }
1354 image1.E = mean_out.E;
1355 image1.G = mean_out.G;
1356 ++num_of_potential_calls;
1357}
1358
1359} // namespace gpr
Linear algebra abstraction layer for GPR hot-path operations.
INLA-style Laplace approximation of the GP/TP hyperparameter posterior.
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.
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.
void setParameters(const GPRSetup &parameters)
Set parameters of the GPR model.
bool fittedHyperparameterInformation(Eigen::MatrixXd &information, Eigen::MatrixXd &directions)
bool decomposeCovarianceMatrix(const EigenMatrix &x, const Eigen::VectorXd &x_ind)
Evaluate and decompose the covariance matrix using Cholesky decomposition.
void calculateVarianceLaplaceSlice(Observation &image1)
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).
bool assembleExactHessian(const Eigen::VectorXd &x_ind, const EigenMatrix &x, const Eigen::VectorXd &y, int n_hyperparameters, Eigen::MatrixXd &H)
Assemble the full p x p observed-information Hessian of the negative log marginal likelihood at the c...
Definition Hessian.cpp:568
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
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 setRetainFittedHyperparameterDensity(bool retain) noexcept
void captureFittedHyperparameterDensity(const Coord &positions, const Eigen::VectorXd &targets, const Eigen::VectorXd &theta, const funcmin::MapObjectiveConfig &penalty, double target_scale, bool use_ties)
void extractUniqueIndices(const Eigen::VectorXd &input_ind, Eigen::VectorXd &output_ind) const
Extract unique indices from the input vector.
bool assembleHessianInDirections(const Eigen::VectorXd &x_ind, const EigenMatrix &x, const Eigen::VectorXd &y, const Eigen::MatrixXd &directions, Eigen::MatrixXd &H)
Definition Hessian.cpp:581
void calculatePotentialLaplaceSlice(Observation &image1)
double evaluateEnergyLocalOnly(const Eigen::VectorXd &w, const EigenMatrix &x, const Eigen::VectorXd &x_ind, const Eigen::VectorXd &y)
Eigen::Index activeFactorOrder(Eigen::Index full_rows) const noexcept
bool hasTrainingCholeskyFactor(Eigen::Index expected_rows) const noexcept
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).
bool lengthScaleTiesActive(Eigen::Index length_count) const noexcept
Laplace / INLA uncertainty quantifier over GP/TP hyperparameters.
Definition LaplaceINLA.h:73
eon_relax_band_t eon_relax_surface_fn void eon_relax_outcome_t * out
bool mapParametersInDomain(const Eigen::VectorXd &w, const MapObjectiveConfig &cfg)
double mapPenaltyDirectionalCurvature(const Eigen::VectorXd &w, const Eigen::VectorXd &direction, const MapObjectiveConfig &cfg)
double estimateParetoKHat(const std::vector< double > &weights_descending, int M_pareto)
std::vector< double > selfNormalisedWeights(const std::vector< double > &log_w)
constexpr MpiCommType kMpiCommNull
Definition MpiContext.h:56
void exact_sum_bcast(ExactSum *sums, int count, const MpiContext &context)
Gaussian-process regression, kernels, priors, and the searches that run on the surrogate.
Definition Macros.h:16
FieldMatrixd Coord
Definition Macros.h:35
uint32_t Index_t
Definition Macros.h:17
Eigen::Matrix< double, EigenDynamic, EigenDynamic, EigenMatrixStorage > EigenMatrix
Definition Macros.h:20
Eigen::Matrix< double, EigenDynamic, EigenDynamic, FieldMatrixStorage > FieldMatrixd
Definition Macros.h:25
Eigen::VectorXd parameter_lower
Eigen::VectorXd parameter_upper
std::vector< bool > active_parameters
Observation data: energy, gradient and positions.
FieldMatrixd E