9#ifndef GPR_LINALG_SCALAPACKBACKEND_H_
10#define GPR_LINALG_SCALAPACKBACKEND_H_
32#ifdef GPR_LINALG_SLATE
78 if (L.rows() != 0 && L.cols() != 0) {
85 "[gpr::linalg::%s] cache miss with empty dense L: "
86 "requested m=%d, cached_n=%d, has_cached_L=%d. "
87 "Upstream cholesky_distributed resized this->L to 0x0 "
88 "and the cache now belongs to a different GP instance. "
89 "Caller must refresh the model (e.g. updateModelWithFullData "
90 "or refreshCovarianceCache) before this solve.\n",
91 fn, m, st.cached_n(), st.has_cached_L() ? 1 : 0);
97 double* data,
int count,
100 if (count <= 0 || st.nprocs() == 1)
return;
107 if (count <= 0 || st.nprocs() == 1)
return;
130 double* data,
int count,
133 if (count <= 0)
return;
135 if (st.nprocs() == 1)
return;
148 if (A.cols() != B.rows() || &C == &A || &C == &B)
return false;
149 constexpr Eigen::Index max_count = std::numeric_limits<int>::max();
150 if (B.cols() > max_count ||
151 A.rows() > max_count / std::max<Eigen::Index>(1, B.cols()))
155 C.setZero(A.rows(), B.cols());
156 if (C.size() == 0 || A.cols() == 0)
return true;
157 constexpr Eigen::Index kColTile = 64;
158 const Eigen::Index n_tiles = (B.cols() + kColTile - 1) / kColTile;
160 const bool global_device_product =
161 device_product && std::min({A.rows(), A.cols(), B.cols()}) >= 128;
164 for (Eigen::Index tile = st.myrank(); tile < n_tiles; tile += st.nprocs()) {
165 const Eigen::Index start = tile * kColTile;
166 const Eigen::Index count = std::min(kColTile, B.cols() - start);
168 auto output = C.middleCols(start, count);
169 if (!global_device_product ||
171 false,
false, 1.0, 0.0,
true))
172 output.noalias() = A * B.middleCols(start, count);
173 }
catch (
const std::exception& exception) {
175 failure = exception.what();
180 if (device_product && st.nprocs() > 1)
181 MPI_Allreduce(MPI_IN_PLACE, &failed, 1, MPI_INT, MPI_MAX,
184 throw std::runtime_error(failure.empty()
185 ?
"training product failed on another rank"
187 if (st.nprocs() == 1)
return true;
190 st.communication()->view());
204 raised_(previous_ > 0 && target_ > previous_)
207 if (std::getenv(
"GPR_GEOM_DEBUG") !=
nullptr) {
208 static bool reported =
false;
212 "[solve-threads] previous=%d target=%d raised=%d "
214 previous_, target_, raised_ ? 1 : 0,
225 return affinity > 0 ? std::min(affinity, workers) : workers;
237 bool raised_ =
false;
248 double size = std::ceil(std::max(1.0, query));
250 MPI_Allreduce(MPI_IN_PLACE, &size, 1, MPI_DOUBLE, MPI_MAX,
253 throw std::length_error(
254 std::string(routine) +
" asks for a workspace of " +
255 std::to_string(size) +
" entries, past the " +
257 " an LP64 ScaLAPACK indexes; run on more processes");
259 return static_cast<int>(std::ceil(std::max(1.0, query)));
263 int m,
int ncols,
double* b_buf,
const int* desc_b,
bool transpose,
266#ifdef GPR_LINALG_SLATE
267 if (st.reproducible()) {
268 slate_kernels::configure_nested_blas_threading(st);
274 if (slate_kernels::trsm_left_lower(st.cached_L(), st.cached_L_desc(), m,
275 b_buf, desc_b, ncols, transpose, st)) {
280 "[gpr::linalg::%s] SLATE triangular solve failed\n", fn);
285 if (st.reproducible() ||
286 st.tile_kernels(st.cached_L_desc(),
"pdtrsm", desc_b)) {
299 const char* trans = transpose ?
"T" :
"N";
300 pdtrsm_(
"L",
"L", trans,
"N", &m, &ncols, &alpha, st.cached_L(), &one, &one,
301 st.cached_L_desc(), b_buf, &one, &one, desc_b);
308 const int* desc,
int n,
312 const int myrow = st.
myrow(), mycol = st.
mycol();
313 const int nprow = st.
nprow(), npcol = st.
npcol();
314 const int row_coord = (myrow - desc[6] + nprow) % nprow;
315 const int col_coord = (mycol - desc[7] + npcol) % npcol;
316 const int rows =
numroc_(&n, &desc[4], &myrow, &desc[6], &nprow);
317 const int cols =
numroc_(&n, &desc[5], &mycol, &desc[7], &npcol);
318 std::vector<int> global_rows(
static_cast<std::size_t
>(rows));
319 std::vector<double> inverse_rows;
320 if (restore_factor) inverse_rows.resize(global_rows.size());
321 for (
int i = 0; i < rows; ++i) {
323 global_rows[
static_cast<std::size_t
>(i)] = gi;
325 inverse_rows[
static_cast<std::size_t
>(i)] =
328 for (
int j = 0; j < cols; ++j) {
330 const int first =
static_cast<int>(
331 std::lower_bound(global_rows.begin(), global_rows.end(), gj) -
332 global_rows.begin());
333 double* column = buffer.data() +
static_cast<std::size_t
>(j) * desc[8];
334 if (restore_factor) {
335 for (
int i = first; i < rows; ++i)
336 column[i] *= inverse_rows[
static_cast<std::size_t
>(i)];
338 for (
int i = first; i < rows; ++i)
340 column[i], global_rows[
static_cast<std::size_t
>(i)], gj);
346 const int* desc,
int n,
350 const int mycol = st.
mycol(), npcol = st.
npcol();
351 const int row_coord = (st.
myrow() - desc[6] + st.
nprow()) % st.
nprow();
352 const int col_coord = (mycol - desc[7] + npcol) % npcol;
353 const int cols =
numroc_(&n, &desc[5], &mycol, &desc[7], &npcol);
354 Eigen::VectorXd diagonal = Eigen::VectorXd::Zero(n);
355 for (
int j = 0; j < cols; ++j) {
357 if ((gj / desc[4]) % st.
nprow() != row_coord)
continue;
360 diagonal(gj) = buffer[
static_cast<std::size_t
>(j) * desc[8] + i];
363 if (!scaling.
compute(diagonal))
return false;
371 if (C.rows() != C.cols())
return false;
374 const int n =
static_cast<int>(C.rows());
377 std::vector<double> buf_std = st.scatter(C, n, n, desc_std);
383 if (!trainingCholeskyDistributed(buf_std.data(), desc_std, n, st))
386#ifdef GPR_LINALG_SLATE
388 if (st.reproducible()) {
389 slate_kernels::configure_nested_blas_threading(st);
392 }
else if (!slate_kernels::potrf_lower(buf_std.data(), desc_std, n, st))
395 if (st.reproducible() || st.tile_kernels(desc_std,
"pdpotrf")) {
401 int info = 0, one = 1;
402 pdpotrf_(
"L", &n, buf_std.data(), &one, &one, desc_std, &info);
403 if (info != 0)
return false;
409 st.cache_L(std::move(buf_std), desc_std, n);
415 std::vector<double> C_dist,
const int* desc,
int n,
EigenMatrix& L,
421 std::copy_n(desc, 9, local_desc);
427 if (!trainingCholeskyDistributed(C_dist.data(), local_desc, n, st))
430#ifdef GPR_LINALG_SLATE
432 if (st.reproducible()) {
433 slate_kernels::configure_nested_blas_threading(st);
436 }
else if (!slate_kernels::potrf_lower(C_dist.data(), local_desc, n,
440 if (st.reproducible() || st.tile_kernels(local_desc,
"pdpotrf")) {
448 pdpotrf_(
"L", &n, C_dist.data(), &one, &one, local_desc, &info);
449 if (info != 0)
return false;
455 st.cache_L(std::move(C_dist), local_desc, n);
464 const int m =
static_cast<int>(B.rows());
465 const int ncols =
static_cast<int>(B.cols());
467 if (L.size() != 0 || !st.has_cached_L() || st.cached_n() != m) {
470 std::vector<double> Lbuf = st.scatter(L, m, m, desc);
471 st.cache_L(std::move(Lbuf), desc, m);
475 std::vector<double> b_buf = st.scatter(B, m, ncols, desc_b);
477 false,
"forward_solve_mat", st);
478 return st.gather(b_buf.data(), desc_b, m, ncols);
492 const int m =
static_cast<int>(A.rows());
493 const int n =
static_cast<int>(A.cols());
494 const int k = std::min(m, n);
496 int descA[9], descU[9], descVT[9];
497 st.make_desc(m, n, descA);
498 st.make_desc(m, k, descU);
499 st.make_desc(k, n, descVT);
501 for (
const int* desc: {descA, descU, descVT})
502 st.require_lp64(desc,
"pdgesvd");
503 std::vector<double> Aloc = st.scatter(A, m, n, descA);
504 std::vector<double> Uloc = st.alloc_local(m, k, descU);
505 std::vector<double> VTloc = st.alloc_local(k, n, descVT);
506 std::vector<double> Svec(
static_cast<size_t>(k), 0.0);
508 int one = 1, info = 0, lwork = -1;
510 pdgesvd_(
"V",
"V", &m, &n, Aloc.data(), &one, &one, descA, Svec.data(),
511 Uloc.data(), &one, &one, descU, VTloc.data(), &one, &one, descVT,
513 if (info != 0)
return false;
515 std::vector<double> work(
static_cast<size_t>(lwork), 0.0);
516 pdgesvd_(
"V",
"V", &m, &n, Aloc.data(), &one, &one, descA, Svec.data(),
517 Uloc.data(), &one, &one, descU, VTloc.data(), &one, &one, descVT,
518 work.data(), &lwork, &info);
519 if (info != 0)
return false;
521 U = st.gather(Uloc.data(), descU, m, k);
522 const EigenMatrix VT = st.gather(VTloc.data(), descVT, k, n);
524 S = Eigen::Map<Eigen::VectorXd>(Svec.data(), k);
534 const EigenMatrix& A, Eigen::VectorXd& eigenvalues,
535 EigenMatrix& eigenvectors,
const char** driver_name =
nullptr,
539 if (A.rows() != A.cols())
return false;
540 const int n =
static_cast<int>(A.rows());
542 eigenvalues.resize(0);
543 eigenvectors.resize(0, 0);
547 int descA[9], descZ[9];
549 st.make_desc(n, n, descA);
550 st.require_lp64(descA,
"pdsyev");
551 std::vector<double> Aloc = st.scatter(A, n, n, descA);
552 const std::vector<double> Aloc_input = Aloc;
553 std::vector<double> Zloc = st.alloc_local(n, n, descZ);
554 std::vector<double> Wvec(
static_cast<size_t>(n), 0.0);
556 auto pdsyev_symmetric_eigen = [&]() {
558 std::fill(Zloc.begin(), Zloc.end(), 0.0);
559 std::fill(Wvec.begin(), Wvec.end(), 0.0);
560 int one = 1, info = 0, lwork = -1;
562 pdsyev_(
"V",
"L", &n, Aloc.data(), &one, &one, descA, Wvec.data(),
563 Zloc.data(), &one, &one, descZ, &wq, &lwork, &info);
564 if (info != 0)
return false;
566 std::vector<double> work(
static_cast<size_t>(lwork), 0.0);
569 pdsyev_(
"V",
"L", &n, Aloc.data(), &one, &one, descA, Wvec.data(),
570 Zloc.data(), &one, &one, descZ, work.data(), &lwork, &info);
574 auto pdsyevd_symmetric_eigen = [&]() {
577 std::fill(Zloc.begin(), Zloc.end(), 0.0);
578 std::fill(Wvec.begin(), Wvec.end(), 0.0);
579 int one = 1, info = 0, lwork = -1, liwork = -1;
582 pdsyevd_(
"V",
"L", &n, Aloc.data(), &one, &one, descA, Wvec.data(),
583 Zloc.data(), &one, &one, descZ, &wq, &lwork, &iwq, &liwork,
585 if (info != 0)
return false;
587 liwork = std::max(1, iwq);
588 std::vector<double> work(
static_cast<size_t>(lwork), 0.0);
589 std::vector<int> iwork(
static_cast<size_t>(liwork), 0);
592 pdsyevd_(
"V",
"L", &n, Aloc.data(), &one, &one, descA, Wvec.data(),
593 Zloc.data(), &one, &one, descZ, work.data(), &lwork,
594 iwork.data(), &liwork, &info);
598 auto pdsyevr_symmetric_eigen = [&]() {
601 std::fill(Zloc.begin(), Zloc.end(), 0.0);
602 std::fill(Wvec.begin(), Wvec.end(), 0.0);
603 int one = 1, info = 0, lwork = -1, liwork = -1;
604 int il = 1, iu = n, m = 0, nz = 0;
605 double vl = 0.0, vu = 0.0, wq = 0.0;
607 pdsyevr_(
"V",
"A",
"L", &n, Aloc.data(), &one, &one, descA, &vl, &vu,
608 &il, &iu, &m, &nz, Wvec.data(), Zloc.data(), &one, &one, descZ,
609 &wq, &lwork, &iwq, &liwork, &info);
610 if (info != 0)
return false;
612 liwork = std::max(1, iwq);
613 std::vector<double> work(
static_cast<size_t>(lwork), 0.0);
614 std::vector<int> iwork(
static_cast<size_t>(liwork), 0);
619 pdsyevr_(
"V",
"A",
"L", &n, Aloc.data(), &one, &one, descA, &vl, &vu,
620 &il, &iu, &m, &nz, Wvec.data(), Zloc.data(), &one, &one, descZ,
621 work.data(), &lwork, iwork.data(), &liwork, &info);
622 return info == 0 && m == n && nz == n;
625 const char* selected_driver =
nullptr;
626#ifdef GPR_LINALG_SLATE
629 if (slate_kernels::heev_lower(Aloc.data(), descA, n, Zloc.data(), descZ,
631 selected_driver =
"slate_heev_canonical";
639 if (selected_driver ==
nullptr && pdsyev_symmetric_eigen()) {
640 selected_driver =
"pdsyev";
641 }
else if (selected_driver ==
nullptr && pdsyevr_symmetric_eigen()) {
642 selected_driver =
"pdsyevr";
643 }
else if (selected_driver ==
nullptr && pdsyevd_symmetric_eigen()) {
644 selected_driver =
"pdsyevd";
646#ifdef GPR_LINALG_SLATE
647 if (selected_driver ==
nullptr) {
649 if (!slate_kernels::heev_lower(Aloc.data(), descA, n, Zloc.data(),
653 selected_driver =
"slate_heev";
656 if (selected_driver ==
nullptr)
return false;
659 MPI_Bcast(Wvec.data(), n, MPI_DOUBLE, 0, st.world_comm());
660 eigenvectors = st.gather(Zloc.data(), descZ, n, n);
661 eigenvalues = Eigen::Map<Eigen::VectorXd>(Wvec.data(), n);
662 const bool valid = eigenvectors.rows() == n && eigenvectors.cols() == n &&
663 eigenvalues.size() == n && eigenvectors.allFinite() &&
664 eigenvalues.allFinite();
666 for (
int col = 0; col < n; ++col) {
667 Eigen::Index pivot = 0;
669 for (Eigen::Index row = 0; row < n; ++row) {
670 const double mag = std::abs(eigenvectors(row, col));
676 if (eigenvectors(pivot, col) < 0.0)
677 eigenvectors.col(col) = -eigenvectors.col(col);
679 if (driver_name !=
nullptr) *driver_name = selected_driver;
697 const int k = std::min(m, n);
699 int descSrc[9], descA[9], descU[9], descVT[9];
700 st.make_col_desc(m, n, descSrc);
701 st.make_desc(m, n, descA);
702 st.make_desc(m, k, descU);
703 st.make_desc(k, n, descVT);
706 for (
const int* desc: {descSrc, descA, descU, descVT})
707 st.require_lp64(desc,
"pdgesvd");
708 std::vector<double> Aloc = st.alloc_local(m, n, descA);
709 std::vector<double> Uloc = st.alloc_local(m, k, descU);
710 std::vector<double> VTloc = st.alloc_local(k, n, descVT);
711 std::vector<double> Svec(
static_cast<size_t>(k), 0.0);
717 const double* src = A_local.size() ? A_local.data() : &dummy;
718 Cpdgemr2d(m, n, src, 1, 1, descSrc, Aloc.data(), 1, 1, descA,
721 int one = 1, info = 0, lwork = -1;
723 pdgesvd_(
"V",
"V", &m, &n, Aloc.data(), &one, &one, descA, Svec.data(),
724 Uloc.data(), &one, &one, descU, VTloc.data(), &one, &one, descVT,
726 if (info != 0)
return false;
728 std::vector<double> work(
static_cast<size_t>(lwork), 0.0);
729 pdgesvd_(
"V",
"V", &m, &n, Aloc.data(), &one, &one, descA, Svec.data(),
730 Uloc.data(), &one, &one, descU, VTloc.data(), &one, &one, descVT,
731 work.data(), &lwork, &info);
732 if (info != 0)
return false;
734 U = st.gather(Uloc.data(), descU, m, k);
735 const EigenMatrix VT = st.gather(VTloc.data(), descVT, k, n);
737 S = Eigen::Map<Eigen::VectorXd>(Svec.data(), k);
770 MPI_Comm comm = st.world_comm();
771 const int np = st.nprocs();
772 const int myrank = st.myrank();
773 const int count =
static_cast<int>(A_local.cols());
774 const int k = std::min(nobs, N);
782 std::vector<int> vrows(np, 0);
784 MPI_Allgather(&count, 1, MPI_INT, vrows.data(), 1, MPI_INT, comm);
788 std::vector<int> col_offsets(np + 1, 0);
789 for (
int r = 0; r < np; ++r)
790 col_offsets[r + 1] = col_offsets[r] + vrows[r];
791 if (col_offsets[np] != N)
return false;
793 constexpr int kLeafCols = 64;
794 const int n_leaves = (N + kLeafCols - 1) / kLeafCols;
795 std::vector<int> leaf_r_rows(n_leaves, 0), leaf_r_offsets(n_leaves + 1, 0);
796 for (
int leaf = 0; leaf < n_leaves; ++leaf) {
797 const int g0 = leaf * kLeafCols;
798 const int g1 = std::min(N, g0 + kLeafCols);
799 leaf_r_rows[leaf] = std::min(g1 - g0, nobs);
800 leaf_r_offsets[leaf + 1] = leaf_r_offsets[leaf] + leaf_r_rows[leaf];
802 const int total_rows = leaf_r_offsets[n_leaves];
803 const std::int64_t stacked_elems =
804 static_cast<std::int64_t
>(total_rows) * nobs;
806 throw std::length_error(
"TSQR: stacked R factors of " +
807 std::to_string(stacked_elems) +
808 " entries exceed the MPI count range");
809 const std::int64_t gathered_elems =
static_cast<std::int64_t
>(N) * k;
811 throw std::length_error(
"TSQR: right singular vectors of " +
812 std::to_string(gathered_elems) +
813 " entries exceed the MPI count range");
817 std::vector<EigenMatrix> my_leaf_cols;
818 std::vector<int> my_leaves;
819 for (
int leaf = myrank; leaf < n_leaves; leaf += np) {
820 const int g0 = leaf * kLeafCols;
821 const int g1 = std::min(N, g0 + kLeafCols);
822 my_leaves.push_back(leaf);
823 my_leaf_cols.emplace_back(nobs, g1 - g0);
827 for (std::size_t idx = 0; idx < my_leaves.size(); ++idx) {
828 const int leaf = my_leaves[idx];
829 const int g0 = leaf * kLeafCols;
830 const int len =
static_cast<int>(my_leaf_cols[idx].cols());
831 my_leaf_cols[idx] = A_local.middleCols(g0, len);
834 std::vector<int> send_cols(np, 0), recv_cols(np, 0);
835 const int my_g0 = col_offsets[myrank];
836 const int my_g1 = col_offsets[myrank + 1];
837 for (
int g = my_g0; g < my_g1; ++g)
838 ++send_cols[(g / kLeafCols) % np];
839 for (
int src = 0; src < np; ++src) {
840 for (
int g = col_offsets[src]; g < col_offsets[src + 1]; ++g) {
841 if ((g / kLeafCols) % np == myrank) ++recv_cols[src];
844 std::vector<int> send_counts(np, 0), send_displs(np, 0);
845 std::vector<int> recv_counts(np, 0), recv_displs(np, 0);
846 int send_total = 0, recv_total = 0;
847 for (
int r = 0; r < np; ++r) {
848 if (
exceedsLp64(
static_cast<std::int64_t
>(send_total) +
849 static_cast<std::int64_t
>(send_cols[r]) * nobs) ||
850 exceedsLp64(
static_cast<std::int64_t
>(recv_total) +
851 static_cast<std::int64_t
>(recv_cols[r]) * nobs))
852 throw std::length_error(
853 "TSQR: leaf redistribution exceeds the MPI count range");
854 send_displs[r] = send_total;
855 send_counts[r] = send_cols[r] * nobs;
856 send_total += send_counts[r];
857 recv_displs[r] = recv_total;
858 recv_counts[r] = recv_cols[r] * nobs;
859 recv_total += recv_counts[r];
861 std::vector<double> send_buf(std::max(1, send_total), 0.0);
862 std::vector<int> cursor = send_displs;
863 for (
int g = my_g0; g < my_g1; ++g) {
864 const int dst = (g / kLeafCols) % np;
865 std::copy_n(A_local.col(g - my_g0).data(), nobs,
866 send_buf.data() + cursor[dst]);
869 std::vector<double> recv_buf(std::max(1, recv_total), 0.0);
870 MPI_Alltoallv(send_buf.data(), send_counts.data(), send_displs.data(),
871 MPI_DOUBLE, recv_buf.data(), recv_counts.data(),
872 recv_displs.data(), MPI_DOUBLE, comm);
875 for (
int src = 0; src < np; ++src) {
876 for (
int g = col_offsets[src]; g < col_offsets[src + 1]; ++g) {
877 const int leaf = g / kLeafCols;
878 if (leaf % np != myrank)
continue;
879 const std::size_t local_leaf =
880 static_cast<std::size_t
>((leaf - myrank) / np);
881 const int col_in_leaf = g - leaf * kLeafCols;
882 std::copy_n(recv_buf.data() + rpos, nobs,
883 my_leaf_cols[local_leaf].col(col_in_leaf).data());
890 EigenMatrix R_all = EigenMatrix::Zero(total_rows, nobs);
891 std::vector<Eigen::HouseholderQR<EigenMatrix>> qr_leaves(my_leaves.size());
892 for (std::size_t idx = 0; idx < my_leaves.size(); ++idx) {
893 const int leaf = my_leaves[idx];
894 const int rloc = leaf_r_rows[leaf];
895 const EigenMatrix At = my_leaf_cols[idx].transpose();
896 qr_leaves[idx].compute(At);
897 R_all.middleRows(leaf_r_offsets[leaf], rloc) =
901 .template triangularView<Eigen::Upper>();
905 static_cast<std::size_t
>(R_all.size()),
906 st.communication()->view());
910 Eigen::HouseholderQR<EigenMatrix> qr_all(R_all);
911 const int r_final_rows = std::min(total_rows, nobs);
913 .topRows(r_final_rows)
914 .template triangularView<Eigen::Upper>();
915 Eigen::BDCSVD<EigenMatrix> svdR(R_final,
916 Eigen::ComputeThinU | Eigen::ComputeThinV);
917 S = svdR.singularValues().head(k);
918 U = svdR.matrixV().leftCols(k);
920 for (
int col = 0; col < k; ++col) {
921 Eigen::Index pivot = 0;
923 for (Eigen::Index row = 0; row < U.rows(); ++row) {
924 const double mag = std::abs(U(row, col));
930 if (U(pivot, col) < 0.0) {
931 U.col(col) = -U.col(col);
932 U_R.col(col) = -U_R.col(col);
937 EigenMatrix stacked_vectors = EigenMatrix::Zero(total_rows, k);
938 stacked_vectors.topRows(U_R.rows()) = U_R;
939 stacked_vectors = (qr_all.householderQ() * stacked_vectors).eval();
942 for (std::size_t idx = 0; idx < my_leaves.size(); ++idx) {
943 const int leaf = my_leaves[idx];
944 const int g0 = leaf * kLeafCols;
945 const int leaf_len =
static_cast<int>(my_leaf_cols[idx].cols());
946 const int rloc = leaf_r_rows[leaf];
947 EigenMatrix local_vectors = EigenMatrix::Zero(leaf_len, k);
948 local_vectors.topRows(rloc) =
949 stacked_vectors.middleRows(leaf_r_offsets[leaf], rloc);
950 V.middleRows(g0, leaf_len) =
951 qr_leaves[idx].householderQ() * local_vectors;
955 st.communication()->view());
964 const int m =
static_cast<int>(B.rows());
965 const int ncols =
static_cast<int>(B.cols());
967 if (L.size() != 0 || !st.has_cached_L() || st.cached_n() != m) {
970 std::vector<double> Lbuf = st.scatter(L, m, m, desc);
971 st.cache_L(std::move(Lbuf), desc, m);
975 std::vector<double> b_buf = st.scatter(B, m, ncols, desc_b);
977 true,
"back_solve_mat", st);
978 return st.gather(b_buf.data(), desc_b, m, ncols);
986 const int* desc,
int m,
989 const int nb = desc[4];
990 const int lld = desc[8];
992 std::vector<ExactSum> total(
static_cast<std::size_t
>(ncols));
993 for (
int local_j = 0; local_j < local_cols; ++local_j) {
996 if (global_j >= ncols)
continue;
997 const double* column =
998 buf.data() +
static_cast<std::size_t
>(local_j) * lld;
999 for (
int tile = st.
myrow(); tile * nb < m; tile += st.
nprow()) {
1000 const int begin = (tile / st.
nprow()) * nb;
1001 const int rows = std::min(nb, m - tile * nb);
1003 for (
int r = 0; r < rows; ++r)
1004 partial.
addProduct(column[begin + r], column[begin + r]);
1005 total[
static_cast<std::size_t
>(global_j)].add(partial.
sum);
1006 total[
static_cast<std::size_t
>(global_j)].add(partial.
corr);
1010 Eigen::VectorXd result(ncols);
1011 for (
int j = 0; j < ncols; ++j)
1012 result(j) = total[
static_cast<std::size_t
>(j)].value();
1017 const std::vector<double>& buf,
const int* desc,
int m,
int ncols,
1020 if (prior.size() != ncols)
1021 throw std::invalid_argument(
1022 "bordered Cholesky prior and cross covariance disagree");
1023 const int nb = desc[4];
1024 const int lld = desc[8];
1026 std::vector<ExactSum> total(
static_cast<std::size_t
>(ncols));
1027 for (
int local_j = 0; local_j < local_cols; ++local_j) {
1028 const int global_j =
1030 if (global_j >= ncols)
continue;
1031 const double* column =
1032 buf.data() +
static_cast<std::size_t
>(local_j) * lld;
1033 for (
int tile = st.
myrow(); tile * nb < m; tile += st.
nprow()) {
1034 const int begin = (tile / st.
nprow()) * nb;
1035 const int rows = std::min(nb, m - tile * nb);
1036 for (
int row = 0; row < rows; ++row) {
1037 const double value = column[begin + row];
1038 total[
static_cast<std::size_t
>(global_j)].addProduct(-value,
1044 Eigen::VectorXd result(ncols);
1045 for (
int column = 0; column < ncols; ++column) {
1046 total[
static_cast<std::size_t
>(column)].add(prior(column));
1047 result(column) = total[
static_cast<std::size_t
>(column)].value();
1056 const int m =
static_cast<int>(B.rows());
1057 const int ncols =
static_cast<int>(B.cols());
1059 if (L.size() != 0 || !st.has_cached_L() || st.cached_n() != m) {
1063 std::vector<double> Lbuf = st.scatter(L, m, m, desc);
1064 st.cache_L(std::move(Lbuf), desc, m);
1068 std::vector<double> b_buf = st.scatter(B, m, ncols, desc_b);
1071 "forward_solve_mat_colwise_squared_norm", st);
1087 const int* desc = st.cached_L_desc();
1088 const double* factor = st.cached_L();
1089 const int myrow = st.myrow(), mycol = st.mycol();
1090 const int nprow = st.nprow(), npcol = st.npcol();
1091 const int row_coord = (myrow - desc[6] + nprow) % nprow;
1092 const int col_coord = (mycol - desc[7] + npcol) % npcol;
1093 const int rows =
numroc_(&m, &desc[4], &myrow, &desc[6], &nprow);
1094 const int cols =
numroc_(&m, &desc[5], &mycol, &desc[7], &npcol);
1095 const std::size_t lld =
static_cast<std::size_t
>(desc[8]);
1096 std::vector<ExactSum> square(1);
1097 for (
int j = 0; j < cols; ++j) {
1098 const int gj = st.global_index_for_local(j, desc[5], col_coord, npcol);
1099 for (
int i = 0; i < rows; ++i) {
1101 st.global_index_for_local(i, desc[4], row_coord, nprow);
1102 if (gi < gj)
continue;
1103 const double value = factor[
static_cast<std::size_t
>(i) +
1104 static_cast<std::size_t
>(j) * lld];
1105 square[0].addProduct(value, value);
1109 const double frobenius = std::sqrt(square[0].value());
1111 const EigenMatrix identity = EigenMatrix::Identity(m, m);
1113 std::vector<double> buffer = st.scatter(identity, m, m, descriptor);
1115 "bordered_cholesky_conditioning", st);
1116 const EigenMatrix inverse = st.gather(buffer.data(), descriptor, m, m);
1117 const double infinity = std::numeric_limits<double>::infinity();
1118 double inverse_norm = infinity;
1119 if (m > 0 && inverse.rows() == m && inverse.cols() == m &&
1120 inverse.allFinite()) {
1121 Eigen::MatrixXd product = Eigen::MatrixXd::Zero(m, m);
1122 Eigen::VectorXd column_abs = Eigen::VectorXd::Zero(m);
1129 std::vector<ExactSum> column_sum(
static_cast<std::size_t
>(m));
1130 for (
int j = 0; j < cols; ++j) {
1132 st.global_index_for_local(j, desc[5], col_coord, npcol);
1133 for (
int i = 0; i < rows; ++i) {
1135 st.global_index_for_local(i, desc[4], row_coord, nprow);
1136 if (gi < gj)
continue;
1137 const double value = factor[
static_cast<std::size_t
>(i) +
1138 static_cast<std::size_t
>(j) * lld];
1139 column_sum[
static_cast<std::size_t
>(gj)].add(std::abs(value));
1143 for (
int column = 0; column < m; ++column)
1144 column_abs(column) =
1145 column_sum[
static_cast<std::size_t
>(column)].value();
1148 constexpr int kRowChunk = 4;
1149 for (
int row0 = 0; row0 < m; row0 += kRowChunk) {
1150 const int nchunk = std::min(kRowChunk, m - row0);
1151 const int count = nchunk * m;
1152 std::vector<ExactSum> partial(
static_cast<std::size_t
>(count));
1153 for (
int j = 0; j < cols; ++j) {
1155 st.global_index_for_local(j, desc[5], col_coord, npcol);
1156 for (
int i = 0; i < rows; ++i) {
1158 st.global_index_for_local(i, desc[4], row_coord, nprow);
1159 if (gi < gj || gi < row0 || gi >= row0 + nchunk)
continue;
1160 const double value =
1161 factor[
static_cast<std::size_t
>(i) +
1162 static_cast<std::size_t
>(j) * lld];
1163 if (value == 0.0)
continue;
1165 partial.data() +
static_cast<std::size_t
>(gi - row0) *
1166 static_cast<std::size_t
>(m);
1167 for (
int k = 0; k < m; ++k)
1168 row[k].addProduct(value, inverse(gj, k));
1172 for (
int r = 0; r < nchunk; ++r) {
1173 for (
int k = 0; k < m; ++k) {
1174 product(row0 + r, k) =
1175 partial[
static_cast<std::size_t
>(r) *
1176 static_cast<std::size_t
>(m) +
1177 static_cast<std::size_t
>(k)]
1182 const double computed = inverse.cwiseAbs().colwise().sum().maxCoeff();
1183 const Eigen::MatrixXd residual = identity - product;
1184 const double residual_norm =
1185 residual.allFinite()
1186 ? residual.cwiseAbs().colwise().sum().maxCoeff()
1188 const double factor_norm = column_abs.maxCoeff();
1200 const Eigen::VectorXd& prior,
1211 const int m =
static_cast<int>(B.rows());
1212 const int ncols =
static_cast<int>(B.cols());
1213 if (prior.size() != ncols)
1214 throw std::invalid_argument(
1215 "bordered Cholesky prior and cross covariance disagree");
1216 if (m == 0 || ncols == 0) {
1217 Eigen::VectorXd diagonal = prior;
1222 if (L.size() != 0 || !st.has_cached_L() || st.cached_n() != m) {
1225 std::vector<double> factor = st.scatter(L, m, m, descriptor);
1226 st.cache_L(std::move(factor), descriptor, m);
1230 std::vector<double> cross = st.scatter(B, m, ncols, descriptor);
1232 false,
"bordered_cholesky_diagonal",
1234 Eigen::VectorXd diagonal =
1257 const EigenMatrix& L, std::vector<double> b_buf,
const int* desc_b,
int m,
1259 const Eigen::VectorXd* prior =
nullptr,
1260 Eigen::VectorXd* posterior_diagonal =
nullptr)
1262 if (m == 0 || ncols == 0) {
1266 if (prior !=
nullptr && posterior_diagonal !=
nullptr) {
1267 if (prior->size() != ncols)
1268 throw std::invalid_argument(
1269 "bordered Cholesky prior and cross covariance disagree");
1270 *posterior_diagonal = *prior;
1274 return EigenMatrix::Zero(ncols, ncols);
1276 if (L.size() != 0 || !st.has_cached_L() || st.cached_n() != m) {
1280 std::vector<double> Lbuf = st.scatter(L, m, m, desc);
1281 st.cache_L(std::move(Lbuf), desc, m);
1284 int local_desc_b[9];
1285 std::copy_n(desc_b, 9, local_desc_b);
1288 "forward_solve_mat_bilinear_distributed", st);
1289 if (prior !=
nullptr && posterior_diagonal !=
nullptr) {
1291 m, ncols, *prior, st);
1297#ifdef GPR_LINALG_SLATE
1298 if (st.reproducible()) {
1299 slate_kernels::configure_nested_blas_threading(st);
1301 st.gather(b_buf.data(), local_desc_b, m, ncols);
1304 int desc_product[9];
1305 st.make_desc(ncols, ncols, desc_product);
1306 std::vector<double> product(
1307 static_cast<std::size_t
>(desc_product[8]) * st.local_cols(ncols), 0.0);
1308 if (!slate_kernels::gram_lower(b_buf.data(), local_desc_b, m, ncols,
1309 product.data(), desc_product, st))
1310 throw std::runtime_error(
"SLATE posterior covariance product failed");
1312 st.gather(product.data(), desc_product, ncols, ncols);
1313 return gathered.selfadjointView<Eigen::Lower>();
1315 int desc_product[9];
1316 st.make_desc(ncols, ncols, desc_product);
1317 if (st.reproducible() ||
1318 st.tile_kernels(local_desc_b,
"pdsyrk", desc_product)) {
1322 st.gather(b_buf.data(), local_desc_b, m, ncols);
1325 std::vector<double> product(
1326 static_cast<std::size_t
>(desc_product[8]) * st.local_cols(ncols), 0.0);
1328 const double alpha = 1.0, beta = 0.0;
1329 pdsyrk_(
"L",
"T", &ncols, &m, &alpha, b_buf.data(), &one, &one,
1330 local_desc_b, &beta, product.data(), &one, &one, desc_product);
1332 st.gather(product.data(), desc_product, ncols, ncols);
1333 return gathered.selfadjointView<Eigen::Lower>();
1338 const EigenMatrix& L, std::vector<double> b_buf,
const int* desc_b,
int m,
1341 if (L.size() != 0 || !st.has_cached_L() || st.cached_n() != m) {
1343 L, m,
"forward_solve_mat_colwise_squared_norm_distributed", st);
1345 std::vector<double> Lbuf = st.scatter(L, m, m, desc);
1346 st.cache_L(std::move(Lbuf), desc, m);
1349 int local_desc_b[9];
1350 std::copy_n(desc_b, 9, local_desc_b);
1353 "forward_solve_mat_colwise_squared_norm_distributed",
1360 const EigenMatrix& L, std::vector<double> b_buf,
const int* desc_b,
int m,
1361 int ncols,
const Eigen::VectorXd& prior,
1364 if (prior.size() != ncols)
1365 throw std::invalid_argument(
1366 "bordered Cholesky prior and cross covariance disagree");
1367 if (m == 0 || ncols == 0) {
1368 Eigen::VectorXd diagonal = prior;
1372 if (L.size() != 0 || !st.has_cached_L() || st.cached_n() != m) {
1376 std::vector<double> factor = st.scatter(L, m, m, descriptor);
1377 st.cache_L(std::move(factor), descriptor, m);
1381 std::copy_n(desc_b, 9, descriptor);
1384 "bordered_cholesky_diagonal_distributed", st);
1385 Eigen::VectorXd diagonal =
1398 if (order <= 0)
return Eigen::VectorXd();
1399 if (L.size() != 0 || !st.has_cached_L() || st.cached_n() != order) {
1401 "cholesky_inverse_diagonal_distributed", st);
1403 std::vector<double> local_factor = st.scatter(L, order, order, desc);
1404 st.cache_L(std::move(local_factor), desc, order);
1406 if (st.reproducible() || st.tile_kernels(st.cached_L_desc(),
"pdtrtri")) {
1410 const int* descriptor = st.cached_L_desc();
1411 const std::size_t count =
1412 static_cast<std::size_t
>(descriptor[8]) * st.local_cols(order);
1413 std::vector<double> work(std::max<std::size_t>(1, count), 0.0);
1417 for (
int k = 0; k < g.
tiles(order); ++k) {
1420 const int bk = g.
span(k, order);
1426 descriptor, work.data(), descriptor, order, order,
1430#ifndef GPR_LINALG_SLATE
1432 const int* descriptor = st.cached_L_desc();
1433 const int stride = descriptor[8];
1434 const int rows = st.local_rows(order), columns = st.local_cols(order);
1435 const std::size_t count =
static_cast<std::size_t
>(stride) * columns;
1436 std::vector<double> work(std::max<std::size_t>(1, count), 0.0);
1437 if (rows > 0 && columns > 0) std::copy_n(st.cached_L(), count, work.data());
1442 if (info != 0)
return Eigen::VectorXd{};
1443 std::vector<ExactSum> exact_diagonal(
static_cast<std::size_t
>(order));
1444 for (
int column = 0; column < columns; ++column) {
1445 const int global_column = st.global_index_for_local(
1446 column, st.block_size(), st.mycol(), st.npcol());
1447 if (global_column >= order)
continue;
1448 for (
int row = 0; row < rows; ++row) {
1449 const int global_row = st.global_index_for_local(
1450 row, st.block_size(), st.myrow(), st.nprow());
1451 if (global_row < global_column || global_row >= order)
continue;
1452 const double value =
1453 work[row +
static_cast<std::size_t
>(column) * stride];
1454 exact_diagonal[
static_cast<std::size_t
>(global_column)].addProduct(
1458 if (st.nprocs() > 1)
1460 st.communication()->view());
1461 Eigen::VectorXd diagonal(order);
1462 for (
int i = 0; i < order; ++i)
1463 diagonal(i) = exact_diagonal[
static_cast<std::size_t
>(i)].value();
1466 int desc_identity[9];
1467 std::vector<double> identity = st.alloc_local(order, order, desc_identity);
1468 if (identity.empty()) identity.resize(1, 0.0);
1469 const int local_rows = st.local_rows(order);
1470 const int local_cols = st.local_cols(order);
1471 for (
int local_j = 0; local_j < local_cols; ++local_j) {
1472 const int global_j = st.global_index_for_local(local_j, st.block_size(),
1473 st.mycol(), st.npcol());
1474 if (global_j >= order ||
1475 (global_j / st.block_size()) % st.nprow() != st.myrow())
1477 const int local_i = st.local_index_for_global(global_j, st.block_size(),
1478 st.myrow(), st.nprow());
1479 if (local_i >= 0 && local_i < local_rows) {
1480 identity[
static_cast<size_t>(local_j) * local_rows + local_i] = 1.0;
1484 L, std::move(identity), desc_identity, order, order, st);
1492 const int m =
static_cast<int>(b.size());
1494 if (L.size() != 0 || !st.has_cached_L() || st.cached_n() != m) {
1497 std::vector<double> Lbuf = st.scatter(L, m, m, desc);
1498 st.cache_L(std::move(Lbuf), desc, m);
1501 int desc_b[9], ncols = 1;
1502 std::vector<double> b_buf = st.scatter_colvector_root(b, m, desc_b);
1504 false,
"forward_solve", st);
1505 EigenMatrix X = st.gather(b_buf.data(), desc_b, m, ncols);
1513 const int m =
static_cast<int>(b.size());
1515 if (L.size() != 0 || !st.has_cached_L() || st.cached_n() != m) {
1518 std::vector<double> Lbuf = st.scatter(L, m, m, desc);
1519 st.cache_L(std::move(Lbuf), desc, m);
1522 int desc_b[9], ncols = 1;
1523 std::vector<double> x_buf = st.scatter_colvector_root(b, m, desc_b);
1525 true,
"back_solve", st);
1526 EigenMatrix X = st.gather(x_buf.data(), desc_b, m, ncols);
1534 const int m =
static_cast<int>(B.rows());
1535 const int ncols =
static_cast<int>(B.cols());
1537 if (L.size() != 0 || !st.has_cached_L() || st.cached_n() != m) {
1540 std::vector<double> Lbuf = st.scatter(L, m, m, desc);
1541 st.cache_L(std::move(Lbuf), desc, m);
1545 std::vector<double> work = st.scatter(B, m, ncols, desc_b);
1548 "trace_cholesky_solve_scalapack", st);
1550 true,
"trace_cholesky_solve_scalapack",
1553 const int diag_n = std::min(m, ncols);
1554 const int local_rows = st.local_rows(m);
1558 for (
int i = 0; i < diag_n; ++i) {
1559 const int owner_row = (i / st.block_size()) % st.nprow();
1560 const int owner_col = (i / st.block_size()) % st.npcol();
1561 if (owner_row != st.myrow() || owner_col != st.mycol())
continue;
1563 const int local_i = st.local_index_for_global(i, st.block_size(),
1564 st.myrow(), st.nprow());
1565 const int local_j = st.local_index_for_global(i, st.block_size(),
1566 st.mycol(), st.npcol());
1567 local_trace.
add(work[
static_cast<size_t>(local_i) +
1568 static_cast<size_t>(local_j) * local_rows]);
1572 return local_trace.
value();
1583 const EigenMatrix& L,
const double* B_dist,
const int* desc_b,
int m,
1586 if (L.size() != 0 || !st.has_cached_L() || st.cached_n() != m) {
1588 L, m,
"trace_cholesky_solve_scalapack_distributed_local", st);
1590 std::vector<double> Lbuf = st.scatter(L, m, m, desc);
1591 st.cache_L(std::move(Lbuf), desc, m);
1594 const int local_rows = st.local_rows(m);
1595 const int local_cols = st.local_cols(ncols);
1596 std::vector<double> work(
1597 B_dist, B_dist +
static_cast<size_t>(local_rows) * local_cols);
1601 "trace_cholesky_solve_scalapack_distributed_local",
1605 "trace_cholesky_solve_scalapack_distributed_local",
1608 const int diag_n = std::min(m, ncols);
1610 for (
int i = 0; i < diag_n; ++i) {
1611 const int owner_row = (i / st.block_size()) % st.nprow();
1612 const int owner_col = (i / st.block_size()) % st.npcol();
1613 if (owner_row != st.myrow() || owner_col != st.mycol())
continue;
1615 const int local_i = st.local_index_for_global(i, st.block_size(),
1616 st.myrow(), st.nprow());
1617 const int local_j = st.local_index_for_global(i, st.block_size(),
1618 st.mycol(), st.npcol());
1619 local_trace.
add(work[
static_cast<size_t>(local_i) +
1620 static_cast<size_t>(local_j) * local_rows]);
1627 const EigenMatrix& L,
const double* B_dist,
const int* desc_b,
int m,
1631 L, B_dist, desc_b, m, ncols, st);
1633 return trace.
value();
1645 std::vector<double>& inverse,
int* desc,
1651 std::vector<double> Lbuf = st.
scatter(L, n, n, factor_desc);
1652 st.
cache_L(std::move(Lbuf), factor_desc, n);
1655 const auto copyFactor = [&] {
1660#ifdef GPR_LINALG_SLATE
1662 slate_kernels::configure_nested_blas_threading(st);
1670 return slate_kernels::potri_lower(inverse.data(), desc, n, st);
1684 int info = 0, one = 1;
1685 pdpotri_(
"L", &n, inverse.data(), &one, &one, desc, &info);
1697template <
class Entry>
1705 const long blocks = (lc + nb - 1) / nb;
1706 std::vector<ExactSum> partial(
static_cast<size_t>(std::max(1L, blocks)));
1708 ExactSum& sum = partial[
static_cast<size_t>(block)];
1709 const int j0 =
static_cast<int>(block) * nb;
1710 for (
int jl = j0; jl < std::min(lc, j0 + nb); ++jl) {
1711 const int j = (jl / nb * st.
npcol() + st.
mycol()) * nb + jl % nb;
1712 for (
int il = 0; il < lr; ++il) {
1714 (il / nb * st.
nprow() + st.
myrow()) * nb + il % nb;
1715 if (i < j)
continue;
1718 A[
static_cast<size_t>(il) +
static_cast<size_t>(jl) * lda],
1738 if (B !=
nullptr && (B->rows() != n || B->cols() != n)) {
1740 std::fprintf(stderr,
1741 "[gpr::linalg::trace_inverse_times_symmetric] "
1742 "matrix is %ldx%ld, factor order %d\n",
1743 static_cast<long>(B->rows()),
1744 static_cast<long>(B->cols()), n);
1747 std::vector<double> inverse;
1750 int all_ok = ok ? 1 : 0;
1751 MPI_Allreduce(MPI_IN_PLACE, &all_ok, 1, MPI_INT, MPI_MIN, st.world_comm());
1752 if (!all_ok)
return std::numeric_limits<double>::quiet_NaN();
1754 inverse.data(), std::max(1, desc[8]), n,
1755 [&](
int i,
int j,
int,
int) {
1756 return B != nullptr ? (*B)(i, j) : (i == j ? 1.0 : 0.0);
1760 return local.
value();
1766 const int n = (L.rows() > 0) ?
static_cast<int>(L.rows()) : st.cached_n();
1768 if (L.size() == 0 && st.has_cached_inv() && st.cached_inv_n() == n) {
1770 st.gather(st.cached_inv(), st.cached_inv_desc(), n, n,
true);
1771 if (invC.size() != 0) {
1772 for (
int j = 0; j < n; ++j)
1773 for (
int i = 0; i < j; ++i)
1774 invC(i, j) = invC(j, i);
1779 std::vector<double> work;
1782 st.cache_inv(std::move(work), desc, n);
1785 st.gather(st.cached_inv(), st.cached_inv_desc(), n, n,
true);
1786 if (invC.size() != 0) {
1787 for (
int j = 0; j < n; ++j)
1788 for (
int i = 0; i < j; ++i)
1789 invC(i, j) = invC(j, i);
1797 const int n = (L.rows() > 0) ?
static_cast<int>(L.rows()) : st.cached_n();
1798 if (L.size() == 0 && st.has_cached_L() && st.cached_n() == n &&
1799 st.has_cached_inv() && st.cached_inv_n() == n)
1804 std::vector<double> work;
1807 st.cache_inv(std::move(work), desc, n);
1811 const double* lower_colmajor,
int leading_dim,
int n,
1812 const EigenMatrix& block,
int row_component,
int col_component,
1813 int tile_size,
bool transpose_block =
false)
1815 const Eigen::Index obs_rows = transpose_block ? block.cols() : block.rows();
1816 const Eigen::Index obs_cols = transpose_block ? block.rows() : block.cols();
1819 for (Eigen::Index local_j = 0; local_j < obs_cols; ++local_j) {
1820 const int global_col =
1821 static_cast<int>(local_j) * tile_size + col_component;
1822 for (Eigen::Index local_i = 0; local_i < obs_rows; ++local_i) {
1823 const int global_row =
1824 static_cast<int>(local_i) * tile_size + row_component;
1825 if (global_row < global_col)
continue;
1826 if (global_row >= n || global_col >= n)
continue;
1828 const double value = transpose_block ? block(local_j, local_i)
1829 : block(local_i, local_j);
1830 const double weight = (global_row == global_col) ? 1.0 : 2.0;
1831 const size_t inv_idx =
static_cast<size_t>(global_row) +
1832 static_cast<size_t>(global_col) *
1833 static_cast<size_t>(leading_dim);
1834 trace += weight * lower_colmajor[inv_idx] * value;
1841 const EigenMatrix& block,
int row_component,
int col_component,
1842 int tile_size,
bool transpose_block =
false,
1845 if (!st.has_cached_inv()) {
1847 std::fprintf(stderr,
1848 "[gpr::linalg::cached_inverse_observation_tile_"
1849 "trace_np1] cached inverse missing\n");
1853 if (st.nprocs() != 1) {
1855 std::fprintf(stderr,
1856 "[gpr::linalg::cached_inverse_observation_tile_"
1857 "trace_np1] requires nprocs=1, got %d\n",
1862 if (tile_size <= 0 || row_component < 0 || col_component < 0 ||
1863 row_component >= tile_size || col_component >= tile_size) {
1865 std::fprintf(stderr,
1866 "[gpr::linalg::cached_inverse_observation_tile_"
1867 "trace_np1] invalid tile layout: row_component=%d "
1868 "col_component=%d tile_size=%d\n",
1869 row_component, col_component, tile_size);
1874 const int n = st.cached_inv_n();
1875 const int inv_local_rows = st.local_rows(n);
1876 const Eigen::Index obs_rows = transpose_block ? block.cols() : block.rows();
1877 const Eigen::Index obs_cols = transpose_block ? block.rows() : block.cols();
1880 ? (
static_cast<int>(obs_rows) - 1) * tile_size + row_component
1884 ? (
static_cast<int>(obs_cols) - 1) * tile_size + col_component
1886 if (max_row >= n || max_col >= n) {
1888 std::fprintf(stderr,
1889 "[gpr::linalg::cached_inverse_observation_tile_"
1890 "trace_np1] tile indices exceed cached inverse "
1891 "size %d: max_row=%d max_col=%d\n",
1892 n, max_row, max_col);
1897 st.cached_inv(), inv_local_rows, n, block, row_component, col_component,
1898 tile_size, transpose_block);
1902 const double* B_dist,
const int* desc_b,
int n,
1905 if (!st.has_cached_inv() || st.cached_inv_n() != n) {
1907 std::fprintf(stderr,
1908 "[gpr::linalg::trace_cached_inverse_times_"
1909 "symmetric_distributed] cached inverse missing: "
1910 "requested n=%d, cached_inv_n=%d, has_cached_inv=%d\n",
1911 n, st.cached_inv_n(), st.has_cached_inv() ? 1 : 0);
1915 if (desc_b ==
nullptr) {
1917 std::fprintf(stderr,
1918 "[gpr::linalg::trace_cached_inverse_times_"
1919 "symmetric_distributed] null distributed matrix\n");
1924 const int inv_local_rows = st.local_rows(n);
1925 const int b_owned_rows = st.local_rows(n);
1926 const int b_owned_cols = st.local_cols(n);
1927 if (B_dist ==
nullptr && b_owned_rows > 0 && b_owned_cols > 0) {
1929 std::fprintf(stderr,
1930 "[gpr::linalg::trace_cached_inverse_times_"
1931 "symmetric_distributed] null non-empty local block\n");
1935 const int b_local_rows = std::max(1, desc_b[8]);
1936 const double* inv_dist = st.cached_inv();
1941 for (
int global_col = 0; global_col < n; ++global_col) {
1942 for (
int global_row = global_col; global_row < n; ++global_row) {
1943 if (!st.owns_global_entry(global_row, global_col))
continue;
1945 const int local_i = st.local_index_for_global(
1946 global_row, st.block_size(), st.myrow(), st.nprow());
1947 const int local_j = st.local_index_for_global(
1948 global_col, st.block_size(), st.mycol(), st.npcol());
1949 const size_t inv_idx =
static_cast<size_t>(local_i) +
1950 static_cast<size_t>(local_j) *
1951 static_cast<size_t>(inv_local_rows);
1952 const size_t b_idx =
static_cast<size_t>(local_i) +
1953 static_cast<size_t>(local_j) *
1954 static_cast<size_t>(b_local_rows);
1956 const double weight = (global_row == global_col) ? 1.0 : 2.0;
1963 return local_trace.
value();
1969 const int n = (L.rows() > 0) ?
static_cast<int>(L.rows()) : st.cached_n();
1971 std::vector<double> work;
1973 if (L.size() == 0 && st.has_cached_L() && st.cached_n() == n) {
1974 int lr = st.local_rows(n), lc = st.local_cols(n);
1975 work.assign(st.cached_L(),
1976 st.cached_L() +
static_cast<size_t>(lr) * lc);
1977 std::copy_n(st.cached_L_desc(), 9, desc);
1979 work = st.scatter(L, n, n, desc);
1982 if (st.reproducible() || st.tile_kernels(desc,
"pdpotri")) {
1984 std::vector<double> inverse;
1986 work = std::move(inverse);
1988 int info = 0, one = 1;
1989 pdpotri_(
"L", &n, work.data(), &one, &one, desc, &info);
1997 EigenMatrix invC = st.gather(work.data(), desc, n, n,
false);
1998 if (invC.size() != 0) {
1999 for (
int j = 0; j < n; ++j)
2000 for (
int i = 0; i < j; ++i)
2001 invC(i, j) = invC(j, i);
2011 const auto sz = A.size();
2013 const double* a = A.data();
2014 const double* b = B.data();
2015 for (Eigen::Index i = 0; i < sz; ++i)
2018 if (st.nprocs() == 1)
return sum;
2020 double result = 0.0;
2021 if (st.is_root()) result = sum;
2022 MPI_Bcast(&result, 1, MPI_DOUBLE, 0, st.world_comm());
2038 if (L.rows() > 0 && L.cols() > 0) {
2039 const int n =
static_cast<int>(L.rows());
2041 for (
int i = 0; i < n; ++i)
2045 if (!st.has_cached_L())
return 0.0;
2047 const int n = st.cached_n();
2048 const int local_rows = st.local_rows(n);
2052 for (
int i = 0; i < n; ++i) {
2053 const int owner_row = (i / st.block_size()) % st.nprow();
2054 const int owner_col = (i / st.block_size()) % st.npcol();
2055 if (owner_row != st.myrow() || owner_col != st.mycol())
continue;
2057 const int local_i = st.local_index_for_global(i, st.block_size(),
2058 st.myrow(), st.nprow());
2059 const int local_j = st.local_index_for_global(i, st.block_size(),
2060 st.mycol(), st.npcol());
2062 st.cached_L()[
static_cast<size_t>(local_i) +
2063 static_cast<size_t>(local_j) * local_rows]));
2067 return local_sum.
value();
Triangular solves and Cholesky inverse whose floating-point result does not depend on the process gri...
Correctly rounded Schur-complement diagonals from Cholesky solves.
int numroc_(const int *n, const int *nb, const int *iproc, const int *isrcproc, const int *nprocs)
void pdsyevr_(const char *jobz, const char *range, const char *uplo, const int *n, double *a, const int *ia, const int *ja, const int *desca, const double *vl, const double *vu, const int *il, const int *iu, int *m, int *nz, double *w, double *z, const int *iz, const int *jz, const int *descz, double *work, const int *lwork, int *iwork, const int *liwork, int *info)
bool pdsyevr_available_()
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 pdsyev_(const char *jobz, const char *uplo, const int *n, double *a, const int *ia, const int *ja, const int *desca, double *w, double *z, const int *iz, const int *jz, const int *descz, double *work, const int *lwork, int *info)
void pdgesvd_(const char *jobu, const char *jobvt, const int *m, const int *n, double *a, const int *ia, const int *ja, const int *desca, double *s, double *u, const int *iu, const int *ju, const int *descu, double *vt, const int *ivt, const int *jvt, const int *descvt, double *work, const int *lwork, int *info)
void pdpotrf_(const char *uplo, const int *n, double *a, const int *ia, const int *ja, const int *desca, int *info)
void pdtrsm_(const char *side, const char *uplo, const char *trans, const char *diag, const int *m, const int *n, const double *alpha, const double *a, const int *ia, const int *ja, const int *desca, double *b, const int *ib, const int *jb, const int *descb)
void pdsyrk_(const char *uplo, const char *trans, const int *n, const int *k, const double *alpha, const double *a, const int *ia, const int *ja, const int *desca, const double *beta, double *c, const int *ic, const int *jc, const int *descc)
void pdsyevd_(const char *jobz, const char *uplo, const int *n, double *a, const int *ia, const int *ja, const int *desca, double *w, double *z, const int *iz, const int *jz, const int *descz, double *work, const int *lwork, int *iwork, const int *liwork, int *info)
bool pdsyevd_available_()
void pdpotri_(const char *uplo, const int *n, double *a, const int *ia, const int *ja, const int *desca, int *info)
bool compute(const Eigen::MatrixBase< Derived > &diagonal)
double physicalFactor(double value, Eigen::Index row) const noexcept
double covariance(double value, Eigen::Index row, Eigen::Index column) const noexcept
int local_rows(int m) const
int global_index_for_local(int local_index, int block_size, int proc_coord, int nprocs_dim) const
void cache_L(std::vector< double > L_dist, const int *desc, int n)
bool tile_kernels(const int *desc, const char *routine, const int *other=nullptr) const
bool has_cached_L() const
MPI_Comm world_comm() const
void cache_U(std::vector< double > U)
int local_index_for_global(int global_index, int block_size, int proc_coord, int nprocs_dim) const
const int * cached_L_desc() const
int local_cols(int n) const
const double * cached_U() const
std::vector< double > scatter(const EigenMatrix &global, int m, int n, int *desc) const
static DistributedState & instance()
bool reproducible() const noexcept
bool has_cached_U() const noexcept
const double * cached_L() const
void add(double x) noexcept
double value() const noexcept
The exact sum rounded once to the nearest double, ties to even.
void addTripleProduct(double a, double b, double c) noexcept
void merge(const ExactSum &other) noexcept
Adds another accumulator exactly.
int concurrency() const noexcept
static ScalapackLib & instance()
ScopedSolveThreads & operator=(const ScopedSolveThreads &)=delete
static int solveThreadTarget() noexcept
ScopedSolveThreads(const ScopedSolveThreads &)=delete
ScopedSolveThreads() noexcept
void trsmCachedLowerFactor(DistributedState &st, double *B, const int *desc_b, int n, int ncols, bool transpose)
Eigen::MatrixXd gramTiles(const Eigen::MatrixXd &x, int nb)
TileMap tileAt(double *base, int lld, const TileGeometry &g, int row_tile, int col_tile, int rows, int cols)
bool potrfLower(DistributedState &st, double *A, const int *desc, int n, int n_factored=0)
void choleskyInverseLower(DistributedState &st, const double *L, const int *desc, int n, std::vector< double > &inverse, std::optional< const double * > upper=std::nullopt)
TileGeometry geometryOf(DistributedState &st, const int *desc)
void trsm(DistributedState &st, Triangle triangle, const double *T, const int *desc_t, double *B, const int *desc_b, int n, int ncols, bool lower_rhs)
std::vector< double > transposeFactor(DistributedState &st, const double *L, const int *desc, int n, std::int64_t batch_entries=0)
Dense and structured linear algebra behind the GP: Cholesky and eigen solvers, linear operators,...
int blasThreadCount() noexcept
double cachedFactorSchurRelativeError(int m, DistributedState &st=DistributedState::instance())
EigenMatrix back_solve_mat(const EigenMatrix &L, const EigenMatrix &B)
Back triangular solve with matrix RHS (BLAS equivalent: dtrsm with side=L, uplo=L,...
Eigen::VectorXd columnSquaredNormsExact(const std::vector< double > &buf, const int *desc, int m, int ncols, DistributedState &st)
void requireStablePosteriorVariance(double &variance, double signal_variance, double relative_allowance)
Accept one stable posterior variance or throw.
Eigen::VectorXd forward_solve(const EigenMatrix &L, const Eigen::VectorXd &b)
Forward triangular solve with vector RHS (BLAS equivalent: dtrsv).
void disjoint_sum_bcast(double *data, int count, const MpiContext &context)
ExactSum trace_cholesky_solve_scalapack_distributed_local(const EigenMatrix &L, const double *B_dist, const int *desc_b, int m, int ncols, DistributedState &st=DistributedState::instance())
double choleskySchurRelativeError(Eigen::Index order, double factor_frobenius_norm, double inverse_norm1) noexcept
Relative forward error of a Schur complement computed from a rounded Cholesky factor and triangular s...
bool distributed_gemm_nn(const EigenMatrix &A, const EigenMatrix &B, EigenMatrix &C, DistributedState &st=DistributedState::instance())
void requireStableSchurDiagonal(Eigen::VectorXd &variance, const Eigen::VectorXd &signal, RelativeError &&relative_error)
requireStablePosteriorVariance over a Schur diagonal whose allowance is the forward error of a solve.
bool distributed_thin_svd_colblock(const EigenMatrix &A_local, int m, int n, EigenMatrix &U, Eigen::VectorXd &S, EigenMatrix &V, DistributedState &st=DistributedState::instance())
EigenMatrix forward_solve_mat(const EigenMatrix &L, const EigenMatrix &B)
Forward triangular solve with matrix RHS (BLAS equivalent: dtrsm).
ExactSum trace_lower_symmetric_local(const double *A, int lda, int n, Entry &&b, DistributedState &st)
void ordered_sum_bcast(double *data, int count, const MpiContext &context)
Eigen::VectorXd bordered_cholesky_diagonal_distributed(const EigenMatrix &L, std::vector< double > b_buf, const int *desc_b, int m, int ncols, const Eigen::VectorXd &prior, DistributedState &st=DistributedState::instance())
Eigen::VectorXd columnSchurComplementsExact(const std::vector< double > &buf, const int *desc, int m, int ncols, const Eigen::VectorXd &prior, DistributedState &st)
bool stablePosteriorVarianceEnabled() noexcept
Whether stable posterior variance reductions are enabled.
void configureLinalgThreads(int threads)
bool distributed_thin_svd_tsqr(const EigenMatrix &A_local, int nobs, int N, EigenMatrix &U, Eigen::VectorXd &S, EigenMatrix &V, DistributedState &st=DistributedState::instance())
Eigen::VectorXd forward_solve_mat_colwise_squared_norm(const EigenMatrix &L, const EigenMatrix &B)
Forward triangular solve followed by columnwise squared norms.
void parallelFor(long count, F &&fn)
parallelFor(count, fn): see TilePool::run.
bool exceedsLp64(const int *desc, int nprow, int npcol) noexcept
Eigen::VectorXd cholesky_inverse_diagonal_distributed(const EigenMatrix &L, int order, DistributedState &st=DistributedState::instance())
void replicate_owned_values(double *data, std::size_t count, const MpiContext &context)
bool unconstrainedLibraryReductions() noexcept
int lp64Workspace(double query, const char *routine, const DistributedState &st)
double observation_tile_lower_trace_colmajor_unchecked(const double *lower_colmajor, int leading_dim, int n, const EigenMatrix &block, int row_component, int col_component, int tile_size, bool transpose_block=false)
EigenMatrix cholesky_inverse_root(const EigenMatrix &L, DistributedState &st=DistributedState::instance())
double cached_inverse_observation_tile_trace_np1(const EigenMatrix &block, int row_component, int col_component, int tile_size, bool transpose_block=false, DistributedState &st=DistributedState::instance())
void exact_sum_bcast(ExactSum *sums, int count, const MpiContext &context)
double trace_inverse_times_symmetric(const EigenMatrix &L, const EigenMatrix *B, int n, DistributedState &st=DistributedState::instance())
void transformDistributedLower(std::vector< double > &buffer, const int *desc, int n, const CovarianceEquilibration &scaling, bool restore_factor, DistributedState &st)
double upperInverseNorm1FromResidual(double computed_norm, double residual_norm, double factor_abs_norm, Eigen::Index order) noexcept
Upper bound on ||L^-1||_1 from a computed triangular solve.
double log_det_cholesky(const EigenMatrix &L)
Half log-determinant from Cholesky factor.
Eigen::VectorXd back_solve(const EigenMatrix &L, const Eigen::VectorXd &b)
Back triangular solve with vector RHS (BLAS equivalent: dtrsv).
bool distributed_symmetric_eigen(const EigenMatrix &A, Eigen::VectorXd &eigenvalues, EigenMatrix &eigenvectors, const char **driver_name=nullptr, DistributedState &st=DistributedState::instance())
bool tryTrainingProduct(ConstProductMatrix a, ConstProductMatrix b, ProductMatrix c, bool transpose_a, bool transpose_b, double alpha, double beta, bool partitioned)
double trace_cholesky_solve_scalapack(const EigenMatrix &L, const EigenMatrix &B, DistributedState &st=DistributedState::instance())
double trace_product(const EigenMatrix &A, const EigenMatrix &B)
Frobenius inner product / trace of matrix product.
Eigen::VectorXd bordered_cholesky_diagonal(const EigenMatrix &L, const EigenMatrix &B, const Eigen::VectorXd &prior)
Posterior diagonal from bordered Cholesky pivots.
EigenMatrix cholesky_inverse(const EigenMatrix &L)
Symmetric inverse from Cholesky factor (LAPACK equivalent: dpotri).
bool factor_inverse_lower(const EigenMatrix &L, int n, std::vector< double > &inverse, int *desc, DistributedState &st)
void requireRebuildableDenseL(const EigenMatrix &L, int m, const char *fn, DistributedState &st=DistributedState::instance())
void cached_trsm_left_lower(int m, int ncols, double *b_buf, const int *desc_b, bool transpose, const char *fn, DistributedState &st=DistributedState::instance())
bool distributed_thin_svd(const EigenMatrix &A, EigenMatrix &U, Eigen::VectorXd &S, EigenMatrix &V, DistributedState &st=DistributedState::instance())
bool cholesky(const EigenMatrix &C, EigenMatrix &L)
Cholesky decomposition (LAPACK equivalent: dpotrf).
constexpr Eigen::Index kMinDistributedGemmOrder
bool equilibrateDistributedLower(std::vector< double > &buffer, const int *desc, int n, CovarianceEquilibration &scaling, DistributedState &st)
EigenMatrix forward_solve_mat_bilinear_distributed(const EigenMatrix &L, std::vector< double > b_buf, const int *desc_b, int m, int ncols, DistributedState &st=DistributedState::instance(), const Eigen::VectorXd *prior=nullptr, Eigen::VectorXd *posterior_diagonal=nullptr)
int affinityCpuCount() noexcept
CPUs in this process's scheduling affinity, or 0 when unknown.
bool trainingProductConfigured()
A device library or an in-process engine is configured.
Eigen::VectorXd forward_solve_mat_colwise_squared_norm_distributed(const EigenMatrix &L, std::vector< double > b_buf, const int *desc_b, int m, int ncols, DistributedState &st=DistributedState::instance())
double trace_cholesky_solve_scalapack_distributed(const EigenMatrix &L, const double *B_dist, const int *desc_b, int m, int ncols, DistributedState &st=DistributedState::instance())
constexpr std::int64_t kLp64IndexLimit
Largest element offset an LP64 ScaLAPACK routine forms without overflow.
double trace_cached_inverse_times_symmetric_distributed(const double *B_dist, const int *desc_b, int n, DistributedState &st=DistributedState::instance())
bool trainingCholeskyDistributedSelected(Eigen::Index order)
void cache_cholesky_inverse(const EigenMatrix &L, DistributedState &st=DistributedState::instance())
bool cholesky_distributed(std::vector< double > C_dist, const int *desc, int n, EigenMatrix &L, DistributedState &st=DistributedState::instance())
constexpr Eigen::Index kMinDistributedSymmetricEigenOrder
void requireCachedFactorSchurDiagonal(Eigen::VectorXd &diagonal, const Eigen::VectorXd &prior, int m, DistributedState &st)
double log(double x) noexcept
Gaussian-process regression, kernels, priors, and the searches that run on the surrogate.
Eigen::Matrix< double, EigenDynamic, EigenDynamic, EigenMatrixStorage > EigenMatrix
void addProduct(double left, double right)
int tiles(int extent) const
int ownerRow(int tile) const
int ownerCol(int tile) const
int span(int tile, int extent) const