Loading...
Searching...
No Matches
SVGD.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// Stein Variational Gradient Descent predict path. fitSVGDFromScratch
6// builds a fresh particle posterior from a caller-owned LaplaceINLA fit;
7// calculate{Potential,Variance}SVGD route the posterior through the
8// uniform-particle Laplace mixture for predict and variance.
9
10#include <Eigen/Core>
11#include <cmath>
12#include <stdexcept>
13#include <utility>
14
17#include "../LaplaceINLA.h"
21
22namespace gpr {
23
24bool GaussianProcessRegression::fitSVGDFromScratch(
26{
27 // Initialise particles from the CCD pattern in z-space then map
28 // through L_scale. theta_star + L_scale come from the caller-owned
29 // LaplaceINLA fit (the dimer fits Laplace fresh once per call and
30 // hands the resulting object here).
31 const auto& theta_star = laplace.theta0();
32 const auto& L_scale = laplace.lScale();
33 if (theta_star.size() == 0 || L_scale.rows() == 0) return false;
34 try {
35 out.initFromCCD(theta_star, L_scale);
36 } catch (const std::exception&) {
37 return false;
38 }
39
40 // Capture training data + targets for the SVGD gradient oracle. The
41 // oracle returns the log-posterior gradient (= -NLML gradient).
42 // y_capture is moved into the closure so the lambda owns its
43 // training-target snapshot for the duration of the fit -- the
44 // closure outlives the local y_capture variable.
45 //
46 // Routing through evaluateEnergyAndGradientLocal (Eigen LLT, no
47 // collectives) is mandatory: SteinVariational::fit distributes
48 // particles round-robin across MPI ranks, so each grad_oracle call
49 // happens on a different theta_k per rank. The distributed
50 // evaluateEnergyAndGradient would call ScaLAPACK's pdpotrf as a
51 // collective and either deadlock or feed mismatched matrices into
52 // the same global call.
53 Eigen::VectorXd y_capture = energy_and_gradient;
54 const auto grad_oracle =
55 [this, y_capture = std::move(y_capture)](
56 const Eigen::VectorXd& theta) -> Eigen::VectorXd {
57 double e_buf = 0.0;
58 Eigen::VectorXd g_buf;
59 EnergyAndGradient eg(e_buf, g_buf);
61 eg);
62 if (!std::isfinite(eg.energy) || eg.gradient.size() != theta.size() ||
63 !eg.gradient.allFinite()) {
64 return Eigen::VectorXd::Zero(theta.size());
65 }
66 // log-posterior gradient = -NLML gradient.
67 return Eigen::VectorXd(-eg.gradient);
68 };
69
70 // Snapshot + restore kernel state across the SVGD fit -- the
71 // gradient oracle mutates (magn, ls, sigma2) at each particle.
72 laplace::ScopedKernelState guard(*sexpat_cov_func, sigma2,
73 lik_gaussian.get());
74
75 // RAII flip: gpr::sexpat_local_oracle_active = true for the
76 // duration of the SVGD fit. Gates the OpenMP pragma in
77 // SexpatCF::calculateGradOfCovMatrixWithDerivatives* so the per-pair
78 // derivative kernel parallelises only on this rank-local gradient
79 // compute, never inside the SCG/MAP distributed Cholesky path.
80 SexpatLocalOracleScope omp_scope;
81
82 const int t_done = out.fit(grad_oracle, svgd_config_, mpiContext());
83 (void)t_done;
84 return out.fitted();
85}
86
88{
89 // The particle-fit oracle decomposes at other hyperparameters and
90 // leaves that factor behind. Curvature for the next mixture is the
91 // Hessian at the caller's theta, so rebuild that factor first.
92 if (R_matrix.rows() > 0 && R_indices.size() == R_matrix.rows())
94 // Predict using SVGD particles as a uniformly weighted mixture.
95 LaplaceINLA local_laplace;
96 if (!fitLaplaceFromScratch(local_laplace)) {
97 Observation mean_out = image1;
98 if (usesRankOwnedMixturePosterior() &&
99 calculateRankOwnedMapPosteriorMoments(image1, mean_out, nullptr)) {
100 image1.E = mean_out.E;
101 image1.G = mean_out.G;
102 ++num_of_potential_calls;
103 return;
104 }
105 calculatePotential(image1);
106 return;
107 }
108 laplace::SteinVariational local_svgd;
109 if (!fitSVGDFromScratch(local_laplace, local_svgd)) {
110 Observation mean_out = image1;
111 if (usesRankOwnedMixturePosterior() &&
112 calculateRankOwnedMapPosteriorMoments(image1, mean_out, nullptr)) {
113 image1.E = mean_out.E;
114 image1.G = mean_out.G;
115 ++num_of_potential_calls;
116 return;
117 }
118 calculatePotential(image1);
119 return;
120 }
121 const auto& particles = local_svgd.particles();
122 if (particles.empty() || R_matrix.size() == 0 ||
123 energy_and_gradient.size() == 0) {
124 Observation mean_out = image1;
125 if (usesRankOwnedMixturePosterior() &&
126 calculateRankOwnedMapPosteriorMoments(image1, mean_out, nullptr)) {
127 image1.E = mean_out.E;
128 image1.G = mean_out.G;
129 ++num_of_potential_calls;
130 return;
131 }
132 calculatePotential(image1);
133 return;
134 }
135 const LaplacePosteriorSignature signature =
136 currentLaplacePosteriorSignature();
138 if (!buildUniformParticlePosteriorState(particles, signature, state)) {
139 Observation mean_out = image1;
140 if (usesRankOwnedMixturePosterior() &&
141 calculateRankOwnedMapPosteriorMoments(image1, mean_out, nullptr)) {
142 image1.E = mean_out.E;
143 image1.G = mean_out.G;
144 ++num_of_potential_calls;
145 return;
146 }
147 calculatePotential(image1);
148 return;
149 }
150 Observation mean_out = image1;
151 if (!calculateLaplacePosteriorMoments(state, image1, mean_out, nullptr)) {
152 if (usesRankOwnedMixturePosterior() &&
153 calculateRankOwnedMapPosteriorMoments(image1, mean_out, nullptr)) {
154 image1.E = mean_out.E;
155 image1.G = mean_out.G;
156 ++num_of_potential_calls;
157 return;
158 }
159 calculatePotential(image1);
160 return;
161 }
162 image1.E = mean_out.E;
163 image1.G = mean_out.G;
164 ++num_of_potential_calls;
165}
166
168{
169 // Variance via the law of total variance over SVGD particles.
170 LaplaceINLA local_laplace;
171 if (!fitLaplaceFromScratch(local_laplace)) {
172 Observation mean_out = image1;
173 Observation variance_out = image1;
174 if (usesRankOwnedMixturePosterior() &&
175 calculateRankOwnedMapPosteriorMoments(image1, mean_out,
176 &variance_out)) {
177 image1.E = variance_out.E;
178 image1.G = variance_out.G;
179 return;
180 }
181 calculateMapVarianceInTrainingUnits(image1);
182 return;
183 }
184 laplace::SteinVariational local_svgd;
185 if (!fitSVGDFromScratch(local_laplace, local_svgd)) {
186 Observation mean_out = image1;
187 Observation variance_out = image1;
188 if (usesRankOwnedMixturePosterior() &&
189 calculateRankOwnedMapPosteriorMoments(image1, mean_out,
190 &variance_out)) {
191 image1.E = variance_out.E;
192 image1.G = variance_out.G;
193 return;
194 }
195 calculateMapVarianceInTrainingUnits(image1);
196 return;
197 }
198 const auto& particles = local_svgd.particles();
199 if (particles.empty() || R_matrix.size() == 0 ||
200 energy_and_gradient.size() == 0) {
201 Observation mean_out = image1;
202 Observation variance_out = image1;
203 if (usesRankOwnedMixturePosterior() &&
204 calculateRankOwnedMapPosteriorMoments(image1, mean_out,
205 &variance_out)) {
206 image1.E = variance_out.E;
207 image1.G = variance_out.G;
208 return;
209 }
210 calculateMapVarianceInTrainingUnits(image1);
211 return;
212 }
213 const LaplacePosteriorSignature signature =
214 currentLaplacePosteriorSignature();
216 if (!buildUniformParticlePosteriorState(particles, signature, state)) {
217 Observation mean_out = image1;
218 Observation variance_out = image1;
219 if (usesRankOwnedMixturePosterior() &&
220 calculateRankOwnedMapPosteriorMoments(image1, mean_out,
221 &variance_out)) {
222 image1.E = variance_out.E;
223 image1.G = variance_out.G;
224 return;
225 }
226 calculateMapVarianceInTrainingUnits(image1);
227 return;
228 }
229 Observation mean_out = image1;
230 Observation variance_out = image1;
231 if (!calculateLaplacePosteriorMoments(state, image1, mean_out,
232 &variance_out)) {
233 if (usesRankOwnedMixturePosterior() &&
234 calculateRankOwnedMapPosteriorMoments(image1, mean_out,
235 &variance_out)) {
236 image1.E = variance_out.E;
237 image1.G = variance_out.G;
238 return;
239 }
240 calculateMapVarianceInTrainingUnits(image1);
241 return;
242 }
243 image1.E = variance_out.E;
244 image1.G = variance_out.G;
245}
246
248GaussianProcessRegression::calculateSvgdMixtureMeanHessianVector(
249 const Coord& R, const Eigen::VectorXd& direction,
250 Eigen::VectorXd& hessian_vector)
251{
252 hessian_vector.resize(0);
253 const Eigen::Index dof = R.cols();
254 if (uncertainty_mode_ != UncertaintyMode::SVGD ||
255 atomic_environment_model_ || active_posterior_ ||
256 sexpat_cov_func == nullptr || R.rows() != 1 ||
257 direction.size() != dof || dof <= 0 || !R.allFinite() ||
258 !direction.allFinite() || R_matrix.size() == 0 ||
259 energy_and_gradient.size() == 0) {
261 }
262
263 // A failed fit uses the MAP mean, the same way calculatePotentialSVGD
264 // does. That mean's own derivative is returned below. A built mixture
265 // that cannot be contracted refuses instead of differencing it.
266 {
267 laplace::ScopedKernelState guard(*sexpat_cov_func, sigma2,
268 lik_gaussian.get());
269 if (R_matrix.rows() > 0 && R_indices.size() == R_matrix.rows())
271 LaplaceINLA local_laplace;
272 laplace::SteinVariational local_svgd;
273 if (fitLaplaceFromScratch(local_laplace) &&
274 fitSVGDFromScratch(local_laplace, local_svgd)) {
275 const auto& particles = local_svgd.particles();
276 LaplacePosteriorState state;
277 if (!particles.empty() &&
278 buildUniformParticlePosteriorState(
279 particles, currentLaplacePosteriorSignature(), state)) {
280 return contractFactorMixtureMeanHessian(state, R, direction,
281 hessian_vector);
282 }
283 }
284 }
285 return calculateMapFallbackMeanHessianVector(R, direction, hessian_vector);
286}
287
288} // namespace gpr
INLA-style Laplace approximation of the GP/TP hyperparameter posterior.
void calculatePotentialSVGD(Observation &image1)
Definition SVGD.cpp:87
void calculateVarianceSVGD(Observation &image1)
Definition SVGD.cpp:167
void calculatePotential(Observation &image1)
Calculate potential within GPR model.
Definition Predict.cpp:713
std::unique_ptr< SexpatCF > sexpat_cov_func
void evaluateEnergyAndGradientLocal(const Eigen::VectorXd &w, const EigenMatrix &x, const Eigen::VectorXd &x_ind, const Eigen::VectorXd &y, EnergyAndGradient &energy_and_gradient)
bool decomposeForFittedTargets()
Factor the fitted design at the current hyperparameters and leave the posterior weights those of the ...
Laplace / INLA uncertainty quantifier over GP/TP hyperparameters.
Definition LaplaceINLA.h:73
const std::vector< Eigen::VectorXd > & particles() const noexcept
Particle access (post-fit).
eon_relax_band_t eon_relax_surface_fn void eon_relax_outcome_t * out
Gaussian-process regression, kernels, priors, and the searches that run on the surrogate.
Definition Macros.h:16
FieldMatrixd Coord
Definition Macros.h:35
Observation data: energy, gradient and positions.
FieldMatrixd E