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
172
173 int t_done = 0;
174 for (int t = 0; t < T; ++t) {
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
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
209
210
211
212
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
247 double h = 1.0;
248 const Eigen::MatrixXd K_mat = rbfKernel(&h);
249 const double inv_h2 = 1.0 / (h * h);
250
251
252
253
254
255
256
257
258
259
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
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}