Loading...
Searching...
No Matches
ScalapackPDPotrfInverse.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// Copyright (c) gpridge developers
3// See LICENSE for details.
4
6
8#include "ExactSum.h"
9
10#ifdef GPR_LINALG_SCALAPACK
11
12#include <algorithm>
13#include <atomic>
14#include <cmath>
15#include <cstdint>
16#include <cstdlib>
17#include <limits>
18#include <stdexcept>
19#ifdef __unix__
20#include <fcntl.h>
21#include <sys/mman.h>
22#include <unistd.h>
23#endif
24
25#include "Backend.h"
26#include "DistributedState.h"
27#include "TeamFactor.h"
28#include "TrainingCholesky.h"
29#ifdef GPR_LINALG_SLATE
30#include "SlateKernels.h"
31#endif
32
33// All four virtuals operate directly on the distributed L factor owned by
34// this object. Each pdtrsm is one triangular solve; KernelInverse::solve is
35// K x = b under K = L L^T, so it costs the pair (L y = b then L^T x = y),
36// not a single triangular solve:
37//
38// solve(b) -> two pdtrsm's over an n x 1 RHS
39// (two pdtrsm's: L y = b, L^T x = y => x = K^{-1} b)
40// solve_mat(B) -> two pdtrsm's over an n x nrhs RHS
41// (two pdtrsm's, matrix RHS)
42// log_det() -> diagonal traversal of owned distributed L
43// (diag traversal of L with ordered_sum_bcast,
44// times 2 to convert sum log L_ii into log|K|)
45// trace_inv_times(A) -> two pdtrsm's over A's distributed buffer
46// pdtrsm's + diag-of-Z reduction; Z = K^{-1} A)
47//
48// None of the four go through Eigen LLT or DistributedState's singleton factor
49// storage. DistributedState supplies the BLACS grid, descriptors, and scatter /
50// gather helpers; numerical kernels consume L_dist_/L_desc_ directly.
51
52namespace gpr {
53namespace linalg {
54
55namespace {
56struct SharedFactorStorage {
57 std::shared_ptr<double> data;
58 bool writer = true;
59};
60
61SharedFactorStorage allocateSharedFactor(Eigen::Index entries,
62 const DistributedState& state)
63{
64 SharedFactorStorage result;
65#ifdef __unix__
66 if (state.nprocs() <= 1 || entries == 0) return result;
67 constexpr auto byte_limit = std::min(
68 static_cast<std::uintmax_t>(std::numeric_limits<off_t>::max()),
69 static_cast<std::uintmax_t>(std::numeric_limits<std::size_t>::max()));
70 if (entries < 0 ||
71 static_cast<std::uintmax_t>(entries) > byte_limit / sizeof(double))
72 throw std::length_error("shared Cholesky storage is too large");
73 MPI_Comm local = MPI_COMM_NULL;
74 MPI_Comm_split_type(state.world_comm(), MPI_COMM_TYPE_SHARED,
75 state.myrank(), MPI_INFO_NULL, &local);
76 int rank = 0, ranks = 1;
77 MPI_Comm_rank(local, &rank);
78 MPI_Comm_size(local, &ranks);
79 const auto bytes = static_cast<std::size_t>(entries) * sizeof(double);
80 void* mapping = MAP_FAILED;
81 int valid = 1;
82 if (ranks > 1) {
83 char path[] = "/tmp/gpr-factor-XXXXXX";
84 int fd = -1;
85 bool created = false;
86 if (rank == 0) {
87 fd = mkstemp(path);
88 created = fd >= 0;
89 valid = created && ftruncate(fd, static_cast<off_t>(bytes)) == 0;
90 }
91 MPI_Bcast(&valid, 1, MPI_INT, 0, local);
92 MPI_Bcast(path, sizeof(path), MPI_CHAR, 0, local);
93 if (valid) {
94 if (rank != 0) fd = open(path, O_RDONLY);
95 if (fd >= 0)
96 mapping = mmap(nullptr, bytes,
97 rank == 0 ? PROT_READ | PROT_WRITE : PROT_READ,
98 MAP_SHARED, fd, 0);
99 valid = mapping != MAP_FAILED;
100 }
101 if (fd >= 0) close(fd);
102 // Every reader holds a mapping before the name is removed. Mapping
103 // lifetime is local; retiring a posterior requires no MPI collective.
104 MPI_Barrier(local);
105 if (created) unlink(path);
106 result.writer = rank == 0;
107 }
108 MPI_Allreduce(MPI_IN_PLACE, &valid, 1, MPI_INT, MPI_MIN,
109 state.world_comm());
110 MPI_Comm_free(&local);
111 if (!valid) {
112 if (mapping != MAP_FAILED) munmap(mapping, bytes);
113 throw std::runtime_error("cannot allocate shared Cholesky storage");
114 }
115 if (mapping != MAP_FAILED)
116 result.data = std::shared_ptr<double>(
117 static_cast<double*>(mapping),
118 [bytes](double* data) { munmap(data, bytes); });
119#else
120 (void)entries;
121 (void)state;
122#endif
123 return result;
124}
125} // namespace
126
127ScalapackPDPotrfInverse::ScalapackPDPotrfInverse(
128 std::shared_ptr<DistributedState> state)
129 : state_(std::move(state))
130{
131 if (!state_)
132 throw std::invalid_argument(
133 "distributed inverse requires a process grid");
134}
135
136DistributedState& ScalapackPDPotrfInverse::state() const
137{
138 return state_ ? *state_ : DistributedState::instance();
139}
140
141void ScalapackPDPotrfInverse::require_factor() const
142{
143 if (!factored_ || grid_generation_ != state().grid_generation() ||
144 factorization_generation_ !=
145 DistributedState::factorization_generation())
146 throw std::logic_error(
147 "distributed inverse requires a factor on its active grid and "
148 "factorization");
149}
150
151bool ScalapackPDPotrfInverse::factorise(const EigenMatrix& covariance)
152{
153 if (covariance.rows() <= 0 || covariance.rows() != covariance.cols() ||
154 covariance.rows() > std::numeric_limits<int>::max() ||
155 !covariance.allFinite())
156 return factorise({}, nullptr, 0);
157 auto& st = state();
158 st.initialize();
159 const int order = static_cast<int>(covariance.rows());
160 int descriptor[9];
161 auto values = st.scatter(covariance, order, order, descriptor);
162 return factorise(std::move(values), descriptor, order);
163}
164
165EigenMatrix ScalapackPDPotrfInverse::lowerFactor() const
166{
167 require_factor();
168 EigenMatrix lower = state().gather(L_dist_.data(), L_desc_, n_, n_);
169 lower.triangularView<Eigen::StrictlyUpper>().setZero();
170 return lower;
171}
172
173CholeskyPanels ScalapackPDPotrfInverse::lowerFactorPanels() const
174{
175 require_factor();
176 const auto& st = state();
177 constexpr int transfer_elements = 1024 * 1024;
178 const int panel_columns = std::min<int>(
179 CholeskyPanels::panel_columns, std::max(1, transfer_elements / n_));
180 SharedFactorStorage storage;
181 CholeskyPanels panels(n_, panel_columns, [&](Eigen::Index entries) {
182 storage = allocateSharedFactor(entries, st);
183 return storage.data;
184 });
185 double dummy = 0.0;
186 const double* source = L_dist_.empty() ? &dummy : L_dist_.data();
187 int first = 0;
188 for (Eigen::Index i = 0; i < panels.panelCount(); ++i) {
189 const int rows = n_ - first;
190 const int columns = std::min(panel_columns, rows);
191 if (st.nprocs() == 1) {
192 auto panel = panels.panel(i);
193 for (int column = 0; column < columns; ++column)
194 std::copy_n(
195 source +
196 static_cast<std::size_t>(first + column) * L_desc_[8] +
197 first,
198 rows, panel.col(column).data());
199 } else {
200 // Packed by hand: Cpdgemr2d forms LP64 offsets into the local
201 // factor and cannot reach past 2^31 - 1 local entries.
202 const Eigen::MatrixXd transfer =
203 st.gather_block(source, L_desc_, first, first, rows, columns,
204 /*broadcast_result=*/true);
205 if (storage.writer) panels.panel(i) = transfer;
206 }
207 first += columns;
208 }
209 std::atomic_thread_fence(std::memory_order_release);
210 if (st.nprocs() > 1) MPI_Barrier(st.world_comm());
211 std::atomic_thread_fence(std::memory_order_acquire);
212 panels.shared_read_only_ = panels.hasSharedStorage();
213 return panels;
214}
215
216EigenMatrix ScalapackPDPotrfInverse::precision() const
217{
218 require_factor();
219 auto work = L_dist_;
220#ifdef GPR_LINALG_SLATE
221 if (state().reproducible()) {
222 slate_kernels::configure_nested_blas_threading(state());
223 std::vector<double> inverse_values;
224 canonical::choleskyInverseLower(state(), work.data(), L_desc_, n_,
225 inverse_values);
226 work = std::move(inverse_values);
227 } else if (!slate_kernels::potri_lower(work.data(), L_desc_, n_, state()))
228 throw std::runtime_error("distributed Cholesky inverse failed");
229#else
230 if (state().tile_kernels(L_desc_, "pdpotri")) {
231 ScopedTileKernelThreads tile_threads(state());
232 std::vector<double> inverse_values;
233 canonical::choleskyInverseLower(state(), work.data(), L_desc_, n_,
234 inverse_values);
235 work = std::move(inverse_values);
236 } else {
237 int info = 0, one = 1;
238 pdpotri_("L", &n_, work.data(), &one, &one, L_desc_, &info);
239 if (info != 0)
240 throw std::runtime_error("distributed Cholesky inverse failed");
241 }
242#endif
243 EigenMatrix inverse = state().gather(work.data(), L_desc_, n_, n_);
244 inverse = inverse.selfadjointView<Eigen::Lower>();
245 return inverse;
246}
247
248bool ScalapackPDPotrfInverse::factorise(std::vector<double> K_distributed,
249 const int desc[9], int n)
250{
251 // Reset to the unfactored state up-front. Prevents a partial-failure
252 // path (n <= 0, cholesky_distributed returns false, future exception
253 // out of the in-place pdpotrf) from leaving the operator silently
254 // re-using a stale L from a prior successful factorise on a different
255 // K. Subsequent solve/log_det/trace_inv_times will then throw via the
256 // factored_ guard rather than return numerically wrong answers.
257 factored_ = false;
258 L_dist_.clear();
259 substitution_.reset();
260 n_ = 0;
261 std::fill_n(L_desc_, 9, 0);
262
263 if (n <= 0) return false;
264
265 auto& st = state();
266 st.initialize();
267 if (desc == nullptr ||
268 (desc[1] != st.context() && desc[1] != st.lin_context()) ||
269 desc[2] != n || desc[3] != n)
270 return false;
271
272 int local_desc[9];
273 std::copy_n(desc, 9, local_desc);
275 if (!trainingCholeskyDistributed(K_distributed.data(), local_desc, n,
276 st))
277 return false;
278 } else {
279#ifdef GPR_LINALG_SLATE
280 // Reproducible arithmetic uses the same tile order on every grid.
281 if (st.reproducible()) {
282 slate_kernels::configure_nested_blas_threading(st);
283 if (!canonical::potrfLower(st, K_distributed.data(), local_desc, n))
284 return false;
285 } else if (!slate_kernels::potrf_lower(K_distributed.data(), local_desc,
286 n, st)) {
287 return false;
288 }
289#else
290 if (st.tile_kernels(local_desc, "pdpotrf")) {
291 ScopedTileKernelThreads tile_threads(st);
292 if (!canonical::potrfLower(st, K_distributed.data(), local_desc, n))
293 return false;
294 } else {
295 KernelWall wall(KernelWall::Kind::Factor);
296 int info = 0;
297 int one = 1;
298 pdpotrf_("L", &n, K_distributed.data(), &one, &one, local_desc,
299 &info);
300 if (info != 0) {
301 return false;
302 }
303 }
304#endif
305 }
306
307 L_dist_ = std::move(K_distributed);
308 std::copy_n(local_desc, 9, L_desc_);
309 n_ = n;
310 grid_generation_ = st.grid_generation();
311 factorization_generation_ = DistributedState::factorization_generation();
312 factored_ = true;
313 return true;
314}
315
316Eigen::VectorXd ScalapackPDPotrfInverse::solve(const Eigen::VectorXd& b) const
317{
318 require_factor();
319 // K x = b with K = L L^T factors as: solve L y = b (forward, pdtrsm
320 // with trans=N), then L^T x = y (back, pdtrsm with trans=T).
321 auto& st = state();
322 int desc_b[9];
323 int ncols = 1;
324 const bool linear = L_desc_[1] == st.lin_context();
325 std::vector<double> work =
326 linear ? st.scatter_lin_colvector_root(b, n_, desc_b)
327 : st.scatter_colvector_root(b, n_, desc_b);
328#ifdef GPR_LINALG_SLATE
329 // The factor and its substitutions use the same arithmetic mode.
330 if (st.reproducible()) {
331 slate_kernels::configure_nested_blas_threading(st);
332 canonical::solveLowerFactorCached(st, substitution_, L_dist_.data(),
333 L_desc_, work.data(), desc_b, n_,
334 ncols);
335 } else if (!slate_kernels::trsm_left_lower(L_dist_.data(), L_desc_, n_,
336 work.data(), desc_b, ncols,
337 /*transpose=*/false, st) ||
338 !slate_kernels::trsm_left_lower(L_dist_.data(), L_desc_, n_,
339 work.data(), desc_b, ncols,
340 /*transpose=*/true, st)) {
341 throw std::runtime_error(
342 "ScalapackPDPotrfInverse: SLATE triangular solve failed");
343 }
344#else
345 if (st.tile_kernels(L_desc_, "pdtrsm", desc_b)) {
346 ScopedTileKernelThreads tile_threads(st);
347 canonical::solveLowerFactorCached(st, substitution_, L_dist_.data(),
348 L_desc_, work.data(), desc_b, n_,
349 ncols);
350 } else {
351 KernelWall wall(KernelWall::Kind::Solve);
352 int one = 1;
353 double alpha = 1.0;
354 pdtrsm_("L", "L", "N", "N", &n_, &ncols, &alpha, L_dist_.data(), &one,
355 &one, L_desc_, work.data(), &one, &one, desc_b);
356 pdtrsm_("L", "L", "T", "N", &n_, &ncols, &alpha, L_dist_.data(), &one,
357 &one, L_desc_, work.data(), &one, &one, desc_b);
358 }
359#endif
360 return linear ? st.gather_lin_colvector_root(work.data(), desc_b, n_)
361 : st.gather_colvector_root(work.data(), desc_b, n_);
362}
363
364EigenMatrix ScalapackPDPotrfInverse::solve_mat(const EigenMatrix& B) const
365{
366 require_factor();
367 // Solve K X = B via L L^T X = B: forward solve L Y = B, then back
368 // solve L^T X = Y. At np=1 this matches DenseLLT to 1e-10.
369 auto& st = state();
370 int desc_b[9];
371 int ncols = static_cast<int>(B.cols());
372 const bool linear = L_desc_[1] == st.lin_context();
373 std::vector<double> work = linear ? st.scatter_lin(B, n_, ncols, desc_b)
374 : st.scatter(B, n_, ncols, desc_b);
375#ifdef GPR_LINALG_SLATE
376 // The factor and its substitutions use the same arithmetic mode.
377 if (st.reproducible()) {
378 slate_kernels::configure_nested_blas_threading(st);
379 canonical::solveLowerFactorCached(st, substitution_, L_dist_.data(),
380 L_desc_, work.data(), desc_b, n_,
381 ncols);
382 } else if (!slate_kernels::trsm_left_lower(L_dist_.data(), L_desc_, n_,
383 work.data(), desc_b, ncols,
384 /*transpose=*/false, st) ||
385 !slate_kernels::trsm_left_lower(L_dist_.data(), L_desc_, n_,
386 work.data(), desc_b, ncols,
387 /*transpose=*/true, st)) {
388 throw std::runtime_error(
389 "ScalapackPDPotrfInverse: SLATE triangular solve failed");
390 }
391#else
392 if (st.tile_kernels(L_desc_, "pdtrsm", desc_b)) {
393 ScopedTileKernelThreads tile_threads(st);
394 canonical::solveLowerFactorCached(st, substitution_, L_dist_.data(),
395 L_desc_, work.data(), desc_b, n_,
396 ncols);
397 } else {
398 KernelWall wall(KernelWall::Kind::Solve);
399 int one = 1;
400 double alpha = 1.0;
401 pdtrsm_("L", "L", "N", "N", &n_, &ncols, &alpha, L_dist_.data(), &one,
402 &one, L_desc_, work.data(), &one, &one, desc_b);
403 pdtrsm_("L", "L", "T", "N", &n_, &ncols, &alpha, L_dist_.data(), &one,
404 &one, L_desc_, work.data(), &one, &one, desc_b);
405 }
406#endif
407 return st.gather(work.data(), desc_b, n_, ncols);
408}
409
410double ScalapackPDPotrfInverse::log_det() const
411{
412 require_factor();
413 auto& st = state();
414 const auto grid = canonical::geometryOf(st, L_desc_);
415 ExactSum local_sum;
416 for (int i = 0; i < n_; ++i) {
417 const int owner_row = (i / grid.nb) % grid.nprow;
418 const int owner_col = (i / grid.nb) % grid.npcol;
419 if (owner_row != grid.myrow || owner_col != grid.mycol) continue;
420
421 const int local_i =
422 st.local_index_for_global(i, grid.nb, grid.myrow, grid.nprow);
423 const int local_j =
424 st.local_index_for_global(i, grid.nb, grid.mycol, grid.npcol);
425 local_sum.add(std::log(L_dist_[static_cast<size_t>(local_i) +
426 static_cast<size_t>(local_j) *
427 static_cast<size_t>(L_desc_[8])]));
428 }
429 exact_sum_bcast(&local_sum, 1, st);
430 return 2.0 * local_sum.value();
431}
432
433double ScalapackPDPotrfInverse::trace_inv_times(const EigenMatrix& A) const
434{
435 require_factor();
436 // Scatter A through the BLACS layout, apply two pdtrsm's
437 // (L Y = A, L^T Z = Y so Z = K^{-1} A), then sum the diagonal via
438 // owner-aware local extraction + ordered_sum_bcast. No symmetry
439 // exploitation on A; matches the base KernelInverse contract.
440 auto& st = state();
441 int desc_a[9];
442 int ncols = static_cast<int>(A.cols());
443 const bool linear = L_desc_[1] == st.lin_context();
444 std::vector<double> work = linear ? st.scatter_lin(A, n_, ncols, desc_a)
445 : st.scatter(A, n_, ncols, desc_a);
446#ifdef GPR_LINALG_SLATE
447 // The factor and its substitutions use the same arithmetic mode.
448 if (st.reproducible()) {
449 slate_kernels::configure_nested_blas_threading(st);
450 canonical::solveLowerFactorCached(st, substitution_, L_dist_.data(),
451 L_desc_, work.data(), desc_a, n_,
452 ncols);
453 } else if (!slate_kernels::trsm_left_lower(L_dist_.data(), L_desc_, n_,
454 work.data(), desc_a, ncols,
455 /*transpose=*/false, st) ||
456 !slate_kernels::trsm_left_lower(L_dist_.data(), L_desc_, n_,
457 work.data(), desc_a, ncols,
458 /*transpose=*/true, st)) {
459 throw std::runtime_error(
460 "ScalapackPDPotrfInverse: SLATE triangular solve failed");
461 }
462#else
463 if (st.tile_kernels(L_desc_, "pdtrsm", desc_a)) {
464 ScopedTileKernelThreads tile_threads(st);
465 canonical::solveLowerFactorCached(st, substitution_, L_dist_.data(),
466 L_desc_, work.data(), desc_a, n_,
467 ncols);
468 } else {
469 KernelWall wall(KernelWall::Kind::Solve);
470 int one = 1;
471 double alpha = 1.0;
472 pdtrsm_("L", "L", "N", "N", &n_, &ncols, &alpha, L_dist_.data(), &one,
473 &one, L_desc_, work.data(), &one, &one, desc_a);
474 pdtrsm_("L", "L", "T", "N", &n_, &ncols, &alpha, L_dist_.data(), &one,
475 &one, L_desc_, work.data(), &one, &one, desc_a);
476 }
477#endif
478
479 const int diag_n = std::min(n_, ncols);
480 const auto grid = canonical::geometryOf(st, desc_a);
481 ExactSum local_trace;
482 for (int i = 0; i < diag_n; ++i) {
483 const int owner_row = (i / grid.nb) % grid.nprow;
484 const int owner_col = (i / grid.nb) % grid.npcol;
485 if (owner_row != grid.myrow || owner_col != grid.mycol) continue;
486
487 const int local_i =
488 st.local_index_for_global(i, grid.nb, grid.myrow, grid.nprow);
489 const int local_j =
490 st.local_index_for_global(i, grid.nb, grid.mycol, grid.npcol);
491 local_trace.add(work[static_cast<size_t>(local_i) +
492 static_cast<size_t>(local_j) *
493 static_cast<size_t>(desc_a[8])]);
494 }
495 exact_sum_bcast(&local_trace, 1, st);
496 return local_trace.value();
497}
498
499} // namespace linalg
500} // namespace gpr
501
502#endif // GPR_LINALG_SCALAPACK
Linear algebra abstraction layer for GPR hot-path operations.
Triangular solves and Cholesky inverse whose floating-point result does not depend on the process gri...
Exact floating-point accumulator (Kulisch long accumulator).
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 pdpotri_(const char *uplo, const int *n, double *a, const int *ia, const int *ja, const int *desca, int *info)
Distributed ScaLAPACK pdpotrf-based KernelInverse impl.
Dense and structured linear algebra behind the GP: Cholesky and eigen solvers, linear operators,...
void exact_sum_bcast(ExactSum *sums, int count, const MpiContext &context)
bool trainingCholeskyDistributedSelected(Eigen::Index order)
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
Panel panel(Real left, Real right, const Function &function, std::size_t &evaluations)