13#ifndef GPR_ML_GAUSSIANPROCESSREGRESSION_INL_
14#define GPR_ML_GAUSSIANPROCESSREGRESSION_INL_
28#ifdef GPR_LINALG_SCALAPACK
41#if defined(GPR_OPENMP_LOCAL_ORACLE) && defined(_OPENMP)
49 const Eigen::VectorXd& ind_Ddim)
const
52 Index_t first_elt = ind_Ddim(0);
54 for (
Index_t n = 1; n < ind_Ddim.rows(); ++n) {
55 if (ind_Ddim(n) == first_elt)
64template <
typename CovFunc>
65GaussianProcessRegression::CovarianceAssemblyOwnership
66GaussianProcessRegression::applyCovarianceFunction(
68 const Eigen::VectorXd& uDdim, CovFunc& cov_func,
EigenMatrix& Ktemp,
69 bool do_reduce,
bool serial_per_rank)
const
71 if constexpr (std::is_same<typename std::decay<CovFunc>::type,
74 return CovarianceAssemblyOwnership::Complete;
79 std::vector<FieldMatrixd> Kdf;
80 std::vector<FieldMatrixd> Kdf2;
81 std::vector<FieldMatrixd> D;
86 x_loc_0.resize(number_of_rep_indices, (
Index_t)
x.cols() + 1);
88 x_loc_1.resize(number_of_rep_indices, (
Index_t)
x.cols() + 1);
90 x_loc_2.resize(number_of_rep_indices, (
Index_t)
x.cols() + 1);
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);
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);
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];
123 Ktemp.resize(
x.rows(),
x.rows());
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();
131 const int _mpi_rank = 0, _mpi_np = 1;
143 std::atomic<int> _mpi_blk{0};
144 const bool assembly_team = serial_per_rank || _mpi_np == 1;
148 if (
ownsBlock(_mpi_blk.fetch_add(1), _mpi_rank, _mpi_np,
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;
158#if (defined(GPR_OPENMP_LOCAL_ORACLE) || defined(USE_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)
166 for (
Index_t n = 0; n < uDdim.size(); ++n) {
167 dims1(0, 0) = uDdim[n];
170 if (
ownsBlock(_mpi_blk.fetch_add(1), _mpi_rank, _mpi_np,
172 cov_func.ginput4(x_loc_1, x_loc_0, dims1, Kdf);
173 cov_func.ginput2(x_loc_1, x_loc_1, dims1, D);
183 for (
Index_t m = n + 1; m < uDdim.size(); ++m) {
184 if (
ownsBlock(_mpi_blk.fetch_add(1), _mpi_rank, _mpi_np,
186 dims2(0, 0) = uDdim[m];
188 cov_func.ginput3(x_loc_1, x_loc_2, dims1, dims2, Kdf2);
193 Kdf2[0], Ktemp,
true);
198#ifdef GPR_LINALG_SCALAPACK
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()));
210 return CovarianceAssemblyOwnership::Complete;
213template <
typename CovFunc>
214void GaussianProcessRegression::applyCrossCovarianceFunction(
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
220 if constexpr (std::is_same<typename std::decay<CovFunc>::type,
228#ifndef GPR_LINALG_SCALAPACK
241 std::vector<FieldMatrixd> Kdf(1), Kdf2(1);
243 Ktemp.resize(x1.rows(), x2.rows());
249 Eigen::Map<const Eigen::ArrayXd> ind_Ddim_copy(ind_Ddim.data(),
251 ind_Ddim2_copy(ind_Ddim2.data(), ind_Ddim2.size());
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();
258 const int _mpi_rank = 0, _mpi_np = 1;
262 x1_loc_0.resize((
Index_t)(ind_Ddim_copy == 0).count(),
265 x2_loc_0.resize((
Index_t)(ind_Ddim2_copy == 0).count(),
273 if ((ind_Ddim_copy == 0).count() > 0 && (ind_Ddim2_copy == 0).count() > 0) {
275 cov_func.calculateCovarianceMatrix(x1_loc_0, x2_loc_0, C_temp);
281 if ((ind_Ddim_copy == 0).count() > 0) {
282 for (
Index_t i = 0; i < uDdim2.size(); ++i) {
284 dims2(0, 0) = uDdim2[i];
285 x2_loc_1.resize((
Index_t)(ind_Ddim2_copy == uDdim2[i]).count(),
289 cov_func.ginput4(x2_loc_1, x1_loc_0, dims2, Kdf);
297 if ((ind_Ddim2_copy == 0).count() > 0) {
298 for (
Index_t i = 0; i < uDdim.size(); ++i) {
300 dims1(0, 0) = uDdim[i];
301 x1_loc_1.resize((
Index_t)(ind_Ddim_copy == uDdim[i]).count(),
305 cov_func.ginput4(x1_loc_1, x2_loc_0, dims1, Kdf);
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(),
319 for (
Index_t j = 0; j < uDdim2.size(); ++j) {
321 dims2(0, 0) = uDdim2[j];
322 x2_loc_1.resize((
Index_t)(ind_Ddim2_copy == uDdim2[j]).count(),
326 if (uDdim[i] == uDdim2[j]) {
327 cov_func.ginput2(x1_loc_1, x2_loc_1, dims1, Kdf2);
329 cov_func.ginput3(x1_loc_1, x2_loc_1, dims1, dims2, Kdf2);
337#ifdef GPR_LINALG_SCALAPACK
340 if (do_reduce && _mpi_np > 1)
341 backend().disjoint_sum_bcast(Ktemp.data(),
342 static_cast<int>(Ktemp.size()));
346template <
typename CovFunc>
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
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);
363 column.data(), coefficients.data(),
364 static_cast<int>(coefficients.size()), product_mode);
368 if constexpr (std::is_same<typename std::decay<CovFunc>::type,
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");
377 output = contract(joint_covariance, weights);
385 std::vector<FieldMatrixd> Kdf(1), Kdf2(1);
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(
398 prediction_channels.block(
static_cast<Index_t>(uDdim2(channel)))
401 output.resize(x2.rows());
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);
415 auto assign_block_contrib = [&](
const Index_t row_val,
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);
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;
432 Eigen::Map<const Eigen::ArrayXd> ind_Ddim_copy(ind_Ddim.data(),
434 Eigen::Map<const Eigen::ArrayXd> ind_Ddim2_copy(ind_Ddim2.data(),
437#ifdef GPR_LINALG_SCALAPACK
438 auto& _mpi_st =
backend().distributed();
439 _mpi_st.initialize();
442 const auto owns_block = [&](
const Index_t block_idx) {
443 return !do_reduce || block_idx % mpi_np == mpi_rank;
447 const auto owns_block = [&](
const Index_t) {
return true; };
450 x1_loc_0.resize((
Index_t)(ind_Ddim_copy == 0).count(),
453 x2_loc_0.resize((
Index_t)(ind_Ddim2_copy == 0).count(),
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);
472 if ((ind_Ddim_copy == 0).count() > 0) {
473 for (
Index_t i = 0; i < uDdim2.size(); ++i, ++block_idx) {
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;
481 dims2(0, 0) = pred_block;
482 x2_loc_1.resize((
Index_t)(ind_Ddim2_copy == pred_block).count(),
486 cov_func.ginput4(x2_loc_1, x1_loc_0, dims2, Kdf);
487 assign_block_contrib(0, pred_block, Kdf[0], block_idx,
true);
490 block_idx +=
static_cast<Index_t>(uDdim2.size());
493 if ((ind_Ddim2_copy == 0).count() > 0) {
494 for (
Index_t i = 0; i < uDdim.size(); ++i, ++block_idx) {
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;
501 dims1(0, 0) = obs_block;
502 x1_loc_1.resize((
Index_t)(ind_Ddim_copy == obs_block).count(),
506 cov_func.ginput4(x1_loc_1, x2_loc_0, dims1, Kdf);
507 assign_block_contrib(obs_block, 0, Kdf[0], block_idx);
510 block_idx +=
static_cast<Index_t>(uDdim.size());
513 for (
Index_t i = 0; i < uDdim.size(); ++i) {
515 dims1(0, 0) = obs_block;
516 x1_loc_1.resize((
Index_t)(ind_Ddim_copy == obs_block).count(),
520 for (
Index_t j = 0; j < uDdim2.size(); ++j, ++block_idx) {
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;
528 dims2(0, 0) = pred_block;
529 x2_loc_1.resize((
Index_t)(ind_Ddim2_copy == pred_block).count(),
533 if (obs_block == pred_block) {
534 cov_func.ginput2(x1_loc_1, x2_loc_1, dims1, Kdf2);
536 cov_func.ginput3(x1_loc_1, x2_loc_1, dims1, dims2, Kdf2);
538 assign_block_contrib(obs_block, pred_block, Kdf2[0], block_idx);
542#ifdef GPR_LINALG_SCALAPACK
543 if (do_reduce && mpi_np > 1) {
547 backend().disjoint_sum_bcast(block_contribs.data(),
548 static_cast<int>(block_contribs.size()));
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();
563template <
typename CovFunc>
564void GaussianProcessRegression::calculateGradientWithCovFunc(
566 const Eigen::VectorXd& uDdim,
const Eigen::VectorXd& b,
571 const detail::RigidDeflationState* deflation_override)
573 const detail::RigidDeflationState& active_deflation =
577 const double diagonal_nugget = kernelNuggetCoefficient(
x.rows());
578#ifdef GPR_LINALG_SCALAPACK
579 if (!serial_per_rank) (void)invC;
581 (void)serial_per_rank;
583 if constexpr (std::is_same_v<std::decay_t<CovFunc>,
SexpatCF>) {
584 if (cov_func.usesManifoldChart()) {
589 std::vector<EigenMatrix> dC;
592 throw std::logic_error(
593 "charted Sexpat gradient requires the composite "
594 "derivative assembly");
596 const Eigen::Index n_joint = dC.front().rows();
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;
608#ifdef GPR_LINALG_SCALAPACK
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;
618#ifndef GPR_LINALG_CHOLMOD
619 !(invC.rows() == n_joint && invC.cols() == n_joint)
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) +
")");
639#ifdef GPR_LINALG_CHOLMOD
642 throw std::runtime_error(
643 "charted Sexpat gradient: training covariance is "
644 "not positive definite");
646 chart_factor = std::move(factored);
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");
654 chart_factor = llt.matrixL();
656 have_chart_factor =
true;
658 Eigen::VectorXd alpha_chart =
b;
659#ifdef GPR_LINALG_SCALAPACK
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) +
")");
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) {
676 static_cast<Eigen::Index
>(
682#ifndef GPR_LINALG_CHOLMOD
684 trace_term = invC.cwiseProduct(dC[j]).sum();
687 const double quad_term = alpha_chart.dot(dC[j] * alpha_chart);
688 *(gdata.data() + j) = 0.5 * (trace_term - quad_term);
690 FieldMatrixd gprior_chart = cov_func.calculateLogPriorGradient();
696 std::vector<FieldMatrixd> DKffa;
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");
708 x_loc_0.resize(number_of_rep_indices, (
Index_t)
x.cols() + 1);
710 x_loc_1.resize(number_of_rep_indices, (
Index_t)
x.cols() + 1);
712 x_loc_2.resize(number_of_rep_indices, (
Index_t)
x.cols() + 1);
718 gprior_cf = cov_func.calculateLogPriorGradient();
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);
737 parameter_indices = &selected_parameters;
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);
760 bool grad_geom_active =
false;
761 Eigen::VectorXd grad_geom_theta;
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) {
768 training_geom->gradient_live_geometry_builds_for_testing)
769 .fetch_add(1, std::memory_order_relaxed);
773 const auto resolve_gradient_geometry =
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);
788 if constexpr (std::is_same_v<std::decay_t<CovFunc>, SexpatCF>) {
789 if (training_geom !=
nullptr && training_geom->
valid &&
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;
801#ifdef GPR_LINALG_SCALAPACK
802 bool use_observation_tile_fast_path =
false;
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()) ==
813 if (use_observation_tile_fast_path) {
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;
823 if (parameter_indices !=
nullptr && grad_geom_active) {
824 DKffa.resize(parameter_indices->size());
826 cov_func.calculateGradOfCovMatrix(x_loc_probe_1, x_loc_probe_2,
828 select_live_gradient_blocks(DKffa);
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);
841 cov_func.calculateGradOfCovMatrix(x_loc_0, x_loc_0, DKffa);
842 select_live_gradient_blocks(DKffa);
845 cov_func.calculateGradOfCovMatrix(x_loc_0, x_loc_0, DKffa);
846 select_live_gradient_blocks(DKffa);
849 if (DKffa.size() != 0) {
850 gdata.resize(1, (
Index_t)DKffa.size());
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();
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 &&
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);
894 Eigen::Index& group =
896 ? leader_groups[
static_cast<std::size_t
>(
897 length_scale_ties_.leader[index])]
899 if (group < 0) group = group_count++;
900 pair_derivative_groups[index] = group;
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 -
910 const auto index =
static_cast<std::size_t
>(group);
911 p = represented[index] ? -1 : 1 + group;
912 represented[index] =
true;
915 pair_derivative_groups.clear();
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
929 std::vector<linalg::ExactSum> Cdist(n_hp), Bdist(n_hp);
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
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));
951 const Eigen::VectorXd alpha_E = alpha_for_alpha_k.head(num_rep);
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));
960 alpha_k_quadratic.assign(
962 alpha_k_quad.data() + alpha_k_quad.size());
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);
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 &&
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();
987 std::vector<linalg::ExactSum> cached_inverse_trace(n_hp);
988 if (use_observation_tile_fast_path || use_pair_non_tile_trace) {
990 ScopedPhaseTimer inverse_timer(
992 backend().cache_cholesky_inverse(
L);
994 use_cached_inverse_trace =
995 _mpi_st.has_cached_inv() && _mpi_st.cached_inv_n() == dk_n;
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),
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)))
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;
1021 (void)assign_owned_entry;
1023 auto accumulate_trace_or_store_entry = [&](
const Index_t elt,
1027 if (global_row == global_col && diagonal_nugget > 0.0) {
1028 const double shift = diagonal_nugget * value;
1030 if (!alpha_k_quadratic.empty())
1031 Bex[elt].addTripleProduct(
b(global_row), shift,
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)))
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)),
1047 assign_owned_entry(DKdist[elt], global_row, global_col, value);
1049 (void)accumulate_trace_or_store_entry;
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();
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) {
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);
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)));
1110 _mpi_st.cached_inv_desc(),
1111 observation_inverse.data(), 1, 1, descriptor,
1113 inverse = observation_inverse.data();
1115 Eigen::MatrixXd diag, contraction_piece;
1116 Eigen::VectorXd part;
1117 std::vector<int> row_lane, col_lane;
1120 std::numeric_limits<std::int64_t>::max() /
1121 sizeof(
double) / tile_size)
1122 throw std::length_error(
1123 "canonical contraction exceeds addressable "
1125 const Index_t last_owned_row =
1126 process_row < num_rep
1127 ? process_row + ((num_rep - 1 - process_row) /
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)
1137 _mpi_st,
"canonical contraction block", bytes,
1140 contraction_piece.resize(tile_size, tile_size);
1141 row_lane.resize(tile_size);
1142 col_lane.resize(tile_size);
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)];
1160 cached_inverse_trace[elt].addProduct(
1169 const int nb = _mpi_st.block_size();
1170 for (
Index_t c = 0; c < tile_size; ++c) {
1172 ((obs_i * tile_size + c) / nb) % 2;
1174 ((obs_j * tile_size + c) / nb) % 2;
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;
1182 if (col_lane[col] != lane_j)
1185 obs_i == obs_j ? col : 0;
1187 row < tile_size; ++row) {
1188 if (row_lane[row] != lane_i)
1190 contraction_piece(row, col) =
1196 if (!has_entries)
continue;
1198 contraction_piece.data(), 1,
1199 tile_size, obs_i == obs_j, part);
1204 evaluator.contract(block, 1, inverse_ld,
1205 obs_i == obs_j, part);
1208 if (obs_i != obs_j || diagonal_nugget <= 0.0)
1210 evaluator.diagonals(diag);
1211 for (
Index_t channel = 0; channel < tile_size;
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],
1226 Bex[elt].addTripleProduct(alpha, shift,
1232 pair_non_tile_trace_done =
true;
1236 if (use_observation_tile_fast_path) {
1238 static_cast<Index_t>(channel_layout.channelCount());
1241 std::vector<Index_t> owned_obs_rows;
1242 std::vector<Index_t> owned_obs_cols;
1243 std::vector<FieldMatrixd> pair_lower;
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);
1253 auto build_observation_subset =
1254 [&](
const Index_t dim_ind,
const std::vector<Index_t>& obs_inds,
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);
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();
1266 x_loc_subset.block(local_idx, 0, 1,
x.cols()) =
x.block(
1267 start + obs_inds[local_idx], 0, 1,
x.cols());
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 =
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();
1313 const bool include_equal_obs = row_val >= col_val;
1314 for (
Index_t elt = 0; elt < n_hp; ++elt) {
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 +
1327 for (Eigen::Index i = j + 1; i < num_rep; ++i)
1328 block_trace.addProduct(2.0 * column[i * stride],
1330 if (include_equal_obs) {
1331 const double weight =
1332 diagonal_block ? 1.0 + diagonal_nugget
1334 block_trace.addProduct(
1335 weight * column[j * stride], F(j, j));
1338 const double trace_term = block_trace.value();
1340 quadratic ? b_rows.dot(F * b_cols) : 0.0;
1341 if (diagonal_block && diagonal_nugget > 0.0) {
1342 const double shift =
1344 b_rows.cwiseProduct(b_rows).dot(F.diagonal());
1348 quad_out[elt] += shift;
1350 trace_out[elt].add(trace_term);
1351 if (quadratic) quad_out[elt] += quad_term;
1357 const bool check_dense_against_entrywise =
1358 single_rank_dense_trace &&
1359 std::getenv(
"GPR_GRADIENT_CHECK") !=
nullptr;
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;
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,
1394 auto accumulate_owned_subset =
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);
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];
1425 accumulate_owned_subset_dense(
1426 row_val, col_val, fields, transpose_field,
1433 for (
size_t local_j = 0; local_j < owned_obs_cols.size();
1435 const Index_t obs_j = owned_obs_cols[local_j];
1437 obs_j * tile_size + col_channel;
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];
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)))
1448 for (
Index_t elt = 0; elt < n_hp; ++elt) {
1449 const double value =
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);
1458 if (!alpha_k_quadratic.empty())
return;
1463 for (
size_t local_i = 0; local_i < owned_obs_rows.size();
1465 const Index_t obs_i = owned_obs_rows[local_i];
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];
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)))
1477 for (
Index_t elt = 0; elt < n_hp; ++elt) {
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,
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)];
1517 Eigen::VectorXd part;
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,
1530 const double* W = _mpi_st.cached_inv_block(
1531 global_row, global_col, lld);
1532 evaluator.prepare(obs_i, obs_j);
1535 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);
1541 cached_inverse_trace[elt].addProduct(
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 =
1549 if (p < 0)
continue;
1550 for (
Index_t c = 0; c < tile_size;
1552 const double value =
1553 diagonal_nugget * diag(p, c);
1554 cached_inverse_trace[elt]
1555 .addProduct(W[c + c * lld],
1557 if (!alpha_k_quadratic.empty()) {
1560 Bex[elt].addTripleProduct(
1568 pair_local_trace_done =
true;
1572 if (!pair_local_trace_done && !owned_obs_rows.empty() &&
1573 !owned_obs_cols.empty()) {
1578 build_observation_subset(0, owned_obs_rows, ff_rows);
1579 build_observation_subset(0, owned_obs_cols, ff_cols);
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;
1597 std::vector<FieldMatrixd> shared_distances_rc_storage;
1598 std::vector<FieldMatrixd> shared_distances_cr_storage;
1601 const std::vector<FieldMatrixd>* shared_distances_rc =
nullptr;
1602 const std::vector<FieldMatrixd>* shared_distances_cr =
nullptr;
1603 const auto select_owned_field =
1605 const std::vector<Index_t>& rows,
1606 const std::vector<Index_t>& cols) {
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]);
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 ==
1618 ->num_repetitive_indices &&
1620 grad_geom_handle->num_repetitive_indices;
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,
1631 shared_kernel_rc_storage)) {
1632 shared_kernel_rc = &shared_kernel_rc_storage;
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,
1644 shared_kernel_cr_storage)) {
1645 shared_kernel_cr = &shared_kernel_cr_storage;
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,
1653 std::vector<FieldMatrixd>& distances_storage,
1655 const std::vector<FieldMatrixd>*& distances) {
1657 static_cast<std::size_t
>(num_rep) &&
1659 static_cast<std::size_t
>(num_rep)) {
1660 kernel = &grad_geom_shared_kernel;
1663 ->shared_distance_neg_per_pt;
1666 kernel_storage = select_owned_field(
1667 grad_geom_shared_kernel, rows, cols);
1668 for (
const auto& field:
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;
1676 prepare_streamed_subset(owned_obs_rows, owned_obs_cols,
1677 shared_kernel_rc_storage,
1678 shared_distances_rc_storage,
1680 shared_distances_rc);
1681 prepare_streamed_subset(owned_obs_cols, owned_obs_rows,
1682 shared_kernel_cr_storage,
1683 shared_distances_cr_storage,
1685 shared_distances_cr);
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 =
1694 SexpatCF::CrossBlockGeometry& scratch)
1695 ->
const SexpatCF::CrossBlockGeometry* {
1696 if (use_streamed_subset) {
1697 const uint8_t options =
1703 transpose ? owned_obs_cols : owned_obs_rows;
1705 transpose ? owned_obs_rows : owned_obs_cols;
1706 if (!grad_geom_handle->factors.valid) {
1710 if constexpr (std::is_same_v<std::decay_t<CovFunc>,
1713 build_observation_subset(block_n, rows,
1715 build_observation_subset(block_m, cols,
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)
1731 grad_geom_handle->factors, block_n, block_m,
1734 if (rows.size() !=
static_cast<std::size_t
>(num_rep) ||
1735 cols.size() !=
static_cast<std::size_t
>(num_rep)) {
1737 {&scratch.d1, &scratch.d2, &scratch.d12})
1738 for (
auto& field: *fields)
1740 select_owned_field(field, rows, cols);
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;
1751 bool kff_geom =
false;
1752 if constexpr (std::is_same_v<std::decay_t<CovFunc>, SexpatCF>) {
1755 cov_func.calculateGradOfCovMatrixFromGeometry(
1756 *shared_kernel_rc, *shared_distances_rc,
1757 grad_geom_theta, pair_lower, parameter_indices);
1762 cov_func.calculateGradOfCovMatrix(ff_rows, ff_cols,
1764 select_live_gradient_blocks(pair_lower);
1766 accumulate_owned_subset(0, 0, pair_lower);
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>,
1776 SexpatCF::CrossBlockGeometry scratch;
1777 const auto* kdf_block = resolve_owned_geometry(
1778 static_cast<Index_t>(uDdim[n]), 0,
false,
1780 if (kdf_block !=
nullptr) {
1783 .calculateGradOfCovMatrixWithDerivativesFromGeometry(
1784 *kdf_block, *shared_kernel_rc,
1785 *shared_distances_rc,
1786 grad_geom_theta, pair_lower,
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);
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>,
1805 SexpatCF::CrossBlockGeometry scratch;
1806 const auto* kdf_block = resolve_owned_geometry(
1807 static_cast<Index_t>(uDdim[n]), 0,
true,
1809 if (kdf_block !=
nullptr) {
1812 .calculateGradOfCovMatrixWithDerivativesFromGeometry(
1813 *kdf_block, *shared_kernel_cr,
1814 *shared_distances_cr,
1815 grad_geom_theta, pair_lower,
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);
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>,
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) {
1839 .calculateGradOfCovMatrixWithDerivatives2FromGeometry(
1840 *d_block, *shared_kernel_rc,
1841 *shared_distances_rc,
1842 grad_geom_theta, pair_lower,
1849 record_live_gradient_geometry();
1850 cov_func.calculateGradOfCovMatrixWithDerivatives2(
1851 df_rows, df_cols, pair_dims1, pair_dims1,
1853 select_live_gradient_blocks(pair_lower);
1855 accumulate_owned_subset(uDdim[n], uDdim[n], pair_lower);
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,
1861 build_observation_subset(uDdim[m], owned_obs_cols,
1863 bool kdf2_geom =
false;
1864 if constexpr (std::is_same_v<std::decay_t<CovFunc>,
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,
1872 if (kdf2_block !=
nullptr) {
1875 .calculateGradOfCovMatrixWithDerivatives2FromGeometry(
1876 *kdf2_block, *shared_kernel_rc,
1877 *shared_distances_rc,
1878 grad_geom_theta, pair_lower,
1885 record_live_gradient_geometry();
1886 cov_func.calculateGradOfCovMatrixWithDerivatives2(
1887 df_rows, dg_cols, pair_dims1, pair_dims2,
1889 select_live_gradient_blocks(pair_lower);
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>,
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,
1905 if (kdf2_t_block !=
nullptr) {
1908 .calculateGradOfCovMatrixWithDerivatives2FromGeometry(
1911 *shared_distances_rc,
1912 grad_geom_theta, pair_lower,
1919 record_live_gradient_geometry();
1920 cov_func.calculateGradOfCovMatrixWithDerivatives2(
1921 dg_rows, df_cols, pair_dims2, pair_dims1,
1923 select_live_gradient_blocks(pair_lower);
1925 accumulate_owned_subset(uDdim[m], uDdim[n], pair_lower);
1929 }
else if (!serial_per_rank && !pair_non_tile_trace_done) {
1930 auto accumulate_distributed_block =
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;
1940 for (
Index_t local_i = 0; local_i < row_block.count;
1942 const Index_t global_i = i_start + local_i;
1943 for (
Index_t local_j = 0; local_j < col_block.count;
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);
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;
1955 perm_i =
static_cast<int>(
1957 perm_j =
static_cast<int>(
1959 alpha_i_index =
static_cast<Index_t>(perm_i);
1960 alpha_j_index =
static_cast<Index_t>(perm_j);
1963 if (!_mpi_st.owns_global_entry(perm_i, perm_j))
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(
1972 field_value * (global_i == global_j
1973 ? 1.0 + diagonal_nugget
1980 for (
Index_t elt = 0; elt < DKffa.size(); ++elt)
1981 accumulate_distributed_block(0, 0, DKffa[elt], elt, Bdist[elt]);
1983 std::vector<FieldMatrixd> Kdf;
1984 std::vector<FieldMatrixd> Kdf2;
1985 std::vector<FieldMatrixd> D;
1987 for (
Index_t n = 0; n < uDdim.size(); ++n) {
1988 dims1(0, 0) = uDdim[n];
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,
1998 if (kdf_block !=
nullptr) {
2001 .calculateGradOfCovMatrixWithDerivativesFromGeometry(
2002 *kdf_block, grad_geom_shared_kernel,
2004 ->shared_distance_neg_per_pt,
2005 grad_geom_theta, Kdf,
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) {
2015 .calculateGradOfCovMatrixWithDerivatives2FromGeometry(
2016 *d_block, grad_geom_shared_kernel,
2018 ->shared_distance_neg_per_pt,
2019 grad_geom_theta, D, parameter_indices);
2025 record_live_gradient_geometry();
2026 cov_func.calculateGradOfCovMatrixWithDerivatives(
2027 x_loc_1, x_loc_0, dims1, Kdf);
2028 select_live_gradient_blocks(Kdf);
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);
2038 for (
Index_t elt = 0; elt < DKffa.size(); ++elt) {
2039 accumulate_distributed_block(uDdim[n], 0, Kdf[elt], elt,
2041 accumulate_distributed_block(0, uDdim[n], Kdf[elt], elt,
2043 accumulate_distributed_block(uDdim[n], uDdim[n], D[elt],
2047 for (
Index_t m = n + 1; m < uDdim.size(); ++m) {
2048 dims2(0, 0) = uDdim[m];
2051 bool kdf2_geom =
false;
2052 if constexpr (std::is_same_v<std::decay_t<CovFunc>,
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) {
2063 .calculateGradOfCovMatrixWithDerivatives2FromGeometry(
2065 grad_geom_shared_kernel,
2067 ->shared_distance_neg_per_pt,
2068 grad_geom_theta, Kdf2,
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);
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],
2092 if (!serial_per_rank && !use_cached_inverse_trace && n_hp > 0) {
2097 std::vector<double> inverse;
2098 int inverse_desc[9];
2099 bool inverse_ok =
false;
2101 ScopedPhaseTimer inverse_timer(
2103 inverse_ok =
backend().factor_inverse_lower(
L, dk_n, inverse,
2107 throw std::runtime_error(
2108 "ScaLAPACK gradient path could not invert the training "
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];
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);
2136#ifdef GPR_LINALG_SCALAPACK
2137 if (serial_per_rank)
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)");
2157 std::vector<EigenMatrix> dk_trace;
2158 if constexpr (std::is_same_v<std::decay_t<CovFunc>, SexpatCF>) {
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 ==
2168#ifdef GPR_LINALG_CHOLMOD
2172 (invC.rows() == Ddim_rows && invC.cols() == Ddim_rows)) &&
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)];
2189#ifndef GPR_LINALG_CHOLMOD
2190 std::vector<linalg::CompensatedSum> trace(
2191 static_cast<std::size_t
>(n_hp));
2192 Eigen::VectorXd part;
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;
2200 std::vector<EigenMatrix> solved_dk;
2202 solved_dk.resize(
static_cast<std::size_t
>(n_hp));
2203 for (
auto& matrix: solved_dk)
2205 EigenMatrix::Zero(Ddim_rows, Ddim_rows);
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;
2217 static_cast<Index_t>(block.rows());
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);
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;
2233 for (
Index_t elt = 0; elt < n_hp; ++elt) {
2234 const Eigen::Index p =
2236 if (p < 0)
continue;
2237 evaluator.tile(p, deriv_tile);
2238 scatter_tile(solved_dk[elt], deriv_tile,
2240 if (obs_i != obs_j) {
2242 deriv_tile.transpose();
2243 scatter_tile(solved_dk[elt],
2244 flipped, obs_j, obs_i);
2246 if (obs_i == obs_j &&
2247 diagonal_nugget > 0.0) {
2248 for (
Index_t c = 0; c < tile; ++c) {
2250 c * num_rep + obs_i;
2251 solved_dk[elt](row, row) +=
2258#ifndef GPR_LINALG_CHOLMOD
2261 W + obs_i + obs_j * Ddim_rows,
2262 row_stride, col_stride,
2264 for (
Index_t elt = 0; elt < n_hp; ++elt) {
2265 const Eigen::Index p =
2268 trace[
static_cast<std::size_t
>(elt)]
2269 .addProduct(weight, part(p));
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);
2280 evaluator.quadratic(alpha_i.data(),
2283 for (
Index_t elt = 0; elt < n_hp; ++elt) {
2284 const Eigen::Index p =
2287 quad[
static_cast<std::size_t
>(elt)]
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 =
2297 if (p < 0)
continue;
2298 for (
Index_t c = 0; c < tile; ++c) {
2300 c * num_rep + obs_i;
2301 const double value =
2302 diagonal_nugget * diag(p, c);
2303#ifndef GPR_LINALG_CHOLMOD
2305 trace[
static_cast<std::size_t
>(
2307 .addProduct(invC(row, row),
2310 if (accumulate_quad_blocks ||
2311 !alpha_k_quadratic.empty())
2312 quad[
static_cast<std::size_t
>(
2314 .addProduct(
b(row) * value,
2322 ScopedPhaseTimer inverse_timer(
2324 for (
Index_t elt = 0; elt < n_hp; ++elt)
2326 *trace_factor, solved_dk[elt],
2329#ifndef GPR_LINALG_CHOLMOD
2331 for (
Index_t elt = 0; elt < n_hp; ++elt)
2332 Cdl[elt] += trace[
static_cast<std::size_t
>(elt)]
2336 for (
Index_t elt = 0; elt < n_hp; ++elt)
2338 quad[
static_cast<std::size_t
>(elt)].value();
2339 dense_pair_local_done =
true;
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);
2348 if (!dense_pair_local_done)
2351 for (
Index_t elt = 0; elt < DKffa.size(); ++elt) {
2353 ind_Ddim, ind_Ddim, 0, 0, DKffa[elt], invC,
b, Cdl[elt],
2355 false, accumulate_quad_blocks,
2357 solve_trace ? &dk_trace[elt] :
nullptr);
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)
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;
2383#if defined(GPR_OPENMP_LOCAL_ORACLE) && defined(_OPENMP)
2384#pragma omp for schedule(static)
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];
2393 bool kdf_geom =
false, d_geom =
false;
2394 if constexpr (std::is_same_v<std::decay_t<CovFunc>,
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,
2402 if (kdf_block !=
nullptr) {
2405 .calculateGradOfCovMatrixWithDerivativesFromGeometry(
2407 grad_geom_shared_kernel,
2409 ->shared_distance_neg_per_pt,
2410 grad_geom_theta, Kdf,
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]),
2418 if (d_block !=
nullptr) {
2421 .calculateGradOfCovMatrixWithDerivatives2FromGeometry(
2423 grad_geom_shared_kernel,
2425 ->shared_distance_neg_per_pt,
2433 record_live_gradient_geometry();
2434 cov_func.calculateGradOfCovMatrixWithDerivatives(
2435 x_loc_1, x_loc_0, dims1, Kdf);
2436 select_live_gradient_blocks(Kdf);
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);
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],
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],
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],
2463 accumulate_quad_blocks, diagonal_nugget,
2464 solve_trace ? &dk_trace[elt] :
nullptr);
2467 for (
Index_t m = n + 1; m < uDdim.size(); ++m) {
2468 dims2(0, 0) = uDdim[m];
2471 bool kdf2_geom =
false;
2472 if constexpr (std::is_same_v<std::decay_t<CovFunc>,
2474 if (grad_geom_active) {
2475 SexpatCF::CrossBlockGeometry
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) {
2484 cov_func.calculateGradOfCovMatrixWithDerivatives2FromGeometry(
2486 grad_geom_shared_kernel,
2488 ->shared_distance_neg_per_pt,
2489 grad_geom_theta, Kdf2,
2496 record_live_gradient_geometry();
2498 .calculateGradOfCovMatrixWithDerivatives2(
2499 x_loc_1, x_loc_2, dims1, dims2, Kdf2);
2500 select_live_gradient_blocks(Kdf2);
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],
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],
2514 accumulate_quad_blocks, diagonal_nugget,
2515 solve_trace ? &dk_trace[elt] :
nullptr);
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];
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));
2533 Cdl[elt] = c_sum.value();
2534 Bdl[elt] = b_sum.value();
2537 if (solve_trace && !dense_pair_local_done) {
2538 ScopedPhaseTimer inverse_timer(
2540 for (
Index_t elt = 0; elt < n_hp; ++elt)
2542 *trace_factor, dk_trace[elt], &active_deflation);
2548#ifdef GPR_LINALG_SCALAPACK
2549 if (use_cached_inverse_trace && n_hp > 0) {
2555 static_cast<int>(n_hp),
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");
2578 if (!serial_per_rank && n_hp > 0) {
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));
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();
2592 }
else if (n_hp > 0) {
2593 for (
Index_t elt = 0; elt < n_hp; ++elt)
2594 Bdl[elt] += Bex[elt].value();
2602 const double hutch_inv_m =
2603 hutch_trace_W_ !=
nullptr
2604 ? 1.0 /
static_cast<double>(hutch_trace_W_->cols())
2606 for (
Index_t elt = 0; elt < n_hp; ++elt) {
2607 const double quad_term =
2608 alpha_k_quadratic.empty()
2610 : alpha_k_quadratic[
static_cast<size_t>(elt)] +
2612 *(gdata.data() + elt) =
2613 0.5 * (Cdl[elt] * hutch_inv_m - quad_term);
2616 if (parameter_indices !=
nullptr) {
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);
2629 const Eigen::VectorXd& uDdim,
const Eigen::VectorXd& direction,
2632#ifndef GPR_LINALG_SCALAPACK
2633 (void)serial_per_rank;
2638 const Index_t number_of_rep_indices =
2641 x_loc_0.resize(number_of_rep_indices,
static_cast<Index_t>(
x.cols()) + 1);
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);
2655 first.resize(
x.rows(),
x.rows());
2657 second.resize(
x.rows(),
x.rows());
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();
2668 const int _mpi_rank = 0, _mpi_np = 1;
2673 if (
ownsBlock(_mpi_blk++, _mpi_rank, _mpi_np, serial_per_rank)) {
2675 x_loc_0, x_loc_0, direction, block_first, block_second);
2676 if (block_first.size() != 0) {
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)];
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,
2691 if (block_first.size() != 0) {
2693 block_first, first);
2695 block_first, first,
true);
2697 block_second, second);
2699 block_second, second,
true);
2703 ->calculateDirectionalCovarianceMatrixWithDerivatives2(
2704 x_loc_1, x_loc_1, dims1, dims1, direction, block_first,
2706 if (block_first.size() != 0) {
2708 block_first, first);
2710 block_second, second);
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,
2722 if (block_first.size() != 0) {
2724 block_first, first);
2726 block_first, first,
true);
2728 block_second, second);
2730 block_second, second,
true);
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()));
2745 applyKernelNugget(first,
x.rows());
2746 applyKernelNugget(second,
x.rows());
2749 if (direction.size() > n_cov_params) {
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;
2762 const Eigen::VectorXd& ind_Ddim,
const Eigen::VectorXd& uDdim,
2764 bool serial_per_rank)
const
2766#ifndef GPR_LINALG_SCALAPACK
2767 (void)serial_per_rank;
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();
2780 const int mpi_rank = 0, mpi_np = 1;
2783 [[maybe_unused]]
bool pair_tiles_used =
false;
2784 const bool local_ok = [&]() {
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)) !=
2796 geom, ind_Ddim, direction, first, second, mpi_rank, mpi_np);
2797 if (local.has_value()) {
2798 pair_tiles_used =
true;
2805 theta, shared_kernel)) {
2809 first.resize(
x.rows(),
x.rows());
2811 second.resize(
x.rows(),
x.rows());
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,
2819 owned.push_back(index);
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()) {
2830 for (std::size_t task = worker; task < owned.size();
2832 const auto& block = geom.
blocks[owned[task]];
2835 block, streamed_scratch);
2836 if (block_geometry ==
nullptr) {
2840 resolved.fetch_add(1, std::memory_order_relaxed);
2842 const std::vector<FieldMatrixd>* distances =
2845 block.derivative_options != 0) {
2846 distances = &block_geometry->
distance;
2848 *distances, theta, block_kernel)) {
2852 kernel = &block_kernel;
2856 if (block.derivative_options == 0) {
2859 ->calculateDirectionalCovarianceMatrixFromGeometry(
2860 *kernel, *distances, theta, direction,
2861 block_first, block_second);
2862 }
else if (block.derivative_options ==
2866 ->calculateDirectionalCovarianceMatrixWithDerivativesFromGeometry(
2867 *block_geometry, *kernel, *distances, theta,
2868 direction, block_first, block_second);
2872 ->calculateDirectionalCovarianceMatrixWithDerivatives2FromGeometry(
2873 *block_geometry, *kernel, *distances, theta,
2874 direction, block_first, block_second);
2876 if (!ok || block_first.size() == 0 ||
2877 block_second.size() == 0) {
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()) {
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) {
2897 0, block_first, first);
2899 block.block_n, block_first, first,
2902 0, block_second, second);
2904 block.block_n, block_second, second,
2906 }
else if (block.block_n == block.block_m) {
2908 block.block_n, block_first, first);
2910 block.block_n, block_second,
2914 block.block_m, block_first, first);
2916 block.block_n, block_first, first,
2919 block.block_m, block_second,
2922 block.block_n, block_second, second,
2928 geom.directional_geometry_blocks_for_testing += resolved.load();
2929 if (std::find(block_ok.begin(), block_ok.end(), 0) != block_ok.end())
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]);
2946 second.resize(0, 0);
2950#ifdef GPR_LINALG_SCALAPACK
2951 if (!serial_per_rank && mpi_np > 1) {
2952 if (pair_tiles_used) {
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()));
2966 applyKernelNugget(first,
x.rows());
2967 applyKernelNugget(second,
x.rows());
2970 if (direction.size() > n_cov_params) {
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;
2983 jitter_sigma2 = value;
2984 ++laplace_model_revision_;
2989 sigma2 = parameters.
sigma2;
2990 theta_includes_likelihood_noise_ =
false;
2993 use_ls_prior_ = parameters.
ls_prior;
2994 detail::validateRigidNullDeflationConfiguration(
2999 scg_opt_settings.map_use_configured_magn_prior =
3001 scg_opt_settings.map_use_configured_lengthscale_prior =
3003 hyperparameter_optimization_mode_ =
3007 ++laplace_model_revision_;
3012 return *lik_gaussian;
3017 return *lik_gaussian;
3033 return *const_cov_fun;
3039 return *const_cov_fun;
3044 return num_of_potential_calls;
Linear algebra abstraction layer for GPR hot-path operations.
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.
linalg::BackendContext & backend() const
ConstantCF & getConstantCovarianceFunction()
LikGaussian & getLikGaussian()
Index_t getNumberOfPotentialCalls() const
void setParameters(const GPRSetup ¶meters)
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
Eigen::Index covarianceParameterCount() const
detail::RigidDeflationState rigid_deflation_
double likelihoodNoiseVariance() const noexcept
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
bool use_rigid_null_deflation_
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 hasTrainingPermutation() const
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.
StructuredPermutation training_permutation_
SexpatCF & getSexpAtCovarianceFunction()
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 .
linalg::MpiContext mpiContext() const
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.
Pair-type inverse-distance squared-exponential primitive.
const LocalExecutor & local() const noexcept
void forEach(std::size_t count, Operation &&operation, Grain grain=Grain::Fine) const
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.
const SexpatCF::CrossBlockGeometry * resolveTrainingBlockGeometry(const SexpatCF &covariance, const TrainingKernelGeometry &geom, const TrainingKernelGeometryBlock &block, SexpatCF::CrossBlockGeometry &scratch)
Eigen::Matrix< Index_t, EigenDynamic, EigenDynamic, FieldMatrixStorage > FieldMatrixIdx
EigenMatrix permuteSymmetricMatrix(const EigenMatrix &input, const StructuredPermutation &p)
Eigen::Matrix< double, EigenDynamic, EigenDynamic, EigenMatrixStorage > EigenMatrix
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
bool ownsBlockIfReduce(long block_idx, int rank, int nprocs, bool do_reduce)
Structure of GPR properties.
bool map_use_configured_priors
MapPriorWeightMode map_prior_weight_mode
static double gradient_inverse_seconds
static double gradient_seconds
static int gradient_count
static double gradient_accumulate_seconds
std::vector< FieldMatrixd > distance
bool shared_coordinates
Channel blocks carry the same Cartesian positions.
std::vector< TrainingKernelGeometryBlock > blocks
std::vector< FieldMatrixd > shared_distance_neg_per_pt