Loading...
Searching...
No Matches
GaussianProcessRegression.inl
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// Copyright (c) gpridge developers
3// See LICENSE for details.
4
5/*
6 * GaussianProcessRegression.inl
7 *
8 * Created on: 17 Nov 2020
9 * Author: Maxim Masterov
10 * Company: SURFSara
11 */
12
13#ifndef GPR_ML_GAUSSIANPROCESSREGRESSION_INL_
14#define GPR_ML_GAUSSIANPROCESSREGRESSION_INL_
15
16#include <algorithm>
17#include <atomic>
18#include <cstdlib>
19#include <stdexcept>
20#include <type_traits>
21
22#include "PhaseTimers.h"
23#include "gpr/linalg/Backend.h"
25#include "gpr/linalg/ExactSum.h"
28#ifdef GPR_LINALG_SCALAPACK
29#include <mpi.h>
30
32#endif
33
34// Carve-out OpenMP for the local-oracle per-rank gradient regions only.
35// Activates inside applyCovarianceFunction(serial_per_rank=true) and
36// calculateGradientWithCovFunc(serial_per_rank=true) -- both branches do
37// no MPI / ScaLAPACK collective work. The carve-out is gated by the
38// build flag use_openmp_local_oracle which sets GPR_OPENMP_LOCAL_ORACLE
39// and links libgomp. Both GPR_OPENMP_LOCAL_ORACLE and the toolchain
40// macro _OPENMP must be live for the parallel regions to compile in.
41#if defined(GPR_OPENMP_LOCAL_ORACLE) && defined(_OPENMP)
42#include <omp.h>
43#endif
44
45#include <cstring>
46namespace gpr {
47
49 const Eigen::VectorXd& ind_Ddim) const
50{
51 Index_t counter = 1;
52 Index_t first_elt = ind_Ddim(0);
53
54 for (Index_t n = 1; n < ind_Ddim.rows(); ++n) {
55 if (ind_Ddim(n) == first_elt)
56 ++counter;
57 else
58 break;
59 }
60
61 return counter;
62}
63
64template <typename CovFunc>
65GaussianProcessRegression::CovarianceAssemblyOwnership
66GaussianProcessRegression::applyCovarianceFunction(
67 const EigenMatrix& x, const Eigen::VectorXd& ind_Ddim,
68 const Eigen::VectorXd& uDdim, CovFunc& cov_func, EigenMatrix& Ktemp,
69 bool do_reduce, bool serial_per_rank) const
70{
71 if constexpr (std::is_same<typename std::decay<CovFunc>::type,
72 SexpatCF>::value) {
73 if (assembleCompositeJointCovariance(x, ind_Ddim, cov_func, Ktemp)) {
74 return CovarianceAssemblyOwnership::Complete;
75 }
76 }
77
78 FieldMatrixd Kff;
79 std::vector<FieldMatrixd> Kdf;
80 std::vector<FieldMatrixd> Kdf2;
81 std::vector<FieldMatrixd> D;
82 FieldMatrixIdx dims1, dims2;
83 FieldMatrixd x_loc_0, x_loc_1, x_loc_2;
84 Index_t number_of_rep_indices = getNumberOfRepetitiveIndices(ind_Ddim);
85
86 x_loc_0.resize(number_of_rep_indices, (Index_t)x.cols() + 1);
87 x_loc_0.setZero();
88 x_loc_1.resize(number_of_rep_indices, (Index_t)x.cols() + 1);
89 x_loc_1.setZero();
90 x_loc_2.resize(number_of_rep_indices, (Index_t)x.cols() + 1);
91 x_loc_2.setZero();
92
93 dims1.resize(1, 1);
94 dims2.resize(1, 1);
95
96 // One dimensional input
97 if (x.cols() < 2) {
98 // NOTE: This 1D path is correct (matches MATLAB gp_trvar for 1D)
99 // but is untested in integration tests — CuH2 always takes the
100 // multi-dimensional branch.
101 dims1(0, 0) = 0;
102
103 extractCoordinatesByIndex(x, ind_Ddim, 0, x_loc_0);
104 extractCoordinatesByIndex(x, ind_Ddim, 1, x_loc_1);
105
106 cov_func.calculateCovarianceMatrix(x_loc_0, x_loc_0, Kff);
107 cov_func.ginput4(x_loc_1, x_loc_0, dims1, Kdf);
108 cov_func.ginput2(x_loc_1, x_loc_1, dims1, D);
109
110 // Assembles block matrix [Kff Kdf{1}'; Kdf{1} D{1}]
111 Index_t r_kff = Kff.rows(), c_kff = Kff.cols();
112 Index_t r_kdf = Kdf[0].rows(), c_kdf = Kdf[0].cols();
113 Ktemp.resize(r_kff + r_kdf, c_kff + c_kdf);
114 Ktemp.setZero();
115
116 Ktemp.block(0, 0, r_kff, c_kff) = Kff;
117 Ktemp.block(r_kff, 0, r_kdf, c_kdf) = Kdf[0];
118 Ktemp.block(0, c_kff, r_kff, r_kdf) = Kdf[0].transpose();
119 Ktemp.block(r_kff, c_kff, r_kdf, r_kdf) = D[0];
120 } else {
121 FieldMatrixd tmp_cov;
122
123 Ktemp.resize(x.rows(), x.rows());
124 Ktemp.setZero();
125
126#ifdef GPR_LINALG_SCALAPACK
127 auto& _mpi_st = backend().distributed();
128 _mpi_st.initialize();
129 int _mpi_rank = _mpi_st.myrank(), _mpi_np = _mpi_st.nprocs();
130#else
131 const int _mpi_rank = 0, _mpi_np = 1;
132#endif
133 // serial_per_rank: every rank computes every block locally and
134 // skips the Allreduce. Used by the local-only oracle path
135 // (evaluateEnergyAndGradientLocal) where each rank holds a
136 // different theta_k and a collective would deadlock.
137 // ownsBlock: see gpr/ml/BlockOwnership.h (one owner per block
138 // when reducing; all ranks when serial_per_rank).
139 // Block ids are taken with fetch_add. A single thread issues them
140 // in loop order, which is the distributed owner map. A team runs
141 // only when every rank owns every block (one process, or the
142 // local oracle), so a scrambled id still selects the block.
143 std::atomic<int> _mpi_blk{0};
144 const bool assembly_team = serial_per_rank || _mpi_np == 1;
145
146 extractCoordinatesByIndex(x, ind_Ddim, 0, x_loc_0);
147
148 if (ownsBlock(_mpi_blk.fetch_add(1), _mpi_rank, _mpi_np,
149 serial_per_rank)) {
150 cov_func.calculateCovarianceMatrix(x_loc_0, x_loc_0, tmp_cov);
151 Ktemp.block(0, 0, tmp_cov.rows(), tmp_cov.cols()) = tmp_cov;
152 }
153
154 // Parallelism is over the per-pairtype outer index n. Each (n, *)
155 // tuple writes to disjoint blocks of Ktemp via assignBlockToMatrix.
156 // Per-iteration work buffers are firstprivate. On a distributed
157 // reduce the team stays off so the owner ids stay in loop order.
158#if (defined(GPR_OPENMP_LOCAL_ORACLE) || defined(USE_OPENMP)) && \
159 defined(_OPENMP)
160#pragma omp parallel for schedule( \
161 dynamic) if (assembly_team && omp_get_max_threads() > 1 && \
162 uDdim.size() >= 4096) \
163 firstprivate(x_loc_1, x_loc_2, dims1, dims2, Kdf, Kdf2, D) \
164 shared(Ktemp, cov_func, x, ind_Ddim, uDdim, x_loc_0, _mpi_blk)
165#endif
166 for (Index_t n = 0; n < uDdim.size(); ++n) {
167 dims1(0, 0) = uDdim[n];
168 extractCoordinatesByIndex(x, ind_Ddim, uDdim[n], x_loc_1);
169
170 if (ownsBlock(_mpi_blk.fetch_add(1), _mpi_rank, _mpi_np,
171 serial_per_rank)) {
172 cov_func.ginput4(x_loc_1, x_loc_0, dims1, Kdf);
173 cov_func.ginput2(x_loc_1, x_loc_1, dims1, D);
174
175 assignBlockToMatrix(ind_Ddim, ind_Ddim, uDdim[n], 0, Kdf[0],
176 Ktemp);
177 assignBlockToMatrix(ind_Ddim, ind_Ddim, 0, uDdim[n], Kdf[0],
178 Ktemp, true);
179 assignBlockToMatrix(ind_Ddim, ind_Ddim, uDdim[n], uDdim[n],
180 D[0], Ktemp);
181 }
182
183 for (Index_t m = n + 1; m < uDdim.size(); ++m) {
184 if (ownsBlock(_mpi_blk.fetch_add(1), _mpi_rank, _mpi_np,
185 serial_per_rank)) {
186 dims2(0, 0) = uDdim[m];
187 extractCoordinatesByIndex(x, ind_Ddim, uDdim[m], x_loc_2);
188 cov_func.ginput3(x_loc_1, x_loc_2, dims1, dims2, Kdf2);
189
190 assignBlockToMatrix(ind_Ddim, ind_Ddim, uDdim[n], uDdim[m],
191 Kdf2[0], Ktemp);
192 assignBlockToMatrix(ind_Ddim, ind_Ddim, uDdim[m], uDdim[n],
193 Kdf2[0], Ktemp, true);
194 }
195 }
196 }
197
198#ifdef GPR_LINALG_SCALAPACK
199 // One owner per (block, transpose-partner) pair: disjoint
200 // support, so the Allreduce is exact (see disjoint_sum_bcast).
201 if (!serial_per_rank && _mpi_np > 1) {
202 if (!do_reduce) return CovarianceAssemblyOwnership::Disjoint;
203 backend().disjoint_sum_bcast(Ktemp.data(),
204 static_cast<int>(Ktemp.size()));
205 }
206#else
207 (void)do_reduce;
208#endif
209 }
210 return CovarianceAssemblyOwnership::Complete;
211}
212
213template <typename CovFunc>
214void GaussianProcessRegression::applyCrossCovarianceFunction(
215 const EigenMatrix& x1, const EigenMatrix& x2,
216 const Eigen::VectorXd& ind_Ddim, const Eigen::VectorXd& uDdim,
217 const Eigen::VectorXd& ind_Ddim2, const Eigen::VectorXd& uDdim2,
218 CovFunc& cov_func, EigenMatrix& Ktemp, bool do_reduce) const
219{
220 if constexpr (std::is_same<typename std::decay<CovFunc>::type,
221 SexpatCF>::value) {
222 if (assembleCompositeJointCrossCovariance(x1, x2, ind_Ddim, ind_Ddim2,
223 cov_func, Ktemp)) {
224 return;
225 }
226 }
227
228#ifndef GPR_LINALG_SCALAPACK
229 (void)do_reduce;
230#endif
231 // PERF: For both sexpat and const functions the same matrices x1/x2 and
232 // vectors ind_Ddim/ind_Ddim2 are passed. The coordinate extraction is
233 // therefore redundant and repeated inside the loop. Optimization possible:
234 // 1. Cache extracted coordinates across covariance function calls
235 // 2. Reuse allocations for x_loc buffers
236 // 3. Arrange memory for better cache locality
237
238 FieldMatrixd x1_loc_0, x2_loc_0, x1_loc_1, x2_loc_1;
239 FieldMatrixd C_temp;
240 FieldMatrixIdx dims1, dims2;
241 std::vector<FieldMatrixd> Kdf(1), Kdf2(1);
242
243 Ktemp.resize(x1.rows(), x2.rows());
244 Ktemp.setZero();
245 dims1.resize(1, 1);
246 dims2.resize(1, 1);
247
248 /* Read-only maps avoid copying the index vectors. */
249 Eigen::Map<const Eigen::ArrayXd> ind_Ddim_copy(ind_Ddim.data(),
250 ind_Ddim.size()),
251 ind_Ddim2_copy(ind_Ddim2.data(), ind_Ddim2.size());
252
253#ifdef GPR_LINALG_SCALAPACK
254 auto& _mpi_st = backend().distributed();
255 _mpi_st.initialize();
256 int _mpi_rank = _mpi_st.myrank(), _mpi_np = _mpi_st.nprocs();
257#else
258 const int _mpi_rank = 0, _mpi_np = 1;
259#endif
260 int _mpi_blk = 0;
261
262 x1_loc_0.resize((Index_t)(ind_Ddim_copy == 0).count(),
263 (Index_t)x1.cols() + 1);
264 x1_loc_0.setZero();
265 x2_loc_0.resize((Index_t)(ind_Ddim2_copy == 0).count(),
266 (Index_t)x2.cols() + 1);
267 x2_loc_0.setZero();
268
269 extractCoordinatesByIndex(x1, ind_Ddim, 0, x1_loc_0);
270 extractCoordinatesByIndex(x2, ind_Ddim2, 0, x2_loc_0);
271
272 // % Non-derivative observation non-derivative prediction
273 if ((ind_Ddim_copy == 0).count() > 0 && (ind_Ddim2_copy == 0).count() > 0) {
274 if (ownsBlockIfReduce(_mpi_blk++, _mpi_rank, _mpi_np, do_reduce)) {
275 cov_func.calculateCovarianceMatrix(x1_loc_0, x2_loc_0, C_temp);
276 assignBlockToMatrix(ind_Ddim, ind_Ddim2, 0, 0, C_temp, Ktemp);
277 }
278 }
279
280 // % Non-derivative observation, derivative prediction
281 if ((ind_Ddim_copy == 0).count() > 0) {
282 for (Index_t i = 0; i < uDdim2.size(); ++i) {
283 if (ownsBlockIfReduce(_mpi_blk++, _mpi_rank, _mpi_np, do_reduce)) {
284 dims2(0, 0) = uDdim2[i];
285 x2_loc_1.resize((Index_t)(ind_Ddim2_copy == uDdim2[i]).count(),
286 (Index_t)x2.cols() + 1);
287 x2_loc_1.setZero();
288 extractCoordinatesByIndex(x2, ind_Ddim2, uDdim2[i], x2_loc_1);
289 cov_func.ginput4(x2_loc_1, x1_loc_0, dims2, Kdf);
290 assignBlockToMatrix(ind_Ddim, ind_Ddim2, 0, uDdim2[i], Kdf[0],
291 Ktemp, true);
292 }
293 }
294 }
295
296 // % Derivative observation non-derivative prediction
297 if ((ind_Ddim2_copy == 0).count() > 0) {
298 for (Index_t i = 0; i < uDdim.size(); ++i) {
299 if (ownsBlockIfReduce(_mpi_blk++, _mpi_rank, _mpi_np, do_reduce)) {
300 dims1(0, 0) = uDdim[i];
301 x1_loc_1.resize((Index_t)(ind_Ddim_copy == uDdim[i]).count(),
302 (Index_t)x1.cols() + 1);
303 x1_loc_1.setZero();
304 extractCoordinatesByIndex(x1, ind_Ddim, uDdim[i], x1_loc_1);
305 cov_func.ginput4(x1_loc_1, x2_loc_0, dims1, Kdf);
306 assignBlockToMatrix(ind_Ddim, ind_Ddim2, uDdim[i], 0, Kdf[0],
307 Ktemp);
308 }
309 }
310 }
311
312 // % Derivative observation, derivative prediction
313 for (Index_t i = 0; i < uDdim.size(); ++i) {
314 dims1(0, 0) = uDdim[i];
315 x1_loc_1.resize((Index_t)(ind_Ddim_copy == uDdim[i]).count(),
316 (Index_t)x1.cols() + 1);
317 x1_loc_1.setZero();
318 extractCoordinatesByIndex(x1, ind_Ddim, uDdim[i], x1_loc_1);
319 for (Index_t j = 0; j < uDdim2.size(); ++j) {
320 if (ownsBlockIfReduce(_mpi_blk++, _mpi_rank, _mpi_np, do_reduce)) {
321 dims2(0, 0) = uDdim2[j];
322 x2_loc_1.resize((Index_t)(ind_Ddim2_copy == uDdim2[j]).count(),
323 (Index_t)x2.cols() + 1);
324 x2_loc_1.setZero();
325 extractCoordinatesByIndex(x2, ind_Ddim2, uDdim2[j], x2_loc_1);
326 if (uDdim[i] == uDdim2[j]) {
327 cov_func.ginput2(x1_loc_1, x2_loc_1, dims1, Kdf2);
328 } else {
329 cov_func.ginput3(x1_loc_1, x2_loc_1, dims1, dims2, Kdf2);
330 }
331 assignBlockToMatrix(ind_Ddim, ind_Ddim2, uDdim[i], uDdim2[j],
332 Kdf2[0], Ktemp);
333 }
334 }
335 }
336
337#ifdef GPR_LINALG_SCALAPACK
338 // One owner per block: disjoint support, exact under Allreduce
339 // (see disjoint_sum_bcast).
340 if (do_reduce && _mpi_np > 1)
341 backend().disjoint_sum_bcast(Ktemp.data(),
342 static_cast<int>(Ktemp.size()));
343#endif
344}
345
346template <typename CovFunc>
348 const EigenMatrix& x1, const EigenMatrix& x2,
349 const Eigen::VectorXd& ind_Ddim, const Eigen::VectorXd& uDdim,
350 const Eigen::VectorXd& ind_Ddim2, const Eigen::VectorXd& uDdim2,
351 CovFunc& cov_func, const Eigen::VectorXd& weights, Eigen::VectorXd& output,
352 bool do_reduce, bool select_prediction_product) const
353{
354 const auto product_mode = select_prediction_product
357 const auto contract = [&](const auto& matrix,
358 const Eigen::VectorXd& coefficients) {
359 Eigen::VectorXd result(matrix.cols());
360 for (Eigen::Index col = 0; col < matrix.cols(); ++col) {
361 const Eigen::VectorXd column = matrix.col(col);
362 result(col) = linalg::evaluateStoredProduct(
363 column.data(), coefficients.data(),
364 static_cast<int>(coefficients.size()), product_mode);
365 }
366 return result;
367 };
368 if constexpr (std::is_same<typename std::decay<CovFunc>::type,
369 SexpatCF>::value) {
370 EigenMatrix joint_covariance;
371 if (assembleCompositeJointCrossCovariance(x1, x2, ind_Ddim, ind_Ddim2,
372 cov_func, joint_covariance)) {
373 if (weights.size() != joint_covariance.rows()) {
374 throw std::invalid_argument(
375 "manifold covariance weights do not match joint rows");
376 }
377 output = contract(joint_covariance, weights);
378 return;
379 }
380 }
381
382 FieldMatrixd x1_loc_0, x2_loc_0, x1_loc_1, x2_loc_1;
383 FieldMatrixd C_temp;
384 FieldMatrixIdx dims1, dims2;
385 std::vector<FieldMatrixd> Kdf(1), Kdf2(1);
386
387 const detail::ObservationChannelLayout training_channels(ind_Ddim);
388 const detail::ObservationChannelLayout prediction_channels(ind_Ddim2);
389 if (!training_channels.valid() || !prediction_channels.valid() ||
390 ind_Ddim.size() != x1.rows() || ind_Ddim2.size() != x2.rows() ||
391 weights.size() != x1.rows())
392 throw std::invalid_argument(
393 "cross covariance channels have invalid shape");
394 Eigen::Index max_prediction_rows = prediction_channels.block(0).count;
395 for (Eigen::Index channel = 0; channel < uDdim2.size(); ++channel)
396 max_prediction_rows = std::max(
397 max_prediction_rows,
398 prediction_channels.block(static_cast<Index_t>(uDdim2(channel)))
399 .count);
400
401 output.resize(x2.rows());
402 output.setZero();
403 dims1.resize(1, 1);
404 dims2.resize(1, 1);
405
406 const Index_t total_blocks =
407 1 + static_cast<Index_t>(uDdim2.size()) +
408 static_cast<Index_t>(uDdim.size()) +
409 static_cast<Index_t>(uDdim.size() * uDdim2.size());
410 Eigen::MatrixXd block_contribs =
411 Eigen::MatrixXd::Zero(total_blocks, max_prediction_rows);
412 std::vector<Index_t> block_cols(static_cast<size_t>(total_blocks), 0);
413 std::vector<Index_t> block_sizes(static_cast<size_t>(total_blocks), 0);
414
415 auto assign_block_contrib = [&](const Index_t row_val,
416 const Index_t col_val,
417 const FieldMatrixd& field,
418 const Index_t block_idx,
419 const bool transpose_field = false) {
420 const auto row_block = training_channels.block(row_val);
421 const auto col_block = prediction_channels.block(col_val);
422 const Eigen::Map<const Eigen::VectorXd> weight_block(
423 weights.data() + row_block.start, row_block.count);
424
425 const auto matrix_block = !transpose_field ? field : field.transpose();
426 block_contribs.row(block_idx).head(col_block.count) =
427 contract(matrix_block, weight_block).transpose();
428 block_cols[static_cast<size_t>(block_idx)] = col_block.start;
429 block_sizes[static_cast<size_t>(block_idx)] = col_block.count;
430 };
431
432 Eigen::Map<const Eigen::ArrayXd> ind_Ddim_copy(ind_Ddim.data(),
433 ind_Ddim.size());
434 Eigen::Map<const Eigen::ArrayXd> ind_Ddim2_copy(ind_Ddim2.data(),
435 ind_Ddim2.size());
436
437#ifdef GPR_LINALG_SCALAPACK
438 auto& _mpi_st = backend().distributed();
439 _mpi_st.initialize();
440 const Index_t mpi_rank = static_cast<Index_t>(_mpi_st.myrank());
441 const Index_t mpi_np = static_cast<Index_t>(_mpi_st.nprocs());
442 const auto owns_block = [&](const Index_t block_idx) {
443 return !do_reduce || block_idx % mpi_np == mpi_rank;
444 };
445#else
446 (void)do_reduce;
447 const auto owns_block = [&](const Index_t) { return true; };
448#endif
449
450 x1_loc_0.resize((Index_t)(ind_Ddim_copy == 0).count(),
451 (Index_t)x1.cols() + 1);
452 x1_loc_0.setZero();
453 x2_loc_0.resize((Index_t)(ind_Ddim2_copy == 0).count(),
454 (Index_t)x2.cols() + 1);
455 x2_loc_0.setZero();
456
457 extractCoordinatesByIndex(x1, ind_Ddim, 0, x1_loc_0);
458 extractCoordinatesByIndex(x2, ind_Ddim2, 0, x2_loc_0);
459
460 Index_t block_idx = 0;
461 if ((ind_Ddim_copy == 0).count() > 0 && (ind_Ddim2_copy == 0).count() > 0) {
462 block_cols[static_cast<size_t>(block_idx)] = 0;
463 block_sizes[static_cast<size_t>(block_idx)] =
464 prediction_channels.block(0).count;
465 if (owns_block(block_idx)) {
466 cov_func.calculateCovarianceMatrix(x1_loc_0, x2_loc_0, C_temp);
467 assign_block_contrib(0, 0, C_temp, block_idx);
468 }
469 }
470 ++block_idx;
471
472 if ((ind_Ddim_copy == 0).count() > 0) {
473 for (Index_t i = 0; i < uDdim2.size(); ++i, ++block_idx) {
474 const Index_t pred_block = static_cast<Index_t>(uDdim2[i]);
475 block_cols[static_cast<size_t>(block_idx)] =
476 prediction_channels.block(pred_block).start;
477 block_sizes[static_cast<size_t>(block_idx)] =
478 prediction_channels.block(pred_block).count;
479 if (!owns_block(block_idx)) continue;
480
481 dims2(0, 0) = pred_block;
482 x2_loc_1.resize((Index_t)(ind_Ddim2_copy == pred_block).count(),
483 (Index_t)x2.cols() + 1);
484 x2_loc_1.setZero();
485 extractCoordinatesByIndex(x2, ind_Ddim2, pred_block, x2_loc_1);
486 cov_func.ginput4(x2_loc_1, x1_loc_0, dims2, Kdf);
487 assign_block_contrib(0, pred_block, Kdf[0], block_idx, true);
488 }
489 } else {
490 block_idx += static_cast<Index_t>(uDdim2.size());
491 }
492
493 if ((ind_Ddim2_copy == 0).count() > 0) {
494 for (Index_t i = 0; i < uDdim.size(); ++i, ++block_idx) {
495 const Index_t obs_block = static_cast<Index_t>(uDdim[i]);
496 block_cols[static_cast<size_t>(block_idx)] = 0;
497 block_sizes[static_cast<size_t>(block_idx)] =
498 prediction_channels.block(0).count;
499 if (!owns_block(block_idx)) continue;
500
501 dims1(0, 0) = obs_block;
502 x1_loc_1.resize((Index_t)(ind_Ddim_copy == obs_block).count(),
503 (Index_t)x1.cols() + 1);
504 x1_loc_1.setZero();
505 extractCoordinatesByIndex(x1, ind_Ddim, obs_block, x1_loc_1);
506 cov_func.ginput4(x1_loc_1, x2_loc_0, dims1, Kdf);
507 assign_block_contrib(obs_block, 0, Kdf[0], block_idx);
508 }
509 } else {
510 block_idx += static_cast<Index_t>(uDdim.size());
511 }
512
513 for (Index_t i = 0; i < uDdim.size(); ++i) {
514 const Index_t obs_block = static_cast<Index_t>(uDdim[i]);
515 dims1(0, 0) = obs_block;
516 x1_loc_1.resize((Index_t)(ind_Ddim_copy == obs_block).count(),
517 (Index_t)x1.cols() + 1);
518 x1_loc_1.setZero();
519 extractCoordinatesByIndex(x1, ind_Ddim, obs_block, x1_loc_1);
520 for (Index_t j = 0; j < uDdim2.size(); ++j, ++block_idx) {
521 const Index_t pred_block = static_cast<Index_t>(uDdim2[j]);
522 block_cols[static_cast<size_t>(block_idx)] =
523 prediction_channels.block(pred_block).start;
524 block_sizes[static_cast<size_t>(block_idx)] =
525 prediction_channels.block(pred_block).count;
526 if (!owns_block(block_idx)) continue;
527
528 dims2(0, 0) = pred_block;
529 x2_loc_1.resize((Index_t)(ind_Ddim2_copy == pred_block).count(),
530 (Index_t)x2.cols() + 1);
531 x2_loc_1.setZero();
532 extractCoordinatesByIndex(x2, ind_Ddim2, pred_block, x2_loc_1);
533 if (obs_block == pred_block) {
534 cov_func.ginput2(x1_loc_1, x2_loc_1, dims1, Kdf2);
535 } else {
536 cov_func.ginput3(x1_loc_1, x2_loc_1, dims1, dims2, Kdf2);
537 }
538 assign_block_contrib(obs_block, pred_block, Kdf2[0], block_idx);
539 }
540 }
541
542#ifdef GPR_LINALG_SCALAPACK
543 if (do_reduce && mpi_np > 1) {
544 // Each block_contribs row is written by exactly one owning
545 // rank: disjoint support, exact under Allreduce (see
546 // disjoint_sum_bcast).
547 backend().disjoint_sum_bcast(block_contribs.data(),
548 static_cast<int>(block_contribs.size()));
549 }
550 // disjoint_sum_bcast makes block_contribs bit-identical on every rank.
551 // block_cols is populated unconditionally per-rank at the top of the
552 // block loop, so the output assembles identically without an extra
553 // trailing MPI_Bcast(output) round-trip.
554#endif
555 for (Index_t idx = 0; idx < total_blocks; ++idx) {
556 const Index_t col_start = block_cols[static_cast<size_t>(idx)];
557 const Index_t count = block_sizes[static_cast<size_t>(idx)];
558 output.segment(col_start, count).noalias() +=
559 block_contribs.row(idx).head(count).transpose();
560 }
561}
562
563template <typename CovFunc>
564void GaussianProcessRegression::calculateGradientWithCovFunc(
565 const EigenMatrix& x, const Eigen::VectorXd& ind_Ddim,
566 const Eigen::VectorXd& uDdim, const Eigen::VectorXd& b,
567 const EigenMatrix& invC, CovFunc& cov_func, FieldMatrixd& gdata,
568 FieldMatrixd& gprior, bool serial_per_rank,
569 const TrainingKernelGeometry* training_geom,
570 const EigenMatrix* trace_factor,
571 const detail::RigidDeflationState* deflation_override)
572{
573 const detail::RigidDeflationState& active_deflation =
574 deflation_override != nullptr ? *deflation_override : rigid_deflation_;
577 const double diagonal_nugget = kernelNuggetCoefficient(x.rows());
578#ifdef GPR_LINALG_SCALAPACK
579 if (!serial_per_rank) (void)invC;
580#else
581 (void)serial_per_rank;
582#endif
583 if constexpr (std::is_same_v<std::decay_t<CovFunc>, SexpatCF>) {
584 if (cov_func.usesManifoldChart()) {
585 // Composite (charted) covariance: exact marginal-likelihood
586 // gradient dNLML/dtheta_j = 1/2 tr(C^-1 dC_j) - 1/2 b^T dC_j b
587 // from the operator-algebra derivative tensors. invC and b are
588 // the dense whole-rank objects (HS-SVD is off under a chart).
589 std::vector<EigenMatrix> dC;
591 cov_func, dC)) {
592 throw std::logic_error(
593 "charted Sexpat gradient requires the composite "
594 "derivative assembly");
595 }
596 const Eigen::Index n_joint = dC.front().rows();
597 // Solve tr(K^{-1} dC) against the factor. A supplied inverse is
598 // only the fallback when no factor is in the derivative's order.
599 EigenMatrix chart_factor;
600 bool chart_factor_permuted = false;
601 bool have_chart_factor = false;
602 if (trace_factor != nullptr && trace_factor->rows() == n_joint &&
603 trace_factor->cols() == n_joint) {
604 chart_factor = *trace_factor;
605 chart_factor_permuted = true;
606 have_chart_factor = true;
607 }
608#ifdef GPR_LINALG_SCALAPACK
609 else if (const EigenMatrix L_whole =
610 wholeRankCachedCholeskyFactor();
611 L_whole.rows() == n_joint && L_whole.cols() == n_joint) {
612 chart_factor = L_whole;
613 chart_factor_permuted = true;
614 have_chart_factor = true;
615 }
616#endif
617 else if (
618#ifndef GPR_LINALG_CHOLMOD
619 !(invC.rows() == n_joint && invC.cols() == n_joint)
620#else
621 // CHOLMOD has no inverse fallback. A missing factor used to
622 // leave the trace at zero. Factor the training covariance
623 // in observation order instead.
624 true
625#endif
626 ) {
627 EigenMatrix C_chart;
628 evaluateTrainingCovarianceMatrix(x, ind_Ddim, C_chart,
629 /*serial_per_rank=*/true);
630 if (jitter_sigma2 > 0.0)
631 C_chart.diagonal().array() += jitter_sigma2;
632 if (C_chart.rows() != n_joint || C_chart.cols() != n_joint) {
633 throw std::logic_error(
634 "charted Sexpat gradient: training covariance and "
635 "derivative tensor shapes disagree (C=" +
636 std::to_string(C_chart.rows()) +
637 ", dC=" + std::to_string(n_joint) + ")");
638 }
639#ifdef GPR_LINALG_CHOLMOD
640 EigenMatrix factored;
641 if (!linalg::cholesky(C_chart, factored)) {
642 throw std::runtime_error(
643 "charted Sexpat gradient: training covariance is "
644 "not positive definite");
645 }
646 chart_factor = std::move(factored);
647#else
648 Eigen::LLT<EigenMatrix> llt(C_chart);
649 if (llt.info() != Eigen::Success) {
650 throw std::runtime_error(
651 "charted Sexpat gradient: training covariance is "
652 "not positive definite");
653 }
654 chart_factor = llt.matrixL();
655#endif
656 have_chart_factor = true;
657 }
658 Eigen::VectorXd alpha_chart = b;
659#ifdef GPR_LINALG_SCALAPACK
660 if (!serial_per_rank && hasTrainingPermutation())
661 alpha_chart = unpermuteTrainingVector(b);
662#endif
663 if (alpha_chart.size() != n_joint) {
664 throw std::logic_error(
665 "charted Sexpat gradient: posterior weights and "
666 "derivative tensor shapes disagree (alpha=" +
667 std::to_string(alpha_chart.size()) +
668 ", dC=" + std::to_string(n_joint) + ")");
669 }
670 gdata.resize(1, static_cast<Index_t>(dC.size()));
671 for (std::size_t j = 0; j < dC.size(); ++j) {
672 double trace_term = 0.0;
673 if (have_chart_factor) {
674 EigenMatrix rhs = dC[j];
675 if (chart_factor_permuted && hasTrainingPermutation() &&
676 static_cast<Eigen::Index>(
677 training_permutation_.perm.size()) == n_joint)
679 dC[j], training_permutation_);
680 trace_term = linalg::trace_solve_product(chart_factor, rhs);
681 }
682#ifndef GPR_LINALG_CHOLMOD
683 else {
684 trace_term = invC.cwiseProduct(dC[j]).sum();
685 }
686#endif
687 const double quad_term = alpha_chart.dot(dC[j] * alpha_chart);
688 *(gdata.data() + j) = 0.5 * (trace_term - quad_term);
689 }
690 FieldMatrixd gprior_chart = cov_func.calculateLogPriorGradient();
691 gprior_chart *= -1.;
692 gpr::field::appendRows(gprior, gprior_chart);
693 return;
694 }
695 }
696 std::vector<FieldMatrixd> DKffa;
697 FieldMatrixd x_loc_0, x_loc_1, x_loc_2;
698 FieldMatrixIdx dims1, dims2;
699 FieldMatrixd gprior_cf;
700 const detail::ObservationChannelLayout channel_layout(ind_Ddim);
701 if (!channel_layout.valid())
702 throw std::invalid_argument(
703 "observation channels must be grouped in order");
704 Index_t number_of_rep_indices = getNumberOfRepetitiveIndices(ind_Ddim);
705
706 // NOTE: ind_Ddim encodes pairtype-based repetitive indices; the block
707 // size per index equals number_of_rep_indices (atoms per image).
708 x_loc_0.resize(number_of_rep_indices, (Index_t)x.cols() + 1);
709 x_loc_0.setZero();
710 x_loc_1.resize(number_of_rep_indices, (Index_t)x.cols() + 1);
711 x_loc_1.setZero();
712 x_loc_2.resize(number_of_rep_indices, (Index_t)x.cols() + 1);
713 x_loc_2.setZero();
714
715 dims1.resize(1, 1);
716 dims2.resize(1, 1);
717
718 gprior_cf = cov_func.calculateLogPriorGradient();
719 gprior_cf *= -1.;
720
721 std::vector<Eigen::Index> selected_parameters;
722 const std::vector<Eigen::Index>* parameter_indices = nullptr;
723 if constexpr (std::is_same_v<std::decay_t<CovFunc>, SexpatCF>) {
724 const auto& mask = scg_opt_settings.active_parameters;
725 const Eigen::Index count = cov_func.combineParameters().size();
726 if (gprior.size() == 0 && gprior_cf.size() == count &&
727 mask.size() >= static_cast<std::size_t>(count)) {
728 for (Eigen::Index i = 0; i < count; ++i)
729 if (mask[static_cast<std::size_t>(i)])
730 selected_parameters.push_back(i);
731 if (selected_parameters.size() < static_cast<std::size_t>(count)) {
732 if (selected_parameters.empty()) {
733 gdata.setZero(1, count);
734 gpr::field::appendRows(gprior, gprior_cf);
735 return;
736 }
737 parameter_indices = &selected_parameters;
738 }
739 }
740 }
741 const auto select_live_gradient_blocks =
742 [&](std::vector<FieldMatrixd>& blocks) {
743 if (parameter_indices == nullptr) return;
744 std::vector<FieldMatrixd> selected;
745 selected.reserve(parameter_indices->size());
746 for (const Eigen::Index index: *parameter_indices)
747 selected.push_back(std::move(blocks.at(index)));
748 blocks = std::move(selected);
749 };
750
751 extractCoordinatesByIndex(x, ind_Ddim, 0, x_loc_0);
752
753 // dK-from-geometry fast path. Active only for SexpatCF and only when the
754 // caller supplied a training geometry for this objective evaluation.
755 // shared_kernel is built once per evaluateGradient call and reused across
756 // all per-block dK computations below. Rank-local callers supply alpha
757 // and the inverse in the full geometry's observation-channel ordering.
758 // Other covariance functions and incompatible geometry use the live
759 // calculateGradOfCovMatrix* calls.
760 bool grad_geom_active = false;
761 Eigen::VectorXd grad_geom_theta;
762 FieldMatrixd grad_geom_shared_kernel;
763 [[maybe_unused]] const TrainingKernelGeometry* grad_geom_handle = nullptr;
764 const auto record_live_gradient_geometry = [&]() {
765 if constexpr (std::is_same_v<std::decay_t<CovFunc>, SexpatCF>) {
766 if (training_geom != nullptr && training_geom->streamed) {
767 std::atomic_ref(
768 training_geom->gradient_live_geometry_builds_for_testing)
769 .fetch_add(1, std::memory_order_relaxed);
770 }
771 }
772 };
773 const auto resolve_gradient_geometry =
774 [&](Index_t block_n, Index_t block_m,
775 SexpatCF::CrossBlockGeometry& scratch)
776 -> const SexpatCF::CrossBlockGeometry* {
777 if constexpr (std::is_same_v<std::decay_t<CovFunc>, SexpatCF>) {
778 if (grad_geom_handle != nullptr) {
779 const auto* block = grad_geom_handle->find(block_n, block_m);
780 if (block != nullptr) {
782 cov_func, *grad_geom_handle, *block, scratch);
783 }
784 }
785 }
786 return nullptr;
787 };
788 if constexpr (std::is_same_v<std::decay_t<CovFunc>, SexpatCF>) {
789 if (training_geom != nullptr && training_geom->valid &&
790 training_geom->shared_coordinates && training_geom->n == x.rows()) {
791 grad_geom_handle = training_geom;
792 grad_geom_theta = cov_func.combineParameters();
793 if (cov_func.buildSharedKernel(
794 grad_geom_handle->shared_distance_neg_per_pt,
795 grad_geom_theta, grad_geom_shared_kernel)) {
796 grad_geom_active = true;
797 }
798 }
799 }
800
801#ifdef GPR_LINALG_SCALAPACK
802 bool use_observation_tile_fast_path = false;
803 if (!serial_per_rank && hasTrainingPermutation()) {
804 auto& st_for_gradient_layout = backend().distributed();
805 st_for_gradient_layout.initialize();
806 const Index_t expected_tile_size =
807 static_cast<Index_t>(channel_layout.channelCount());
808 use_observation_tile_fast_path =
809 channel_layout.rowsPerChannel() > 0 &&
810 static_cast<Index_t>(st_for_gradient_layout.block_size()) ==
811 expected_tile_size;
812 }
813 if (use_observation_tile_fast_path) {
814 FieldMatrixd x_loc_probe_1(1, (Index_t)x.cols() + 1);
815 FieldMatrixd x_loc_probe_2(1, (Index_t)x.cols() + 1);
816 x_loc_probe_1.setZero();
817 x_loc_probe_2.setZero();
818 x_loc_probe_1.block(0, 0, 1, x.cols()) = x.block(0, 0, 1, x.cols());
819 x_loc_probe_2 = x_loc_probe_1;
820 // n_hp probe: the distributed path only needs DKffa.size() to size
821 // downstream buffers; the actual Kff dK values get re-computed via
822 // the geometry path further below when grad_geom_active.
823 if (parameter_indices != nullptr && grad_geom_active) {
824 DKffa.resize(parameter_indices->size());
825 } else {
826 cov_func.calculateGradOfCovMatrix(x_loc_probe_1, x_loc_probe_2,
827 DKffa);
828 select_live_gradient_blocks(DKffa);
829 }
830 } else
831#endif
832 if constexpr (std::is_same_v<std::decay_t<CovFunc>, SexpatCF>) {
833 bool produced = false;
834 if (grad_geom_active) {
835 produced = cov_func.calculateGradOfCovMatrixFromGeometry(
836 grad_geom_shared_kernel,
837 grad_geom_handle->shared_distance_neg_per_pt, grad_geom_theta,
838 DKffa, parameter_indices);
839 }
840 if (!produced) {
841 cov_func.calculateGradOfCovMatrix(x_loc_0, x_loc_0, DKffa);
842 select_live_gradient_blocks(DKffa);
843 }
844 } else {
845 cov_func.calculateGradOfCovMatrix(x_loc_0, x_loc_0, DKffa);
846 select_live_gradient_blocks(DKffa);
847 }
848
849 if (DKffa.size() != 0) {
850 gdata.resize(1, (Index_t)DKffa.size());
851
852#ifdef GPR_LINALG_SCALAPACK
853 auto& _mpi_st = backend().distributed();
854 if (!serial_per_rank) _mpi_st.initialize();
855 int _mpi_np = serial_per_rank ? 1 : _mpi_st.nprocs();
856#else
857#endif
858
859 const Index_t n_hp = static_cast<Index_t>(DKffa.size());
860 if (n_hp == 0) {
861 // A covariance function without hyperparameter derivative
862 // blocks (the constant kernel) contributes only its prior
863 // gradient; walking every channel-block pair for it doubled
864 // the block traffic of each gradient.
865 gpr::field::appendRows(gprior, gprior_cf);
866 return;
867 }
868 std::vector<Eigen::Index> pair_derivative_groups;
869 std::vector<Eigen::Index> pair_parameter_indices(
870 static_cast<std::size_t>(n_hp));
871 for (Index_t elt = 0; elt < n_hp; ++elt)
872 pair_parameter_indices[static_cast<std::size_t>(elt)] =
873 parameter_indices != nullptr
874 ? (*parameter_indices)[static_cast<std::size_t>(elt)]
875 : static_cast<Eigen::Index>(elt);
876 if constexpr (std::is_same_v<std::decay_t<CovFunc>, SexpatCF>) {
877 const Eigen::Index length_count = grad_geom_theta.size() - 1;
878 if (tied_length_scale_gradient_ && grad_geom_active &&
879 lengthScaleTiesActive(length_count)) {
880 std::vector<bool> selected(
881 static_cast<std::size_t>(length_count), false);
882 for (const Eigen::Index p: pair_parameter_indices)
883 if (p > 0) selected[static_cast<std::size_t>(p - 1)] = true;
884 std::vector<Eigen::Index> leader_groups(
885 static_cast<std::size_t>(length_count), -1);
886 pair_derivative_groups.resize(
887 static_cast<std::size_t>(length_count));
888 Eigen::Index group_count = 0;
889 Eigen::Index held_group = -1;
890 for (Eigen::Index t = 0; t < length_count; ++t) {
891 const auto index = static_cast<std::size_t>(t);
892 // A masked member still contributes to K, but cannot
893 // contribute to a selected group's derivative sum.
894 Eigen::Index& group =
895 selected[index]
896 ? leader_groups[static_cast<std::size_t>(
897 length_scale_ties_.leader[index])]
898 : held_group;
899 if (group < 0) group = group_count++;
900 pair_derivative_groups[index] = group;
901 }
902 if (group_count < length_count) {
903 std::vector<bool> represented(
904 static_cast<std::size_t>(group_count), false);
905 for (Eigen::Index& p: pair_parameter_indices) {
906 if (p == 0) continue;
907 const Eigen::Index group =
908 pair_derivative_groups[static_cast<std::size_t>(p -
909 1)];
910 const auto index = static_cast<std::size_t>(group);
911 p = represented[index] ? -1 : 1 + group;
912 represented[index] = true;
913 }
914 } else {
915 pair_derivative_groups.clear();
916 }
917 }
918 }
919 // Only the trace and tile nugget terms are scattered by group.
920 // The independent alpha-K contraction and prior retain fine
921 // coordinates; the tied wrapper sums all three terms once.
922 std::vector<double> Cdl(n_hp, 0.0);
923 std::vector<double> Bdl(n_hp, 0.0);
924 std::vector<linalg::ExactSum> Bex(n_hp);
925#ifdef GPR_LINALG_SCALAPACK
926 // Owned entries of the distributed trace and quadratic terms enter
927 // exact accumulators, so their reduced values do not depend on the
928 // process grid that assigned the entries.
929 std::vector<linalg::ExactSum> Cdist(n_hp), Bdist(n_hp);
930#endif
931 const Index_t Ddim_rows = (Index_t)ind_Ddim.rows();
932 const Index_t num_rep =
933 static_cast<Index_t>(channel_layout.rowsPerChannel());
934 std::vector<double> alpha_k_quadratic;
935 if constexpr (std::is_same_v<std::decay_t<CovFunc>, SexpatCF>) {
936 const Eigen::Index physical_dimensions =
937 3 * cov_func.getConfInfo().atoms_mov.type.size();
938 if (channel_layout.completeCartesian(physical_dimensions) &&
939 channel_layout.repeatsCoordinates(x, physical_dimensions) &&
940 num_rep > 0 && b.rows() == Ddim_rows) {
941 Eigen::VectorXd alpha_for_alpha_k = b;
942#ifdef GPR_LINALG_SCALAPACK
943 if (!serial_per_rank && hasTrainingPermutation())
944 alpha_for_alpha_k = unpermuteTrainingVector(b);
945#endif
946 Eigen::VectorXd alpha_k_quad = Eigen::VectorXd::Zero(
947 parameter_indices != nullptr
948 ? cov_func.combineParameters().size()
949 : static_cast<Eigen::Index>(n_hp));
950 const EigenMatrix x_train_pts = x.topRows(num_rep);
951 const Eigen::VectorXd alpha_E = alpha_for_alpha_k.head(num_rep);
952 const auto process_group = mpiContext();
953 cov_func.trainingGradientAlphaK(
954 x_train_pts, alpha_E, alpha_for_alpha_k, alpha_k_quad,
955 !serial_per_rank, nullptr, &process_group);
956 if (parameter_indices != nullptr && alpha_k_quad.size() > 0) {
957 for (const Eigen::Index index: *parameter_indices)
958 alpha_k_quadratic.push_back(alpha_k_quad(index));
959 } else {
960 alpha_k_quadratic.assign(
961 alpha_k_quad.data(),
962 alpha_k_quad.data() + alpha_k_quad.size());
963 }
964 }
965 }
966
967#ifdef GPR_LINALG_SCALAPACK
968 const int dk_n = static_cast<int>(Ddim_rows);
969 const int dk_local_rows =
970 serial_per_rank ? 0 : _mpi_st.local_rows(dk_n);
971 const int dk_local_cols =
972 serial_per_rank ? 0 : _mpi_st.local_cols(dk_n);
973 int dk_desc[9];
974 if (!serial_per_rank) _mpi_st.make_desc(dk_n, dk_n, dk_desc);
975 bool use_cached_inverse_trace = false;
976 bool use_pair_non_tile_trace = false;
977 if constexpr (std::is_same_v<std::decay_t<CovFunc>, SexpatCF>) {
978 use_pair_non_tile_trace =
979 !serial_per_rank && !use_observation_tile_fast_path &&
980 hasTrainingPermutation() && grad_geom_active &&
981 hutch_trace_W_ == nullptr && hssvd_trace_basis_ == nullptr &&
982 grad_geom_handle->pair_local.valid &&
983 grad_geom_handle->pair_local.n_conf == num_rep &&
984 (grad_geom_handle->pair_local.dof + 1) * num_rep == Ddim_rows &&
985 !alpha_k_quadratic.empty();
986 }
987 std::vector<linalg::ExactSum> cached_inverse_trace(n_hp);
988 if (use_observation_tile_fast_path || use_pair_non_tile_trace) {
989 {
990 ScopedPhaseTimer inverse_timer(
992 backend().cache_cholesky_inverse(L);
993 }
994 use_cached_inverse_trace =
995 _mpi_st.has_cached_inv() && _mpi_st.cached_inv_n() == dk_n;
996 }
997 std::vector<std::vector<double>> DKdist;
998 if (!serial_per_rank && !use_cached_inverse_trace) {
999 DKdist.assign(n_hp, std::vector<double>(
1000 static_cast<size_t>(dk_local_rows) *
1001 static_cast<size_t>(dk_local_cols),
1002 0.0));
1003 }
1004
1005 auto assign_owned_entry =
1006 [&](std::vector<double>& dk_local, const Index_t global_row,
1007 const Index_t global_col, const double value) {
1008 if (!_mpi_st.owns_global_entry(static_cast<int>(global_row),
1009 static_cast<int>(global_col)))
1010 return;
1011
1012 const int local_i = _mpi_st.local_index_for_global(
1013 static_cast<int>(global_row), _mpi_st.block_size(),
1014 _mpi_st.myrow(), _mpi_st.nprow());
1015 const int local_j = _mpi_st.local_index_for_global(
1016 static_cast<int>(global_col), _mpi_st.block_size(),
1017 _mpi_st.mycol(), _mpi_st.npcol());
1018 dk_local[static_cast<size_t>(local_i) +
1019 static_cast<size_t>(local_j) * dk_local_rows] += value;
1020 };
1021 (void)assign_owned_entry;
1022
1023 auto accumulate_trace_or_store_entry = [&](const Index_t elt,
1024 const Index_t global_row,
1025 const Index_t global_col,
1026 double value) {
1027 if (global_row == global_col && diagonal_nugget > 0.0) {
1028 const double shift = diagonal_nugget * value;
1029 value += shift;
1030 if (!alpha_k_quadratic.empty())
1031 Bex[elt].addTripleProduct(b(global_row), shift,
1032 b(global_row));
1033 }
1034 if (use_cached_inverse_trace) {
1035 if (global_row < global_col) return;
1036 if (!_mpi_st.owns_global_entry(static_cast<int>(global_row),
1037 static_cast<int>(global_col)))
1038 return;
1039 const double weight = (global_row == global_col) ? 1.0 : 2.0;
1040 cached_inverse_trace[elt].addProduct(
1041 weight * _mpi_st.cached_inv_local_entry(
1042 static_cast<int>(global_row),
1043 static_cast<int>(global_col)),
1044 value);
1045 return;
1046 }
1047 assign_owned_entry(DKdist[elt], global_row, global_col, value);
1048 };
1049 (void)accumulate_trace_or_store_entry;
1050#endif
1051
1052#ifdef GPR_LINALG_SCALAPACK
1053 bool pair_non_tile_trace_done = false;
1054 if constexpr (std::is_same_v<std::decay_t<CovFunc>, SexpatCF>) {
1055 if (use_pair_non_tile_trace && use_cached_inverse_trace) {
1056 const pairlocal::Weights weights =
1058 grad_geom_theta, grad_geom_handle->pair_local.n_pt);
1059 if (weights.valid) {
1060 pairlocal::TileEvaluator evaluator(
1061 grad_geom_handle->pair_local, weights,
1062 pair_derivative_groups);
1063 if (!pair_derivative_groups.empty())
1064 ++pair_local_grouped_gradients_for_testing_;
1065 const Index_t tile_size = evaluator.tileSize();
1066 // Each observation block has one contraction owner. The
1067 // computation layout may split it, so redistribute the
1068 // inverse entries before doing floating-point arithmetic.
1069 // Summing rounded contractions of zero-padded pieces
1070 // would make the derivative depend on the process grid.
1071 const int observation_block = static_cast<int>(tile_size);
1072 const int process_rows = _mpi_st.nprow();
1073 const int process_cols = _mpi_st.npcol();
1074 const int process_row = _mpi_st.myrow();
1075 const int process_col = _mpi_st.mycol();
1076 const double* inverse = _mpi_st.cached_inv();
1077 int inverse_ld = _mpi_st.cached_inv_desc()[8];
1078 std::vector<double> observation_inverse;
1079 if (_mpi_st.nprocs() > 1) {
1080 const int zero = 0;
1081 const int local_rows =
1082 numroc_(&dk_n, &observation_block, &process_row,
1083 &zero, &process_rows);
1084 const int local_cols =
1085 numroc_(&dk_n, &observation_block, &process_col,
1086 &zero, &process_cols);
1087 inverse_ld = std::max(1, local_rows);
1088 const int context = _mpi_st.context();
1089 int descriptor[9], info = 0;
1090 descinit_(descriptor, &dk_n, &dk_n, &observation_block,
1091 &observation_block, &zero, &zero, &context,
1092 &inverse_ld, &info);
1093 if (info != 0)
1094 throw std::runtime_error(
1095 "cannot describe observation inverse blocks");
1096 _mpi_st.require_lp64(
1097 _mpi_st.cached_inv_desc(),
1098 "observation inverse redistribution");
1099 _mpi_st.require_lp64(
1100 descriptor, "observation inverse redistribution");
1101 const std::int64_t entries =
1102 static_cast<std::int64_t>(inverse_ld) * local_cols;
1104 _mpi_st, "observation inverse blocks",
1105 entries * sizeof(double),
1107 observation_inverse.resize(static_cast<std::size_t>(
1108 std::max<std::int64_t>(1, entries)));
1109 Cpdgemr2d(dk_n, dk_n, inverse, 1, 1,
1110 _mpi_st.cached_inv_desc(),
1111 observation_inverse.data(), 1, 1, descriptor,
1112 context);
1113 inverse = observation_inverse.data();
1114 }
1115 Eigen::MatrixXd diag, contraction_piece;
1116 Eigen::VectorXd part;
1117 std::vector<int> row_lane, col_lane;
1119 if (tile_size >
1120 std::numeric_limits<std::int64_t>::max() /
1121 sizeof(double) / tile_size)
1122 throw std::length_error(
1123 "canonical contraction exceeds addressable "
1124 "storage");
1125 const Index_t last_owned_row =
1126 process_row < num_rep
1127 ? process_row + ((num_rep - 1 - process_row) /
1128 process_rows) *
1129 process_rows
1130 : -1;
1131 const bool has_pairs = last_owned_row >= process_col;
1132 const std::int64_t bytes =
1133 has_pairs ? static_cast<std::int64_t>(tile_size) *
1134 tile_size * sizeof(double)
1135 : 0;
1137 _mpi_st, "canonical contraction block", bytes,
1139 if (has_pairs) {
1140 contraction_piece.resize(tile_size, tile_size);
1141 row_lane.resize(tile_size);
1142 col_lane.resize(tile_size);
1143 }
1144 }
1145 for (Index_t obs_i = process_row; obs_i < num_rep;
1146 obs_i += process_rows) {
1147 for (Index_t obs_j = process_col; obs_j <= obs_i;
1148 obs_j += process_cols) {
1149 const double* block =
1150 inverse + (obs_i / process_rows) * tile_size +
1151 (obs_j / process_cols) * tile_size * inverse_ld;
1152 evaluator.prepare(obs_i, obs_j);
1153 const double weight = obs_i == obs_j ? 1.0 : 2.0;
1154 const auto accumulate_part = [&] {
1155 for (Index_t elt = 0; elt < n_hp; ++elt) {
1156 const Eigen::Index p =
1157 pair_parameter_indices
1158 [static_cast<std::size_t>(elt)];
1159 if (p >= 0)
1160 cached_inverse_trace[elt].addProduct(
1161 weight, part(p));
1162 }
1163 };
1165 // Two logical lanes per axis fix the rounding
1166 // partition of the factor blocks. The physical
1167 // grid moves complete observations; ExactSum
1168 // combines the same rounded pieces on any grid.
1169 const int nb = _mpi_st.block_size();
1170 for (Index_t c = 0; c < tile_size; ++c) {
1171 row_lane[c] =
1172 ((obs_i * tile_size + c) / nb) % 2;
1173 col_lane[c] =
1174 ((obs_j * tile_size + c) / nb) % 2;
1175 }
1176 for (int lane_i = 0; lane_i < 2; ++lane_i) {
1177 for (int lane_j = 0; lane_j < 2; ++lane_j) {
1178 contraction_piece.setZero();
1179 bool has_entries = false;
1180 for (Index_t col = 0; col < tile_size;
1181 ++col) {
1182 if (col_lane[col] != lane_j)
1183 continue;
1184 const Index_t first =
1185 obs_i == obs_j ? col : 0;
1186 for (Index_t row = first;
1187 row < tile_size; ++row) {
1188 if (row_lane[row] != lane_i)
1189 continue;
1190 contraction_piece(row, col) =
1191 block[row +
1192 col * inverse_ld];
1193 has_entries = true;
1194 }
1195 }
1196 if (!has_entries) continue;
1197 evaluator.contract(
1198 contraction_piece.data(), 1,
1199 tile_size, obs_i == obs_j, part);
1200 accumulate_part();
1201 }
1202 }
1203 } else {
1204 evaluator.contract(block, 1, inverse_ld,
1205 obs_i == obs_j, part);
1206 accumulate_part();
1207 }
1208 if (obs_i != obs_j || diagonal_nugget <= 0.0)
1209 continue;
1210 evaluator.diagonals(diag);
1211 for (Index_t channel = 0; channel < tile_size;
1212 ++channel) {
1213 const int global = static_cast<int>(
1214 obs_i * tile_size + channel);
1215 const double alpha = b(global);
1216 for (Index_t elt = 0; elt < n_hp; ++elt) {
1217 const Eigen::Index p =
1218 pair_parameter_indices
1219 [static_cast<std::size_t>(elt)];
1220 if (p < 0) continue;
1221 const double shift =
1222 diagonal_nugget * diag(p, channel);
1223 cached_inverse_trace[elt].addProduct(
1224 block[channel + channel * inverse_ld],
1225 shift);
1226 Bex[elt].addTripleProduct(alpha, shift,
1227 alpha);
1228 }
1229 }
1230 }
1231 }
1232 pair_non_tile_trace_done = true;
1233 }
1234 }
1235 }
1236 if (use_observation_tile_fast_path) {
1237 const Index_t tile_size =
1238 static_cast<Index_t>(channel_layout.channelCount());
1239
1240 FieldMatrixIdx pair_dims1(1, 1), pair_dims2(1, 1);
1241 std::vector<Index_t> owned_obs_rows;
1242 std::vector<Index_t> owned_obs_cols;
1243 std::vector<FieldMatrixd> pair_lower;
1244 const Index_t proc_rows = static_cast<Index_t>(_mpi_st.nprow());
1245 const Index_t proc_cols = static_cast<Index_t>(_mpi_st.npcol());
1246 const Index_t my_row = static_cast<Index_t>(_mpi_st.myrow());
1247 const Index_t my_col = static_cast<Index_t>(_mpi_st.mycol());
1248 for (Index_t obs = 0; obs < num_rep; ++obs) {
1249 if (obs % proc_rows == my_row) owned_obs_rows.push_back(obs);
1250 if (obs % proc_cols == my_col) owned_obs_cols.push_back(obs);
1251 }
1252
1253 auto build_observation_subset =
1254 [&](const Index_t dim_ind, const std::vector<Index_t>& obs_inds,
1255 FieldMatrixd& x_loc_subset) {
1256 const auto channel = channel_layout.block(dim_ind);
1257 if (channel.count == 0) {
1258 x_loc_subset.resize(0, (Index_t)x.cols() + 1);
1259 return;
1260 }
1261 x_loc_subset.resize(obs_inds.size(), (Index_t)x.cols() + 1);
1262 x_loc_subset.setZero();
1263 const Eigen::Index start = channel.start;
1264 for (size_t local_idx = 0; local_idx < obs_inds.size();
1265 ++local_idx) {
1266 x_loc_subset.block(local_idx, 0, 1, x.cols()) = x.block(
1267 start + obs_inds[local_idx], 0, 1, x.cols());
1268 }
1269 };
1270
1271 // One rank owns every entry and the local index is the global
1272 // index, so a (row block, column block) pair contracts against
1273 // the cached inverse with plain strided reads instead of an
1274 // ownership test, an index translation, and a compensated
1275 // update per entry. The inverse is held in its lower triangle
1276 // only, so the trace walks the entries with global row >= column
1277 // (weight two off the global diagonal), exactly the rule of the
1278 // entrywise path; the quadratic form needs only the field and
1279 // is a dense product.
1280 const bool single_rank_dense_trace =
1281 use_cached_inverse_trace && _mpi_st.nprow() == 1 &&
1282 _mpi_st.npcol() == 1 &&
1283 std::getenv("GPR_GRADIENT_DENSE") != nullptr &&
1284 owned_obs_rows.size() == static_cast<std::size_t>(num_rep) &&
1285 owned_obs_cols.size() == static_cast<std::size_t>(num_rep);
1286 const Eigen::Index inverse_leading_dimension =
1287 single_rank_dense_trace ? _mpi_st.cached_inv_desc()[8] : 0;
1288 using StridedVector =
1289 Eigen::Map<const Eigen::VectorXd, 0, Eigen::InnerStride<>>;
1290 auto accumulate_owned_subset_dense =
1291 [&](const Index_t row_val, const Index_t col_val,
1292 const std::vector<FieldMatrixd>& fields,
1293 const bool transpose_field,
1294 std::vector<linalg::ExactSum>& trace_out,
1295 std::vector<double>& quad_out) {
1296 const double* inverse = _mpi_st.cached_inv();
1297 const Eigen::Index row_channel =
1298 channel_layout.ordinal(row_val);
1299 const Eigen::Index col_channel =
1300 channel_layout.ordinal(col_val);
1301 if (row_channel < 0 || col_channel < 0) return;
1302 const Eigen::Index stride =
1303 static_cast<Eigen::Index>(tile_size);
1304 const Eigen::Index lld = inverse_leading_dimension;
1305 const StridedVector b_rows(b.data() + row_channel, num_rep,
1306 Eigen::InnerStride<>(stride));
1307 const StridedVector b_cols(b.data() + col_channel, num_rep,
1308 Eigen::InnerStride<>(stride));
1309 const bool diagonal_block = row_val == col_val;
1310 const bool quadratic = alpha_k_quadratic.empty();
1311 // Global row >= column holds for obs_i > obs_j in every
1312 // block, and for obs_i == obs_j when row_val >= col_val.
1313 const bool include_equal_obs = row_val >= col_val;
1314 for (Index_t elt = 0; elt < n_hp; ++elt) {
1315 const EigenMatrix F =
1316 transpose_field
1317 ? EigenMatrix(fields[elt].transpose())
1318 : EigenMatrix(fields[elt]);
1319 // Compensated products as in the entrywise path,
1320 // so the two orderings differ only at the level of
1321 // the final rounding.
1322 linalg::CompensatedSum block_trace;
1323 for (Eigen::Index j = 0; j < num_rep; ++j) {
1324 const double* column =
1325 inverse + (j * stride + col_channel) * lld +
1326 row_channel;
1327 for (Eigen::Index i = j + 1; i < num_rep; ++i)
1328 block_trace.addProduct(2.0 * column[i * stride],
1329 F(i, j));
1330 if (include_equal_obs) {
1331 const double weight =
1332 diagonal_block ? 1.0 + diagonal_nugget
1333 : 2.0;
1334 block_trace.addProduct(
1335 weight * column[j * stride], F(j, j));
1336 }
1337 }
1338 const double trace_term = block_trace.value();
1339 double quad_term =
1340 quadratic ? b_rows.dot(F * b_cols) : 0.0;
1341 if (diagonal_block && diagonal_nugget > 0.0) {
1342 const double shift =
1343 diagonal_nugget *
1344 b_rows.cwiseProduct(b_rows).dot(F.diagonal());
1345 if (quadratic)
1346 quad_term += shift;
1347 else
1348 quad_out[elt] += shift;
1349 }
1350 trace_out[elt].add(trace_term);
1351 if (quadratic) quad_out[elt] += quad_term;
1352 }
1353 };
1354 // GPR_GRADIENT_DENSE selects the dense contraction.
1355 // GPR_GRADIENT_CHECK compares both accumulations on each block
1356 // and reports disagreements in trace or quadratic contributions.
1357 const bool check_dense_against_entrywise =
1358 single_rank_dense_trace &&
1359 std::getenv("GPR_GRADIENT_CHECK") != nullptr;
1360 struct DenseCheck {
1361 std::vector<linalg::ExactSum>& trace;
1362 std::vector<double>& quad;
1363 std::vector<linalg::ExactSum> trace_dense;
1364 std::vector<double> quad_dense;
1365 std::vector<double> trace_before;
1366 std::vector<double> quad_before;
1367 Index_t row_val, col_val;
1368 ~DenseCheck()
1369 {
1370 for (std::size_t elt = 0; elt < trace_dense.size(); ++elt) {
1371 const double entry_trace =
1372 trace[elt].value() - trace_before[elt];
1373 const double entry_quad = quad[elt] - quad_before[elt];
1374 const double dense_trace = trace_dense[elt].value();
1375 const double dense_quad = quad_dense[elt];
1376 const bool trace_off =
1377 std::abs(entry_trace - dense_trace) >
1378 1e-9 * (1.0 + std::abs(entry_trace));
1379 const bool quad_off =
1380 std::abs(entry_quad - dense_quad) >
1381 1e-9 * (1.0 + std::abs(entry_quad));
1382 if (trace_off || quad_off)
1383 std::fprintf(stderr,
1384 "[gradient-check] block (%ld,%ld) "
1385 "elt %zu trace entry %.17g dense "
1386 "%.17g quad entry %.17g dense %.17g\n",
1387 static_cast<long>(row_val),
1388 static_cast<long>(col_val), elt,
1389 entry_trace, dense_trace, entry_quad,
1390 dense_quad);
1391 }
1392 }
1393 };
1394 auto accumulate_owned_subset =
1395 [&](const Index_t row_val, const Index_t col_val,
1396 const std::vector<FieldMatrixd>& fields,
1397 const bool transpose_field = false) {
1398 ScopedPhaseTimer accumulate_timer(
1400 const Eigen::Index row_channel =
1401 channel_layout.ordinal(row_val);
1402 const Eigen::Index col_channel =
1403 channel_layout.ordinal(col_val);
1404 if (row_channel < 0 || col_channel < 0) return;
1405 if (single_rank_dense_trace &&
1406 !check_dense_against_entrywise) {
1407 accumulate_owned_subset_dense(
1408 row_val, col_val, fields, transpose_field,
1409 cached_inverse_trace, Bdl);
1410 return;
1411 }
1412 std::unique_ptr<DenseCheck> check;
1413 if (check_dense_against_entrywise) {
1414 check.reset(new DenseCheck{
1415 cached_inverse_trace, Bdl,
1416 std::vector<linalg::ExactSum>(n_hp),
1417 std::vector<double>(n_hp, 0.0),
1418 std::vector<double>(n_hp, 0.0),
1419 std::vector<double>(n_hp, 0.0), row_val, col_val});
1420 for (Index_t elt = 0; elt < n_hp; ++elt) {
1421 check->trace_before[elt] =
1422 cached_inverse_trace[elt].value();
1423 check->quad_before[elt] = Bdl[elt];
1424 }
1425 accumulate_owned_subset_dense(
1426 row_val, col_val, fields, transpose_field,
1427 check->trace_dense, check->quad_dense);
1428 }
1429 // Pass 1 walks owned entries in column-major order. The
1430 // solve-based fallback stores DKdist contiguously, while
1431 // cached-inverse trace mode uses the same traversal for a
1432 // deterministic lower-triangle contraction.
1433 for (size_t local_j = 0; local_j < owned_obs_cols.size();
1434 ++local_j) {
1435 const Index_t obs_j = owned_obs_cols[local_j];
1436 const Index_t col_j_idx =
1437 obs_j * tile_size + col_channel;
1438
1439 for (size_t local_i = 0;
1440 local_i < owned_obs_rows.size(); ++local_i) {
1441 const Index_t obs_i = owned_obs_rows[local_i];
1442 const Index_t row_i_idx =
1443 obs_i * tile_size + row_channel;
1444 if (!_mpi_st.owns_global_entry(
1445 static_cast<int>(row_i_idx),
1446 static_cast<int>(col_j_idx)))
1447 continue;
1448 for (Index_t elt = 0; elt < n_hp; ++elt) {
1449 const double value =
1450 !transpose_field
1451 ? fields[elt](local_i, local_j)
1452 : fields[elt](local_j, local_i);
1453 accumulate_trace_or_store_entry(
1454 elt, row_i_idx, col_j_idx, value);
1455 }
1456 }
1457 }
1458 if (!alpha_k_quadratic.empty()) return;
1459 // Pass 2: Bdl accumulates in the scalar reference order
1460 // (local_i outer, local_j inner, elt innermost). Keeping
1461 // this sum order stable protects the SCG trajectory from
1462 // reduction-order drift.
1463 for (size_t local_i = 0; local_i < owned_obs_rows.size();
1464 ++local_i) {
1465 const Index_t obs_i = owned_obs_rows[local_i];
1466 const Index_t row_i_idx =
1467 obs_i * tile_size + row_channel;
1468 for (size_t local_j = 0;
1469 local_j < owned_obs_cols.size(); ++local_j) {
1470 const Index_t obs_j = owned_obs_cols[local_j];
1471 const Index_t col_j_idx =
1472 obs_j * tile_size + col_channel;
1473 if (!_mpi_st.owns_global_entry(
1474 static_cast<int>(row_i_idx),
1475 static_cast<int>(col_j_idx)))
1476 continue;
1477 for (Index_t elt = 0; elt < n_hp; ++elt) {
1478 double value =
1479 !transpose_field
1480 ? fields[elt](local_i, local_j)
1481 : fields[elt](local_j, local_i);
1482 if (row_i_idx == col_j_idx)
1483 value += diagonal_nugget * value;
1484 Bex[elt].addTripleProduct(b(row_i_idx), value,
1485 b(col_j_idx));
1486 }
1487 }
1488 }
1489 };
1490
1491 // Pair-local tiles: each owned (i >= j) tile of the cached
1492 // inverse contracts with the covariance tile and its
1493 // hyperparameter derivatives directly; nothing is walked per
1494 // channel pair.
1495 bool pair_local_trace_done = false;
1496 if constexpr (std::is_same_v<std::decay_t<CovFunc>, SexpatCF>) {
1497 if (grad_geom_active && use_cached_inverse_trace &&
1498 hutch_trace_W_ == nullptr &&
1499 grad_geom_handle->pair_local.valid &&
1500 grad_geom_handle->pair_local.n_conf == num_rep &&
1501 grad_geom_handle->pair_local.dof + 1 == tile_size &&
1502 !alpha_k_quadratic.empty() && !owned_obs_rows.empty() &&
1503 !owned_obs_cols.empty()) {
1504 const pairlocal::Weights weights =
1506 grad_geom_theta, grad_geom_handle->pair_local.n_pt);
1507 if (weights.valid) {
1508 pairlocal::TileEvaluator evaluator(
1509 grad_geom_handle->pair_local, weights,
1510 pair_derivative_groups);
1511 if (!pair_derivative_groups.empty())
1512 ++pair_local_grouped_gradients_for_testing_;
1513 const auto parameter_of = [&](Index_t elt) {
1514 return pair_parameter_indices
1515 [static_cast<std::size_t>(elt)];
1516 };
1517 Eigen::VectorXd part;
1518 EigenMatrix diag;
1519 for (const Index_t obs_i: owned_obs_rows) {
1520 for (const Index_t obs_j: owned_obs_cols) {
1521 if (obs_j > obs_i) continue;
1522 const int global_row =
1523 static_cast<int>(obs_i * tile_size);
1524 const int global_col =
1525 static_cast<int>(obs_j * tile_size);
1526 if (!_mpi_st.owns_global_entry(global_row,
1527 global_col))
1528 continue;
1529 int lld = 0;
1530 const double* W = _mpi_st.cached_inv_block(
1531 global_row, global_col, lld);
1532 evaluator.prepare(obs_i, obs_j);
1533 evaluator.contract(
1534 W, 1, lld,
1535 /*lower_only=*/obs_i == obs_j, part);
1536 const double weight =
1537 obs_i == obs_j ? 1.0 : 2.0;
1538 for (Index_t elt = 0; elt < n_hp; ++elt) {
1539 const Eigen::Index p = parameter_of(elt);
1540 if (p >= 0)
1541 cached_inverse_trace[elt].addProduct(
1542 weight, part(p));
1543 }
1544 if (obs_i == obs_j && diagonal_nugget > 0.0) {
1545 evaluator.diagonals(diag);
1546 for (Index_t elt = 0; elt < n_hp; ++elt) {
1547 const Eigen::Index p =
1548 parameter_of(elt);
1549 if (p < 0) continue;
1550 for (Index_t c = 0; c < tile_size;
1551 ++c) {
1552 const double value =
1553 diagonal_nugget * diag(p, c);
1554 cached_inverse_trace[elt]
1555 .addProduct(W[c + c * lld],
1556 value);
1557 if (!alpha_k_quadratic.empty()) {
1558 const double bc =
1559 b(global_row + c);
1560 Bex[elt].addTripleProduct(
1561 bc, value, bc);
1562 }
1563 }
1564 }
1565 }
1566 }
1567 }
1568 pair_local_trace_done = true;
1569 }
1570 }
1571 }
1572 if (!pair_local_trace_done && !owned_obs_rows.empty() &&
1573 !owned_obs_cols.empty()) {
1574 FieldMatrixd ff_rows, ff_cols;
1575 FieldMatrixd df_rows, df_cols;
1576 FieldMatrixd dg_rows, dg_cols;
1577
1578 build_observation_subset(0, owned_obs_rows, ff_rows);
1579 build_observation_subset(0, owned_obs_cols, ff_cols);
1580
1581 // Per-rank subset geometry dispatch. At np=1 owned ==
1582 // full so the subset blocks coincide with the full
1583 // geometry; at np>1 each rank uses its own subset shape.
1584 // rc = (owned_rows, owned_cols) shape;
1585 // cr = (owned_cols, owned_rows) shape (for the
1586 // transpose-flavour Kdf_t call only).
1587 const bool use_rc_subset =
1588 grad_geom_active && grad_geom_handle->has_per_rank_subset &&
1589 grad_geom_handle->rows_cols.valid;
1590 const bool use_cr_subset =
1591 grad_geom_active && grad_geom_handle->has_per_rank_subset &&
1592 grad_geom_handle->cols_rows.valid;
1593 const bool use_streamed_subset =
1594 grad_geom_active && grad_geom_handle->streamed;
1595 FieldMatrixd shared_kernel_rc_storage;
1596 FieldMatrixd shared_kernel_cr_storage;
1597 std::vector<FieldMatrixd> shared_distances_rc_storage;
1598 std::vector<FieldMatrixd> shared_distances_cr_storage;
1599 const FieldMatrixd* shared_kernel_rc = nullptr;
1600 const FieldMatrixd* shared_kernel_cr = nullptr;
1601 const std::vector<FieldMatrixd>* shared_distances_rc = nullptr;
1602 const std::vector<FieldMatrixd>* shared_distances_cr = nullptr;
1603 const auto select_owned_field =
1604 [](const FieldMatrixd& field,
1605 const std::vector<Index_t>& rows,
1606 const std::vector<Index_t>& cols) {
1607 FieldMatrixd subset(rows.size(), cols.size());
1608 for (std::size_t j = 0; j < cols.size(); ++j)
1609 for (std::size_t i = 0; i < rows.size(); ++i)
1610 subset(i, j) = field(rows[i], cols[j]);
1611 return subset;
1612 };
1613 if constexpr (std::is_same_v<std::decay_t<CovFunc>, SexpatCF>) {
1614 auto subset_is_full =
1615 [&](const TrainingKernelGeometrySubset& subset) {
1616 return subset.n_rows ==
1617 grad_geom_handle
1618 ->num_repetitive_indices &&
1619 subset.n_cols ==
1620 grad_geom_handle->num_repetitive_indices;
1621 };
1622 if (use_rc_subset) {
1623 shared_distances_rc = &grad_geom_handle->rows_cols
1624 .shared_distance_neg_per_pt;
1625 if (subset_is_full(grad_geom_handle->rows_cols)) {
1626 shared_kernel_rc = &grad_geom_shared_kernel;
1627 } else if (cov_func.buildSharedKernel(
1628 grad_geom_handle->rows_cols
1629 .shared_distance_neg_per_pt,
1630 grad_geom_theta,
1631 shared_kernel_rc_storage)) {
1632 shared_kernel_rc = &shared_kernel_rc_storage;
1633 }
1634 }
1635 if (use_cr_subset) {
1636 shared_distances_cr = &grad_geom_handle->cols_rows
1637 .shared_distance_neg_per_pt;
1638 if (subset_is_full(grad_geom_handle->cols_rows)) {
1639 shared_kernel_cr = &grad_geom_shared_kernel;
1640 } else if (cov_func.buildSharedKernel(
1641 grad_geom_handle->cols_rows
1642 .shared_distance_neg_per_pt,
1643 grad_geom_theta,
1644 shared_kernel_cr_storage)) {
1645 shared_kernel_cr = &shared_kernel_cr_storage;
1646 }
1647 }
1648 if (use_streamed_subset) {
1649 const auto prepare_streamed_subset =
1650 [&](const std::vector<Index_t>& rows,
1651 const std::vector<Index_t>& cols,
1652 FieldMatrixd& kernel_storage,
1653 std::vector<FieldMatrixd>& distances_storage,
1654 const FieldMatrixd*& kernel,
1655 const std::vector<FieldMatrixd>*& distances) {
1656 if (rows.size() ==
1657 static_cast<std::size_t>(num_rep) &&
1658 cols.size() ==
1659 static_cast<std::size_t>(num_rep)) {
1660 kernel = &grad_geom_shared_kernel;
1661 distances =
1662 &grad_geom_handle
1663 ->shared_distance_neg_per_pt;
1664 return;
1665 }
1666 kernel_storage = select_owned_field(
1667 grad_geom_shared_kernel, rows, cols);
1668 for (const auto& field:
1669 grad_geom_handle
1670 ->shared_distance_neg_per_pt)
1671 distances_storage.push_back(
1672 select_owned_field(field, rows, cols));
1673 kernel = &kernel_storage;
1674 distances = &distances_storage;
1675 };
1676 prepare_streamed_subset(owned_obs_rows, owned_obs_cols,
1677 shared_kernel_rc_storage,
1678 shared_distances_rc_storage,
1679 shared_kernel_rc,
1680 shared_distances_rc);
1681 prepare_streamed_subset(owned_obs_cols, owned_obs_rows,
1682 shared_kernel_cr_storage,
1683 shared_distances_cr_storage,
1684 shared_kernel_cr,
1685 shared_distances_cr);
1686 }
1687 }
1688 const bool rc_ready = shared_distances_rc != nullptr &&
1689 shared_kernel_rc != nullptr;
1690 const bool cr_ready = shared_distances_cr != nullptr &&
1691 shared_kernel_cr != nullptr;
1692 const auto resolve_owned_geometry =
1693 [&](Index_t block_n, Index_t block_m, bool transpose,
1694 SexpatCF::CrossBlockGeometry& scratch)
1695 -> const SexpatCF::CrossBlockGeometry* {
1696 if (use_streamed_subset) {
1697 const uint8_t options =
1698 block_m == 0 ? OptionsForGradCalculation::D1
1702 const auto& rows =
1703 transpose ? owned_obs_cols : owned_obs_rows;
1704 const auto& cols =
1705 transpose ? owned_obs_rows : owned_obs_cols;
1706 if (!grad_geom_handle->factors.valid) {
1707 // A spilled walked cache rebuilds the same owned
1708 // geometry and uses the shared-kernel derivative
1709 // formula, preserving the cached contraction bits.
1710 if constexpr (std::is_same_v<std::decay_t<CovFunc>,
1711 SexpatCF>) {
1712 FieldMatrixd row_coordinates, col_coordinates;
1713 build_observation_subset(block_n, rows,
1714 row_coordinates);
1715 build_observation_subset(block_m, cols,
1716 col_coordinates);
1717 FieldMatrixIdx row_dimension(1, 1),
1718 col_dimension(1, 1);
1719 row_dimension(0, 0) = block_n;
1720 col_dimension(0, 0) = block_m;
1721 return cov_func.buildCrossBlockDerivativesOnly(
1722 row_coordinates, col_coordinates,
1723 options, row_dimension,
1724 col_dimension, scratch)
1725 ? &scratch
1726 : nullptr;
1727 }
1728 return nullptr;
1729 }
1731 grad_geom_handle->factors, block_n, block_m,
1732 options, scratch))
1733 return nullptr;
1734 if (rows.size() != static_cast<std::size_t>(num_rep) ||
1735 cols.size() != static_cast<std::size_t>(num_rep)) {
1736 for (auto* fields:
1737 {&scratch.d1, &scratch.d2, &scratch.d12})
1738 for (auto& field: *fields)
1739 field =
1740 select_owned_field(field, rows, cols);
1741 }
1742 return &scratch;
1743 }
1744 const auto& subset = transpose
1745 ? grad_geom_handle->cols_rows
1746 : grad_geom_handle->rows_cols;
1747 const auto* block = subset.find(block_n, block_m);
1748 return block == nullptr ? nullptr : &block->geometry;
1749 };
1750
1751 bool kff_geom = false;
1752 if constexpr (std::is_same_v<std::decay_t<CovFunc>, SexpatCF>) {
1753 if (rc_ready) {
1754 kff_geom =
1755 cov_func.calculateGradOfCovMatrixFromGeometry(
1756 *shared_kernel_rc, *shared_distances_rc,
1757 grad_geom_theta, pair_lower, parameter_indices);
1758 }
1759 }
1760 if (!kff_geom) {
1761 pair_lower.clear();
1762 cov_func.calculateGradOfCovMatrix(ff_rows, ff_cols,
1763 pair_lower);
1764 select_live_gradient_blocks(pair_lower);
1765 }
1766 accumulate_owned_subset(0, 0, pair_lower);
1767
1768 for (Index_t n = 0; n < uDdim.size(); ++n) {
1769 pair_dims1(0, 0) = uDdim[n];
1770 build_observation_subset(uDdim[n], owned_obs_rows, df_rows);
1771 build_observation_subset(uDdim[n], owned_obs_cols, df_cols);
1772 bool kdf_geom = false;
1773 if constexpr (std::is_same_v<std::decay_t<CovFunc>,
1774 SexpatCF>) {
1775 if (rc_ready) {
1776 SexpatCF::CrossBlockGeometry scratch;
1777 const auto* kdf_block = resolve_owned_geometry(
1778 static_cast<Index_t>(uDdim[n]), 0, false,
1779 scratch);
1780 if (kdf_block != nullptr) {
1781 kdf_geom =
1782 cov_func
1783 .calculateGradOfCovMatrixWithDerivativesFromGeometry(
1784 *kdf_block, *shared_kernel_rc,
1785 *shared_distances_rc,
1786 grad_geom_theta, pair_lower,
1787 parameter_indices);
1788 }
1789 }
1790 }
1791 if (!kdf_geom) {
1792 pair_lower.clear();
1793 record_live_gradient_geometry();
1794 cov_func.calculateGradOfCovMatrixWithDerivatives(
1795 df_rows, ff_cols, pair_dims1, pair_lower);
1796 select_live_gradient_blocks(pair_lower);
1797 }
1798 accumulate_owned_subset(uDdim[n], 0, pair_lower);
1799 bool kdf_t_geom = false;
1800 if constexpr (std::is_same_v<std::decay_t<CovFunc>,
1801 SexpatCF>) {
1802 if (cr_ready) {
1803 // (df_cols, ff_rows) shape -- use cols_rows
1804 // subset block (uDdim[n], 0).
1805 SexpatCF::CrossBlockGeometry scratch;
1806 const auto* kdf_block = resolve_owned_geometry(
1807 static_cast<Index_t>(uDdim[n]), 0, true,
1808 scratch);
1809 if (kdf_block != nullptr) {
1810 kdf_t_geom =
1811 cov_func
1812 .calculateGradOfCovMatrixWithDerivativesFromGeometry(
1813 *kdf_block, *shared_kernel_cr,
1814 *shared_distances_cr,
1815 grad_geom_theta, pair_lower,
1816 parameter_indices);
1817 }
1818 }
1819 }
1820 if (!kdf_t_geom) {
1821 pair_lower.clear();
1822 record_live_gradient_geometry();
1823 cov_func.calculateGradOfCovMatrixWithDerivatives(
1824 df_cols, ff_rows, pair_dims1, pair_lower);
1825 select_live_gradient_blocks(pair_lower);
1826 }
1827 accumulate_owned_subset(0, uDdim[n], pair_lower, true);
1828 bool d_geom = false;
1829 if constexpr (std::is_same_v<std::decay_t<CovFunc>,
1830 SexpatCF>) {
1831 if (rc_ready) {
1832 SexpatCF::CrossBlockGeometry scratch;
1833 const auto* d_block = resolve_owned_geometry(
1834 static_cast<Index_t>(uDdim[n]),
1835 static_cast<Index_t>(uDdim[n]), false, scratch);
1836 if (d_block != nullptr) {
1837 d_geom =
1838 cov_func
1839 .calculateGradOfCovMatrixWithDerivatives2FromGeometry(
1840 *d_block, *shared_kernel_rc,
1841 *shared_distances_rc,
1842 grad_geom_theta, pair_lower,
1843 parameter_indices);
1844 }
1845 }
1846 }
1847 if (!d_geom) {
1848 pair_lower.clear();
1849 record_live_gradient_geometry();
1850 cov_func.calculateGradOfCovMatrixWithDerivatives2(
1851 df_rows, df_cols, pair_dims1, pair_dims1,
1852 pair_lower);
1853 select_live_gradient_blocks(pair_lower);
1854 }
1855 accumulate_owned_subset(uDdim[n], uDdim[n], pair_lower);
1856
1857 for (Index_t m = n + 1; m < uDdim.size(); ++m) {
1858 pair_dims2(0, 0) = uDdim[m];
1859 build_observation_subset(uDdim[m], owned_obs_rows,
1860 dg_rows);
1861 build_observation_subset(uDdim[m], owned_obs_cols,
1862 dg_cols);
1863 bool kdf2_geom = false;
1864 if constexpr (std::is_same_v<std::decay_t<CovFunc>,
1865 SexpatCF>) {
1866 if (rc_ready) {
1867 SexpatCF::CrossBlockGeometry scratch;
1868 const auto* kdf2_block = resolve_owned_geometry(
1869 static_cast<Index_t>(uDdim[n]),
1870 static_cast<Index_t>(uDdim[m]), false,
1871 scratch);
1872 if (kdf2_block != nullptr) {
1873 kdf2_geom =
1874 cov_func
1875 .calculateGradOfCovMatrixWithDerivatives2FromGeometry(
1876 *kdf2_block, *shared_kernel_rc,
1877 *shared_distances_rc,
1878 grad_geom_theta, pair_lower,
1879 parameter_indices);
1880 }
1881 }
1882 }
1883 if (!kdf2_geom) {
1884 pair_lower.clear();
1885 record_live_gradient_geometry();
1886 cov_func.calculateGradOfCovMatrixWithDerivatives2(
1887 df_rows, dg_cols, pair_dims1, pair_dims2,
1888 pair_lower);
1889 select_live_gradient_blocks(pair_lower);
1890 }
1891 accumulate_owned_subset(uDdim[n], uDdim[m], pair_lower);
1892 bool kdf2_t_geom = false;
1893 if constexpr (std::is_same_v<std::decay_t<CovFunc>,
1894 SexpatCF>) {
1895 if (rc_ready) {
1896 // (dg_rows, df_cols) shape -- use rows_cols
1897 // subset block (uDdim[m], uDdim[n]) provided
1898 // by fill_subset.
1899 SexpatCF::CrossBlockGeometry scratch;
1900 const auto* kdf2_t_block =
1901 resolve_owned_geometry(
1902 static_cast<Index_t>(uDdim[m]),
1903 static_cast<Index_t>(uDdim[n]), false,
1904 scratch);
1905 if (kdf2_t_block != nullptr) {
1906 kdf2_t_geom =
1907 cov_func
1908 .calculateGradOfCovMatrixWithDerivatives2FromGeometry(
1909 *kdf2_t_block,
1910 *shared_kernel_rc,
1911 *shared_distances_rc,
1912 grad_geom_theta, pair_lower,
1913 parameter_indices);
1914 }
1915 }
1916 }
1917 if (!kdf2_t_geom) {
1918 pair_lower.clear();
1919 record_live_gradient_geometry();
1920 cov_func.calculateGradOfCovMatrixWithDerivatives2(
1921 dg_rows, df_cols, pair_dims2, pair_dims1,
1922 pair_lower);
1923 select_live_gradient_blocks(pair_lower);
1924 }
1925 accumulate_owned_subset(uDdim[m], uDdim[n], pair_lower);
1926 }
1927 }
1928 }
1929 } else if (!serial_per_rank && !pair_non_tile_trace_done) {
1930 auto accumulate_distributed_block =
1931 [&](const Index_t row_val, const Index_t col_val,
1932 const FieldMatrixd& field, const Index_t elt,
1933 linalg::ExactSum& quad_accum,
1934 const bool transpose_field = false) {
1935 const auto row_block = channel_layout.block(row_val);
1936 const auto col_block = channel_layout.block(col_val);
1937 const Eigen::Index i_start = row_block.start;
1938 const Eigen::Index j_start = col_block.start;
1939
1940 for (Index_t local_i = 0; local_i < row_block.count;
1941 ++local_i) {
1942 const Index_t global_i = i_start + local_i;
1943 for (Index_t local_j = 0; local_j < col_block.count;
1944 ++local_j) {
1945 const Index_t global_j = j_start + local_j;
1946 const double field_value =
1947 !transpose_field ? field(local_i, local_j)
1948 : field(local_j, local_i);
1949
1950 int perm_i = static_cast<int>(global_i);
1951 int perm_j = static_cast<int>(global_j);
1952 Index_t alpha_i_index = global_i;
1953 Index_t alpha_j_index = global_j;
1954 if (hasTrainingPermutation()) {
1955 perm_i = static_cast<int>(
1956 training_permutation_.inv_perm[global_i]);
1957 perm_j = static_cast<int>(
1958 training_permutation_.inv_perm[global_j]);
1959 alpha_i_index = static_cast<Index_t>(perm_i);
1960 alpha_j_index = static_cast<Index_t>(perm_j);
1961 }
1962
1963 if (!_mpi_st.owns_global_entry(perm_i, perm_j))
1964 continue;
1965
1966 accumulate_trace_or_store_entry(
1967 elt, static_cast<Index_t>(perm_i),
1968 static_cast<Index_t>(perm_j), field_value);
1969 if (alpha_k_quadratic.empty())
1970 quad_accum.addTripleProduct(
1971 b(alpha_i_index),
1972 field_value * (global_i == global_j
1973 ? 1.0 + diagonal_nugget
1974 : 1.0),
1975 b(alpha_j_index));
1976 }
1977 }
1978 };
1979
1980 for (Index_t elt = 0; elt < DKffa.size(); ++elt)
1981 accumulate_distributed_block(0, 0, DKffa[elt], elt, Bdist[elt]);
1982
1983 std::vector<FieldMatrixd> Kdf;
1984 std::vector<FieldMatrixd> Kdf2;
1985 std::vector<FieldMatrixd> D;
1986
1987 for (Index_t n = 0; n < uDdim.size(); ++n) {
1988 dims1(0, 0) = uDdim[n];
1989 extractCoordinatesByIndex(x, ind_Ddim, uDdim[n], x_loc_1);
1990
1991 bool kdf_geom = false, d_geom = false;
1992 if constexpr (std::is_same_v<std::decay_t<CovFunc>, SexpatCF>) {
1993 if (grad_geom_active) {
1994 SexpatCF::CrossBlockGeometry kdf_block_scratch;
1995 const auto* kdf_block = resolve_gradient_geometry(
1996 static_cast<Index_t>(uDdim[n]), 0,
1997 kdf_block_scratch);
1998 if (kdf_block != nullptr) {
1999 kdf_geom =
2000 cov_func
2001 .calculateGradOfCovMatrixWithDerivativesFromGeometry(
2002 *kdf_block, grad_geom_shared_kernel,
2003 grad_geom_handle
2004 ->shared_distance_neg_per_pt,
2005 grad_geom_theta, Kdf,
2006 parameter_indices);
2007 }
2008 SexpatCF::CrossBlockGeometry d_block_scratch;
2009 const auto* d_block = resolve_gradient_geometry(
2010 static_cast<Index_t>(uDdim[n]),
2011 static_cast<Index_t>(uDdim[n]), d_block_scratch);
2012 if (d_block != nullptr) {
2013 d_geom =
2014 cov_func
2015 .calculateGradOfCovMatrixWithDerivatives2FromGeometry(
2016 *d_block, grad_geom_shared_kernel,
2017 grad_geom_handle
2018 ->shared_distance_neg_per_pt,
2019 grad_geom_theta, D, parameter_indices);
2020 }
2021 }
2022 }
2023 if (!kdf_geom) {
2024 Kdf.clear();
2025 record_live_gradient_geometry();
2026 cov_func.calculateGradOfCovMatrixWithDerivatives(
2027 x_loc_1, x_loc_0, dims1, Kdf);
2028 select_live_gradient_blocks(Kdf);
2029 }
2030 if (!d_geom) {
2031 D.clear();
2032 record_live_gradient_geometry();
2033 cov_func.calculateGradOfCovMatrixWithDerivatives2(
2034 x_loc_1, x_loc_1, dims1, dims1, D);
2035 select_live_gradient_blocks(D);
2036 }
2037
2038 for (Index_t elt = 0; elt < DKffa.size(); ++elt) {
2039 accumulate_distributed_block(uDdim[n], 0, Kdf[elt], elt,
2040 Bdist[elt]);
2041 accumulate_distributed_block(0, uDdim[n], Kdf[elt], elt,
2042 Bdist[elt], true);
2043 accumulate_distributed_block(uDdim[n], uDdim[n], D[elt],
2044 elt, Bdist[elt]);
2045 }
2046
2047 for (Index_t m = n + 1; m < uDdim.size(); ++m) {
2048 dims2(0, 0) = uDdim[m];
2049 extractCoordinatesByIndex(x, ind_Ddim, uDdim[m], x_loc_2);
2050
2051 bool kdf2_geom = false;
2052 if constexpr (std::is_same_v<std::decay_t<CovFunc>,
2053 SexpatCF>) {
2054 if (grad_geom_active) {
2055 SexpatCF::CrossBlockGeometry kdf2_block_scratch;
2056 const auto* kdf2_block = resolve_gradient_geometry(
2057 static_cast<Index_t>(uDdim[n]),
2058 static_cast<Index_t>(uDdim[m]),
2059 kdf2_block_scratch);
2060 if (kdf2_block != nullptr) {
2061 kdf2_geom =
2062 cov_func
2063 .calculateGradOfCovMatrixWithDerivatives2FromGeometry(
2064 *kdf2_block,
2065 grad_geom_shared_kernel,
2066 grad_geom_handle
2067 ->shared_distance_neg_per_pt,
2068 grad_geom_theta, Kdf2,
2069 parameter_indices);
2070 }
2071 }
2072 }
2073 if (!kdf2_geom) {
2074 Kdf2.clear();
2075 record_live_gradient_geometry();
2076 cov_func.calculateGradOfCovMatrixWithDerivatives2(
2077 x_loc_1, x_loc_2, dims1, dims2, Kdf2);
2078 select_live_gradient_blocks(Kdf2);
2079 }
2080
2081 for (Index_t elt = 0; elt < DKffa.size(); ++elt) {
2082 accumulate_distributed_block(
2083 uDdim[n], uDdim[m], Kdf2[elt], elt, Bdist[elt]);
2084 accumulate_distributed_block(uDdim[m], uDdim[n],
2085 Kdf2[elt], elt, Bdist[elt],
2086 true);
2087 }
2088 }
2089 }
2090 }
2091
2092 if (!serial_per_rank && !use_cached_inverse_trace && n_hp > 0) {
2093 // tr(C^{-1} dK) for every parameter from one inverse of the
2094 // factor: about 2n^3/3 in place of 2n^3 per parameter for
2095 // substitutions, by the same formula at every rank count. The
2096 // inverse is not kept.
2097 std::vector<double> inverse;
2098 int inverse_desc[9];
2099 bool inverse_ok = false;
2100 {
2101 ScopedPhaseTimer inverse_timer(
2103 inverse_ok = backend().factor_inverse_lower(L, dk_n, inverse,
2104 inverse_desc);
2105 }
2106 if (!inverse_ok)
2107 throw std::runtime_error(
2108 "ScaLAPACK gradient path could not invert the training "
2109 "Cholesky factor");
2110 const int dk_ld = std::max(1, dk_desc[8]);
2111 for (Index_t elt = 0; elt < n_hp; ++elt) {
2112 const double* dk = DKdist[elt].data();
2113 Cdist[elt] = backend().trace_lower_symmetric_local(
2114 inverse.data(), std::max(1, inverse_desc[8]), dk_n,
2115 [&](int, int, int il, int jl) {
2116 return dk[static_cast<size_t>(il) +
2117 static_cast<size_t>(jl) * dk_ld];
2118 });
2119 }
2120 }
2121#endif
2122
2123 // Eigen-style Cdl/Bdl path: always taken in non-SCALAPACK builds
2124 // and also in SCALAPACK builds when serial_per_rank=true (so the
2125 // local oracle can compute the gradient without entering any
2126 // collective). Cdl + Bdl are reset before recomputing under
2127 // serial_per_rank to avoid double-counting on top of any
2128 // partial accumulation from the SCALAPACK distributed loops
2129 // above.
2130#ifdef GPR_LINALG_SCALAPACK
2131 if (serial_per_rank) {
2132 std::fill(Cdl.begin(), Cdl.end(), 0.0);
2133 std::fill(Bdl.begin(), Bdl.end(), 0.0);
2134 }
2135#endif
2136#ifdef GPR_LINALG_SCALAPACK
2137 if (serial_per_rank)
2138#endif
2139 {
2140 const bool accumulate_quad_blocks = alpha_k_quadratic.empty();
2141 bool dense_pair_local_done = false;
2142 const Eigen::Index expected_trace_rows =
2143 active_deflation.activeOrderFor(
2144 static_cast<Eigen::Index>(Ddim_rows));
2145 const bool solve_trace =
2146 trace_factor != nullptr &&
2147 trace_factor->rows() == expected_trace_rows &&
2148 trace_factor->cols() == expected_trace_rows &&
2149 hutch_trace_W_ == nullptr && hssvd_trace_basis_ == nullptr;
2150 if (!solve_trace && hutch_trace_W_ == nullptr &&
2151 hssvd_trace_basis_ == nullptr &&
2152 !(invC.rows() == Ddim_rows && invC.cols() == Ddim_rows)) {
2153 throw std::logic_error(
2154 "gradient: no covariance factor, inverse or trace "
2155 "estimator for tr(C^{-1} dK)");
2156 }
2157 std::vector<EigenMatrix> dk_trace;
2158 if constexpr (std::is_same_v<std::decay_t<CovFunc>, SexpatCF>) {
2159 // Pair-local tiles in the repetitive layout: entry
2160 // (c, i; c', j) sits at row c * N + i, column c' * N + j.
2161 // The trace solves K X = dK instead of contracting K^{-1}.
2162 if (grad_geom_active && hutch_trace_W_ == nullptr &&
2163 hssvd_trace_basis_ == nullptr &&
2164 grad_geom_handle->pair_local.valid &&
2165 grad_geom_handle->pair_local.n_conf == num_rep &&
2166 (grad_geom_handle->pair_local.dof + 1) * num_rep ==
2167 Ddim_rows &&
2168#ifdef GPR_LINALG_CHOLMOD
2169 solve_trace &&
2170#else
2171 (solve_trace ||
2172 (invC.rows() == Ddim_rows && invC.cols() == Ddim_rows)) &&
2173#endif
2174 (!accumulate_quad_blocks || b.size() == Ddim_rows)) {
2175 const pairlocal::Weights weights =
2177 grad_geom_theta, grad_geom_handle->pair_local.n_pt);
2178 if (weights.valid) {
2179 pairlocal::TileEvaluator evaluator(
2180 grad_geom_handle->pair_local, weights,
2181 pair_derivative_groups);
2182 if (!pair_derivative_groups.empty())
2183 ++pair_local_grouped_gradients_for_testing_;
2184 const Index_t tile = evaluator.tileSize();
2185 const auto parameter_of = [&](Index_t elt) {
2186 return pair_parameter_indices
2187 [static_cast<std::size_t>(elt)];
2188 };
2189#ifndef GPR_LINALG_CHOLMOD
2190 std::vector<linalg::CompensatedSum> trace(
2191 static_cast<std::size_t>(n_hp));
2192 Eigen::VectorXd part;
2193#endif
2194 std::vector<linalg::CompensatedSum> quad(
2195 static_cast<std::size_t>(n_hp));
2196 Eigen::VectorXd quad_part;
2197 Eigen::VectorXd alpha_i, alpha_j;
2198 EigenMatrix diag;
2199 EigenMatrix deriv_tile;
2200 std::vector<EigenMatrix> solved_dk;
2201 if (solve_trace) {
2202 solved_dk.resize(static_cast<std::size_t>(n_hp));
2203 for (auto& matrix: solved_dk)
2204 matrix =
2205 EigenMatrix::Zero(Ddim_rows, Ddim_rows);
2206 }
2207#ifndef GPR_LINALG_CHOLMOD
2208 const double* W = solve_trace ? nullptr : invC.data();
2209 const Index_t row_stride = num_rep;
2210 const Index_t col_stride = num_rep * Ddim_rows;
2211#endif
2212 const auto scatter_tile = [&](EigenMatrix& dest,
2213 const EigenMatrix& block,
2214 Index_t obs_row,
2215 Index_t obs_col) {
2216 const Index_t channels =
2217 static_cast<Index_t>(block.rows());
2218 const Index_t partners =
2219 static_cast<Index_t>(block.cols());
2220 for (Index_t c = 0; c < channels; ++c) {
2221 for (Index_t cp = 0; cp < partners; ++cp) {
2222 dest(c * num_rep + obs_row,
2223 cp * num_rep + obs_col) = block(c, cp);
2224 }
2225 }
2226 };
2227 for (Index_t obs_i = 0; obs_i < num_rep; ++obs_i) {
2228 for (Index_t obs_j = 0; obs_j <= obs_i; ++obs_j) {
2229 evaluator.prepare(obs_i, obs_j);
2230 const double weight =
2231 obs_i == obs_j ? 1.0 : 2.0;
2232 if (solve_trace) {
2233 for (Index_t elt = 0; elt < n_hp; ++elt) {
2234 const Eigen::Index p =
2235 parameter_of(elt);
2236 if (p < 0) continue;
2237 evaluator.tile(p, deriv_tile);
2238 scatter_tile(solved_dk[elt], deriv_tile,
2239 obs_i, obs_j);
2240 if (obs_i != obs_j) {
2241 const EigenMatrix flipped =
2242 deriv_tile.transpose();
2243 scatter_tile(solved_dk[elt],
2244 flipped, obs_j, obs_i);
2245 }
2246 if (obs_i == obs_j &&
2247 diagonal_nugget > 0.0) {
2248 for (Index_t c = 0; c < tile; ++c) {
2249 const Index_t row =
2250 c * num_rep + obs_i;
2251 solved_dk[elt](row, row) +=
2252 diagonal_nugget *
2253 deriv_tile(c, c);
2254 }
2255 }
2256 }
2257 }
2258#ifndef GPR_LINALG_CHOLMOD
2259 else {
2260 evaluator.contract(
2261 W + obs_i + obs_j * Ddim_rows,
2262 row_stride, col_stride,
2263 /*lower_only=*/false, part);
2264 for (Index_t elt = 0; elt < n_hp; ++elt) {
2265 const Eigen::Index p =
2266 parameter_of(elt);
2267 if (p >= 0)
2268 trace[static_cast<std::size_t>(elt)]
2269 .addProduct(weight, part(p));
2270 }
2271 }
2272#endif
2273 if (accumulate_quad_blocks) {
2274 alpha_i.resize(tile);
2275 alpha_j.resize(tile);
2276 for (Index_t c = 0; c < tile; ++c) {
2277 alpha_i(c) = b(c * num_rep + obs_i);
2278 alpha_j(c) = b(c * num_rep + obs_j);
2279 }
2280 evaluator.quadratic(alpha_i.data(),
2281 alpha_j.data(),
2282 quad_part);
2283 for (Index_t elt = 0; elt < n_hp; ++elt) {
2284 const Eigen::Index p =
2285 parameter_of(elt);
2286 if (p >= 0)
2287 quad[static_cast<std::size_t>(elt)]
2288 .addProduct(weight,
2289 quad_part(p));
2290 }
2291 }
2292 if (obs_i == obs_j && diagonal_nugget > 0.0) {
2293 evaluator.diagonals(diag);
2294 for (Index_t elt = 0; elt < n_hp; ++elt) {
2295 const Eigen::Index p =
2296 parameter_of(elt);
2297 if (p < 0) continue;
2298 for (Index_t c = 0; c < tile; ++c) {
2299 const Index_t row =
2300 c * num_rep + obs_i;
2301 const double value =
2302 diagonal_nugget * diag(p, c);
2303#ifndef GPR_LINALG_CHOLMOD
2304 if (!solve_trace)
2305 trace[static_cast<std::size_t>(
2306 elt)]
2307 .addProduct(invC(row, row),
2308 value);
2309#endif
2310 if (accumulate_quad_blocks ||
2311 !alpha_k_quadratic.empty())
2312 quad[static_cast<std::size_t>(
2313 elt)]
2314 .addProduct(b(row) * value,
2315 b(row));
2316 }
2317 }
2318 }
2319 }
2320 }
2321 if (solve_trace) {
2322 ScopedPhaseTimer inverse_timer(
2324 for (Index_t elt = 0; elt < n_hp; ++elt)
2325 Cdl[elt] += traceInverseProduct(
2326 *trace_factor, solved_dk[elt],
2327 &active_deflation);
2328 }
2329#ifndef GPR_LINALG_CHOLMOD
2330 else {
2331 for (Index_t elt = 0; elt < n_hp; ++elt)
2332 Cdl[elt] += trace[static_cast<std::size_t>(elt)]
2333 .value();
2334 }
2335#endif
2336 for (Index_t elt = 0; elt < n_hp; ++elt)
2337 Bdl[elt] +=
2338 quad[static_cast<std::size_t>(elt)].value();
2339 dense_pair_local_done = true;
2340 }
2341 }
2342 }
2343 if (solve_trace && !dense_pair_local_done) {
2344 dk_trace.resize(static_cast<std::size_t>(n_hp));
2345 for (auto& matrix: dk_trace)
2346 matrix = EigenMatrix::Zero(Ddim_rows, Ddim_rows);
2347 }
2348 if (!dense_pair_local_done)
2349 // Diagonal n=0 contribution: single-shot, no useful
2350 // parallelism.
2351 for (Index_t elt = 0; elt < DKffa.size(); ++elt) {
2353 ind_Ddim, ind_Ddim, 0, 0, DKffa[elt], invC, b, Cdl[elt],
2354 Bdl[elt],
2355 /*transpose_field=*/false, accumulate_quad_blocks,
2356 diagonal_nugget,
2357 solve_trace ? &dk_trace[elt] : nullptr);
2358 }
2359
2360 // OpenMP carve-out for the serial_per_rank=true gradient path.
2361 // Each observation writes its own column of Cdl_slots and
2362 // Bdl_slots. The columns fold in observation order through
2363 // ExactSum, so the gradient does not follow the thread count.
2364 // The if-clause collapses the parallel region to one thread when
2365 // serial_per_rank is false, which keeps the macro correct in the
2366 // distributed builds.
2367 if (!dense_pair_local_done && uDdim.size() > 0 && n_hp > 0) {
2368 EigenMatrix Cdl_slots = EigenMatrix::Zero(n_hp, uDdim.size());
2369 EigenMatrix Bdl_slots = EigenMatrix::Zero(n_hp, uDdim.size());
2370#if defined(GPR_OPENMP_LOCAL_ORACLE) && defined(_OPENMP)
2371#pragma omp parallel if (serial_per_rank) \
2372 firstprivate(x_loc_1, x_loc_2, dims1, dims2) \
2373 shared(Cdl_slots, Bdl_slots, cov_func, invC, b, x, ind_Ddim, uDdim, \
2374 x_loc_0, DKffa, n_hp)
2375#endif
2376 {
2377 std::vector<double> Cdl_col(static_cast<size_t>(n_hp), 0.0);
2378 std::vector<double> Bdl_col(static_cast<size_t>(n_hp), 0.0);
2379 std::vector<FieldMatrixd> Kdf;
2380 std::vector<FieldMatrixd> Kdf2;
2381 std::vector<FieldMatrixd> D;
2382
2383#if defined(GPR_OPENMP_LOCAL_ORACLE) && defined(_OPENMP)
2384#pragma omp for schedule(static)
2385#endif
2386 for (Index_t n = 0; n < uDdim.size(); ++n) {
2387 std::fill(Cdl_col.begin(), Cdl_col.end(), 0.0);
2388 std::fill(Bdl_col.begin(), Bdl_col.end(), 0.0);
2389 dims1(0, 0) = uDdim[n];
2390 extractCoordinatesByIndex(x, ind_Ddim, uDdim[n],
2391 x_loc_1);
2392
2393 bool kdf_geom = false, d_geom = false;
2394 if constexpr (std::is_same_v<std::decay_t<CovFunc>,
2395 SexpatCF>) {
2396 if (grad_geom_active) {
2397 SexpatCF::CrossBlockGeometry kdf_block_scratch;
2398 const auto* kdf_block =
2399 resolve_gradient_geometry(
2400 static_cast<Index_t>(uDdim[n]), 0,
2401 kdf_block_scratch);
2402 if (kdf_block != nullptr) {
2403 kdf_geom =
2404 cov_func
2405 .calculateGradOfCovMatrixWithDerivativesFromGeometry(
2406 *kdf_block,
2407 grad_geom_shared_kernel,
2408 grad_geom_handle
2409 ->shared_distance_neg_per_pt,
2410 grad_geom_theta, Kdf,
2411 parameter_indices);
2412 }
2413 SexpatCF::CrossBlockGeometry d_block_scratch;
2414 const auto* d_block = resolve_gradient_geometry(
2415 static_cast<Index_t>(uDdim[n]),
2416 static_cast<Index_t>(uDdim[n]),
2417 d_block_scratch);
2418 if (d_block != nullptr) {
2419 d_geom =
2420 cov_func
2421 .calculateGradOfCovMatrixWithDerivatives2FromGeometry(
2422 *d_block,
2423 grad_geom_shared_kernel,
2424 grad_geom_handle
2425 ->shared_distance_neg_per_pt,
2426 grad_geom_theta, D,
2427 parameter_indices);
2428 }
2429 }
2430 }
2431 if (!kdf_geom) {
2432 Kdf.clear();
2433 record_live_gradient_geometry();
2434 cov_func.calculateGradOfCovMatrixWithDerivatives(
2435 x_loc_1, x_loc_0, dims1, Kdf);
2436 select_live_gradient_blocks(Kdf);
2437 }
2438 if (!d_geom) {
2439 D.clear();
2440 record_live_gradient_geometry();
2441 cov_func.calculateGradOfCovMatrixWithDerivatives2(
2442 x_loc_1, x_loc_1, dims1, dims1, D);
2443 select_live_gradient_blocks(D);
2444 }
2445
2446 for (Index_t elt = 0; elt < DKffa.size(); ++elt) {
2448 ind_Ddim, ind_Ddim, uDdim[n], 0, Kdf[elt], invC,
2449 b, Cdl_col[elt], Bdl_col[elt],
2450 /*transpose_field=*/false,
2451 accumulate_quad_blocks, diagonal_nugget,
2452 solve_trace ? &dk_trace[elt] : nullptr);
2454 ind_Ddim, ind_Ddim, 0, uDdim[n], Kdf[elt], invC,
2455 b, Cdl_col[elt], Bdl_col[elt],
2456 /*transpose_field=*/true,
2457 accumulate_quad_blocks, diagonal_nugget,
2458 solve_trace ? &dk_trace[elt] : nullptr);
2460 ind_Ddim, ind_Ddim, uDdim[n], uDdim[n], D[elt],
2461 invC, b, Cdl_col[elt], Bdl_col[elt],
2462 /*transpose_field=*/false,
2463 accumulate_quad_blocks, diagonal_nugget,
2464 solve_trace ? &dk_trace[elt] : nullptr);
2465 }
2466
2467 for (Index_t m = n + 1; m < uDdim.size(); ++m) {
2468 dims2(0, 0) = uDdim[m];
2469 extractCoordinatesByIndex(x, ind_Ddim, uDdim[m],
2470 x_loc_2);
2471 bool kdf2_geom = false;
2472 if constexpr (std::is_same_v<std::decay_t<CovFunc>,
2473 SexpatCF>) {
2474 if (grad_geom_active) {
2475 SexpatCF::CrossBlockGeometry
2476 kdf2_block_scratch;
2477 const auto* kdf2_block =
2478 resolve_gradient_geometry(
2479 static_cast<Index_t>(uDdim[n]),
2480 static_cast<Index_t>(uDdim[m]),
2481 kdf2_block_scratch);
2482 if (kdf2_block != nullptr) {
2483 kdf2_geom =
2484 cov_func.calculateGradOfCovMatrixWithDerivatives2FromGeometry(
2485 *kdf2_block,
2486 grad_geom_shared_kernel,
2487 grad_geom_handle
2488 ->shared_distance_neg_per_pt,
2489 grad_geom_theta, Kdf2,
2490 parameter_indices);
2491 }
2492 }
2493 }
2494 if (!kdf2_geom) {
2495 Kdf2.clear();
2496 record_live_gradient_geometry();
2497 cov_func
2498 .calculateGradOfCovMatrixWithDerivatives2(
2499 x_loc_1, x_loc_2, dims1, dims2, Kdf2);
2500 select_live_gradient_blocks(Kdf2);
2501 }
2502
2503 for (Index_t elt = 0; elt < DKffa.size(); ++elt) {
2505 ind_Ddim, ind_Ddim, uDdim[n], uDdim[m],
2506 Kdf2[elt], invC, b, Cdl_col[elt],
2507 Bdl_col[elt], /*transpose_field=*/false,
2508 accumulate_quad_blocks, diagonal_nugget,
2509 solve_trace ? &dk_trace[elt] : nullptr);
2511 ind_Ddim, ind_Ddim, uDdim[m], uDdim[n],
2512 Kdf2[elt], invC, b, Cdl_col[elt],
2513 Bdl_col[elt], /*transpose_field=*/true,
2514 accumulate_quad_blocks, diagonal_nugget,
2515 solve_trace ? &dk_trace[elt] : nullptr);
2516 }
2517 }
2518
2519 for (Index_t elt = 0; elt < n_hp; ++elt) {
2520 Cdl_slots(elt, n) = Cdl_col[elt];
2521 Bdl_slots(elt, n) = Bdl_col[elt];
2522 }
2523 }
2524 }
2525 for (Index_t elt = 0; elt < n_hp; ++elt) {
2526 linalg::ExactSum c_sum, b_sum;
2527 c_sum.add(Cdl[elt]);
2528 b_sum.add(Bdl[elt]);
2529 for (Index_t n = 0; n < uDdim.size(); ++n) {
2530 c_sum.add(Cdl_slots(elt, n));
2531 b_sum.add(Bdl_slots(elt, n));
2532 }
2533 Cdl[elt] = c_sum.value();
2534 Bdl[elt] = b_sum.value();
2535 }
2536 }
2537 if (solve_trace && !dense_pair_local_done) {
2538 ScopedPhaseTimer inverse_timer(
2540 for (Index_t elt = 0; elt < n_hp; ++elt)
2541 Cdl[elt] += traceInverseProduct(
2542 *trace_factor, dk_trace[elt], &active_deflation);
2543 }
2544 }
2545
2546 // Evaluate the gradient with respect to covariance function parameters.
2547 {
2548#ifdef GPR_LINALG_SCALAPACK
2549 if (use_cached_inverse_trace && n_hp > 0) {
2550 // Exact accumulators merge by integer addition, so the
2551 // reduced trace is the correctly rounded exact sum for any
2552 // partition of the entries over ranks.
2553 if (_mpi_np > 1)
2554 linalg::exact_sum_bcast(cached_inverse_trace.data(),
2555 static_cast<int>(n_hp),
2556 mpiContext());
2557 for (Index_t elt = 0; elt < n_hp; ++elt)
2558 Cdl[elt] = cached_inverse_trace[elt].value();
2559 if (std::getenv("GPR_GRADIENT_PRINT") != nullptr) {
2560 std::fprintf(stderr, "[gradient-final] n=%ld",
2561 static_cast<long>(Ddim_rows));
2562 const Eigen::VectorXd theta_now =
2563 cov_func.combineParameters();
2564 for (Eigen::Index k = 0; k < theta_now.size(); ++k)
2565 std::fprintf(stderr, " w[%ld]=%.17g",
2566 static_cast<long>(k), theta_now(k));
2567 for (Index_t elt = 0; elt < n_hp; ++elt)
2568 std::fprintf(stderr, " C[%ld]=%.17g B[%ld]=%.17g",
2569 static_cast<long>(elt), Cdl[elt],
2570 static_cast<long>(elt), Bdl[elt]);
2571 std::fprintf(stderr, "\n");
2572 }
2573 }
2574 // The owned trace, quadratic and nugget terms are exact
2575 // accumulators in every distributed mode; their merge across
2576 // ranks is an integer sum, so the gradient is the correctly
2577 // rounded value for any partition of the entries.
2578 if (!serial_per_rank && n_hp > 0) {
2579 if (_mpi_np > 1) {
2580 backend().exact_sum_bcast(Cdist.data(),
2581 static_cast<int>(n_hp));
2582 backend().exact_sum_bcast(Bdist.data(),
2583 static_cast<int>(n_hp));
2584 backend().exact_sum_bcast(Bex.data(),
2585 static_cast<int>(n_hp));
2586 }
2587 for (Index_t elt = 0; elt < n_hp; ++elt) {
2588 if (!use_cached_inverse_trace)
2589 Cdl[elt] += Cdist[elt].value();
2590 Bdl[elt] += Bdist[elt].value() + Bex[elt].value();
2591 }
2592 } else if (n_hp > 0) {
2593 for (Index_t elt = 0; elt < n_hp; ++elt)
2594 Bdl[elt] += Bex[elt].value();
2595 }
2596#endif
2597
2598 // Hutchinson trace normalisation: the block walk accumulated the
2599 // un-normalised estimator sum_j w_j^T dK z_j into Cdl; divide by
2600 // the probe count m to obtain the tr(K^-1 dK) estimate. Only the
2601 // trace term is affected; the quadratic (alpha-K) term is exact.
2602 const double hutch_inv_m =
2603 hutch_trace_W_ != nullptr
2604 ? 1.0 / static_cast<double>(hutch_trace_W_->cols())
2605 : 1.0;
2606 for (Index_t elt = 0; elt < n_hp; ++elt) {
2607 const double quad_term =
2608 alpha_k_quadratic.empty()
2609 ? Bdl[elt]
2610 : alpha_k_quadratic[static_cast<size_t>(elt)] +
2611 Bdl[elt];
2612 *(gdata.data() + elt) =
2613 0.5 * (Cdl[elt] * hutch_inv_m - quad_term);
2614 }
2615 }
2616 if (parameter_indices != nullptr) {
2617 FieldMatrixd full_gradient =
2618 FieldMatrixd::Zero(1, gprior_cf.size());
2619 for (std::size_t i = 0; i < parameter_indices->size(); ++i)
2620 full_gradient.data()[(*parameter_indices)[i]] = gdata.data()[i];
2621 gdata = std::move(full_gradient);
2622 }
2623 gpr::field::appendRows(gprior, gprior_cf);
2624 }
2625}
2626
2628 const EigenMatrix& x, const Eigen::VectorXd& ind_Ddim,
2629 const Eigen::VectorXd& uDdim, const Eigen::VectorXd& direction,
2630 EigenMatrix& first, EigenMatrix& second, bool serial_per_rank) const
2631{
2632#ifndef GPR_LINALG_SCALAPACK
2633 (void)serial_per_rank;
2634#endif
2635 FieldMatrixd x_loc_0;
2636 FieldMatrixIdx dims1, dims2;
2637 FieldMatrixd block_first, block_second;
2638 const Index_t number_of_rep_indices =
2640
2641 x_loc_0.resize(number_of_rep_indices, static_cast<Index_t>(x.cols()) + 1);
2642 x_loc_0.setZero();
2643 dims1.resize(1, 1);
2644 dims2.resize(1, 1);
2645
2646 std::vector<FieldMatrixd> x_loc_by_udim(
2647 static_cast<std::size_t>(uDdim.size()));
2648 for (Index_t n = 0; n < uDdim.size(); ++n) {
2649 auto& x_loc = x_loc_by_udim[static_cast<std::size_t>(n)];
2650 x_loc.resize(number_of_rep_indices, static_cast<Index_t>(x.cols()) + 1);
2651 x_loc.setZero();
2652 extractCoordinatesByIndex(x, ind_Ddim, uDdim[n], x_loc);
2653 }
2654
2655 first.resize(x.rows(), x.rows());
2656 first.setZero();
2657 second.resize(x.rows(), x.rows());
2658 second.setZero();
2659
2660#ifdef GPR_LINALG_SCALAPACK
2661 int _mpi_rank = 0, _mpi_np = 1;
2662 if (!serial_per_rank) {
2663 auto& _mpi_st = backend().distributed();
2664 _mpi_rank = _mpi_st.myrank();
2665 _mpi_np = _mpi_st.nprocs();
2666 }
2667#else
2668 const int _mpi_rank = 0, _mpi_np = 1;
2669#endif
2670 int _mpi_blk = 0;
2671
2672 extractCoordinatesByIndex(x, ind_Ddim, 0, x_loc_0);
2673 if (ownsBlock(_mpi_blk++, _mpi_rank, _mpi_np, serial_per_rank)) {
2674 sexpat_cov_func->calculateDirectionalCovarianceMatrix(
2675 x_loc_0, x_loc_0, direction, block_first, block_second);
2676 if (block_first.size() != 0) {
2677 assignBlockToMatrix(ind_Ddim, ind_Ddim, 0, 0, block_first, first);
2678 assignBlockToMatrix(ind_Ddim, ind_Ddim, 0, 0, block_second, second);
2679 }
2680 }
2681
2682 for (Index_t n = 0; n < uDdim.size(); ++n) {
2683 dims1(0, 0) = uDdim[n];
2684 auto& x_loc_1 = x_loc_by_udim[static_cast<std::size_t>(n)];
2685
2686 if (ownsBlock(_mpi_blk++, _mpi_rank, _mpi_np, serial_per_rank)) {
2688 ->calculateDirectionalCovarianceMatrixWithDerivatives(
2689 x_loc_1, x_loc_0, dims1, direction, block_first,
2690 block_second);
2691 if (block_first.size() != 0) {
2692 assignBlockToMatrix(ind_Ddim, ind_Ddim, uDdim[n], 0,
2693 block_first, first);
2694 assignBlockToMatrix(ind_Ddim, ind_Ddim, 0, uDdim[n],
2695 block_first, first, true);
2696 assignBlockToMatrix(ind_Ddim, ind_Ddim, uDdim[n], 0,
2697 block_second, second);
2698 assignBlockToMatrix(ind_Ddim, ind_Ddim, 0, uDdim[n],
2699 block_second, second, true);
2700 }
2701
2703 ->calculateDirectionalCovarianceMatrixWithDerivatives2(
2704 x_loc_1, x_loc_1, dims1, dims1, direction, block_first,
2705 block_second);
2706 if (block_first.size() != 0) {
2707 assignBlockToMatrix(ind_Ddim, ind_Ddim, uDdim[n], uDdim[n],
2708 block_first, first);
2709 assignBlockToMatrix(ind_Ddim, ind_Ddim, uDdim[n], uDdim[n],
2710 block_second, second);
2711 }
2712 }
2713
2714 for (Index_t m = n + 1; m < uDdim.size(); ++m) {
2715 if (ownsBlock(_mpi_blk++, _mpi_rank, _mpi_np, serial_per_rank)) {
2716 dims2(0, 0) = uDdim[m];
2717 auto& x_loc_2 = x_loc_by_udim[static_cast<std::size_t>(m)];
2719 ->calculateDirectionalCovarianceMatrixWithDerivatives2(
2720 x_loc_1, x_loc_2, dims1, dims2, direction, block_first,
2721 block_second);
2722 if (block_first.size() != 0) {
2723 assignBlockToMatrix(ind_Ddim, ind_Ddim, uDdim[n], uDdim[m],
2724 block_first, first);
2725 assignBlockToMatrix(ind_Ddim, ind_Ddim, uDdim[m], uDdim[n],
2726 block_first, first, true);
2727 assignBlockToMatrix(ind_Ddim, ind_Ddim, uDdim[n], uDdim[m],
2728 block_second, second);
2729 assignBlockToMatrix(ind_Ddim, ind_Ddim, uDdim[m], uDdim[n],
2730 block_second, second, true);
2731 }
2732 }
2733 }
2734 }
2735
2736#ifdef GPR_LINALG_SCALAPACK
2737 if (!serial_per_rank && _mpi_np > 1) {
2738 backend().ordered_sum_bcast(first.data(),
2739 static_cast<int>(first.size()));
2740 backend().ordered_sum_bcast(second.data(),
2741 static_cast<int>(second.size()));
2742 }
2743#endif
2744
2745 applyKernelNugget(first, x.rows());
2746 applyKernelNugget(second, x.rows());
2747
2748 const Eigen::Index n_cov_params = covarianceParameterCount();
2749 if (direction.size() > n_cov_params) {
2750 const double noise = likelihoodNoiseVariance();
2751 if (noise > 0.0) {
2752 const double noise_dir = direction(direction.size() - 1);
2753 first.diagonal().array() += noise * noise_dir;
2754 second.diagonal().array() += noise * noise_dir * noise_dir;
2755 }
2756 }
2757}
2758
2759inline bool
2761 const TrainingKernelGeometry& geom, const EigenMatrix& x,
2762 const Eigen::VectorXd& ind_Ddim, const Eigen::VectorXd& uDdim,
2763 const Eigen::VectorXd& direction, EigenMatrix& first, EigenMatrix& second,
2764 bool serial_per_rank) const
2765{
2766#ifndef GPR_LINALG_SCALAPACK
2767 (void)serial_per_rank;
2768#endif
2769 first.resize(0, 0);
2770 second.resize(0, 0);
2771#ifdef GPR_LINALG_SCALAPACK
2772 int mpi_rank = 0, mpi_np = 1;
2773 if (!serial_per_rank) {
2774 auto& mpi_st = backend().distributed();
2775 mpi_st.initialize();
2776 mpi_rank = mpi_st.myrank();
2777 mpi_np = mpi_st.nprocs();
2778 }
2779#else
2780 const int mpi_rank = 0, mpi_np = 1;
2781#endif
2782
2783 [[maybe_unused]] bool pair_tiles_used = false;
2784 const bool local_ok = [&]() {
2785 if (!geom.valid || sexpat_cov_func == nullptr) return false;
2786 if (geom.n != x.rows() || ind_Ddim.size() != x.rows()) return false;
2787 if (uDdim.size() != geom.uDdim.size()) return false;
2788 for (Eigen::Index i = 0; i < uDdim.size(); ++i) {
2789 if (static_cast<Index_t>(uDdim(i)) !=
2790 static_cast<Index_t>(geom.uDdim(i))) {
2791 return false;
2792 }
2793 }
2794
2795 const auto local = tryPairLocalDirectionalCovariance(
2796 geom, ind_Ddim, direction, first, second, mpi_rank, mpi_np);
2797 if (local.has_value()) {
2798 pair_tiles_used = true;
2799 return *local;
2800 }
2801
2802 const Eigen::VectorXd theta = sexpat_cov_func->combineParameters();
2803 FieldMatrixd shared_kernel;
2804 if (!sexpat_cov_func->buildSharedKernel(geom.shared_distance_neg_per_pt,
2805 theta, shared_kernel)) {
2806 return false;
2807 }
2808
2809 first.resize(x.rows(), x.rows());
2810 first.setZero();
2811 second.resize(x.rows(), x.rows());
2812 second.setZero();
2813
2814 std::vector<std::size_t> owned;
2815 owned.reserve(geom.blocks.size());
2816 for (std::size_t index = 0; index < geom.blocks.size(); ++index) {
2817 if (ownsBlock(static_cast<long>(index), mpi_rank, mpi_np,
2818 serial_per_rank))
2819 owned.push_back(index);
2820 }
2821 std::vector<uint8_t> block_ok(owned.size(), 1);
2822 std::atomic<std::size_t> resolved{0};
2823 const std::size_t workers = std::max<std::size_t>(
2824 1, std::min(owned.size(), static_cast<std::size_t>(
2825 backend().local().concurrency())));
2826 if (!owned.empty()) {
2827 backend().local().forEach(workers, [&](std::size_t worker) {
2828 FieldMatrixd block_first, block_second, block_kernel;
2829 SexpatCF::CrossBlockGeometry streamed_scratch;
2830 for (std::size_t task = worker; task < owned.size();
2831 task += workers) {
2832 const auto& block = geom.blocks[owned[task]];
2833 const SexpatCF::CrossBlockGeometry* block_geometry =
2835 block, streamed_scratch);
2836 if (block_geometry == nullptr) {
2837 block_ok[task] = 0;
2838 return;
2839 }
2840 resolved.fetch_add(1, std::memory_order_relaxed);
2841 const FieldMatrixd* kernel = &shared_kernel;
2842 const std::vector<FieldMatrixd>* distances =
2844 if (!geom.shared_coordinates &&
2845 block.derivative_options != 0) {
2846 distances = &block_geometry->distance;
2847 if (!sexpat_cov_func->buildSharedKernel(
2848 *distances, theta, block_kernel)) {
2849 block_ok[task] = 0;
2850 return;
2851 }
2852 kernel = &block_kernel;
2853 }
2854
2855 bool ok = false;
2856 if (block.derivative_options == 0) {
2857 ok =
2859 ->calculateDirectionalCovarianceMatrixFromGeometry(
2860 *kernel, *distances, theta, direction,
2861 block_first, block_second);
2862 } else if (block.derivative_options ==
2864 ok =
2866 ->calculateDirectionalCovarianceMatrixWithDerivativesFromGeometry(
2867 *block_geometry, *kernel, *distances, theta,
2868 direction, block_first, block_second);
2869 } else {
2870 ok =
2872 ->calculateDirectionalCovarianceMatrixWithDerivatives2FromGeometry(
2873 *block_geometry, *kernel, *distances, theta,
2874 direction, block_first, block_second);
2875 }
2876 if (!ok || block_first.size() == 0 ||
2877 block_second.size() == 0) {
2878 block_ok[task] = 0;
2879 return;
2880 }
2881
2882 if (block.block_n == 0 && block.block_m == 0 &&
2883 block.derivative_options == 0) {
2884 if (block_first.rows() > first.rows() ||
2885 block_first.cols() > first.cols() ||
2886 block_second.rows() > second.rows() ||
2887 block_second.cols() > second.cols()) {
2888 block_ok[task] = 0;
2889 return;
2890 }
2891 first.block(0, 0, block_first.rows(),
2892 block_first.cols()) = block_first;
2893 second.block(0, 0, block_second.rows(),
2894 block_second.cols()) = block_second;
2895 } else if (block.block_n != 0 && block.block_m == 0) {
2896 assignBlockToMatrix(ind_Ddim, ind_Ddim, block.block_n,
2897 0, block_first, first);
2898 assignBlockToMatrix(ind_Ddim, ind_Ddim, 0,
2899 block.block_n, block_first, first,
2900 /*transpose_field=*/true);
2901 assignBlockToMatrix(ind_Ddim, ind_Ddim, block.block_n,
2902 0, block_second, second);
2903 assignBlockToMatrix(ind_Ddim, ind_Ddim, 0,
2904 block.block_n, block_second, second,
2905 /*transpose_field=*/true);
2906 } else if (block.block_n == block.block_m) {
2907 assignBlockToMatrix(ind_Ddim, ind_Ddim, block.block_n,
2908 block.block_n, block_first, first);
2909 assignBlockToMatrix(ind_Ddim, ind_Ddim, block.block_n,
2910 block.block_n, block_second,
2911 second);
2912 } else {
2913 assignBlockToMatrix(ind_Ddim, ind_Ddim, block.block_n,
2914 block.block_m, block_first, first);
2915 assignBlockToMatrix(ind_Ddim, ind_Ddim, block.block_m,
2916 block.block_n, block_first, first,
2917 /*transpose_field=*/true);
2918 assignBlockToMatrix(ind_Ddim, ind_Ddim, block.block_n,
2919 block.block_m, block_second,
2920 second);
2921 assignBlockToMatrix(ind_Ddim, ind_Ddim, block.block_m,
2922 block.block_n, block_second, second,
2923 /*transpose_field=*/true);
2924 }
2925 }
2926 });
2927 }
2928 geom.directional_geometry_blocks_for_testing += resolved.load();
2929 if (std::find(block_ok.begin(), block_ok.end(), 0) != block_ok.end())
2930 return false;
2931
2932 return true;
2933 }();
2934 bool failed = !local_ok;
2935#ifdef GPR_LINALG_SCALAPACK
2936 if (!serial_per_rank && mpi_np > 1) {
2937 int state[3] = {failed, pair_tiles_used, !pair_tiles_used};
2938 MPI_Allreduce(MPI_IN_PLACE, state, 3, MPI_INT, MPI_MAX,
2939 backend().distributed().world_comm());
2940 failed = state[0] || (state[1] && state[2]);
2941 }
2942#endif
2943 // All ranks agree on rejection before entering covariance collectives.
2944 if (failed) {
2945 first.resize(0, 0);
2946 second.resize(0, 0);
2947 return false;
2948 }
2949
2950#ifdef GPR_LINALG_SCALAPACK
2951 if (!serial_per_rank && mpi_np > 1) {
2952 if (pair_tiles_used) {
2953 linalg::replicate_owned_values(first.data(), first.size(),
2954 backend().mpi());
2955 linalg::replicate_owned_values(second.data(), second.size(),
2956 backend().mpi());
2957 } else {
2958 backend().ordered_sum_bcast(first.data(),
2959 static_cast<int>(first.size()));
2960 backend().ordered_sum_bcast(second.data(),
2961 static_cast<int>(second.size()));
2962 }
2963 }
2964#endif
2965
2966 applyKernelNugget(first, x.rows());
2967 applyKernelNugget(second, x.rows());
2968
2969 const Eigen::Index n_cov_params = covarianceParameterCount();
2970 if (direction.size() > n_cov_params) {
2971 const double noise = likelihoodNoiseVariance();
2972 if (noise > 0.0) {
2973 const double noise_dir = direction(direction.size() - 1);
2974 first.diagonal().array() += noise * noise_dir;
2975 second.diagonal().array() += noise * noise_dir * noise_dir;
2976 }
2977 }
2978 return true;
2979}
2980
2982{
2983 jitter_sigma2 = value;
2984 ++laplace_model_revision_;
2985}
2986
2988{
2989 sigma2 = parameters.sigma2;
2990 theta_includes_likelihood_noise_ = false;
2991 jitter_sigma2 = parameters.jitter_sigma2;
2992 optimization_alg = parameters.optimization_alg;
2993 use_ls_prior_ = parameters.ls_prior;
2994 detail::validateRigidNullDeflationConfiguration(
2996 principled_nugget_ = parameters.principled_nugget;
2997 kappa_max_ = parameters.kappa_max;
2998 scg_opt_settings.map_prior_weight_mode = parameters.map_prior_weight_mode;
2999 scg_opt_settings.map_use_configured_magn_prior =
3000 parameters.map_use_configured_priors;
3001 scg_opt_settings.map_use_configured_lengthscale_prior =
3002 parameters.map_use_configured_priors;
3003 hyperparameter_optimization_mode_ =
3004 (parameters.optimization_alg == INLA_opt)
3007 ++laplace_model_revision_;
3008}
3009
3011{
3012 return *lik_gaussian;
3013}
3014
3016{
3017 return *lik_gaussian;
3018}
3019
3024
3026 const
3027{
3028 return *sexpat_cov_func;
3029}
3030
3032{
3033 return *const_cov_fun;
3034}
3035
3036inline const ConstantCF&
3038{
3039 return *const_cov_fun;
3040}
3041
3043{
3044 return num_of_potential_calls;
3045}
3046
3047} /* namespace gpr */
3048
3049#endif /* GPR_ML_GAUSSIANPROCESSREGRESSION_INL_ */
Linear algebra abstraction layer for GPR hot-path operations.
@ x
Definition Enums.h:28
@ INLA_opt
Definition Enums.h:30
@ D1
Definition Enums.h:19
@ D12
Definition Enums.h:21
@ D2
Definition Enums.h:20
Exact floating-point accumulator (Kulisch long accumulator).
int numroc_(const int *n, const int *nb, const int *iproc, const int *isrcproc, const int *nprocs)
void Cpdgemr2d(int m, int n, const double *a, int ia, int ja, const int *desca, double *b, int ib, int jb, const int *descb, int ictxt)
void descinit_(int *desc, const int *m, const int *n, const int *mb, const int *nb, const int *irsrc, const int *icsrc, const int *ictxt, const int *lld, int *info)
Constant covariance function.
Definition ConstantCF.h:21
linalg::BackendContext & backend() const
void setParameters(const GPRSetup &parameters)
Set parameters of the GPR model.
Eigen::VectorXd unpermuteTrainingVector(const Eigen::VectorXd &input) const
std::optional< bool > tryPairLocalDirectionalCovariance(const TrainingKernelGeometry &geom, const Eigen::VectorXd &indices, const Eigen::VectorXd &direction, EigenMatrix &first, EigenMatrix &second, int rank=0, int ranks=1) const
bool assembleCompositeJointCovarianceDerivatives(const EigenMatrix &x, const Eigen::VectorXd &indices, SexpatCF &covariance, std::vector< EigenMatrix > &derivatives) const
detail::RigidDeflationState rigid_deflation_
void assignBlockToMatrix(const Eigen::VectorXd &ind_Ddim1, const Eigen::VectorXd &ind_Ddim2, const Index_t row_val, const Index_t col_val, const FieldMatrixd &field, EigenMatrix &matrix, bool transpose_field=false) const
Assign field to matrix according to indices form ind_Ddim1 and ind_Ddim2.
void setJitterSigma2(double value)
Set sigma2 jitter value.
bool assembleCompositeJointCrossCovariance(const EigenMatrix &left, const EigenMatrix &right, const Eigen::VectorXd &left_indices, const Eigen::VectorXd &right_indices, SexpatCF &covariance, EigenMatrix &result) const
bool assembleDirectionalCovarianceDerivativesFromGeometry(const TrainingKernelGeometry &geom, const EigenMatrix &x, const Eigen::VectorXd &ind_Ddim, const Eigen::VectorXd &uDdim, const Eigen::VectorXd &direction, EigenMatrix &first, EigenMatrix &second, bool serial_per_rank=false) const
void accumulateCrossCovarianceMatVecLocal(const EigenMatrix &x1, const EigenMatrix &x2, const Eigen::VectorXd &ind_Ddim, const Eigen::VectorXd &uDdim, const Eigen::VectorXd &ind_Ddim2, const Eigen::VectorXd &uDdim2, CovFunc &cov_func, const Eigen::VectorXd &weights, Eigen::VectorXd &output, bool do_reduce=true, bool select_prediction_product=false) const
Accumulate local K(x1, x2)^T * weights contributions without materializing the full cross-covariance ...
std::unique_ptr< SexpatCF > sexpat_cov_func
void accumulateBlockContribution(const Eigen::VectorXd &ind_Ddim1, const Eigen::VectorXd &ind_Ddim2, const Index_t row_val, const Index_t col_val, const FieldMatrixd &field, const EigenMatrix &invC, const Eigen::VectorXd &b, double &trace_accum, double &quad_accum, bool transpose_field=false, bool accumulate_quad=true, double diagonal_nugget=0.0, EigenMatrix *trace_sink=nullptr)
Accumulate trace and quadratic-form contributions from one block.
bool assembleCompositeJointCovariance(const EigenMatrix &x, const Eigen::VectorXd &indices, SexpatCF &covariance, EigenMatrix &result) const
double traceInverseProduct(const EigenMatrix &factor, const EigenMatrix &observation_order, const detail::RigidDeflationState *deflation_override=nullptr) const
tr(K^{-1} A) through the training factor. A is in observation order.
void extractCoordinatesByIndex(const EigenMatrix &x, const Eigen::VectorXd &ind_Ddim, const Index_t ind, FieldMatrixd &x_loc) const
Extract coordinates from x using value ind from ind_Ddim.
void assembleDirectionalCovarianceDerivatives(const EigenMatrix &x, const Eigen::VectorXd &ind_Ddim, const Eigen::VectorXd &uDdim, const Eigen::VectorXd &direction, EigenMatrix &first, EigenMatrix &second, bool serial_per_rank=false) const
Assemble the directional first and second derivatives of the training covariance matrix for the optim...
Index_t getNumberOfRepetitiveIndices(const Eigen::VectorXd &ind_Ddim) const
Count number of the first repetitive indices in ind_Ddim .
void evaluateTrainingCovarianceMatrix(const EigenMatrix &x, const Eigen::VectorXd &x_ind, EigenMatrix &cov_matrix, bool serial_per_rank=false, bool include_constant=true, bool include_noise=true)
Evaluate training covariance matrix (gp_cov + noise covariance).
bool lengthScaleTiesActive(Eigen::Index length_count) const noexcept
Gaussian noise with variance.
Definition LikGaussian.h:29
Pair-type inverse-distance squared-exponential primitive.
Definition SexpatCF.h:74
const LocalExecutor & local() const noexcept
void forEach(std::size_t count, Operation &&operation, Grain grain=Grain::Fine) const
void check(int status)
Definition gpridge.hpp:323
void appendRows(Eigen::PlainObjectBase< Derived > &mat, const Eigen::PlainObjectBase< Derived > &other)
Kokkos::IndexType< std::size_t > Index
void requireWorkspaceBudget(DistributedState &st, const char *what, std::int64_t needed, AvailableMemory available)
double evaluateStoredProduct(const double *left, const double *right, int length, ProductMode mode)
ProductMode productMode()
void replicate_owned_values(double *data, std::size_t count, const MpiContext &context)
bool unconstrainedLibraryReductions() noexcept
void exact_sum_bcast(ExactSum *sums, int count, const MpiContext &context)
double trace_solve_product(const EigenMatrix &L, const EigenMatrix &A)
AvailableMemory availableHostBudget()
bool cholesky(const EigenMatrix &C, EigenMatrix &L)
Cholesky decomposition (LAPACK equivalent: dpotrf).
Weights weightsFromLogParameters(const Eigen::VectorXd &theta, Eigen::Index n_pt)
Gaussian-process regression, kernels, priors, and the searches that run on the surrogate.
Definition Macros.h:16
const SexpatCF::CrossBlockGeometry * resolveTrainingBlockGeometry(const SexpatCF &covariance, const TrainingKernelGeometry &geom, const TrainingKernelGeometryBlock &block, SexpatCF::CrossBlockGeometry &scratch)
Eigen::Matrix< Index_t, EigenDynamic, EigenDynamic, FieldMatrixStorage > FieldMatrixIdx
Definition Macros.h:29
uint32_t Index_t
Definition Macros.h:17
EigenMatrix permuteSymmetricMatrix(const EigenMatrix &input, const StructuredPermutation &p)
Eigen::Matrix< double, EigenDynamic, EigenDynamic, EigenMatrixStorage > EigenMatrix
Definition Macros.h:20
bool buildCrossBlockDerivativesFactored(const FactoredTrainingGeometry &factors, Index_t block_n, Index_t block_m, uint8_t derivative_options, SexpatCF::CrossBlockGeometry &out)
bool ownsBlock(long block_idx, int rank, int nprocs, bool serial_per_rank)
Eigen::Matrix< double, EigenDynamic, EigenDynamic, FieldMatrixStorage > FieldMatrixd
Definition Macros.h:25
bool ownsBlockIfReduce(long block_idx, int rank, int nprocs, bool do_reduce)
Structure of GPR properties.
Definition Structures.h:105
uint8_t optimization_alg
Definition Structures.h:110
bool map_use_configured_priors
Definition Structures.h:128
double kappa_max
Definition Structures.h:121
bool principled_nugget
Definition Structures.h:118
double jitter_sigma2
Definition Structures.h:107
MapPriorWeightMode map_prior_weight_mode
Definition Structures.h:124
static double gradient_inverse_seconds
static double gradient_seconds
static int gradient_count
static double gradient_accumulate_seconds
std::vector< FieldMatrixd > distance
Definition SexpatCF.h:278
bool shared_coordinates
Channel blocks carry the same Cartesian positions.
std::vector< TrainingKernelGeometryBlock > blocks
std::vector< FieldMatrixd > shared_distance_neg_per_pt