Loading...
Searching...
No Matches
DistributedState.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// BLACS process grids and ScaLAPACK descriptor/buffer utilities.
6
7#ifndef GPR_LINALG_DISTRIBUTEDSTATE_H_
8#define GPR_LINALG_DISTRIBUTEDSTATE_H_
9
10#include <mpi.h>
11#ifdef __linux__
12#include <sched.h>
13#endif
14
15#include <algorithm>
16#include <array>
17#include <atomic>
18#include <bit>
19#include <cassert>
20#include <cmath>
21#include <cstdint>
22#include <cstdio>
23#include <memory>
24#include <mutex>
25#include <stdexcept>
26#include <string>
27#include <utility>
28#include <vector>
29
31// ScaLAPACK / BLACS / PBLAS symbols are loaded at runtime (dlopen + dlsym); the
32// loader provides global forwarders preserving the original symbol names so the
33// calls below are unchanged. Conda-forge scalapack 2.1.0 bundles BLACS into
34// libscalapack.so. See ScalapackLib.h for the runtime-vs-Eigen rationale.
35#include "LinalgThreads.h"
36#include "Lp64Limits.h"
37#include "MpiCommunicator.h"
38#include "MpiThreading.h"
39#include "ScalapackLib.h"
40#include "TileParallel.h"
41
42namespace gpr {
43namespace linalg {
44
46
48{
49#if defined(GPR_LINALG_SLATE)
51#elif defined(GPR_LINALG_SCALAPACK)
53#else
55#endif
56}
57
58constexpr const char* distributed_backend_name(
60{
61 switch (backend) {
63 return "slate";
65 return "scalapack";
67 return "eigen";
68 }
69 return "eigen";
70}
71
73public:
75 std::vector<double> values;
76 std::array<int, 9> descriptor{};
77 int order = 0;
78
79 [[nodiscard]] bool valid() const noexcept
80 {
81 // A global factor can have no entries on an idle rank.
82 return order > 0 && descriptor[2] == order &&
83 descriptor[3] == order && descriptor[8] > 0;
84 }
85
86 void clear() noexcept
87 {
88 values.clear();
89 descriptor.fill(0);
90 order = 0;
91 }
92 };
93
95 {
96 static DistributedState inst;
97 return inst;
98 }
99
103 std::shared_ptr<const MpiCommunicator> communication)
104 : communication_(std::move(communication))
105 {
106 if (!communication_)
107 throw std::invalid_argument(
108 "distributed state requires communication");
109 }
110
112 {
113 int mpi_up = 0;
114 int mpi_fin = 0;
115 MPI_Initialized(&mpi_up);
116 MPI_Finalized(&mpi_fin);
117 if (!mpi_up || mpi_fin) return;
118 release_grids();
119 communication_.reset();
120 if (owns_mpi_) MPI_Finalize();
121 }
122
123 [[nodiscard]] const std::shared_ptr<const MpiCommunicator>& communication()
124 const noexcept
125 {
126 return communication_;
127 }
128
129 [[nodiscard]] std::uint64_t grid_generation() const noexcept
130 {
131 return grid_generation_;
132 }
133
136 [[nodiscard]] DistributedFactorization factorization() const noexcept
137 {
139 }
140
141 [[nodiscard]] bool reproducible() const noexcept
142 {
144 }
145
149 [[nodiscard]] bool exceeds_lp64(const int* desc) const
150 {
151 int rows = 0, cols = 0;
152 descriptor_grid(desc, rows, cols);
153 return exceedsLp64(desc, rows, cols);
154 }
155
162 [[nodiscard]] bool tile_kernels(const int* desc, const char* routine,
163 const int* other = nullptr) const
164 {
165 if (reproducible()) return true;
166 if (other != nullptr && !exceeds_lp64(desc) && exceeds_lp64(other))
167 desc = other;
168 if (!exceeds_lp64(desc)) return false;
169 static std::atomic<bool> reported{false};
170 if (is_root() && !reported.exchange(true)) {
171 int rows = 0, cols = 0;
172 descriptor_grid(desc, rows, cols);
173 std::fprintf(
174 stderr,
175 "[gpr::linalg] library factorization: %s on order %d needs "
176 "%lld local entries on a %d x %d grid, past the %lld an "
177 "LP64 ScaLAPACK indexes; operations on this order run on "
178 "the tile kernels\n",
179 routine, desc[2],
180 static_cast<long long>(largestLocalEntries(desc, rows, cols)),
181 rows, cols, static_cast<long long>(lp64IndexLimit()));
182 }
183 return true;
184 }
185
188 void require_lp64(const int* desc, const char* routine) const
189 {
190 if (!exceeds_lp64(desc)) return;
191 int rows = 0, cols = 0;
192 descriptor_grid(desc, rows, cols);
193 throw std::length_error(
194 std::string(routine) + ": a " + std::to_string(desc[2]) + " x " +
195 std::to_string(desc[3]) + " matrix on a " + std::to_string(rows) +
196 " x " + std::to_string(cols) + " grid needs " +
197 std::to_string(largestLocalEntries(desc, rows, cols)) +
198 " local entries, past the " + std::to_string(lp64IndexLimit()) +
199 " an LP64 ScaLAPACK indexes; run on more processes");
200 }
201
206 {
207 if (mode == factorization()) return;
209 invalidate_L();
211 }
212
215 [[nodiscard]] static std::uint64_t factorization_generation() noexcept
216 {
218 }
219
220 static constexpr DistributedBackendKind compiled_backend() noexcept
221 {
223 }
224
225 [[nodiscard]] DistributedBackendKind backend_kind() const noexcept
226 {
227 return compiled_backend();
228 }
229
230 [[nodiscard]] const char* backend_name() const noexcept
231 {
233 }
234
235 static int recommended_block_size(int requested_block, int nprocs)
236 {
237 (void)nprocs;
238 if (requested_block <= 0) return 64;
239 return requested_block;
240 }
241
243 {
244 (void)block_size;
245 if (nprocs <= 1) return 1;
246 int nprow = static_cast<int>(std::sqrt(static_cast<double>(nprocs)));
247 if (nprow < 1) nprow = 1;
248 while (nprocs % nprow != 0)
249 --nprow;
250 return nprow;
251 }
252
263 bool computation_tile = false) noexcept
264 {
265 configured_block_size_ = block_size > 0 ? block_size : 0;
266 configured_nprow_ = nprow > 0 ? nprow : 0;
267 computation_tile_ = computation_tile;
268 }
269
270 [[nodiscard]] int configured_block_size() const noexcept
271 {
272 return configured_block_size_;
273 }
274
277 [[nodiscard]] int effective_configured_block_size() const noexcept
278 {
279 if (configured_block_size_ > 0) return configured_block_size_;
280 const bool tile_sets_arithmetic =
282 reproducible();
283 if (computation_tile_ && tile_sets_arithmetic)
284 return recommended_block_size(0, nprocs_);
285 return 0;
286 }
287
288 [[nodiscard]] int configured_nprow() const noexcept
289 {
290 return configured_nprow_;
291 }
292
293 // Idempotent initialization. Call before any ScaLAPACK operation.
294 void initialize(int block_size = 0, int nprow = 0)
295 {
296 const int configured_block = effective_configured_block_size();
297 const int requested_block_size =
298 configured_block > 0 ? configured_block : block_size;
299 const int requested_nprow =
300 configured_nprow_ > 0 ? configured_nprow_ : nprow;
301 // Hot-path fast exit: when callers pass block_size=0 (the no-override
302 // default used by every per-iter site such as
303 // applyCrossCovarianceFunction and
304 // accumulateCrossCovarianceMatVecLocal), and we are already
305 // initialized, the requested grid cannot change. Skip all of
306 // MPI_Initialized + MPI_Comm_size + MPI_Comm_rank + the
307 // recommended-block / recommended-nprow math.
308 if (initialized_ &&
309 (requested_block_size <= 0 || requested_block_size == mb_) &&
310 (requested_nprow <= 0 || requested_nprow == nprow_)) {
311 return;
312 }
313
314 // Ensure MPI is up (BLACS piggybacks on MPI)
315 int mpi_up = 0;
316 MPI_Initialized(&mpi_up);
317 int provided = MPI_THREAD_SINGLE;
318 if (!mpi_up) {
319 if (MPI_Init_thread(nullptr, nullptr, requiredMpiThreadSupport(),
320 &provided) != MPI_SUCCESS)
321 throw std::runtime_error("could not initialize MPI");
322 owns_mpi_ = true;
323 } else if (MPI_Query_thread(&provided) != MPI_SUCCESS) {
324 throw std::runtime_error("could not inspect MPI thread support");
325 }
326 if (provided < requiredMpiThreadSupport()) {
327 if (owns_mpi_) {
328 MPI_Finalize();
329 owns_mpi_ = false;
330 }
331 throw std::runtime_error(mpiThreadSupportError());
332 }
333
334 if (!communication_)
335 communication_ = std::make_shared<MpiCommunicator>(MPI_COMM_WORLD);
336 const MpiContext process_group = communication_->view();
337 const int next_nprocs = process_group.nprocs;
338 const int next_myrank = process_group.rank;
339
340 if (requested_block_size > 0) {
341 block_size =
342 recommended_block_size(requested_block_size, next_nprocs);
343 } else if (block_size <= 0) {
344 block_size =
345 initialized_ ? mb_ : recommended_block_size(64, next_nprocs);
346 } else {
348 }
349
350 // Create BLACS process grid (as close to square as possible)
351 int next_nprow = recommended_nprow(next_nprocs, block_size);
352 if (requested_nprow > 0 && next_nprocs % requested_nprow == 0) {
353 next_nprow = requested_nprow;
354 }
355 const int next_npcol = next_nprocs / next_nprow;
356
357 if (initialized_) {
358 const bool same_grid = mb_ == block_size &&
359 nprocs_ == next_nprocs &&
360 myrank_ == next_myrank &&
361 nprow_ == next_nprow && npcol_ == next_npcol;
362 if (same_grid) return;
363
364 release_grids();
365 has_L_ = false;
366 L_owner_ = nullptr;
367 has_inv_ = false;
368 L_cache_.clear();
369 U_cache_.clear();
370 has_U_ = false;
371 Inv_cache_.clear();
372 L_n_ = 0;
373 Inv_n_ = 0;
374 L_lin_cache_.clear();
375 L_lin_n_ = 0;
376 has_L_lin_ = false;
377 desc_cache_.clear();
378 initialized_ = false;
379 }
380
381 nprocs_ = next_nprocs;
382 myrank_ = next_myrank;
383 mb_ = block_size;
384 nprow_ = next_nprow;
385 npcol_ = next_npcol;
386
387 gpr_comm_ = process_group.comm;
388 // BLACS interns system handles by MPI handle identity. A private
389 // duplicate gives this grid sole ownership of its system-table entry.
390 blacs_communication_ = std::make_unique<MpiCommunicator>(gpr_comm_);
391 system_handle_ = Csys2blacs_handle(blacs_communication_->view().comm);
392
393 ictxt_ = system_handle_;
394 Cblacs_gridinit(&ictxt_, "Row-major", nprow_, npcol_);
395 Cblacs_gridinfo(ictxt_, &nprow_, &npcol_, &myrow_, &mycol_);
396
397 // Linear (nprocs x 1) sub-context for deterministic distributed
398 // factorisations. With a single process column, pdpotrf / pdtrsm
399 // partition matrix rows across ranks in numerical order; column-wise
400 // sums stay local to one rank, and cross-rank reductions traverse
401 // ranks 0..nprocs-1 in fixed order. The dense factor / solve output
402 // is bit-stable across primary-grid topology choices, satisfying
403 // the ELPA-style invariant.
404 lin_ictxt_ = system_handle_;
405 Cblacs_gridinit(&lin_ictxt_, "Row-major", nprocs_, 1);
406 int lin_nprow = 0, lin_npcol = 0;
407 Cblacs_gridinfo(lin_ictxt_, &lin_nprow, &lin_npcol, &lin_myrow_,
408 &lin_mycol_);
409
410 // Column-block (1 x nprocs) grid: process j owns the j-th contiguous
411 // block of mode columns for the mode-distributed HS-SVD design build.
412 col_ictxt_ = system_handle_;
413 Cblacs_gridinit(&col_ictxt_, "Row-major", 1, nprocs_);
414 int col_nprow = 0, col_npcol = 0;
415 Cblacs_gridinfo(col_ictxt_, &col_nprow, &col_npcol, &col_myrow_,
416 &col_mycol_);
417
418 // Ranks sharing this node's memory, for the per-rank memory budget
419 // of large workspaces (MemoryBudget.h).
420 MPI_Comm node = MPI_COMM_NULL;
421 MPI_Comm_split_type(gpr_comm_, MPI_COMM_TYPE_SHARED, myrank_,
422 MPI_INFO_NULL, &node);
423 MPI_Comm_size(node, &node_ranks_);
424 cpu_share_ = node_cpu_share(node);
425 MPI_Comm_free(&node);
426
427 initialized_ = true;
428 ++grid_generation_;
429 }
430
432 [[nodiscard]] int node_ranks() const noexcept
433 {
434 return node_ranks_;
435 }
436
442 [[nodiscard]] int cpu_share() const noexcept
443 {
444 return cpu_share_;
445 }
446
447 // Linear-grid descriptor (nprocs x 1 distribution). Used for
448 // deterministic Cholesky / triangular solve.
449 void make_lin_desc(int m, int n, int* desc) const
450 {
451 int lld = std::max(1, lin_local_rows(m));
452 int info = 0;
453 int zero = 0;
454 descinit_(desc, &m, &n, &mb_, &mb_, &zero, &zero, &lin_ictxt_, &lld,
455 &info);
456 assert(info == 0);
457 }
458
459 int lin_local_rows(int m) const
460 {
461 int zero = 0;
462 return numroc_(&m, &mb_, &lin_myrow_, &zero, &nprocs_);
463 }
464
465 // Block width for the contiguous 1 x nprocs column distribution: with
466 // nb = ceil(n/np), process j owns exactly the columns [j*nb, (j+1)*nb),
467 // one contiguous block per rank (the last possibly short, later ranks
468 // empty). This is the column ownership the mode-distributed design build
469 // must match so each rank computes only its own modes.
470 int col_block_nb(int n) const
471 {
472 return (n + nprocs_ - 1) / nprocs_;
473 }
474
475 // This rank's contiguous global column range [start, start+count) on the
476 // 1 x nprocs column-block grid. count == 0 for ranks past the last block.
477 void col_block_range(int n, int& start, int& count) const
478 {
479 const int nb = col_block_nb(n);
480 start = col_mycol_ * nb;
481 if (start >= n) {
482 start = n;
483 count = 0;
484 } else {
485 count = std::min(nb, n - start);
486 }
487 }
488
489 // Source descriptor for the col-block layout on col_ictxt_: a single row
490 // block (mb = m) and nb = ceil(n/np), so each rank's local array is the
491 // contiguous m x count column slice it built. Feed to Cpdgemr2d to
492 // redistribute into the block-cyclic compute grid for pdgesvd.
493 void make_col_desc(int m, int n, int* desc) const
494 {
495 const int nb = col_block_nb(n);
496 int lld = std::max(1, m);
497 int info = 0;
498 int zero = 0;
499 descinit_(desc, &m, &n, &m, &nb, &zero, &zero, &col_ictxt_, &lld,
500 &info);
501 assert(info == 0);
502 }
503
504 int compute_ictxt() const
505 {
506 return ictxt_;
507 }
508
509 int lin_local_cols(int n) const
510 {
511 // Single column on the linear grid: every rank owns all n columns.
512 (void)n;
513 return n;
514 }
515
516 // Scatter a global ColMajor matrix (root-only) onto the linear
517 // (nprocs x 1) grid. Returns the local block-cyclic buffer and fills
518 // desc. nprocs == 1 collapses to a Cpdgemr2d 1x1 -> 1x1 redistribution
519 // which is a memcpy on root with the same descriptor on both sides.
520 std::vector<double> scatter_lin(const EigenMatrix& global, int m, int n,
521 int* desc) const
522 {
523 make_lin_desc(m, n, desc);
524 const int lr = lin_local_rows(m);
525 const int lc = lin_local_cols(n);
526 std::vector<double> local(static_cast<size_t>(lr) * lc, 0.0);
527
528 int desc_g[9];
529 int lld_g = std::max(1, m);
530 int zero = 0;
531 int info = 0;
532 descinit_(desc_g, &m, &n, &m, &n, &zero, &zero, &lin_ictxt_, &lld_g,
533 &info);
534 assert(info == 0);
535
536 double dummy = 0.0;
537 const bool root_has_data =
538 lin_myrow_ == 0 && lin_mycol_ == 0 &&
539 global.size() == static_cast<Eigen::Index>(m) * n;
540 if (exceeds_lp64(desc_g) || exceeds_lp64(desc)) {
541 // Grid process (0, 0) of the linear grid is world rank 0.
542 scatter_by_panels(root_has_data ? global.data() : nullptr, m, n,
543 desc, local.data(), lin_myrow_, 0, nprocs_, 1);
544 return local;
545 }
546 const double* global_data = root_has_data ? global.data() : &dummy;
547 Cpdgemr2d(m, n, global_data, 1, 1, desc_g, local.data(), 1, 1, desc,
548 lin_ictxt_);
549 return local;
550 }
551
552 // Scatter a (m x 1) column vector replicated on rank 0 onto the linear
553 // (nprocs x 1) grid. The single column lives on every rank's mycol=0;
554 // rows are partitioned across ranks by myrow. nprocs == 1 collapses
555 // to a single rank owning all m rows -- the same code path runs
556 // without special casing.
557 std::vector<double> scatter_lin_colvector_root(
558 const Eigen::VectorXd& global, int m, int* desc) const
559 {
560 make_lin_desc(m, 1, desc);
561 const int lr = lin_local_rows(m);
562 std::vector<double> local(static_cast<size_t>(lr), 0.0);
563
564 Eigen::VectorXd replicated =
565 is_root() ? global : Eigen::VectorXd::Zero(m);
566 if (replicated.size() != m) replicated.resize(m);
567 if (nprocs_ > 1) {
568 MPI_Bcast(replicated.data(), m, MPI_DOUBLE, 0, gpr_comm_);
569 }
570
571 for (int i = 0; i < m; ++i) {
572 const int owner_row = (i / mb_) % nprocs_;
573 if (owner_row != lin_myrow_) continue;
574 const int local_i =
575 local_index_for_global(i, mb_, lin_myrow_, nprocs_);
576 local[static_cast<size_t>(local_i)] = replicated(i);
577 }
578 return local;
579 }
580
581 // Gather a (m x 1) result on the linear grid back to a replicated
582 // VectorXd on every rank. With (nprocs x 1) layout, ranks own disjoint
583 // row slices; sum-reduce over disjoint one-hot contributions
584 // reconstitutes the full vector. The FP sum is bit-trivial because at
585 // each index exactly one rank holds a non-zero value -- reduction
586 // order does not matter.
587 Eigen::VectorXd gather_lin_colvector_root(const double* local,
588 const int* desc, int m) const
589 {
590 (void)desc;
591 Eigen::VectorXd result = Eigen::VectorXd::Zero(m);
592 for (int i = 0; i < m; ++i) {
593 const int owner_row = (i / mb_) % nprocs_;
594 if (owner_row != lin_myrow_) continue;
595 const int local_i =
596 local_index_for_global(i, mb_, lin_myrow_, nprocs_);
597 result(i) = local[static_cast<size_t>(local_i)];
598 }
599 if (nprocs_ > 1) {
600 MPI_Allreduce(MPI_IN_PLACE, result.data(), m, MPI_DOUBLE, MPI_SUM,
601 gpr_comm_);
602 }
603 return result;
604 }
605
606 // Fill a 9-element ScaLAPACK descriptor for an (m x n) distributed matrix.
607 // The descriptor depends only on (m, n, mb_, ictxt_); since mb_ and ictxt_
608 // are stable between initialize() reconfigurations and a small number of
609 // distinct (m, n) shapes are reused per gradient call (training NxN cov,
610 // Nx1 RHS, derivative blocks), cache the BLACS descinit_ output so repeat
611 // shapes skip the Fortran call. The cache invalidates whenever
612 // initialize() actually reconfigures the grid (see desc_cache_.clear()
613 // call there).
614 void make_desc(int m, int n, int* desc) const
615 {
616 // desc_cache_ is mutable and shared across threads on this
617 // singleton state. Today's call sites are all outside any
618 // OpenMP region, but since the kernel-assembly hot path could
619 // legitimately be wrapped in #pragma omp parallel for in the
620 // future (per the day-1 par_unseq target), guard the cache
621 // read/write with a mutex so the latent hazard cannot
622 // silently corrupt the descriptor vector. The lock is
623 // uncontended on the serial path (one acquire per descinit_
624 // call, ~10 ns); under multi-threaded callers it serialises
625 // cache access without affecting the cached descinit_ output.
626 std::lock_guard<std::mutex> guard(desc_cache_mutex_);
627 for (const auto& entry: desc_cache_) {
628 if (entry.m == m && entry.n == n) {
629 std::copy_n(entry.desc, 9, desc);
630 return;
631 }
632 }
633 int lld = std::max(1, local_rows(m));
634 int info = 0;
635 int zero = 0;
636 descinit_(desc, &m, &n, &mb_, &mb_, &zero, &zero, &ictxt_, &lld, &info);
637 assert(info == 0);
638 DescCacheEntry entry;
639 entry.m = m;
640 entry.n = n;
641 std::copy_n(desc, 9, entry.desc);
642 desc_cache_.push_back(entry);
643 }
644
645 // Local row count for global dimension m on this rank.
646 int local_rows(int m) const
647 {
648 int zero = 0;
649 return numroc_(&m, &mb_, &myrow_, &zero, &nprow_);
650 }
651
652 // Local column count for global dimension n on this rank.
653 int local_cols(int n) const
654 {
655 int zero = 0;
656 return numroc_(&n, &mb_, &mycol_, &zero, &npcol_);
657 }
658
659 int local_index_for_global(int global_index, int block_size, int proc_coord,
660 int nprocs_dim) const
661 {
662 const int block = global_index / block_size;
663 const int intra = global_index % block_size;
664#ifndef NDEBUG
665 const int owner = block % nprocs_dim;
666 assert(owner == proc_coord);
667#else
668 (void)proc_coord;
669#endif
670 const int local_block = block / nprocs_dim;
671 return local_block * block_size + intra;
672 }
673
674 int global_index_for_local(int local_index, int block_size, int proc_coord,
675 int nprocs_dim) const
676 {
677 const int local_block = local_index / block_size;
678 const int intra = local_index % block_size;
679 const int global_block = local_block * nprocs_dim + proc_coord;
680 return global_block * block_size + intra;
681 }
682
683 // Scatter a global ColMajor matrix (meaningful on rank 0) into a
684 // block-cyclic distributed buffer. Returns local buffer; fills desc.
685 //
686 std::vector<double> scatter(const EigenMatrix& global, int m, int n,
687 int* desc) const
688 {
689 make_desc(m, n, desc);
690 int lr = local_rows(m);
691 int lc = local_cols(n);
692 std::vector<double> local(static_cast<size_t>(lr) * lc, 0.0);
693
694 if (nprocs_ == 1) {
695 // Single rank: just copy (no redistribution overhead)
696 assert(lr == m && lc == n);
697 if (global.size() > 0)
698 std::copy_n(global.data(), static_cast<size_t>(m) * n,
699 local.data());
700 return local;
701 }
702
703 // Build a single-process descriptor covering the full matrix on rank 0
704 int desc_g[9];
705 int lld_g = std::max(1, m);
706 int zero = 0;
707 int info = 0;
708 descinit_(desc_g, &m, &n, &m, &n, &zero, &zero, &ictxt_, &lld_g, &info);
709 assert(info == 0);
710
711 // Redistribute: rank-0 global -> distributed block-cyclic. Non-root
712 // ranks may keep the dense matrix empty when the caller only
713 // materializes the assembled covariance on the root rank.
714 double dummy = 0.0;
715 const bool root_has_data =
716 is_root() && global.size() == static_cast<Eigen::Index>(m) * n;
717 if (exceeds_lp64(desc_g) || exceeds_lp64(desc)) {
718 scatter_by_panels(root_has_data ? global.data() : nullptr, m, n,
719 desc, local.data(), myrow_, mycol_, nprow_,
720 npcol_);
721 return local;
722 }
723 const double* global_data = root_has_data ? global.data() : &dummy;
724 Cpdgemr2d(m, n, global_data, 1, 1, desc_g, local.data(), 1, 1, desc,
725 ictxt_);
726 return local;
727 }
728
729 // Scatter from rank 0 without Cpdgemr2d, whose LP64 offsets cannot reach
730 // a root matrix or local array past 2^31 - 1 entries. Root broadcasts
731 // bounded column panels and every rank copies the entries it owns in
732 // the layout of desc on the (row, col) coordinate of an nprow x npcol
733 // grid, with every offset in std::size_t. global is read on rank 0
734 // only; null there scatters zeros. Collective.
735 void scatter_by_panels(const double* global, int m, int n, const int* desc,
736 double* local, int row, int col, int nprow,
737 int npcol) const
738 {
739 constexpr int transfer_elements = 1024 * 1024;
740 const int panel_columns =
741 std::max(1, transfer_elements / std::max(1, m));
742 const int local_rows_here =
743 numroc_(&m, &desc[4], &row, &desc[6], &nprow);
744 std::vector<int> owned_rows(static_cast<std::size_t>(local_rows_here));
745 for (int il = 0; il < local_rows_here; ++il)
746 owned_rows[static_cast<std::size_t>(il)] =
747 ((il / desc[4]) * nprow + (row - desc[6] + nprow) % nprow) *
748 desc[4] +
749 il % desc[4];
750 std::vector<double> panel;
751 for (int first = 0; first < n; first += panel_columns) {
752 const int columns = std::min(panel_columns, n - first);
753 panel.assign(static_cast<std::size_t>(m) * columns, 0.0);
754 if (is_root() && global != nullptr)
755 std::copy_n(global + static_cast<std::size_t>(first) * m,
756 panel.size(), panel.data());
757 MPI_Bcast(panel.data(), static_cast<int>(panel.size()), MPI_DOUBLE,
758 0, gpr_comm_);
759 for (int j = first; j < first + columns; ++j) {
760 if ((j / desc[5] + desc[7]) % npcol != col) continue;
761 const int jl = (j / desc[5] / npcol) * desc[5] + j % desc[5];
762 double* target = local + static_cast<std::size_t>(jl) * desc[8];
763 const double* source =
764 panel.data() + static_cast<std::size_t>(j - first) * m;
765 for (int il = 0; il < local_rows_here; ++il)
766 target[il] =
767 source[owned_rows[static_cast<std::size_t>(il)]];
768 }
769 }
770 }
771
772 // Allocate a zero-filled block-cyclic local buffer for an m x n distributed
773 // matrix and fill its descriptor. Used for SVD output factors (U, VT) that
774 // pdgesvd writes but the caller does not pre-populate.
775 std::vector<double> alloc_local(int m, int n, int* desc) const
776 {
777 make_desc(m, n, desc);
778 return std::vector<double>(
779 static_cast<size_t>(local_rows(m)) * local_cols(n), 0.0);
780 }
781
782 // Broadcast a replicated root vector and pack the owned entries directly
783 // into the distributed (m x 1) ScaLAPACK layout. This avoids Cpdgemr2d's
784 // datatype/communicator churn on the hot vector-solve path.
785 std::vector<double> scatter_colvector_root(const Eigen::VectorXd& global,
786 int m, int* desc) const
787 {
788 make_desc(m, 1, desc);
789 const int lr = local_rows(m);
790 const int lc = local_cols(1);
791 std::vector<double> local(static_cast<size_t>(lr) * lc, 0.0);
792
793 if (nprocs_ == 1) {
794 assert(lr == m && lc == 1);
795 if (global.size() > 0)
796 std::copy_n(global.data(), static_cast<size_t>(m),
797 local.data());
798 return local;
799 }
800
801 Eigen::VectorXd replicated =
802 is_root() ? global : Eigen::VectorXd::Zero(m);
803 if (replicated.size() != m) replicated.resize(m);
804 MPI_Bcast(replicated.data(), m, MPI_DOUBLE, 0, gpr_comm_);
805
806 if (lc == 0 || mycol_ != 0) return local;
807
808 for (int i = 0; i < m; ++i) {
809 const int owner_row = (i / mb_) % nprow_;
810 if (owner_row != myrow_) continue;
811 const int local_i = local_index_for_global(i, mb_, myrow_, nprow_);
812 local[static_cast<size_t>(local_i)] = replicated(i);
813 }
814 return local;
815 }
816
817 // Gather a distributed buffer back into a global EigenMatrix.
818 // By default the gathered matrix is broadcast to all ranks for callers
819 // that still need replicated results; large square intermediates can stay
820 // root-local by passing broadcast_result=false.
821 EigenMatrix gather(const double* local, const int* desc, int m, int n,
822 bool broadcast_result = true) const
823 {
824 return gather_block(local, desc, 0, 0, m, n, broadcast_result);
825 }
826
827 // Gather the m x n block whose first entry is global (row0, col0) of a
828 // distributed buffer. Owned entries are packed by hand in bounded column
829 // panels, with every local offset formed in std::size_t, so the block
830 // is reachable at any local array size (Cpdgemr2d forms LP64 offsets).
831 EigenMatrix gather_block(const double* local, const int* desc, int row0,
832 int col0, int m, int n,
833 bool broadcast_result = true) const
834 {
835 EigenMatrix global;
836
837 if (nprocs_ == 1) {
838 global.resize(m, n);
839 for (int j = 0; j < n; ++j)
840 std::copy_n(
841 local + static_cast<std::size_t>(col0 + j) * desc[8] + row0,
842 m, global.data() + static_cast<std::size_t>(j) * m);
843 return global;
844 }
845
846 if (broadcast_result || is_root()) {
847 global.resize(m, n);
848 } else {
849 global = EigenMatrix::Zero(1, 1);
850 }
851
852 // Pack owned entries into bounded panels. Redistribution through a
853 // block descriptor can reserve an entire source block even when the
854 // requested panel contains only a few columns of that block.
855 int grid_rows = 0, grid_columns = 0, row = 0, column = 0;
856 Cblacs_gridinfo(desc[1], &grid_rows, &grid_columns, &row, &column);
857 if (n == 1) {
858 // A vector has one owner for each bit pattern. Integer OR moves
859 // those patterns in one collective, preserving signed zeros and
860 // non-finite payloads without floating-point arithmetic.
861 std::vector<std::uint64_t> bits(static_cast<std::size_t>(m), 0);
862 if ((col0 / desc[5] + desc[7]) % grid_columns == column) {
863 const std::size_t local_column =
864 (col0 / desc[5] / grid_columns) * desc[5] + col0 % desc[5];
865 for (int i = 0; i < m; ++i) {
866 const int global_row = row0 + i;
867 if ((global_row / desc[4] + desc[6]) % grid_rows != row)
868 continue;
869 const std::size_t local_row =
870 (global_row / desc[4] / grid_rows) * desc[4] +
871 global_row % desc[4];
872 bits[static_cast<std::size_t>(i)] =
873 std::bit_cast<std::uint64_t>(
874 local[local_column * desc[8] + local_row]);
875 }
876 }
877 if (broadcast_result) {
878 MPI_Allreduce(MPI_IN_PLACE, bits.data(), m, MPI_UINT64_T,
879 MPI_BOR, gpr_comm_);
880 } else if (is_root()) {
881 MPI_Reduce(MPI_IN_PLACE, bits.data(), m, MPI_UINT64_T, MPI_BOR,
882 0, gpr_comm_);
883 } else {
884 MPI_Reduce(bits.data(), nullptr, m, MPI_UINT64_T, MPI_BOR, 0,
885 gpr_comm_);
886 return EigenMatrix();
887 }
888 for (int i = 0; i < m; ++i)
889 global(i, 0) =
890 std::bit_cast<double>(bits[static_cast<std::size_t>(i)]);
891 return global;
892 }
893 const int coordinates[2] = {row, column};
894 std::vector<int> owners(2 * nprocs_);
895 MPI_Gather(coordinates, 2, MPI_INT, owners.data(), 2, MPI_INT, 0,
896 gpr_comm_);
897 // Local rows ascend with global rows, so the owned rows of the block
898 // are the contiguous local range [local_first, local_first + count).
899 const int row_end = row0 + m;
900 const int local_first =
901 numroc_(&row0, &desc[4], &row, &desc[6], &grid_rows);
902 const int local_count =
903 numroc_(&row_end, &desc[4], &row, &desc[6], &grid_rows) -
904 local_first;
905 std::vector<std::vector<int>> global_rows;
906 if (is_root()) {
907 global_rows.resize(grid_rows);
908 for (int i = row0; i < row_end; ++i)
909 global_rows[(i / desc[4] + desc[6]) % grid_rows].push_back(
910 i - row0);
911 }
912 constexpr int transfer_elements = 1024 * 1024;
913 const int panel_columns =
914 std::max(1, transfer_elements / std::max(1, m));
915 std::vector<double> send, receive;
916 std::vector<int> counts(nprocs_), offsets(nprocs_);
917 std::vector<int> column_counts(grid_columns);
918 double dummy = 0.0;
919 for (int first = 0; first < n;) {
920 const int columns = std::min(panel_columns, n - first);
921 std::fill(column_counts.begin(), column_counts.end(), 0);
922 for (int j = col0 + first; j < col0 + first + columns; ++j)
923 ++column_counts[(j / desc[5] + desc[7]) % grid_columns];
924 const int send_count = local_count * column_counts[column];
925 send.resize(send_count);
926 int at = 0;
927 for (int j = col0 + first; j < col0 + first + columns; ++j) {
928 if ((j / desc[5] + desc[7]) % grid_columns != column) continue;
929 const int local_column =
930 (j / desc[5] / grid_columns) * desc[5] + j % desc[5];
931 if (local_count > 0) {
932 std::copy_n(
933 local +
934 static_cast<std::size_t>(local_column) * desc[8] +
935 local_first,
936 local_count, send.data() + at);
937 at += local_count;
938 }
939 }
940 if (is_root()) {
941 int offset = 0;
942 for (int rank = 0; rank < nprocs_; ++rank) {
943 counts[rank] =
944 static_cast<int>(global_rows[owners[2 * rank]].size()) *
945 column_counts[owners[2 * rank + 1]];
946 offsets[rank] = offset;
947 offset += counts[rank];
948 }
949 assert(offset == m * columns);
950 receive.resize(offset);
951 }
952 MPI_Gatherv(send.empty() ? &dummy : send.data(), send_count,
953 MPI_DOUBLE, receive.empty() ? &dummy : receive.data(),
954 counts.data(), offsets.data(), MPI_DOUBLE, 0,
955 gpr_comm_);
956 if (is_root()) {
957 for (int rank = 0; rank < nprocs_; ++rank) {
958 int cursor = offsets[rank];
959 const auto& rows = global_rows[owners[2 * rank]];
960 const int owner_column = owners[2 * rank + 1];
961 for (int j = first; j < first + columns; ++j) {
962 if (((col0 + j) / desc[5] + desc[7]) % grid_columns !=
963 owner_column)
964 continue;
965 for (const int i: rows)
966 global(i, j) = receive[cursor++];
967 }
968 }
969 }
970 if (broadcast_result)
971 MPI_Bcast(global.data() + static_cast<std::size_t>(first) * m,
972 m * columns, MPI_DOUBLE, 0, gpr_comm_);
973 first += columns;
974 }
975 if (!broadcast_result && !is_root()) {
976 global.resize(0, 0);
977 }
978 return global;
979 }
980
981 // Gather a distributed (m x 1) ScaLAPACK vector back to root using a
982 // scalar reduction on the replicated global vector. This is cheaper than
983 // a general matrix redistribution for the frequent training RHS solves.
984 // The local buffer may be null on ranks that own no vector entries.
985 Eigen::VectorXd gather_colvector_root(const double* local, const int* desc,
986 int m,
987 bool broadcast_result = true) const
988 {
989 (void)desc;
990 if (m < 0)
991 throw std::invalid_argument(
992 "distributed column-vector gather requires a nonnegative size");
993 if (m == 0) return Eigen::VectorXd();
994 if (nprocs_ == 1) {
995 if (!local)
996 throw std::invalid_argument(
997 "distributed column-vector gather requires a source "
998 "buffer");
999 Eigen::VectorXd global(m);
1000 for (int i = 0; i < m; ++i)
1001 global(i) = local[i];
1002 return global;
1003 }
1004
1005 const bool owns_entries =
1006 mycol_ == 0 && local_cols(1) > 0 && local_rows(m) > 0;
1007 int missing_source = owns_entries && !local ? 1 : 0;
1008 int any_missing_source = 0;
1009 MPI_Allreduce(&missing_source, &any_missing_source, 1, MPI_INT, MPI_MAX,
1010 gpr_comm_);
1011 if (any_missing_source)
1012 throw std::invalid_argument(
1013 "distributed column-vector gather requires source buffers on "
1014 "ranks that own vector entries");
1015
1016 Eigen::VectorXd local_full = Eigen::VectorXd::Zero(m);
1017 if (mycol_ == 0 && local_cols(1) > 0) {
1018 for (int i = 0; i < m; ++i) {
1019 const int owner_row = (i / mb_) % nprow_;
1020 if (owner_row != myrow_) continue;
1021 const int local_i =
1022 local_index_for_global(i, mb_, myrow_, nprow_);
1023 local_full(i) = local[static_cast<size_t>(local_i)];
1024 }
1025 }
1026
1027 // Every entry has one owner; all other contributions are positive
1028 // zero. The reduction preserves each finite value independently of
1029 // its tree and needs no root buffer proportional to the rank count.
1030 if (broadcast_result) {
1031 MPI_Allreduce(MPI_IN_PLACE, local_full.data(), m, MPI_DOUBLE,
1032 MPI_SUM, gpr_comm_);
1033 return local_full;
1034 }
1035 if (is_root()) {
1036 MPI_Reduce(MPI_IN_PLACE, local_full.data(), m, MPI_DOUBLE, MPI_SUM,
1037 0, gpr_comm_);
1038 return local_full;
1039 }
1040 MPI_Reduce(local_full.data(), nullptr, m, MPI_DOUBLE, MPI_SUM, 0,
1041 gpr_comm_);
1042 return Eigen::VectorXd();
1043 }
1044
1045 // Cache the distributed L buffer after cholesky() for reuse in solves.
1046 void cache_L(std::vector<double> L_dist, const int* desc, int n)
1047 {
1048 L_cache_ = std::move(L_dist);
1049 std::copy_n(desc, 9, L_desc_);
1050 L_n_ = n;
1051 has_L_ = true;
1052 L_generation_ = factorization_generation();
1053 L_owner_ = nullptr;
1054 has_inv_ = false;
1055 has_L_lin_ = false;
1056 has_U_ = false;
1057 }
1058
1059 void claim_cached_L(const void* owner) noexcept
1060 {
1061 if (L_current()) L_owner_ = owner;
1062 }
1063
1064 [[nodiscard]] bool cached_L_owned_by(const void* owner) const noexcept
1065 {
1066 return L_current() && owner != nullptr && L_owner_ == owner;
1067 }
1068
1069 [[nodiscard]] bool cached_L_is_unowned() const noexcept
1070 {
1071 return L_current() && L_owner_ == nullptr;
1072 }
1073
1074 [[nodiscard]] CholeskyFactorSnapshot take_cached_L(const void* owner)
1075 {
1076 CholeskyFactorSnapshot snapshot;
1077 if (!cached_L_owned_by(owner)) return snapshot;
1078 snapshot.values = std::move(L_cache_);
1079 std::copy_n(L_desc_, 9, snapshot.descriptor.begin());
1080 snapshot.order = L_n_;
1081 has_L_ = false;
1082 L_owner_ = nullptr;
1083 L_n_ = 0;
1084 has_inv_ = false;
1085 has_L_lin_ = false;
1086 has_U_ = false;
1087 return snapshot;
1088 }
1089
1090 bool restore_cached_L(CholeskyFactorSnapshot snapshot, const void* owner)
1091 {
1092 if (!snapshot.valid() || owner == nullptr) return false;
1093 cache_L(std::move(snapshot.values), snapshot.descriptor.data(),
1094 snapshot.order);
1095 L_owner_ = owner;
1096 return true;
1097 }
1098
1099 bool has_cached_L() const
1100 {
1101 return L_current();
1102 }
1103 const double* cached_L() const
1104 {
1105 return L_cache_.data();
1106 }
1108 {
1109 has_L_lin_ = false;
1110 // The caller may write the factor, so the transpose is stale.
1111 has_U_ = false;
1112 return L_cache_.data();
1113 }
1114 // Transpose of the cached factor in the tile layout of L, built on
1115 // first use after the factor changes and shared by every back
1116 // substitution until then.
1117 [[nodiscard]] bool has_cached_U() const noexcept
1118 {
1119 return L_current() && has_U_;
1120 }
1121 void cache_U(std::vector<double> U)
1122 {
1123 U_cache_ = std::move(U);
1124 has_U_ = true;
1125 }
1126 const double* cached_U() const
1127 {
1128 return U_cache_.data();
1129 }
1130 const int* cached_L_desc() const
1131 {
1132 return L_desc_;
1133 }
1134 int cached_n() const
1135 {
1136 return L_n_;
1137 }
1139 {
1140 has_L_ = false;
1141 has_U_ = false;
1142 has_L_lin_ = false;
1143 L_owner_ = nullptr;
1144 // Each buffer is a share of an n x n matrix; held after invalidation
1145 // it sits beside the next factorization's covariance and factor.
1146 release(L_cache_);
1147 release(U_cache_);
1148 release(L_lin_cache_);
1149 }
1150
1151 // Row-distributed (nprocs x 1) replica of the cached factor.
1152 void cache_L_lin(std::vector<double> L_dist, const int* desc, int n)
1153 {
1154 L_lin_cache_ = std::move(L_dist);
1155 std::copy_n(desc, 9, L_lin_desc_);
1156 L_lin_n_ = n;
1157 has_L_lin_ = true;
1158 L_lin_generation_ = factorization_generation();
1159 }
1160
1161 bool has_cached_L_lin() const
1162 {
1163 return has_L_lin_ && L_lin_generation_ == factorization_generation();
1164 }
1165 const double* cached_L_lin() const
1166 {
1167 return L_lin_cache_.data();
1168 }
1170 {
1171 return L_lin_cache_.data();
1172 }
1173 const int* cached_L_lin_desc() const
1174 {
1175 return L_lin_desc_;
1176 }
1177 int cached_lin_n() const
1178 {
1179 return L_lin_n_;
1180 }
1181
1182 void cache_inv(std::vector<double> inv_dist, const int* desc, int n)
1183 {
1184 ++inverse_builds_;
1185 Inv_cache_ = std::move(inv_dist);
1186 std::copy_n(desc, 9, Inv_desc_);
1187 Inv_n_ = n;
1188 has_inv_ = true;
1189 Inv_generation_ = factorization_generation();
1190 }
1191
1192 [[nodiscard]] std::size_t inverse_builds() const noexcept
1193 {
1194 return inverse_builds_;
1195 }
1196
1197 bool has_cached_inv() const
1198 {
1199 return has_inv_ && Inv_generation_ == factorization_generation();
1200 }
1201 const double* cached_inv() const
1202 {
1203 return Inv_cache_.data();
1204 }
1205 const int* cached_inv_desc() const
1206 {
1207 return Inv_desc_;
1208 }
1209 int cached_inv_n() const
1210 {
1211 return Inv_n_;
1212 }
1214 {
1215 has_inv_ = false;
1216 release(Inv_cache_);
1217 }
1218
1220 {
1221 has_inv_ = false;
1222 has_L_lin_ = false;
1223 release(Inv_cache_);
1224 release(L_lin_cache_);
1225 }
1226
1228 static void release(std::vector<double>& buffer) noexcept
1229 {
1230 std::vector<double>().swap(buffer);
1231 }
1232
1233 bool owns_global_entry(int global_row, int global_col) const
1234 {
1235 const int owner_row = (global_row / mb_) % nprow_;
1236 const int owner_col = (global_col / mb_) % npcol_;
1237 return owner_row == myrow_ && owner_col == mycol_;
1238 }
1239
1240 // Row owner on the nprocs x 1 grid. Every rank has column coordinate 0,
1241 // so a rank that owns the row owns every column of that row.
1242 bool owns_lin_entry(int global_row, int global_col) const
1243 {
1244 (void)global_col;
1245 return (global_row / mb_) % nprocs_ == lin_myrow_;
1246 }
1247
1252 const double* cached_inv_block(int global_row, int global_col,
1253 int& leading_dimension) const
1254 {
1255 assert(has_inv_);
1256 assert(owns_global_entry(global_row, global_col));
1257 const int local_i =
1258 local_index_for_global(global_row, mb_, myrow_, nprow_);
1259 const int local_j =
1260 local_index_for_global(global_col, mb_, mycol_, npcol_);
1261 leading_dimension = Inv_desc_[8];
1262 return Inv_cache_.data() + static_cast<size_t>(local_i) +
1263 static_cast<size_t>(local_j) * leading_dimension;
1264 }
1265
1266 double cached_inv_local_entry(int global_row, int global_col) const
1267 {
1268 assert(has_inv_);
1269 assert(owns_global_entry(global_row, global_col));
1270
1271 const int local_i =
1272 local_index_for_global(global_row, mb_, myrow_, nprow_);
1273 const int local_j =
1274 local_index_for_global(global_col, mb_, mycol_, npcol_);
1275 // The descriptor's leading dimension includes any storage padding.
1276 const int leading_dimension = Inv_desc_[8];
1277 return Inv_cache_[static_cast<size_t>(local_i) +
1278 static_cast<size_t>(local_j) * leading_dimension];
1279 }
1280
1281 // Accessors
1282 int context() const
1283 {
1284 return ictxt_;
1285 }
1286 int lin_context() const
1287 {
1288 return lin_ictxt_;
1289 }
1290 MPI_Comm world_comm() const
1291 {
1292 return gpr_comm_;
1293 }
1294 int lin_myrow() const
1295 {
1296 return lin_myrow_;
1297 }
1298 int lin_mycol() const
1299 {
1300 return lin_mycol_;
1301 }
1302 int nprocs() const
1303 {
1304 return nprocs_;
1305 }
1306 int myrank() const
1307 {
1308 return myrank_;
1309 }
1310 int myrow() const
1311 {
1312 return myrow_;
1313 }
1314 int mycol() const
1315 {
1316 return mycol_;
1317 }
1318 int nprow() const
1319 {
1320 return nprow_;
1321 }
1322 int npcol() const
1323 {
1324 return npcol_;
1325 }
1326 int block_size() const
1327 {
1328 return mb_;
1329 }
1330 bool is_root() const
1331 {
1332 return myrank_ == 0;
1333 }
1334
1339 MPI_Comm row;
1340 MPI_Comm col;
1341 const std::vector<int>& rank_of;
1342 };
1344 {
1345 const bool linear = context == lin_ictxt_;
1346 if (context >= 0 && context != ictxt_ && !linear)
1347 throw std::invalid_argument(
1348 "tile communicator needs an active grid");
1349 auto& row_comm = linear ? lin_tile_row_comm_ : tile_row_comm_;
1350 auto& col_comm = linear ? lin_tile_col_comm_ : tile_col_comm_;
1351 auto& rank_of = linear ? lin_tile_rank_of_ : tile_rank_of_;
1352 const int row = linear ? lin_myrow_ : myrow_;
1353 const int col = linear ? lin_mycol_ : mycol_;
1354 const int columns = linear ? 1 : npcol_;
1355 if (row_comm == MPI_COMM_NULL) {
1356 MPI_Comm_split(gpr_comm_, row, col, &row_comm);
1357 MPI_Comm_split(gpr_comm_, col, row, &col_comm);
1358 std::vector<int> coordinates(2 * static_cast<std::size_t>(nprocs_));
1359 const int mine[2] = {row, col};
1360 MPI_Allgather(mine, 2, MPI_INT, coordinates.data(), 2, MPI_INT,
1361 gpr_comm_);
1362 rank_of.assign(static_cast<std::size_t>(nprocs_), -1);
1363 for (int r = 0; r < nprocs_; ++r)
1364 rank_of[static_cast<std::size_t>(coordinates[2 * r]) * columns +
1365 coordinates[2 * r + 1]] = r;
1366 }
1367 return {row_comm, col_comm, rank_of};
1368 }
1369
1370private:
1371 DistributedState() = default;
1372
1375 static int node_cpu_share(MPI_Comm node)
1376 {
1377#ifdef __linux__
1378 cpu_set_t mine;
1379 CPU_ZERO(&mine);
1380 const int known = sched_getaffinity(0, sizeof(mine), &mine) == 0;
1381 int all_known = known;
1382 MPI_Allreduce(MPI_IN_PLACE, &all_known, 1, MPI_INT, MPI_MIN, node);
1383 int ranks = 1;
1384 MPI_Comm_size(node, &ranks);
1385 std::vector<cpu_set_t> masks(static_cast<std::size_t>(ranks));
1386 MPI_Allgather(&mine, static_cast<int>(sizeof(mine)), MPI_BYTE,
1387 masks.data(), static_cast<int>(sizeof(mine)), MPI_BYTE,
1388 node);
1389 if (!all_known || CPU_COUNT(&mine) <= 0) return 0;
1390 int sharers = 0;
1391 for (cpu_set_t& other: masks) {
1392 cpu_set_t common;
1393 CPU_AND(&common, &mine, &other);
1394 if (CPU_COUNT(&common) > 0) ++sharers;
1395 }
1396 return std::max(1, CPU_COUNT(&mine) / std::max(1, sharers));
1397#else
1398 (void)node;
1399 return 0;
1400#endif
1401 }
1402
1405 void descriptor_grid(const int* desc, int& rows, int& cols) const
1406 {
1407 int row = 0, col = 0;
1408 rows = cols = 0;
1409 if (initialized_) Cblacs_gridinfo(desc[1], &rows, &cols, &row, &col);
1410 if (rows <= 0 || cols <= 0) {
1411 rows = nprow_;
1412 cols = npcol_;
1413 }
1414 }
1415
1416 [[nodiscard]] bool L_current() const noexcept
1417 {
1418 return has_L_ && L_generation_ == factorization_generation();
1419 }
1420
1421 void release_grids() noexcept
1422 {
1423 if (tile_row_comm_ != MPI_COMM_NULL) MPI_Comm_free(&tile_row_comm_);
1424 if (tile_col_comm_ != MPI_COMM_NULL) MPI_Comm_free(&tile_col_comm_);
1425 if (lin_tile_row_comm_ != MPI_COMM_NULL)
1426 MPI_Comm_free(&lin_tile_row_comm_);
1427 if (lin_tile_col_comm_ != MPI_COMM_NULL)
1428 MPI_Comm_free(&lin_tile_col_comm_);
1429 tile_rank_of_.clear();
1430 lin_tile_rank_of_.clear();
1431 for (int* context: {&ictxt_, &lin_ictxt_, &col_ictxt_}) {
1432 if (*context >= 0) Cblacs_gridexit(*context);
1433 *context = -1;
1434 }
1435 if (system_handle_ >= 0) Cfree_blacs_system_handle(system_handle_);
1436 system_handle_ = -1;
1437 blacs_communication_.reset();
1438 }
1439 DistributedState(const DistributedState&) = delete;
1440 DistributedState& operator=(const DistributedState&) = delete;
1441
1442 int ictxt_ = -1;
1443 int nprow_ = 1, npcol_ = 1;
1444 int myrow_ = 0, mycol_ = 0;
1445 int nprocs_ = 1, myrank_ = 0;
1446 int node_ranks_ = 1;
1447 int cpu_share_ = 0;
1448 int mb_ = 64;
1449 int configured_block_size_ = 0;
1450 int configured_nprow_ = 0;
1451 bool computation_tile_ = false;
1452 bool initialized_ = false;
1453 bool owns_mpi_ = false;
1454 std::shared_ptr<const MpiCommunicator> communication_;
1455 std::unique_ptr<MpiCommunicator> blacs_communication_;
1456 int system_handle_ = -1;
1457 std::uint64_t grid_generation_ = 0;
1458
1459 // Linear (nprocs x 1) sub-context for row-distributed factorisations.
1460 int lin_ictxt_ = -1;
1461 int lin_myrow_ = 0;
1462 int lin_mycol_ = 0;
1463
1464 // Column-block (1 x nprocs) context for the mode-distributed HS-SVD design
1465 // build. Each rank owns a contiguous block of ceil(n/np) mode columns, so
1466 // the per-rank design build computes exactly its column slice; one
1467 // Cpdgemr2d redistributes into the block-cyclic compute grid before
1468 // pdgesvd. Distinct from lin_ictxt_ (nprocs x 1, row-distributed).
1469 int col_ictxt_ = -1;
1470 int col_myrow_ = 0;
1471 int col_mycol_ = 0;
1472
1473 std::vector<double> L_lin_cache_;
1474 int L_lin_desc_[9] = {};
1475 int L_lin_n_ = 0;
1476 bool has_L_lin_ = false;
1477 std::uint64_t L_lin_generation_ = 0;
1478
1479 // Pre-dup'd communicator reused for every collective.
1480 MPI_Comm gpr_comm_ = MPI_COMM_NULL;
1481
1482 // Row and column communicators of the grid (see tile_communicators()).
1483 MPI_Comm tile_row_comm_ = MPI_COMM_NULL;
1484 MPI_Comm tile_col_comm_ = MPI_COMM_NULL;
1485 std::vector<int> tile_rank_of_;
1486 MPI_Comm lin_tile_row_comm_ = MPI_COMM_NULL;
1487 MPI_Comm lin_tile_col_comm_ = MPI_COMM_NULL;
1488 std::vector<int> lin_tile_rank_of_;
1489
1490 // Cached Cholesky factor (distributed layout)
1491 std::vector<double> L_cache_;
1492 std::vector<double> U_cache_;
1493 bool has_U_ = false;
1494 int L_desc_[9] = {};
1495 int L_n_ = 0;
1496 bool has_L_ = false;
1497 std::uint64_t L_generation_ = 0;
1498 const void* L_owner_ = nullptr;
1499
1500 std::vector<double> Inv_cache_;
1501 int Inv_desc_[9] = {};
1502 int Inv_n_ = 0;
1503 bool has_inv_ = false;
1504 std::uint64_t Inv_generation_ = 0;
1505 std::size_t inverse_builds_ = 0;
1506
1507 // Cached BLACS descriptors keyed on (m, n). descinit_ depends only on
1508 // (m, n, mb_, ictxt_) which are stable between initialize()
1509 // reconfigurations, so a few-entry linear-search cache eliminates the
1510 // per-call descinit_ overhead for the small set of repeat shapes
1511 // (training NxN cov, Nx1 RHS, derivative NxN, etc.).
1512 struct DescCacheEntry {
1513 int m;
1514 int n;
1515 int desc[9];
1516 };
1517 mutable std::vector<DescCacheEntry> desc_cache_;
1518 mutable std::mutex desc_cache_mutex_;
1519};
1520
1531public:
1533 : active_(!st.reproducible() && configuredLinalgThreads() > 1),
1534 previous_(tileThreadCount().load())
1535 {
1536 if (!active_) return;
1539 }
1541 {
1542 if (!active_) return;
1543 setTileThreads(previous_);
1545 }
1548
1549private:
1550 bool active_;
1551 int previous_;
1552};
1553
1554} // namespace linalg
1555} // namespace gpr
1556
1557#endif // GPR_LINALG_DISTRIBUTEDSTATE_H_
Index range of LP64 ScaLAPACK, PBLAS and BLACS on a descriptor.
Runtime loader for ScaLAPACK / BLACS symbols (dlopen + dlsym).
void Cblacs_gridinfo(int a, int *b, int *c, int *d, int *e)
int numroc_(const int *n, const int *nb, const int *iproc, const int *isrcproc, const int *nprocs)
void Cpdgemr2d(int m, int n, const double *a, int ia, int ja, const int *desca, double *b, int ib, int jb, const int *descb, int ictxt)
int Csys2blacs_handle(MPI_Comm communicator)
void Cblacs_gridexit(int a)
void Cfree_blacs_system_handle(int handle)
void descinit_(int *desc, const int *m, const int *n, const int *mb, const int *nb, const int *irsrc, const int *icsrc, const int *ictxt, const int *lld, int *info)
void Cblacs_gridinit(int *a, const char *b, int c, int d)
bool restore_cached_L(CholeskyFactorSnapshot snapshot, const void *owner)
void scatter_by_panels(const double *global, int m, int n, const int *desc, double *local, int row, int col, int nprow, int npcol) const
std::uint64_t grid_generation() const noexcept
void make_col_desc(int m, int n, int *desc) const
static void release(std::vector< double > &buffer) noexcept
Returns the storage of buffer to the allocator.
bool exceeds_lp64(const int *desc) const
void configure(int block_size, int nprow, bool computation_tile=false) noexcept
const int * cached_inv_desc() const
static int recommended_block_size(int requested_block, int nprocs)
int effective_configured_block_size() const noexcept
int global_index_for_local(int local_index, int block_size, int proc_coord, int nprocs_dim) const
const std::shared_ptr< const MpiCommunicator > & communication() const noexcept
void make_lin_desc(int m, int n, int *desc) 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
static constexpr DistributedBackendKind compiled_backend() noexcept
int configured_block_size() const noexcept
EigenMatrix gather(const double *local, const int *desc, int m, int n, bool broadcast_result=true) const
std::vector< double > scatter_lin(const EigenMatrix &global, int m, int n, int *desc) const
const double * cached_inv() const
static int recommended_nprow(int nprocs, int block_size)
void require_lp64(const int *desc, const char *routine) const
std::vector< double > scatter_colvector_root(const Eigen::VectorXd &global, int m, int *desc) const
void make_desc(int m, int n, int *desc) 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_inv_block(int global_row, int global_col, int &leading_dimension) const
bool owns_global_entry(int global_row, int global_col) const
std::vector< double > scatter_lin_colvector_root(const Eigen::VectorXd &global, int m, int *desc) const
const char * backend_name() const noexcept
Eigen::VectorXd gather_colvector_root(const double *local, const int *desc, int m, bool broadcast_result=true) const
EigenMatrix gather_block(const double *local, const int *desc, int row0, int col0, int m, int n, bool broadcast_result=true) const
DistributedBackendKind backend_kind() const noexcept
TileCommunicators tile_communicators(int context=-1)
void cache_L_lin(std::vector< double > L_dist, const int *desc, int n)
DistributedState(std::shared_ptr< const MpiCommunicator > communication)
bool cached_L_owned_by(const void *owner) const noexcept
Eigen::VectorXd gather_lin_colvector_root(const double *local, const int *desc, int m) const
double cached_inv_local_entry(int global_row, int global_col) const
bool cached_L_is_unowned() const noexcept
const double * cached_U() const
std::vector< double > scatter(const EigenMatrix &global, int m, int n, int *desc) const
static DistributedState & instance()
void claim_cached_L(const void *owner) noexcept
const int * cached_L_lin_desc() const
bool reproducible() const noexcept
void set_factorization(DistributedFactorization mode)
bool has_cached_U() const noexcept
std::vector< double > alloc_local(int m, int n, int *desc) const
std::size_t inverse_builds() const noexcept
DistributedFactorization factorization() const noexcept
void cache_inv(std::vector< double > inv_dist, const int *desc, int n)
int node_ranks() const noexcept
Ranks of this process group on this node (one before initialize).
bool owns_lin_entry(int global_row, int global_col) const
void initialize(int block_size=0, int nprow=0)
static std::uint64_t factorization_generation() noexcept
CholeskyFactorSnapshot take_cached_L(const void *owner)
const double * cached_L() const
void col_block_range(int n, int &start, int &count) const
int configured_nprow() const noexcept
const double * cached_L_lin() const
ScopedTileKernelThreads(const DistributedState &st)
ScopedTileKernelThreads & operator=(const ScopedTileKernelThreads &)=delete
ScopedTileKernelThreads(const ScopedTileKernelThreads &)=delete
Dense and structured linear algebra behind the GP: Cholesky and eigen solvers, linear operators,...
void setTileThreads(int threads) noexcept
Sets the tile thread count (at least one).
std::uint64_t distributedFactorizationGeneration() noexcept
std::int64_t lp64IndexLimit() noexcept
Definition Lp64Limits.h:120
constexpr const char * distributed_backend_name(DistributedBackendKind backend) noexcept
void configureProductThreads(int threads)
constexpr std::int64_t largestLocalEntries(std::int64_t m, std::int64_t n, std::int64_t mb, std::int64_t nb, std::int64_t rsrc, std::int64_t csrc, std::int64_t nprow, std::int64_t npcol) noexcept
Definition Lp64Limits.h:84
constexpr DistributedBackendKind compiled_distributed_backend() noexcept
bool exceedsLp64(const int *desc, int nprow, int npcol) noexcept
Definition Lp64Limits.h:151
DistributedFactorization distributedFactorization() noexcept
Process-wide selection; Reproducible unless configured otherwise.
int configuredLinalgThreads() noexcept
Requested dense numerical budget, independent of nested BLAS controls.
void configureDistributedFactorization(DistributedFactorization mode)
std::atomic< int > & tileThreadCount() noexcept
Number of threads one rank devotes to independent tile products.
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
STL namespace.
const std::vector< int > & rank_of
indexed by row * npcol + col