Loading...
Searching...
No Matches
ScalapackBackend.h
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// Copyright (c) gpridge developers
3// See LICENSE for details.
4
5// ScaLAPACK backend -- MPI-distributed dense linear algebra.
6// Implements the 7 gpr::linalg functions using pdpotrf/pdtrsm/pdpotri
7// over a 2D block-cyclic BLACS process grid.
8
9#ifndef GPR_LINALG_SCALAPACKBACKEND_H_
10#define GPR_LINALG_SCALAPACKBACKEND_H_
11
12#include <algorithm>
13#include <cmath>
14#include <cstdio>
15#include <cstdlib>
16#include <limits>
17#include <stdexcept>
18#include <string>
19#include <vector>
20
22#include "CanonicalTriangular.h"
23#include "CompensatedSum.h"
25#include "DistributedState.h"
26#include "ExactSchur.h"
27#include "LinalgThreads.h"
28#include "LocalExecutor.h"
29#include "MpiCollectives.h"
30#include "TeamFactor.h"
31#include "TrainingProduct.h"
32#ifdef GPR_LINALG_SLATE
33#include "SlateKernels.h"
34#endif
35#include "TrainingCholesky.h"
36// pdpotrf_/pdtrsm_/pdpotri_/pdgemv_/pdsyrk_/pdtran_ and the BLACS symbols are
37// runtime-loaded forwarders from ScalapackLib.h (pulled in via
38// DistributedState.h above); the incremental-Cholesky append path uses pdsyrk
39// (Schur complement D - Y^T Y, uplo='L', trans='T') and pdtran (transpose Y
40// into the appended L_new bottom-left block).
41
42namespace gpr {
43namespace linalg {
44
45// Hard-fail when a distributed solve is asked to rebuild its
46// Cholesky cache from a dense L matrix that has been resized to
47// 0x0 by an earlier distributed factorisation. The recovery
48// branch in forward_solve / back_solve / forward_solve_*_distributed
49// (cache invalid OR cached_n != m) calls
50// ~DistributedState::scatter(L, m, m, desc)~, which on rank 0 passes
51// ~global_data = &dummy~ when ~L.size() == 0~ but tells Cpdgemr2d
52// the global block is ~m x m~. Cpdgemr2d then walks off the
53// stack-allocated ~dummy~ pointer -- segfault inside the BLACS
54// redistribution.
55//
56// The legitimate reach into this branch is a caller that knows
57// the cache is stale and provides a fresh dense L (e.g. unit
58// tests calling forward_solve on a hand-built L). The illegitimate
59// reach is a caller whose dense L was overwritten by
60// ~cholesky_distributed~ on a different GP instance (e.g. OCINEB's
61// internal AtomicDimer GP trains, mutates the singleton cache to
62// its own size, then control returns to the NEB GP whose dense L
63// is 0x0). The legitimate path keeps L; the illegitimate path
64// aborts here with a diagnostic instead of segfaulting deeper in
65// Cpdgemr2d.
66//
67// Why abort instead of silently rebuild: rebuilding from R_matrix
68// requires a full pdpotrf, but the L this function takes is the
69// raw factor -- we have no R_matrix in scope. Returning a zero or
70// junk solution silently corrupts the variance computation, which
71// is the bug class the abort is meant to prevent. The fix is at
72// the call site (refresh the cache via decomposeCovarianceMatrix
73// before the next solve), not here.
75 const EigenMatrix& L, int m, const char* fn,
77{
78 if (L.rows() != 0 && L.cols() != 0) {
79 st.initialize();
80 return;
81 }
82 if (st.is_root()) {
83 std::fprintf(
84 stderr,
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);
92 }
93 std::abort();
94}
95
97 double* data, int count,
99{
100 if (count <= 0 || st.nprocs() == 1) return;
101 ordered_sum_bcast(data, count, st.communication()->view());
102}
103
104inline void exact_sum_bcast(ExactSum* sums, int count,
106{
107 if (count <= 0 || st.nprocs() == 1) return;
108 exact_sum_bcast(sums, count, st.communication()->view());
109}
110
130 double* data, int count,
132{
133 if (count <= 0) return;
134
135 if (st.nprocs() == 1) return;
136
137 disjoint_sum_bcast(data, count, st.communication()->view());
138}
139
140// Replicated inputs and output, with each rank computing disjoint output
141// columns. Column-major storage makes each contribution contiguous; gathering
142// these blocks requires no floating-point reduction. All ranks must provide
143// identical input matrices, and C must be distinct from A and B.
145 const EigenMatrix& A, const EigenMatrix& B, EigenMatrix& C,
147{
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()))
152 return false;
153
154 st.initialize();
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;
159 const bool device_product = trainingProductConfigured();
160 const bool global_device_product =
161 device_product && std::min({A.rows(), A.cols(), B.cols()}) >= 128;
162 int failed = 0;
163 std::string failure;
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);
167 try {
168 auto output = C.middleCols(start, count);
169 if (!global_device_product ||
170 !tryTrainingProduct(A, B.middleCols(start, count), output,
171 false, false, 1.0, 0.0, true))
172 output.noalias() = A * B.middleCols(start, count);
173 } catch (const std::exception& exception) {
174 failed = 1;
175 failure = exception.what();
176 break;
177 }
178 }
179 // Every rank reaches the same error decision before the output gather.
180 if (device_product && st.nprocs() > 1)
181 MPI_Allreduce(MPI_IN_PLACE, &failed, 1, MPI_INT, MPI_MAX,
182 st.world_comm());
183 if (failed)
184 throw std::runtime_error(failure.empty()
185 ? "training product failed on another rank"
186 : failure);
187 if (st.nprocs() == 1) return true;
188
189 replicate_owned_values(C.data(), static_cast<std::size_t>(C.size()),
190 st.communication()->view());
191 return true;
192}
193
194// Small products keep the local BLAS path to avoid collective latency.
195inline constexpr Eigen::Index kMinDistributedGemmOrder = 512;
196
200public:
202 : previous_(blasThreadCount()),
203 target_(solveThreadTarget()),
204 raised_(previous_ > 0 && target_ > previous_)
205 {
206 if (raised_) configureLinalgThreads(target_);
207 if (std::getenv("GPR_GEOM_DEBUG") != nullptr) {
208 static bool reported = false;
209 if (!reported) {
210 reported = true;
211 std::fprintf(stderr,
212 "[solve-threads] previous=%d target=%d raised=%d "
213 "now=%d\n",
214 previous_, target_, raised_ ? 1 : 0,
216 }
217 }
218 }
219
221 [[nodiscard]] static int solveThreadTarget() noexcept
222 {
223 const int affinity = affinityCpuCount();
224 const int workers = LocalExecutor().concurrency();
225 return affinity > 0 ? std::min(affinity, workers) : workers;
226 }
228 {
229 if (raised_) configureLinalgThreads(previous_);
230 }
233
234private:
235 int previous_ = 0;
236 int target_ = 0;
237 bool raised_ = false;
238};
239
245inline int lp64Workspace(double query, const char* routine,
246 const DistributedState& st)
247{
248 double size = std::ceil(std::max(1.0, query));
249 if (st.nprocs() > 1)
250 MPI_Allreduce(MPI_IN_PLACE, &size, 1, MPI_DOUBLE, MPI_MAX,
251 st.world_comm());
252 if (!(size <= static_cast<double>(kLp64IndexLimit)))
253 throw std::length_error(
254 std::string(routine) + " asks for a workspace of " +
255 std::to_string(size) + " entries, past the " +
256 std::to_string(kLp64IndexLimit) +
257 " an LP64 ScaLAPACK indexes; run on more processes");
258 // This process's own query is at most the grid's largest, so it fits.
259 return static_cast<int>(std::ceil(std::max(1.0, query)));
260}
261
263 int m, int ncols, double* b_buf, const int* desc_b, bool transpose,
264 const char* fn, DistributedState& st = DistributedState::instance())
265{
266#ifdef GPR_LINALG_SLATE
267 if (st.reproducible()) {
268 slate_kernels::configure_nested_blas_threading(st);
269 // Substitution follows the fixed tile order of the factorization.
270 canonical::trsmCachedLowerFactor(st, b_buf, desc_b, m, ncols,
271 transpose);
272 return;
273 }
274 if (slate_kernels::trsm_left_lower(st.cached_L(), st.cached_L_desc(), m,
275 b_buf, desc_b, ncols, transpose, st)) {
276 return;
277 }
278 if (st.is_root()) {
279 std::fprintf(stderr,
280 "[gpr::linalg::%s] SLATE triangular solve failed\n", fn);
281 }
282 std::abort();
283#else
284 (void)fn;
285 if (st.reproducible() ||
286 st.tile_kernels(st.cached_L_desc(), "pdtrsm", desc_b)) {
287 // Tile-ordered substitution: the result does not depend on the grid.
288 ScopedTileKernelThreads tile_threads(st);
289 canonical::trsmCachedLowerFactor(st, b_buf, desc_b, m, ncols,
290 transpose);
291 return;
292 }
293 // ScaLAPACK uses the rank's idle cores for BLAS. SLATE manages its own
294 // task team and requires a single BLAS thread inside each task.
295 ScopedSolveThreads solve_threads;
297 int one = 1;
298 double alpha = 1.0;
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);
302#endif
303}
304
305// Only the diagonal is replicated. Matrix entries and the physical factor
306// stay in their block-cyclic layout throughout the conditioning operation.
307inline void transformDistributedLower(std::vector<double>& buffer,
308 const int* desc, int n,
309 const CovarianceEquilibration& scaling,
310 bool restore_factor, DistributedState& st)
311{
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) {
322 const int gi = st.global_index_for_local(i, desc[4], row_coord, nprow);
323 global_rows[static_cast<std::size_t>(i)] = gi;
324 if (restore_factor)
325 inverse_rows[static_cast<std::size_t>(i)] =
326 scaling.physicalFactor(1.0, gi);
327 }
328 for (int j = 0; j < cols; ++j) {
329 const int gj = st.global_index_for_local(j, desc[5], col_coord, npcol);
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)];
337 } else {
338 for (int i = first; i < rows; ++i)
339 column[i] = scaling.covariance(
340 column[i], global_rows[static_cast<std::size_t>(i)], gj);
341 }
342 }
343}
344
345inline bool equilibrateDistributedLower(std::vector<double>& buffer,
346 const int* desc, int n,
349{
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) {
356 const int gj = st.global_index_for_local(j, desc[5], col_coord, npcol);
357 if ((gj / desc[4]) % st.nprow() != row_coord) continue;
358 const int i =
359 st.local_index_for_global(gj, desc[4], row_coord, st.nprow());
360 diagonal(gj) = buffer[static_cast<std::size_t>(j) * desc[8] + i];
361 }
362 ordered_sum_bcast(diagonal.data(), n, st);
363 if (!scaling.compute(diagonal)) return false;
364 transformDistributedLower(buffer, desc, n, scaling, false, st);
365 return true;
366}
367
368inline bool cholesky(const EigenMatrix& C, EigenMatrix& L,
370{
371 if (C.rows() != C.cols()) return false;
372 st.initialize();
373
374 const int n = static_cast<int>(C.rows());
375
376 int desc_std[9];
377 std::vector<double> buf_std = st.scatter(C, n, n, desc_std);
379 if (!equilibrateDistributedLower(buf_std, desc_std, n, scaling, st))
380 return false;
381
383 if (!trainingCholeskyDistributed(buf_std.data(), desc_std, n, st))
384 return false;
385 } else {
386#ifdef GPR_LINALG_SLATE
387 // Reproducible arithmetic uses the same tile order on every grid.
388 if (st.reproducible()) {
389 slate_kernels::configure_nested_blas_threading(st);
390 if (!canonical::potrfLower(st, buf_std.data(), desc_std, n))
391 return false;
392 } else if (!slate_kernels::potrf_lower(buf_std.data(), desc_std, n, st))
393 return false;
394#else
395 if (st.reproducible() || st.tile_kernels(desc_std, "pdpotrf")) {
396 ScopedTileKernelThreads tile_threads(st);
397 if (!canonical::potrfLower(st, buf_std.data(), desc_std, n))
398 return false;
399 } else {
401 int info = 0, one = 1;
402 pdpotrf_("L", &n, buf_std.data(), &one, &one, desc_std, &info);
403 if (info != 0) return false;
404 }
405#endif
406 }
407
408 transformDistributedLower(buf_std, desc_std, n, scaling, true, st);
409 st.cache_L(std::move(buf_std), desc_std, n);
410 L.resize(0, 0);
411 return true;
412}
413
415 std::vector<double> C_dist, const int* desc, int n, EigenMatrix& L,
417{
418 st.initialize();
419
420 int local_desc[9];
421 std::copy_n(desc, 9, local_desc);
423 if (!equilibrateDistributedLower(C_dist, local_desc, n, scaling, st))
424 return false;
425
427 if (!trainingCholeskyDistributed(C_dist.data(), local_desc, n, st))
428 return false;
429 } else {
430#ifdef GPR_LINALG_SLATE
431 // Reproducible arithmetic uses the same tile order on every grid.
432 if (st.reproducible()) {
433 slate_kernels::configure_nested_blas_threading(st);
434 if (!canonical::potrfLower(st, C_dist.data(), local_desc, n))
435 return false;
436 } else if (!slate_kernels::potrf_lower(C_dist.data(), local_desc, n,
437 st))
438 return false;
439#else
440 if (st.reproducible() || st.tile_kernels(local_desc, "pdpotrf")) {
441 ScopedTileKernelThreads tile_threads(st);
442 if (!canonical::potrfLower(st, C_dist.data(), local_desc, n))
443 return false;
444 } else {
446 int info = 0;
447 int one = 1;
448 pdpotrf_("L", &n, C_dist.data(), &one, &one, local_desc, &info);
449 if (info != 0) return false;
450 }
451#endif
452 }
453
454 transformDistributedLower(C_dist, local_desc, n, scaling, true, st);
455 st.cache_L(std::move(C_dist), local_desc, n);
456 L.resize(0, 0);
457 return true;
458}
459
461 const EigenMatrix& L, const EigenMatrix& B,
463{
464 const int m = static_cast<int>(B.rows());
465 const int ncols = static_cast<int>(B.cols());
466
467 if (L.size() != 0 || !st.has_cached_L() || st.cached_n() != m) {
468 requireRebuildableDenseL(L, m, "forward_solve_mat", st);
469 int desc[9];
470 std::vector<double> Lbuf = st.scatter(L, m, m, desc);
471 st.cache_L(std::move(Lbuf), desc, m);
472 }
473
474 int desc_b[9];
475 std::vector<double> b_buf = st.scatter(B, m, ncols, desc_b);
476 cached_trsm_left_lower(m, ncols, b_buf.data(), desc_b,
477 /*transpose=*/false, "forward_solve_mat", st);
478 return st.gather(b_buf.data(), desc_b, m, ncols);
479}
480
481// Distributed thin SVD A = U S V^T via ScaLAPACK pdgesvd (#89, HS-SVD strong
482// scaling). A is the replicated design (m x n, m=nobs <= n=N modes); the SVD
483// distributes over the BLACS grid. Returns U (m x k), S (k), V (n x k),
484// k=min(m,n), gathered to replicated for the (small) downstream Psi/Sr/W. The
485// distributed pdgesvd is the kernel; the per-rank design build is the larger
486// strong-scaling lever (follow-on). Returns false on a ScaLAPACK error.
488 const EigenMatrix& A, EigenMatrix& U, Eigen::VectorXd& S, EigenMatrix& V,
490{
491 st.initialize();
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);
495
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);
500 // pdgesvd has no 64-bit counterpart here; refuse before any work.
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); // m x n
504 std::vector<double> Uloc = st.alloc_local(m, k, descU); // m x k
505 std::vector<double> VTloc = st.alloc_local(k, n, descVT); // k x n
506 std::vector<double> Svec(static_cast<size_t>(k), 0.0);
507
508 int one = 1, info = 0, lwork = -1;
509 double wq = 0.0;
510 pdgesvd_("V", "V", &m, &n, Aloc.data(), &one, &one, descA, Svec.data(),
511 Uloc.data(), &one, &one, descU, VTloc.data(), &one, &one, descVT,
512 &wq, &lwork, &info); // workspace query
513 if (info != 0) return false;
514 lwork = lp64Workspace(wq, "pdgesvd", st);
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;
520
521 U = st.gather(Uloc.data(), descU, m, k);
522 const EigenMatrix VT = st.gather(VTloc.data(), descVT, k, n);
523 V = VT.transpose(); // n x k
524 S = Eigen::Map<Eigen::VectorXd>(Svec.data(), k);
525 return true;
526}
527
528// Every multi-rank eigensolve must enter a collective driver. A size floor
529// used to turn the common dimer orders into a rank-0 serial fallback, hiding
530// both regressions and process-grid dependence.
531inline constexpr Eigen::Index kMinDistributedSymmetricEigenOrder = 1;
532
534 const EigenMatrix& A, Eigen::VectorXd& eigenvalues,
535 EigenMatrix& eigenvectors, const char** driver_name = nullptr,
537{
538 st.initialize();
539 if (A.rows() != A.cols()) return false;
540 const int n = static_cast<int>(A.rows());
541 if (n == 0) {
542 eigenvalues.resize(0);
543 eigenvectors.resize(0, 0);
544 return true;
545 }
546
547 int descA[9], descZ[9];
548 // The eigensolvers have no 64-bit counterpart here; refuse before work.
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);
555
556 auto pdsyev_symmetric_eigen = [&]() {
557 Aloc = Aloc_input;
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;
561 double wq = 0.0;
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;
565 lwork = lp64Workspace(wq, "pdsyev", st);
566 std::vector<double> work(static_cast<size_t>(lwork), 0.0);
567 Aloc = Aloc_input;
568 info = 0;
569 pdsyev_("V", "L", &n, Aloc.data(), &one, &one, descA, Wvec.data(),
570 Zloc.data(), &one, &one, descZ, work.data(), &lwork, &info);
571 return info == 0;
572 };
573
574 auto pdsyevd_symmetric_eigen = [&]() {
575 if (!pdsyevd_available_()) return false;
576 Aloc = Aloc_input;
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;
580 double wq = 0.0;
581 int iwq = 0;
582 pdsyevd_("V", "L", &n, Aloc.data(), &one, &one, descA, Wvec.data(),
583 Zloc.data(), &one, &one, descZ, &wq, &lwork, &iwq, &liwork,
584 &info);
585 if (info != 0) return false;
586 lwork = lp64Workspace(wq, "pdsyev", st);
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);
590 Aloc = Aloc_input;
591 info = 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);
595 return info == 0;
596 };
597
598 auto pdsyevr_symmetric_eigen = [&]() {
599 if (!pdsyevr_available_()) return false;
600 Aloc = Aloc_input;
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;
606 int iwq = 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;
611 lwork = lp64Workspace(wq, "pdsyev", st);
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);
615 Aloc = Aloc_input;
616 info = 0;
617 m = 0;
618 nz = 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;
623 };
624
625 const char* selected_driver = nullptr;
626#ifdef GPR_LINALG_SLATE
628 Aloc = Aloc_input;
629 if (slate_kernels::heev_lower(Aloc.data(), descA, n, Zloc.data(), descZ,
630 Wvec, st))
631 selected_driver = "slate_heev_canonical";
632 }
633#endif
634 // Netlib ScaLAPACK's PDSYEVD can report INFO=0 after PDORMTR rejected its
635 // internally chosen workspace (notably on narrow process grids), leaving
636 // finite but invalid eigenvectors. PDSYEV is a collective eigensolver too
637 // and does not take that broken PDORMTR path, so make it the portable
638 // system-ScaLAPACK driver rather than accepting a false success.
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";
645 }
646#ifdef GPR_LINALG_SLATE
647 if (selected_driver == nullptr) {
648 Aloc = Aloc_input;
649 if (!slate_kernels::heev_lower(Aloc.data(), descA, n, Zloc.data(),
650 descZ, Wvec, st)) {
651 return false;
652 }
653 selected_driver = "slate_heev";
654 }
655#endif
656 if (selected_driver == nullptr) return false;
657
658 if (st.nprocs() > 1)
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();
665 if (valid) {
666 for (int col = 0; col < n; ++col) {
667 Eigen::Index pivot = 0;
668 double best = -1.0;
669 for (Eigen::Index row = 0; row < n; ++row) {
670 const double mag = std::abs(eigenvectors(row, col));
671 if (mag > best) {
672 best = mag;
673 pivot = row;
674 }
675 }
676 if (eigenvectors(pivot, col) < 0.0)
677 eigenvectors.col(col) = -eigenvectors.col(col);
678 }
679 if (driver_name != nullptr) *driver_name = selected_driver;
680 }
681 return valid;
682}
683
684// Mode-distributed thin SVD (#89, the strong-scaling entry). Each rank passes
685// the CONTIGUOUS column block it owns: A_local is m x count for the modes in
686// DistributedState::col_block_range, so the (~60%) per-rank design build never
687// forms the full m x n design on any single rank. The block redistributes from
688// the 1 x np column grid into the block-cyclic compute grid via Cpdgemr2d, then
689// pdgesvd runs exactly as distributed_thin_svd. U (m x k), S (k), V (n x k),
690// k = min(m, n), gathered to replicated. Returns false on a ScaLAPACK error.
692 const EigenMatrix& A_local, int m, int n, EigenMatrix& U,
693 Eigen::VectorXd& S, EigenMatrix& V,
695{
696 st.initialize();
697 const int k = std::min(m, n);
698
699 int descSrc[9], descA[9], descU[9], descVT[9];
700 st.make_col_desc(m, n, descSrc); // 1 x np contiguous column blocks
701 st.make_desc(m, n, descA);
702 st.make_desc(m, k, descU);
703 st.make_desc(k, n, descVT);
704 // Cpdgemr2d and pdgesvd have no 64-bit counterpart here; refuse before
705 // any work.
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); // block-cyclic
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);
712
713 // Redistribute the per-rank column block into the compute grid. Ranks with
714 // an empty block (count == 0) still participate in the collective; their
715 // source pointer is unused by Cpdgemr2d so a dummy keeps it non-null.
716 double dummy = 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,
719 st.compute_ictxt());
720
721 int one = 1, info = 0, lwork = -1;
722 double wq = 0.0;
723 pdgesvd_("V", "V", &m, &n, Aloc.data(), &one, &one, descA, Svec.data(),
724 Uloc.data(), &one, &one, descU, VTloc.data(), &one, &one, descVT,
725 &wq, &lwork, &info); // workspace query
726 if (info != 0) return false;
727 lwork = lp64Workspace(wq, "pdgesvd", st);
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;
733
734 U = st.gather(Uloc.data(), descU, m, k);
735 const EigenMatrix VT = st.gather(VTloc.data(), descVT, k, n);
736 V = VT.transpose(); // n x k
737 S = Eigen::Map<Eigen::VectorXd>(Svec.data(), k);
738 return true;
739}
740
741// TSQR-based mode-distributed thin SVD (#90). The design A is distributed by
742// mode-columns, so A^T is tall-skinny (N >> nobs) with its rows (modes)
743// distributed across ranks -- exactly the communication-avoiding TSQR target
744// (Demmel-Grigori-Hoemmen-Langou, SIAM J. Sci. Comput. 2012). Pure MPI + Eigen:
745// no ScaLAPACK/BLACS, no pdgesvd, never the Gram A A^T (so cond(Psi) stays
746// O(1)). The steps:
747// 1. local QR of each rank's A_local^T block (count x nobs) -> R_local
748// (rloc x nobs, rloc=min(count,nobs)); each local QR is unconditioned.
749// 2. Allgatherv the tiny R factors, stack, re-factor -> the global R
750// (nobs x nobs). This is the one-level reduction; for the rank counts here
751// (<= a few tens) it costs one collective of ~np*nobs^2 doubles, far below
752// pdgesvd's distributed bidiagonalization, and it sidesteps the small-
753// matrix Comm_create overhead entirely.
754// 3. dense SVD of R (nobs x nobs): R = U_R S V_R^T. Since A^T = Q R with Q
755// the
756// composed (implicit) TSQR factor, A = V_R S (Q U_R)^T, so the left
757// singular vectors of A are U_A = V_R (replicated, free) and S = diag.
758// 4. compose the local and stacked QR factors with U_R to form V. Applying
759// orthogonal factors preserves small singular modes without division by S.
760// The contiguous mode-row blocks are gathered to V (N x k).
761// Returns U (nobs x k), S (k), V (N x k), k=min(nobs,N). TSQR is the exact QR
762// of A^T to machine precision, so S matches the dense Eigen SVD. A_local is
763// this rank's contiguous column block per DistributedState::col_block_range.
765 const EigenMatrix& A_local, int nobs, int N, EigenMatrix& U,
766 Eigen::VectorXd& S, EigenMatrix& V,
768{
769 st.initialize();
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);
775 if (k <= 0) {
776 U.resize(nobs, 0);
777 S.resize(0);
778 V.resize(N, 0);
779 return true;
780 }
781
782 std::vector<int> vrows(np, 0);
783 if (np > 1) {
784 MPI_Allgather(&count, 1, MPI_INT, vrows.data(), 1, MPI_INT, comm);
785 } else {
786 vrows[0] = count;
787 }
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;
792
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];
801 }
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;
805 if (exceedsLp64(stacked_elems))
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;
810 if (exceedsLp64(gathered_elems))
811 throw std::length_error("TSQR: right singular vectors of " +
812 std::to_string(gathered_elems) +
813 " entries exceed the MPI count range");
814
815 // Route columns from rank-contiguous input blocks into fixed 64-mode leaves
816 // so every leaf QR factor is independent of np.
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);
824 }
825
826 if (np == 1) {
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);
832 }
833 } else {
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];
842 }
843 }
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];
860 }
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]);
867 cursor[dst] += nobs;
868 }
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);
873
874 int rpos = 0;
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());
884 rpos += nobs;
885 }
886 }
887 }
888
889 // 1. Fixed-leaf QR of each owned leaf^T and canonical stacking into R_all.
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) =
898 qr_leaves[idx]
899 .matrixQR()
900 .topRows(rloc)
901 .template triangularView<Eigen::Upper>();
902 }
903 if (np > 1) {
904 replicate_owned_values(R_all.data(),
905 static_cast<std::size_t>(R_all.size()),
906 st.communication()->view());
907 }
908
909 // 2. Global R then its dense SVD with deterministic singular-vector signs.
910 Eigen::HouseholderQR<EigenMatrix> qr_all(R_all);
911 const int r_final_rows = std::min(total_rows, nobs);
912 const EigenMatrix R_final = qr_all.matrixQR()
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);
919 EigenMatrix U_R = svdR.matrixU().leftCols(k);
920 for (int col = 0; col < k; ++col) {
921 Eigen::Index pivot = 0;
922 double best = -1.0;
923 for (Eigen::Index row = 0; row < U.rows(); ++row) {
924 const double mag = std::abs(U(row, col));
925 if (mag > best) {
926 best = mag;
927 pivot = row;
928 }
929 }
930 if (U(pivot, col) < 0.0) {
931 U.col(col) = -U.col(col);
932 U_R.col(col) = -U_R.col(col);
933 }
934 }
935
936 // 3. V = Q_leaf Q_stacked U_R assembled into global mode rows.
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();
940
941 V.setZero(N, k);
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;
952 }
953 if (np > 1) {
954 replicate_owned_values(V.data(), static_cast<std::size_t>(V.size()),
955 st.communication()->view());
956 }
957 return true;
958}
959
961 const EigenMatrix& L, const EigenMatrix& B,
963{
964 const int m = static_cast<int>(B.rows());
965 const int ncols = static_cast<int>(B.cols());
966
967 if (L.size() != 0 || !st.has_cached_L() || st.cached_n() != m) {
968 requireRebuildableDenseL(L, m, "back_solve_mat", st);
969 int desc[9];
970 std::vector<double> Lbuf = st.scatter(L, m, m, desc);
971 st.cache_L(std::move(Lbuf), desc, m);
972 }
973
974 int desc_b[9];
975 std::vector<double> b_buf = st.scatter(B, m, ncols, desc_b);
976 cached_trsm_left_lower(m, ncols, b_buf.data(), desc_b,
977 /*transpose=*/true, "back_solve_mat", st);
978 return st.gather(b_buf.data(), desc_b, m, ncols);
979}
980
985inline Eigen::VectorXd columnSquaredNormsExact(const std::vector<double>& buf,
986 const int* desc, int m,
987 int ncols, DistributedState& st)
988{
989 const int nb = desc[4];
990 const int lld = desc[8];
991 const int local_cols = st.local_cols(ncols);
992 std::vector<ExactSum> total(static_cast<std::size_t>(ncols));
993 for (int local_j = 0; local_j < local_cols; ++local_j) {
994 const int global_j =
995 st.global_index_for_local(local_j, desc[5], st.mycol(), st.npcol());
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);
1002 CompensatedSum partial;
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);
1007 }
1008 }
1009 exact_sum_bcast(total.data(), ncols, st);
1010 Eigen::VectorXd result(ncols);
1011 for (int j = 0; j < ncols; ++j)
1012 result(j) = total[static_cast<std::size_t>(j)].value();
1013 return result;
1014}
1015
1016inline Eigen::VectorXd columnSchurComplementsExact(
1017 const std::vector<double>& buf, const int* desc, int m, int ncols,
1018 const Eigen::VectorXd& prior, DistributedState& st)
1019{
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];
1025 const int local_cols = st.local_cols(ncols);
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 =
1029 st.global_index_for_local(local_j, desc[5], st.mycol(), st.npcol());
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,
1039 value);
1040 }
1041 }
1042 }
1043 exact_sum_bcast(total.data(), ncols, st);
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();
1048 }
1049 return result;
1050}
1051
1053 const EigenMatrix& L, const EigenMatrix& B,
1055{
1056 const int m = static_cast<int>(B.rows());
1057 const int ncols = static_cast<int>(B.cols());
1058
1059 if (L.size() != 0 || !st.has_cached_L() || st.cached_n() != m) {
1060 requireRebuildableDenseL(L, m, "forward_solve_mat_colwise_squared_norm",
1061 st);
1062 int desc[9];
1063 std::vector<double> Lbuf = st.scatter(L, m, m, desc);
1064 st.cache_L(std::move(Lbuf), desc, m);
1065 }
1066
1067 int desc_b[9];
1068 std::vector<double> b_buf = st.scatter(B, m, ncols, desc_b);
1069 cached_trsm_left_lower(m, ncols, b_buf.data(), desc_b,
1070 /*transpose=*/false,
1071 "forward_solve_mat_colwise_squared_norm", st);
1072
1073 return columnSquaredNormsExact(b_buf, desc_b, m, ncols, st);
1074}
1075
1086{
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) {
1100 const int gi =
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);
1106 }
1107 }
1108 exact_sum_bcast(square.data(), 1, st);
1109 const double frobenius = std::sqrt(square[0].value());
1110
1111 const EigenMatrix identity = EigenMatrix::Identity(m, m);
1112 int descriptor[9];
1113 std::vector<double> buffer = st.scatter(identity, m, m, descriptor);
1114 cached_trsm_left_lower(m, m, buffer.data(), descriptor, false,
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);
1123 // Each lower-triangular entry is owned by one rank. Summing the
1124 // rounded partials with MPI_Allreduce follows the reduction tree, so
1125 // np=1 and np>1 can disagree. ExactSum records every product, and
1126 // exact_sum_bcast sums those integers with MPI_Allreduce. The sum is
1127 // exact only because integer addition is associative, so value()
1128 // rounds once to the same bits on every rank and every rank count.
1129 std::vector<ExactSum> column_sum(static_cast<std::size_t>(m));
1130 for (int j = 0; j < cols; ++j) {
1131 const int gj =
1132 st.global_index_for_local(j, desc[5], col_coord, npcol);
1133 for (int i = 0; i < rows; ++i) {
1134 const int gi =
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));
1140 }
1141 }
1142 exact_sum_bcast(column_sum.data(), m, st);
1143 for (int column = 0; column < m; ++column)
1144 column_abs(column) =
1145 column_sum[static_cast<std::size_t>(column)].value();
1146 // One row-chunk of ExactSums is enough to hold the products. Every
1147 // rank takes the same chunks, so the reductions stay aligned.
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) {
1154 const int gj =
1155 st.global_index_for_local(j, desc[5], col_coord, npcol);
1156 for (int i = 0; i < rows; ++i) {
1157 const int gi =
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;
1164 ExactSum* const row =
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));
1169 }
1170 }
1171 exact_sum_bcast(partial.data(), count, st);
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)]
1178 .value();
1179 }
1180 }
1181 }
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()
1187 : infinity;
1188 const double factor_norm = column_abs.maxCoeff();
1189 inverse_norm = upperInverseNorm1FromResidual(computed, residual_norm,
1190 factor_norm, m);
1191 }
1192 return choleskySchurRelativeError(m, frobenius, inverse_norm);
1193}
1194
1199inline void requireCachedFactorSchurDiagonal(Eigen::VectorXd& diagonal,
1200 const Eigen::VectorXd& prior,
1201 int m, DistributedState& st)
1202{
1204 diagonal, prior, [&] { return cachedFactorSchurRelativeError(m, st); });
1205}
1206
1207inline Eigen::VectorXd bordered_cholesky_diagonal(
1208 const EigenMatrix& L, const EigenMatrix& B, const Eigen::VectorXd& prior,
1210{
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;
1218 requireStablePosteriorVariance(diagonal, prior);
1219 return diagonal;
1220 }
1221
1222 if (L.size() != 0 || !st.has_cached_L() || st.cached_n() != m) {
1223 requireRebuildableDenseL(L, m, "bordered_cholesky_diagonal", st);
1224 int descriptor[9];
1225 std::vector<double> factor = st.scatter(L, m, m, descriptor);
1226 st.cache_L(std::move(factor), descriptor, m);
1227 }
1228
1229 int descriptor[9];
1230 std::vector<double> cross = st.scatter(B, m, ncols, descriptor);
1231 cached_trsm_left_lower(m, ncols, cross.data(), descriptor,
1232 /*transpose=*/false, "bordered_cholesky_diagonal",
1233 st);
1234 Eigen::VectorXd diagonal =
1235 columnSchurComplementsExact(cross, descriptor, m, ncols, prior, st);
1236 requireCachedFactorSchurDiagonal(diagonal, prior, m, st);
1237 return diagonal;
1238}
1239
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)
1261{
1262 if (m == 0 || ncols == 0) {
1263 // Nothing is observed (or nothing is queried), so the Gram matrix is
1264 // zero and the posterior diagonal is the prior itself. The caller
1265 // reads *posterior_diagonal whenever it passed one in.
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;
1272 requireStablePosteriorVariance(*posterior_diagonal, *prior);
1273 }
1274 return EigenMatrix::Zero(ncols, ncols);
1275 }
1276 if (L.size() != 0 || !st.has_cached_L() || st.cached_n() != m) {
1277 requireRebuildableDenseL(L, m, "forward_solve_mat_bilinear_distributed",
1278 st);
1279 int desc[9];
1280 std::vector<double> Lbuf = st.scatter(L, m, m, desc);
1281 st.cache_L(std::move(Lbuf), desc, m);
1282 }
1283
1284 int local_desc_b[9];
1285 std::copy_n(desc_b, 9, local_desc_b);
1286 cached_trsm_left_lower(m, ncols, b_buf.data(), local_desc_b,
1287 /*transpose=*/false,
1288 "forward_solve_mat_bilinear_distributed", st);
1289 if (prior != nullptr && posterior_diagonal != nullptr) {
1290 *posterior_diagonal = columnSchurComplementsExact(b_buf, local_desc_b,
1291 m, ncols, *prior, st);
1293 requireCachedFactorSchurDiagonal(*posterior_diagonal, *prior, m,
1294 st);
1295 }
1296
1297#ifdef GPR_LINALG_SLATE
1298 if (st.reproducible()) {
1299 slate_kernels::configure_nested_blas_threading(st);
1300 const EigenMatrix solved =
1301 st.gather(b_buf.data(), local_desc_b, m, ncols);
1302 return canonical::gramTiles(solved, local_desc_b[4]);
1303 }
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");
1311 const EigenMatrix gathered =
1312 st.gather(product.data(), desc_product, ncols, ncols);
1313 return gathered.selfadjointView<Eigen::Lower>();
1314#else
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)) {
1319 // The solved block is replicated and multiplied in a fixed tile
1320 // order, so the covariance carries the same bits on every grid.
1321 const EigenMatrix solved =
1322 st.gather(b_buf.data(), local_desc_b, m, ncols);
1323 return canonical::gramTiles(solved, local_desc_b[4]);
1324 }
1325 std::vector<double> product(
1326 static_cast<std::size_t>(desc_product[8]) * st.local_cols(ncols), 0.0);
1327 const int one = 1;
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);
1331 const EigenMatrix gathered =
1332 st.gather(product.data(), desc_product, ncols, ncols);
1333 return gathered.selfadjointView<Eigen::Lower>();
1334#endif
1335}
1336
1338 const EigenMatrix& L, std::vector<double> b_buf, const int* desc_b, int m,
1340{
1341 if (L.size() != 0 || !st.has_cached_L() || st.cached_n() != m) {
1343 L, m, "forward_solve_mat_colwise_squared_norm_distributed", st);
1344 int desc[9];
1345 std::vector<double> Lbuf = st.scatter(L, m, m, desc);
1346 st.cache_L(std::move(Lbuf), desc, m);
1347 }
1348
1349 int local_desc_b[9];
1350 std::copy_n(desc_b, 9, local_desc_b);
1351 cached_trsm_left_lower(m, ncols, b_buf.data(), local_desc_b,
1352 /*transpose=*/false,
1353 "forward_solve_mat_colwise_squared_norm_distributed",
1354 st);
1355
1356 return columnSquaredNormsExact(b_buf, local_desc_b, m, ncols, st);
1357}
1358
1360 const EigenMatrix& L, std::vector<double> b_buf, const int* desc_b, int m,
1361 int ncols, const Eigen::VectorXd& prior,
1363{
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;
1369 requireStablePosteriorVariance(diagonal, prior);
1370 return diagonal;
1371 }
1372 if (L.size() != 0 || !st.has_cached_L() || st.cached_n() != m) {
1373 requireRebuildableDenseL(L, m, "bordered_cholesky_diagonal_distributed",
1374 st);
1375 int descriptor[9];
1376 std::vector<double> factor = st.scatter(L, m, m, descriptor);
1377 st.cache_L(std::move(factor), descriptor, m);
1378 }
1379
1380 int descriptor[9];
1381 std::copy_n(desc_b, 9, descriptor);
1382 cached_trsm_left_lower(m, ncols, b_buf.data(), descriptor,
1383 /*transpose=*/false,
1384 "bordered_cholesky_diagonal_distributed", st);
1385 Eigen::VectorXd diagonal =
1386 columnSchurComplementsExact(b_buf, descriptor, m, ncols, prior, st);
1387 requireCachedFactorSchurDiagonal(diagonal, prior, m, st);
1388 return diagonal;
1389}
1390
1395 const EigenMatrix& L, int order,
1397{
1398 if (order <= 0) return Eigen::VectorXd();
1399 if (L.size() != 0 || !st.has_cached_L() || st.cached_n() != order) {
1400 requireRebuildableDenseL(L, order,
1401 "cholesky_inverse_diagonal_distributed", st);
1402 int desc[9];
1403 std::vector<double> local_factor = st.scatter(L, order, order, desc);
1404 st.cache_L(std::move(local_factor), desc, order);
1405 }
1406 if (st.reproducible() || st.tile_kernels(st.cached_L_desc(), "pdtrtri")) {
1407 // Column j of L^{-1} has squared norm (K^{-1})_{jj}. The tile-ordered
1408 // solve and the exact column sums give the same bits on every grid.
1409 ScopedTileKernelThreads tile_threads(st);
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);
1414 {
1415 const canonical::TileGeometry g =
1416 canonical::geometryOf(st, descriptor);
1417 for (int k = 0; k < g.tiles(order); ++k) {
1418 if (g.ownerRow(k) != g.myrow || g.ownerCol(k) != g.mycol)
1419 continue;
1420 const int bk = g.span(k, order);
1421 canonical::tileAt(work.data(), descriptor[8], g, k, k, bk, bk)
1422 .setIdentity();
1423 }
1424 }
1426 descriptor, work.data(), descriptor, order, order,
1427 true);
1428 return columnSquaredNormsExact(work, descriptor, order, order, st);
1429 }
1430#ifndef GPR_LINALG_SLATE
1431 ScopedSolveThreads solve_threads;
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());
1438 const int one = 1;
1439 int info = 0;
1440 ScalapackLib::instance().pdtrtri("L", "N", &order, work.data(), &one, &one,
1441 descriptor, &info);
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(
1455 value, value);
1456 }
1457 }
1458 if (st.nprocs() > 1)
1459 exact_sum_bcast(exact_diagonal.data(), order,
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();
1464 return diagonal;
1465#else
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())
1476 continue;
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;
1481 }
1482 }
1484 L, std::move(identity), desc_identity, order, order, st);
1485#endif
1486}
1487
1488inline Eigen::VectorXd forward_solve(
1489 const EigenMatrix& L, const Eigen::VectorXd& b,
1491{
1492 const int m = static_cast<int>(b.size());
1493
1494 if (L.size() != 0 || !st.has_cached_L() || st.cached_n() != m) {
1495 requireRebuildableDenseL(L, m, "forward_solve", st);
1496 int desc[9];
1497 std::vector<double> Lbuf = st.scatter(L, m, m, desc);
1498 st.cache_L(std::move(Lbuf), desc, m);
1499 }
1500
1501 int desc_b[9], ncols = 1;
1502 std::vector<double> b_buf = st.scatter_colvector_root(b, m, desc_b);
1503 cached_trsm_left_lower(m, ncols, b_buf.data(), desc_b,
1504 /*transpose=*/false, "forward_solve", st);
1505 EigenMatrix X = st.gather(b_buf.data(), desc_b, m, ncols);
1506 return X.col(0);
1507}
1508
1509inline Eigen::VectorXd back_solve(
1510 const EigenMatrix& L, const Eigen::VectorXd& b,
1512{
1513 const int m = static_cast<int>(b.size());
1514
1515 if (L.size() != 0 || !st.has_cached_L() || st.cached_n() != m) {
1516 requireRebuildableDenseL(L, m, "back_solve", st);
1517 int desc[9];
1518 std::vector<double> Lbuf = st.scatter(L, m, m, desc);
1519 st.cache_L(std::move(Lbuf), desc, m);
1520 }
1521
1522 int desc_b[9], ncols = 1;
1523 std::vector<double> x_buf = st.scatter_colvector_root(b, m, desc_b);
1524 cached_trsm_left_lower(m, ncols, x_buf.data(), desc_b,
1525 /*transpose=*/true, "back_solve", st);
1526 EigenMatrix X = st.gather(x_buf.data(), desc_b, m, ncols);
1527 return X.col(0);
1528}
1529
1531 const EigenMatrix& L, const EigenMatrix& B,
1533{
1534 const int m = static_cast<int>(B.rows());
1535 const int ncols = static_cast<int>(B.cols());
1536
1537 if (L.size() != 0 || !st.has_cached_L() || st.cached_n() != m) {
1538 requireRebuildableDenseL(L, m, "trace_cholesky_solve_scalapack", st);
1539 int desc[9];
1540 std::vector<double> Lbuf = st.scatter(L, m, m, desc);
1541 st.cache_L(std::move(Lbuf), desc, m);
1542 }
1543
1544 int desc_b[9];
1545 std::vector<double> work = st.scatter(B, m, ncols, desc_b);
1546 cached_trsm_left_lower(m, ncols, work.data(), desc_b,
1547 /*transpose=*/false,
1548 "trace_cholesky_solve_scalapack", st);
1549 cached_trsm_left_lower(m, ncols, work.data(), desc_b,
1550 /*transpose=*/true, "trace_cholesky_solve_scalapack",
1551 st);
1552
1553 const int diag_n = std::min(m, ncols);
1554 const int local_rows = st.local_rows(m);
1555 // The diagonal entries are deterministic doubles; an exact accumulator
1556 // makes the trace independent of how the diagonal is distributed.
1557 ExactSum local_trace;
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;
1562
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]);
1569 }
1570
1571 exact_sum_bcast(&local_trace, 1, st);
1572 return local_trace.value();
1573}
1574
1575// Compute the rank-local contribution to trace(C^{-1} B) using the cached
1576// distributed Cholesky factor; no MPI reduction is performed. Callers that
1577// evaluate several B matrices in a row should accumulate the per-call local
1578// values into a vector and reduce them with a single ordered_sum_bcast, which
1579// trades 2 * n_calls MPI collectives for 2 without altering the per-call
1580// PDTRSM math (so the reduction-order sensitivity that sank e47e89b2 cannot
1581// reappear here).
1583 const EigenMatrix& L, const double* B_dist, const int* desc_b, int m,
1585{
1586 if (L.size() != 0 || !st.has_cached_L() || st.cached_n() != m) {
1588 L, m, "trace_cholesky_solve_scalapack_distributed_local", st);
1589 int desc[9];
1590 std::vector<double> Lbuf = st.scatter(L, m, m, desc);
1591 st.cache_L(std::move(Lbuf), desc, m);
1592 }
1593
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);
1598
1599 cached_trsm_left_lower(m, ncols, work.data(), desc_b,
1600 /*transpose=*/false,
1601 "trace_cholesky_solve_scalapack_distributed_local",
1602 st);
1603 cached_trsm_left_lower(m, ncols, work.data(), desc_b,
1604 /*transpose=*/true,
1605 "trace_cholesky_solve_scalapack_distributed_local",
1606 st);
1607
1608 const int diag_n = std::min(m, ncols);
1609 ExactSum local_trace;
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;
1614
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]);
1621 }
1622
1623 return local_trace;
1624}
1625
1627 const EigenMatrix& L, const double* B_dist, const int* desc_b, int m,
1629{
1631 L, B_dist, desc_b, m, ncols, st);
1632 exact_sum_bcast(&trace, 1, st);
1633 return trace.value();
1634}
1635
1644inline bool factor_inverse_lower(const EigenMatrix& L, int n,
1645 std::vector<double>& inverse, int* desc,
1646 DistributedState& st)
1647{
1648 if (L.size() != 0 || !st.has_cached_L() || st.cached_n() != n) {
1649 requireRebuildableDenseL(L, n, "factor_inverse_lower", st);
1650 int factor_desc[9];
1651 std::vector<double> Lbuf = st.scatter(L, n, n, factor_desc);
1652 st.cache_L(std::move(Lbuf), factor_desc, n);
1653 }
1654 std::copy_n(st.cached_L_desc(), 9, desc);
1655 const auto copyFactor = [&] {
1656 inverse.assign(st.cached_L(),
1657 st.cached_L() + static_cast<size_t>(st.local_rows(n)) *
1658 st.local_cols(n));
1659 };
1660#ifdef GPR_LINALG_SLATE
1661 if (st.reproducible()) {
1662 slate_kernels::configure_nested_blas_threading(st);
1663 if (!st.has_cached_U())
1664 st.cache_U(canonical::transposeFactor(st, st.cached_L(), desc, n));
1665 canonical::choleskyInverseLower(st, st.cached_L(), desc, n, inverse,
1666 st.cached_U());
1667 return true;
1668 }
1669 copyFactor();
1670 return slate_kernels::potri_lower(inverse.data(), desc, n, st);
1671#else
1672 if (st.reproducible() || st.tile_kernels(desc, "pdpotri")) {
1673 // The transposed factor serves the back substitutions too; keep it
1674 // with the factor rather than build a second one here.
1675 ScopedTileKernelThreads tile_threads(st);
1676 if (!st.has_cached_U())
1677 st.cache_U(canonical::transposeFactor(st, st.cached_L(), desc, n));
1678 canonical::choleskyInverseLower(st, st.cached_L(), desc, n, inverse,
1679 st.cached_U());
1680 return true;
1681 }
1682 copyFactor();
1683 ScopedSolveThreads solve_threads;
1684 int info = 0, one = 1;
1685 pdpotri_("L", &n, inverse.data(), &one, &one, desc, &info);
1686 return info == 0;
1687#endif
1688}
1689
1697template <class Entry>
1698inline ExactSum trace_lower_symmetric_local(const double* A, int lda, int n,
1699 Entry&& b, DistributedState& st)
1700{
1701 const int lr = st.local_rows(n), lc = st.local_cols(n);
1702 const int nb = st.block_size();
1703 // One accumulator per block of local columns on the tile threads; exact
1704 // accumulators merge exactly, in any order.
1705 const long blocks = (lc + nb - 1) / nb;
1706 std::vector<ExactSum> partial(static_cast<size_t>(std::max(1L, blocks)));
1707 parallelFor(blocks, [&](long block) {
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) {
1713 const int i =
1714 (il / nb * st.nprow() + st.myrow()) * nb + il % nb;
1715 if (i < j) continue;
1716 sum.addTripleProduct(
1717 i == j ? 1.0 : 2.0,
1718 A[static_cast<size_t>(il) + static_cast<size_t>(jl) * lda],
1719 b(i, j, il, jl));
1720 }
1721 }
1722 });
1723 ExactSum local;
1724 for (const ExactSum& sum: partial)
1725 local.merge(sum);
1726 return local;
1727}
1728
1735 const EigenMatrix& L, const EigenMatrix* B, int n,
1737{
1738 if (B != nullptr && (B->rows() != n || B->cols() != n)) {
1739 if (st.is_root())
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);
1745 std::abort();
1746 }
1747 std::vector<double> inverse;
1748 int desc[9];
1749 const bool ok = factor_inverse_lower(L, n, inverse, desc, st);
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);
1757 },
1758 st);
1759 exact_sum_bcast(&local, 1, st);
1760 return local.value();
1761}
1762
1765{
1766 const int n = (L.rows() > 0) ? static_cast<int>(L.rows()) : st.cached_n();
1767
1768 if (L.size() == 0 && st.has_cached_inv() && st.cached_inv_n() == n) {
1769 EigenMatrix invC =
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);
1775 }
1776 return invC;
1777 }
1778
1779 std::vector<double> work;
1780 int desc[9];
1781 if (!factor_inverse_lower(L, n, work, desc, st)) return EigenMatrix{};
1782 st.cache_inv(std::move(work), desc, n);
1783
1784 EigenMatrix invC =
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);
1790 }
1791 return invC;
1792}
1793
1796{
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)
1800 return;
1801
1802 // The factor inverse shares the transpose used by the posterior solve.
1803 // Its reproducible path reads the factor without copying the full matrix.
1804 std::vector<double> work;
1805 int desc[9];
1806 if (!factor_inverse_lower(L, n, work, desc, st)) return;
1807 st.cache_inv(std::move(work), desc, n);
1808}
1809
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)
1814{
1815 const Eigen::Index obs_rows = transpose_block ? block.cols() : block.rows();
1816 const Eigen::Index obs_cols = transpose_block ? block.rows() : block.cols();
1817
1818 double trace = 0.0;
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;
1827
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;
1835 }
1836 }
1837 return trace;
1838}
1839
1841 const EigenMatrix& block, int row_component, int col_component,
1842 int tile_size, bool transpose_block = false,
1844{
1845 if (!st.has_cached_inv()) {
1846 if (st.is_root()) {
1847 std::fprintf(stderr,
1848 "[gpr::linalg::cached_inverse_observation_tile_"
1849 "trace_np1] cached inverse missing\n");
1850 }
1851 std::abort();
1852 }
1853 if (st.nprocs() != 1) {
1854 if (st.is_root()) {
1855 std::fprintf(stderr,
1856 "[gpr::linalg::cached_inverse_observation_tile_"
1857 "trace_np1] requires nprocs=1, got %d\n",
1858 st.nprocs());
1859 }
1860 std::abort();
1861 }
1862 if (tile_size <= 0 || row_component < 0 || col_component < 0 ||
1863 row_component >= tile_size || col_component >= tile_size) {
1864 if (st.is_root()) {
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);
1870 }
1871 std::abort();
1872 }
1873
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();
1878 const int max_row =
1879 obs_rows > 0
1880 ? (static_cast<int>(obs_rows) - 1) * tile_size + row_component
1881 : row_component;
1882 const int max_col =
1883 obs_cols > 0
1884 ? (static_cast<int>(obs_cols) - 1) * tile_size + col_component
1885 : col_component;
1886 if (max_row >= n || max_col >= n) {
1887 if (st.is_root()) {
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);
1893 }
1894 std::abort();
1895 }
1897 st.cached_inv(), inv_local_rows, n, block, row_component, col_component,
1898 tile_size, transpose_block);
1899}
1900
1902 const double* B_dist, const int* desc_b, int n,
1904{
1905 if (!st.has_cached_inv() || st.cached_inv_n() != n) {
1906 if (st.is_root()) {
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);
1912 }
1913 std::abort();
1914 }
1915 if (desc_b == nullptr) {
1916 if (st.is_root()) {
1917 std::fprintf(stderr,
1918 "[gpr::linalg::trace_cached_inverse_times_"
1919 "symmetric_distributed] null distributed matrix\n");
1920 }
1921 std::abort();
1922 }
1923
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) {
1928 if (st.is_root()) {
1929 std::fprintf(stderr,
1930 "[gpr::linalg::trace_cached_inverse_times_"
1931 "symmetric_distributed] null non-empty local block\n");
1932 }
1933 std::abort();
1934 }
1935 const int b_local_rows = std::max(1, desc_b[8]);
1936 const double* inv_dist = st.cached_inv();
1937
1938 // Every owned product enters an exact accumulator, so the trace does
1939 // not depend on which rank owns an entry.
1940 ExactSum local_trace;
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;
1944
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);
1955
1956 const double weight = (global_row == global_col) ? 1.0 : 2.0;
1957 local_trace.addTripleProduct(weight, inv_dist[inv_idx],
1958 B_dist[b_idx]);
1959 }
1960 }
1961
1962 exact_sum_bcast(&local_trace, 1, st);
1963 return local_trace.value();
1964}
1965
1968{
1969 const int n = (L.rows() > 0) ? static_cast<int>(L.rows()) : st.cached_n();
1970
1971 std::vector<double> work;
1972 int desc[9];
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);
1978 } else {
1979 work = st.scatter(L, n, n, desc);
1980 }
1981
1982 if (st.reproducible() || st.tile_kernels(desc, "pdpotri")) {
1983 ScopedTileKernelThreads tile_threads(st);
1984 std::vector<double> inverse;
1985 canonical::choleskyInverseLower(st, work.data(), desc, n, inverse);
1986 work = std::move(inverse);
1987 } else {
1988 int info = 0, one = 1;
1989 pdpotri_("L", &n, work.data(), &one, &one, desc, &info);
1990 if (info != 0) {
1991 // pdpotri failed; mirror the empty-return shape used by the
1992 // other cholesky_inverse variants above so the caller's
1993 // invC.size() == 0 sentinel triggers the same fall-back.
1994 return EigenMatrix{};
1995 }
1996 }
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);
2002 }
2003 return invC;
2004}
2005
2006inline double trace_product(const EigenMatrix& A, const EigenMatrix& B,
2008{
2009 st.initialize();
2010
2011 const auto sz = A.size();
2012 double sum = 0.0;
2013 const double* a = A.data();
2014 const double* b = B.data();
2015 for (Eigen::Index i = 0; i < sz; ++i)
2016 sum += a[i] * b[i];
2017
2018 if (st.nprocs() == 1) return sum;
2019
2020 double result = 0.0;
2021 if (st.is_root()) result = sum;
2022 MPI_Bcast(&result, 1, MPI_DOUBLE, 0, st.world_comm());
2023 return result;
2024}
2025
2026inline double log_det_cholesky(
2028{
2029 st.initialize();
2030
2031 // Prefer the L the caller actually passed in: cholesky() now populates
2032 // the dense L on every rank, so the right-by-construction sum-of-logs
2033 // is the local diagonal traversal -- it also tolerates callers that
2034 // build L outside of cholesky() (the EigenBackend parity tests assemble
2035 // a hand-crafted diagonal L). Only fall back to the cached distributed
2036 // L if no dense L was provided (e.g. legacy SVGD oracle paths that
2037 // touch the cache directly).
2038 if (L.rows() > 0 && L.cols() > 0) {
2039 const int n = static_cast<int>(L.rows());
2040 ExactSum sum;
2041 for (int i = 0; i < n; ++i)
2042 sum.add(numerics::log(L(i, i)));
2043 return sum.value();
2044 }
2045 if (!st.has_cached_L()) return 0.0;
2046
2047 const int n = st.cached_n();
2048 const int local_rows = st.local_rows(n);
2049 // The logarithms are deterministic doubles; accumulating them exactly
2050 // makes the reduced sum independent of how the diagonal is distributed.
2051 ExactSum local_sum;
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;
2056
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());
2061 local_sum.add(numerics::log(
2062 st.cached_L()[static_cast<size_t>(local_i) +
2063 static_cast<size_t>(local_j) * local_rows]));
2064 }
2065
2066 exact_sum_bcast(&local_sum, 1, st);
2067 return local_sum.value();
2068}
2069
2070} // namespace linalg
2071} // namespace gpr
2072
2073#endif // GPR_LINALG_SCALAPACKBACKEND_H_
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 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
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 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
Definition ExactSum.h:54
double value() const noexcept
The exact sum rounded once to the nearest double, ties to even.
Definition ExactSum.h:190
void addTripleProduct(double a, double b, double c) noexcept
Definition ExactSum.h:86
void merge(const ExactSum &other) noexcept
Adds another accumulator exactly.
Definition ExactSum.h:146
int concurrency() const noexcept
static ScalapackLib & instance()
ScopedSolveThreads & operator=(const ScopedSolveThreads &)=delete
static int solveThreadTarget() noexcept
ScopedSolveThreads(const ScopedSolveThreads &)=delete
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.
Definition ExactSchur.h:131
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...
Definition ExactSchur.h:259
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.
Definition ExactSchur.h:174
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.
Definition ExactSchur.h:40
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
Definition Lp64Limits.h:151
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.
Definition ExactSchur.h:310
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.
Definition Lp64Limits.h:35
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.
Definition Macros.h:16
Eigen::Matrix< double, EigenDynamic, EigenDynamic, EigenMatrixStorage > EigenMatrix
Definition Macros.h:20
void addProduct(double left, double right)
int span(int tile, int extent) const