Loading...
Searching...
No Matches
gpr::laplace::SteinVariational Class Reference

#include <gpr/ml/laplace/SteinVariational.h>

Public Types

using GradOracle

Public Member Functions

 SteinVariational ()=default
void initFromCCD (const Eigen::VectorXd &theta_star, const Eigen::MatrixXd &L, double f0=0.0)
int fit (GradOracle grad_oracle, int T=30, double eps=0.05, double conv_tol=1e-3)
int fit (GradOracle grad_oracle, int T, double eps, double conv_tol, const linalg::MpiContext &process_group)
int fit (GradOracle grad_oracle, const SteinVariationalConfig &cfg)
int fit (GradOracle grad_oracle, const SteinVariationalConfig &cfg, const linalg::MpiContext &process_group)
const std::vector< Eigen::VectorXd > & particles () const noexcept
 Particle access (post-fit).
std::size_t numParticles () const noexcept
Eigen::VectorXd uniformWeights () const
bool fitted () const noexcept
void invalidate () noexcept

Detailed Description

Definition at line 92 of file SteinVariational.h.

Member Typedef Documentation

◆ GradOracle

Initial value:
std::function<Eigen::VectorXd(const Eigen::VectorXd& theta)>

Type of the negative-log-marginal-likelihood gradient oracle. Caller provides a callable that returns grad_log_p(theta) = -grad_NLML(theta) + grad_log_prior(theta) at a given theta.

Definition at line 97 of file SteinVariational.h.

Constructor & Destructor Documentation

◆ SteinVariational()

gpr::laplace::SteinVariational::SteinVariational ( )
default

Member Function Documentation

◆ fit() [1/4]

int gpr::laplace::SteinVariational::fit ( GradOracle grad_oracle,
const SteinVariationalConfig & cfg )
inlinenodiscard

Config-struct overload of fit. Forwards to the primitive fit(oracle, T, eps, tol) above; new code should prefer this form so the hardcoded literals don't proliferate at call sites and so future knobs can be added without breaking the caller API.

Definition at line 130 of file SteinVariational.h.

132 {
133 return fit(std::move(grad_oracle), cfg.n_iterations, cfg.step_size,
134 cfg.conv_tol);
135 }
int fit(GradOracle grad_oracle, int T=30, double eps=0.05, double conv_tol=1e-3)

◆ fit() [2/4]

int gpr::laplace::SteinVariational::fit ( GradOracle grad_oracle,
const SteinVariationalConfig & cfg,
const linalg::MpiContext & process_group )
inlinenodiscard

Definition at line 137 of file SteinVariational.h.

140 {
141 return fit(std::move(grad_oracle), cfg.n_iterations, cfg.step_size,
142 cfg.conv_tol, process_group);
143 }

◆ fit() [3/4]

int gpr::laplace::SteinVariational::fit ( GradOracle grad_oracle,
int T,
double eps,
double conv_tol,
const linalg::MpiContext & process_group )
nodiscard

Definition at line 152 of file SteinVariational.cpp.

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}

◆ fit() [4/4]

int gpr::laplace::SteinVariational::fit ( GradOracle grad_oracle,
int T = 30,
double eps = 0.05,
double conv_tol = 1e-3 )
nodiscard

Run T SVGD iterations using the given gradient oracle. step_size eps: 0.01-0.1 typical (Liu & Wang 2016 use 0.1 with AdaGrad scaling; we use a fixed step for simplicity since our gradient magnitudes are already O(1) post-RBF). Returns the iteration count actually performed (<=T if converged early).

Definition at line 145 of file SteinVariational.cpp.

147{
148 return fit(std::move(grad_oracle), T, eps, conv_tol,
149 linalg::BackendContext{}.mpi());
150}

◆ fitted()

bool gpr::laplace::SteinVariational::fitted ( ) const
inlinenodiscardnoexcept

Definition at line 160 of file SteinVariational.h.

161 {
162 return fitted_;
163 }

◆ initFromCCD()

void gpr::laplace::SteinVariational::initFromCCD ( const Eigen::VectorXd & theta_star,
const Eigen::MatrixXd & L,
double f0 = 0.0 )

Initialise K particles from a CCD-style grid centred at theta_star with stretch L (theta_k = theta_star + L * z_k). theta_star: p-dim MAP point. L: p x q z-to-theta stretch matrix (typically U * Lambda^{-1/2} from the LaplaceINLA decomposition; provides a sensible initial spread that the SVGD updates will refine). Updates remain in the affine span of L when q < p. f0: CCD radius (default Rue 2009: sqrt(q + 2)).

Definition at line 69 of file SteinVariational.cpp.

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}
@ z
Definition Enums.h:28

◆ invalidate()

void gpr::laplace::SteinVariational::invalidate ( )
inlinenoexcept

Definition at line 165 of file SteinVariational.h.

166 {
167 fitted_ = false;
168 particles_.clear();
169 parameter_basis_.resize(0, 0);
170 }

◆ numParticles()

std::size_t gpr::laplace::SteinVariational::numParticles ( ) const
inlinenodiscardnoexcept

Definition at line 150 of file SteinVariational.h.

151 {
152 return particles_.size();
153 }

◆ particles()

const std::vector< Eigen::VectorXd > & gpr::laplace::SteinVariational::particles ( ) const
inlinenodiscardnoexcept

Particle access (post-fit).

Definition at line 146 of file SteinVariational.h.

147 {
148 return particles_;
149 }

◆ uniformWeights()

Eigen::VectorXd gpr::laplace::SteinVariational::uniformWeights ( ) const
nodiscard

Uniform mixture weights (1/K each); included for API parity with LaplaceINLA's gridWeights() which returns Rue-weighted CCD points.

Definition at line 285 of file SteinVariational.cpp.

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}

The documentation for this class was generated from the following files: