Loading...
Searching...
No Matches
PsisLaplace.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// Copyright (c) gpridge developers
3// See LICENSE for details.
4
5#include "PsisLaplace.h"
6
7#include <Eigen/Cholesky>
8#include <algorithm>
9#include <cmath>
10#include <limits>
11#include <numeric>
12
13namespace gpr {
14namespace laplace {
15
17 : opts_(std::move(opts)), rng_(opts_.seed)
18{
19}
20
21double logGaussianDensity(const Eigen::VectorXd& delta,
22 const Eigen::MatrixXd& cov_chol)
23{
24 const Eigen::Index p = delta.size();
25 if (p <= 0 || cov_chol.rows() != p || cov_chol.cols() != p) {
26 return std::numeric_limits<double>::quiet_NaN();
27 }
28 // Quadratic form: delta^T Sigma^{-1} delta = ||L^{-1} delta||^2
29 const Eigen::VectorXd z =
30 cov_chol.template triangularView<Eigen::Lower>().solve(delta);
31 const double quad = z.squaredNorm();
32 // log det Sigma = 2 sum log diag(L)
33 const double log_det = 2.0 * cov_chol.diagonal().array().log().sum();
34 constexpr double LOG_2PI =
35 1.8378770664093454835606594728112352797227949472756;
36 return -0.5 * quad - 0.5 * log_det - 0.5 * static_cast<double>(p) * LOG_2PI;
37}
38
39std::vector<double> selfNormalisedWeights(const std::vector<double>& log_w)
40{
41 const std::size_t K = log_w.size();
42 if (K == 0) return {};
43 const double max_lw = *std::max_element(log_w.begin(), log_w.end());
44 if (!std::isfinite(max_lw)) return std::vector<double>(K, 0.0);
45 std::vector<double> w(K);
46 double sum = 0.0;
47 for (std::size_t k = 0; k < K; ++k) {
48 const double v = std::exp(log_w[k] - max_lw);
49 w[k] = std::isfinite(v) ? v : 0.0;
50 sum += w[k];
51 }
52 if (sum <= 0.0) return std::vector<double>(K, 0.0);
53 for (std::size_t k = 0; k < K; ++k)
54 w[k] /= sum;
55 return w;
56}
57
58double estimateParetoKHat(const std::vector<double>& weights_descending,
59 int M_pareto)
60{
61 if (M_pareto < 2 ||
62 static_cast<std::size_t>(M_pareto) > weights_descending.size()) {
63 return 0.0;
64 }
65 // Hill estimator: k_hat = (1 / (M_pareto - 1))
66 // * sum_{i = 0}^{M_pareto - 2} log(w_i / w_{M_pareto
67 // - 1})
68 // where w_0 >= w_1 >= ... >= w_{M_pareto - 1} > 0.
69 const double threshold = weights_descending[M_pareto - 1];
70 if (threshold <= 0.0) return 0.0;
71 double acc = 0.0;
72 int count = 0;
73 for (int i = 0; i < M_pareto - 1; ++i) {
74 const double w_i = weights_descending[i];
75 if (w_i <= 0.0) continue;
76 const double ratio = w_i / threshold;
77 if (ratio <= 1.0) continue; // numeric tie at the threshold
78 acc += std::log(ratio);
79 ++count;
80 }
81 if (count == 0) return 0.0;
82 return acc / static_cast<double>(count);
83}
84
85bool PsisLaplace::fit(const Eigen::VectorXd& theta_map,
86 const Eigen::MatrixXd& hessian,
87 const LogTarget& log_target, const AlphaCacheFn& alpha_fn,
89{
90 out.valid = false;
91 out.reliable = false;
92 out.k_hat = 0.0;
93 out.n_target_evals = 0;
94
95 const Eigen::Index p = theta_map.size();
96 if (p == 0 || hessian.rows() != p || hessian.cols() != p) return false;
97
98 // Cholesky of the proposal covariance. Sigma = H^{-1}; we want L
99 // such that Sigma = L L^T. Compute L by factoring H = U U^T (U
100 // upper-triangular in Eigen's matrixL() convention), then
101 // L = (U^T)^{-1} which we obtain by solving U^T L = I in two
102 // steps. Equivalent and cheaper: Cholesky-factor H and form
103 // L = U_H^{-T}; sample x = theta_map + L z for z ~ N(0, I) gives
104 // x ~ N(theta_map, H^{-1}).
105 Eigen::MatrixXd H = hessian;
106 Eigen::LLT<Eigen::MatrixXd> llt_H(H);
107 if (llt_H.info() != Eigen::Success) {
108 // Hessian not PD; jitter and retry.
109 double jitter = 1.0e-9;
110 bool ok = false;
111 while (jitter <= opts_.hessian_jitter_max) {
112 H = hessian;
113 H.diagonal().array() += jitter;
114 llt_H.compute(H);
115 if (llt_H.info() == Eigen::Success) {
116 ok = true;
117 break;
118 }
119 jitter *= 10.0;
120 }
121 if (!ok) return false;
122 }
123
124 // U_H is upper triangular with H = U_H U_H^T.
125 // L = U_H^{-T} satisfies L L^T = (U_H^T)^{-1} U_H^{-1} = (U_H U_H^T)^{-1} =
126 // H^{-1}. Solve U_H^T L = I for L.
127 const Eigen::MatrixXd U_H = llt_H.matrixU();
128 const Eigen::MatrixXd I =
129 Eigen::MatrixXd::Identity(static_cast<int>(p), static_cast<int>(p));
130 const Eigen::MatrixXd L =
131 U_H.transpose().template triangularView<Eigen::Lower>().solve(I);
132
133 out.theta_map = theta_map;
134 out.proposal_cov_chol = L;
135
136 // Sample-position generator: random N(theta_MAP, H^{-1}) draws by
137 // default, or a deterministic axial grid (CCD-style: theta_MAP and
138 // theta_MAP +/- sigma_j e_j on the principal axes of H^{-1}) when
139 // opts_.deterministic_axial_grid is true. The axial grid gives
140 // K = 1 + 2 p reproducible samples regardless of MPI rank topology
141 // -- the per-rank seed offset that made random PSIS np-fragile is
142 // absent. SymPy proof of axial-grid-LOTV identity:
143 // python/tests/test_sympy_inla_delta.py P6 (quadratic form delta
144 // method). The IS weights are still computed under the same
145 // proposal q = N(theta_MAP, H^{-1}); the only thing that changes
146 // is the sample positions.
147 int K = std::max(1, opts_.n_samples);
148 std::vector<Eigen::VectorXd> sample_positions;
149 if (opts_.deterministic_axial_grid) {
150 K = 1 + 2 * static_cast<int>(p);
151 sample_positions.reserve(K);
152 sample_positions.push_back(theta_map);
153 for (Eigen::Index j = 0; j < p; ++j) {
154 Eigen::VectorXd e_j = Eigen::VectorXd::Zero(p);
155 e_j(j) = 1.0;
156 const Eigen::VectorXd step = L * e_j;
157 sample_positions.push_back(theta_map + step);
158 sample_positions.push_back(theta_map - step);
159 }
160 } else {
161 sample_positions.reserve(K);
162 std::normal_distribution<double> normal_init(0.0, 1.0);
163 for (int k = 0; k < K; ++k) {
164 Eigen::VectorXd z(p);
165 for (Eigen::Index j = 0; j < p; ++j)
166 z(j) = normal_init(rng_);
167 sample_positions.push_back(theta_map + L * z);
168 }
169 }
170
171 out.theta_samples.clear();
172 out.theta_samples.reserve(K);
173 out.alpha_samples.clear();
174 out.alpha_samples.reserve(K);
175 out.log_weights_raw.clear();
176 out.log_weights_raw.reserve(K);
177
178 // Iterate the precomputed sample positions and evaluate
179 // log_target / alpha_fn at each. The same code path serves both
180 // the random IS draws and the deterministic axial grid.
181 for (int k = 0; k < K; ++k) {
182 Eigen::VectorXd theta_k = sample_positions[k];
183
184 const double log_p_target = log_target(theta_k);
185 if (!std::isfinite(log_p_target)) {
186 // Sample fell outside the target's support; record but
187 // mark invalid via NaN log-weight so it is dropped from
188 // the normalised weight vector.
189 out.theta_samples.push_back(std::move(theta_k));
190 out.alpha_samples.emplace_back();
191 out.log_weights_raw.push_back(
192 std::numeric_limits<double>::quiet_NaN());
193 continue;
194 }
195 ++out.n_target_evals;
196 // log q(theta_k) under N(theta_map, H^{-1}). The quadratic
197 // term in the closed-form (-0.5 z^T z, since z = L^{-1} delta)
198 // is just -0.5 * z.squaredNorm() because z was drawn standard
199 // normal. We could shortcut, but we evaluate via
200 // logGaussianDensity for symmetry with the unit-test path.
201 const Eigen::VectorXd delta = theta_k - theta_map;
202 const double log_q = logGaussianDensity(delta, L);
203 const double log_w = log_p_target - log_q;
204
205 // alpha for this sample (cached for the predict path).
206 Eigen::VectorXd alpha;
207 if (alpha_fn) alpha = alpha_fn(theta_k);
208
209 out.theta_samples.push_back(std::move(theta_k));
210 out.alpha_samples.push_back(std::move(alpha));
211 out.log_weights_raw.push_back(log_w);
212 }
213
214 // Self-normalise weights, ignoring samples with NaN log-weight
215 // (they get weight 0 and are excluded from normalisation).
216 std::vector<double> log_w_finite;
217 log_w_finite.reserve(out.log_weights_raw.size());
218 std::vector<int> finite_idx;
219 finite_idx.reserve(out.log_weights_raw.size());
220 for (std::size_t i = 0; i < out.log_weights_raw.size(); ++i) {
221 if (std::isfinite(out.log_weights_raw[i])) {
222 log_w_finite.push_back(out.log_weights_raw[i]);
223 finite_idx.push_back(static_cast<int>(i));
224 }
225 }
226 out.weights.assign(out.log_weights_raw.size(), 0.0);
227 if (log_w_finite.empty()) return false;
228
229 const std::vector<double> w_finite = selfNormalisedWeights(log_w_finite);
230 for (std::size_t j = 0; j < finite_idx.size(); ++j) {
231 out.weights[static_cast<std::size_t>(finite_idx[j])] = w_finite[j];
232 }
233
234 // k-hat diagnostic on the upper tail. Vehtari 2024 recommends
235 // M_pareto = min(K/5, 3*sqrt(K)); at K = 16 that is 3 which is
236 // too few. Use min(K - 1, max(K / 5, K / 4)) so we get a usable
237 // tail estimator without consuming the whole sample.
238 std::vector<double> w_sorted = w_finite;
239 std::sort(w_sorted.begin(), w_sorted.end(), std::greater<double>());
240 const int K_finite = static_cast<int>(w_sorted.size());
241 const int M_pareto = std::min(std::max(K_finite / 5, 4), K_finite - 1);
242 out.k_hat = estimateParetoKHat(w_sorted, M_pareto);
243 out.reliable = (out.k_hat <= opts_.k_hat_threshold);
244
245 out.valid = true;
246 return true;
247}
248
249} // namespace laplace
250} // namespace gpr
@ z
Definition Enums.h:28
std::function< double(const Eigen::VectorXd &)> LogTarget
PsisLaplace(PsisLaplaceOptions opts={})
std::function< Eigen::VectorXd(const Eigen::VectorXd &)> AlphaCacheFn
bool fit(const Eigen::VectorXd &theta_map, const Eigen::MatrixXd &hessian, const LogTarget &log_target, const AlphaCacheFn &alpha_fn, PsisLaplaceState &out)
eon_relax_band_t eon_relax_surface_fn void eon_relax_outcome_t * out
double estimateParetoKHat(const std::vector< double > &weights_descending, int M_pareto)
double logGaussianDensity(const Eigen::VectorXd &delta, const Eigen::MatrixXd &cov_chol)
std::vector< double > selfNormalisedWeights(const std::vector< double > &log_w)
Gaussian-process regression, kernels, priors, and the searches that run on the surrogate.
Definition Macros.h:16
STL namespace.