Loading...
Searching...
No Matches
SteinVariational.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 "SteinVariational.h"
6
7#include <Eigen/QR>
8#include <algorithm>
9#include <cmath>
10#include <cstdio>
11#include <stdexcept>
12#include <vector>
13
15
16#ifdef GPR_LINALG_SCALAPACK
17#include <mpi.h>
18#endif
19
20namespace gpr {
21namespace laplace {
22
23namespace {
24
25// CCD point set in z-space (Rue, Martino, Chopin 2009 Section 4.1).
26// 1 centre + 2p axis points + 2^p factorial corners. Same generator as
27// LaplaceINLA::buildGrid; duplicated locally for SVGD initialisation
28// to avoid coupling header dependencies.
29std::vector<Eigen::VectorXd> ccdSet(int p, double f0)
30{
31 if (p <= 0 || f0 <= 0.0) return {};
32 std::vector<Eigen::VectorXd> out;
33 // Origin
34 out.emplace_back(Eigen::VectorXd::Zero(p));
35 // Axis points
36 for (int d = 0; d < p; ++d) {
37 Eigen::VectorXd z = Eigen::VectorXd::Zero(p);
38 z(d) = f0;
39 out.push_back(z);
40 z(d) = -f0;
41 out.push_back(z);
42 }
43 // Factorial corners at radius f0 in L2.
44 if (p >= 2) {
45 const int n_corner = 1 << p;
46 const double corner_axis = f0 / std::sqrt(static_cast<double>(p));
47 for (int mask = 0; mask < n_corner; ++mask) {
48 Eigen::VectorXd z = Eigen::VectorXd::Zero(p);
49 for (int d = 0; d < p; ++d) {
50 const double sign = ((mask >> d) & 1) ? +1.0 : -1.0;
51 z(d) = sign * corner_axis;
52 }
53 out.push_back(z);
54 }
55 }
56 return out;
57}
58
59double ruesDefaultF0(int p)
60{
61 // Liu & Wang 2016 don't prescribe an initial spread; we reuse the
62 // Rue 2009 CCD default, matching LaplaceINLA::buildGrid.
63 if (p <= 0) return 0.0;
64 return std::sqrt(static_cast<double>(p) + 2.0);
65}
66
67} // namespace
68
69void SteinVariational::initFromCCD(const Eigen::VectorXd& theta_star,
70 const Eigen::MatrixXd& L, double f0)
71{
72 invalidate();
73 const int p = static_cast<int>(theta_star.size());
74 if (p <= 0) {
75 throw std::invalid_argument(
76 "SteinVariational::initFromCCD: empty theta_star");
77 }
78 const int q = static_cast<int>(L.cols());
79 if (L.rows() != p || q <= 0 || q > p || !L.allFinite()) {
80 throw std::invalid_argument(
81 "SteinVariational::initFromCCD: L dimension mismatch");
82 }
83 if (q < p) {
84 const Eigen::ColPivHouseholderQR<Eigen::MatrixXd> factor(L);
85 if (factor.rank() != q) {
86 throw std::invalid_argument(
87 "SteinVariational::initFromCCD: dependent parameter "
88 "directions");
89 }
90 parameter_basis_ =
91 factor.householderQ() * Eigen::MatrixXd::Identity(p, q);
92 }
93 if (f0 <= 0.0) f0 = ruesDefaultF0(q);
94
95 const auto z_pts = ccdSet(q, f0);
96 particles_.clear();
97 particles_.reserve(z_pts.size());
98 for (const auto& z: z_pts) {
99 particles_.emplace_back(theta_star + L * z);
100 }
101}
102
103Eigen::MatrixXd SteinVariational::rbfKernel(double* h_out) const
104{
105 const std::size_t K = particles_.size();
106 if (K == 0) {
107 if (h_out) *h_out = 0.0;
108 return {};
109 }
110 // Pairwise squared distances + median heuristic for bandwidth.
111 Eigen::MatrixXd dist_sq(K, K);
112 std::vector<double> all_dist;
113 all_dist.reserve(K * (K - 1) / 2);
114 for (std::size_t i = 0; i < K; ++i) {
115 dist_sq(i, i) = 0.0;
116 for (std::size_t j = i + 1; j < K; ++j) {
117 const double d2 = (particles_[i] - particles_[j]).squaredNorm();
118 dist_sq(i, j) = d2;
119 dist_sq(j, i) = d2;
120 all_dist.push_back(d2);
121 }
122 }
123 // Median of pairwise squared distances; h = sqrt(median / log K)
124 // is the Liu & Wang 2016 heuristic.
125 double h = 1.0;
126 if (!all_dist.empty()) {
127 const auto mid = all_dist.size() / 2;
128 std::nth_element(all_dist.begin(), all_dist.begin() + mid,
129 all_dist.end());
130 const double median_sq = all_dist[mid];
131 const double log_K = std::log(std::max<double>(K, 2.0));
132 h = std::sqrt(std::max(median_sq, 1e-12) / log_K);
133 }
134 if (h_out) *h_out = h;
135 const double inv_2h2 = 1.0 / (2.0 * h * h);
136 Eigen::MatrixXd K_mat(K, K);
137 for (std::size_t i = 0; i < K; ++i) {
138 for (std::size_t j = 0; j < K; ++j) {
139 K_mat(i, j) = std::exp(-dist_sq(i, j) * inv_2h2);
140 }
141 }
142 return K_mat;
143}
144
145int SteinVariational::fit(GradOracle grad_oracle, int T, double eps,
146 double conv_tol)
147{
148 return fit(std::move(grad_oracle), T, eps, conv_tol,
150}
151
152int SteinVariational::fit(GradOracle grad_oracle, int T, double eps,
153 double conv_tol,
154 const linalg::MpiContext& process_group)
155{
156 if (particles_.empty()) {
157 throw std::runtime_error(
158 "SteinVariational::fit: call initFromCCD first");
159 }
160 if (T <= 0) {
161 fitted_ = true;
162 return 0;
163 }
164
165 const std::size_t K = particles_.size();
166 const int p = static_cast<int>(particles_.front().size());
167
168 const int mpi_rank = process_group.rank;
169 const int mpi_size = process_group.nprocs;
170
171 // SVGD iteration loop. Convergence: max particle update norm
172 // falls below conv_tol relative to median pairwise distance.
173 int t_done = 0;
174 for (int t = 0; t < T; ++t) {
175 // Compute log-posterior gradients at each particle.
176 // Distribute the K per-particle gradient oracle calls across
177 // MPI ranks (round-robin). Each oracle call assembles K(theta_k)
178 // and Cholesky-factors it; the K calls are fully independent,
179 // so the distributed cost is K / nprocs Choleskies per rank
180 // instead of K sequential. After the local pass an
181 // MPI_Allreduce on a stacked (K * p)-vector buffer collects
182 // every rank's owned gradients.
183 //
184 // CRITICAL invariant: the grad_oracle must NOT call any MPI /
185 // ScaLAPACK collective inside (pdpotrf, MPI_Allreduce, etc.)
186 // because each rank holds a different particle here -- a
187 // collective would either deadlock or feed different matrices
188 // into the same global call. The SVGD oracle wired by
189 // GaussianProcessRegression::fitSVGDFromScratch satisfies this
190 // by routing through the local-only Eigen LLT path
191 // evaluateEnergyAndGradientLocal.
192 std::vector<Eigen::VectorXd> grads(K, Eigen::VectorXd::Zero(p));
193 bool any_nan = false;
194 for (std::size_t k = 0; k < K; ++k) {
195 if (static_cast<int>(k) % mpi_size != mpi_rank) continue;
196 grads[k] = grad_oracle(particles_[k]);
197 if (grads[k].size() != p || !grads[k].allFinite()) {
198 any_nan = true;
199 break;
200 }
201 if (parameter_basis_.cols() > 0) {
202 grads[k] = parameter_basis_ *
203 (parameter_basis_.transpose() * grads[k]).eval();
204 }
205 }
206#ifdef GPR_LINALG_SCALAPACK
207 if (mpi_size > 1) {
208 // Each rank owns a disjoint subset; sum-reduce the stacked
209 // (K * p)-vector to broadcast the owner's gradient to all
210 // ranks. Use a stacked buffer so a single Allreduce covers
211 // all K particles. Also OR-reduce the any_nan flag so any
212 // rank's NaN aborts the whole iteration.
213 std::vector<double> buf(
214 static_cast<size_t>(K) * static_cast<size_t>(p), 0.0);
215 for (std::size_t k = 0; k < K; ++k) {
216 if (static_cast<int>(k) % mpi_size != mpi_rank) continue;
217 std::copy(grads[k].data(), grads[k].data() + p,
218 buf.data() +
219 static_cast<size_t>(k) * static_cast<size_t>(p));
220 }
221 MPI_Allreduce(MPI_IN_PLACE, buf.data(),
222 static_cast<int>(buf.size()), MPI_DOUBLE, MPI_SUM,
223 process_group.comm);
224 int local_nan = any_nan ? 1 : 0;
225 int global_nan = 0;
226 MPI_Allreduce(&local_nan, &global_nan, 1, MPI_INT, MPI_MAX,
227 process_group.comm);
228 any_nan = (global_nan != 0);
229 for (std::size_t k = 0; k < K; ++k) {
230 grads[k] = Eigen::Map<Eigen::VectorXd>(
231 buf.data() +
232 static_cast<size_t>(k) * static_cast<size_t>(p),
233 p);
234 }
235 }
236#endif
237 if (any_nan) {
238 std::fprintf(
239 stderr,
240 "[SteinVariational] non-finite gradient at iter %d; "
241 "stopping early with %lu particles in current state.\n",
242 t, K);
243 break;
244 }
245
246 // RBF kernel + bandwidth.
247 double h = 1.0;
248 const Eigen::MatrixXd K_mat = rbfKernel(&h);
249 const double inv_h2 = 1.0 / (h * h);
250
251 // SVGD update direction phi*(theta_k):
252 // phi*(theta_k) = (1/K) sum_j [k(theta_j, theta_k) * grad_j
253 // + grad_{theta_j} k(theta_j, theta_k)]
254 //
255 // For RBF kernel k(x, y) = exp(-||x-y||^2 / 2h^2):
256 // grad_y k(x, y) = -(y - x) / h^2 * k(x, y)
257 // and we want grad_{theta_j} k(theta_j, theta_k) =
258 // -(theta_j - theta_k) / h^2 * k(theta_j, theta_k)
259 // = (theta_k - theta_j) / h^2 * k(theta_j, theta_k)
260 std::vector<Eigen::VectorXd> phi(K, Eigen::VectorXd::Zero(p));
261 for (std::size_t k = 0; k < K; ++k) {
262 for (std::size_t j = 0; j < K; ++j) {
263 const double k_jk = K_mat(j, k);
264 phi[k] += k_jk * grads[j];
265 phi[k] += inv_h2 * k_jk * (particles_[k] - particles_[j]);
266 }
267 phi[k] /= static_cast<double>(K);
268 }
269
270 // Apply update + check convergence (max particle move).
271 double max_move = 0.0;
272 for (std::size_t k = 0; k < K; ++k) {
273 const Eigen::VectorXd step = eps * phi[k];
274 particles_[k] += step;
275 max_move = std::max(max_move, step.norm());
276 }
277 ++t_done;
278 if (max_move < conv_tol) break;
279 }
280
281 fitted_ = true;
282 return t_done;
283}
284
285Eigen::VectorXd SteinVariational::uniformWeights() const
286{
287 const std::size_t K = particles_.size();
288 if (K == 0) return {};
289 return Eigen::VectorXd::Constant(K, 1.0 / static_cast<double>(K));
290}
291
292} // namespace laplace
293} // namespace gpr
@ z
Definition Enums.h:28
int fit(GradOracle grad_oracle, int T=30, double eps=0.05, double conv_tol=1e-3)
void initFromCCD(const Eigen::VectorXd &theta_star, const Eigen::MatrixXd &L, double f0=0.0)
Eigen::VectorXd uniformWeights() const
std::function< Eigen::VectorXd(const Eigen::VectorXd &theta)> GradOracle
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