Loading...
Searching...
No Matches
gpr::linalg Namespace Reference

Dense and structured linear algebra behind the GP: Cholesky and eigen solvers, linear operators, backend selection. More...

Namespaces

namespace  backend
namespace  canonical
namespace  cutlass
namespace  fixed
namespace  kokkos_joint
namespace  linop
namespace  portable_tiles
namespace  schemeii

Classes

class  BackendContext
struct  BackendTraits
struct  BackendTraits< backend::CholmodTag >
struct  BackendTraits< backend::CusolverTag >
struct  BackendTraits< backend::EigenTag >
struct  BackendTraits< backend::KokkosTag >
struct  BackendTraits< backend::ScalapackTag >
struct  BackendTraits< backend::SlateTag >
struct  BackendTraits< backend::StdParTag >
class  CholeskyPanels
struct  CompensatedSum
struct  ConstTileView
class  CovarianceEquilibration
class  CusolverEighLib
class  CusolverInverse
class  DenseLLTInverse
class  DistributedKernelProvider
struct  DistributedShape
class  DistributedState
class  EnvironmentGpuExecutor
struct  ExactProductAccumulator
class  ExactSum
class  KernelInverse
class  KernelWall
class  KokkosFactor
class  KokkosMolecularPosterior
struct  KokkosMolecularStats
struct  KokkosTransferAuditStats
struct  KokkosTransferDirectionStats
struct  KokkosTransferStats
class  KokkosWorkspace
class  LocalExecutor
class  MpiCommunicator
struct  MpiContext
struct  PCGResult
struct  PCGSettings
class  PredictProduct
class  ProbeExecutor
struct  ProviderTraits
 Description of a distributed kernel provider. More...
struct  RayleighRitzOptions
struct  RayleighRitzResult
class  ScalapackLib
struct  SchemeIIIntegers
struct  SchemeIIWide
struct  SchemeISlices
class  ScopedLp64IndexLimit
 Lowers the routing limit for the lifetime of the object (tests only). More...
class  ScopedSerialEigenThreads
class  ScopedSolveThreads
class  ScopedTileKernelThreads
class  StableVarianceError
 Raised when a stable posterior variance is not finite, is materially negative, or its operands do not match. More...
struct  StoredProduct
struct  ThreadBudget
class  TileBackground
class  TileCholesky
class  TilePool
struct  TileView
class  TwoStageEigenLib

Concepts

concept  LocalDenseBackend

Typedefs

using ActiveBackend = backend::EigenTag
using ActiveBackendTraits = BackendTraits<ActiveBackend>
using AvailableMemory = std::optional<std::int64_t>
using MpiCommType = int
using ScalapackState = DistributedState
using ConstProductMatrix
using ProductMatrix = Eigen::Ref<Eigen::MatrixXd, 0, Eigen::OuterStride<>>

Enumerations

enum class  MemoryKind { Host , CudaDevice , HipDevice , SyclDevice }
enum class  ExecutionKind {
  Serial , HostThreads , Cuda , Hip ,
  Sycl
}
 Which units run the operation. More...
enum class  ArithmeticClass { Unconstrained , GridInvariant , SerialEqual }
enum class  ProductMode { Compensated , SchemeI , SchemeII , KernelFloat }
enum class  DistributedBackendKind { None , Scalapack , Slate }
enum class  DistributedFactorization { Reproducible , Library }
enum  Lp64DescriptorField : int {
  kDescM = 2 , kDescN = 3 , kDescMb = 4 , kDescNb = 5 ,
  kDescRsrc = 6 , kDescCsrc = 7 , kDescLld = 8
}
 Offsets of the ScaLAPACK array descriptor fields (DTYPE_ .. LLD_ - 1). More...

Functions

bool arrowheadEigenRankOne (const Eigen::VectorXd &d_in, const Eigen::VectorXd &z_in, double alpha, Eigen::VectorXd &evals_asc, Eigen::MatrixXd &evecs)
bool arrowheadEigen (const Eigen::VectorXd &d, const Eigen::MatrixXd &B, const Eigen::MatrixXd &A, Eigen::VectorXd &evals_asc, Eigen::MatrixXd &evecs)
bool cholesky (const EigenMatrix &C, EigenMatrix &L)
 Cholesky decomposition (LAPACK equivalent: dpotrf).
Eigen::VectorXd forward_solve (const EigenMatrix &L, const Eigen::VectorXd &b)
 Forward triangular solve with vector RHS (BLAS equivalent: dtrsv).
Eigen::VectorXd back_solve (const EigenMatrix &L, const Eigen::VectorXd &b)
 Back triangular solve with vector RHS (BLAS equivalent: dtrsv).
EigenMatrix forward_solve_mat (const EigenMatrix &L, const EigenMatrix &B)
 Forward triangular solve with matrix RHS (BLAS equivalent: dtrsm).
EigenMatrix back_solve_mat (const EigenMatrix &L, const EigenMatrix &B)
 Back triangular solve with matrix RHS (BLAS equivalent: dtrsm with side=L, uplo=L, trans=T).
Eigen::VectorXd forward_solve_mat_colwise_squared_norm (const EigenMatrix &L, const EigenMatrix &B)
 Forward triangular solve followed by columnwise squared norms.
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).
double trace_product (const EigenMatrix &A, const EigenMatrix &B)
 Frobenius inner product / trace of matrix product.
double log_det_cholesky (const EigenMatrix &L)
 Half log-determinant from Cholesky factor.
constexpr bool hostAccessible (MemoryKind kind) noexcept
constexpr const char * memoryKindName (MemoryKind kind) noexcept
constexpr const char * executionKindName (ExecutionKind kind) noexcept
constexpr const char * arithmeticClassName (ArithmeticClass cls) noexcept
constexpr bool satisfies (ArithmeticClass provided, ArithmeticClass required) noexcept
 True when a provider of class provided meets the class required.
double symmetricBackwardError (Eigen::Index n, double scale) noexcept
bool curvatureIsNegative (double lambda, double scale, Eigen::Index n) noexcept
void canonicalizeEigenvectorSign (Eigen::Ref< Eigen::VectorXd > vector, double tolerance) noexcept
bool signedEigenvectorLess (const Eigen::Ref< const Eigen::VectorXd > &left, const Eigen::Ref< const Eigen::VectorXd > &right)
void canonicalizeEigenpairs (Eigen::Ref< Eigen::VectorXd > evals, Eigen::Ref< Eigen::MatrixXd > evecs)
 evals has one entry per leading column of evecs. Both are rewritten.
Eigen::Index resolvedSingularRank (const Eigen::VectorXd &singular, double cutoff)
double twoSumResidual (double a, double b, double rounded)
bool tryCertifiedProduct (const double *left, const double *right, int length, double &result)
bool rank_one_update_lower (EigenMatrix &lower, const Eigen::VectorXd &vector)
bool cholesky_rank_update (EigenMatrix &lower, const Eigen::VectorXd &vector)
 Update the selected backend's live Cholesky factor in its existing layout.
template<class Matrices, class Body>
void assembleCollectively (const MpiContext &context, Matrices &result, const Body &body)
ProductMode productMode ()
bool kernelFloatProductAvailable ()
bool selectPredictProduct (const char *value)
double evaluateStoredProduct (const double *left, const double *right, int length, ProductMode mode)
void contractPredictionMatrix (const double *column_major, int rows, int cols, const double *coefficients, double *output, ProductMode mode)
void evaluateStoredProducts (const StoredProduct *products, int count, ProductMode mode, double *values)
double trace_solve_product (const EigenMatrix &L, const EigenMatrix &A)
double dense_factor_inverse_trace (const EigenMatrix &L)
constexpr DistributedBackendKind compiled_distributed_backend () noexcept
constexpr const char * distributed_backend_name (DistributedBackendKind backend) noexcept
void configureEnvironmentGpu (const std::string &library)
std::shared_ptr< const EnvironmentGpuExecutor > configuredEnvironmentGpu ()
void configureStablePosteriorVariance (bool enabled) noexcept
 Turn stable posterior variance reductions on or off for the process.
bool stablePosteriorVarianceEnabled () noexcept
 Whether stable posterior variance reductions are enabled.
bool acceptStablePosteriorVariance (double &variance, double signal_variance, double relative_allowance) noexcept
 Accept one stable posterior variance.
bool acceptStablePosteriorVariance (double &variance, double signal_variance) noexcept
 acceptStablePosteriorVariance with the compensated-sum allowance.
bool acceptStablePosteriorVariance (Eigen::VectorXd &variance, const Eigen::VectorXd &signal) noexcept
 Accept every entry of a stable posterior variance vector.
void requireStablePosteriorVariance (double &variance, double signal_variance, double relative_allowance)
 Accept one stable posterior variance or throw.
void requireStablePosteriorVariance (double &variance, double signal_variance)
void requireStablePosteriorVariance (Eigen::VectorXd &variance, const Eigen::VectorXd &signal)
 Accept every entry of a stable posterior variance vector or throw.
template<typename RelativeError>
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.
template<typename Solve, typename SolveTranspose>
double estimateLowerInverseNorm1 (Eigen::Index order, Solve &&solve, SolveTranspose &&solve_transpose)
 Estimate of ||L^-1||_1 for a lower triangular L (Hager, with Higham's alternating-sign probe).
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 solve.
double upperInverseNorm1FromComputed (double computed_norm, Eigen::Index order) noexcept
 Upper bound on ||L^-1||_1 from a computed inverse's 1-norm.
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.
template<typename Derived>
double upperInverseNorm1 (const Eigen::MatrixBase< Derived > &factor)
 Upper bound on ||L^-1||_1 for an explicit lower-triangular factor.
template<typename Derived>
double denseCholeskySchurRelativeError (const Eigen::MatrixBase< Derived > &factor)
 choleskySchurRelativeError of a dense lower Cholesky factor.
template<typename Backend, typename Derived>
double subsetFactorSchurRelativeError (Backend &backend, const Eigen::MatrixBase< Derived > &factor, int order)
template<typename Derived, typename RelativeError>
Eigen::VectorXd borderedCholeskyDiagonalWith (const Eigen::VectorXd &prior, const Eigen::MatrixBase< Derived > &whitened, RelativeError &&relative_error)
 Squared final pivots of bordered Cholesky factorizations.
template<typename Derived>
Eigen::VectorXd borderedCholeskyDiagonal (const Eigen::VectorXd &prior, const Eigen::MatrixBase< Derived > &whitened)
 borderedCholeskyDiagonal for a whitened block L^-1 K_tq with no factor in hand: the allowance is the rounding of the compensated sum alone.
template<typename Derived, typename FactorDerived>
Eigen::VectorXd borderedCholeskyDiagonal (const Eigen::VectorXd &prior, const Eigen::MatrixBase< Derived > &whitened, const Eigen::MatrixBase< FactorDerived > &factor)
 borderedCholeskyDiagonal for W = L^-1 K_tq solved with the dense lower factor factor; the allowance is choleskySchurRelativeError of that factor.
template<typename PriorDerived, typename WeightDerived, typename SolvedDerived, typename RelativeError>
double borderedCholeskyActionVarianceWith (const Eigen::MatrixBase< PriorDerived > &prior, const Eigen::MatrixBase< WeightDerived > &weights, const Eigen::MatrixBase< SolvedDerived > &whitened_action, RelativeError &&relative_error)
 Variance of a linear query action from its bordered Cholesky solve.
template<typename PriorDerived, typename WeightDerived, typename SolvedDerived>
double borderedCholeskyActionVariance (const Eigen::MatrixBase< PriorDerived > &prior, const Eigen::MatrixBase< WeightDerived > &weights, const Eigen::MatrixBase< SolvedDerived > &whitened_action)
 borderedCholeskyActionVariance with the compensated-sum allowance.
template<typename PriorDerived, typename WeightDerived, typename SolvedDerived, typename FactorDerived>
double borderedCholeskyActionVariance (const Eigen::MatrixBase< PriorDerived > &prior, const Eigen::MatrixBase< WeightDerived > &weights, const Eigen::MatrixBase< SolvedDerived > &whitened_action, const Eigen::MatrixBase< FactorDerived > &factor)
 borderedCholeskyActionVariance for L^-1 K_tq w solved with the dense lower factor factor, with the allowance of choleskySchurRelativeError.
double pcg_dot (const Eigen::VectorXd &a, const Eigen::VectorXd &b)
PCGResult preconditioned_cg (const std::function< Eigen::VectorXd(const Eigen::VectorXd &)> &apply_A, const std::function< Eigen::VectorXd(const Eigen::VectorXd &)> &apply_M_inv, const Eigen::VectorXd &b, const PCGSettings &settings={})
void resetKokkosTransferAuditStats () noexcept
KokkosTransferAuditStats kokkosTransferAuditStats () noexcept
bool kokkosHostExecutionMemory () noexcept
DistributedFactorization distributedFactorization () noexcept
 Process-wide selection; Reproducible unless configured otherwise.
std::uint64_t distributedFactorizationGeneration () noexcept
void configureDistributedFactorization (DistributedFactorization mode)
const char * distributedFactorizationName (DistributedFactorization mode) noexcept
std::optional< DistributedFactorization > parseDistributedFactorization (std::string_view name) noexcept
 "reproducible" or "library"; anything else gives no value.
int configuredLinalgThreads () noexcept
 Requested dense numerical budget, independent of nested BLAS controls.
void configureLinalgThreads (int threads)
void configureProductThreads (int threads)
void configureLibrarySerialKernels (bool enabled) noexcept
bool librarySerialKernels () noexcept
void configureUnconstrainedLibraryReductions (bool enabled) noexcept
bool unconstrainedLibraryReductions () noexcept
void configureTileThreads (int threads)
int affinityCpuCount () noexcept
 CPUs in this process's scheduling affinity, or 0 when unknown.
int blasThreadCount () noexcept
bool teamPanelKernels () noexcept
void configureKernelThreads (int threads)
void refreshKernelTeam ()
constexpr std::int64_t blockCyclicLocalExtent (std::int64_t n, std::int64_t nb, std::int64_t iproc, std::int64_t isrc, std::int64_t nprocs) noexcept
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
constexpr std::int64_t largestLocalEntries (const int *desc, int nprow, int npcol) noexcept
std::atomic< std::int64_t > & lp64IndexLimitStore () noexcept
std::int64_t lp64IndexLimit () noexcept
bool exceedsLp64 (const int *desc, int nprow, int npcol) noexcept
bool exceedsLp64 (std::int64_t count) noexcept
 True when an element count or workspace size does not fit LP64 INTEGER.
AvailableMemory availableHostBudget ()
std::int64_t availableHostBytes ()
constexpr bool fitsRankShare (std::int64_t needed, AvailableMemory available, int node_ranks) noexcept
constexpr bool fitsRankShare (std::int64_t needed, std::int64_t available, int node_ranks) noexcept
void requireRankShare (const char *what, std::int64_t needed, AvailableMemory available, int node_ranks)
void requireRankShare (const char *what, std::int64_t needed, std::int64_t available, int node_ranks)
void replicate_owned_values (double *data, std::size_t count, const MpiContext &context)
void disjoint_sum_bcast (double *data, int count, const MpiContext &context)
void ordered_sum_bcast (double *data, int count, const MpiContext &context)
void compensated_sum_bcast (CompensatedSum *data, int count, const MpiContext &context)
void exact_sum_bcast (ExactSum *sums, int count, const MpiContext &context)
int schemeISliceBits (Eigen::Index length)
SchemeISlices splitSchemeI (const Eigen::Ref< const Eigen::VectorXd > &values)
double accumulateSchemeI (const SchemeISlices &left, const SchemeISlices &right)
 Sum the exact slice products. The split and this accumulation are separate.
double scheme_i_trunc (double value)
int scheme_i_slice_bits (int length)
int scheme_i_split (const double *values, int length, int bits, double *slices, int cap)
int scheme_i_slice_cap (const double *values, int length, int bits)
double schemeIProductRaw (const double *left, const double *right, int length)
 Scheme I product of two length-n factors in term order.
template<typename Left, typename Right>
double schemeIProduct (const Eigen::MatrixBase< Left > &left, const Eigen::MatrixBase< Right > &right)
constexpr uint32_t schemeIIModulus (int index)
const uint32_t * schemeIIModuli ()
bool scaleSchemeII (const double *left, const double *right, int length, SchemeIIIntegers *scaled)
uint32_t modularProductSchemeII (const SchemeIIIntegers &scaled, uint32_t modulus)
bool takeSchemeIIWindow (const SchemeIIIntegers &scaled, char *consumed, SchemeIIIntegers *window)
SchemeIIWide crtSchemeII (const uint32_t *residues)
double unscaleSchemeII (const SchemeIIWide &coefficient, int exponent)
double schemeIIProductRaw (const double *left, const double *right, int length)
bool jacobiDavidsonCorrection (const Eigen::MatrixXd &A, const double theta, const Eigen::VectorXd &residual, const Eigen::VectorXd &ritz_vector, Eigen::VectorXd &correction, double *alpha=nullptr)
template<class Apply>
RayleighRitzResult lowestEigenpairRayleighRitz (const Eigen::Index dimension, Apply &&apply, const Eigen::VectorXd &seed, RayleighRitzOptions options)
void requireRebuildableDenseL (const EigenMatrix &L, int m, const char *fn, DistributedState &st=DistributedState::instance())
void ordered_sum_bcast (double *data, int count, DistributedState &st=DistributedState::instance())
void exact_sum_bcast (ExactSum *sums, int count, DistributedState &st=DistributedState::instance())
void disjoint_sum_bcast (double *data, int count, DistributedState &st=DistributedState::instance())
bool distributed_gemm_nn (const EigenMatrix &A, const EigenMatrix &B, EigenMatrix &C, DistributedState &st=DistributedState::instance())
int lp64Workspace (double query, const char *routine, const DistributedState &st)
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())
void transformDistributedLower (std::vector< double > &buffer, const int *desc, int n, const CovarianceEquilibration &scaling, bool restore_factor, DistributedState &st)
bool equilibrateDistributedLower (std::vector< double > &buffer, const int *desc, int n, CovarianceEquilibration &scaling, DistributedState &st)
bool cholesky (const EigenMatrix &C, 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())
EigenMatrix forward_solve_mat (const EigenMatrix &L, const EigenMatrix &B, DistributedState &st=DistributedState::instance())
bool distributed_thin_svd (const EigenMatrix &A, EigenMatrix &U, Eigen::VectorXd &S, EigenMatrix &V, DistributedState &st=DistributedState::instance())
bool distributed_symmetric_eigen (const EigenMatrix &A, Eigen::VectorXd &eigenvalues, EigenMatrix &eigenvectors, const char **driver_name=nullptr, DistributedState &st=DistributedState::instance())
bool distributed_thin_svd_colblock (const EigenMatrix &A_local, int m, int n, EigenMatrix &U, Eigen::VectorXd &S, EigenMatrix &V, DistributedState &st=DistributedState::instance())
bool distributed_thin_svd_tsqr (const EigenMatrix &A_local, int nobs, int N, EigenMatrix &U, Eigen::VectorXd &S, EigenMatrix &V, DistributedState &st=DistributedState::instance())
EigenMatrix back_solve_mat (const EigenMatrix &L, const EigenMatrix &B, DistributedState &st=DistributedState::instance())
Eigen::VectorXd columnSquaredNormsExact (const std::vector< double > &buf, const int *desc, int m, int ncols, DistributedState &st)
Eigen::VectorXd columnSchurComplementsExact (const std::vector< double > &buf, const int *desc, int m, int ncols, const Eigen::VectorXd &prior, DistributedState &st)
Eigen::VectorXd forward_solve_mat_colwise_squared_norm (const EigenMatrix &L, const EigenMatrix &B, DistributedState &st=DistributedState::instance())
double cachedFactorSchurRelativeError (int m, DistributedState &st=DistributedState::instance())
void requireCachedFactorSchurDiagonal (Eigen::VectorXd &diagonal, const Eigen::VectorXd &prior, int m, DistributedState &st)
Eigen::VectorXd bordered_cholesky_diagonal (const EigenMatrix &L, const EigenMatrix &B, const Eigen::VectorXd &prior, DistributedState &st=DistributedState::instance())
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)
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())
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 cholesky_inverse_diagonal_distributed (const EigenMatrix &L, int order, DistributedState &st=DistributedState::instance())
Eigen::VectorXd forward_solve (const EigenMatrix &L, const Eigen::VectorXd &b, DistributedState &st=DistributedState::instance())
Eigen::VectorXd back_solve (const EigenMatrix &L, const Eigen::VectorXd &b, DistributedState &st=DistributedState::instance())
double trace_cholesky_solve_scalapack (const EigenMatrix &L, const EigenMatrix &B, DistributedState &st=DistributedState::instance())
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 trace_cholesky_solve_scalapack_distributed (const EigenMatrix &L, const double *B_dist, const int *desc_b, int m, int ncols, DistributedState &st=DistributedState::instance())
bool factor_inverse_lower (const EigenMatrix &L, int n, std::vector< double > &inverse, int *desc, DistributedState &st)
template<class Entry>
ExactSum trace_lower_symmetric_local (const double *A, int lda, int n, Entry &&b, DistributedState &st)
double trace_inverse_times_symmetric (const EigenMatrix &L, const EigenMatrix *B, int n, DistributedState &st=DistributedState::instance())
EigenMatrix cholesky_inverse (const EigenMatrix &L, DistributedState &st=DistributedState::instance())
void cache_cholesky_inverse (const EigenMatrix &L, DistributedState &st=DistributedState::instance())
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)
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())
double trace_cached_inverse_times_symmetric_distributed (const double *B_dist, const int *desc_b, int n, DistributedState &st=DistributedState::instance())
EigenMatrix cholesky_inverse_root (const EigenMatrix &L, DistributedState &st=DistributedState::instance())
double trace_product (const EigenMatrix &A, const EigenMatrix &B, DistributedState &st=DistributedState::instance())
double log_det_cholesky (const EigenMatrix &L, DistributedState &st=DistributedState::instance())
bool teamDivideConquerEigen (const Eigen::MatrixXd &sym, Eigen::VectorXd &evals, Eigen::MatrixXd &evecs)
bool covarianceDsyevr (const Eigen::MatrixXd &sym, Eigen::VectorXd &evals, Eigen::MatrixXd &evecs)
std::int64_t teamPanelWidth ()
bool teamPanelBitsIndependent ()
double teamSolveWallSeconds ()
void teamSolveWallReset ()
void teamAddSolveWall (double seconds)
double teamFactorWallSeconds ()
void teamFactorWallReset ()
bool teamParallelPays (double flops)
bool teamCholeskyLower (double *lower, std::int64_t lda, std::int64_t n)
void teamSolveLower (const double *lower, std::int64_t lda, bool lower_factor, double *rhs, std::int64_t ldb, std::int64_t n, std::int64_t cols)
void teamSolveLowerVector (const double *lower, std::int64_t lda, bool lower_factor, double *rhs, std::int64_t n)
void teamSymmetricGram (const double *b, std::int64_t ldb, double *c, std::int64_t ldc, std::int64_t n)
bool teamCholeskyLower (Eigen::Ref< Eigen::MatrixXd > lower)
void teamSolveLower (const Eigen::Ref< const Eigen::MatrixXd > &lower, bool lower_factor, Eigen::Ref< Eigen::MatrixXd > rhs)
void teamSolveLowerVector (const Eigen::Ref< const Eigen::MatrixXd > &lower, bool lower_factor, Eigen::Ref< Eigen::VectorXd > rhs)
std::atomic< int > & tileThreadCount () noexcept
 Number of threads one rank devotes to independent tile products.
void setTileThreads (int threads) noexcept
 Sets the tile thread count (at least one).
template<class F>
void parallelFor (long count, F &&fn)
 parallelFor(count, fn): see TilePool::run.
bool trainingCholeskySelected (Eigen::Index order)
bool trainingCholeskyDistributedSelected (Eigen::Index order)
bool trainingCholeskyLower (ProductMatrix lower)
std::shared_ptr< const schemeii::Context > schemeIIContext ()
void configureTrainingProductLibrary (const std::string &library)
bool trainingProductConfigured ()
 A device library or an in-process engine is configured.
bool trainingProductLibraryLoaded ()
 A device library (not an in-process engine) is configured.
bool tryTrainingProduct (ConstProductMatrix a, ConstProductMatrix b, ProductMatrix c, bool transpose_a, bool transpose_b, double alpha, double beta, bool partitioned)
Eigen::MatrixXd trainingProduct (ConstProductMatrix a, ConstProductMatrix b, bool transpose_a=false, bool transpose_b=false)
 Allocating form with a native Eigen product when no device product runs.

Variables

constexpr const char * kPredictSumOption
constexpr const char * kPredictSumHelp
std::atomic_bool stable_posterior_variance {false}
 Process-wide switch for stable posterior variance reductions. Off by default; set through configureStablePosteriorVariance.
constexpr int kStablePosteriorVarianceRoundoffUlps = 4
 Ulps of the signal variance that a compensated posterior variance may sit below zero.
constexpr std::int64_t kLp64IndexLimit
 Largest element offset an LP64 ScaLAPACK routine forms without overflow.
constexpr MpiCommType kMpiCommNull = 0
constexpr int kSchemeIIModulusCount = 8
constexpr int kSchemeIIMaxShift = 120
constexpr Eigen::Index kMinDistributedGemmOrder = 512
constexpr Eigen::Index kMinDistributedSymmetricEigenOrder = 1

Detailed Description

Dense and structured linear algebra behind the GP: Cholesky and eigen solvers, linear operators, backend selection.

Two-stage symmetric eigensolver: full -> banded -> eigenpairs.

One-stage reduction (LAPACK dsytrd, reached through dsyevr) spends its time in dsymv, a matrix-VECTOR product. That is bandwidth-bound, and a live profile of a Baker cell put dsymv at 56% of the run once MPI wait was removed. The two-stage form exists to replace it: reducing to a BAND first can be done with matrix-MATRIX products, which are not bandwidth-bound.

Only stage one is written here. LAPACK already ships the rest and, unlike its *_2stage drivers, dsbevd supports JOBZ='V', so the band eigenproblem and its eigenvectors come from the library:

stage 1 full -> band, blocked Householder (this file, BLAS3) stage 2 band -> eigenpairs (dsbevd) stage 3 back-transform Z through stage 1 (dlarfb, BLAS3)

The trailing update applies the block reflector from both sides rather than using the symmetric dsyr2k form. That costs about twice the flops of the symmetry-exploiting update, and is still the right trade here because the point is to leave BLAS2 behind. The result is symmetrized explicitly, since applying the two sides separately leaves asymmetry at roundoff.

The reflector block is built with dlarft and applied with dlarfb directly, not through dormqr. dormqr takes its blocked path only when ILAENV's block size is strictly smaller than the number of reflectors k; a panel k chosen to equal that block size sends every update to the unblocked dorm2r, which applies reflectors one at a time through dger. Calling dlarfb makes the panel width a property of this file rather than of a tuning table that can be equal to it.

Typedef Documentation

◆ ActiveBackend

Definition at line 211 of file Backend.h.

◆ ActiveBackendTraits

◆ AvailableMemory

using gpr::linalg::AvailableMemory = std::optional<std::int64_t>

Definition at line 35 of file MemoryBudget.h.

◆ ConstProductMatrix

Initial value:
Eigen::Ref<const Eigen::MatrixXd, 0, Eigen::OuterStride<>>

Definition at line 15 of file TrainingProduct.h.

◆ MpiCommType

Definition at line 55 of file MpiContext.h.

◆ ProductMatrix

using gpr::linalg::ProductMatrix = Eigen::Ref<Eigen::MatrixXd, 0, Eigen::OuterStride<>>

Definition at line 17 of file TrainingProduct.h.

◆ ScalapackState

Definition at line 13 of file ScalapackState.h.

Enumeration Type Documentation

◆ ArithmeticClass

enum class gpr::linalg::ArithmeticClass
strong

What a provider promises about the bits of its results.

SerialEqual: every result equals the serial Eigen result bit for bit, at any thread count and rank count. GridInvariant: the result is the same at every rank count and process grid, but need not equal serial Eigen. Unconstrained: neither; results can differ with the grid, the thread count and the library version. SerialEqual implies GridInvariant.

Enumerator
Unconstrained 
GridInvariant 
SerialEqual 

Definition at line 112 of file BackendInterface.h.

◆ DistributedBackendKind

◆ DistributedFactorization

How the distributed backend factors, solves and inverts. Reproducible runs the tile-ordered kernels: every product inside a tile runs on one thread in a fixed order, so the results carry the same bits at every rank and thread count. Library calls the ScaLAPACK (or SLATE) routines. The selection also picks the HS-SVD kernel eigensolve in StableBasis.cpp: Eigen's self-adjoint solver on the host under both selections. Library adds cuSOLVER at one rank when a GPU is present, and pdsyev from order kMinDistributedSymmetricEigenOrder (1) across ranks when unconstrained reductions are enabled. In-process Eigen and BLAS products stay on one thread in both selections: a threaded reduction changes the summation order, and that changes band and saddle oracle counts between thread counts and between OpenBLAS and a reference LAPACK.

Enumerator
Reproducible 
Library 

Definition at line 24 of file LinalgThreads.h.

◆ ExecutionKind

enum class gpr::linalg::ExecutionKind
strong

Which units run the operation.

Enumerator
Serial 
HostThreads 
Cuda 
Hip 
Sycl 

Definition at line 65 of file BackendInterface.h.

◆ Lp64DescriptorField

Offsets of the ScaLAPACK array descriptor fields (DTYPE_ .. LLD_ - 1).

Enumerator
kDescM 
kDescN 
kDescMb 
kDescNb 
kDescRsrc 
kDescCsrc 
kDescLld 

Definition at line 39 of file Lp64Limits.h.

39 : int {
40 kDescM = 2,
41 kDescN = 3,
42 kDescMb = 4,
43 kDescNb = 5,
44 kDescRsrc = 6,
45 kDescCsrc = 7,
46 kDescLld = 8
47};

◆ MemoryKind

enum class gpr::linalg::MemoryKind
strong

Where an operand lives. Host memory is addressable by every backend; a device kind names the vendor runtime that owns the allocation.

Enumerator
Host 
CudaDevice 
HipDevice 
SyclDevice 

Definition at line 62 of file BackendInterface.h.

◆ ProductMode

enum class gpr::linalg::ProductMode
strong
Enumerator
Compensated 
SchemeI 
SchemeII 
KernelFloat 

Definition at line 15 of file CompensatedSum.h.

Function Documentation

◆ acceptStablePosteriorVariance() [1/3]

bool gpr::linalg::acceptStablePosteriorVariance ( double & variance,
double signal_variance )
inlinenodiscardnoexcept

acceptStablePosteriorVariance with the compensated-sum allowance.

Definition at line 105 of file ExactSchur.h.

107{
109 variance, signal_variance,
110 static_cast<double>(kStablePosteriorVarianceRoundoffUlps) *
111 std::numeric_limits<double>::epsilon());
112}
bool acceptStablePosteriorVariance(double &variance, double signal_variance, double relative_allowance) noexcept
Accept one stable posterior variance.
Definition ExactSchur.h:86
constexpr int kStablePosteriorVarianceRoundoffUlps
Ulps of the signal variance that a compensated posterior variance may sit below zero.
Definition ExactSchur.h:53

◆ acceptStablePosteriorVariance() [2/3]

bool gpr::linalg::acceptStablePosteriorVariance ( double & variance,
double signal_variance,
double relative_allowance )
inlinenodiscardnoexcept

Accept one stable posterior variance.

A nonnegative finite value is unchanged. A negative value at or above -relative_allowance * signal_variance is replaced by 0. Any more negative value, and any NaN or infinity, is rejected. signal_variance is the variance of the diagonal that entered the reduction: the kernel signal k(x,x), plus observation noise when that noise was added to the same diagonal. For the training-row latent identity the same role is the noise variance that bounds the identity. signal_variance is read only for a negative value.

The default relative allowance, kStablePosteriorVarianceRoundoffUlps machine epsilons, covers the rounding of a compensated sum. A Schur complement that follows a rounded Cholesky factorization and triangular solve carries the conditioning of the factor as well; its allowance is choleskySchurRelativeError.

Parameters
varianceVariance to check; a roundoff negative becomes 0.
signal_varianceVariance of the diagonal that entered the sum.
relative_allowanceForward error of the reduction relative to signal_variance. A negative value is accepted only when this is finite and below 1: an error of the size of the signal certifies no digit, so clamping to 0 would be a guess. Infinity, NaN and 1 or more reject every negative value.
Returns
False when the value is rejected.

Definition at line 86 of file ExactSchur.h.

89{
90 if (!std::isfinite(variance)) return false;
91 if (variance >= 0.0) return true;
92 if (!(signal_variance > 0.0) || !std::isfinite(signal_variance) ||
93 !std::isfinite(relative_allowance) || !(relative_allowance >= 0.0) ||
94 !(relative_allowance < 1.0))
95 return false;
96 const double allowance = relative_allowance * signal_variance;
97 if (variance >= -allowance) {
98 variance = 0.0;
99 return true;
100 }
101 return false;
102}

◆ acceptStablePosteriorVariance() [3/3]

bool gpr::linalg::acceptStablePosteriorVariance ( Eigen::VectorXd & variance,
const Eigen::VectorXd & signal )
inlinenodiscardnoexcept

Accept every entry of a stable posterior variance vector.

Returns
False when the sizes differ or any entry is rejected by the scalar overload; entries before the rejected one may already be clamped.

Definition at line 118 of file ExactSchur.h.

120{
121 if (variance.size() != signal.size()) return false;
122 for (Eigen::Index i = 0; i < variance.size(); ++i)
123 if (!acceptStablePosteriorVariance(variance(i), signal(i)))
124 return false;
125 return true;
126}

◆ accumulateSchemeI()

double gpr::linalg::accumulateSchemeI ( const SchemeISlices & left,
const SchemeISlices & right )

Sum the exact slice products. The split and this accumulation are separate.

Definition at line 102 of file OzakiScheme.cpp.

103{
104 if (left.bits == 0 || right.bits == 0 || left.slices.empty() ||
105 right.slices.empty()) {
106 return std::numeric_limits<double>::quiet_NaN();
107 }
108 struct NormalizedSlice {
109 Eigen::VectorXd values;
110 int exponent;
111 };
112 const auto normalize = [](const SchemeISlices& input) {
113 std::vector<NormalizedSlice> result;
114 result.reserve(input.slices.size());
115 for (const auto& slice: input.slices) {
116 int exponent = 0;
117 if (slice.size() > 0)
118 std::frexp(slice.cwiseAbs().maxCoeff(), &exponent);
119 const int unit = exponent - input.bits;
120 Eigen::VectorXd values(slice.size());
121 for (Eigen::Index i = 0; i < slice.size(); ++i)
122 values(i) = std::ldexp(slice(i), -unit);
123 result.push_back({std::move(values), unit});
124 }
125 return result;
126 };
127 const auto left_normalized = normalize(left);
128 const auto right_normalized = normalize(right);
130 for (const auto& a: left_normalized) {
131 for (const auto& b: right_normalized) {
132 if (a.values.size() != b.values.size())
133 return std::numeric_limits<double>::quiet_NaN();
134 // Slice integers and their partial sums fit in 52 bits. Keeping
135 // the scale separate prevents floating overflow and underflow.
136 double dot = 0.0;
137 for (Eigen::Index i = 0; i < a.values.size(); ++i)
138 dot += a.values(i) * b.values(i);
139 SchemeIIWide coefficient{};
140 coefficient.negative = dot < 0;
141 coefficient.limb[0] = static_cast<uint64_t>(std::fabs(dot));
142 total.add(coefficient, a.exponent + b.exponent);
143 }
144 }
145 return total.value();
146}
std::vector< Eigen::VectorXd > slices
Definition OzakiScheme.h:22

◆ affinityCpuCount()

int gpr::linalg::affinityCpuCount ( )
nodiscardnoexcept

CPUs in this process's scheduling affinity, or 0 when unknown.

Definition at line 189 of file LinalgThreads.cpp.

190{
191#ifdef __linux__
192 cpu_set_t set;
193 CPU_ZERO(&set);
194 if (sched_getaffinity(0, sizeof(set), &set) != 0) return 0;
195 return CPU_COUNT(&set);
196#else
197 return 0;
198#endif
199}

◆ arithmeticClassName()

const char * gpr::linalg::arithmeticClassName ( ArithmeticClass cls)
nodiscardconstexprnoexcept

Definition at line 114 of file BackendInterface.h.

116{
117 switch (cls) {
119 return "serial-equal";
121 return "grid-invariant";
123 return "unconstrained";
124 }
125 return "unknown";
126}

◆ arrowheadEigen()

bool gpr::linalg::arrowheadEigen ( const Eigen::VectorXd & d,
const Eigen::MatrixXd & B,
const Eigen::MatrixXd & A,
Eigen::VectorXd & evals_asc,
Eigen::MatrixXd & evecs )

Eigenpairs of a symmetric diagonal-plus-border matrix.

M = [ diag(d)   B ]      d in R^p,  B in R^{p x k},  A in R^{k x k}
    [ B^T       A ]

This is the shape the HS-SVD append builds: the old basis already diagonalises the old kernel, so the leading block is diagonal and the appended observations are a narrow border. A dense eigensolver costs O((p+k)^3) on it; the structure costs O(k (p+k)^2), and k is one or two because that is how many rows an acquisition adds.

Accuracy is the whole difficulty, not speed. Two things are needed and both are done here:

  • the secular equation is solved in a SHIFTED variable, so the quantity that decides an eigenvector is a difference of nearby diagonal entries rather than a difference of a diagonal entry and a nearly equal eigenvalue;
  • the coupling vector is reconstructed from the computed eigenvalues through Lowner's theorem before eigenvectors are formed. Forming them from the original coupling gives vectors that lose orthogonality when eigenvalues cluster, which is exactly what an eight-decade flat spectrum produces.

Deflation handles the two degenerate directions: a negligible border entry means its diagonal entry is already an eigenvalue, and two equal diagonal entries are rotated so that one coupling entry becomes zero and deflates. The zero block that the residual directions contribute deflates through the first of those by construction.

Returns false when the structure or the arguments do not hold, leaving the outputs untouched so a caller falls back to a dense solve.

Parameters
ddiagonal of the leading block, any order.
Bborder, p x k.
Atrailing block, k x k, symmetrised internally.
evals_ascascending eigenvalues, size p + k.
evecsmatching eigenvectors as columns, (p+k) x (p+k).

Definition at line 326 of file ArrowheadEigen.cpp.

329{
330 const Eigen::Index p = d.size();
331 const Eigen::Index k = A.rows();
332 if (B.rows() != p || B.cols() != k || A.cols() != k || k < 1) return false;
333 if (!d.allFinite() || !B.allFinite() || !A.allFinite()) return false;
334
335 // Diagonalise the trailing block first. That is what makes each pass
336 // below a genuine arrowhead: once A is diagonal the appended rows do
337 // not couple to each other, so a border column meets a diagonal and
338 // nothing else. A is k x k with k the number of rows an acquisition
339 // added, so this eigendecomposition is free.
340 const Eigen::MatrixXd As = 0.5 * (A + A.transpose());
341 Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> aes(As);
342 if (aes.info() != Eigen::Success) return false;
343 const Eigen::VectorXd a_ev = aes.eigenvalues();
344 const Eigen::MatrixXd Bq = B * aes.eigenvectors();
345
346 // Absorb one border column per pass. After a pass the leading part is
347 // diagonal again in the accumulated basis, so the next column meets an
348 // arrowhead too: k passes at O((p+k)^2) instead of one at O((p+k)^3).
349 Eigen::VectorXd cur_d = d;
350 Eigen::MatrixXd basis = Eigen::MatrixXd::Identity(p, p);
351
352 for (Eigen::Index c = 0; c < k; ++c) {
353 const Eigen::Index cur = cur_d.size(); // p + c
354
355 // Border in the ORIGINAL coordinates: the coupling to the leading
356 // block, then zero against every previously absorbed row, since
357 // diagonalising A removed those couplings.
358 Eigen::VectorXd raw = Eigen::VectorXd::Zero(cur);
359 raw.head(p) = Bq.col(c);
360
361 // Same border expressed in the basis the previous passes produced.
362 const Eigen::VectorXd zc = basis.transpose() * raw;
363
364 Eigen::VectorXd ev;
365 Eigen::MatrixXd V; // (cur + 1) x (cur + 1)
366 if (!arrowheadEigenRankOne(cur_d, zc, a_ev(c), ev, V)) return false;
367
368 // Extend the accumulated basis by the coordinate this pass added,
369 // then rotate it into the new eigenvectors.
370 Eigen::MatrixXd grown =
371 Eigen::MatrixXd::Zero(basis.rows() + 1, cur + 1);
372 grown.topLeftCorner(basis.rows(), cur) = basis;
373 grown(basis.rows(), cur) = 1.0;
374 basis = grown * V;
375 cur_d = ev;
376 }
377
378 // Back out of the basis A was diagonalised in. Everything above works
379 // in coordinates where the trailing block is diagonal, so the trailing
380 // rows of the accumulated eigenvectors are expressed in Qa's columns
381 // and have to be rotated back before a caller can use them against the
382 // original matrix. For k = 1 this is a sign and hides itself.
383 evecs = basis;
384 evecs.bottomRows(k) = aes.eigenvectors() * basis.bottomRows(k);
385 evals_asc = cur_d;
386 return evals_asc.allFinite() && evecs.allFinite() &&
387 evals_asc.size() == p + k && evecs.rows() == p + k;
388}
bool arrowheadEigenRankOne(const Eigen::VectorXd &d_in, const Eigen::VectorXd &z_in, double alpha, Eigen::VectorXd &evals_asc, Eigen::MatrixXd &evecs)

◆ arrowheadEigenRankOne()

bool gpr::linalg::arrowheadEigenRankOne ( const Eigen::VectorXd & d,
const Eigen::VectorXd & z,
double alpha,
Eigen::VectorXd & evals_asc,
Eigen::MatrixXd & evecs )

Single-border case, the primitive the block version iterates. M = [diag(d), z; z^T, alpha].

lam_j - d_i, from shifts rather than from reconstructed values.

Definition at line 107 of file ArrowheadEigen.cpp.

110{
111 const Eigen::Index p = d_in.size();
112 if (z_in.size() != p || p < 0) return false;
113 const Eigen::Index n = p + 1;
114 if (!std::isfinite(alpha) || !d_in.allFinite() || !z_in.allFinite())
115 return false;
116
117 if (p == 0) {
118 evals_asc.resize(1);
119 evals_asc(0) = alpha;
120 evecs = Eigen::MatrixXd::Identity(1, 1);
121 return true;
122 }
123
124 // Ascending diagonal; the interlacing the root search relies on is
125 // stated for sorted poles.
126 std::vector<Eigen::Index> perm(static_cast<std::size_t>(p));
127 std::iota(perm.begin(), perm.end(), Eigen::Index{0});
128 std::sort(perm.begin(), perm.end(), [&](Eigen::Index a, Eigen::Index b) {
129 return d_in(a) < d_in(b);
130 });
131 Eigen::VectorXd d(p), z(p);
132 for (Eigen::Index i = 0; i < p; ++i) {
133 d(i) = d_in(perm[static_cast<std::size_t>(i)]);
134 z(i) = z_in(perm[static_cast<std::size_t>(i)]);
135 }
136
137 const double scale =
138 std::max({d.cwiseAbs().maxCoeff(), z.cwiseAbs().maxCoeff(),
139 std::abs(alpha), 1.0});
140 const double eps = std::numeric_limits<double>::epsilon();
141 // Coupling is judged against the overall scale, but a gap between two
142 // diagonal entries is judged against those entries. These spectra span
143 // eight decades: one absolute gap tolerance either deflates everything
144 // at the small end or nothing at the large end.
145 const double z_tol = 8.0 * eps * scale;
146 const auto close = [&](double x, double y) {
147 return std::abs(x - y) <=
148 8.0 * eps * std::max({std::abs(x), std::abs(y), 1e-300});
149 };
150
151 // Deflation. A negligible coupling entry leaves its diagonal entry an
152 // eigenvalue outright, and two diagonal entries closer than tol are
153 // rotated so one coupling entry vanishes and joins that case. Without
154 // this the secular equation has a zero-width bracket and the
155 // eigenvectors it produces are not orthogonal.
156 std::vector<Eigen::Index> keep;
157 std::vector<std::pair<Eigen::Index, double>> deflated; // index, eigenvalue
158 std::vector<std::array<Eigen::Index, 2>> rotations;
159 std::vector<double> rot_c, rot_s;
160 for (Eigen::Index i = 0; i < p; ++i) {
161 if (std::abs(z(i)) <= z_tol) {
162 deflated.emplace_back(i, d(i));
163 continue;
164 }
165 if (!keep.empty()) {
166 const Eigen::Index j = keep.back();
167 if (close(d(i), d(j))) {
168 // Rotate (j, i) so the coupling concentrates on one of
169 // them; the other deflates at the shared diagonal value.
170 const double r = std::hypot(z(j), z(i));
171 const double c = z(j) / r, s = z(i) / r;
172 rotations.push_back({j, i});
173 rot_c.push_back(c);
174 rot_s.push_back(s);
175 z(j) = r;
176 z(i) = 0.0;
177 deflated.emplace_back(i, d(i));
178 continue;
179 }
180 }
181 keep.push_back(i);
182 }
183
184 const auto m = static_cast<Eigen::Index>(keep.size());
185 Eigen::VectorXd dk(m), zk(m), z2k(m);
186 for (Eigen::Index i = 0; i < m; ++i) {
187 dk(i) = d(keep[static_cast<std::size_t>(i)]);
188 zk(i) = z(keep[static_cast<std::size_t>(i)]);
189 z2k(i) = zk(i) * zk(i);
190 }
191
192 // Roots. Interlacing for an arrowhead is
193 // lam_0 <= d_0 <= lam_1 <= d_1 <= ... <= d_{m-1} <= lam_m,
194 // so there is one below the first pole, one in each gap, and one above
195 // the last: m + 1 in total.
196 //
197 // Each root is KEPT as the pole it was shifted from plus its offset,
198 // never as a reconstructed absolute value. Everything downstream needs
199 // differences lam_j - d_i, and forming those by subtracting a
200 // reconstructed eigenvalue from a nearby pole throws away exactly the
201 // digits the eigenvector depends on. Written as
202 // (d_{origin(j)} - d_i) + delta_j the cancellation happens between two
203 // input poles instead, which is as good as the data allows.
204 std::vector<Eigen::Index> root_org(static_cast<std::size_t>(m + 1));
205 Eigen::VectorXd root_del(m + 1);
206 Secular f{dk.data(), z2k.data(), static_cast<int>(m), alpha, 0.0};
207 const double zsum = z2k.sum();
208 const double span = std::abs(alpha) + zsum + dk.cwiseAbs().maxCoeff() + 1.0;
209 {
210 Secular fs = f;
211 fs.origin = dk(0);
212 root_org[0] = 0;
213 root_del(0) = solveShifted(fs, -span, 0.0);
214 }
215 for (Eigen::Index k = 0; k + 1 < m; ++k) {
216 Secular fs = f;
217 fs.origin = dk(k);
218 root_org[static_cast<std::size_t>(k + 1)] = k;
219 root_del(k + 1) = solveShifted(fs, 0.0, dk(k + 1) - dk(k));
220 }
221 {
222 Secular fs = f;
223 fs.origin = dk(m - 1);
224 root_org[static_cast<std::size_t>(m)] = m - 1;
225 root_del(m) = solveShifted(fs, 0.0, span);
226 }
227
229 const auto lam_minus_d = [&](Eigen::Index j, Eigen::Index i) {
230 return (dk(root_org[static_cast<std::size_t>(j)]) - dk(i)) +
231 root_del(j);
232 };
233
234 Eigen::VectorXd lam(m + 1);
235 for (Eigen::Index j = 0; j <= m; ++j)
236 lam(j) = dk(root_org[static_cast<std::size_t>(j)]) + root_del(j);
237
238 // Lowner reconstruction: the coupling that makes the COMPUTED
239 // eigenvalues exact. Eigenvectors built from this are orthogonal to
240 // working precision; built from the original coupling they are not,
241 // once eigenvalues cluster.
242 Eigen::VectorXd zhat(m);
243 for (Eigen::Index i = 0; i < m; ++i) {
244 // zhat_i^2 = -prod_j (lam_j - d_i) / prod_{j != i} (d_j - d_i),
245 // as paired ratios so nothing over- or underflows across eight
246 // decades, and with every numerator taken from the shifts.
247 double acc = -lam_minus_d(i, i) * lam_minus_d(m, i);
248 for (Eigen::Index j = 0; j < m; ++j) {
249 if (j == i) continue;
250 const double den = dk(j) - dk(i);
251 if (den == 0.0) {
252 acc = 0.0;
253 break;
254 }
255 acc *= lam_minus_d(j, i) / den;
256 }
257 zhat(i) = std::sqrt(std::max(acc, 0.0));
258 if (zk(i) < 0.0) zhat(i) = -zhat(i);
259 }
260
261 Eigen::MatrixXd Vk(m + 1, m + 1);
262 for (Eigen::Index j = 0; j <= m; ++j) {
263 Eigen::VectorXd x(m + 1);
264 // d_i - lam_j through the shift, for the same reason as above:
265 // this denominator is what the eigenvector is made of, and it is
266 // smallest exactly where subtracting reconstructed values is worst.
267 for (Eigen::Index i = 0; i < m; ++i)
268 x(i) = -zhat(i) / lam_minus_d(j, i);
269 x(m) = -1.0;
270 Vk.col(j) = x.normalized();
271 }
272
273 // Reassemble: deflated directions are unit vectors at their own
274 // diagonal value, then the rotations are undone, then the sort is.
275 evals_asc.resize(n);
276 evecs = Eigen::MatrixXd::Zero(n, n);
277 Eigen::Index col = 0;
278 for (Eigen::Index j = 0; j <= m; ++j) {
279 for (Eigen::Index i = 0; i < m; ++i)
280 evecs(keep[static_cast<std::size_t>(i)], col) = Vk(i, j);
281 evecs(p, col) = Vk(m, j);
282 evals_asc(col) = lam(j);
283 ++col;
284 }
285 for (const auto& [idx, val]: deflated) {
286 evecs(idx, col) = 1.0;
287 evals_asc(col) = val;
288 ++col;
289 }
290 for (Eigen::Index r = static_cast<Eigen::Index>(rotations.size()) - 1;
291 r >= 0; --r) {
292 const Eigen::Index j = rotations[static_cast<std::size_t>(r)][0];
293 const Eigen::Index i = rotations[static_cast<std::size_t>(r)][1];
294 const double c = rot_c[static_cast<std::size_t>(r)];
295 const double s = rot_s[static_cast<std::size_t>(r)];
296 for (Eigen::Index k = 0; k < n; ++k) {
297 const double vj = evecs(j, k), vi = evecs(i, k);
298 evecs(j, k) = c * vj - s * vi;
299 evecs(i, k) = s * vj + c * vi;
300 }
301 }
302 // Undo the diagonal sort on the leading block.
303 Eigen::MatrixXd out = Eigen::MatrixXd::Zero(n, n);
304 for (Eigen::Index i = 0; i < p; ++i)
305 out.row(perm[static_cast<std::size_t>(i)]) = evecs.row(i);
306 out.row(p) = evecs.row(p);
307 evecs = out;
308
309 // Ascending order, which every caller assumes.
310 std::vector<Eigen::Index> order(static_cast<std::size_t>(n));
311 std::iota(order.begin(), order.end(), Eigen::Index{0});
312 std::sort(order.begin(), order.end(), [&](Eigen::Index a, Eigen::Index b) {
313 return evals_asc(a) < evals_asc(b);
314 });
315 Eigen::VectorXd ev_sorted(n);
316 Eigen::MatrixXd V_sorted(n, n);
317 for (Eigen::Index i = 0; i < n; ++i) {
318 ev_sorted(i) = evals_asc(order[static_cast<std::size_t>(i)]);
319 V_sorted.col(i) = evecs.col(order[static_cast<std::size_t>(i)]);
320 }
321 evals_asc = ev_sorted;
322 evecs = V_sorted;
323 return evals_asc.allFinite() && evecs.allFinite();
324}
@ z
Definition Enums.h:28
@ x
Definition Enums.h:28
@ y
Definition Enums.h:28
eon_relax_band_t eon_relax_surface_fn void eon_relax_outcome_t * out

◆ assembleCollectively()

template<class Matrices, class Body>
void gpr::linalg::assembleCollectively ( const MpiContext & context,
Matrices & result,
const Body & body )

Assemble disjoint entries, propagate failures within the owning group, and replicate the tensors. The body joins its workers before returning; only the calling thread enters MPI collectives.

Definition at line 19 of file CollectiveAssembly.h.

21{
22 std::exception_ptr failure;
23 try {
24 body();
25 } catch (...) {
26 failure = std::current_exception();
27 }
28#if defined(GPR_HAVE_MPI) || defined(GPR_LINALG_SCALAPACK)
29 if (context.is_distributed()) {
30 int failed = failure ? 1 : 0;
31 if (MPI_Allreduce(MPI_IN_PLACE, &failed, 1, MPI_INT, MPI_MAX,
32 context.comm) != MPI_SUCCESS)
33 throw std::runtime_error("could not share assembly status");
34 if (failed && !failure)
35 throw std::runtime_error("assembly failed on another rank");
36 }
37#endif
38 if (failure) std::rethrow_exception(failure);
39 if (!context.is_distributed()) return;
40 constexpr Eigen::Index maximum = std::numeric_limits<int>::max();
41 for (auto& matrix: result)
42 for (Eigen::Index offset = 0; offset < matrix.size();) {
43 const int entries =
44 static_cast<int>(std::min(maximum, matrix.size() - offset));
45 disjoint_sum_bcast(matrix.data() + offset, entries, context);
46 offset += entries;
47 }
48}
void disjoint_sum_bcast(double *data, int count, const MpiContext &context)
bool is_distributed() const noexcept
Definition MpiContext.h:67

◆ availableHostBudget()

AvailableMemory gpr::linalg::availableHostBudget ( )
inline

Node headroom restricted by visible cgroup v1 and v2 ancestors. Null means unknown; zero means the allocation has exhausted a measured limit.

Definition at line 117 of file MemoryBudget.h.

118{
119 return memory_budget_detail::readAvailableMemory(
120 "/proc/meminfo", "/proc/self/cgroup", "/sys/fs/cgroup");
121}

◆ availableHostBytes()

std::int64_t gpr::linalg::availableHostBytes ( )
inline

Compatibility query: zero represents unknown or exhausted availability. Allocation decisions use availableHostBudget to distinguish the two.

Definition at line 125 of file MemoryBudget.h.

126{
127 return availableHostBudget().value_or(0);
128}
AvailableMemory availableHostBudget()

◆ back_solve() [1/2]

Eigen::VectorXd gpr::linalg::back_solve ( const EigenMatrix & L,
const Eigen::VectorXd & b )
inline

Back triangular solve with vector RHS (BLAS equivalent: dtrsv).

Solves \( L^T x = b \) where L is lower-triangular.

Parameters
[in]LLower-triangular matrix.
[in]bRight-hand side vector.
Returns
Solution vector \( x = L^{-T} b \).

Definition at line 384 of file CusolverBackend.h.

386{
388 const int n = static_cast<int>(L.rows());
389 auto& state = detail::DeviceState::instance();
390 auto& cblas = detail::CublasLib::instance();
391
392 state.ensureCapacity(n);
393 detail::h2d(state.d_L, L.data(), static_cast<size_t>(n) * n);
394 double* d_L_ptr = state.d_L;
395
396 detail::DevBuf d_x(n);
397 detail::h2d(d_x, b.data(), n);
398
399 detail::check_cublas(
400 cblas.cublasDtrsv(detail::cublas_handle(), CUBLAS_FILL_MODE_LOWER,
401 CUBLAS_OP_T, CUBLAS_DIAG_NON_UNIT, n, d_L_ptr, n, d_x,
402 1),
403 "dtrsv back");
404
405 Eigen::VectorXd x(n);
406 detail::d2h(x.data(), d_x, n);
407 return x;
408}
static constexpr int CUBLAS_DIAG_NON_UNIT
static constexpr int CUBLAS_OP_T
static constexpr int CUBLAS_FILL_MODE_LOWER

◆ back_solve() [2/2]

Eigen::VectorXd gpr::linalg::back_solve ( const EigenMatrix & L,
const Eigen::VectorXd & b,
DistributedState & st = DistributedState::instance() )
inline

Definition at line 1509 of file ScalapackBackend.h.

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}
void cache_L(std::vector< double > L_dist, const int *desc, int n)
EigenMatrix gather(const double *local, const int *desc, int m, int n, bool broadcast_result=true) const
std::vector< double > scatter_colvector_root(const Eigen::VectorXd &global, int m, int *desc) const
std::vector< double > scatter(const EigenMatrix &global, int m, int n, int *desc) const
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())
Eigen::Matrix< double, EigenDynamic, EigenDynamic, EigenMatrixStorage > EigenMatrix
Definition Macros.h:20

◆ back_solve_mat() [1/2]

EigenMatrix gpr::linalg::back_solve_mat ( const EigenMatrix & L,
const EigenMatrix & B )
inline

Back triangular solve with matrix RHS (BLAS equivalent: dtrsm with side=L, uplo=L, trans=T).

Solves \( L^T X = B \) where L is lower-triangular.

Parameters
[in]LLower-triangular matrix.
[in]BRight-hand side matrix.
Returns
Solution matrix \( X = L^{-T} B \).

Definition at line 438 of file CusolverBackend.h.

439{
441 const int m = static_cast<int>(L.rows());
442 const int n = static_cast<int>(B.cols());
443 auto& state = detail::DeviceState::instance();
444 auto& cblas = detail::CublasLib::instance();
445
446 state.ensureCapacity(m);
447 detail::h2d(state.d_L, L.data(), static_cast<size_t>(m) * m);
448 double* d_L_ptr = state.d_L;
449
450 detail::DevBuf d_X(m * n);
451 detail::h2d(d_X, B.data(), m * n);
452
453 const double alpha = 1.0;
454 detail::check_cublas(
455 cblas.cublasDtrsm(detail::cublas_handle(), CUBLAS_SIDE_LEFT,
457 CUBLAS_DIAG_NON_UNIT, m, n, &alpha, d_L_ptr, m, d_X,
458 m),
459 "dtrsm_t");
460
461 EigenMatrix X(m, n);
462 detail::d2h(X.data(), d_X, m * n);
463 return X;
464}
static constexpr int CUBLAS_SIDE_LEFT

◆ back_solve_mat() [2/2]

EigenMatrix gpr::linalg::back_solve_mat ( const EigenMatrix & L,
const EigenMatrix & B,
DistributedState & st = DistributedState::instance() )
inline

Definition at line 960 of file ScalapackBackend.h.

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}

◆ blasThreadCount()

int gpr::linalg::blasThreadCount ( )
nodiscardnoexcept

Actual thread count of the BLAS runtime linked inside this library, or zero when the build uses no OpenBLAS runtime.

Definition at line 201 of file LinalgThreads.cpp.

202{
203#ifdef GPR_HAVE_OPENBLAS
204 return openblas_get_num_threads();
205#else
206 return 0;
207#endif
208}

◆ blockCyclicLocalExtent()

std::int64_t gpr::linalg::blockCyclicLocalExtent ( std::int64_t n,
std::int64_t nb,
std::int64_t iproc,
std::int64_t isrc,
std::int64_t nprocs )
constexprnoexcept

NUMROC in 64-bit arithmetic: the number of the n entries of one dimension, distributed in blocks of nb over nprocs processes starting at process isrc, that process iproc owns. Returns 0 for a non-positive order, block or process count.

Definition at line 55 of file Lp64Limits.h.

59{
60 if (n <= 0 || nb <= 0 || nprocs <= 0) return 0;
61 const std::int64_t distance = ((iproc - isrc) % nprocs + nprocs) % nprocs;
62 const std::int64_t blocks = n / nb;
63 std::int64_t extent = (blocks / nprocs) * nb;
64 const std::int64_t extra = blocks % nprocs;
65 if (distance < extra)
66 extent += nb;
67 else if (distance == extra)
68 extent += n % nb;
69 return extent;
70}

◆ bordered_cholesky_diagonal() [1/2]

Eigen::VectorXd gpr::linalg::bordered_cholesky_diagonal ( const EigenMatrix & L,
const EigenMatrix & B,
const Eigen::VectorXd & prior )
inline

Posterior diagonal from bordered Cholesky pivots.

Solves \(L X=B\) and returns the correctly rounded Schur-complement diagonal \(D-\operatorname{diag}(X^T X)\). The prior and negative squares are accumulated together, so a small posterior pivot is not formed by subtracting two independently rounded signal-scale values.

Parameters
[in]LLower-triangular training factor.
[in]BTraining-query cross covariance.
[in]priorQuery prior diagonal.
Returns
Squared final pivots of the bordered Cholesky factorizations.

Definition at line 473 of file CusolverBackend.h.

476{
477 return borderedCholeskyDiagonal(prior, forward_solve_mat(L, B), L);
478}
EigenMatrix forward_solve_mat(const EigenMatrix &L, const EigenMatrix &B)
Forward triangular solve with matrix RHS (BLAS equivalent: dtrsm).
Eigen::VectorXd borderedCholeskyDiagonal(const Eigen::VectorXd &prior, const Eigen::MatrixBase< Derived > &whitened)
borderedCholeskyDiagonal for a whitened block L^-1 K_tq with no factor in hand: the allowance is the ...
Definition ExactSchur.h:444

◆ bordered_cholesky_diagonal() [2/2]

Eigen::VectorXd gpr::linalg::bordered_cholesky_diagonal ( const EigenMatrix & L,
const EigenMatrix & B,
const Eigen::VectorXd & prior,
DistributedState & st = DistributedState::instance() )
inline

Definition at line 1207 of file ScalapackBackend.h.

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}
void requireStablePosteriorVariance(double &variance, double signal_variance, double relative_allowance)
Accept one stable posterior variance or throw.
Definition ExactSchur.h:131
Eigen::VectorXd columnSchurComplementsExact(const std::vector< double > &buf, const int *desc, int m, int ncols, const Eigen::VectorXd &prior, DistributedState &st)
void requireCachedFactorSchurDiagonal(Eigen::VectorXd &diagonal, const Eigen::VectorXd &prior, int m, DistributedState &st)

◆ bordered_cholesky_diagonal_distributed()

Eigen::VectorXd gpr::linalg::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() )
inline

Definition at line 1359 of file ScalapackBackend.h.

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}

◆ borderedCholeskyActionVariance() [1/2]

template<typename PriorDerived, typename WeightDerived, typename SolvedDerived>
double gpr::linalg::borderedCholeskyActionVariance ( const Eigen::MatrixBase< PriorDerived > & prior,
const Eigen::MatrixBase< WeightDerived > & weights,
const Eigen::MatrixBase< SolvedDerived > & whitened_action )
nodiscard

borderedCholeskyActionVariance with the compensated-sum allowance.

Definition at line 519 of file ExactSchur.h.

523{
525 prior, weights, whitened_action, [] {
526 return static_cast<double>(kStablePosteriorVarianceRoundoffUlps) *
527 std::numeric_limits<double>::epsilon();
528 });
529}
double borderedCholeskyActionVarianceWith(const Eigen::MatrixBase< PriorDerived > &prior, const Eigen::MatrixBase< WeightDerived > &weights, const Eigen::MatrixBase< SolvedDerived > &whitened_action, RelativeError &&relative_error)
Variance of a linear query action from its bordered Cholesky solve.
Definition ExactSchur.h:480

◆ borderedCholeskyActionVariance() [2/2]

template<typename PriorDerived, typename WeightDerived, typename SolvedDerived, typename FactorDerived>
double gpr::linalg::borderedCholeskyActionVariance ( const Eigen::MatrixBase< PriorDerived > & prior,
const Eigen::MatrixBase< WeightDerived > & weights,
const Eigen::MatrixBase< SolvedDerived > & whitened_action,
const Eigen::MatrixBase< FactorDerived > & factor )
nodiscard

borderedCholeskyActionVariance for L^-1 K_tq w solved with the dense lower factor factor, with the allowance of choleskySchurRelativeError.

Definition at line 536 of file ExactSchur.h.

541{
542 if (factor.size() == 0)
543 return borderedCholeskyActionVariance(prior, weights, whitened_action);
545 prior, weights, whitened_action,
546 [&] { return denseCholeskySchurRelativeError(factor); });
547}
double borderedCholeskyActionVariance(const Eigen::MatrixBase< PriorDerived > &prior, const Eigen::MatrixBase< WeightDerived > &weights, const Eigen::MatrixBase< SolvedDerived > &whitened_action)
borderedCholeskyActionVariance with the compensated-sum allowance.
Definition ExactSchur.h:519
double denseCholeskySchurRelativeError(const Eigen::MatrixBase< Derived > &factor)
choleskySchurRelativeError of a dense lower Cholesky factor.
Definition ExactSchur.h:362

◆ borderedCholeskyActionVarianceWith()

template<typename PriorDerived, typename WeightDerived, typename SolvedDerived, typename RelativeError>
double gpr::linalg::borderedCholeskyActionVarianceWith ( const Eigen::MatrixBase< PriorDerived > & prior,
const Eigen::MatrixBase< WeightDerived > & weights,
const Eigen::MatrixBase< SolvedDerived > & whitened_action,
RelativeError && relative_error )
nodiscard

Variance of a linear query action from its bordered Cholesky solve.

The prior action \(w^T K_{qq}w\) and the negative squared entries of \(L^{-1}K_{tq}w\) share one exact accumulator. This is the scalar bordered-Cholesky pivot for a directional or integrated observation.

Definition at line 480 of file ExactSchur.h.

485{
486 if (prior.rows() != prior.cols() || prior.rows() != weights.size())
487 throw std::invalid_argument(
488 "bordered Cholesky action prior and weights disagree");
490 const long double prior_variance =
491 weights.template cast<long double>().dot(
492 prior.template cast<long double>() *
493 weights.template cast<long double>());
494 const long double projected_variance =
495 whitened_action.template cast<long double>().squaredNorm();
496 return static_cast<double>(prior_variance - projected_variance);
497 }
498 ExactSum pivot;
499 ExactSum signal;
500 for (Eigen::Index column = 0; column < prior.cols(); ++column)
501 for (Eigen::Index row = 0; row < prior.rows(); ++row) {
502 pivot.addTripleProduct(weights(row), prior(row, column),
503 weights(column));
504 signal.addTripleProduct(weights(row), prior(row, column),
505 weights(column));
506 }
507 for (Eigen::Index row = 0; row < whitened_action.size(); ++row) {
508 const double value = whitened_action(row);
509 pivot.addProduct(-value, value);
510 }
511 double variance = pivot.value();
512 requireStablePosteriorVariance(variance, signal.value(),
513 variance < 0.0 ? relative_error() : 0.0);
514 return variance;
515}
bool stablePosteriorVarianceEnabled() noexcept
Whether stable posterior variance reductions are enabled.
Definition ExactSchur.h:40
double variance(const Weights &w, const Matrix &covariance)

◆ borderedCholeskyDiagonal() [1/2]

template<typename Derived>
Eigen::VectorXd gpr::linalg::borderedCholeskyDiagonal ( const Eigen::VectorXd & prior,
const Eigen::MatrixBase< Derived > & whitened )
nodiscard

borderedCholeskyDiagonal for a whitened block L^-1 K_tq with no factor in hand: the allowance is the rounding of the compensated sum alone.

Definition at line 444 of file ExactSchur.h.

446{
447 return borderedCholeskyDiagonalWith(prior, whitened, [] {
448 return static_cast<double>(kStablePosteriorVarianceRoundoffUlps) *
449 std::numeric_limits<double>::epsilon();
450 });
451}
Eigen::VectorXd borderedCholeskyDiagonalWith(const Eigen::VectorXd &prior, const Eigen::MatrixBase< Derived > &whitened, RelativeError &&relative_error)
Squared final pivots of bordered Cholesky factorizations.
Definition ExactSchur.h:407

◆ borderedCholeskyDiagonal() [2/2]

template<typename Derived, typename FactorDerived>
Eigen::VectorXd gpr::linalg::borderedCholeskyDiagonal ( const Eigen::VectorXd & prior,
const Eigen::MatrixBase< Derived > & whitened,
const Eigen::MatrixBase< FactorDerived > & factor )
nodiscard

borderedCholeskyDiagonal for W = L^-1 K_tq solved with the dense lower factor factor; the allowance is choleskySchurRelativeError of that factor.

An empty factor means the factor is not held on the host (it is resident on a device), so its conditioning cannot be read; the allowance is then that of the two-argument form.

Definition at line 461 of file ExactSchur.h.

464{
465 if (factor.size() == 0) return borderedCholeskyDiagonal(prior, whitened);
466 return borderedCholeskyDiagonalWith(prior, whitened, [&] {
467 return denseCholeskySchurRelativeError(factor);
468 });
469}

◆ borderedCholeskyDiagonalWith()

template<typename Derived, typename RelativeError>
Eigen::VectorXd gpr::linalg::borderedCholeskyDiagonalWith ( const Eigen::VectorXd & prior,
const Eigen::MatrixBase< Derived > & whitened,
RelativeError && relative_error )
nodiscard

Squared final pivots of bordered Cholesky factorizations.

If whitened is \(W=L^{-1}K_{tq}\), entry \(j\) is

\[ \ell_j^2 = K_{qq,jj} - \sum_i W_{ij}^2, \]

the square of the last diagonal in the Cholesky factor of \(\begin{bmatrix}LL^T&K_{tq}\\K_{tq}^T&K_{qq,jj}\end{bmatrix}\). ExactSum accumulates the prior and every negative square without rounding; only the final result is rounded to binary64. Consequently the reduction error is at most one rounding of the local posterior variance, rather than \(\gamma_n K_{qq,jj}\) from a length- \(n\) dot product followed by a cancellation.

Definition at line 407 of file ExactSchur.h.

410{
411 if (prior.size() != whitened.cols())
412 throw std::invalid_argument(
413 "bordered Cholesky prior and cross covariance disagree");
415 return prior - whitened.colwise().squaredNorm().transpose();
416 Eigen::VectorXd diagonal(prior.size());
417 bool have_error = false;
418 double error = 0.0;
419 for (Eigen::Index column = 0; column < whitened.cols(); ++column) {
420 ExactSum pivot;
421 pivot.add(prior(column));
422 for (Eigen::Index row = 0; row < whitened.rows(); ++row) {
423 const double value = whitened(row, column);
424 pivot.addProduct(-value, value);
425 }
426 diagonal(column) = pivot.value();
427 // The conditioning of the factor matters only for a negative value,
428 // and estimating it costs a few triangular solves, so it is asked for
429 // once and only then.
430 if (diagonal(column) < 0.0 && !have_error) {
431 error = relative_error();
432 have_error = true;
433 }
434 requireStablePosteriorVariance(diagonal(column), prior(column),
435 have_error ? error : 0.0);
436 }
437 return diagonal;
438}
void addProduct(double a, double b) noexcept
Definition ExactSum.h:70
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

◆ cache_cholesky_inverse()

void gpr::linalg::cache_cholesky_inverse ( const EigenMatrix & L,
DistributedState & st = DistributedState::instance() )
inline

Definition at line 1794 of file ScalapackBackend.h.

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}
void cache_inv(std::vector< double > inv_dist, const int *desc, int n)
bool factor_inverse_lower(const EigenMatrix &L, int n, std::vector< double > &inverse, int *desc, DistributedState &st)

◆ cached_inverse_observation_tile_trace_np1()

double gpr::linalg::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() )
inline

Definition at line 1840 of file ScalapackBackend.h.

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}
const double * cached_inv() const
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)

◆ cached_trsm_left_lower()

void gpr::linalg::cached_trsm_left_lower ( int m,
int ncols,
double * b_buf,
const int * desc_b,
bool transpose,
const char * fn,
DistributedState & st = DistributedState::instance() )
inline

Definition at line 262 of file ScalapackBackend.h.

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}
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)
bool tile_kernels(const int *desc, const char *routine, const int *other=nullptr) const
bool reproducible() const noexcept
const double * cached_L() const
void trsmCachedLowerFactor(DistributedState &st, double *B, const int *desc_b, int n, int ncols, bool transpose)

◆ cachedFactorSchurRelativeError()

double gpr::linalg::cachedFactorSchurRelativeError ( int m,
DistributedState & st = DistributedState::instance() )
inline

Relative forward error of a Schur complement formed from the cached distributed factor (choleskySchurRelativeError). ||L||_F is summed over the lower triangle of the local blocks. ||L^-1||_1 is upperInverseNorm1FromResidual: the 1-norm of the inverse from one cached triangular solve, corrected by the residual of that solve. A column-sum lift alone leaves out the triangular-solve error and is not a certificate. The factor itself is never gathered. Every rank receives the same value, and every rank must call it.

Definition at line 1084 of file ScalapackBackend.h.

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}
int numroc_(const int *n, const int *nb, const int *iproc, const int *isrcproc, const int *nprocs)
int global_index_for_local(int local_index, int block_size, int proc_coord, int nprocs_dim) const
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
void exact_sum_bcast(ExactSum *sums, int count, const MpiContext &context)
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

◆ canonicalizeEigenpairs()

void gpr::linalg::canonicalizeEigenpairs ( Eigen::Ref< Eigen::VectorXd > evals,
Eigen::Ref< Eigen::MatrixXd > evecs )
inline

evals has one entry per leading column of evecs. Both are rewritten.

Definition at line 94 of file CanonicalEigen.h.

96{
97 const Eigen::Index n = evals.size();
98 if (n == 0 || evecs.cols() < n || evecs.rows() == 0) return;
99
100 double scale = 0.0;
101 for (Eigen::Index i = 0; i < n; ++i) {
102 if (!std::isfinite(evals(i))) return;
103 scale = std::max(scale, std::abs(evals(i)));
104 }
105 const double tolerance = symmetricBackwardError(evecs.rows(), scale);
106 for (Eigen::Index i = 0; i < n; ++i) {
107 if (std::abs(evals(i)) <= tolerance) evals(i) = 0.0;
108 canonicalizeEigenvectorSign(evecs.col(i), tolerance);
109 }
110
111 std::vector<Eigen::Index> order(static_cast<std::size_t>(n));
112 for (Eigen::Index i = 0; i < n; ++i)
113 order[static_cast<std::size_t>(i)] = i;
114 std::sort(
115 order.begin(), order.end(), [&](Eigen::Index left, Eigen::Index right) {
116 if (evals(left) < evals(right)) return true;
117 if (evals(left) > evals(right)) return false;
118 return signedEigenvectorLess(evecs.col(left), evecs.col(right));
119 });
120
121 const Eigen::VectorXd saved_evals = evals;
122 const Eigen::MatrixXd saved_evecs = evecs.leftCols(n);
123 for (Eigen::Index i = 0; i < n; ++i) {
124 const Eigen::Index source = order[static_cast<std::size_t>(i)];
125 evals(i) = saved_evals(source);
126 evecs.col(i) = saved_evecs.col(source);
127 }
128}
void canonicalizeEigenvectorSign(Eigen::Ref< Eigen::VectorXd > vector, double tolerance) noexcept
double symmetricBackwardError(Eigen::Index n, double scale) noexcept

◆ canonicalizeEigenvectorSign()

void gpr::linalg::canonicalizeEigenvectorSign ( Eigen::Ref< Eigen::VectorXd > vector,
double tolerance )
inlinenoexcept

Definition at line 53 of file CanonicalEigen.h.

55{
56 double max_abs = 0.0;
57 for (Eigen::Index i = 0; i < vector.size(); ++i) {
58 if (!std::isfinite(vector(i))) return;
59 max_abs = std::max(max_abs, std::abs(vector(i)));
60 }
61 if (!(max_abs > 0.0)) return;
62 // The tie is the rounding of this vector. An eigenvalue backward error
63 // grows with |lambda| and is not a component tolerance: past the vector
64 // scale it marks a smaller leading entry as tied and leaves the true
65 // maximum negative.
66 const double entry_roundoff =
67 16.0 * std::numeric_limits<double>::epsilon() * max_abs;
68 const double vector_backward =
69 symmetricBackwardError(vector.size(), max_abs);
70 const double requested =
71 (std::isfinite(tolerance) && tolerance > 0.0) ? tolerance : 0.0;
72 const double floor =
73 std::max(entry_roundoff, std::min(requested, vector_backward));
74 for (Eigen::Index i = 0; i < vector.size(); ++i) {
75 if (std::abs(vector(i)) + floor < max_abs) continue;
76 if (vector(i) < 0.0) vector *= -1.0;
77 return;
78 }
79}

◆ cholesky() [1/2]

bool gpr::linalg::cholesky ( const EigenMatrix & C,
EigenMatrix & L )
inline

Cholesky decomposition (LAPACK equivalent: dpotrf).

Decomposes a symmetric positive-definite matrix \( C = L L^T \).

Parameters
[in]CSymmetric positive-definite matrix.
[out]LLower-triangular Cholesky factor.
Returns
true if C is positive-definite, false otherwise.

Dense operations execute in the installed Kokkos execution space. GPU inputs and results cross the host interface as Eigen matrices.

Definition at line 44 of file CholmodBackend.h.

45{
46 if (C.rows() != C.cols()) return false;
49 if (!scaling.compute(C.diagonal())) return false;
50 const auto n = static_cast<std::size_t>(C.rows());
51 const auto max_index =
52 static_cast<std::size_t>(std::numeric_limits<SuiteSparse_long>::max());
53 if (n >= max_index) return false;
54 if (n == 0) {
55 L.resize(0, 0);
56 return true;
57 }
58
59 std::size_t entries = 0;
60 for (Eigen::Index column = 0; column < C.cols(); ++column) {
61 for (Eigen::Index row = column; row < C.rows(); ++row) {
62 const double value =
63 scaling.covariance(C(row, column), row, column);
64 if (!std::isfinite(value)) return false;
65 if (C(row, column) != 0.0 && ++entries > max_index) return false;
66 }
67 }
68
69 detail::CholmodWorkspace workspace;
70 if (!workspace.started) return false;
71 auto& common = workspace.common;
72 common.print = 0;
73 // The supernodal factor runs dense supernodes through dpotrf, dsyrk and
74 // dgemm on the OpenBLAS kernel the CPU selects, so a dense covariance
75 // of order 64 already factored to different bits per OPENBLAS_CORETYPE.
76 // The simplicial up-looking factor calls no BLAS.
77 common.supernodal = CHOLMOD_SIMPLICIAL;
78 common.nmethods = 1;
79 common.method[0].ordering = CHOLMOD_NATURAL;
80 common.postorder = 0;
81 common.final_asis = 0;
82 common.final_ll = 1;
83 common.final_pack = 1;
84 common.final_monotonic = 1;
85 workspace.covariance = cholmod_l_allocate_sparse(n, n, entries, 1, 1, -1,
86 CHOLMOD_REAL, &common);
87 if (!workspace.covariance) return false;
88 auto* column_offsets =
89 static_cast<SuiteSparse_long*>(workspace.covariance->p);
90 auto* rows = static_cast<SuiteSparse_long*>(workspace.covariance->i);
91 auto* values = static_cast<double*>(workspace.covariance->x);
92 std::size_t offset = 0;
93 for (Eigen::Index column = 0; column < C.cols(); ++column) {
94 column_offsets[column] = static_cast<SuiteSparse_long>(offset);
95 for (Eigen::Index row = column; row < C.rows(); ++row) {
96 // Exact zeros are absent from CSC; no tolerance changes the matrix.
97 if (C(row, column) == 0.0) continue;
98 rows[offset] = static_cast<SuiteSparse_long>(row);
99 values[offset] = scaling.covariance(C(row, column), row, column);
100 ++offset;
101 }
102 }
103 column_offsets[n] = static_cast<SuiteSparse_long>(offset);
104 workspace.factor = cholmod_l_analyze(workspace.covariance, &common);
105 if (!workspace.factor || common.status != CHOLMOD_OK) return false;
106 if (!cholmod_l_factorize(workspace.covariance, workspace.factor, &common) ||
107 common.status != CHOLMOD_OK || workspace.factor->minor != n ||
108 !workspace.factor->is_ll || workspace.factor->itype != CHOLMOD_LONG)
109 return false;
110 const auto* permutation =
111 static_cast<const SuiteSparse_long*>(workspace.factor->Perm);
112 if (permutation) {
113 for (std::size_t i = 0; i < n; ++i)
114 if (permutation[i] != static_cast<SuiteSparse_long>(i))
115 return false;
116 }
117 workspace.lower = cholmod_l_factor_to_sparse(workspace.factor, &common);
118 if (!workspace.lower || common.status != CHOLMOD_OK ||
119 workspace.lower->itype != CHOLMOD_LONG ||
120 workspace.lower->xtype != CHOLMOD_REAL ||
121 workspace.lower->dtype != CHOLMOD_DOUBLE || !workspace.lower->packed)
122 return false;
123
124 const auto* lower_offsets =
125 static_cast<const SuiteSparse_long*>(workspace.lower->p);
126 const auto* lower_rows =
127 static_cast<const SuiteSparse_long*>(workspace.lower->i);
128 const auto* lower_values = static_cast<const double*>(workspace.lower->x);
129 EigenMatrix candidate = EigenMatrix::Zero(C.rows(), C.cols());
130 for (Eigen::Index column = 0; column < C.cols(); ++column) {
131 for (auto k = lower_offsets[column]; k < lower_offsets[column + 1];
132 ++k) {
133 const auto row = lower_rows[k];
134 if (row < column || row >= C.rows()) return false;
135 candidate(row, column) =
136 scaling.physicalFactor(lower_values[k], row);
137 }
138 }
139 if (!candidate.allFinite() || !(candidate.diagonal().array() > 0.0).all())
140 return false;
141 L = std::move(candidate);
142 return true;
143}
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

◆ cholesky() [2/2]

bool gpr::linalg::cholesky ( const EigenMatrix & C,
EigenMatrix & L,
DistributedState & st = DistributedState::instance() )
inline

Definition at line 368 of file ScalapackBackend.h.

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}
void pdpotrf_(const char *uplo, const int *n, double *a, const int *ia, const int *ja, const int *desca, int *info)
void initialize(int block_size=0, int nprow=0)
bool potrfLower(DistributedState &st, double *A, const int *desc, int n, int n_factored=0)
void transformDistributedLower(std::vector< double > &buffer, const int *desc, int n, const CovarianceEquilibration &scaling, bool restore_factor, DistributedState &st)
bool equilibrateDistributedLower(std::vector< double > &buffer, const int *desc, int n, CovarianceEquilibration &scaling, DistributedState &st)
bool trainingCholeskyDistributedSelected(Eigen::Index order)

◆ cholesky_distributed()

bool gpr::linalg::cholesky_distributed ( std::vector< double > C_dist,
const int * desc,
int n,
EigenMatrix & L,
DistributedState & st = DistributedState::instance() )
inline

Definition at line 414 of file ScalapackBackend.h.

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}

◆ cholesky_inverse() [1/2]

EigenMatrix gpr::linalg::cholesky_inverse ( const EigenMatrix & L)
inline

Symmetric inverse from Cholesky factor (LAPACK equivalent: dpotri).

Computes \( C^{-1} = L^{-T} L^{-1} \) given the lower-triangular Cholesky factor L.

Parameters
[in]LLower-triangular Cholesky factor.
Returns
The symmetric positive-definite inverse \( C^{-1} \).

Definition at line 480 of file CusolverBackend.h.

481{
483 const int n = static_cast<int>(L.rows());
484 auto& csol = detail::CusolverLib::instance();
485
486 detail::DevBuf d_A(n * n);
487 detail::h2d(d_A, L.data(), static_cast<size_t>(n) * n);
488
489 int lwork = 0;
490 detail::check_cusolver(csol.cusolverDnDpotri_bufferSize(
491 detail::cusolver_handle(),
492 CUBLAS_FILL_MODE_LOWER, n, d_A, n, &lwork),
493 "potri_bufferSize");
494 detail::DevBuf d_work(lwork);
495 detail::DevInt d_info;
496
497 detail::check_cusolver(
498 csol.cusolverDnDpotri(detail::cusolver_handle(), CUBLAS_FILL_MODE_LOWER,
499 n, d_A, n, d_work, lwork, d_info),
500 "potri");
501
502 EigenMatrix invC(n, n);
503 detail::d2h(invC.data(), d_A, n * n);
504 for (int j = 0; j < n; ++j)
505 for (int i = 0; i < j; ++i)
506 invC(i, j) = invC(j, i);
507 return invC;
508}

◆ cholesky_inverse() [2/2]

EigenMatrix gpr::linalg::cholesky_inverse ( const EigenMatrix & L,
DistributedState & st = DistributedState::instance() )
inline

Definition at line 1763 of file ScalapackBackend.h.

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}
const int * cached_inv_desc() const

◆ cholesky_inverse_diagonal_distributed()

Eigen::VectorXd gpr::linalg::cholesky_inverse_diagonal_distributed ( const EigenMatrix & L,
int order,
DistributedState & st = DistributedState::instance() )
inline

Diagonal of (L L^T)^-1 from distributed columns of L^-1. Triangular inversion avoids solving for the known zero upper triangle. The owned factor is immutable; only the resulting diagonal is replicated.

Definition at line 1394 of file ScalapackBackend.h.

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}
const std::shared_ptr< const MpiCommunicator > & communication() const noexcept
int local_index_for_global(int global_index, int block_size, int proc_coord, int nprocs_dim) const
std::vector< double > alloc_local(int m, int n, int *desc) const
static ScalapackLib & instance()
TileMap tileAt(double *base, int lld, const TileGeometry &g, int row_tile, int col_tile, int rows, int cols)
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)
Eigen::VectorXd columnSquaredNormsExact(const std::vector< double > &buf, const int *desc, int m, int ncols, DistributedState &st)
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())

◆ cholesky_inverse_root()

EigenMatrix gpr::linalg::cholesky_inverse_root ( const EigenMatrix & L,
DistributedState & st = DistributedState::instance() )
inline

Definition at line 1966 of file ScalapackBackend.h.

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}
void pdpotri_(const char *uplo, const int *n, double *a, const int *ia, const int *ja, const int *desca, int *info)
void choleskyInverseLower(DistributedState &st, const double *L, const int *desc, int n, std::vector< double > &inverse, std::optional< const double * > upper=std::nullopt)

◆ cholesky_rank_update()

bool gpr::linalg::cholesky_rank_update ( EigenMatrix & lower,
const Eigen::VectorXd & vector )
inline

Update the selected backend's live Cholesky factor in its existing layout.

Definition at line 46 of file CholeskyUpdate.h.

53{
54#ifdef GPR_LINALG_SCALAPACK
55 if (lower.size() != 0) return rank_one_update_lower(lower, vector);
56 const int n = state.cached_n();
57 if (!state.has_cached_L() || n <= 0 || vector.size() != n ||
58 !vector.allFinite())
59 return false;
60 if (vector.isZero(0.0)) return true;
61 state.invalidate_derived_cholesky();
62 const int block = state.block_size();
63 const bool linear = state.cached_L_desc()[1] == state.lin_context();
64 const int grid_rows = linear ? state.nprocs() : state.nprow();
65 const int grid_cols = linear ? 1 : state.npcol();
66 const int proc_row = linear ? state.lin_myrow() : state.myrow();
67 const int proc_col = linear ? state.lin_mycol() : state.mycol();
68 const int rows = linear ? state.lin_local_rows(n) : state.local_rows(n);
69 std::vector<int> global_rows;
70 global_rows.reserve(rows);
71 for (int i = 0; i < n; ++i)
72 if ((i / block) % grid_rows == proc_row) global_rows.push_back(i);
73 Eigen::VectorXd update = vector;
74 std::vector<double> row_update(static_cast<std::size_t>(rows));
75 std::vector<double> rotations(
76 1 + 2 * static_cast<std::size_t>(std::min(block, n)));
77 // Rotations reuse the grid's communication contexts across fits; a
78 // rank update changes the factor values and leaves its layout intact.
79 const auto comms = state.tile_communicators(state.cached_L_desc()[1]);
80 double* factor = state.cached_L_mut();
81 bool valid = true;
82 for (int first = 0; first < n;) {
83 const int width = std::min(block, n - first);
84 const int end = first + width;
85 const int owner_row = (first / block) % grid_rows;
86 const int owner_col = (first / block) % grid_cols;
87 const int local_first_col =
88 state.local_index_for_global(first, block, owner_col, grid_cols);
89 rotations[0] = 1.0;
90 // Every pivot in this block depends only on its lower triangle and
91 // the update entries in these rows. One owner forms the rotations;
92 // rows below the block consume them in the same increasing order.
93 if (proc_row == owner_row && proc_col == owner_col) {
94 const int local_first_row = state.local_index_for_global(
95 first, block, owner_row, grid_rows);
96 for (int offset = 0; offset < width; ++offset) {
97 const int j = first + offset;
98 double* column =
99 factor +
100 static_cast<std::size_t>(local_first_col + offset) * rows;
101 const double diagonal = column[local_first_row + offset];
102 const double radius = std::hypot(diagonal, update(j));
103 if (!(diagonal > 0.0) || !std::isfinite(radius)) {
104 rotations[0] = 0.0;
105 break;
106 }
107 const double cosine = diagonal / radius;
108 const double sine = update(j) / radius;
109 rotations[1 + 2 * offset] = cosine;
110 rotations[2 + 2 * offset] = sine;
111 column[local_first_row + offset] = radius;
112 for (int i = offset + 1; i < width; ++i) {
113 const double value = column[local_first_row + i];
114 const double tail = update(first + i);
115 column[local_first_row + i] =
116 std::fma(sine, tail, cosine * value);
117 update(first + i) = std::fma(-sine, value, cosine * tail);
118 }
119 }
120 }
121 MPI_Bcast(
122 rotations.data(), 1 + 2 * width, MPI_DOUBLE,
123 comms.rank_of[static_cast<std::size_t>(owner_row) * grid_cols +
124 owner_col],
125 state.world_comm());
126 if (rotations[0] == 0.0) {
127 valid = false;
128 break;
129 }
130 if (proc_col == owner_col && rows > 0) {
131 for (int offset = 0; offset < width; ++offset) {
132 const double cosine = rotations[1 + 2 * offset];
133 const double sine = rotations[2 + 2 * offset];
134 double* column =
135 factor +
136 static_cast<std::size_t>(local_first_col + offset) * rows;
137 for (int local_row = 0; local_row < rows; ++local_row) {
138 const int i = global_rows[local_row];
139 if (i < end) continue;
140 const double value = column[local_row];
141 const double tail = update(i);
142 column[local_row] = std::fma(sine, tail, cosine * value);
143 update(i) = std::fma(-sine, value, cosine * tail);
144 }
145 }
146 for (int local_row = 0; local_row < rows; ++local_row)
147 row_update[local_row] = update(global_rows[local_row]);
148 }
149 // Replicate the completed row updates across process columns before
150 // the next diagonal block selects its owner.
151 MPI_Bcast(row_update.data(), rows, MPI_DOUBLE, owner_col, comms.row);
152 for (int local_row = 0; local_row < rows; ++local_row)
153 update(global_rows[local_row]) = row_update[local_row];
154 first = end;
155 }
156 if (!valid) state.invalidate_L();
157 return valid;
158#else
159 return rank_one_update_lower(lower, vector);
160#endif
161}
bool rank_one_update_lower(EigenMatrix &lower, const Eigen::VectorXd &vector)

◆ choleskySchurRelativeError()

double gpr::linalg::choleskySchurRelativeError ( Eigen::Index order,
double factor_frobenius_norm,
double inverse_norm1 )
inlinenodiscardnoexcept

Relative forward error of a Schur complement computed from a rounded Cholesky factor and triangular solve.

Let L be the computed factor of order m, K + dK = L L^T its backward error, w = L^-1 b the exact solve and w^ the rounded one, and nu = ||L||_F ||L^-1||_1, which bounds kappa_2(L) / sqrt(m) because ||L||_2 <= ||L||_F and ||L^-1||_2 <= sqrt(m) ||L^-1||_1. inverse_norm1 is an upper bound on ||L^-1||_1. A lower bound makes nu, and this allowance, a lower bound on the forward error, so a pivot whose negativity is real roundoff is rejected. With u = eps / 2 and gamma_k = k u / (1 - k u):

  • substitution solves (L + dL) w^ = b with abs(dL) <= gamma_m abs(L) (Higham, Accuracy and Stability, Thm 8.5), so ||w^ - w||_2 <= a ||w^||_2 with a = gamma_m m nu;
  • Cholesky has abs(dK) <= gamma_{m+1} abs(L) abs(L^T) (Thm 10.3), which moves b^T K^-1 b by at most b_f ||w||^2 with b_f = gamma_{m+1} m^2 nu^2.

A valid Schur complement has ||w||^2 <= prior, so the computed one prior - ||w^||^2 is off by at most (a (2 + a) + b_f) / (1 - a - b_f)^2 of the prior, plus one rounding of the result, eps. The value is infinite when a + b_f >= 1 or when the bound itself is 1 or more: an error as large as the signal leaves no certified digit, and no negative result can be called roundoff.

Definition at line 259 of file ExactSchur.h.

262{
263 const double infinity = std::numeric_limits<double>::infinity();
264 const double eps = std::numeric_limits<double>::epsilon();
265 if (order <= 0) return eps;
266 const double u = 0.5 * eps;
267 const double m = static_cast<double>(order);
268 const double nu = factor_frobenius_norm * inverse_norm1;
269 if (!std::isfinite(nu) || !(nu >= 0.0) || !((m + 1.0) * u < 1.0))
270 return infinity;
271 const double gamma_m = m * u / (1.0 - m * u);
272 const double gamma_m1 = (m + 1.0) * u / (1.0 - (m + 1.0) * u);
273 const double a = gamma_m * m * nu;
274 const double b = gamma_m1 * m * m * nu * nu;
275 const double total = a + b;
276 if (!std::isfinite(total) || !(total < 1.0)) return infinity;
277 const double rest = 1.0 - total;
278 const double bound = (a * (2.0 + a) + b) / (rest * rest) + eps;
279 return std::isfinite(bound) && bound < 1.0 ? bound : infinity;
280}

◆ columnSchurComplementsExact()

Eigen::VectorXd gpr::linalg::columnSchurComplementsExact ( const std::vector< double > & buf,
const int * desc,
int m,
int ncols,
const Eigen::VectorXd & prior,
DistributedState & st )
inline

Definition at line 1016 of file ScalapackBackend.h.

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}

◆ columnSquaredNormsExact()

Eigen::VectorXd gpr::linalg::columnSquaredNormsExact ( const std::vector< double > & buf,
const int * desc,
int m,
int ncols,
DistributedState & st )
inline

Column-wise sums of squares of a block-cyclic matrix whose tiles are owned whole by one rank. Each tile column contributes a partial sum accumulated in a fixed order inside the tile; the partials enter an exact accumulator, so the replicated result is independent of the grid.

Definition at line 985 of file ScalapackBackend.h.

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}
void addProduct(double left, double right)

◆ compensated_sum_bcast()

void gpr::linalg::compensated_sum_bcast ( CompensatedSum * data,
int count,
const MpiContext & context )
inline

Merge compensated contributions in rank order, retaining the rounding error from adding their main sums in the resulting correction.

Definition at line 107 of file MpiCollectives.h.

109{
110 if (count <= 0 || context.nprocs == 1) return;
111 if (count > std::numeric_limits<int>::max() / 2)
112 throw std::length_error("compensated reduction exceeds MPI count");
113#if defined(GPR_HAVE_MPI) || defined(GPR_LINALG_SCALAPACK)
114 std::vector<double> parts(2 * static_cast<std::size_t>(count));
115 for (int i = 0; i < count; ++i) {
116 parts[i] = data[i].sum;
117 parts[count + i] = data[i].corr;
118 }
119 std::vector<double> gathered;
120 if (context.rank == 0)
121 gathered.resize(parts.size() *
122 static_cast<std::size_t>(context.nprocs));
123 MPI_Gather(parts.data(), static_cast<int>(parts.size()), MPI_DOUBLE,
124 context.rank == 0 ? gathered.data() : nullptr,
125 static_cast<int>(parts.size()), MPI_DOUBLE, 0, context.comm);
126 if (context.rank == 0) {
127 for (int i = 0; i < count; ++i) {
128 CompensatedSum combined;
129 for (int rank = 0; rank < context.nprocs; ++rank) {
130 const std::size_t offset =
131 static_cast<std::size_t>(rank) * parts.size();
132 combined.add(gathered[offset + i]);
133 combined.add(gathered[offset + count + i]);
134 }
135 parts[i] = combined.sum;
136 parts[count + i] = combined.corr;
137 }
138 }
139 MPI_Bcast(parts.data(), static_cast<int>(parts.size()), MPI_DOUBLE, 0,
140 context.comm);
141 for (int i = 0; i < count; ++i) {
142 data[i].sum = parts[i];
143 data[i].corr = parts[count + i];
144 }
145#else
146 (void)data;
147 throw std::logic_error("distributed reduction requires MPI");
148#endif
149}

◆ compiled_distributed_backend()

DistributedBackendKind gpr::linalg::compiled_distributed_backend ( )
constexprnoexcept

Definition at line 47 of file DistributedState.h.

48{
49#if defined(GPR_LINALG_SLATE)
51#elif defined(GPR_LINALG_SCALAPACK)
53#else
55#endif
56}

◆ configuredEnvironmentGpu()

std::shared_ptr< const EnvironmentGpuExecutor > gpr::linalg::configuredEnvironmentGpu ( )
nodiscard

Definition at line 93 of file EnvironmentGpuExecutor.cpp.

94{
95 std::lock_guard guard(default_mutex);
96 return default_executor;
97}

◆ configureDistributedFactorization()

void gpr::linalg::configureDistributedFactorization ( DistributedFactorization mode)

Select the distributed factorization and reapply the configured thread count, since the BLAS thread policy depends on the selection.

Definition at line 96 of file LinalgThreads.cpp.

97{
98 if (factorization.exchange(mode, std::memory_order_relaxed) != mode)
99 factorization_generation.fetch_add(1, std::memory_order_relaxed);
102 requested_tile_threads.load(std::memory_order_relaxed));
103}
void configureLinalgThreads(int threads)
void configureTileThreads(int threads)
int configuredLinalgThreads() noexcept
Requested dense numerical budget, independent of nested BLAS controls.

◆ configuredLinalgThreads()

int gpr::linalg::configuredLinalgThreads ( )
nodiscardnoexcept

Requested dense numerical budget, independent of nested BLAS controls.

Definition at line 119 of file LinalgThreads.cpp.

120{
121 return configured_threads.load(std::memory_order_relaxed);
122}

◆ configureEnvironmentGpu()

void gpr::linalg::configureEnvironmentGpu ( const std::string & library)

Native entry points select the device before constructing model contexts. Existing models retain their execution context when this default changes.

Definition at line 83 of file EnvironmentGpuExecutor.cpp.

84{
85 auto executor =
86 library.empty()
87 ? nullptr
88 : std::make_shared<const EnvironmentGpuExecutor>(library);
89 std::lock_guard guard(default_mutex);
90 default_executor = std::move(executor);
91}

◆ configureKernelThreads()

void gpr::linalg::configureKernelThreads ( int threads)

Process default captured by subsequently constructed local executors. Configure before constructing models; CPU allocation and BLAS thread limits belong to the application that owns the process.

Definition at line 18 of file LocalExecutor.cpp.

19{
20 const LocalExecutor validated(threads);
21 requested_kernel_threads.store(validated.concurrency(),
22 std::memory_order_relaxed);
24}
void refreshKernelTeam()

◆ configureLibrarySerialKernels()

void gpr::linalg::configureLibrarySerialKernels ( bool enabled)
noexcept

When set, the dense factor and the triangular solves use Eigen's library kernels (LAPACK when BLAS is linked) instead of the OpenMP panel kernels. One thread is the serial baseline the scaling notes compare with the panel path. Clearing the flag restores the panel kernels for a team of more than one. A single configured thread stays on Eigen's factor and triangular solve: the panel kernels are a different rounding even with one worker, and the oracle counts were measured on Eigen.

Definition at line 154 of file LinalgThreads.cpp.

155{
156 library_serial_kernels.store(enabled, std::memory_order_relaxed);
157}

◆ configureLinalgThreads()

void gpr::linalg::configureLinalgThreads ( int threads)

Configure the process thread budget before concurrent numerical work. Keeping the call inside the library reaches private static BLAS symbols without exposing them to an oracle's BLAS runtime. The count is a process-wide run parameter; set it before constructing models. Eigen and BLAS search products keep one fixed reduction order; canonical tiles and panels spend the requested budget in parallel without changing their inner product order. The count is also the OpenMP team of kernel and Hessian assembly. The OpenMP runtime receives the same count, so OMP_NUM_THREADS does not fight the team.

Definition at line 124 of file LinalgThreads.cpp.

125{
126 if (threads < 1) threads = 1;
127 configured_threads.store(threads, std::memory_order_relaxed);
128 // Search products keep one fixed reduction order. The requested budget
129 // is spent by the canonical tile and panel executors instead.
131#if defined(_OPENMP)
132 omp_set_dynamic(0);
133 // One active level: an assembly worker must not start another team on
134 // top of the factor team. The factor itself runs outside those regions.
135 omp_set_max_active_levels(1);
136 omp_set_num_threads(threads);
137#endif
139}
void configureProductThreads(int threads)

◆ configureProductThreads()

void gpr::linalg::configureProductThreads ( int threads)

Thread count of Eigen and BLAS products alone, leaving configuredLinalgThreads() unchanged. This low-level control honours its argument; callers that require invariant reductions explicitly select one thread per independently scheduled tile.

Definition at line 141 of file LinalgThreads.cpp.

142{
143 if (threads < 1) threads = 1;
144 {
145 const std::lock_guard<std::recursive_mutex> lock(
146 serialEigenThreadState().mutex);
147 Eigen::setNbThreads(threads);
148 }
149#ifdef GPR_HAVE_OPENBLAS
150 openblas_set_num_threads(threads);
151#endif
152}

◆ configureStablePosteriorVariance()

void gpr::linalg::configureStablePosteriorVariance ( bool enabled)
inlinenoexcept

Turn stable posterior variance reductions on or off for the process.

Parameters
enabledTrue selects ExactSum reductions and the checks of requireStablePosteriorVariance; false restores the default paths.

Definition at line 34 of file ExactSchur.h.

35{
36 stable_posterior_variance.store(enabled, std::memory_order_relaxed);
37}
std::atomic_bool stable_posterior_variance
Process-wide switch for stable posterior variance reductions. Off by default; set through configureSt...
Definition ExactSchur.h:28

◆ configureTileThreads()

void gpr::linalg::configureTileThreads ( int threads)

Threads one rank devotes to independent tile products of the canonical factorization and solves. Each product runs on one thread, so the values do not depend on this count. Under the Library factorization the tiles stay on the calling thread as well.

Definition at line 177 of file LinalgThreads.cpp.

178{
179 requested_tile_threads.store(threads, std::memory_order_relaxed);
180 // Products are already one thread. Reproducible mode spends the count
181 // on independent tiles. Library mode keeps tiles on the calling thread;
182 // its ScaLAPACK rounding still follows the process grid, not this count.
185 ? threads
186 : 1);
187}
void setTileThreads(int threads) noexcept
Sets the tile thread count (at least one).
DistributedFactorization distributedFactorization() noexcept
Process-wide selection; Reproducible unless configured otherwise.

◆ configureTrainingProductLibrary()

void gpr::linalg::configureTrainingProductLibrary ( const std::string & library)

Select a Scheme II product. A path loads a device library through the v1 C ABI; "scheme2:fp64[...]" or "scheme2:int8[...]" selects an in-process CPU engine (see schemeii::parseOptions). Empty selects the native backend. Explicit library or device errors throw; they cannot masquerade as a run with the requested arithmetic. Configure before training starts.

Definition at line 54 of file TrainingProduct.cpp.

55{
56 std::shared_ptr<ProductLibrary> replacement;
57 std::shared_ptr<schemeii::Context> scheme;
58 if (schemeii::isSpec(library)) {
59 // In-process Scheme II engine; no device library is loaded.
60 scheme = std::make_shared<schemeii::Context>(
61 schemeii::parseOptions(library));
62 scheme->setThreadSource(&linalgThreadSource);
63 std::fprintf(stderr, "[training-product] scheme2 %s\n",
64 scheme->describe(256).c_str());
65 } else if (!library.empty()) {
66 replacement = std::make_shared<ProductLibrary>();
67 auto& state = *replacement;
68 state.library = dlopen(library.c_str(), RTLD_NOW | RTLD_LOCAL);
69 if (!state.library) throw std::runtime_error(dlerror());
70 const auto create =
71 reinterpret_cast<decltype(&gpr_training_product_create_v1)>(
72 dlsym(state.library, "gpr_training_product_create_v1"));
73 state.destroy =
74 reinterpret_cast<decltype(&gpr_training_product_destroy_v1)>(
75 dlsym(state.library, "gpr_training_product_destroy_v1"));
76 state.gemm = reinterpret_cast<decltype(&gpr_training_product_gemm_v1)>(
77 dlsym(state.library, "gpr_training_product_gemm_v1"));
78 if (!create || !state.destroy || !state.gemm)
79 throw std::runtime_error("incompatible training product library");
80 char error[1024]{};
81 state.workspace = create(error, sizeof(error));
82 if (!state.workspace) throw std::runtime_error(error);
83 }
84 std::lock_guard lock(configuration);
85 configured = std::move(replacement);
86 configured_scheme = std::move(scheme);
87}
void * gpr_training_product_create_v1(char *error, size_t capacity)
int gpr_training_product_gemm_v1(void *workspace, int transpose_a, int transpose_b, int64_t m, int64_t n, int64_t k, double alpha, const double *a, int64_t lda, const double *b, int64_t ldb, double beta, double *c, int64_t ldc, char *error, size_t capacity)
void gpr_training_product_destroy_v1(void *workspace)
bool isSpec(std::string_view spec) noexcept
Definition SchemeII.cpp:455
Options parseOptions(std::string_view spec)
Definition SchemeII.cpp:460

◆ configureUnconstrainedLibraryReductions()

void gpr::linalg::configureUnconstrainedLibraryReductions ( bool enabled)
noexcept

Opt into unconstrained library reductions (e.g. SLATE MethodTrsm::Auto hypercube reductions and unaligned ScaLAPACK slab views) for diagnostic overhead comparisons. Disabled by default so both Reproducible and Library factorizations preserve canonical tile order across ranks, grids and threads.

Definition at line 164 of file LinalgThreads.cpp.

165{
166 if (unconstrained_library_reductions.exchange(
167 enabled, std::memory_order_relaxed) != enabled) {
168 factorization_generation.fetch_add(1, std::memory_order_relaxed);
169 }
170}

◆ contractPredictionMatrix()

void gpr::linalg::contractPredictionMatrix ( const double * column_major,
int rows,
int cols,
const double * coefficients,
double * output,
ProductMode mode )

Definition at line 251 of file PredictProduct.cpp.

254{
255 if (cols < 0 || rows < 0 ||
256 (cols > 0 && (column_major == nullptr || output == nullptr)) ||
257 (rows > 0 && coefficients == nullptr))
258 throw std::invalid_argument("invalid prediction contraction");
259 // One column is one energy or one force component of one test point.
260 // Each column is an exact sum of products rounded once, so the column
261 // a thread owns does not depend on the team. Kernel-float launches stay
262 // on the calling thread.
263 const double flops =
264 2.0 * static_cast<double>(rows) * static_cast<double>(cols);
265 const bool parallel =
267#if defined(USE_OPENMP)
268#pragma omp parallel for schedule(static) if (parallel)
269#endif
270 for (int col = 0; col < cols; ++col) {
271 output[col] = evaluateStoredProduct(
272 column_major + static_cast<std::ptrdiff_t>(col) * rows,
273 coefficients, rows, mode);
274 }
275}
double evaluateStoredProduct(const double *left, const double *right, int length, ProductMode mode)
bool teamParallelPays(double flops)

◆ covarianceDsyevr()

bool gpr::linalg::covarianceDsyevr ( const Eigen::MatrixXd & sym,
Eigen::VectorXd & evals,
Eigen::MatrixXd & evecs )

Covariance eigensolve used by the stable basis. Eigen's symmetric eigensolver, range all, lower triangle. The pairs do not follow the OpenBLAS microkernel.

Definition at line 611 of file StableBasis.cpp.

613{
614 return hostSymmetricEigenpairs(sym, evals, evecs);
615}

◆ crtSchemeII()

SchemeIIWide gpr::linalg::crtSchemeII ( const uint32_t * residues)
inline

Definition at line 309 of file OzakiSchemeII.inl.

310{
311 SchemeIIWide value{};
312 value.limb[0] = residues[0];
313 SchemeIIWide modulus{};
314 modulus.limb[0] = schemeIIModulus(0);
315 for (int i = 1; i < kSchemeIIModulusCount; ++i) {
316 const uint32_t current = schemeIIModulus(i);
317 const uint32_t value_mod = wide_mod(value, current);
318 const uint32_t modulus_mod = wide_mod(modulus, current);
319 uint32_t delta = residues[i] >= value_mod
320 ? residues[i] - value_mod
321 : current - (value_mod - residues[i]);
322 delta = mul_mod(delta, mod_inverse(modulus_mod, current), current);
323 SchemeIIWide step = wide_mul_small(modulus, delta);
324 value = wide_add(value, step);
325 modulus = wide_mul_small(modulus, current);
326 }
327 SchemeIIWide half = modulus;
328 uint64_t carry = 0;
329 // half = modulus >> 1
330 for (int i = SchemeIIWide::kLimbs - 1; i >= 0; --i) {
331 const uint64_t word = half.limb[i];
332 half.limb[i] = (word >> 1) | (carry ? 0x8000000000000000ull : 0ull);
333 carry = word & 1ull;
334 }
335 if (wide_cmp(value, half) > 0) {
336 value = wide_sub(modulus, value);
337 value.negative = true;
338 }
339 return value;
340}
constexpr int kSchemeIIModulusCount
constexpr uint32_t schemeIIModulus(int index)
static constexpr int kLimbs

◆ curvatureIsNegative()

bool gpr::linalg::curvatureIsNegative ( double lambda,
double scale,
Eigen::Index n )
inlinenoexcept

True when lambda is negative by more than the backward error of an n-dimensional symmetric solve at scale. A value inside that ball is unresolved, not a negative mode.

Definition at line 47 of file CanonicalEigen.h.

49{
50 return std::isfinite(lambda) && lambda < -symmetricBackwardError(n, scale);
51}

◆ dense_factor_inverse_trace()

double gpr::linalg::dense_factor_inverse_trace ( const EigenMatrix & L)
inline

tr(K^{-1}) = ||L^{-1}||_F^2 for a dense factor already in hand. Same rank-local rule as trace_solve_product.

Definition at line 32 of file DenseFactorTrace.h.

33{
34 if (L.rows() != L.cols()) return std::numeric_limits<double>::quiet_NaN();
35 if (L.rows() == 0) return 0.0;
36 return L.triangularView<Eigen::Lower>()
37 .solve(EigenMatrix::Identity(L.rows(), L.cols()))
38 .squaredNorm();
39}

◆ denseCholeskySchurRelativeError()

template<typename Derived>
double gpr::linalg::denseCholeskySchurRelativeError ( const Eigen::MatrixBase< Derived > & factor)
nodiscard

choleskySchurRelativeError of a dense lower Cholesky factor.

The inverse norm is upperInverseNorm1, an upper bound. The Hager estimate is a lower bound and is not used here.

Definition at line 362 of file ExactSchur.h.

364{
365 if (factor.rows() != factor.cols() || factor.rows() == 0)
366 return std::numeric_limits<double>::infinity();
367 const Eigen::MatrixXd lower = factor.derived().template cast<double>();
368 return choleskySchurRelativeError(lower.rows(), lower.norm(),
369 upperInverseNorm1(lower));
370}
double upperInverseNorm1(const Eigen::MatrixBase< Derived > &factor)
Upper bound on ||L^-1||_1 for an explicit lower-triangular factor.
Definition ExactSchur.h:335

◆ disjoint_sum_bcast() [1/2]

void gpr::linalg::disjoint_sum_bcast ( double * data,
int count,
const MpiContext & context )
inline

Replicate a sum with at most one nonzero contributor per entry. Adding positive zeros preserves that contributor's value regardless of the reduction tree. Overlapping contributions require ordered_sum_bcast.

Definition at line 49 of file MpiCollectives.h.

51{
52 if (count <= 0 || context.nprocs == 1) return;
53#if defined(GPR_HAVE_MPI) || defined(GPR_LINALG_SCALAPACK)
54 MPI_Allreduce(MPI_IN_PLACE, data, count, MPI_DOUBLE, MPI_SUM, context.comm);
55#else
56 (void)data;
57 throw std::logic_error("distributed reduction requires MPI");
58#endif
59}

◆ disjoint_sum_bcast() [2/2]

void gpr::linalg::disjoint_sum_bcast ( double * data,
int count,
DistributedState & st = DistributedState::instance() )
inline

Reduction for buffers whose per-rank contributions have DISJOINT support: every entry is nonzero on at most one rank and +0.0 (from setZero) everywhere else. IEEE-754 addition gives x + (+0.0) = x and (+0.0) + (+0.0) = +0.0 exactly, so MPI_SUM under any reduction tree returns the unique contributor bit-for-bit – identical to ordered_sum_bcast and to the single-rank assembly, at MPI_Allreduce's O(log P) cost instead of the Gather(P * count) + root long-double sum + Bcast round-trip.

Applies to the one-owner-per-block covariance assemblies (ownsBlock gating writes each block and its transpose partner from exactly one rank via assignBlockToMatrix assignment, never accumulation). Overlapping partial sums (per-rank training-slice means, trace terms, scalar log-marginal contributions) require ordered_sum_bcast to fix their reduction order for a given partition. Different partitions can produce different rounded local sums.

Definition at line 129 of file ScalapackBackend.h.

132{
133 if (count <= 0) return;
134
135 if (st.nprocs() == 1) return;
136
137 disjoint_sum_bcast(data, count, st.communication()->view());
138}

◆ distributed_backend_name()

const char * gpr::linalg::distributed_backend_name ( DistributedBackendKind backend)
constexprnoexcept

Definition at line 58 of file DistributedState.h.

60{
61 switch (backend) {
63 return "slate";
65 return "scalapack";
67 return "eigen";
68 }
69 return "eigen";
70}

◆ distributed_gemm_nn()

bool gpr::linalg::distributed_gemm_nn ( const EigenMatrix & A,
const EigenMatrix & B,
EigenMatrix & C,
DistributedState & st = DistributedState::instance() )
inline

Definition at line 144 of file ScalapackBackend.h.

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}
void replicate_owned_values(double *data, std::size_t count, const MpiContext &context)
bool tryTrainingProduct(ConstProductMatrix a, ConstProductMatrix b, ProductMatrix c, bool transpose_a, bool transpose_b, double alpha, double beta, bool partitioned)
bool trainingProductConfigured()
A device library or an in-process engine is configured.

◆ distributed_symmetric_eigen()

bool gpr::linalg::distributed_symmetric_eigen ( const EigenMatrix & A,
Eigen::VectorXd & eigenvalues,
EigenMatrix & eigenvectors,
const char ** driver_name = nullptr,
DistributedState & st = DistributedState::instance() )
inline

Definition at line 533 of file ScalapackBackend.h.

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}
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 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 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 require_lp64(const int *desc, const char *routine) const
void make_desc(int m, int n, int *desc) const
bool unconstrainedLibraryReductions() noexcept
int lp64Workspace(double query, const char *routine, const DistributedState &st)

◆ distributed_thin_svd()

bool gpr::linalg::distributed_thin_svd ( const EigenMatrix & A,
EigenMatrix & U,
Eigen::VectorXd & S,
EigenMatrix & V,
DistributedState & st = DistributedState::instance() )
inline

Definition at line 487 of file ScalapackBackend.h.

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}
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)

◆ distributed_thin_svd_colblock()

bool gpr::linalg::distributed_thin_svd_colblock ( const EigenMatrix & A_local,
int m,
int n,
EigenMatrix & U,
Eigen::VectorXd & S,
EigenMatrix & V,
DistributedState & st = DistributedState::instance() )
inline

Definition at line 691 of file ScalapackBackend.h.

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}
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 make_col_desc(int m, int n, int *desc) const

◆ distributed_thin_svd_tsqr()

bool gpr::linalg::distributed_thin_svd_tsqr ( const EigenMatrix & A_local,
int nobs,
int N,
EigenMatrix & U,
Eigen::VectorXd & S,
EigenMatrix & V,
DistributedState & st = DistributedState::instance() )
inline

Definition at line 764 of file ScalapackBackend.h.

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}
bool exceedsLp64(const int *desc, int nprow, int npcol) noexcept
Definition Lp64Limits.h:151

◆ distributedFactorization()

DistributedFactorization gpr::linalg::distributedFactorization ( )
nodiscardnoexcept

Process-wide selection; Reproducible unless configured otherwise.

Definition at line 86 of file LinalgThreads.cpp.

87{
88 return factorization.load(std::memory_order_relaxed);
89}

◆ distributedFactorizationGeneration()

std::uint64_t gpr::linalg::distributedFactorizationGeneration ( )
nodiscardnoexcept

Changes each time the selection changes. A cached factor, inverse or replica records the generation it was computed under and is not reused under another one.

Definition at line 91 of file LinalgThreads.cpp.

92{
93 return factorization_generation.load(std::memory_order_relaxed);
94}

◆ distributedFactorizationName()

const char * gpr::linalg::distributedFactorizationName ( DistributedFactorization mode)
nodiscardnoexcept

Definition at line 105 of file LinalgThreads.cpp.

106{
107 return mode == DistributedFactorization::Library ? "library"
108 : "reproducible";
109}

◆ equilibrateDistributedLower()

bool gpr::linalg::equilibrateDistributedLower ( std::vector< double > & buffer,
const int * desc,
int n,
CovarianceEquilibration & scaling,
DistributedState & st )
inline

Definition at line 345 of file ScalapackBackend.h.

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}
void ordered_sum_bcast(double *data, int count, const MpiContext &context)

◆ estimateLowerInverseNorm1()

template<typename Solve, typename SolveTranspose>
double gpr::linalg::estimateLowerInverseNorm1 ( Eigen::Index order,
Solve && solve,
SolveTranspose && solve_transpose )
nodiscard

Estimate of ||L^-1||_1 for a lower triangular L (Hager, with Higham's alternating-sign probe).

solve applies L^-1 to a vector and solve_transpose applies L^-T. The estimate is a lower bound on the norm, as in LAPACK's xTRCON, and in practice within a small factor of it. It costs at most ten triangular solves. Infinite when a solve is not finite, which is a singular factor.

Definition at line 197 of file ExactSchur.h.

200{
201 const double infinity = std::numeric_limits<double>::infinity();
202 if (order <= 0) return 0.0;
203 Eigen::VectorXd x = Eigen::VectorXd::Constant(order, 1.0 / order);
204 double estimate = 0.0;
205 for (int iteration = 0; iteration < 5; ++iteration) {
206 const Eigen::VectorXd y = solve(x);
207 if (!y.allFinite()) return infinity;
208 estimate = std::max(estimate, y.lpNorm<1>());
209 Eigen::VectorXd signs(order);
210 for (Eigen::Index i = 0; i < order; ++i)
211 signs(i) = y(i) >= 0.0 ? 1.0 : -1.0;
212 const Eigen::VectorXd z = solve_transpose(signs);
213 if (!z.allFinite()) return infinity;
214 Eigen::Index largest = 0;
215 const double bound = z.cwiseAbs().maxCoeff(&largest);
216 if (bound <= z.dot(x)) break;
217 x = Eigen::VectorXd::Zero(order);
218 x(largest) = 1.0;
219 }
220 if (order > 1) {
221 Eigen::VectorXd alternating(order);
222 for (Eigen::Index i = 0; i < order; ++i)
223 alternating(i) = (i % 2 == 0 ? 1.0 : -1.0) *
224 (1.0 + static_cast<double>(i) / (order - 1));
225 const Eigen::VectorXd y = solve(alternating);
226 if (!y.allFinite()) return infinity;
227 estimate = std::max(estimate, 2.0 * y.lpNorm<1>() / (3.0 * order));
228 }
229 return estimate;
230}

◆ evaluateStoredProduct()

double gpr::linalg::evaluateStoredProduct ( const double * left,
const double * right,
int length,
ProductMode mode )

Definition at line 277 of file PredictProduct.cpp.

279{
280 if (length <= 0) return 0.0;
281 const bool emulated = mode == ProductMode::SchemeI ||
282 mode == ProductMode::SchemeII ||
284 if (emulated) {
285 double native = 0.0;
286 if (nativeBinary64Fallback(left, right, length, native)) return native;
287 }
288 if (mode == ProductMode::SchemeI || mode == ProductMode::SchemeII) {
289 double certified;
290 if (tryCertifiedProduct(left, right, length, certified))
291 return certified;
292 }
293 const char* device_library = std::getenv("GPR_EMULATED_PRODUCT_LIB");
294 const bool on_device =
295 device_library != nullptr && device_library[0] != '\0';
296 if (mode == ProductMode::SchemeI) {
297 if (on_device)
298 return deviceSchemeProduct("scheme_i_product_launch_v1", left,
299 right, length);
300 Eigen::Map<const Eigen::VectorXd> left_terms(left, length);
301 Eigen::Map<const Eigen::VectorXd> right_terms(right, length);
302 return schemeIProduct(left_terms, right_terms);
303 }
304 if (mode == ProductMode::SchemeII) {
305 if (on_device)
306 return deviceSchemeProduct("scheme_ii_native_launch_v1", left,
307 right, length);
308 return schemeIIProductRaw(left, right, length);
309 }
310 if (mode == ProductMode::KernelFloat)
311 return kernelFloatProduct(left, right, length);
312 // Eigen KK'*a and cutoff Sexpat energy. ExactSum stores the
313 // TwoProductFMA split and value() rounds once. CompensatedSum::addProduct
314 // sums that split with Neumaier, which returns 0 for the Ozaki window
315 // residual 2^-300 and moves the alternating-pi dots off the cell.
316 ExactSum sum;
317 for (int i = 0; i < length; ++i)
318 sum.addProduct(left[i], right[i]);
319 return sum.value();
320}
double schemeIProduct(const Eigen::MatrixBase< Left > &left, const Eigen::MatrixBase< Right > &right)
Definition OzakiScheme.h:38
bool tryCertifiedProduct(const double *left, const double *right, int length, double &result)
double schemeIIProductRaw(const double *left, const double *right, int length)

◆ evaluateStoredProducts()

void gpr::linalg::evaluateStoredProducts ( const StoredProduct * products,
int count,
ProductMode mode,
double * values )

Definition at line 170 of file PredictProduct.cpp.

172{
173 if (count < 0 || (count > 0 && (products == nullptr || values == nullptr)))
174 throw std::invalid_argument("invalid product batch");
175 if (count == 0) return;
176 for (int i = 0; i < count; ++i) {
177 const auto& p = products[i];
178 if (p.length < 0 || (p.length > 0 && (!p.left || !p.right)))
179 throw std::invalid_argument("invalid operands in product batch");
180 }
181 if (mode == ProductMode::KernelFloat) {
182 // An empty batch has nothing for the device; its products are zero
183 // whether or not the library is present.
184 bool any_terms = false;
185 for (int i = 0; i < count; ++i)
186 any_terms = any_terms || products[i].length > 0;
187 if (!any_terms) {
188 std::fill(values, values + count, 0.0);
189 return;
190 }
191 bool exceptional = false;
192 for (int i = 0; i < count; ++i) {
193 if (products[i].length <= 0) continue;
194 double native = 0.0;
195 if (nativeBinary64Fallback(products[i].left, products[i].right,
196 products[i].length, native))
197 exceptional = true;
198 }
199 if (!exceptional)
200 kernelFloatProducts(products, count, values);
201 else {
202 for (int i = 0; i < count; ++i)
203 values[i] =
204 evaluateStoredProduct(products[i].left, products[i].right,
205 products[i].length, mode);
206 }
207 } else {
208 for (int i = 0; i < count; ++i)
209 values[i] = evaluateStoredProduct(
210 products[i].left, products[i].right, products[i].length, mode);
211 }
212}

◆ exact_sum_bcast() [1/2]

void gpr::linalg::exact_sum_bcast ( ExactSum * sums,
int count,
const MpiContext & context )
inline

Replace each accumulator by the exact sum over the process group and replicate the result. Digits are integers, so the reduction is associative: the outcome does not depend on the rank count, the reduction tree or the way the addends were split over ranks.

Definition at line 155 of file MpiCollectives.h.

157{
158 if (count <= 0 || context.nprocs == 1) return;
159#if defined(GPR_HAVE_MPI) || defined(GPR_LINALG_SCALAPACK)
160 constexpr int kDigits = ExactSum::kLimbs;
161 std::vector<std::int64_t> digits(static_cast<std::size_t>(count) * kDigits);
162 std::vector<double> nonfinite(static_cast<std::size_t>(count));
163 for (int i = 0; i < count; ++i) {
164 sums[i].normalize();
165 std::copy_n(sums[i].limbs(), kDigits,
166 digits.data() + static_cast<std::size_t>(i) * kDigits);
167 nonfinite[static_cast<std::size_t>(i)] = sums[i].nonfinite();
168 }
169 MPI_Allreduce(MPI_IN_PLACE, digits.data(), static_cast<int>(digits.size()),
170 MPI_INT64_T, MPI_SUM, context.comm);
171 MPI_Allreduce(MPI_IN_PLACE, nonfinite.data(), count, MPI_DOUBLE, MPI_SUM,
172 context.comm);
173 for (int i = 0; i < count; ++i) {
174 sums[i].assignLimbs(digits.data() +
175 static_cast<std::size_t>(i) * kDigits);
176 sums[i].setNonfinite(nonfinite[static_cast<std::size_t>(i)]);
177 }
178#else
179 (void)sums;
180 throw std::logic_error("distributed reduction requires MPI");
181#endif
182}
void assignLimbs(const std::int64_t *digits) noexcept
Definition ExactSum.h:138
void setNonfinite(double value) noexcept
Definition ExactSum.h:184
static constexpr int kLimbs
Definition ExactSum.h:41
void normalize() noexcept
Definition ExactSum.h:159

◆ exact_sum_bcast() [2/2]

void gpr::linalg::exact_sum_bcast ( ExactSum * sums,
int count,
DistributedState & st = DistributedState::instance() )
inline

Definition at line 104 of file ScalapackBackend.h.

106{
107 if (count <= 0 || st.nprocs() == 1) return;
108 exact_sum_bcast(sums, count, st.communication()->view());
109}

◆ exceedsLp64() [1/2]

bool gpr::linalg::exceedsLp64 ( const int * desc,
int nprow,
int npcol )
inlinenoexcept

True when an LP64 ScaLAPACK routine on this descriptor would form an element offset past 2^31 - 1 on some process of the grid. Every process that passes the same descriptor fields gets the same answer, except where processes pass different leading dimensions; the descriptors DistributedState builds use max(1, local rows), whose largest value is the source process's row count, and give the same answer everywhere.

Definition at line 151 of file Lp64Limits.h.

152{
153 return largestLocalEntries(desc, nprow, npcol) > lp64IndexLimit();
154}
std::int64_t lp64IndexLimit() noexcept
Definition Lp64Limits.h:120
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

◆ exceedsLp64() [2/2]

bool gpr::linalg::exceedsLp64 ( std::int64_t count)
inlinenoexcept

True when an element count or workspace size does not fit LP64 INTEGER.

Definition at line 157 of file Lp64Limits.h.

158{
159 return count > lp64IndexLimit();
160}

◆ executionKindName()

const char * gpr::linalg::executionKindName ( ExecutionKind kind)
nodiscardconstexprnoexcept

Definition at line 87 of file BackendInterface.h.

89{
90 switch (kind) {
92 return "serial";
94 return "host-threads";
96 return "cuda";
98 return "hip";
100 return "sycl";
101 }
102 return "unknown";
103}

◆ factor_inverse_lower()

bool gpr::linalg::factor_inverse_lower ( const EigenMatrix & L,
int n,
std::vector< double > & inverse,
int * desc,
DistributedState & st )
inline

Lower triangle of C^{-1}, in the layout of the cached factor of order n (L, when not empty, replaces the cache first). The reproducible factorization forms it with the tile-ordered inverse, whose bits do not depend on the grid; the library factorization uses pdpotri. The inverse costs about 2n^3/3, against 2n^3 for substitutions on n columns. It is returned, not cached. Returns false when the library inverse fails.

Definition at line 1644 of file ScalapackBackend.h.

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}
void cache_U(std::vector< double > U)
const double * cached_U() const
bool has_cached_U() const noexcept
std::vector< double > transposeFactor(DistributedState &st, const double *L, const int *desc, int n, std::int64_t batch_entries=0)

◆ fitsRankShare() [1/2]

bool gpr::linalg::fitsRankShare ( std::int64_t needed,
AvailableMemory available,
int node_ranks )
constexprnoexcept

Definition at line 130 of file MemoryBudget.h.

132{
133 return !available || needed <= *available / std::max(1, node_ranks);
134}

◆ fitsRankShare() [2/2]

bool gpr::linalg::fitsRankShare ( std::int64_t needed,
std::int64_t available,
int node_ranks )
constexprnoexcept

True when needed bytes fit this rank's share of available bytes split evenly over the ranks of the node. Unknown availability (zero) fits.

Definition at line 138 of file MemoryBudget.h.

140{
141 return available <= 0 || needed <= available / std::max(1, node_ranks);
142}

◆ forward_solve() [1/2]

Eigen::VectorXd gpr::linalg::forward_solve ( const EigenMatrix & L,
const Eigen::VectorXd & b )
inline

Forward triangular solve with vector RHS (BLAS equivalent: dtrsv).

Solves \( L\,x = b \) where L is lower-triangular.

Parameters
[in]LLower-triangular matrix (e.g. from cholesky()).
[in]bRight-hand side vector.
Returns
Solution vector \( x = L^{-1} b \).

Definition at line 358 of file CusolverBackend.h.

360{
362 const int n = static_cast<int>(L.rows());
363 auto& state = detail::DeviceState::instance();
364 auto& cblas = detail::CublasLib::instance();
365
366 state.ensureCapacity(n);
367 detail::h2d(state.d_L, L.data(), static_cast<size_t>(n) * n);
368 double* d_L_ptr = state.d_L;
369
370 detail::DevBuf d_x(n);
371 detail::h2d(d_x, b.data(), n);
372
373 detail::check_cublas(
374 cblas.cublasDtrsv(detail::cublas_handle(), CUBLAS_FILL_MODE_LOWER,
375 CUBLAS_OP_N, CUBLAS_DIAG_NON_UNIT, n, d_L_ptr, n, d_x,
376 1),
377 "dtrsv fwd");
378
379 Eigen::VectorXd x(n);
380 detail::d2h(x.data(), d_x, n);
381 return x;
382}
static constexpr int CUBLAS_OP_N

◆ forward_solve() [2/2]

Eigen::VectorXd gpr::linalg::forward_solve ( const EigenMatrix & L,
const Eigen::VectorXd & b,
DistributedState & st = DistributedState::instance() )
inline

Definition at line 1488 of file ScalapackBackend.h.

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}

◆ forward_solve_mat() [1/2]

EigenMatrix gpr::linalg::forward_solve_mat ( const EigenMatrix & L,
const EigenMatrix & B )
inline

Forward triangular solve with matrix RHS (BLAS equivalent: dtrsm).

Solves \( L\,X = B \) where L is lower-triangular.

Parameters
[in]LLower-triangular matrix.
[in]BRight-hand side matrix.
Returns
Solution matrix \( X = L^{-1} B \).

Definition at line 410 of file CusolverBackend.h.

411{
413 const int m = static_cast<int>(L.rows());
414 const int n = static_cast<int>(B.cols());
415 auto& state = detail::DeviceState::instance();
416 auto& cblas = detail::CublasLib::instance();
417
418 state.ensureCapacity(m);
419 detail::h2d(state.d_L, L.data(), static_cast<size_t>(m) * m);
420 double* d_L_ptr = state.d_L;
421
422 detail::DevBuf d_X(m * n);
423 detail::h2d(d_X, B.data(), m * n);
424
425 const double alpha = 1.0;
426 detail::check_cublas(
427 cblas.cublasDtrsm(detail::cublas_handle(), CUBLAS_SIDE_LEFT,
429 CUBLAS_DIAG_NON_UNIT, m, n, &alpha, d_L_ptr, m, d_X,
430 m),
431 "dtrsm");
432
433 EigenMatrix X(m, n);
434 detail::d2h(X.data(), d_X, m * n);
435 return X;
436}

◆ forward_solve_mat() [2/2]

EigenMatrix gpr::linalg::forward_solve_mat ( const EigenMatrix & L,
const EigenMatrix & B,
DistributedState & st = DistributedState::instance() )
inline

Definition at line 460 of file ScalapackBackend.h.

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}

◆ forward_solve_mat_bilinear_distributed()

EigenMatrix gpr::linalg::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 )
inline

Distributed bilinear form M = (L^{-1} KK)^T (L^{-1} KK).

Given the lower Cholesky factor L of the training kernel K (m x m, scattered into the DistributedState cache on first use, reused on subsequent calls) and a distributed cross-covariance buffer KK_dist (m x ncols, block-cyclic with descriptor desc_kk), returns the small ncols x ncols matrix M = (L^{-1} KK)^T (L^{-1} KK).

Used by GaussianProcessRegression::calculateObservationPosteriorCovariance to compute the posterior covariance between joint query channels: K_post(i, j) = K_qq(i, j) - M(i, j), since K^{-1} = L^{-T} L^{-1} so KK^T K^{-1} KK = (L^{-1} KK)^T (L^{-1} KK).

The factor, triangular solve and symmetric product stay distributed. Only the ncols x ncols result is gathered for the caller.

Definition at line 1256 of file ScalapackBackend.h.

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}
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)
Eigen::MatrixXd gramTiles(const Eigen::MatrixXd &x, int nb)

◆ forward_solve_mat_colwise_squared_norm() [1/2]

Eigen::VectorXd gpr::linalg::forward_solve_mat_colwise_squared_norm ( const EigenMatrix & L,
const EigenMatrix & B )
inline

Forward triangular solve followed by columnwise squared norms.

Solves \( L\,X = B \) where L is lower-triangular and returns the vector with entries \( \sum_i X_{ij}^2 \).

Parameters
[in]LLower-triangular matrix.
[in]BRight-hand side matrix.
Returns
Columnwise squared norms of \( X = L^{-1} B \).

Definition at line 466 of file CusolverBackend.h.

468{
469 const EigenMatrix X = forward_solve_mat(L, B);
470 return X.colwise().squaredNorm().transpose();
471}

◆ forward_solve_mat_colwise_squared_norm() [2/2]

Eigen::VectorXd gpr::linalg::forward_solve_mat_colwise_squared_norm ( const EigenMatrix & L,
const EigenMatrix & B,
DistributedState & st = DistributedState::instance() )
inline

Definition at line 1052 of file ScalapackBackend.h.

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}

◆ forward_solve_mat_colwise_squared_norm_distributed()

Eigen::VectorXd gpr::linalg::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() )
inline

Definition at line 1337 of file ScalapackBackend.h.

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}

◆ hostAccessible()

bool gpr::linalg::hostAccessible ( MemoryKind kind)
nodiscardconstexprnoexcept

Definition at line 67 of file BackendInterface.h.

68{
69 return kind == MemoryKind::Host;
70}

◆ jacobiDavidsonCorrection()

bool gpr::linalg::jacobiDavidsonCorrection ( const Eigen::MatrixXd & A,
const double theta,
const Eigen::VectorXd & residual,
const Eigen::VectorXd & ritz_vector,
Eigen::VectorXd & correction,
double * alpha = nullptr )
inline

Definition at line 61 of file RayleighRitz.h.

67{
68 const Eigen::Index n = A.rows();
69 correction.resize(0);
70 if (n <= 0 || A.cols() != n || residual.size() != n ||
71 ritz_vector.size() != n || !A.allFinite() || !residual.allFinite() ||
72 !ritz_vector.allFinite() || !std::isfinite(theta))
73 return false;
74
75 const double u_norm = ritz_vector.norm();
76 if (u_norm <= detail::orthogonalizationTolerance(n)) return false;
77 const Eigen::VectorXd u = ritz_vector / u_norm;
78
79 Eigen::MatrixXd kkt = Eigen::MatrixXd::Zero(n + 1, n + 1);
80 kkt.topLeftCorner(n, n) = A - theta * Eigen::MatrixXd::Identity(n, n);
81 kkt.topRightCorner(n, 1) = u;
82 kkt.bottomLeftCorner(1, n) = u.transpose();
83
84 Eigen::VectorXd rhs = Eigen::VectorXd::Zero(n + 1);
85 rhs.head(n) = -residual;
86
87 Eigen::FullPivLU<Eigen::MatrixXd> lu(kkt);
88 const Eigen::VectorXd solution = lu.solve(rhs);
89 if (solution.size() != n + 1 || !solution.allFinite()) return false;
90
91 const double backward_scale =
92 std::max({1.0, rhs.norm(), kkt.norm() * solution.norm()});
93 const double backward_error = (kkt * solution - rhs).norm();
94 const double backward_tolerance =
95 detail::orthogonalizationTolerance(n + 1) * backward_scale;
96 if (backward_error > backward_tolerance) return false;
97
98 correction = solution.head(n);
99 if (alpha != nullptr) *alpha = solution(n);
100 return correction.allFinite();
101}

◆ kernelFloatProductAvailable()

bool gpr::linalg::kernelFloatProductAvailable ( )

Definition at line 165 of file PredictProduct.cpp.

166{
167 return kernelFloatLibrary() != nullptr;
168}

◆ kokkosHostExecutionMemory()

bool gpr::linalg::kokkosHostExecutionMemory ( )
nodiscardnoexcept

True when the Kokkos execution memory is the host. A non-Kokkos build does not call this. Host memory is already the execution space, so a factor that lives in an Eigen matrix does not cross a boundary.

Definition at line 173 of file KokkosBackend.cpp.

174{
175 return std::is_same_v<Kokkos::DefaultExecutionSpace::memory_space,
176 Kokkos::HostSpace>;
177}

◆ kokkosTransferAuditStats()

KokkosTransferAuditStats gpr::linalg::kokkosTransferAuditStats ( )
nodiscardnoexcept

Definition at line 81 of file KokkosBackend.cpp.

82{
83 auto& audit = transfer_audit();
85 result.host_to_device.calls =
86 audit.h2d_calls.load(std::memory_order_relaxed);
87 result.host_to_device.bytes =
88 audit.h2d_bytes.load(std::memory_order_relaxed);
89 result.device_to_host.calls =
90 audit.d2h_calls.load(std::memory_order_relaxed);
91 result.device_to_host.bytes =
92 audit.d2h_bytes.load(std::memory_order_relaxed);
93 result.device_to_device.calls =
94 audit.d2d_calls.load(std::memory_order_relaxed);
95 result.device_to_device.bytes =
96 audit.d2d_bytes.load(std::memory_order_relaxed);
97 result.host_to_host.calls = audit.h2h_calls.load(std::memory_order_relaxed);
98 result.host_to_host.bytes = audit.h2h_bytes.load(std::memory_order_relaxed);
100 audit.to_exec_calls.load(std::memory_order_relaxed);
102 audit.to_exec_bytes.load(std::memory_order_relaxed);
103 result.boundary_to_host.calls =
104 audit.to_host_calls.load(std::memory_order_relaxed);
105 result.boundary_to_host.bytes =
106 audit.to_host_bytes.load(std::memory_order_relaxed);
107 result.mirror_create_calls =
108 audit.mirror_calls.load(std::memory_order_relaxed);
109 result.mirror_create_bytes =
110 audit.mirror_bytes.load(std::memory_order_relaxed);
112 audit.max_to_exec.load(std::memory_order_relaxed);
113 result.max_boundary_to_host =
114 audit.max_to_host.load(std::memory_order_relaxed);
115 return result;
116}
KokkosTransferDirectionStats device_to_device
KokkosTransferDirectionStats host_to_host
KokkosTransferDirectionStats device_to_host
KokkosTransferDirectionStats boundary_to_execution
KokkosTransferDirectionStats host_to_device
KokkosTransferDirectionStats boundary_to_host

◆ largestLocalEntries() [1/2]

std::int64_t gpr::linalg::largestLocalEntries ( const int * desc,
int nprow,
int npcol )
constexprnoexcept

largestLocalEntries for a ScaLAPACK descriptor on an nprow x npcol grid. The leading dimension field is also taken into account, so a descriptor with a padded leading dimension is measured by the array it describes.

Definition at line 98 of file Lp64Limits.h.

100{
101 const std::int64_t by_layout = largestLocalEntries(
102 desc[kDescM], desc[kDescN], desc[kDescMb], desc[kDescNb],
103 desc[kDescRsrc], desc[kDescCsrc], nprow, npcol);
104 const std::int64_t cols = blockCyclicLocalExtent(
105 desc[kDescN], desc[kDescNb], desc[kDescCsrc], desc[kDescCsrc], npcol);
106 return std::max(by_layout,
107 static_cast<std::int64_t>(desc[kDescLld]) * cols);
108}
constexpr std::int64_t blockCyclicLocalExtent(std::int64_t n, std::int64_t nb, std::int64_t iproc, std::int64_t isrc, std::int64_t nprocs) noexcept
Definition Lp64Limits.h:55

◆ largestLocalEntries() [2/2]

std::int64_t gpr::linalg::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 )
constexprnoexcept

Entries of the largest local array (leading dimension times local columns) any process of an nprow x npcol grid holds for an m x n matrix in mb x nb blocks whose first block sits on process (rsrc, csrc).

The source process owns the most rows and the most columns: it receives every complete round of blocks plus the first leftover block. The leading dimension is taken as max(1, local rows) of that process, the convention of every descriptor DistributedState builds; a descriptor whose leading dimension exceeds the largest local row count on some process is outside this bound (see exceedsLp64).

Definition at line 84 of file Lp64Limits.h.

89{
90 const std::int64_t rows = blockCyclicLocalExtent(m, mb, rsrc, rsrc, nprow);
91 const std::int64_t cols = blockCyclicLocalExtent(n, nb, csrc, csrc, npcol);
92 return std::max<std::int64_t>(1, rows) * cols;
93}

◆ librarySerialKernels()

bool gpr::linalg::librarySerialKernels ( )
nodiscardnoexcept

Definition at line 159 of file LinalgThreads.cpp.

160{
161 return library_serial_kernels.load(std::memory_order_relaxed);
162}

◆ log_det_cholesky() [1/2]

double gpr::linalg::log_det_cholesky ( const EigenMatrix & L)
inline

Half log-determinant from Cholesky factor.

Computes \( \sum_i \ln L_{ii} = \tfrac{1}{2}\ln|C| \).

Parameters
[in]LLower-triangular Cholesky factor.
Returns
The half log-determinant.

Definition at line 526 of file CusolverBackend.h.

527{
528 const int n = static_cast<int>(L.rows());
529 double sum = 0.0;
530 for (int i = 0; i < n; ++i)
531 sum += std::log(L(i, i));
532 return sum;
533}

◆ log_det_cholesky() [2/2]

double gpr::linalg::log_det_cholesky ( const EigenMatrix & L,
DistributedState & st = DistributedState::instance() )
inline

Definition at line 2026 of file ScalapackBackend.h.

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}
double log(double x) noexcept

◆ lowestEigenpairRayleighRitz()

template<class Apply>
RayleighRitzResult gpr::linalg::lowestEigenpairRayleighRitz ( const Eigen::Index dimension,
Apply && apply,
const Eigen::VectorXd & seed,
RayleighRitzOptions options )

Definition at line 104 of file RayleighRitz.h.

108{
109 RayleighRitzResult result;
110 result.eigenvector =
111 Eigen::VectorXd::Zero(std::max<Eigen::Index>(dimension, 0));
112 if (dimension <= 0) return result;
113
114 Eigen::Index max_subspace = options.max_subspace;
115 if (max_subspace <= 0) max_subspace = dimension;
116 max_subspace = std::clamp<Eigen::Index>(max_subspace, 1, dimension);
117
118 const double orth_tol = detail::orthogonalizationTolerance(dimension);
119 std::vector<Eigen::VectorXd> basis;
120 std::vector<Eigen::VectorXd> applied_basis;
121 basis.reserve(static_cast<std::size_t>(max_subspace));
122 applied_basis.reserve(static_cast<std::size_t>(max_subspace));
123 Eigen::VectorXd current_residual = Eigen::VectorXd::Zero(dimension);
124
125 auto append_basis = [&](Eigen::VectorXd q) -> bool {
126 if (q.size() != dimension || !q.allFinite()) return false;
127 for (const Eigen::VectorXd& v: basis)
128 q -= v.dot(q) * v;
129 const double norm = q.norm();
130 if (norm <= orth_tol) return false;
131 basis.push_back(q / norm);
132 return true;
133 };
134
135 auto apply_pending_vectors = [&]() -> bool {
136 while (applied_basis.size() < basis.size()) {
137 Eigen::VectorXd Av;
138 if (!apply(basis[applied_basis.size()], Av) ||
139 Av.size() != dimension || !Av.allFinite())
140 return false;
141 applied_basis.push_back(std::move(Av));
142 ++result.matvecs;
143 }
144 return true;
145 };
146
147 auto solve_current_subspace = [&]() -> bool {
148 if (!apply_pending_vectors()) return false;
149 const Eigen::Index k_dim = static_cast<Eigen::Index>(basis.size());
150 if (k_dim <= 0) return false;
151
152 Eigen::MatrixXd T = Eigen::MatrixXd::Zero(k_dim, k_dim);
153 for (Eigen::Index i = 0; i < k_dim; ++i) {
154 for (Eigen::Index j = 0; j <= i; ++j) {
155 const double value = basis[static_cast<std::size_t>(i)].dot(
156 applied_basis[static_cast<std::size_t>(j)]);
157 T(i, j) = value;
158 T(j, i) = value;
159 }
160 }
161 T = (0.5 * (T + T.transpose())).eval();
162
163 Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es(T);
164 if (es.info() != Eigen::Success || es.eigenvectors().cols() == 0)
165 return false;
166
167 const Eigen::VectorXd y = es.eigenvectors().col(0);
168 result.eigenvalue = es.eigenvalues()(0);
169 Eigen::VectorXd mode = Eigen::VectorXd::Zero(dimension);
170 Eigen::VectorXd A_mode = Eigen::VectorXd::Zero(dimension);
171 for (Eigen::Index i = 0; i < k_dim; ++i) {
172 const auto idx = static_cast<std::size_t>(i);
173 mode += y(i) * basis[idx];
174 A_mode += y(i) * applied_basis[idx];
175 }
176
177 const double mode_norm = mode.norm();
178 if (mode_norm <= orth_tol || !std::isfinite(result.eigenvalue))
179 return false;
180 result.eigenvector = mode / mode_norm;
181 A_mode /= mode_norm;
182
183 Eigen::VectorXd residual =
184 A_mode - result.eigenvalue * result.eigenvector;
185 for (const Eigen::VectorXd& v: basis)
186 residual -= v.dot(residual) * v;
187 result.residual_norm = residual.norm();
188 result.basis_size = k_dim;
189 current_residual = residual;
190
191 double residual_tol = 0.0;
192 if (std::isfinite(options.relative_residual_tolerance) &&
193 options.relative_residual_tolerance > 0.0) {
194 residual_tol = options.relative_residual_tolerance *
195 std::max(1.0, std::abs(result.eigenvalue));
196 }
197 if (std::isfinite(options.eigenvalue_relative_residual_tolerance) &&
199 residual_tol = std::max(
200 residual_tol, options.eigenvalue_relative_residual_tolerance *
201 std::abs(result.eigenvalue));
202 }
203 if (std::isfinite(options.separation_lower_bound) &&
204 options.separation_lower_bound > 0.0 &&
205 std::isfinite(options.eigenvector_angle_tolerance) &&
206 options.eigenvector_angle_tolerance > 0.0) {
207 residual_tol =
208 std::max(residual_tol, options.eigenvector_angle_tolerance *
209 options.separation_lower_bound);
210 }
211 if (k_dim > 1 && std::isfinite(options.eigenvector_angle_tolerance) &&
212 options.eigenvector_angle_tolerance > 0.0) {
213 const double ritz_gap = es.eigenvalues()(1) - result.eigenvalue;
214 if (std::isfinite(ritz_gap) && ritz_gap > 0.0)
215 residual_tol =
216 std::max(residual_tol,
217 options.eigenvector_angle_tolerance * ritz_gap);
218 }
219
220 result.converged = result.residual_norm <= residual_tol;
221 return true;
222 };
223
224 if (!append_basis(seed)) {
225 Eigen::VectorXd unit = Eigen::VectorXd::Zero(dimension);
226 unit(0) = 1.0;
227 if (!append_basis(unit)) return result;
228 }
229
230 while (static_cast<Eigen::Index>(basis.size()) <= max_subspace) {
231 if (!solve_current_subspace()) return result;
232 if (result.converged) return result;
233 if (static_cast<Eigen::Index>(basis.size()) >= max_subspace) break;
234 if (!append_basis(current_residual)) break;
235 }
236
237 if (!options.allow_full_subspace_fallback) return result;
238
239 basis.reserve(static_cast<std::size_t>(dimension));
240 applied_basis.reserve(static_cast<std::size_t>(dimension));
241 for (Eigen::Index i = 0;
242 i < dimension && static_cast<Eigen::Index>(basis.size()) < dimension;
243 ++i) {
244 Eigen::VectorXd unit = Eigen::VectorXd::Zero(dimension);
245 unit(i) = 1.0;
246 append_basis(unit);
247 }
248 if (static_cast<Eigen::Index>(basis.size()) != dimension) return result;
249
250 if (!solve_current_subspace()) return result;
251 result.converged = result.eigenvector.size() == dimension &&
252 result.eigenvector.allFinite() &&
253 std::isfinite(result.eigenvalue);
254 return result;
255}

◆ lp64IndexLimit()

std::int64_t gpr::linalg::lp64IndexLimit ( )
inlinenoexcept

Definition at line 120 of file Lp64Limits.h.

121{
122 return lp64IndexLimitStore().load(std::memory_order_relaxed);
123}
std::atomic< std::int64_t > & lp64IndexLimitStore() noexcept
Definition Lp64Limits.h:114

◆ lp64IndexLimitStore()

std::atomic< std::int64_t > & gpr::linalg::lp64IndexLimitStore ( )
inlinenoexcept

Limit the routing decision compares against: kLp64IndexLimit, unless a ScopedLp64IndexLimit lowers it so tests reach the routed paths at small orders. The value is the inline copy of the translation unit that decides.

Definition at line 114 of file Lp64Limits.h.

115{
116 static std::atomic<std::int64_t> limit{kLp64IndexLimit};
117 return limit;
118}
constexpr std::int64_t kLp64IndexLimit
Largest element offset an LP64 ScaLAPACK routine forms without overflow.
Definition Lp64Limits.h:35

◆ lp64Workspace()

int gpr::linalg::lp64Workspace ( double query,
const char * routine,
const DistributedState & st )
inline

LP64 INTEGER workspace length from the ScaLAPACK workspace query result query. The largest query over the grid decides, so every process either proceeds or throws std::length_error naming routine. Collective.

Definition at line 245 of file ScalapackBackend.h.

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}

◆ memoryKindName()

const char * gpr::linalg::memoryKindName ( MemoryKind kind)
nodiscardconstexprnoexcept

Definition at line 72 of file BackendInterface.h.

73{
74 switch (kind) {
76 return "host";
78 return "cuda";
80 return "hip";
82 return "sycl";
83 }
84 return "unknown";
85}

◆ modularProductSchemeII()

uint32_t gpr::linalg::modularProductSchemeII ( const SchemeIIIntegers & scaled,
uint32_t modulus )
inline

Definition at line 290 of file OzakiSchemeII.inl.

292{
293 uint64_t acc = 0;
294 for (int i = 0; i < scaled.length; ++i) {
295 if (scaled.left_sig[i] == 0 || scaled.right_sig[i] == 0) continue;
296 const int shift =
297 scaled.left_exp[i] + scaled.right_exp[i] - scaled.align_exp;
298 if (shift < 0) continue;
299 const uint32_t left = mod_i64(scaled.left_sig[i], modulus);
300 const uint32_t right = mod_i64(scaled.right_sig[i], modulus);
301 uint32_t term = mul_mod(left, right, modulus);
302 term = mul_mod(term, pow2_mod(shift, modulus), modulus);
303 acc += term;
304 if (acc >= modulus) acc -= modulus;
305 }
306 return static_cast<uint32_t>(acc);
307}
int64_t right_sig[kMaxTerms]
int64_t left_sig[kMaxTerms]

◆ observation_tile_lower_trace_colmajor_unchecked()

double gpr::linalg::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 )
inline

Definition at line 1810 of file ScalapackBackend.h.

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}

◆ ordered_sum_bcast() [1/2]

void gpr::linalg::ordered_sum_bcast ( double * data,
int count,
const MpiContext & context )
inline

Sum overlapping contributions in rank order and replicate the result. Only the supplied process group participates. Local views enter no MPI.

Definition at line 63 of file MpiCollectives.h.

65{
66 if (count <= 0 || context.nprocs == 1) return;
67#if defined(GPR_HAVE_MPI) || defined(GPR_LINALG_SCALAPACK)
68
69 if (count <= 0) return;
70
71 if (context.nprocs == 1) return;
72
73#ifdef GPR_NATIVE_REDUCTIONS
74 MPI_Allreduce(MPI_IN_PLACE, data, count, MPI_DOUBLE, MPI_SUM, context.comm);
75#else
76 std::vector<double> gathered;
77 if ((context.rank == 0))
78 gathered.resize(static_cast<size_t>(count) *
79 static_cast<size_t>(context.nprocs));
80
81 MPI_Gather(data, count, MPI_DOUBLE,
82 (context.rank == 0) ? gathered.data() : nullptr, count,
83 MPI_DOUBLE, 0, context.comm);
84
85 if ((context.rank == 0)) {
86 for (int i = 0; i < count; ++i) {
87 long double accum = 0.0L;
88 for (int rank = 0; rank < context.nprocs; ++rank) {
89 accum += static_cast<long double>(
90 gathered[static_cast<size_t>(rank) * count + i]);
91 }
92 data[i] = static_cast<double>(accum);
93 }
94 }
95
96 MPI_Bcast(data, count, MPI_DOUBLE, 0, context.comm);
97#endif
98
99#else
100 (void)data;
101 throw std::logic_error("distributed reduction requires MPI");
102#endif
103}

◆ ordered_sum_bcast() [2/2]

void gpr::linalg::ordered_sum_bcast ( double * data,
int count,
DistributedState & st = DistributedState::instance() )
inline

Definition at line 96 of file ScalapackBackend.h.

99{
100 if (count <= 0 || st.nprocs() == 1) return;
101 ordered_sum_bcast(data, count, st.communication()->view());
102}

◆ parallelFor()

template<class F>
void gpr::linalg::parallelFor ( long count,
F && fn )
inline

parallelFor(count, fn): see TilePool::run.

Definition at line 277 of file TileParallel.h.

278{
279 TilePool::instance().run(count, std::forward<F>(fn));
280}
void run(long count, F &&fn)
static TilePool & instance()

◆ parseDistributedFactorization()

std::optional< DistributedFactorization > gpr::linalg::parseDistributedFactorization ( std::string_view name)
nodiscardnoexcept

"reproducible" or "library"; anything else gives no value.

Definition at line 111 of file LinalgThreads.cpp.

113{
114 if (name == "reproducible") return DistributedFactorization::Reproducible;
115 if (name == "library") return DistributedFactorization::Library;
116 return std::nullopt;
117}

◆ pcg_dot()

double gpr::linalg::pcg_dot ( const Eigen::VectorXd & a,
const Eigen::VectorXd & b )
inlinenodiscard

Inner product over the replicated CG state. The solver runs the same loop on every rank with x, r, p, z held identically replicated, and apply_A returns an already-assembled (replicated) matvec, so each rank's long-double dot is the full inner product. No cross-rank reduction is taken: summing the P identical replicated copies would scale every dot by P (harmless in the alpha/beta ratios) but the long-double accumulation of P identical doubles rounds differently per rank count, so a reduction here makes the CG trajectory match only within a fixed-P group. Returning the local replicated dot is bit-identical at every rank count.

Definition at line 71 of file IterativeSolver.h.

73{
74 assert(a.size() == b.size());
75 const Eigen::Index n = a.size();
76 long double accum = 0.0L;
77 for (Eigen::Index i = 0; i < n; ++i) {
78 accum +=
79 static_cast<long double>(a(i)) * static_cast<long double>(b(i));
80 }
81 return static_cast<double>(accum);
82}

◆ preconditioned_cg()

PCGResult gpr::linalg::preconditioned_cg ( const std::function< Eigen::VectorXd(const Eigen::VectorXd &)> & apply_A,
const std::function< Eigen::VectorXd(const Eigen::VectorXd &)> & apply_M_inv,
const Eigen::VectorXd & b,
const PCGSettings & settings = {} )
inline

Preconditioned conjugate gradient on a SPD matrix A whose action on a vector is given by apply_A. The preconditioner inverse is apply_M_inv. Both are evaluated once per CG iteration.

The full CG state (x, r, p, z) is replicated on every rank; apply_A returns a replicated matvec, so the inner products inside the loop are taken locally without MPI. Each iteration performs:

  • 1 matvec A @ p
  • 1 precondit z = M^{-1} r
  • 3 inner prod p^T A p, r^T z, ||r||^2 (latter for tolerance check)
  • 2 axpy x += alpha p; r -= alpha A p
  • 1 vec sum p = z + beta p

pcg_dot accumulates in long double over the replicated vector, so the floating-point trajectory of CG is bit-identical at every rank count when the matvec and preconditioner are also bit-identical.

Definition at line 101 of file IterativeSolver.h.

104 {})
105{
106 const Eigen::Index n = b.size();
107 const int max_iter = settings.max_iterations > 0 ? settings.max_iterations
108 : static_cast<int>(2 * n);
109
110 Eigen::VectorXd x = Eigen::VectorXd::Zero(n);
111 Eigen::VectorXd r = b; // r_0 = b - A x_0 = b
112 Eigen::VectorXd z = apply_M_inv(r);
113 Eigen::VectorXd p = z;
114
115 const double b_norm = b.stableNorm();
116 const double tolerance = settings.rtol * b_norm;
117
118 double rz_old = pcg_dot(r, z);
119
120 PCGResult result;
121 result.iterations = 0;
122 result.converged = false;
123 result.final_residual = b_norm;
124
125 if (b_norm == 0.0) {
126 result.x = x;
127 result.converged = true;
128 result.final_residual = 0.0;
129 return result;
130 }
131
132 const auto finish = [&](int iterations) {
133 result.x = x;
134 result.iterations = iterations;
135 result.final_residual = (b - apply_A(x)).stableNorm();
136 result.converged = std::isfinite(tolerance) && tolerance >= 0.0 &&
137 std::isfinite(result.final_residual) &&
138 result.final_residual <= tolerance;
139 return result;
140 };
141 if (!std::isfinite(b_norm) || !std::isfinite(tolerance) ||
142 tolerance < 0.0 || !(rz_old > 0.0) || !std::isfinite(rz_old))
143 return finish(0);
144
145 for (int k = 0; k < max_iter; ++k) {
146 Eigen::VectorXd Ap = apply_A(p);
147 const double pAp = pcg_dot(p, Ap);
148 if (!(pAp > 0.0) || !std::isfinite(pAp)) {
149 // Loss of positive-definiteness. The matvec or the iteration
150 // hit a non-PD direction; bail out with the best-so-far x.
151 return finish(k);
152 }
153 const double alpha = rz_old / pAp;
154
155 x.noalias() += alpha * p;
156 r.noalias() -= alpha * Ap;
157
158 const double r_norm = r.stableNorm();
159 if (settings.log_progress) {
160 std::fprintf(stderr, " PCG iter %d: ||r||=%.6e\n", k + 1, r_norm);
161 }
162 if (r_norm <= tolerance) {
163 // Recurrence residuals accumulate rounding error independently
164 // of b - A x. Only an explicit product certifies convergence.
165 r = b - apply_A(x);
166 const double explicit_norm = r.stableNorm();
167 if (std::isfinite(explicit_norm) && explicit_norm <= tolerance) {
168 result.x = x;
169 result.iterations = k + 1;
170 result.final_residual = explicit_norm;
171 result.converged = true;
172 return result;
173 }
174 // Restart conjugacy from the corrected residual: directions
175 // generated by the drifted recurrence cannot be reused.
176 z = apply_M_inv(r);
177 rz_old = pcg_dot(r, z);
178 if (!(rz_old > 0.0) || !std::isfinite(rz_old)) return finish(k + 1);
179 p = z;
180 continue;
181 }
182
183 z = apply_M_inv(r);
184 const double rz_new = pcg_dot(r, z);
185 if (!(rz_new > 0.0) || !std::isfinite(rz_new)) return finish(k + 1);
186 const double beta = rz_new / rz_old;
187 p = z + beta * p;
188 rz_old = rz_new;
189 }
190
191 return finish(max_iter);
192}
double pcg_dot(const Eigen::VectorXd &a, const Eigen::VectorXd &b)
Panel finish(Real left, Real right, const Value &k, const Value &g, const Value &absolute)
double rtol
Relative residual tolerance.
int max_iterations
0 = use 2 * n as the iteration cap
bool log_progress
Emit per-iteration residual to stderr.

◆ productMode()

ProductMode gpr::linalg::productMode ( )
inline

Definition at line 19 of file CompensatedSum.h.

20{
21 const char* value = std::getenv("GPR_PREDICT_SUM");
22 if (value == nullptr || value[0] == '\0' ||
23 std::strcmp(value, "compensated") == 0) {
25 }
26 if (std::strcmp(value, "scheme1") == 0) return ProductMode::SchemeI;
27 if (std::strcmp(value, "scheme2") == 0) return ProductMode::SchemeII;
28 if (std::strcmp(value, "kernel_float") == 0)
31}

◆ rank_one_update_lower()

bool gpr::linalg::rank_one_update_lower ( EigenMatrix & lower,
const Eigen::VectorXd & vector )
inline

Factor L L^T + u u^T through orthogonal rotations of [L^T; u^T]. The base covariance and the update retain their separate rounding scales.

Definition at line 19 of file CholeskyUpdate.h.

21{
22 const Eigen::Index n = lower.rows();
23 if (n <= 0 || lower.cols() != n || vector.size() != n ||
24 !vector.allFinite())
25 return false;
26 if (vector.isZero(0.0)) return true;
27 Eigen::VectorXd update = vector;
28 for (Eigen::Index j = 0; j < n; ++j) {
29 const double diagonal = lower(j, j);
30 const double radius = std::hypot(diagonal, update(j));
31 if (!(diagonal > 0.0) || !std::isfinite(radius)) return false;
32 const double cosine = diagonal / radius;
33 const double sine = update(j) / radius;
34 lower(j, j) = radius;
35 for (Eigen::Index i = j + 1; i < n; ++i) {
36 const double value = lower(i, j);
37 const double tail = update(i);
38 lower(i, j) = std::fma(sine, tail, cosine * value);
39 update(i) = std::fma(-sine, value, cosine * tail);
40 }
41 }
42 return true;
43}

◆ refreshKernelTeam()

void gpr::linalg::refreshKernelTeam ( )

Recompute the default team from the requested kernel threads and the configured linalg threads: the larger of the two when a parallel runtime is built in. configureLinalgThreads calls this.

Definition at line 26 of file LocalExecutor.cpp.

27{
28 // The linalg count is the assembly team; --kernel-threads can widen it
29 // but its default of one must not shrink it.
30 int team = requested_kernel_threads.load(std::memory_order_relaxed);
32 team = std::max(team, configuredLinalgThreads());
33 default_concurrency.store(team, std::memory_order_relaxed);
34}
static bool parallelAvailable() noexcept

◆ replicate_owned_values()

void gpr::linalg::replicate_owned_values ( double * data,
std::size_t count,
const MpiContext & context )
inline

Replicate entries with exactly one owner and positive zero elsewhere. Integer OR preserves the owner's bits, including signed zero, without rounding or a rank-dependent floating-point reduction.

Definition at line 24 of file MpiCollectives.h.

26{
27 if (count == 0 || context.nprocs == 1) return;
28#if defined(GPR_HAVE_MPI) || defined(GPR_LINALG_SCALAPACK)
29 constexpr std::size_t panel_size = 131072;
30 std::vector<std::uint64_t> bits(std::min(count, panel_size));
31 for (std::size_t offset = 0; offset < count; offset += bits.size()) {
32 const auto length = std::min(bits.size(), count - offset);
33 for (std::size_t i = 0; i < length; ++i)
34 bits[i] = std::bit_cast<std::uint64_t>(data[offset + i]);
35 MPI_Allreduce(MPI_IN_PLACE, bits.data(), static_cast<int>(length),
36 MPI_UINT64_T, MPI_BOR, context.comm);
37 for (std::size_t i = 0; i < length; ++i)
38 data[offset + i] = std::bit_cast<double>(bits[i]);
39 }
40#else
41 (void)data;
42 throw std::logic_error("distributed replication requires MPI");
43#endif
44}

◆ requireCachedFactorSchurDiagonal()

void gpr::linalg::requireCachedFactorSchurDiagonal ( Eigen::VectorXd & diagonal,
const Eigen::VectorXd & prior,
int m,
DistributedState & st )
inline

requireStablePosteriorVariance over a Schur diagonal formed from the cached distributed factor. The diagonal is replicated, so every rank asks for the conditioning together or none does, and every rank throws together.

Definition at line 1199 of file ScalapackBackend.h.

1202{
1204 diagonal, prior, [&] { return cachedFactorSchurRelativeError(m, st); });
1205}
double cachedFactorSchurRelativeError(int m, 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

◆ requireRankShare() [1/2]

void gpr::linalg::requireRankShare ( const char * what,
std::int64_t needed,
AvailableMemory available,
int node_ranks )
inline

Throws std::runtime_error naming what, the bytes it needs per rank and this rank's share when needed does not fit fitsRankShare.

Definition at line 146 of file MemoryBudget.h.

148{
149 if (fitsRankShare(needed, available, node_ranks)) return;
150 const auto gib = [](std::int64_t bytes) {
151 char text[32];
152 std::snprintf(text, sizeof text, "%.1f GiB",
153 static_cast<double>(bytes) / (1024.0 * 1024.0 * 1024.0));
154 return std::string(text);
155 };
156 throw std::runtime_error(
157 std::string(what) + " needs " + gib(needed) + " per rank; " +
158 gib(*available / std::max(1, node_ranks)) + " is available per rank (" +
159 gib(*available) + " on the node over " + std::to_string(node_ranks) +
160 " ranks). Run on more nodes or with fewer ranks per node.");
161}
constexpr bool fitsRankShare(std::int64_t needed, AvailableMemory available, int node_ranks) noexcept

◆ requireRankShare() [2/2]

void gpr::linalg::requireRankShare ( const char * what,
std::int64_t needed,
std::int64_t available,
int node_ranks )
inline

Definition at line 163 of file MemoryBudget.h.

165{
166 requireRankShare(what, needed,
167 available > 0 ? AvailableMemory{available} : std::nullopt,
168 node_ranks);
169}
std::optional< std::int64_t > AvailableMemory
void requireRankShare(const char *what, std::int64_t needed, AvailableMemory available, int node_ranks)

◆ requireRebuildableDenseL()

void gpr::linalg::requireRebuildableDenseL ( const EigenMatrix & L,
int m,
const char * fn,
DistributedState & st = DistributedState::instance() )
inline

Definition at line 74 of file ScalapackBackend.h.

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}

◆ requireStablePosteriorVariance() [1/3]

void gpr::linalg::requireStablePosteriorVariance ( double & variance,
double signal_variance )
inline

Definition at line 141 of file ExactSchur.h.

143{
144 if (!acceptStablePosteriorVariance(variance, signal_variance))
146 "stable posterior variance is not finite and nonnegative");
147}
Raised when a stable posterior variance is not finite, is materially negative, or its operands do not...
Definition ExactSchur.h:57

◆ requireStablePosteriorVariance() [2/3]

void gpr::linalg::requireStablePosteriorVariance ( double & variance,
double signal_variance,
double relative_allowance )
inline

Accept one stable posterior variance or throw.

Exceptions
StableVarianceErrorwhen acceptStablePosteriorVariance rejects the value.

Definition at line 131 of file ExactSchur.h.

134{
135 if (!acceptStablePosteriorVariance(variance, signal_variance,
136 relative_allowance))
138 "stable posterior variance is not finite and nonnegative");
139}

◆ requireStablePosteriorVariance() [3/3]

void gpr::linalg::requireStablePosteriorVariance ( Eigen::VectorXd & variance,
const Eigen::VectorXd & signal )
inline

Accept every entry of a stable posterior variance vector or throw.

Exceptions
StableVarianceErrorwhen the sizes differ or any entry is rejected.

Definition at line 152 of file ExactSchur.h.

154{
155 if (variance.size() != signal.size())
157 "stable posterior variance and signal variance disagree");
158 for (Eigen::Index i = 0; i < variance.size(); ++i)
159 requireStablePosteriorVariance(variance(i), signal(i));
160}

◆ requireStableSchurDiagonal()

template<typename RelativeError>
void gpr::linalg::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.

relative_error is called once, and only when an entry is negative, because it may cost triangular solves or a collective. It must return the same value on every rank that reaches this call. Each entry is then accepted down to -relative_error * signal; NaN, infinity and anything more negative raise StableVarianceError. This is the one check for diagonals that come from a rounded Cholesky solve, whatever holds the factor.

Definition at line 174 of file ExactSchur.h.

177{
178 if (variance.size() != signal.size())
180 "stable posterior variance and signal sizes disagree");
181 double error = 0.0;
182 if ((variance.array() < 0.0).any()) error = relative_error();
183 for (Eigen::Index i = 0; i < variance.size(); ++i)
184 requireStablePosteriorVariance(variance(i), signal(i), error);
185}

◆ resetKokkosTransferAuditStats()

void gpr::linalg::resetKokkosTransferAuditStats ( )
noexcept

Definition at line 60 of file KokkosBackend.cpp.

61{
62 auto& audit = transfer_audit();
63 audit.h2d_calls.store(0, std::memory_order_relaxed);
64 audit.h2d_bytes.store(0, std::memory_order_relaxed);
65 audit.d2h_calls.store(0, std::memory_order_relaxed);
66 audit.d2h_bytes.store(0, std::memory_order_relaxed);
67 audit.d2d_calls.store(0, std::memory_order_relaxed);
68 audit.d2d_bytes.store(0, std::memory_order_relaxed);
69 audit.h2h_calls.store(0, std::memory_order_relaxed);
70 audit.h2h_bytes.store(0, std::memory_order_relaxed);
71 audit.to_exec_calls.store(0, std::memory_order_relaxed);
72 audit.to_exec_bytes.store(0, std::memory_order_relaxed);
73 audit.to_host_calls.store(0, std::memory_order_relaxed);
74 audit.to_host_bytes.store(0, std::memory_order_relaxed);
75 audit.mirror_calls.store(0, std::memory_order_relaxed);
76 audit.mirror_bytes.store(0, std::memory_order_relaxed);
77 audit.max_to_exec.store(0, std::memory_order_relaxed);
78 audit.max_to_host.store(0, std::memory_order_relaxed);
79}

◆ resolvedSingularRank()

Eigen::Index gpr::linalg::resolvedSingularRank ( const Eigen::VectorXd & singular,
double cutoff )
inline

How many leading descending singular values clear cutoff. A value that the backward error cannot separate from the cutoff, or from its neighbour across the cutoff, is not a resolved component: the whole unresolved cluster is dropped, so two solvers that straddle the cutoff by an ulp keep the same rank.

Definition at line 135 of file CanonicalEigen.h.

137{
138 Eigen::Index rank = 0;
139 while (rank < singular.size() && singular(rank) > cutoff)
140 ++rank;
141 if (rank == 0) return 0;
142
143 const double scale = std::max(std::abs(singular(0)), std::abs(cutoff));
144 const double tolerance = symmetricBackwardError(singular.size(), scale);
145 // The last kept value sits on the cutoff, or the cutoff splits a pair
146 // the backward error cannot tell apart.
147 const bool on_cutoff = std::abs(singular(rank - 1) - cutoff) <= tolerance;
148 const bool split =
149 rank < singular.size() &&
150 std::abs(singular(rank - 1) - singular(rank)) <= tolerance;
151 if (!on_cutoff && !split) return rank;
152
153 Eigen::Index begin = rank - 1;
154 while (begin > 0 &&
155 std::abs(singular(begin - 1) - singular(begin)) <= tolerance)
156 --begin;
157 return begin;
158}

◆ satisfies()

bool gpr::linalg::satisfies ( ArithmeticClass provided,
ArithmeticClass required )
nodiscardconstexprnoexcept

True when a provider of class provided meets the class required.

Definition at line 129 of file BackendInterface.h.

131{
132 return static_cast<int>(provided) >= static_cast<int>(required);
133}

◆ scaleSchemeII()

bool gpr::linalg::scaleSchemeII ( const double * left,
const double * right,
int length,
SchemeIIIntegers * scaled )
inline

Definition at line 267 of file OzakiSchemeII.inl.

269{
270 if (scaled == nullptr || length < 0 || length > SchemeIIIntegers::kMaxTerms)
271 return false;
272 scaled->length = length;
273 int align = 0;
274 bool have = false;
275 for (int i = 0; i < length; ++i) {
276 if (!scheme_ii_isfinite(left[i]) || !scheme_ii_isfinite(right[i]))
277 return false;
278 split_significand(left[i], &scaled->left_sig[i], &scaled->left_exp[i]);
279 split_significand(right[i], &scaled->right_sig[i],
280 &scaled->right_exp[i]);
281 if (scaled->left_sig[i] == 0 || scaled->right_sig[i] == 0) continue;
282 const int product_exp = scaled->left_exp[i] + scaled->right_exp[i];
283 if (!have || product_exp < align) align = product_exp;
284 have = true;
285 }
286 scaled->align_exp = have ? align : 0;
287 return true;
288}
static constexpr int kMaxTerms

◆ scheme_i_slice_bits()

int gpr::linalg::scheme_i_slice_bits ( int length)

Definition at line 14 of file OzakiScheme.cpp.

16{
17 if (length <= 1) return 0;
18 int bits = 0;
19 auto rest = static_cast<unsigned long long>(length);
20 while (rest > 1) {
21 rest >>= 1;
22 ++bits;
23 }
24 if ((static_cast<unsigned long long>(length) &
25 (static_cast<unsigned long long>(length) - 1ULL)) != 0) {
26 ++bits;
27 }
28 return bits;

◆ scheme_i_slice_cap()

int gpr::linalg::scheme_i_slice_cap ( const double * values,
int length,
int bits )

Definition at line 101 of file OzakiScheme.cpp.

103{
104 if (left.bits == 0 || right.bits == 0 || left.slices.empty() ||
105 right.slices.empty()) {
106 return std::numeric_limits<double>::quiet_NaN();
107 }
108 struct NormalizedSlice {
109 Eigen::VectorXd values;
110 int exponent;
111 };
112 const auto normalize = [](const SchemeISlices& input) {
113 std::vector<NormalizedSlice> result;
114 result.reserve(input.slices.size());
115 for (const auto& slice: input.slices) {
116 int exponent = 0;
117 if (slice.size() > 0)
118 std::frexp(slice.cwiseAbs().maxCoeff(), &exponent);
119 const int unit = exponent - input.bits;
120 Eigen::VectorXd values(slice.size());

◆ scheme_i_split()

int gpr::linalg::scheme_i_split ( const double * values,
int length,
int bits,
double * slices,
int cap )

Definition at line 30 of file OzakiScheme.cpp.

34{
35 // 2*tau + ceil(log2(length)) <= 52 leaves the sum of `length` slice
36 // products inside the binary64 significand.
37 const int room = 52 - ceilLog2(length < 1 ? 1 : length);
38 const int width = room / 2;
39 return width < 1 ? 1 : width;
40}
41
42SchemeISlices splitSchemeI(const Eigen::Ref<const Eigen::VectorXd>& values)
43{
44 SchemeISlices out;
45 out.bits = schemeISliceBits(values.size());
46 const Eigen::Index length = values.size();
47 double max_abs = 0.0;
48 bool finite = true;
49 for (Eigen::Index i = 0; i < length; ++i) {
50 const double value = values(i);
51 if (!std::isfinite(value)) finite = false;
52 max_abs = std::max(max_abs, std::fabs(value));
53 }
54 if (!finite || length == 0) {
55 out.bits = 0;
56 return out;
57 }
58 if (max_abs == 0.0) {
59 out.slices.push_back(Eigen::VectorXd::Zero(length));
60 return out;
61 }
62
63 Eigen::VectorXd residual = values;
64 while (true) {
65 double residual_max = 0.0;
66 for (Eigen::Index i = 0; i < length; ++i)
67 residual_max = std::max(residual_max, std::fabs(residual(i)));
68 if (residual_max == 0.0) break;
69 int exponent = 0;
70 std::frexp(residual_max, &exponent);
71 const int shift = exponent - out.bits;
72 Eigen::VectorXd slice(length);
73 bool any = false;
74 for (Eigen::Index i = 0; i < length; ++i) {
75 const double value = residual(i);
76 if (value == 0.0) {
77 slice(i) = 0.0;
78 continue;
79 }
80 int value_exponent = 0;
81 std::frexp(std::fabs(value), &value_exponent);
82 // A term below this slice's unit is left for a later slice.
83 // Scaling it here would overflow the exponent range.
84 if (value_exponent <= shift) {
85 slice(i) = 0.0;
86 continue;
87 }
88 const double scaled = std::ldexp(value, -shift);
89 const double digits = std::trunc(scaled);
90 const double piece = std::ldexp(digits, shift);
91 slice(i) = piece;
92 residual(i) = value - piece;
93 if (piece != 0.0) any = true;
94 }
95 if (!any) break;
96 out.slices.push_back(std::move(slice));
97 }
98 if (out.slices.empty()) out.slices.push_back(Eigen::VectorXd::Zero(length));
99 return out;
int schemeISliceBits(Eigen::Index length)
SchemeISlices splitSchemeI(const Eigen::Ref< const Eigen::VectorXd > &values)

◆ scheme_i_trunc()

double gpr::linalg::scheme_i_trunc ( double value)

Definition at line 5 of file OzakiScheme.cpp.

12 {

◆ schemeIIContext()

std::shared_ptr< const schemeii::Context > gpr::linalg::schemeIIContext ( )

The in-process Scheme II engine, or null. The reproducible distributed kernels take their tile products from it.

Definition at line 48 of file TrainingProduct.cpp.

49{
50 std::lock_guard lock(configuration);
51 return configured_scheme;
52}

◆ schemeIIModuli()

const uint32_t * gpr::linalg::schemeIIModuli ( )
inline

Definition at line 67 of file OzakiSchemeII.h.

68{
69 static const uint32_t moduli[kSchemeIIModulusCount] = {
73 return moduli;
74}

◆ schemeIIModulus()

uint32_t gpr::linalg::schemeIIModulus ( int index)
inlineconstexpr

Definition at line 42 of file OzakiSchemeII.h.

43{
44 switch (index) {
45 case 0:
46 return 998244353u;
47 case 1:
48 return 985661441u;
49 case 2:
50 return 975175681u;
51 case 3:
52 return 469762049u;
53 case 4:
54 return 167772161u;
55 case 5:
56 return 1004535809u;
57 case 6:
58 return 2013265921u;
59 case 7:
60 return 1811939329u;
61 default:
62 return 0u;
63 }
64}

◆ schemeIIProductRaw()

double gpr::linalg::schemeIIProductRaw ( const double * left,
const double * right,
int length )
inline

Definition at line 412 of file OzakiSchemeII.inl.

414{
415 if (length < 0 || (length > 0 && (left == nullptr || right == nullptr)))
416 return scheme_ii_nan();
418 for (int offset = 0; offset < length;) {
419 const int remaining = length - offset;
420 const int count = remaining < SchemeIIIntegers::kMaxTerms
421 ? remaining
423 SchemeIIIntegers scaled{};
424 if (!scaleSchemeII(left + offset, right + offset, count, &scaled))
425 return scheme_ii_nan();
426 char consumed[SchemeIIIntegers::kMaxTerms] = {};
427 SchemeIIIntegers window{};
428 while (takeSchemeIIWindow(scaled, consumed, &window)) {
429 uint32_t residues[kSchemeIIModulusCount];
430 for (int i = 0; i < kSchemeIIModulusCount; ++i)
431 residues[i] =
433 total.add(crtSchemeII(residues), window.align_exp);
434 }
435 offset += count;
436 }
437 return total.value();
438}
bool takeSchemeIIWindow(const SchemeIIIntegers &scaled, char *consumed, SchemeIIIntegers *window)
SchemeIIWide crtSchemeII(const uint32_t *residues)
bool scaleSchemeII(const double *left, const double *right, int length, SchemeIIIntegers *scaled)
uint32_t modularProductSchemeII(const SchemeIIIntegers &scaled, uint32_t modulus)
void add(const SchemeIIWide &coefficient, int exponent)

◆ schemeIProduct()

template<typename Left, typename Right>
double gpr::linalg::schemeIProduct ( const Eigen::MatrixBase< Left > & left,
const Eigen::MatrixBase< Right > & right )

Scheme I product of two equally shaped operands, in the same term order as the compensated predict contraction (column, then row).

Definition at line 38 of file OzakiScheme.h.

40{
41 if (left.rows() != right.rows() || left.cols() != right.cols() ||
42 left.size() > std::numeric_limits<int>::max()) {
43 return std::numeric_limits<double>::quiet_NaN();
44 }
45 Eigen::VectorXd left_terms(left.size());
46 Eigen::VectorXd right_terms(right.size());
47 Eigen::Index term = 0;
48 for (Eigen::Index column = 0; column < left.cols(); ++column) {
49 for (Eigen::Index row = 0; row < left.rows(); ++row, ++term) {
50 left_terms(term) = left(row, column);
51 right_terms(term) = right(row, column);
52 }
53 }
54 return accumulateSchemeI(splitSchemeI(left_terms),
55 splitSchemeI(right_terms));
56}
double accumulateSchemeI(const SchemeISlices &left, const SchemeISlices &right)
Sum the exact slice products. The split and this accumulation are separate.

◆ schemeIProductRaw()

double gpr::linalg::schemeIProductRaw ( const double * left,
const double * right,
int length )

Scheme I product of two length-n factors in term order.

Definition at line 122 of file OzakiScheme.cpp.

123 {std::move(values), unit});
124 }
125 return result;
126 };
127 const auto left_normalized = normalize(left);
128 const auto right_normalized = normalize(right);
130 for (const auto& a: left_normalized) {
131 for (const auto& b: right_normalized) {
132 if (a.values.size() != b.values.size())
133 return std::numeric_limits<double>::quiet_NaN();
134 // Slice integers and their partial sums fit in 52 bits. Keeping
135 // the scale separate prevents floating overflow and underflow.
136 double dot = 0.0;
137 for (Eigen::Index i = 0; i < a.values.size(); ++i)
138 dot += a.values(i) * b.values(i);
139 SchemeIIWide coefficient{};
140 coefficient.negative = dot < 0;
141 coefficient.limb[0] = static_cast<uint64_t>(std::fabs(dot));
142 total.add(coefficient, a.exponent + b.exponent);
143 }
144 }
145 return total.value();
146}
147
148#define SCHEME_I_HD
149#include "SchemeIProduct.inl"
150#undef SCHEME_I_HD
151
152} // namespace gpr::linalg

◆ schemeISliceBits()

int gpr::linalg::schemeISliceBits ( Eigen::Index length)

Bit width of one Ozaki Scheme I slice for a product of length terms. Two slices of this width have an exact binary64 product, and the sum of length such products is exact as well, with the slice scales kept separate.

Definition at line 33 of file OzakiScheme.cpp.

34{
35 // 2*tau + ceil(log2(length)) <= 52 leaves the sum of `length` slice
36 // products inside the binary64 significand.
37 const int room = 52 - ceilLog2(length < 1 ? 1 : length);
38 const int width = room / 2;
39 return width < 1 ? 1 : width;
40}

◆ selectPredictProduct()

bool gpr::linalg::selectPredictProduct ( const char * value)
inline

Definition at line 40 of file CompensatedSum.h.

41{
42 if (value == nullptr || value[0] == '\0' ||
43 std::strcmp(value, "compensated") == 0) {
44 return unsetenv("GPR_PREDICT_SUM") == 0;
45 }
46 if (std::strcmp(value, "kernel_float") == 0 &&
48 return false;
49 if (std::strcmp(value, "scheme1") == 0 ||
50 std::strcmp(value, "scheme2") == 0 ||
51 std::strcmp(value, "kernel_float") == 0) {
52 return setenv("GPR_PREDICT_SUM", value, 1) == 0;
53 }
54 return false;
55}
bool kernelFloatProductAvailable()

◆ setTileThreads()

void gpr::linalg::setTileThreads ( int threads)
inlinenoexcept

Sets the tile thread count (at least one).

Definition at line 28 of file TileParallel.h.

29{
30 tileThreadCount().store(std::max(1, threads));
31}
std::atomic< int > & tileThreadCount() noexcept
Number of threads one rank devotes to independent tile products.

◆ signedEigenvectorLess()

bool gpr::linalg::signedEigenvectorLess ( const Eigen::Ref< const Eigen::VectorXd > & left,
const Eigen::Ref< const Eigen::VectorXd > & right )
inline

Definition at line 81 of file CanonicalEigen.h.

84{
85 const Eigen::Index n = std::min(left.size(), right.size());
86 for (Eigen::Index i = 0; i < n; ++i) {
87 if (left(i) < right(i)) return true;
88 if (left(i) > right(i)) return false;
89 }
90 return left.size() < right.size();
91}

◆ splitSchemeI()

SchemeISlices gpr::linalg::splitSchemeI ( const Eigen::Ref< const Eigen::VectorXd > & values)

Split one operand into Scheme I slices. The sum of the slices is the operand. This split does not form the product.

Definition at line 42 of file OzakiScheme.cpp.

43{
45 out.bits = schemeISliceBits(values.size());
46 const Eigen::Index length = values.size();
47 double max_abs = 0.0;
48 bool finite = true;
49 for (Eigen::Index i = 0; i < length; ++i) {
50 const double value = values(i);
51 if (!std::isfinite(value)) finite = false;
52 max_abs = std::max(max_abs, std::fabs(value));
53 }
54 if (!finite || length == 0) {
55 out.bits = 0;
56 return out;
57 }
58 if (max_abs == 0.0) {
59 out.slices.push_back(Eigen::VectorXd::Zero(length));
60 return out;
61 }
62
63 Eigen::VectorXd residual = values;
64 while (true) {
65 double residual_max = 0.0;
66 for (Eigen::Index i = 0; i < length; ++i)
67 residual_max = std::max(residual_max, std::fabs(residual(i)));
68 if (residual_max == 0.0) break;
69 int exponent = 0;
70 std::frexp(residual_max, &exponent);
71 const int shift = exponent - out.bits;
72 Eigen::VectorXd slice(length);
73 bool any = false;
74 for (Eigen::Index i = 0; i < length; ++i) {
75 const double value = residual(i);
76 if (value == 0.0) {
77 slice(i) = 0.0;
78 continue;
79 }
80 int value_exponent = 0;
81 std::frexp(std::fabs(value), &value_exponent);
82 // A term below this slice's unit is left for a later slice.
83 // Scaling it here would overflow the exponent range.
84 if (value_exponent <= shift) {
85 slice(i) = 0.0;
86 continue;
87 }
88 const double scaled = std::ldexp(value, -shift);
89 const double digits = std::trunc(scaled);
90 const double piece = std::ldexp(digits, shift);
91 slice(i) = piece;
92 residual(i) = value - piece;
93 if (piece != 0.0) any = true;
94 }
95 if (!any) break;
96 out.slices.push_back(std::move(slice));
97 }
98 if (out.slices.empty()) out.slices.push_back(Eigen::VectorXd::Zero(length));
99 return out;
100}

◆ stablePosteriorVarianceEnabled()

bool gpr::linalg::stablePosteriorVarianceEnabled ( )
inlinenodiscardnoexcept

Whether stable posterior variance reductions are enabled.

Definition at line 40 of file ExactSchur.h.

41{
42 return stable_posterior_variance.load(std::memory_order_relaxed);
43}

◆ subsetFactorSchurRelativeError()

template<typename Backend, typename Derived>
double gpr::linalg::subsetFactorSchurRelativeError ( Backend & backend,
const Eigen::MatrixBase< Derived > & factor,
int order )
nodiscard

Schur relative error of a variance-subset factor.

A dense host factor is read with denseCholeskySchurRelativeError. An empty host factor is what a distributed factorization leaves behind: the factor is cached on the backend, and the empty matrix reads as +inf, which makes borderedCholeskyDiagonal fall back to four ulps. The backend's cached_factor_schur_relative_error is that factor's conditioning. order is the cached factor's dimension.

Definition at line 381 of file ExactSchur.h.

383{
384 if (factor.size() == 0)
385 return backend.cached_factor_schur_relative_error(order);
386 return denseCholeskySchurRelativeError(factor);
387}

◆ symmetricBackwardError()

double gpr::linalg::symmetricBackwardError ( Eigen::Index n,
double scale )
inlinenoexcept

Higham's gamma_n times a scale: the backward error of a symmetric eigensolver on an n-by-n matrix of that scale.

Definition at line 35 of file CanonicalEigen.h.

36{
37 if (!(scale > 0.0) || !std::isfinite(scale)) scale = 1.0;
38 const double neps = static_cast<double>(std::max<Eigen::Index>(1, n)) *
39 std::numeric_limits<double>::epsilon();
40 if (!(neps > 0.0) || !(neps < 1.0)) return 0.0;
41 return (neps / (1.0 - neps)) * scale;
42}

◆ takeSchemeIIWindow()

bool gpr::linalg::takeSchemeIIWindow ( const SchemeIIIntegers & scaled,
char * consumed,
SchemeIIIntegers * window )
inline

Definition at line 376 of file OzakiSchemeII.inl.

378{
379 if (consumed == nullptr || window == nullptr) return false;
380 int lead = 0;
381 bool have = false;
382 for (int i = 0; i < scaled.length; ++i) {
383 if (consumed[i]) continue;
384 if (scaled.left_sig[i] == 0 || scaled.right_sig[i] == 0) {
385 consumed[i] = 1;
386 continue;
387 }
388 const int product_exp = scaled.left_exp[i] + scaled.right_exp[i];
389 if (!have || product_exp > lead) lead = product_exp;
390 have = true;
391 }
392 if (!have) return false;
393 const int align = lead - kSchemeIIMaxShift;
394 window->length = 0;
395 window->align_exp = align;
396 for (int i = 0; i < scaled.length; ++i) {
397 if (consumed[i]) continue;
398 if (scaled.left_sig[i] == 0 || scaled.right_sig[i] == 0) continue;
399 const int product_exp = scaled.left_exp[i] + scaled.right_exp[i];
400 if (product_exp < align) continue;
401 const int slot = window->length;
402 window->left_sig[slot] = scaled.left_sig[i];
403 window->right_sig[slot] = scaled.right_sig[i];
404 window->left_exp[slot] = scaled.left_exp[i];
405 window->right_exp[slot] = scaled.right_exp[i];
406 window->length += 1;
407 consumed[i] = 1;
408 }
409 return window->length > 0;
410}
constexpr int kSchemeIIMaxShift

◆ teamAddSolveWall()

void gpr::linalg::teamAddSolveWall ( double seconds)

Definition at line 102 of file TeamFactor.cpp.

103{
104 if (seconds > 0.0) addWall(solveWallSeconds(), seconds);
105}

◆ teamCholeskyLower() [1/2]

bool gpr::linalg::teamCholeskyLower ( double * lower,
std::int64_t lda,
std::int64_t n )

Lower Cholesky of a column-major matrix. Only the lower triangle is read and written. The factor is Eigen's blocked Cholesky, compiled without a BLAS kernel. Returns false when a pivot is not positive; the matrix may then be partly overwritten.

Definition at line 137 of file TeamFactor.cpp.

138{
139 if (n < 0 || (n > 0 && (lower == nullptr || lda < n))) return false;
141 TeamRunner team;
142 return portable_tiles::factorLowerGeneral(lower, lda, n, team.run(),
143 team.context());
144}
bool factorLowerGeneral(double *matrix, std::ptrdiff_t stride, std::ptrdiff_t order, ParallelItems run, void *run_context)

◆ teamCholeskyLower() [2/2]

bool gpr::linalg::teamCholeskyLower ( Eigen::Ref< Eigen::MatrixXd > lower)
inline

Definition at line 83 of file TeamFactor.h.

84{
85 if (lower.rows() != lower.cols()) return false;
86 return teamCholeskyLower(lower.data(), lower.outerStride(), lower.rows());
87}
bool teamCholeskyLower(double *lower, std::int64_t lda, std::int64_t n)

◆ teamDivideConquerEigen()

bool gpr::linalg::teamDivideConquerEigen ( const Eigen::MatrixXd & sym,
Eigen::VectorXd & evals,
Eigen::MatrixXd & evecs )

Ascending eigenpairs of a symmetric matrix.

Eigen's blocked Householder tridiagonalization, compiled without a BLAS kernel. The pairs do not follow the OpenBLAS microkernel or the thread count. Returns false when the order is not square or the solver fails.

Definition at line 11 of file TeamEigen.cpp.

13{
14 if (sym.rows() != sym.cols()) return false;
15 if (sym.rows() > static_cast<Eigen::Index>(std::numeric_limits<int>::max()))
16 return false;
17 const int n = static_cast<int>(sym.rows());
18 if (n == 0) {
19 evals.resize(0);
20 evecs.resize(0, 0);
21 return true;
22 }
23 // Eigen's blocked tridiagonalization, compiled without a BLAS kernel.
24 // The pairs do not follow OPENBLAS_CORETYPE.
25 Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> solver(
26 sym.selfadjointView<Eigen::Lower>());
27 if (solver.info() != Eigen::Success) return false;
28 evals = solver.eigenvalues();
29 evecs = solver.eigenvectors();
30 return true;
31}

◆ teamFactorWallReset()

void gpr::linalg::teamFactorWallReset ( )

Definition at line 112 of file TeamFactor.cpp.

113{
114 factorWallSeconds() = 0.0;
115}

◆ teamFactorWallSeconds()

double gpr::linalg::teamFactorWallSeconds ( )
nodiscard

Wall time accumulated by dense and distributed Cholesky factors since the last reset.

Definition at line 107 of file TeamFactor.cpp.

108{
109 return factorWallSeconds();
110}

◆ teamPanelBitsIndependent()

bool gpr::linalg::teamPanelBitsIndependent ( )
nodiscard

True when a one-thread solve, a one-column panel, and the derived panel write the same bits on one lower factor. The check is the sweep behind the claim that the published solve does not depend on the panel width.

Definition at line 86 of file TeamFactor.cpp.

87{
88 // One Eigen product writes the solve. There is no panel width to vary.
89 return true;
90}

◆ teamPanelKernels()

bool gpr::linalg::teamPanelKernels ( )
inlinenodiscardnoexcept

Panel factorization and substitution. False when the library serial flag is set, when OpenMP is off, and when the configured team is one thread. The one-thread case is Eigen's own kernels.

Definition at line 102 of file LinalgThreads.h.

103{
104#if defined(USE_OPENMP)
106#else
107 return false;
108#endif
109}
bool librarySerialKernels() noexcept

◆ teamPanelWidth()

std::int64_t gpr::linalg::teamPanelWidth ( )
nodiscard

Column panel of the triangular solve. The width is the largest power of two whose panel fits in one core's level-2 cache at the joint order of the scaling grid. TeamFactor.cpp states that rule. The solve bits do not follow this width: teamPanelBitsIndependent checks that.

Definition at line 81 of file TeamFactor.cpp.

82{
83 return kAlgoBlock;
84}

◆ teamParallelPays()

bool gpr::linalg::teamParallelPays ( double flops)
nodiscard

False. Vendor BLAS already uses the affinity count, so this function does not start a second team. The flop argument is ignored. There is no cutoff and no saved clock.

Definition at line 117 of file TeamFactor.cpp.

118{
119 return parallelPays(flops);
120}

◆ teamSolveLower() [1/2]

void gpr::linalg::teamSolveLower ( const double * lower,
std::int64_t lda,
bool lower_factor,
double * rhs,
std::int64_t ldb,
std::int64_t n,
std::int64_t cols )

Solves L X = B (lower == true) or L^T X = B, L stored lower-triangular and column-major. The substitution is Eigen's blocked triangular solve, compiled without a BLAS kernel.

Definition at line 146 of file TeamFactor.cpp.

149{
150 if (n <= 0 || cols <= 0 || lower == nullptr || rhs == nullptr) return;
152 TeamRunner team;
153 portable_tiles::solveLeftGeneral(lower, lda, lower_factor, rhs, ldb, n,
154 cols, team.run(), team.context());
155}
void solveLeftGeneral(const double *factor, std::ptrdiff_t factor_stride, bool lower_factor, double *rhs, std::ptrdiff_t rhs_stride, std::ptrdiff_t order, std::ptrdiff_t columns, ParallelItems run, void *run_context)

◆ teamSolveLower() [2/2]

void gpr::linalg::teamSolveLower ( const Eigen::Ref< const Eigen::MatrixXd > & lower,
bool lower_factor,
Eigen::Ref< Eigen::MatrixXd > rhs )
inline

Definition at line 89 of file TeamFactor.h.

91{
92 teamSolveLower(lower.data(), lower.outerStride(), lower_factor, rhs.data(),
93 rhs.outerStride(), lower.rows(), rhs.cols());
94}
void teamSolveLower(const double *lower, std::int64_t lda, bool lower_factor, double *rhs, std::int64_t ldb, std::int64_t n, std::int64_t cols)

◆ teamSolveLowerVector() [1/2]

void gpr::linalg::teamSolveLowerVector ( const double * lower,
std::int64_t lda,
bool lower_factor,
double * rhs,
std::int64_t n )

The solve above for one right-hand side held as a vector. It runs Eigen's matrix-vector triangular sweep, the kernel a serial build runs on a vector, so a vector solve has the same bits in every build. A one-column matrix goes to teamSolveLower and its blocked matrix kernel.

Definition at line 157 of file TeamFactor.cpp.

159{
160 if (n <= 0 || lower == nullptr || rhs == nullptr) return;
162 portable_tiles::solveVectorGeneral(lower, lda, lower_factor, rhs, n);
163}
void solveVectorGeneral(const double *factor, std::ptrdiff_t factor_stride, bool lower_factor, double *rhs, std::ptrdiff_t order)

◆ teamSolveLowerVector() [2/2]

void gpr::linalg::teamSolveLowerVector ( const Eigen::Ref< const Eigen::MatrixXd > & lower,
bool lower_factor,
Eigen::Ref< Eigen::VectorXd > rhs )
inline

Definition at line 96 of file TeamFactor.h.

99{
100 teamSolveLowerVector(lower.data(), lower.outerStride(), lower_factor,
101 rhs.data(), lower.rows());
102}
void teamSolveLowerVector(const double *lower, std::int64_t lda, bool lower_factor, double *rhs, std::int64_t n)

◆ teamSolveWallReset()

void gpr::linalg::teamSolveWallReset ( )

Definition at line 97 of file TeamFactor.cpp.

98{
99 solveWallSeconds() = 0.0;
100}

◆ teamSolveWallSeconds()

double gpr::linalg::teamSolveWallSeconds ( )
nodiscard

Wall time accumulated by dense and distributed triangular solves since the last reset.

Definition at line 92 of file TeamFactor.cpp.

93{
94 return solveWallSeconds();
95}

◆ teamSymmetricGram()

void gpr::linalg::teamSymmetricGram ( const double * b,
std::int64_t ldb,
double * c,
std::int64_t ldc,
std::int64_t n )

The three kernels below run on configuredLinalgThreads() workers of the tile pool. Each worker owns whole blocks of Eigen's own blocking, so the bits do not follow the thread count. C = B^T B for a column-major B. The product is Eigen's blocked product, compiled without a BLAS kernel, so the bits do not follow OPENBLAS_CORETYPE.

Definition at line 165 of file TeamFactor.cpp.

167{
168 if (n <= 0 || b == nullptr || c == nullptr) return;
170 TeamRunner team;
171 portable_tiles::assignTransposeGram(b, ldb, c, ldc, n, team.run(),
172 team.context());
173}
void assignTransposeGram(const double *b, std::ptrdiff_t b_stride, double *c, std::ptrdiff_t c_stride, std::ptrdiff_t order, ParallelItems run, void *run_context)

◆ tileThreadCount()

std::atomic< int > & gpr::linalg::tileThreadCount ( )
inlinenoexcept

Number of threads one rank devotes to independent tile products.

Definition at line 21 of file TileParallel.h.

22{
23 static std::atomic<int> count{1};
24 return count;
25}

◆ trace_cached_inverse_times_symmetric_distributed()

double gpr::linalg::trace_cached_inverse_times_symmetric_distributed ( const double * B_dist,
const int * desc_b,
int n,
DistributedState & st = DistributedState::instance() )
inline

Definition at line 1901 of file ScalapackBackend.h.

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}
bool owns_global_entry(int global_row, int global_col) const

◆ trace_cholesky_solve_scalapack()

double gpr::linalg::trace_cholesky_solve_scalapack ( const EigenMatrix & L,
const EigenMatrix & B,
DistributedState & st = DistributedState::instance() )
inline

Definition at line 1530 of file ScalapackBackend.h.

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}

◆ trace_cholesky_solve_scalapack_distributed()

double gpr::linalg::trace_cholesky_solve_scalapack_distributed ( const EigenMatrix & L,
const double * B_dist,
const int * desc_b,
int m,
int ncols,
DistributedState & st = DistributedState::instance() )
inline

Definition at line 1626 of file ScalapackBackend.h.

1629{
1631 L, B_dist, desc_b, m, ncols, st);
1632 exact_sum_bcast(&trace, 1, st);
1633 return trace.value();
1634}
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())

◆ trace_cholesky_solve_scalapack_distributed_local()

ExactSum gpr::linalg::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() )
inline

Definition at line 1582 of file ScalapackBackend.h.

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}

◆ trace_inverse_times_symmetric()

double gpr::linalg::trace_inverse_times_symmetric ( const EigenMatrix & L,
const EigenMatrix * B,
int n,
DistributedState & st = DistributedState::instance() )
inline

tr(C^{-1} B) for a symmetric replicated B, or tr(C^{-1}) when B is null, from the inverse of the factor (see factor_inverse_lower). The same formula runs at every rank count. Returns NaN when the inverse fails.

Definition at line 1734 of file ScalapackBackend.h.

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();
1753 ExactSum local = trace_lower_symmetric_local(
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}
ExactSum trace_lower_symmetric_local(const double *A, int lda, int n, Entry &&b, DistributedState &st)

◆ trace_lower_symmetric_local()

template<class Entry>
ExactSum gpr::linalg::trace_lower_symmetric_local ( const double * A,
int lda,
int n,
Entry && b,
DistributedState & st )
inline

This rank's exact share of tr(A B) for symmetric n x n matrices: A is read on its lower triangle in the layout of desc (leading dimension lda), and b(i, j) returns entry (i, j) of B for i >= j. Off-diagonal products count twice. Every product enters the accumulator exactly, so the merged sum does not depend on how the entries are distributed.

Definition at line 1698 of file ScalapackBackend.h.

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}
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
void parallelFor(long count, F &&fn)
parallelFor(count, fn): see TilePool::run.

◆ trace_product() [1/2]

double gpr::linalg::trace_product ( const EigenMatrix & A,
const EigenMatrix & B )
inline

Frobenius inner product / trace of matrix product.

Computes \( \operatorname{tr}(A\,B) = \sum_{ij} A_{ij}\,B_{ij} \). Equivalent to the Frobenius inner product when one of the matrices is symmetric.

Parameters
[in]AFirst matrix.
[in]BSecond matrix (same dimensions as A).
Returns
The scalar trace-product.

Definition at line 510 of file CusolverBackend.h.

511{
512 const int total = static_cast<int>(A.size());
513 auto& cblas = detail::CublasLib::instance();
514 detail::DevBuf d_A(total);
515 detail::DevBuf d_B(total);
516 detail::h2d(d_A, A.data(), total);
517 detail::h2d(d_B, B.data(), total);
518
519 double result = 0.0;
520 detail::check_cublas(cblas.cublasDdot(detail::cublas_handle(), total, d_A,
521 1, d_B, 1, &result),
522 "ddot");
523 return result;
524}

◆ trace_product() [2/2]

double gpr::linalg::trace_product ( const EigenMatrix & A,
const EigenMatrix & B,
DistributedState & st = DistributedState::instance() )
inline

Definition at line 2006 of file ScalapackBackend.h.

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}

◆ trace_solve_product()

double gpr::linalg::trace_solve_product ( const EigenMatrix & L,
const EigenMatrix & A )
inline

tr(K^{-1} A) for a dense factor K = L L^T already in hand.

The solve is Eigen's triangular solve on that matrix. It is not the backend solve: under ScaLAPACK and SLATE, forward_solve_mat scatters its factor into DistributedState::cache_L and runs a collective. A rank-local LLT, such as one SVGD particle, must not enter that path.

Definition at line 19 of file DenseFactorTrace.h.

20{
21 if (L.rows() != L.cols() || A.rows() != L.rows() || A.cols() != L.cols())
22 return std::numeric_limits<double>::quiet_NaN();
23 if (L.rows() == 0) return 0.0;
24 const EigenMatrix solved =
25 L.transpose().triangularView<Eigen::Upper>().solve(
26 L.triangularView<Eigen::Lower>().solve(A));
27 return solved.trace();
28}

◆ trainingCholeskyDistributedSelected()

bool gpr::linalg::trainingCholeskyDistributedSelected ( Eigen::Index order)

As trainingCholeskySelected, for trainingCholeskyDistributed: device libraries only.

Definition at line 82 of file TrainingCholesky.cpp.

83{
84 // The in-process Scheme II engine serves the reproducible tile
85 // factorization instead, which keeps the block-cyclic layout and gathers
86 // no panel on one rank.
87 return order >= 2 * panel_width && trainingProductLibraryLoaded();
88}
bool trainingProductLibraryLoaded()
A device library (not an in-process engine) is configured.

◆ trainingCholeskyLower()

bool gpr::linalg::trainingCholeskyLower ( ProductMatrix lower)

Panel boundaries are independent of the process grid. Fixed-order scalar code factors and solves panels; Scheme II updates the trailing matrix. Only the lower triangle is an input. Failure can modify that input.

Definition at line 90 of file TrainingCholesky.cpp.

91{
92 if (lower.rows() != lower.cols()) return false;
93 lower.triangularView<Eigen::StrictlyUpper>().setZero();
94 for (Eigen::Index first = 0; first < lower.rows(); first += panel_width) {
95 const Eigen::Index rows = lower.rows() - first;
96 const Eigen::Index width = std::min<Eigen::Index>(panel_width, rows);
97 auto panel = lower.block(first, first, rows, width);
98 if (!factorPanel(panel)) return false;
99 const Eigen::Index remaining = rows - width;
100 if (remaining > 0) {
101 const auto border = panel.bottomRows(remaining);
102 updateTrailingLower(border,
103 lower.bottomRightCorner(remaining, remaining));
104 }
105 }
106 lower.triangularView<Eigen::StrictlyUpper>().setZero();
107 return true;
108}

◆ trainingCholeskySelected()

bool gpr::linalg::trainingCholeskySelected ( Eigen::Index order)

A product library or an in-process Scheme II engine is configured and the order spans two panels.

Definition at line 77 of file TrainingCholesky.cpp.

78{
79 return order >= 2 * panel_width && trainingProductConfigured();
80}

◆ trainingProduct()

Eigen::MatrixXd gpr::linalg::trainingProduct ( ConstProductMatrix a,
ConstProductMatrix b,
bool transpose_a,
bool transpose_b )

Allocating form with a native Eigen product when no device product runs.

Definition at line 132 of file TrainingProduct.cpp.

134{
135 const Eigen::Index m = transpose_a ? a.cols() : a.rows();
136 const Eigen::Index k = transpose_a ? a.rows() : a.cols();
137 const Eigen::Index n = transpose_b ? b.rows() : b.cols();
138 if (k != (transpose_b ? b.cols() : b.rows()))
139 throw std::invalid_argument("invalid training product dimensions");
140 Eigen::MatrixXd c(m, n);
141 if (!tryTrainingProduct(a, b, c, transpose_a, transpose_b)) {
142 if (transpose_a && transpose_b)
143 c.noalias() = a.transpose() * b.transpose();
144 else if (transpose_a)
145 c.noalias() = a.transpose() * b;
146 else if (transpose_b)
147 c.noalias() = a * b.transpose();
148 else
149 c.noalias() = a * b;
150 }
151 return c;
152}

◆ trainingProductConfigured()

bool gpr::linalg::trainingProductConfigured ( )

A device library or an in-process engine is configured.

Definition at line 89 of file TrainingProduct.cpp.

90{
91 std::lock_guard lock(configuration);
92 return configured != nullptr || configured_scheme != nullptr;
93}

◆ trainingProductLibraryLoaded()

bool gpr::linalg::trainingProductLibraryLoaded ( )

A device library (not an in-process engine) is configured.

Definition at line 95 of file TrainingProduct.cpp.

96{
97 return current() != nullptr;
98}

◆ transformDistributedLower()

void gpr::linalg::transformDistributedLower ( std::vector< double > & buffer,
const int * desc,
int n,
const CovarianceEquilibration & scaling,
bool restore_factor,
DistributedState & st )
inline

Definition at line 307 of file ScalapackBackend.h.

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}

◆ tryCertifiedProduct()

bool gpr::linalg::tryCertifiedProduct ( const double * left,
const double * right,
int length,
double & result )
inline

Definition at line 21 of file CertifiedProduct.h.

23{
24 if (length < 0 || std::fegetround() != FE_TONEAREST) return false;
25 double sum = 0.0;
26 double correction = 0.0;
27 double absolute_residuals = 0.0;
28 const auto add = [&](double value) {
29 const double next = sum + value;
30 const double residual = twoSumResidual(sum, value, next);
31 correction += residual;
32 absolute_residuals += std::abs(residual);
33 sum = next;
34 };
35 for (int i = 0; i < length; ++i) {
36 const double a = left[i], b = right[i];
37 uint64_t bits_a, bits_b;
38 std::memcpy(&bits_a, &a, sizeof(a));
39 std::memcpy(&bits_b, &b, sizeof(b));
40 bits_a &= UINT64_C(0x7fffffffffffffff);
41 bits_b &= UINT64_C(0x7fffffffffffffff);
42 if (bits_a >= UINT64_C(0x7ff0000000000000) ||
43 bits_b >= UINT64_C(0x7ff0000000000000))
44 return false;
45 if (bits_a == 0 || bits_b == 0) continue;
46 if (std::abs(a) < 0x1p-400 || std::abs(a) > 0x1p400 ||
47 std::abs(b) < 0x1p-400 || std::abs(b) > 0x1p400)
48 return false;
49 const double product = a * b;
50 add(product);
51 add(std::fma(a, b, -product));
52 }
53 if (absolute_residuals == 0.0) {
54 result = sum;
55 return true;
56 }
57
58 // For m <= 2n additions and u = 2^-53, the error in correction is
59 // bounded by gamma_(m-1)/(1-gamma_(m-1)) times absolute_residuals.
60 // With n <= INT_MAX this factor is strictly below 4nu = n*2^-51.
61 const double infinity = std::numeric_limits<double>::infinity();
62 const double bound = std::nextafter(
63 (static_cast<double>(length) * 0x1p-51) * absolute_residuals, infinity);
64 const double rounded = sum + correction;
65 const double residual = twoSumResidual(sum, correction, rounded);
66 const double previous = std::nextafter(rounded, -infinity);
67 const double following = std::nextafter(rounded, infinity);
68 if (!std::isfinite(previous) || !std::isfinite(following)) return false;
69 const double lower_radius = (rounded - previous) * 0.5;
70 const double upper_radius = (following - rounded) * 0.5;
71 const double lower = std::nextafter(residual - bound, -infinity);
72 const double upper = std::nextafter(residual + bound, infinity);
73 if (lower > -lower_radius && upper < upper_radius) {
74 result = rounded;
75 return true;
76 }
77 return false;
78}
double twoSumResidual(double a, double b, double rounded)

◆ tryTrainingProduct()

bool gpr::linalg::tryTrainingProduct ( ConstProductMatrix a,
ConstProductMatrix b,
ProductMatrix c,
bool transpose_a = false,
bool transpose_b = false,
double alpha = 1.0,
double beta = 0.0,
bool partitioned = false )

C = alpha op(A) op(B) + beta C. Returns false when the native backend should handle the product (no device library, or a small matrix). C must have the output dimensions and must not overlap either input. A partitioned call uses a size decision made for the global product, so changing the process grid cannot switch a local block's arithmetic.

Definition at line 100 of file TrainingProduct.cpp.

103{
104 const auto state = current();
105 const auto scheme = schemeIIContext();
106 if (!state && !scheme) return false;
107 const Eigen::Index m = transpose_a ? a.cols() : a.rows();
108 const Eigen::Index k = transpose_a ? a.rows() : a.cols();
109 const Eigen::Index n = transpose_b ? b.rows() : b.cols();
110 if (k != (transpose_b ? b.cols() : b.rows()) || c.rows() != m ||
111 c.cols() != n)
112 throw std::invalid_argument("invalid training product dimensions");
113 // Small matrices do not amortize device transfer and modular GEMM launch
114 // costs. This floor also keeps scalar and vector operations on the host.
115 if (std::min({m, n, k}) == 0 || (!partitioned && std::min({m, n, k}) < 128))
116 return false;
117 if (scheme) {
118 scheme->gemm(transpose_a, transpose_b, m, n, k, alpha, a.data(),
119 a.outerStride(), b.data(), b.outerStride(), beta, c.data(),
120 c.outerStride());
121 return true;
122 }
123 std::lock_guard lock(state->execution);
124 char error[1024]{};
125 if (state->gemm(state->workspace, transpose_a, transpose_b, m, n, k, alpha,
126 a.data(), a.outerStride(), b.data(), b.outerStride(), beta,
127 c.data(), c.outerStride(), error, sizeof(error)))
128 throw std::runtime_error(error);
129 return true;
130}
std::shared_ptr< const schemeii::Context > schemeIIContext()

◆ twoSumResidual()

double gpr::linalg::twoSumResidual ( double a,
double b,
double rounded )
inline

Definition at line 13 of file CertifiedProduct.h.

14{
15 return std::abs(a) >= std::abs(b) ? (a - rounded) + b : (b - rounded) + a;
16}

◆ unconstrainedLibraryReductions()

bool gpr::linalg::unconstrainedLibraryReductions ( )
nodiscardnoexcept

Definition at line 172 of file LinalgThreads.cpp.

173{
174 return unconstrained_library_reductions.load(std::memory_order_relaxed);
175}

◆ unscaleSchemeII()

double gpr::linalg::unscaleSchemeII ( const SchemeIIWide & coefficient,
int exponent )
inline

Definition at line 342 of file OzakiSchemeII.inl.

344{
345 return wide_unscale(coefficient, exponent);
346}

◆ upperInverseNorm1()

template<typename Derived>
double gpr::linalg::upperInverseNorm1 ( const Eigen::MatrixBase< Derived > & factor)
nodiscard

Upper bound on ||L^-1||_1 for an explicit lower-triangular factor.

Y solves L Y = I. The bound is upperInverseNorm1FromResidual. A singular or non-finite solve is infinite.

Definition at line 335 of file ExactSchur.h.

336{
337 const double infinity = std::numeric_limits<double>::infinity();
338 const Eigen::Index order = factor.rows();
339 if (order <= 0) return 0.0;
340 if (factor.cols() != order) return infinity;
341 Eigen::MatrixXd lower = factor.derived().template cast<double>();
342 lower.triangularView<Eigen::StrictlyUpper>().setZero();
343 const Eigen::MatrixXd identity = Eigen::MatrixXd::Identity(order, order);
344 const Eigen::MatrixXd inverse =
345 lower.triangularView<Eigen::Lower>().solve(identity);
346 if (!inverse.allFinite()) return infinity;
347 const double norm = inverse.cwiseAbs().colwise().sum().maxCoeff();
348 const Eigen::MatrixXd residual = identity - lower * inverse;
349 const double residual_norm =
350 residual.allFinite() ? residual.cwiseAbs().colwise().sum().maxCoeff()
351 : infinity;
352 const double factor_norm = lower.cwiseAbs().colwise().sum().maxCoeff();
353 return upperInverseNorm1FromResidual(norm, residual_norm, factor_norm,
354 order);
355}

◆ upperInverseNorm1FromComputed()

double gpr::linalg::upperInverseNorm1FromComputed ( double computed_norm,
Eigen::Index order )
inlinenodiscardnoexcept

Upper bound on ||L^-1||_1 from a computed inverse's 1-norm.

Column sums of a computed inverse can round down, so the value passed to choleskySchurRelativeError is lifted by the unit roundoff of an order-length sum. This is not estimateLowerInverseNorm1: that function is a lower bound and is not an error bound.

Definition at line 288 of file ExactSchur.h.

290{
291 const double infinity = std::numeric_limits<double>::infinity();
292 if (order <= 0) return 0.0;
293 if (!std::isfinite(computed_norm) || !(computed_norm >= 0.0))
294 return infinity;
295 const double eps = std::numeric_limits<double>::epsilon();
296 const double unit = static_cast<double>(order) * eps;
297 if (!(unit < 1.0)) return infinity;
298 const double upper = computed_norm / (1.0 - unit);
299 return std::isfinite(upper) ? upper : infinity;
300}

◆ upperInverseNorm1FromResidual()

double gpr::linalg::upperInverseNorm1FromResidual ( double computed_norm,
double residual_norm,
double factor_abs_norm,
Eigen::Index order )
inlinenodiscardnoexcept

Upper bound on ||L^-1||_1 from a computed triangular solve.

computed_norm is ||Y||_1 for Y solving L Y = I, residual_norm is ||I - L Y||_1, and factor_abs_norm is ||L||_1. The residual is enlarged by the rounding of I - L Y (Higham), and the result is lifted by upperInverseNorm1FromComputed. A column-sum lift alone is not a certificate: it leaves out the triangular-solve error. A non-finite argument or a residual bound of 1 or more is infinite.

Definition at line 310 of file ExactSchur.h.

313{
314 const double infinity = std::numeric_limits<double>::infinity();
315 if (order <= 0) return 0.0;
316 if (!std::isfinite(computed_norm) || !(computed_norm >= 0.0) ||
317 !std::isfinite(residual_norm) || !(residual_norm >= 0.0) ||
318 !std::isfinite(factor_abs_norm) || !(factor_abs_norm >= 0.0))
319 return infinity;
320 const double eps = std::numeric_limits<double>::epsilon();
321 const double unit = static_cast<double>(order) * eps;
322 if (!(unit < 1.0)) return infinity;
323 const double gamma = unit / (1.0 - unit);
324 const double theta =
325 residual_norm + gamma * (1.0 + factor_abs_norm * computed_norm);
326 if (!std::isfinite(theta) || !(theta < 1.0)) return infinity;
327 return upperInverseNorm1FromComputed(computed_norm / (1.0 - theta), order);
328}
double upperInverseNorm1FromComputed(double computed_norm, Eigen::Index order) noexcept
Upper bound on ||L^-1||_1 from a computed inverse's 1-norm.
Definition ExactSchur.h:288

Variable Documentation

◆ kLp64IndexLimit

std::int64_t gpr::linalg::kLp64IndexLimit
inlineconstexpr
Initial value:
=
std::numeric_limits<std::int32_t>::max()

Largest element offset an LP64 ScaLAPACK routine forms without overflow.

Definition at line 35 of file Lp64Limits.h.

◆ kMinDistributedGemmOrder

Eigen::Index gpr::linalg::kMinDistributedGemmOrder = 512
inlineconstexpr

Definition at line 195 of file ScalapackBackend.h.

◆ kMinDistributedSymmetricEigenOrder

Eigen::Index gpr::linalg::kMinDistributedSymmetricEigenOrder = 1
inlineconstexpr

Definition at line 531 of file ScalapackBackend.h.

◆ kMpiCommNull

MpiCommType gpr::linalg::kMpiCommNull = 0
inlineconstexpr

Definition at line 56 of file MpiContext.h.

◆ kPredictSumHelp

const char* gpr::linalg::kPredictSumHelp
inlineconstexpr
Initial value:
=
"Predict product. compensated sums each TwoProductFMA expansion and "
"rounds once, and is the default. scheme1 is Ozaki Scheme I, scheme2 is "
"Ozaki Scheme II, and kernel_float is the Scheme II product formed with "
"kernel_float vectors."

Definition at line 59 of file CompensatedSum.h.

◆ kPredictSumOption

const char* gpr::linalg::kPredictSumOption
inlineconstexpr
Initial value:
=
"--predict-sum <compensated|scheme1|scheme2|kernel_float>"

Definition at line 57 of file CompensatedSum.h.

◆ kSchemeIIMaxShift

int gpr::linalg::kSchemeIIMaxShift = 120
inlineconstexpr

Definition at line 38 of file OzakiSchemeII.h.

◆ kSchemeIIModulusCount

int gpr::linalg::kSchemeIIModulusCount = 8
inlineconstexpr

Definition at line 34 of file OzakiSchemeII.h.

◆ kStablePosteriorVarianceRoundoffUlps

int gpr::linalg::kStablePosteriorVarianceRoundoffUlps = 4
inlineconstexpr

Ulps of the signal variance that a compensated posterior variance may sit below zero.

Higham's bound on compensated summation is about 2*eps*sum|terms|. A prior and the squares that cancel it are at most two copies of the signal variance, so a mathematical zero rounds no lower than -4*eps*sigma2. The constant does not grow with the number of training rows.

Definition at line 53 of file ExactSchur.h.

◆ stable_posterior_variance

std::atomic_bool gpr::linalg::stable_posterior_variance {false}
inline

Process-wide switch for stable posterior variance reductions. Off by default; set through configureStablePosteriorVariance.

Definition at line 28 of file ExactSchur.h.

28{false};