diff --git a/source/Makefile.Objects b/source/Makefile.Objects index 502f29b9e05..48ab8fc6407 100644 --- a/source/Makefile.Objects +++ b/source/Makefile.Objects @@ -179,6 +179,13 @@ OBJS_BASE=assoc_laguerre.o\ math_kernel_op_vec.o\ mathzone_add1.o\ matrix.o\ + matrix2d.o\ + matrix2d_collective.o\ + matrix2d_lapack.o\ + matrix2d_linalg.o\ + matrix2d_mpi.o\ + matrix2d_reduction.o\ + matrix2d_scalapack.o\ matrix3.o\ memory_recorder.o\ mymath.o\ diff --git a/source/source_base/CMakeLists.txt b/source/source_base/CMakeLists.txt index 8098e18da3f..656fb958741 100644 --- a/source/source_base/CMakeLists.txt +++ b/source/source_base/CMakeLists.txt @@ -32,6 +32,13 @@ add_library( math_chebyshev.cpp mathzone_add1.cpp matrix.cpp + matrix2d.cpp + matrix2d_collective.cpp + matrix2d_lapack.cpp + matrix2d_linalg.cpp + matrix2d_mpi.cpp + matrix2d_reduction.cpp + matrix2d_scalapack.cpp matrix3.cpp memory_recorder.cpp mymath.cpp @@ -125,7 +132,6 @@ if(BUILD_TESTING) $ ${MPIEXEC_POSTFLAGS} ) - add_subdirectory(unittests) add_subdirectory(test) add_subdirectory(test_parallel) add_subdirectory(kernels/test) @@ -137,4 +143,5 @@ if(BUILD_TESTING) add_subdirectory(libm/test) endif() endif() + add_subdirectory(unittests) endif() diff --git a/source/source_base/matrix2d.cpp b/source/source_base/matrix2d.cpp new file mode 100644 index 00000000000..5094b6be5c8 --- /dev/null +++ b/source/source_base/matrix2d.cpp @@ -0,0 +1,635 @@ +#include "source_base/matrix2d.h" +#include "source_base/matrix2d_collective.h" +#include "source_base/matrix2d_reduction.h" +#include "source_base/matrix2d_scalapack.h" +#include "source_base/matrix2d_view.h" + +#include +#include +#include +#include +#include + +namespace +{ +namespace elementwise +{ +template +T conj(const T& value) +{ + return value; +} + +inline std::complex conj(const std::complex& value) +{ + return std::conj(value); +} + +inline std::complex conj(const std::complex& value) +{ + return std::conj(value); +} + +template +double real(const T& value) +{ + return static_cast(value); +} + +inline double real(const std::complex& value) +{ + return static_cast(value.real()); +} + +inline double real(const std::complex& value) +{ + return value.real(); +} + +template +double imag(const T&) +{ + return 0.0; +} + +inline double imag(const std::complex& value) +{ + return static_cast(value.imag()); +} + +inline double imag(const std::complex& value) +{ + return value.imag(); +} +} // namespace elementwise + +} // namespace + +namespace matrix2d_impl +{ +namespace scalapack +{ +template +void transpose(Matrix2dView result, Matrix2dView source) +{ + static_cast(result); + static_cast(source); + throw std::invalid_argument( + "ScaLAPACK transpose supports only double and complex"); +} + +template +void conjugate_transpose(Matrix2dView result, + Matrix2dView source) +{ + static_cast(result); + static_cast(source); + throw std::invalid_argument( + "ScaLAPACK conjugate transpose supports only double and complex"); +} + +template +void matmul(Matrix2dView result, + Matrix2dView left, + Matrix2dView right) +{ + static_cast(result); + static_cast(left); + static_cast(right); + throw std::invalid_argument( + "ScaLAPACK matmul supports only double and complex"); +} +} // namespace scalapack +} // namespace matrix2d_impl + +template +void NDArray::assert_compatible_layout( + const NDArray& other) const +{ + if (nrglb() != other.nrglb() + || ncglb() != other.ncglb()) + { + throw std::invalid_argument("matrix global shapes are incompatible"); + } + + const bool distributed = has_distribution(); + const bool distributed_ = other.has_distribution(); + if (distributed != distributed_) + { + throw std::invalid_argument("host and distributed matrices are incompatible"); + } + + if (!distributed) + { + return; + } + + if (distrib_->nb() != other.distribution()->nb()) + { + throw std::invalid_argument("matrix block sizes are incompatible"); + } + if (distrib_->nrproc() != other.distribution()->nrproc() + || distrib_->ncproc() != other.distribution()->ncproc()) + { + throw std::invalid_argument("matrix process grids are incompatible"); + } + if (distrib_ != other.distribution()) + { + throw std::invalid_argument("matrix distribution handles are incompatible"); + } +} + +template +Matrix2dView NDArray::view() +{ + if (distrib_ != nullptr) + { + return Matrix2dView(data(), distrib_); + } + return Matrix2dView(data(), nrglb(), ncglb()); +} + +template +Matrix2dView NDArray::view() const +{ + if (distrib_ != nullptr) + { + return Matrix2dView(data(), distrib_); + } + return Matrix2dView(data(), nrglb(), ncglb()); +} + +template +void NDArray::fill(const T& value) +{ + if (distrib_ == nullptr) + { + std::fill(storage_.begin(), storage_.end(), value); + return; + } + const int nrloc = this->nrloc(); + const int ncloc = this->ncloc(); +#ifdef _OPENMP +#pragma omp parallel for collapse(2) schedule(static) +#endif + for (int irloc = 0; irloc < nrloc; ++irloc) + { + for (int icloc = 0; icloc < ncloc; ++icloc) + { + atloc(irloc, icloc) = value; + } + } +} + +template +void NDArray::scale(const T& value) +{ + if (distrib_ == nullptr) + { +#ifdef _OPENMP +#pragma omp parallel for schedule(static) +#endif + for (std::size_t i = 0; i < storage_.size(); ++i) + { + storage_[i] *= value; + } + return; + } + const int nrloc = this->nrloc(); + const int ncloc = this->ncloc(); +#ifdef _OPENMP +#pragma omp parallel for collapse(2) schedule(static) +#endif + for (int irloc = 0; irloc < nrloc; ++irloc) + { + for (int icloc = 0; icloc < ncloc; ++icloc) + { + atloc(irloc, icloc) *= value; + } + } +} + +template +NDArray& NDArray::operator+=(const NDArray& other) +{ + assert_compatible_layout(other); + const int nrloc = this->nrloc(); + const int ncloc = this->ncloc(); +#ifdef _OPENMP +#pragma omp parallel for collapse(2) schedule(static) +#endif + for (int irloc = 0; irloc < nrloc; ++irloc) + { + for (int icloc = 0; icloc < ncloc; ++icloc) + { + atloc(irloc, icloc) += other.atloc(irloc, icloc); + } + } + return *this; +} + +template +NDArray& NDArray::operator-=(const NDArray& other) +{ + assert_compatible_layout(other); + const int nrloc = this->nrloc(); + const int ncloc = this->ncloc(); +#ifdef _OPENMP +#pragma omp parallel for collapse(2) schedule(static) +#endif + for (int irloc = 0; irloc < nrloc; ++irloc) + { + for (int icloc = 0; icloc < ncloc; ++icloc) + { + atloc(irloc, icloc) -= other.atloc(irloc, icloc); + } + } + return *this; +} + +template +NDArray& NDArray::operator*=(const NDArray& other) +{ + assert_compatible_layout(other); + const int nrloc = this->nrloc(); + const int ncloc = this->ncloc(); +#ifdef _OPENMP +#pragma omp parallel for collapse(2) schedule(static) +#endif + for (int irloc = 0; irloc < nrloc; ++irloc) + { + for (int icloc = 0; icloc < ncloc; ++icloc) + { + atloc(irloc, icloc) *= other.atloc(irloc, icloc); + } + } + return *this; +} + +template +NDArray& NDArray::conjugate() +{ + const int nrloc = this->nrloc(); + const int ncloc = this->ncloc(); +#ifdef _OPENMP +#pragma omp parallel for collapse(2) schedule(static) +#endif + for (int i = 0; i < nrloc; ++i) + { + for (int j = 0; j < ncloc; ++j) + { + atloc(i, j) = elementwise::conj(atloc(i, j)); + } + } + return *this; +} + +template +NDArray NDArray::transpose() const +{ + if (!is_active()) + { + // Serial degenerate path: a serial frozen distribution owns the full + // matrix on one rank with column-major local layout; treat it like the + // host path so distributed operators degrade to the host side. + Matrix2d result(ncloc_, nrloc_); +#ifdef _OPENMP +#pragma omp parallel for collapse(2) schedule(static) +#endif + for (int i = 0; i < nrloc_; ++i) + { + for (int j = 0; j < ncloc_; ++j) + { + result.atloc(j, i) = atloc(i, j); + } + } + return result; + } + +#ifdef __MPI + const int nr = ncglb(); + const int nc = nrglb(); + const int nb = distrib_->nb(); + const std::shared_ptr result_distrib + = make_borrowed_distribution(nr, nc, nb, distrib_); + Matrix2d result(result_distrib); + matrix2d_impl::scalapack::transpose(result.view(), view()); + return result; +#else + throw std::invalid_argument("distributed transpose requires MPI support"); +#endif +} + +template +NDArray NDArray::dagger() const +{ + if (!is_active()) + { + Matrix2d result(ncloc_, nrloc_); +#ifdef _OPENMP +#pragma omp parallel for collapse(2) schedule(static) +#endif + for (int i = 0; i < nrloc_; ++i) + { + for (int j = 0; j < ncloc_; ++j) + { + result.atloc(j, i) = elementwise::conj(atloc(i, j)); + } + } + return result; + } + +#ifdef __MPI + const int nr = ncglb(); + const int nc = nrglb(); + const int nb = distrib_->nb(); + const std::shared_ptr result_distrib + = make_borrowed_distribution(nr, nc, nb, distrib_); + Matrix2d result(result_distrib); + matrix2d_impl::scalapack::conjugate_transpose(result.view(), view()); + return result; +#else + throw std::invalid_argument( + "distributed conjugate transpose requires MPI support"); +#endif +} + +template +NDArray NDArray::matmul(const NDArray& other) const +{ + const int m = nrglb(); + const int k = ncglb(); + const int n = other.ncglb(); + { + const int k_ = other.nrglb(); + if (k != k_) + { + throw std::invalid_argument("matrix inner dimensions are incompatible"); + } + } + + const bool serial = !is_active(); + const bool serial_ = !other.is_active(); + if (serial != serial_) + { + throw std::invalid_argument("host and distributed matrices are incompatible"); + } + + if (serial) + { + // Serial degenerate path: both sides are host or serial frozen + // distributions, so matmul degrades to the host triple loop. + Matrix2d result(m, n); +#ifdef _OPENMP +#pragma omp parallel for collapse(2) schedule(static) +#endif + for (int i = 0; i < m; ++i) + { + for (int j = 0; j < n; ++j) + { + T value = T(); + for (int k_ = 0; k_ < k; ++k_) + { + value += atloc(i, k_) * other.atloc(k_, j); + } + result.atloc(i, j) = value; + } + } + return result; + } + +#ifdef __MPI + const std::shared_ptr other_distrib + = other.distribution(); + if (distrib_->nb() != other_distrib->nb()) + { + throw std::invalid_argument("matrix block sizes are incompatible"); + } + if (distrib_->nrproc() != other_distrib->nrproc() + || distrib_->ncproc() != other_distrib->ncproc()) + { + throw std::invalid_argument("matrix process grids are incompatible"); + } + if (distrib_->ictxt() != other_distrib->ictxt()) + { + throw std::invalid_argument("matrix BLACS contexts are incompatible"); + } + + const int nb = distrib_->nb(); + const std::shared_ptr result_distrib + = make_borrowed_distribution(m, n, nb, distrib_); + Matrix2d result(result_distrib); + matrix2d_impl::scalapack::matmul(result.view(), view(), other.view()); + return result; +#else + throw std::invalid_argument("distributed matmul requires MPI support"); +#endif +} + +template +NDArray NDArray::real() const +{ + Matrix2d result = has_distribution() + ? Matrix2d(distribution()) + : Matrix2d(nrglb(), ncglb()); + const int nrloc = this->nrloc(); + const int ncloc = this->ncloc(); +#ifdef _OPENMP +#pragma omp parallel for collapse(2) schedule(static) +#endif + for (int i = 0; i < nrloc; ++i) + { + for (int j = 0; j < ncloc; ++j) + { + result.atloc(i, j) = elementwise::real(atloc(i, j)); + } + } + return result; +} + +template +NDArray NDArray::imag() const +{ + Matrix2d result = has_distribution() + ? Matrix2d(distribution()) + : Matrix2d(nrglb(), ncglb()); + const int nrloc = this->nrloc(); + const int ncloc = this->ncloc(); +#ifdef _OPENMP +#pragma omp parallel for collapse(2) schedule(static) +#endif + for (int i = 0; i < nrloc; ++i) + { + for (int j = 0; j < ncloc; ++j) + { + result.atloc(i, j) = elementwise::imag(atloc(i, j)); + } + } + return result; +} + +template +T NDArray::sum() const +{ + return matrix2d_impl::sum(*this); +} + +template +T NDArray::dot(const NDArray& other) const +{ + assert_compatible_layout(other); + return matrix2d_impl::dot(*this, other); +} + +template +real_type NDArray::norm() const +{ + return matrix2d_impl::norm(*this); +} + +template +real_type NDArray::max_abs() const +{ + return matrix2d_impl::max_abs(*this); +} + +template +std::vector NDArray::diagonal() const +{ + return matrix2d_impl::diagonal(*this); +} + +template +NDArray NDArray::gather() const +{ + if (distrib_ == nullptr) + { + return *this; + } + if (distrib_->is_serial()) + { + Matrix2d result(nrglb(), ncglb()); + for (int irloc = 0; irloc < nrloc(); ++irloc) + { + const int irglb = distrib_->irglb(irloc); + for (int icloc = 0; icloc < ncloc(); ++icloc) + { + const int icglb = distrib_->icglb(icloc); + result.atloc(irglb, icglb) = atloc(irloc, icloc); + } + } + return result; + } +#ifdef __MPI + const MPI_Comm comm = distrib_->comm(); + if (comm == MPI_COMM_NULL) + { + throw std::invalid_argument("gather requires a valid MPI comm"); + } + return matrix2d_impl::allgather(*this, comm); +#else + return *this; +#endif +} + +template +NDArray NDArray::gather_on_root(const int iproot) const +{ + if (distrib_ == nullptr) + { + if (iproot == 0) + { + return *this; + } + return NDArray(EmptyMatrixTag()); + } + if (distrib_->is_serial()) + { + if (iproot != 0) + { + return NDArray(EmptyMatrixTag()); + } + Matrix2d result(nrglb(), ncglb()); + for (int irloc = 0; irloc < nrloc(); ++irloc) + { + const int irglb = distrib_->irglb(irloc); + for (int icloc = 0; icloc < ncloc(); ++icloc) + { + const int icglb = distrib_->icglb(icloc); + result.atloc(irglb, icglb) = atloc(irloc, icloc); + } + } + return result; + } +#ifdef __MPI + const MPI_Comm comm = distrib_->comm(); + if (comm == MPI_COMM_NULL) + { + throw std::invalid_argument("gather_on_root requires a valid MPI comm"); + } + std::unique_ptr> gathered + = matrix2d_impl::gather_on_root(*this, iproot, comm); + if (gathered) + { + return *gathered; + } + return NDArray(EmptyMatrixTag()); +#else + static_cast(iproot); + return NDArray(EmptyMatrixTag()); +#endif +} + +template +void NDArray::scatter(const NDArray& matglb) +{ + if (distrib_ == nullptr) + { + if (matglb.has_distribution()) + { + throw std::invalid_argument("host scatter requires a host global matrix"); + } + if (nrloc_ != matglb.nrglb() + || ncloc_ != matglb.ncglb()) + { + throw std::invalid_argument("scatter global matrix shape does not match matrix"); + } + *this = matglb; + return; + } + + if (distrib_->is_serial()) + { + if (matglb.has_distribution()) + { + throw std::invalid_argument("scatter requires a host global matrix"); + } + if (nrglb() != matglb.nrglb() + || ncglb() != matglb.ncglb()) + { + throw std::invalid_argument("scatter global matrix shape does not match distribution"); + } + for (int irloc = 0; irloc < nrloc(); ++irloc) + { + for (int icloc = 0; icloc < ncloc(); ++icloc) + { + atloc(irloc, icloc) + = matglb.atloc(distrib_->irglb(irloc), + distrib_->icglb(icloc)); + } + } + return; + } + +#ifdef __MPI + matrix2d_impl::scatter_from_host(matglb, *this); +#else + throw std::invalid_argument("active distributed scatter requires MPI support"); +#endif +} + +template class NDArray; +template class NDArray; +template class NDArray; +template class NDArray, 2>; +template class NDArray, 2>; diff --git a/source/source_base/matrix2d.h b/source/source_base/matrix2d.h new file mode 100644 index 00000000000..16706117043 --- /dev/null +++ b/source/source_base/matrix2d.h @@ -0,0 +1,436 @@ +#ifndef ABACUS_SOURCE_SOURCE_BASE_MATRIX2D_H +#define ABACUS_SOURCE_SOURCE_BASE_MATRIX2D_H + +#include "source_base/parallel_blkcyc.h" +#include "source_base/ndarray.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +template +class Matrix2dView; + +/** + * @brief Select the real scalar type used by Matrix2d numerical reductions. + * + * Integer matrices map to double so that absolute values and squared + * magnitudes do not overflow in int. Floating-point matrices preserve their + * real precision, including complex matrices. + */ +template +struct Matrix2dRealType; + +template <> +struct Matrix2dRealType +{ + using type = double; +}; + +template <> +struct Matrix2dRealType +{ + using type = float; +}; + +template <> +struct Matrix2dRealType +{ + using type = double; +}; + +template <> +struct Matrix2dRealType> +{ + using type = float; +}; + +template <> +struct Matrix2dRealType> +{ + using type = double; +}; + +template +using real_type = typename Matrix2dRealType::type; + +/** + * @brief Rank-two matrix specialization with host or frozen-distribution + * storage. + * + * The `final` specifier prevents further derivation from this specialization. + * Deriving a matrix type would make slicing and rank-two specializations + * ambiguous, while composition is sufficient for all supported matrix usage. + */ +template +class NDArray final +{ + public: + NDArray() = delete; + + NDArray(const int nrloc, const int ncloc) + : nrloc_(nrloc), + ncloc_(ncloc) + { + if (nrloc_ <= 0) + { + throw std::invalid_argument("nrloc must be positive"); + } + if (ncloc_ <= 0) + { + throw std::invalid_argument("ncloc must be positive"); + } + const std::size_t n + = static_cast(nrloc_) * static_cast(ncloc_); + storage_.resize(n); + } + +#ifdef __MPI + NDArray(const int nrglb, + const int ncglb, + const MPI_Comm comm) + { + std::shared_ptr distrib // distribution, not distance + = make_frozen_distribution(nrglb, ncglb, 1, comm); + initialize_distributed_storage(std::move(distrib)); + } + + NDArray(const int nrglb, + const int ncglb, + const int nb, + const MPI_Comm comm) + { + std::shared_ptr distrib + = make_frozen_distribution(nrglb, ncglb, nb, comm); + initialize_distributed_storage(std::move(distrib)); + } + + NDArray(const int nrglb, + const int ncglb, + const int nrproc, + const int ncproc, + const int nb, + const MPI_Comm comm) + { + std::shared_ptr distrib + = make_frozen_distribution(nrglb, ncglb, nrproc, ncproc, nb, comm); + initialize_distributed_storage(std::move(distrib)); + } +#endif + + explicit NDArray(std::shared_ptr distrib) + : distrib_(std::move(distrib)) + { + if (distrib_ == nullptr) + { + throw std::invalid_argument("distribution must not be null"); + } + initialize_distributed_storage(); + } + + NDArray(const NDArray&) = default; + NDArray(NDArray&&) noexcept = default; + ~NDArray() = default; + + NDArray& operator=(const NDArray&) = default; + NDArray& operator=(NDArray&&) noexcept = default; + + void fill(const T& value); + void scale(const T& value); + NDArray& operator+=(const NDArray& other); + NDArray& operator-=(const NDArray& other); + NDArray& operator*=(const NDArray& other); + + NDArray& conjugate(); + NDArray transpose() const; + NDArray dagger() const; + NDArray matmul(const NDArray& other) const; + + /** Return a newly allocated matrix containing the real parts. */ + NDArray real() const; + /** Return a newly allocated matrix containing the imaginary parts. */ + NDArray imag() const; + + T sum() const; + T dot(const NDArray& other) const; + /** Return the Frobenius norm sqrt(sum_ij |a_ij|^2). */ + real_type norm() const; + /** Return max_ij |a_ij|. */ + real_type max_abs() const; + std::vector diagonal() const; + + NDArray gather() const; + + /** + * @brief Gather the distributed matrix on one rank. + * + * MPI collectives require every rank to call this function. When + * iproot == 0, ranks other than rank zero return a 0 x 0 host placeholder. + * Such placeholder results, or a root-only gathered matrix, must not be fed + * back to scatter() because scatter() requires a full host matrix on every + * rank. + */ + NDArray gather_on_root(const int iproot) const; + + /** + * @brief Scatter a full host matrix into the frozen distribution. + * + * The MPI implementation is collective: every rank must call scatter() + * with a complete host matrix of the global shape. Only the matrix supplied + * by communicator rank zero is read; matrices supplied by other ranks are + * ignored. + */ + void scatter(const NDArray& matglb); + + /** Access an owned element by global row and column indices. */ + T& atglb(const int irglb, const int icglb) + { + assert(irglb >= 0); + assert(irglb < nrglb()); + assert(icglb >= 0); + assert(icglb < ncglb()); + + if (distrib_ == nullptr) + { + return atloc(irglb, icglb); + } + + const bool owns = distrib_->in_this_processor(irglb, icglb); + assert(owns); + + const int irloc = distrib_->irloc(irglb); + const int icloc = distrib_->icloc(icglb); + assert(irloc != -1); + assert(icloc != -1); + return atloc(irloc, icloc); + } + + /** Access an owned element by global row and column indices. */ + const T& atglb(const int irglb, const int icglb) const + { + assert(irglb >= 0); + assert(irglb < nrglb()); + assert(icglb >= 0); + assert(icglb < ncglb()); + + if (distrib_ == nullptr) + { + return atloc(irglb, icglb); + } + + const bool owns = distrib_->in_this_processor(irglb, icglb); + assert(owns); + + const int irloc = distrib_->irloc(irglb); + const int icloc = distrib_->icloc(icglb); + assert(irloc != -1); + assert(icloc != -1); + return atloc(irloc, icloc); + } + + /** Access an element by local row and column indices. */ + T& atloc(const int irloc, const int icloc) + { + assert(irloc >= 0); + assert(irloc < nrloc()); + assert(icloc >= 0); + assert(icloc < ncloc()); + + std::size_t offset = 0; + if (distrib_ == nullptr) + { + offset = static_cast(irloc) + * static_cast(ncloc_) + + static_cast(icloc); + } + else + { + const int lld = distrib_->lld(); + offset = static_cast(icloc) + * static_cast(lld) + + static_cast(irloc); + } + assert(offset < storage_.size()); + return storage_[offset]; + } + + /** Access an element by local row and column indices. */ + const T& atloc(const int irloc, const int icloc) const + { + assert(irloc >= 0); + assert(irloc < nrloc()); + assert(icloc >= 0); + assert(icloc < ncloc()); + + std::size_t offset = 0; + if (distrib_ == nullptr) + { + offset = static_cast(irloc) + * static_cast(ncloc_) + + static_cast(icloc); + } + else + { + const int lld = distrib_->lld(); + offset = static_cast(icloc) + * static_cast(lld) + + static_cast(irloc); + } + assert(offset < storage_.size()); + return storage_[offset]; + } + + /** Return whether this processor owns the given global indices. */ + bool in_this_processor(const int irglb, const int icglb) const + { + assert(irglb >= 0); + assert(irglb < nrglb()); + assert(icglb >= 0); + assert(icglb < ncglb()); + if (distrib_ == nullptr) + { + return true; + } + return distrib_->in_this_processor(irglb, icglb); + } + + T* data() { return storage_.data(); } + const T* data() const { return storage_.data(); } + + int nrglb() const { return distrib_ == nullptr ? nrloc_ : distrib_->nrglb(); } + int ncglb() const { return distrib_ == nullptr ? ncloc_ : distrib_->ncglb(); } + int nrloc() const { return distrib_ == nullptr ? nrloc_ : distrib_->nrloc(); } + int ncloc() const { return distrib_ == nullptr ? ncloc_ : distrib_->ncloc(); } + std::size_t size() const + { + return distrib_ == nullptr + ? static_cast(nrloc_) * static_cast(ncloc_) + : distrib_->size(); + } + + /** + * @brief Number of T elements in the physical local storage buffer. + * + * This includes column-major padding and the minimum element reserved on + * ranks that own no local rows or columns. + */ + std::size_t local_storage_size() const { return storage_.size(); } + int nrproc() const { return distrib_ == nullptr ? 1 : distrib_->nrproc(); } + int ncproc() const { return distrib_ == nullptr ? 1 : distrib_->ncproc(); } + int irproc() const { return distrib_ == nullptr ? 0 : distrib_->irproc(); } + int icproc() const { return distrib_ == nullptr ? 0 : distrib_->icproc(); } + int lld() const { return distrib_ == nullptr ? ncloc_ : distrib_->lld(); } + + const int* desc() const + { +#ifdef __MPI + return distrib_ != nullptr ? distrib_->desc() : nullptr; +#else + return nullptr; +#endif + } + + int ictxt() const + { +#ifdef __MPI + return distrib_ != nullptr ? distrib_->ictxt() : -1; +#else + return -1; +#endif + } + + const std::shared_ptr& distribution() const { return distrib_; } + /** + * @brief Return whether a frozen distribution handle is attached. + * + * This includes the serial one-by-one layout. Use `is_active()` when only + * a non-serial MPI distribution should take the distributed code path. + */ + bool has_distribution() const { return distrib_ != nullptr; } + /** + * @brief Return whether an active non-serial MPI distribution is attached. + * + * A serial one-by-one frozen distribution has a handle but is not active. + */ + bool is_active() const + { + return distrib_ != nullptr && !distrib_->is_serial(); + } + + Matrix2dView view(); + Matrix2dView view() const; + + private: + /** + * @brief Internal construction tag for an empty host matrix placeholder. + * + * `gather_on_root()` uses this tag on non-root ranks to construct the + * documented 0 x 0 result without running a public matrix constructor. + */ + struct EmptyMatrixTag + { + }; + + explicit NDArray(EmptyMatrixTag) + { + } + + void assert_compatible_layout(const NDArray& other) const; + + void initialize_distributed_storage( + std::shared_ptr distrib) + { + if (distrib == nullptr) + { + throw std::invalid_argument("distribution must not be null"); + } + distrib_ = std::move(distrib); + initialize_distributed_storage(); + } + + void initialize_distributed_storage() + { + nrloc_ = distrib_->nrloc(); + ncloc_ = distrib_->ncloc(); + assert(nrloc_ >= 0); + assert(ncloc_ >= 0); + + const int lld = std::max(distrib_->lld(), 1); + // BLACS/LAPACK storage is column-major and may contain leading-dimension + // padding. The row-major extent is retained as a guard for local logical + // accesses. + const std::size_t ncolmajor + = static_cast(lld) + * static_cast(ncloc_); + const std::size_t nrowmajor + = static_cast(nrloc_) + * static_cast(ncloc_); + const std::size_t nextent = std::max(ncolmajor, nrowmajor); + const std::size_t nstor_min = 1; + const std::size_t nstor = std::max(nextent, nstor_min); + storage_.resize(nstor); + } + + int nrloc_ = 0; + int ncloc_ = 0; + std::vector storage_; + std::shared_ptr distrib_; +}; + +template +using Matrix2d = NDArray; + +static_assert(std::is_same, NDArray>::value, + "Matrix2d and NDArray must be the same type."); +static_assert(!std::is_same, NDArray>::value, + "NDArray and NDArray must be distinct types."); +static_assert(!std::is_base_of, NDArray>::value, + "The rank-two specialization must compose storage rather than inherit."); + +#endif diff --git a/source/source_base/matrix2d_collective.cpp b/source/source_base/matrix2d_collective.cpp new file mode 100644 index 00000000000..decf0bd4fd4 --- /dev/null +++ b/source/source_base/matrix2d_collective.cpp @@ -0,0 +1,545 @@ +#include "source_base/matrix2d_collective.h" + +#ifdef __MPI +#include "source_base/matrix2d_mpi.h" +#include "source_base/parallel_common.h" + +#include +#include +#include +#include + +/** + * @internal + * @brief Communication adapters for Matrix2d distributed storage. + * + * ScaLAPACK has no drop-in gather/scatter operation for arbitrary frozen + * Matrix2d layouts. Block ownership and BLACS descriptors remain defined by + * `Parallel_Blkcyclic` through `Cblacs_gridinit`, `numroc_`, and `descinit_`. + * The code below only serializes values by the existing owner maps and moves + * the resulting contiguous rank segments with wrapper-managed collective + * operations. + */ +namespace +{ +namespace mpi = matrix2d_impl::mpi; + +constexpr int LOCAL_METADATA_SIZE = 6; +// Width in bytes of a native int in the homogeneous metadata wire format. +constexpr int W_INT = sizeof(int); + +/** + * @brief Pack rank-local axis metadata for Matrix2d collective transfers. + * + * The metadata wire format is + * `[nrloc, ncloc, nrglb, ncglb, iprow, ipcol, + * irglb[nrloc], icglb[ncloc]]`. + * `make_local_buffer()` appends `nrloc * ncloc` logical row-major `T` values + * with no BLACS leading-dimension padding. Every integer is a native `int`. + * This byte-level protocol is valid only among homogeneous MPI processes that + * use the same C++ ABI, scalar representation, and native `int` layout. + */ +template +std::vector make_local_metadata(const Matrix2d& matrix) +{ + static_assert(std::is_trivially_copyable::value, + "Matrix2d collective buffers require trivially copyable T"); + const std::shared_ptr distrib + = matrix.distribution(); + const std::size_t nmeta = static_cast(LOCAL_METADATA_SIZE) + + static_cast(matrix.nrloc()) + + static_cast(matrix.ncloc()); + std::vector metadata(nmeta); + std::size_t offset = 0; + metadata[offset++] = matrix.nrloc(); + metadata[offset++] = matrix.ncloc(); + metadata[offset++] = matrix.nrglb(); + metadata[offset++] = matrix.ncglb(); + metadata[offset++] = distrib->irproc(); + metadata[offset++] = distrib->icproc(); + for (int irloc = 0; irloc < matrix.nrloc(); ++irloc) + { + metadata[offset++] = distrib->irglb(irloc); + } + for (int icloc = 0; icloc < matrix.ncloc(); ++icloc) + { + metadata[offset++] = distrib->icglb(icloc); + } + return metadata; +} + +template +std::vector make_local_buffer(const Matrix2d& matrix) +{ + const std::vector metadata = make_local_metadata(matrix); + const std::size_t nmeta = metadata.size(); + const std::size_t nbytes_meta = nmeta * W_INT; + // Number of stored T values, not bytes. + const std::size_t ndata = static_cast(matrix.nrloc()) + * static_cast(matrix.ncloc()); + const std::size_t nbytes_data = ndata * sizeof(T); + const std::size_t nbytbuf = nbytes_meta + nbytes_data; + std::vector buffer(nbytbuf); + + std::memcpy(buffer.data(), metadata.data(), nbytes_meta); + for (int irloc = 0; irloc < matrix.nrloc(); ++irloc) + { + for (int icloc = 0; icloc < matrix.ncloc(); ++icloc) + { + // The u prefix denotes a checked, unsigned local index. + const std::size_t uirloc = static_cast(irloc); + const std::size_t uicloc = static_cast(icloc); + const std::size_t idx + = uirloc * static_cast(matrix.ncloc()) + uicloc; + const T& value = matrix.atloc(irloc, icloc); + const std::size_t offset = nbytes_meta + idx * sizeof(T); + unsigned char* const destination + = buffer.data() + offset; + std::memcpy(destination, &value, sizeof(T)); + } + } + return buffer; +} + +struct RankBufferView +{ + const unsigned char* data = nullptr; + std::size_t size = 0; +}; + +struct LocalBufferView +{ + int nrloc = 0; + int ncloc = 0; + int nrglb = 0; + int ncglb = 0; + int iprow = 0; + int ipcol = 0; + std::vector irglb; + std::vector icglb; + const unsigned char* data = nullptr; +}; + +/** + * @brief Pack values owned by one rank into a contiguous scatter segment. + * + * The block-cyclic owner map is defined by `Parallel_Blkcyclic` through the + * BLACS/ScaLAPACK grid setup (`Cblacs_gridinit`, `numroc_`, and `descinit_`). + * This helper does not reproduce that distribution algorithm; it only moves + * values according to the already-computed local-to-global axis maps. + */ +template +void pack_rank_values(const Matrix2d& matglb, + const LocalBufferView& view, + unsigned char* destination) +{ + for (int irloc = 0; irloc < view.nrloc; ++irloc) + { + const int irglb = view.irglb[irloc]; + for (int icloc = 0; icloc < view.ncloc; ++icloc) + { + const int icglb = view.icglb[icloc]; + const std::size_t idx + = static_cast(irloc) + * static_cast(view.ncloc) + + static_cast(icloc); + const T& value = matglb.atloc(irglb, icglb); + const std::size_t destination_offset = idx * sizeof(T); + unsigned char* const destination_offset_ptr + = destination + destination_offset; + std::memcpy(destination_offset_ptr, &value, sizeof(T)); + } + } +} + +template +LocalBufferView view_local_buffer( + const RankBufferView& buffer) +{ + if (buffer.size < LOCAL_METADATA_SIZE * W_INT) + { + throw std::invalid_argument( + "Matrix2d collective matrix buffer is truncated"); + } + + int header[LOCAL_METADATA_SIZE] = {}; + std::memcpy(header, buffer.data, sizeof(header)); + LocalBufferView view; + view.nrloc = header[0]; + view.ncloc = header[1]; + view.nrglb = header[2]; + view.ncglb = header[3]; + view.iprow = header[4]; + view.ipcol = header[5]; + + if (view.nrloc < 0 || view.ncloc < 0 || view.nrglb <= 0 + || view.ncglb <= 0) + { + throw std::invalid_argument( + "Matrix2d collective matrix buffer has invalid dimensions"); + } + + const std::size_t nmeta + = static_cast(LOCAL_METADATA_SIZE) + view.nrloc + view.ncloc; + const std::size_t nbytes_meta = nmeta * W_INT; + const std::size_t ndata + = static_cast(view.nrloc) * static_cast(view.ncloc); + const std::size_t nbytes_expected = nbytes_meta + ndata * sizeof(T); + if (buffer.size != nbytes_expected) + { + throw std::invalid_argument( + "Matrix2d collective matrix buffer has an invalid size"); + } + + std::vector metadata(nmeta); + std::memcpy(metadata.data(), buffer.data, nbytes_meta); + view.irglb.assign(metadata.begin() + LOCAL_METADATA_SIZE, + metadata.begin() + LOCAL_METADATA_SIZE + view.nrloc); + view.icglb.assign(metadata.begin() + LOCAL_METADATA_SIZE + view.nrloc, + metadata.end()); + view.data = buffer.data + nbytes_meta; + return view; +} + +std::vector make_rank_buffer_views( + const std::vector& recvbuf, + const std::vector& nbytes_recv, + const std::vector& rdispls) +{ + std::vector buffers(nbytes_recv.size()); + for (std::size_t ip = 0; ip < nbytes_recv.size(); ++ip) + { + const std::size_t rank_begin + = static_cast(rdispls[ip]); + const std::size_t rank_size + = static_cast(nbytes_recv[ip]); + if (rank_begin > recvbuf.size() + || rank_size > recvbuf.size() - rank_begin) + { + throw std::invalid_argument( + "Matrix2d collective rank segment is outside the receive buffer"); + } + buffers[ip].data = recvbuf.data() + rank_begin; + buffers[ip].size = rank_size; + } + return buffers; +} + +template +Matrix2d rebuild_global( + const std::vector& buffers) +{ + std::vector views; + views.reserve(buffers.size()); + int nrglb = 0; + int ncglb = 0; + for (std::size_t ip = 0; ip < buffers.size(); ++ip) + { + views.push_back(view_local_buffer(buffers[ip])); + const LocalBufferView& view = views.back(); + if (ip == 0) + { + nrglb = view.nrglb; + ncglb = view.ncglb; + } + else if (view.nrglb != nrglb || view.ncglb != ncglb) + { + throw std::invalid_argument("Matrix2d ranks disagree on global shape"); + } + } + + Matrix2d result(nrglb, ncglb); + for (std::size_t ip = 0; ip < views.size(); ++ip) + { + const LocalBufferView& view = views[ip]; + for (int irloc = 0; irloc < view.nrloc; ++irloc) + { + const int irglb = view.irglb[irloc]; + if (irglb < 0 || irglb >= nrglb) + { + throw std::invalid_argument("Matrix2d row axis is outside global shape"); + } + for (int icloc = 0; icloc < view.ncloc; ++icloc) + { + const int icglb = view.icglb[icloc]; + if (icglb < 0 || icglb >= ncglb) + { + throw std::invalid_argument("Matrix2d column axis is outside global shape"); + } + const std::size_t idx + = static_cast(irloc) + * static_cast(view.ncloc) + + static_cast(icloc); + const std::size_t source_offset = idx * sizeof(T); + const unsigned char* const source + = view.data + source_offset; + T value; + std::memcpy(&value, source, sizeof(T)); + result.atloc(irglb, icglb) = value; + } + } + } + return result; +} + +} // namespace + +namespace matrix2d_impl +{ +template +Matrix2d allgather(const Matrix2d& matrix, const MPI_Comm comm) +{ + const std::vector locbuf = make_local_buffer(matrix); + const int nbytes_local_mpi = mpi::checked_mpi_count(locbuf.size()); + const std::vector nbytes_recv + = mpi::allgather_nbytes(nbytes_local_mpi, comm); + const std::vector rdispls = mpi::make_byte_offsets(nbytes_recv); + const int nbytes_total = rdispls.back() + nbytes_recv.back(); + std::vector recvbuf( + static_cast(nbytes_total)); + Parallel_Common::allgatherv_bytes(locbuf.data(), + nbytes_local_mpi, + recvbuf.data(), + nbytes_recv.data(), + rdispls.data(), + comm); + const std::vector buffers + = make_rank_buffer_views(recvbuf, nbytes_recv, rdispls); + return rebuild_global(buffers); +} + +template +std::unique_ptr> gather_on_root(const Matrix2d& matrix, + const int iproot, + const MPI_Comm comm) +{ + const int nproc = Parallel_Common::comm_size(comm); + const int ip = Parallel_Common::comm_rank(comm); + if (iproot < 0 || iproot >= nproc) + { + throw std::invalid_argument("gather root rank is outside the communicator"); + } + + const std::vector locbuf = make_local_buffer(matrix); + const int nbytes_local_mpi = mpi::checked_mpi_count(locbuf.size()); + const std::vector nbytes_recv + = mpi::allgather_nbytes(nbytes_local_mpi, comm); + const std::vector rdispls = mpi::make_byte_offsets(nbytes_recv); + const int nbytes_total = rdispls.back() + nbytes_recv.back(); + std::vector rxbuf; + if (ip == iproot) + { + rxbuf.resize(nbytes_total); + } + + unsigned char* const recvbuf = ip == iproot ? rxbuf.data() : nullptr; + Parallel_Common::gatherv_bytes(locbuf.data(), + nbytes_local_mpi, + recvbuf, + nbytes_recv.data(), + rdispls.data(), + iproot, + comm); + if (ip != iproot) + { + return std::unique_ptr>(); + } + + const std::vector buffers + = make_rank_buffer_views(rxbuf, nbytes_recv, rdispls); + return std::unique_ptr>( + new Matrix2d(rebuild_global(buffers))); +} + +template +void scatter_from_host(const Matrix2d& matglb, Matrix2d& matloc) +{ + if (matglb.has_distribution()) + { + throw std::invalid_argument("scatter requires a host global matrix"); + } + + const std::shared_ptr distrib + = matloc.distribution(); + const MPI_Comm comm = distrib->comm(); + if (comm == MPI_COMM_NULL) + { + throw std::invalid_argument("scatter requires a valid MPI comm"); + } + + const std::vector metadata = make_local_metadata(matloc); + const std::size_t nmeta = metadata.size(); + const std::size_t nbytes_meta = nmeta * W_INT; + const int nmeta_mpi = mpi::checked_mpi_count(nbytes_meta); + const std::vector metacounts + = mpi::allgather_nbytes(nmeta_mpi, comm); + const std::vector metadispls + = mpi::make_byte_offsets(metacounts); + const int metadata_total_bytes + = metadispls.back() + metacounts.back(); + if (metadata_total_bytes % W_INT != 0) + { + throw std::invalid_argument("Matrix2d scatter metadata has an invalid byte count"); + } + const int nmeta_all = metadata_total_bytes / W_INT; + std::vector all_metadata(nmeta_all); + + Parallel_Common::allgatherv_bytes(metadata.data(), + nmeta_mpi, + all_metadata.data(), + metacounts.data(), + metadispls.data(), + comm); + + const int nproc = Parallel_Common::comm_size(comm); + const int ip = Parallel_Common::comm_rank(comm); + std::vector sendcounts(nproc, 0); + std::vector views; + views.reserve(nproc); + std::size_t metadata_offset = 0; + const int nrglb = matloc.nrglb(); + const int ncglb = matloc.ncglb(); + for (int ipsrc = 0; ipsrc < nproc; ++ipsrc) + { + if (metadata_offset + LOCAL_METADATA_SIZE > all_metadata.size()) + { + throw std::invalid_argument("Matrix2d scatter metadata is truncated"); + } + LocalBufferView view; + view.nrloc = all_metadata[metadata_offset]; + view.ncloc = all_metadata[metadata_offset + 1]; + view.nrglb = all_metadata[metadata_offset + 2]; + view.ncglb = all_metadata[metadata_offset + 3]; + view.iprow = all_metadata[metadata_offset + 4]; + view.ipcol = all_metadata[metadata_offset + 5]; + metadata_offset += LOCAL_METADATA_SIZE; + const std::size_t naxes + = static_cast(view.nrloc + view.ncloc); + if (metadata_offset + naxes > all_metadata.size()) + { + throw std::invalid_argument("Matrix2d scatter axes are truncated"); + } + view.irglb.assign(all_metadata.begin() + metadata_offset, + all_metadata.begin() + metadata_offset + view.nrloc); + view.icglb.assign(all_metadata.begin() + metadata_offset + view.nrloc, + all_metadata.begin() + metadata_offset + view.nrloc + + view.ncloc); + metadata_offset += naxes; + + if (view.nrloc < 0 || view.ncloc < 0 + || view.nrglb != nrglb || view.ncglb != ncglb) + { + throw std::invalid_argument("Matrix2d ranks disagree on scatter global shape"); + } + const std::size_t nelem_local + = static_cast(view.nrloc) + * static_cast(view.ncloc); + const std::size_t nbytes_local = nelem_local * sizeof(T); + sendcounts[ipsrc] = mpi::checked_mpi_count(nbytes_local); + views.push_back(view); + } + if (metadata_offset != all_metadata.size()) + { + throw std::invalid_argument("Matrix2d scatter metadata has trailing entries"); + } + if (matglb.nrglb() != nrglb || matglb.ncglb() != ncglb) + { + throw std::invalid_argument("scatter global matrix shape does not match distribution"); + } + + const std::vector sdispls = mpi::make_byte_offsets(sendcounts); + std::vector sendbuf; + if (ip == 0) + { + const int total_bytes = sdispls.back() + sendcounts.back(); + sendbuf.resize(total_bytes); + for (int ipdst = 0; ipdst < nproc; ++ipdst) + { + const LocalBufferView& view = views[ipdst]; + unsigned char* const destination + = sendbuf.data() + static_cast(sdispls[ipdst]); + pack_rank_values(matglb, view, destination); + } + } + + const std::size_t nelem_recv + = static_cast(matloc.nrloc()) + * static_cast(matloc.ncloc()); + const std::size_t nbytes_recv = nelem_recv * sizeof(T); + std::vector recvbuf(nbytes_recv); + const int recv = mpi::checked_mpi_count(nbytes_recv); + const unsigned char* receive_source = ip == 0 ? sendbuf.data() : nullptr; + Parallel_Common::scatterv_bytes(receive_source, + sendcounts.data(), + sdispls.data(), + recvbuf.data(), + recv, + 0, + comm); + + for (int irloc = 0; irloc < matloc.nrloc(); ++irloc) + { + for (int icloc = 0; icloc < matloc.ncloc(); ++icloc) + { + const std::size_t idx + = static_cast(irloc) + * static_cast(matloc.ncloc()) + + static_cast(icloc); + const std::size_t receive_offset = idx * sizeof(T); + const unsigned char* const source + = recvbuf.data() + receive_offset; + T value; + std::memcpy(&value, source, sizeof(T)); + matloc.atloc(irloc, icloc) = value; + } + } +} + +template Matrix2d allgather(const Matrix2d& matrix, + const MPI_Comm comm); +template Matrix2d allgather(const Matrix2d& matrix, + const MPI_Comm comm); +template Matrix2d allgather(const Matrix2d& matrix, + const MPI_Comm comm); +template Matrix2d> allgather>( + const Matrix2d>& matrix, + const MPI_Comm comm); +template Matrix2d> allgather>( + const Matrix2d>& matrix, + const MPI_Comm comm); + +template std::unique_ptr> gather_on_root( + const Matrix2d& matrix, + const int iproot, + const MPI_Comm comm); +template std::unique_ptr> gather_on_root( + const Matrix2d& matrix, + const int iproot, + const MPI_Comm comm); +template std::unique_ptr> gather_on_root( + const Matrix2d& matrix, + const int iproot, + const MPI_Comm comm); +template std::unique_ptr>> gather_on_root>( + const Matrix2d>& matrix, + const int iproot, + const MPI_Comm comm); +template std::unique_ptr>> gather_on_root>( + const Matrix2d>& matrix, + const int iproot, + const MPI_Comm comm); + +template void scatter_from_host(const Matrix2d& matglb, + Matrix2d& matloc); +template void scatter_from_host(const Matrix2d& matglb, + Matrix2d& matloc); +template void scatter_from_host(const Matrix2d& matglb, + Matrix2d& matloc); +template void scatter_from_host>( + const Matrix2d>& matglb, + Matrix2d>& matloc); +template void scatter_from_host>( + const Matrix2d>& matglb, + Matrix2d>& matloc); +} // namespace matrix2d_impl +#endif diff --git a/source/source_base/matrix2d_collective.h b/source/source_base/matrix2d_collective.h new file mode 100644 index 00000000000..8b950c7b84b --- /dev/null +++ b/source/source_base/matrix2d_collective.h @@ -0,0 +1,32 @@ +#ifndef ABACUS_SOURCE_SOURCE_BASE_MATRIX2D_COLLECTIVE_H +#define ABACUS_SOURCE_SOURCE_BASE_MATRIX2D_COLLECTIVE_H + +/** + * @file matrix2d_collective.h + * @internal + * @brief Matrix2d collective backend declarations. + * + * Callers should include `source_base/matrix2d.h` instead of this header. + */ + +#include "source_base/matrix2d.h" + +#include + +#ifdef __MPI +namespace matrix2d_impl +{ +template +Matrix2d allgather(const Matrix2d& matrix, const MPI_Comm comm); + +template +std::unique_ptr> gather_on_root(const Matrix2d& matrix, + const int iproot, + const MPI_Comm comm); + +template +void scatter_from_host(const Matrix2d& matglb, Matrix2d& matloc); +} // namespace matrix2d_impl +#endif + +#endif diff --git a/source/source_base/matrix2d_lapack.cpp b/source/source_base/matrix2d_lapack.cpp new file mode 100644 index 00000000000..f3f42352ffb --- /dev/null +++ b/source/source_base/matrix2d_lapack.cpp @@ -0,0 +1,274 @@ +#include "source_base/matrix2d_lapack.h" + +#include "source_base/module_container/base/third_party/lapack.h" +#include "source_base/matrix2d_view.h" + +#include +#include +#include +#include +#include + +namespace +{ +void assert_host_layout(const Matrix2dView& matrix) +{ + if (matrix.is_active()) + { + throw std::invalid_argument("LAPACK requires a host matrix view"); + } +} + +void assert_host_layout(const Matrix2dView>& matrix) +{ + if (matrix.is_active()) + { + throw std::invalid_argument("LAPACK requires a host matrix view"); + } +} + +void assert_inverse_dimensions(const int nr, const int nc) +{ + if (nr <= 0 || nr != nc) + { + throw std::invalid_argument("matrix inverse requires a non-empty square matrix"); + } +} + +void assert_solve_dimensions(const int nr, + const int nc, + const int rhs_nr) +{ + if (nr <= 0 || nr != nc || rhs_nr != nr) + { + throw std::invalid_argument( + "linear solve requires a square matrix and matching right-hand side"); + } +} + +void throw_lapack_error(const char* operation, const int info) +{ + if (info < 0) + { + throw std::invalid_argument(std::string(operation) + + " received an invalid argument"); + } + if (info > 0) + { + throw std::runtime_error(std::string(operation) + + " failed because the matrix is singular"); + } +} +} // namespace + +namespace matrix2d_impl +{ +namespace lapack +{ +void inv(Matrix2dView matrix) +{ + assert_host_layout(matrix); + const int n = matrix.nrglb(); + assert_inverse_dimensions(n, matrix.ncglb()); + const std::size_t n_ = static_cast(n); + + const int lda = matrix.lld(); + std::vector ipiv(n_); + int info = 0; + container::lapackConnector::getrf( + /* m= */ n, + /* n= */ n, + /* a= */ matrix.data(), + /* lda= */ lda, + /* ipiv= */ ipiv.data(), + /* info= */ info); + throw_lapack_error("LAPACK getrf", info); + + int lws = -1; + std::vector ws(1); + container::lapackConnector::getri( + /* n= */ n, + /* a= */ matrix.data(), + /* lda= */ lda, + /* ipiv= */ ipiv.data(), + /* work= */ ws.data(), + /* lwork= */ lws, + /* info= */ info); + throw_lapack_error("LAPACK getri workspace query", info); + lws = static_cast(ws[0]); + const std::size_t lws_ = static_cast(lws); + ws.resize(lws_); + container::lapackConnector::getri( + /* n= */ n, + /* a= */ matrix.data(), + /* lda= */ lda, + /* ipiv= */ ipiv.data(), + /* work= */ ws.data(), + /* lwork= */ lws, + /* info= */ info); + throw_lapack_error("LAPACK getri", info); +} + +void inv(Matrix2dView> matrix) +{ + assert_host_layout(matrix); + const int n = matrix.nrglb(); + assert_inverse_dimensions(n, matrix.ncglb()); + const std::size_t n_ = static_cast(n); + + const int lda = matrix.lld(); + std::vector ipiv(n_); + int info = 0; + container::lapackConnector::getrf( + /* m= */ n, + /* n= */ n, + /* a= */ matrix.data(), + /* lda= */ lda, + /* ipiv= */ ipiv.data(), + /* info= */ info); + throw_lapack_error("LAPACK getrf", info); + + int lws = -1; + std::vector> ws(1); + container::lapackConnector::getri( + /* n= */ n, + /* a= */ matrix.data(), + /* lda= */ lda, + /* ipiv= */ ipiv.data(), + /* work= */ ws.data(), + /* lwork= */ lws, + /* info= */ info); + throw_lapack_error("LAPACK getri workspace query", info); + lws = static_cast(ws[0].real()); + const std::size_t lws_ = static_cast(lws); + ws.resize(lws_); + container::lapackConnector::getri( + /* n= */ n, + /* a= */ matrix.data(), + /* lda= */ lda, + /* ipiv= */ ipiv.data(), + /* work= */ ws.data(), + /* lwork= */ lws, + /* info= */ info); + throw_lapack_error("LAPACK getri", info); +} + +void solve(Matrix2dView matrix, + Matrix2dView rhs) +{ + assert_host_layout(matrix); + assert_host_layout(rhs); + const int n = matrix.nrglb(); + const int nrhs = rhs.ncglb(); + assert_solve_dimensions(n, matrix.ncglb(), rhs.nrglb()); + const std::size_t n_ = static_cast(n); + const std::size_t nrhs_ = static_cast(nrhs); + + const int lda = matrix.lld(); + std::vector ipiv(n_); + int info = 0; + container::lapackConnector::getrf( + /* m= */ n, + /* n= */ n, + /* a= */ matrix.data(), + /* lda= */ lda, + /* ipiv= */ ipiv.data(), + /* info= */ info); + throw_lapack_error("LAPACK getrf", info); + + // Column-major LAPACK right-hand side for A * X = B. + std::vector b(n_ * nrhs_); + for (int i = 0; i < n; ++i) + { + const std::size_t i_ = static_cast(i); + for (int j = 0; j < nrhs; ++j) + { + const std::size_t j_ = static_cast(j); + b[i_ + j_ * n_] = rhs.atloc(i, j); + } + } + + const char trans = matrix.has_distribution() ? 'N' : 'T'; + container::lapackConnector::getrs( + /* trans= */ trans, + /* n= */ n, + /* nrhs= */ nrhs, + /* a= */ matrix.data(), + /* lda= */ lda, + /* ipiv= */ ipiv.data(), + /* b= */ b.data(), + /* ldb= */ n, + /* info= */ info); + throw_lapack_error("LAPACK getrs", info); + + for (int i = 0; i < n; ++i) + { + const std::size_t i_ = static_cast(i); + for (int j = 0; j < nrhs; ++j) + { + const std::size_t j_ = static_cast(j); + rhs.atloc(i, j) = b[i_ + j_ * n_]; + } + } +} + +void solve(Matrix2dView> matrix, + Matrix2dView> rhs) +{ + assert_host_layout(matrix); + assert_host_layout(rhs); + const int n = matrix.nrglb(); + const int nrhs = rhs.ncglb(); + assert_solve_dimensions(n, matrix.ncglb(), rhs.nrglb()); + const std::size_t n_ = static_cast(n); + const std::size_t nrhs_ = static_cast(nrhs); + + const int lda = matrix.lld(); + std::vector ipiv(n_); + int info = 0; + container::lapackConnector::getrf( + /* m= */ n, + /* n= */ n, + /* a= */ matrix.data(), + /* lda= */ lda, + /* ipiv= */ ipiv.data(), + /* info= */ info); + throw_lapack_error("LAPACK getrf", info); + + // Column-major LAPACK right-hand side for A * X = B. + std::vector> b(n_ * nrhs_); + for (int i = 0; i < n; ++i) + { + const std::size_t i_ = static_cast(i); + for (int j = 0; j < nrhs; ++j) + { + const std::size_t j_ = static_cast(j); + b[i_ + j_ * n_] = rhs.atloc(i, j); + } + } + + const char trans = matrix.has_distribution() ? 'N' : 'T'; + container::lapackConnector::getrs( + /* trans= */ trans, + /* n= */ n, + /* nrhs= */ nrhs, + /* a= */ matrix.data(), + /* lda= */ lda, + /* ipiv= */ ipiv.data(), + /* b= */ b.data(), + /* ldb= */ n, + /* info= */ info); + throw_lapack_error("LAPACK getrs", info); + + for (int i = 0; i < n; ++i) + { + const std::size_t i_ = static_cast(i); + for (int j = 0; j < nrhs; ++j) + { + const std::size_t j_ = static_cast(j); + rhs.atloc(i, j) = b[i_ + j_ * n_]; + } + } +} +} // namespace lapack +} // namespace matrix2d_impl diff --git a/source/source_base/matrix2d_lapack.h b/source/source_base/matrix2d_lapack.h new file mode 100644 index 00000000000..19f034caed1 --- /dev/null +++ b/source/source_base/matrix2d_lapack.h @@ -0,0 +1,40 @@ +#ifndef ABACUS_SOURCE_SOURCE_BASE_MATRIX2D_LAPACK_H +#define ABACUS_SOURCE_SOURCE_BASE_MATRIX2D_LAPACK_H + +/** + * @file matrix2d_lapack.h + * @internal + * @brief Matrix2d LAPACK backend declarations. + * + * Callers should include `source_base/matrix2d_linalg.h` instead of this + * header. + */ + +#include + +template +class Matrix2dView; + +namespace matrix2d_impl +{ +namespace lapack +{ +/** + * @brief Invert a square host matrix in place with GETRF and GETRI. + * + * @warning Explicit inversion has poorer numerical stability than solving a + * linear system directly. Use this function only when the inverse matrix + * itself is required. When solving `A * X = B`, call `solve()` instead. + */ +void inv(Matrix2dView matrix); +/** @copydoc inv(Matrix2dView) */ +void inv(Matrix2dView> matrix); + +void solve(Matrix2dView matrix, + Matrix2dView rhs); +void solve(Matrix2dView> matrix, + Matrix2dView> rhs); +} // namespace lapack +} // namespace matrix2d_impl + +#endif diff --git a/source/source_base/matrix2d_linalg.cpp b/source/source_base/matrix2d_linalg.cpp new file mode 100644 index 00000000000..76723ea0e21 --- /dev/null +++ b/source/source_base/matrix2d_linalg.cpp @@ -0,0 +1,647 @@ +#include "source_base/matrix2d_linalg.h" + +#include "source_base/matrix2d_lapack.h" +#include "source_base/matrix2d_view.h" +#include "source_base/parallel_blkcyc.h" +#ifdef __MPI +#include "source_base/matrix2d_scalapack.h" +#endif + +#include +#include +#include +#include + +namespace +{ +/** + * @brief Return true when a distribution handle exists and is not the serial + * one-by-one layout. + */ +template +bool distribution_is_active(const Matrix2dView& matrix) +{ + return matrix.is_active(); +} + +/** + * @brief Return true when a distribution handle exists and describes the + * serial one-by-one layout. + */ +template +bool distribution_is_serial(const Matrix2dView& matrix) +{ + return matrix.has_distribution() && matrix.distribution()->is_serial(); +} + +template +void assert_same_shape(const Matrix2dView& left, + const Matrix2dView& right) +{ + if (left.nrglb() != right.nrglb() || left.ncglb() != right.ncglb()) + { + throw std::invalid_argument("matrix shapes are incompatible"); + } +} + +template +void assert_compatible_layout(const Matrix2dView& left, + const Matrix2dView& right) +{ + if (left.has_distribution() != right.has_distribution()) + { + throw std::invalid_argument( + "matrix operations require matching host or distributed layouts"); + } + if (!left.has_distribution()) + { + return; + } + const bool serial = distribution_is_serial(left); + const bool serial_ = distribution_is_serial(right); + if (serial != serial_) + { + throw std::invalid_argument( + "matrix operations require matching serial or parallel distributions"); + } + if (serial) + { + return; + } +#ifdef __MPI + matrix2d_impl::scalapack::assert_compatible_layout(left.desc(), + right.desc()); +#else + throw std::invalid_argument( + "matrix operations require MPI-compatible distributed layouts"); +#endif +} + +template +void assert_matmul_views(Matrix2dView result, + Matrix2dView left, + Matrix2dView right) +{ + if (left.ncglb() != right.nrglb() + || result.nrglb() != left.nrglb() + || result.ncglb() != right.ncglb()) + { + throw std::invalid_argument("matrix multiplication dimensions are incompatible"); + } + assert_compatible_layout(result, left); + assert_compatible_layout(result, right); +} + +template +void matmul_host(Matrix2dView result, + Matrix2dView left, + Matrix2dView right) +{ + for (int i = 0; i < result.nrglb(); ++i) + { + for (int j = 0; j < result.ncglb(); ++j) + { + T value = T(); + for (int k = 0; k < left.ncglb(); ++k) + { + value += left.atloc(i, k) * right.atloc(k, j); + } + result.atloc(i, j) = value; + } + } +} + +template +void axpby_impl(Matrix2dView result, + const T alpha, + Matrix2dView left, + const T beta, + Matrix2dView right) +{ + assert_same_shape(result, left); + assert_same_shape(result, right); + assert_compatible_layout(result, left); + assert_compatible_layout(result, right); +#ifdef _OPENMP +#pragma omp parallel for collapse(2) schedule(static) +#endif + for (int i = 0; i < result.nrloc(); ++i) + { + for (int j = 0; j < result.ncloc(); ++j) + { + result.atloc(i, j) + = alpha * left.atloc(i, j) + beta * right.atloc(i, j); + } + } +} + +template +void scale_impl(Matrix2dView matrix, const T factor) +{ +#ifdef _OPENMP +#pragma omp parallel for collapse(2) schedule(static) +#endif + for (int i = 0; i < matrix.nrloc(); ++i) + { + for (int j = 0; j < matrix.ncloc(); ++j) + { + matrix.atloc(i, j) *= factor; + } + } +} + +template +void set_identity_impl(Matrix2dView matrix) +{ + if (matrix.nrglb() != matrix.ncglb()) + { + throw std::invalid_argument("identity requires a square matrix"); + } + const std::shared_ptr distrib + = matrix.distribution(); + for (int i = 0; i < matrix.nrloc(); ++i) + { + for (int j = 0; j < matrix.ncloc(); ++j) + { + const int irglb = distrib == nullptr ? i : distrib->irglb(i); + const int icglb = distrib == nullptr ? j : distrib->icglb(j); + matrix.atloc(i, j) = irglb == icglb ? T(1.0) : T(); + } + } +} + +void assert_inverse_view(const Matrix2dView& matrix) +{ + if (matrix.nrglb() <= 0 || matrix.nrglb() != matrix.ncglb()) + { + throw std::invalid_argument("matrix inverse requires a non-empty square matrix"); + } +} + +void assert_inverse_view(const Matrix2dView>& matrix) +{ + if (matrix.nrglb() <= 0 || matrix.nrglb() != matrix.ncglb()) + { + throw std::invalid_argument("matrix inverse requires a non-empty square matrix"); + } +} + +void assert_solve_views(const Matrix2dView& matrix, + const Matrix2dView& rhs) +{ + if (matrix.nrglb() <= 0 + || matrix.nrglb() != matrix.ncglb() + || rhs.nrglb() != matrix.nrglb()) + { + throw std::invalid_argument( + "linear solve requires a square matrix and matching right-hand side"); + } + if (matrix.has_distribution() != rhs.has_distribution()) + { + throw std::invalid_argument( + "linear solve requires matching host or distributed layouts"); + } + if (distribution_is_serial(matrix) != distribution_is_serial(rhs)) + { + throw std::invalid_argument( + "linear solve requires matching serial or parallel distributions"); + } + if (distribution_is_serial(matrix)) + { + return; + } + if (!matrix.has_distribution()) + { + return; + } +#ifdef __MPI + matrix2d_impl::scalapack::assert_compatible_layout(matrix.desc(), + rhs.desc()); +#else + throw std::invalid_argument( + "linear solve requires MPI-compatible distributed layouts"); +#endif +} + +void assert_solve_views(const Matrix2dView>& matrix, + const Matrix2dView>& rhs) +{ + if (matrix.nrglb() <= 0 + || matrix.nrglb() != matrix.ncglb() + || rhs.nrglb() != matrix.nrglb()) + { + throw std::invalid_argument( + "linear solve requires a square matrix and matching right-hand side"); + } + if (matrix.has_distribution() != rhs.has_distribution()) + { + throw std::invalid_argument( + "linear solve requires matching host or distributed layouts"); + } + if (distribution_is_serial(matrix) != distribution_is_serial(rhs)) + { + throw std::invalid_argument( + "linear solve requires matching serial or parallel distributions"); + } + if (distribution_is_serial(matrix)) + { + return; + } + if (!matrix.has_distribution()) + { + return; + } +#ifdef __MPI + matrix2d_impl::scalapack::assert_compatible_layout(matrix.desc(), + rhs.desc()); +#else + throw std::invalid_argument( + "linear solve requires MPI-compatible distributed layouts"); +#endif +} + +template +void assert_supported_linalg_type() +{ + static_assert(std::is_same::value + || std::is_same>::value, + "linear algebra supports double and std::complex"); +} + +template +Matrix2d make_matrix_like(const Matrix2d& source, + const int nrglb, + const int ncglb) +{ + if (!source.has_distribution()) + { + return Matrix2d(nrglb, ncglb); + } + if (!source.is_active()) + { + return Matrix2d(make_frozen_distribution(nrglb, ncglb)); + } +#ifdef __MPI + if (source.nrglb() == nrglb && source.ncglb() == ncglb) + { + return Matrix2d(source.distribution()); + } + const int nb = source.distribution()->nb(); + const std::shared_ptr result_distribution + = make_borrowed_distribution(nrglb, + ncglb, + nb, + source.distribution()); + return Matrix2d(result_distribution); +#else + static_cast(nrglb); + static_cast(ncglb); + throw std::invalid_argument("distributed matrices require MPI support"); +#endif +} +} // namespace + +namespace matrix2d_linalg +{ +void inv_inplace(Matrix2dView matrix) +{ + assert_inverse_view(matrix); + if (distribution_is_active(matrix)) + { +#ifdef __MPI + matrix2d_impl::scalapack::inv(matrix); +#else + throw std::invalid_argument("distributed inverse requires MPI support"); +#endif + return; + } + matrix2d_impl::lapack::inv(matrix); +} + +void inv_inplace(Matrix2dView> matrix) +{ + assert_inverse_view(matrix); + if (distribution_is_active(matrix)) + { +#ifdef __MPI + matrix2d_impl::scalapack::inv(matrix); +#else + throw std::invalid_argument("distributed inverse requires MPI support"); +#endif + return; + } + matrix2d_impl::lapack::inv(matrix); +} + +void solve_inplace(Matrix2dView matrix, + Matrix2dView rhs) +{ + assert_solve_views(matrix, rhs); + if (distribution_is_active(matrix)) + { +#ifdef __MPI + matrix2d_impl::scalapack::solve(matrix, rhs); +#else + throw std::invalid_argument("distributed solve requires MPI support"); +#endif + return; + } + matrix2d_impl::lapack::solve(matrix, rhs); +} + +void solve_inplace(Matrix2dView> matrix, + Matrix2dView> rhs) +{ + assert_solve_views(matrix, rhs); + if (distribution_is_active(matrix)) + { +#ifdef __MPI + matrix2d_impl::scalapack::solve(matrix, rhs); +#else + throw std::invalid_argument("distributed solve requires MPI support"); +#endif + return; + } + matrix2d_impl::lapack::solve(matrix, rhs); +} + +void matmul_inplace(Matrix2dView result, + Matrix2dView left, + Matrix2dView right) +{ + assert_matmul_views(result, left, right); + if (distribution_is_active(result)) + { +#ifdef __MPI + matrix2d_impl::scalapack::matmul(result, left, right); +#else + throw std::invalid_argument("distributed matmul requires MPI support"); +#endif + return; + } + matmul_host(result, left, right); +} + +void matmul_inplace(Matrix2dView> result, + Matrix2dView> left, + Matrix2dView> right) +{ + assert_matmul_views(result, left, right); + if (distribution_is_active(result)) + { +#ifdef __MPI + matrix2d_impl::scalapack::matmul(result, left, right); +#else + throw std::invalid_argument("distributed matmul requires MPI support"); +#endif + return; + } + matmul_host(result, left, right); +} + +void axpby_inplace(Matrix2dView result, + const double alpha, + Matrix2dView left, + const double beta, + Matrix2dView right) +{ + axpby_impl(result, alpha, left, beta, right); +} + +void axpby_inplace( + Matrix2dView> result, + const std::complex alpha, + Matrix2dView> left, + const std::complex beta, + Matrix2dView> right) +{ + axpby_impl(result, alpha, left, beta, right); +} + +void scale_inplace(Matrix2dView matrix, const double factor) +{ + scale_impl(matrix, factor); +} + +void scale_inplace(Matrix2dView> matrix, + const std::complex factor) +{ + scale_impl(matrix, factor); +} + +void set_identity_inplace(Matrix2dView matrix) +{ + set_identity_impl(matrix); +} + +void set_identity_inplace(Matrix2dView> matrix) +{ + set_identity_impl(matrix); +} + +template +Matrix2d inv(const Matrix2d& matrix) +{ + assert_supported_linalg_type(); + Matrix2d inverse = matrix; + inv_inplace(inverse.view()); + return inverse; +} + +template +void inv(const Matrix2d& matrix, Matrix2d& inverse) +{ + Matrix2d inverse_result = inv(matrix); + inverse = std::move(inverse_result); +} + +template +Matrix2d solve(const Matrix2d& matrix, + const Matrix2d& rhs) +{ + assert_supported_linalg_type(); + Matrix2d matrix_copy = matrix; + Matrix2d solution = rhs; + solve_inplace(matrix_copy.view(), solution.view()); + return solution; +} + +template +void solve(const Matrix2d& matrix, + const Matrix2d& rhs, + Matrix2d& solution) +{ + Matrix2d solution_result = solve(matrix, rhs); + solution = std::move(solution_result); +} + +template +Matrix2d matmul(const Matrix2d& left, + const Matrix2d& right) +{ + assert_supported_linalg_type(); + const int nrglb = left.nrglb(); + const int ncglb = right.ncglb(); + Matrix2d result = make_matrix_like(left, nrglb, ncglb); + matmul_inplace(result.view(), left.view(), right.view()); + return result; +} + +template +void matmul(const Matrix2d& left, + const Matrix2d& right, + Matrix2d& result) +{ + Matrix2d product = matmul(left, right); + result = std::move(product); +} + +template +Matrix2d axpby(const T alpha, + const Matrix2d& left, + const T beta, + const Matrix2d& right) +{ + assert_supported_linalg_type(); + const int nrglb = left.nrglb(); + const int ncglb = left.ncglb(); + Matrix2d result + = make_matrix_like(left, nrglb, ncglb); + axpby_inplace(result.view(), + alpha, + left.view(), + beta, + right.view()); + return result; +} + +template +void axpby(const T alpha, + const Matrix2d& left, + const T beta, + const Matrix2d& right, + Matrix2d& result) +{ + Matrix2d combination = axpby(alpha, left, beta, right); + result = std::move(combination); +} + +template +Matrix2d scale(const Matrix2d& matrix, const T factor) +{ + assert_supported_linalg_type(); + Matrix2d result = matrix; + scale_inplace(result.view(), factor); + return result; +} + +template +void scale(const Matrix2d& matrix, + const T factor, + Matrix2d& result) +{ + Matrix2d scaled = scale(matrix, factor); + result = std::move(scaled); +} + +template +Matrix2d eye(const int n) +{ + static_assert(std::is_same::value + || std::is_same>::value, + "eye supports double and std::complex"); + Matrix2d matrix(n, n); + set_identity_inplace(matrix.view()); + return matrix; +} + +template +Matrix2d transpose(const Matrix2d& matrix) +{ + return matrix.transpose(); +} + +template +Matrix2d dagger(const Matrix2d& matrix) +{ + return matrix.dagger(); +} + +template Matrix2d inv(const Matrix2d& matrix); +template void inv(const Matrix2d& matrix, + Matrix2d& inverse); +template Matrix2d> inv>( + const Matrix2d>& matrix); +template void inv>( + const Matrix2d>& matrix, + Matrix2d>& inverse); + +template Matrix2d solve(const Matrix2d& matrix, + const Matrix2d& rhs); +template void solve(const Matrix2d& matrix, + const Matrix2d& rhs, + Matrix2d& solution); +template Matrix2d> solve>( + const Matrix2d>& matrix, + const Matrix2d>& rhs); +template void solve>( + const Matrix2d>& matrix, + const Matrix2d>& rhs, + Matrix2d>& solution); + +template Matrix2d matmul(const Matrix2d& left, + const Matrix2d& right); +template void matmul(const Matrix2d& left, + const Matrix2d& right, + Matrix2d& result); +template Matrix2d> matmul>( + const Matrix2d>& left, + const Matrix2d>& right); +template void matmul>( + const Matrix2d>& left, + const Matrix2d>& right, + Matrix2d>& result); + +template Matrix2d axpby(const double alpha, + const Matrix2d& left, + const double beta, + const Matrix2d& right); +template void axpby(const double alpha, + const Matrix2d& left, + const double beta, + const Matrix2d& right, + Matrix2d& result); +template Matrix2d> axpby>( + const std::complex alpha, + const Matrix2d>& left, + const std::complex beta, + const Matrix2d>& right); +template void axpby>( + const std::complex alpha, + const Matrix2d>& left, + const std::complex beta, + const Matrix2d>& right, + Matrix2d>& result); + +template Matrix2d scale(const Matrix2d& matrix, + const double factor); +template void scale(const Matrix2d& matrix, + const double factor, + Matrix2d& result); +template Matrix2d> scale>( + const Matrix2d>& matrix, + const std::complex factor); +template void scale>( + const Matrix2d>& matrix, + const std::complex factor, + Matrix2d>& result); + +template Matrix2d eye(const int n); +template Matrix2d> eye>(const int n); +template Matrix2d transpose(const Matrix2d& matrix); +template Matrix2d> transpose>( + const Matrix2d>& matrix); +template Matrix2d dagger(const Matrix2d& matrix); +template Matrix2d> dagger>( + const Matrix2d>& matrix); +} // namespace matrix2d_linalg diff --git a/source/source_base/matrix2d_linalg.h b/source/source_base/matrix2d_linalg.h new file mode 100644 index 00000000000..02393e913ff --- /dev/null +++ b/source/source_base/matrix2d_linalg.h @@ -0,0 +1,255 @@ +#ifndef ABACUS_SOURCE_SOURCE_BASE_MATRIX2D_LINALG_H +#define ABACUS_SOURCE_SOURCE_BASE_MATRIX2D_LINALG_H + +#include "source_base/matrix2d.h" +#include "source_base/matrix2d_view.h" + +#include + +namespace matrix2d_linalg +{ +/** + * Value-returning overloads return `Matrix2d` by value. `Matrix2d` has + * defaulted copy and move operations, so C++11 return-value optimization or + * the move constructor transfers ownership without a deep result copy. + */ + +/** + * @brief Return the inverse of a square matrix. + * + * The input matrix is unchanged. The result has the same host or frozen + * distributed layout as the input and is collective when the input is an + * active MPI distribution. + * + * @warning Explicit inversion has poorer numerical stability than solving a + * linear system directly. Use this function only when the inverse matrix + * itself is required. When solving `A * X = B`, call `solve()` instead. + * + * @tparam T Either `double` or `std::complex`. + */ +template +Matrix2d inv(const Matrix2d& matrix); + +/** + * @brief Write the inverse of a square matrix into an existing matrix. + * + * The input matrix is unchanged. `inverse` receives a complete result with + * the same host or frozen distributed layout as the input. + * + * @tparam T Either `double` or `std::complex`. + */ +template +void inv(const Matrix2d& matrix, Matrix2d& inverse); + +/** + * @brief Invert a square matrix in place without copying. + * + * @param matrix `inout` square matrix. It is overwritten by its inverse. + * + * This is a low-level escape hatch over caller-owned storage. Prefer `inv()` + * unless avoiding the input copy is essential. + */ +void inv_inplace(Matrix2dView matrix); +/** @copydoc inv_inplace(Matrix2dView) */ +void inv_inplace(Matrix2dView> matrix); + +/** + * @brief Return the solution X of `A * X = B`. + * + * `matrix` and `rhs` are unchanged. The result has the same host or frozen + * distributed layout as `rhs`. When `rhs` is actively distributed, this + * operation is collective and every rank must call it. + * + * @tparam T Either `double` or `std::complex`. + */ +template +Matrix2d solve(const Matrix2d& matrix, + const Matrix2d& rhs); + +/** + * @brief Write the solution X of `A * X = B` into an existing matrix. + * + * `matrix` and `rhs` are unchanged. `solution` receives a complete result + * with the same host or frozen distributed layout as `rhs`. The output may + * alias either input. + * + * @tparam T Either `double` or `std::complex`. + */ +template +void solve(const Matrix2d& matrix, + const Matrix2d& rhs, + Matrix2d& solution); + +/** + * @brief Solve `A * X = B` in place without copying. + * + * @param matrix `inout` coefficient matrix. It is overwritten by its LU + * factorization. + * @param rhs `inout` right-hand side. It is overwritten by the solution X. + * + * This is a low-level escape hatch for callers that explicitly accept the + * mutation. Prefer `solve()` unless avoiding both input copies is essential. + * The operation is collective for active MPI distributions. + */ +void solve_inplace(Matrix2dView matrix, + Matrix2dView rhs); +/** @copydoc solve_inplace(Matrix2dView,Matrix2dView) */ +void solve_inplace(Matrix2dView> matrix, + Matrix2dView> rhs); + +/** + * @brief Return the matrix product `A * B`. + * + * Both inputs are unchanged. The result has a host layout when the inputs are + * host matrices. For distributed inputs it carries the left input's process + * grid, block size, and BLACS context and the operation is collective. + * + * @tparam T Either `double` or `std::complex`. + */ +template +Matrix2d matmul(const Matrix2d& left, + const Matrix2d& right); + +/** + * @brief Write the matrix product `A * B` into an existing matrix. + * + * Both inputs are unchanged. `result` receives a result with the layout rules + * described by `matmul(left, right)`. The output may alias either input. + * + * @tparam T Either `double` or `std::complex`. + */ +template +void matmul(const Matrix2d& left, + const Matrix2d& right, + Matrix2d& result); + +/** + * @brief Multiply two matrix views into result. + * + * The result storage must not overlap either input. Exact alias as well as + * shifted or partial overlap is unsupported because the implementation writes + * result while still reading left and right. + * + * @param result `out` matrix receiving the product. + * @param left Read-only left input. + * @param right Read-only right input. + */ +void matmul_inplace(Matrix2dView result, + Matrix2dView left, + Matrix2dView right); +/** + * @copydoc matmul_inplace(Matrix2dView,Matrix2dView,Matrix2dView) + */ +void matmul_inplace(Matrix2dView> result, + Matrix2dView> left, + Matrix2dView> right); + +/** + * @brief Return `alpha * left + beta * right`. + * + * The result is newly allocated with the same layout as `left`. Inputs are + * unchanged. + * + * @tparam T Either `double` or `std::complex`. + */ +template +Matrix2d axpby(const T alpha, + const Matrix2d& left, + const T beta, + const Matrix2d& right); + +/** + * @brief Write `alpha * left + beta * right` into an existing matrix. + * + * The output may alias either input. It receives the layout of `left`. + * + * @tparam T Either `double` or `std::complex`. + */ +template +void axpby(const T alpha, + const Matrix2d& left, + const T beta, + const Matrix2d& right, + Matrix2d& result); + +/** + * @brief Compute `result = alpha * left + beta * right` through views. + * + * All views must have the same global shape and compatible host or distributed + * layouts. The result may alias either input only when the aliased views use + * the same element mapping for every logical coordinate, including a fully + * in-place call such as `result == left`. Shifted and partial overlap are + * unsupported because a write may invalidate an input read by another element + * or OpenMP thread. + * + * @param result `inout` matrix receiving the combination. + */ +void axpby_inplace(Matrix2dView result, + const double alpha, + Matrix2dView left, + const double beta, + Matrix2dView right); +/** + * @copydoc axpby_inplace(Matrix2dView,double,Matrix2dView,double,Matrix2dView) + */ +void axpby_inplace( + Matrix2dView> result, + const std::complex alpha, + Matrix2dView> left, + const std::complex beta, + Matrix2dView> right); + +/** @brief Return a newly allocated copy of `matrix` scaled by `factor`. */ +template +Matrix2d scale(const Matrix2d& matrix, const T factor); + +/** @brief Write a scaled copy of `matrix` into `result`. */ +template +void scale(const Matrix2d& matrix, + const T factor, + Matrix2d& result); + +/** + * @brief Scale a matrix view in place without copying. + * + * @param matrix `inout` matrix to scale. + * @param factor Scalar multiplier. + */ +void scale_inplace(Matrix2dView matrix, const double factor); +/** @copydoc scale_inplace(Matrix2dView,double) */ +void scale_inplace(Matrix2dView> matrix, + const std::complex factor); + +/** + * @brief Write the identity matrix into an existing square view. + * + * @param matrix `inout` square matrix receiving the identity. + * + * This is a low-level zero-copy operation. Prefer `eye()` when a new identity + * matrix is required. + */ +void set_identity_inplace(Matrix2dView matrix); +/** @copydoc set_identity_inplace(Matrix2dView) */ +void set_identity_inplace(Matrix2dView> matrix); + +/** + * @brief Create a new `n` by `n` identity matrix. + * + * The returned matrix owns host storage. Use `set_identity_inplace()` only + * when an existing view should be overwritten without allocating. + * + * @tparam T Either `double` or `std::complex`. + */ +template +Matrix2d eye(const int n); + +/** @brief Return the non-conjugate transpose of `matrix`. */ +template +Matrix2d transpose(const Matrix2d& matrix); + +/** @brief Return the conjugate transpose of `matrix`. */ +template +Matrix2d dagger(const Matrix2d& matrix); +} // namespace matrix2d_linalg + +#endif diff --git a/source/source_base/matrix2d_mpi.cpp b/source/source_base/matrix2d_mpi.cpp new file mode 100644 index 00000000000..d2e6667dd26 --- /dev/null +++ b/source/source_base/matrix2d_mpi.cpp @@ -0,0 +1,62 @@ +#include "source_base/matrix2d_mpi.h" + +#ifdef __MPI +#include "source_base/module_parallel/para_mpi_func.h" +#include "source_base/module_parallel/para_world.h" + +#include +#include + +namespace matrix2d_impl +{ +namespace mpi +{ +int checked_mpi_count(const std::size_t nbytes) +{ + // FIXME: BLACS and ScaLAPACK interfaces still expose native int + // dimensions. Revisit this size_t-to-int boundary when those interfaces + // are migrated together. + if (nbytes > static_cast(std::numeric_limits::max())) + { + throw std::invalid_argument( + "Matrix2d MPI buffer exceeds the native int count range"); + } + return static_cast(nbytes); +} + +std::vector make_byte_offsets(const std::vector& nbytes) +{ + std::vector offsets(nbytes.size(), 0); + int offset = 0; + for (std::size_t ip = 0; ip < nbytes.size(); ++ip) + { + offsets[ip] = offset; + if (nbytes[ip] > std::numeric_limits::max() - offset) + { + throw std::invalid_argument( + "Matrix2d MPI buffer size overflow"); + } + offset += nbytes[ip]; + } + return offsets; +} + +std::vector allgather_nbytes(const int nbytes_local, + const MPI_Comm comm) +{ + const Parallel::ParaWorld world + = Parallel::ParaWorld::make_mpi("matrix2d_mpi_counts", comm); + if (!world.valid()) + { + throw std::invalid_argument( + "Matrix2d MPI count collection requires a valid communicator"); + } + + int rank_nbytes = nbytes_local; + std::vector nbytes(static_cast(world.size()), 0); + Parallel::allgather_int(rank_nbytes, nbytes.data(), world); + return nbytes; +} +} // namespace mpi +} // namespace matrix2d_impl +#endif diff --git a/source/source_base/matrix2d_mpi.h b/source/source_base/matrix2d_mpi.h new file mode 100644 index 00000000000..44ed89f9462 --- /dev/null +++ b/source/source_base/matrix2d_mpi.h @@ -0,0 +1,33 @@ +#ifndef ABACUS_SOURCE_SOURCE_BASE_MATRIX2D_MPI_H +#define ABACUS_SOURCE_SOURCE_BASE_MATRIX2D_MPI_H + +/** + * @file matrix2d_mpi.h + * @internal + * @brief MPI bookkeeping shared by Matrix2d backend implementations. + * + * This header is not part of the public Matrix2d interface. Callers should + * include `source_base/matrix2d.h` or `source_base/matrix2d_linalg.h` instead. + */ + +#ifdef __MPI +#include "mpi.h" + +#include +#include + +namespace matrix2d_impl +{ +namespace mpi +{ +int checked_mpi_count(const std::size_t nbytes); + +std::vector make_byte_offsets(const std::vector& nbytes); + +std::vector allgather_nbytes(const int nbytes_local, + const MPI_Comm comm); +} // namespace mpi +} // namespace matrix2d_impl +#endif + +#endif diff --git a/source/source_base/matrix2d_reduction.cpp b/source/source_base/matrix2d_reduction.cpp new file mode 100644 index 00000000000..5e17ec5512c --- /dev/null +++ b/source/source_base/matrix2d_reduction.cpp @@ -0,0 +1,407 @@ +#include "source_base/matrix2d_reduction.h" + +#include "source_base/parallel_common.h" +#ifdef __MPI +#include "source_base/matrix2d_mpi.h" +#endif + +#include +#include +#include +#include +#include +#include +#include + +#ifdef _OPENMP +#include +#endif + +namespace +{ +// Width in bytes of a native int in the homogeneous diagonal wire format. +constexpr int W_INT = sizeof(int); + +#ifdef __MPI +namespace mpi = matrix2d_impl::mpi; +#endif + +namespace elementwise +{ +template +T conj(const T& value) +{ + return value; +} + +template +std::complex conj(const std::complex& value) +{ + return std::conj(value); +} +} // namespace elementwise + +template +double abs2(const T& value) +{ + const double real_value = static_cast(value); + return real_value * real_value; +} + +template +double abs2(const std::complex& value) +{ + const double real = static_cast(value.real()); + const double imag = static_cast(value.imag()); + return real * real + imag * imag; +} + +template +double absolute_value(const T& value) +{ + const double widened_value = static_cast(value); + return std::abs(widened_value); +} + +template +double absolute_value(const std::complex& value) +{ + const double real = static_cast(value.real()); + const double imag = static_cast(value.imag()); + return std::hypot(real, imag); +} + +template +void reduce_sum_over_processes(Value& value, const Matrix2d& matrix) +{ +#ifdef __MPI + const std::shared_ptr distrib + = matrix.distribution(); + if (distrib != nullptr && !distrib->is_serial()) + { + const MPI_Comm comm = distrib->comm(); + if (comm != MPI_COMM_NULL) + { + Parallel_Common::allreduce_sum(value, comm); + } + } +#else + static_cast(value); + static_cast(matrix); +#endif +} + +template +void reduce_max_over_processes(double& value, const Matrix2d& matrix) +{ +#ifdef __MPI + const std::shared_ptr distrib + = matrix.distribution(); + if (distrib != nullptr && !distrib->is_serial()) + { + const MPI_Comm comm = distrib->comm(); + if (comm != MPI_COMM_NULL) + { + Parallel_Common::allreduce_max(value, comm); + } + } +#else + static_cast(value); + static_cast(matrix); +#endif +} + +} // namespace + +namespace matrix2d_impl +{ +template +T sum(const Matrix2d& matrix) +{ + T value = T(); + const int nrloc = matrix.nrloc(); + const int ncloc = matrix.ncloc(); +#ifdef _OPENMP + std::vector partial_sums(omp_get_max_threads(), T()); +#pragma omp parallel + { + const int ip = omp_get_thread_num(); +#pragma omp for collapse(2) schedule(static) + for (int i = 0; i < nrloc; ++i) + { + for (int j = 0; j < ncloc; ++j) + { + partial_sums[ip] += matrix.atloc(i, j); + } + } + } + for (const T& partial_sum : partial_sums) + { + value += partial_sum; + } +#else + for (int i = 0; i < nrloc; ++i) + { + for (int j = 0; j < ncloc; ++j) + { + value += matrix.atloc(i, j); + } + } +#endif + reduce_sum_over_processes(value, matrix); + return value; +} + +template +real_type norm(const Matrix2d& matrix) +{ + double value = 0.0; + const int nrloc = matrix.nrloc(); + const int ncloc = matrix.ncloc(); +#ifdef _OPENMP +#pragma omp parallel for collapse(2) reduction(+ : value) schedule(static) +#endif + for (int i = 0; i < nrloc; ++i) + { + for (int j = 0; j < ncloc; ++j) + { + const T& element = matrix.atloc(i, j); + value += abs2(element); + } + } + reduce_sum_over_processes(value, matrix); + const real_type result = static_cast>(std::sqrt(value)); + return result; +} + +template +T dot(const Matrix2d& left, const Matrix2d& right) +{ + T value = T(); + const int nrloc = left.nrloc(); + const int ncloc = left.ncloc(); +#ifdef _OPENMP + std::vector partial_sums(omp_get_max_threads(), T()); +#pragma omp parallel + { + const int ip = omp_get_thread_num(); +#pragma omp for collapse(2) schedule(static) + for (int i = 0; i < nrloc; ++i) + { + for (int j = 0; j < ncloc; ++j) + { + partial_sums[ip] += elementwise::conj(left.atloc(i, j)) + * right.atloc(i, j); + } + } + } + for (const T& partial_sum : partial_sums) + { + value += partial_sum; + } +#else + for (int i = 0; i < nrloc; ++i) + { + for (int j = 0; j < ncloc; ++j) + { + value += elementwise::conj(left.atloc(i, j)) + * right.atloc(i, j); + } + } +#endif + reduce_sum_over_processes(value, left); + return value; +} + +template +real_type max_abs(const Matrix2d& matrix) +{ + double max_value = 0.0; + const int nrloc = matrix.nrloc(); + const int ncloc = matrix.ncloc(); +#ifdef _OPENMP +#pragma omp parallel for collapse(2) reduction(max : max_value) schedule(static) +#endif + for (int i = 0; i < nrloc; ++i) + { + for (int j = 0; j < ncloc; ++j) + { + const T& element = matrix.atloc(i, j); + const double element_abs = absolute_value(element); + max_value = std::max(max_value, element_abs); + } + } + reduce_max_over_processes(max_value, matrix); + const real_type result = static_cast>(max_value); + return result; +} + +template +std::vector diagonal(const Matrix2d& matrix) +{ + const int diagonal_size = std::min(matrix.nrglb(), matrix.ncglb()); + std::vector values(static_cast(diagonal_size), T()); + const int nrloc = matrix.nrloc(); + const int ncloc = matrix.ncloc(); + const std::shared_ptr distrib + = matrix.distribution(); + std::vector> local_entries; + for (int irloc = 0; irloc < nrloc; ++irloc) + { + for (int icloc = 0; icloc < ncloc; ++icloc) + { + const int irglb = distrib == nullptr ? irloc : distrib->irglb(irloc); + const int icglb = distrib == nullptr ? icloc : distrib->icglb(icloc); + if (irglb == icglb && irglb < diagonal_size) + { + const T value = matrix.atloc(irloc, icloc); + local_entries.push_back(std::pair(irglb, value)); + } + } + } +#ifdef __MPI + if (distrib != nullptr && !distrib->is_serial()) + { + const MPI_Comm comm = distrib->comm(); + if (comm != MPI_COMM_NULL) + { + const std::size_t nbytes_entry = W_INT + sizeof(T); + const std::size_t nbytes_local + = W_INT + local_entries.size() * nbytes_entry; + std::vector local_diagonal_buffer(nbytes_local); + const int nentry_local + = mpi::checked_mpi_count(local_entries.size()); + std::memcpy(local_diagonal_buffer.data(), + &nentry_local, + W_INT); + std::size_t offset = W_INT; + for (const std::pair& entry : local_entries) + { + std::memcpy(local_diagonal_buffer.data() + offset, + &entry.first, + sizeof(entry.first)); + offset += sizeof(entry.first); + std::memcpy(local_diagonal_buffer.data() + offset, + &entry.second, + sizeof(entry.second)); + offset += sizeof(entry.second); + } + + const int nbytes_local_mpi + = mpi::checked_mpi_count(nbytes_local); + const std::vector nbytes_recv + = mpi::allgather_nbytes(nbytes_local_mpi, comm); + const std::vector rdispls + = mpi::make_byte_offsets(nbytes_recv); + const int total_bytes + = rdispls.back() + nbytes_recv.back(); + std::vector received( + static_cast(total_bytes)); + Parallel_Common::allgatherv_bytes(local_diagonal_buffer.data(), + nbytes_local_mpi, + received.data(), + nbytes_recv.data(), + rdispls.data(), + comm); + + for (std::size_t ip = 0; ip < nbytes_recv.size(); ++ip) + { + const std::size_t begin + = static_cast(rdispls[ip]); + const std::size_t end + = begin + static_cast(nbytes_recv[ip]); + if (end - begin < W_INT) + { + throw std::runtime_error( + "Matrix2d diagonal data buffer is truncated"); + } + int nentry = 0; + std::memcpy(&nentry, + received.data() + begin, + sizeof(nentry)); + const std::size_t nbytes_expected + = static_cast(nentry) * nbytes_entry; + if (nentry < 0 + || end - begin != W_INT + nbytes_expected) + { + throw std::runtime_error( + "Matrix2d diagonal data buffer has an invalid size"); + } + std::size_t entry_offset = begin + sizeof(nentry); + for (int ientry = 0; ientry < nentry; ++ientry) + { + int irglb = 0; + T value = T(); + std::memcpy(&irglb, + received.data() + entry_offset, + W_INT); + entry_offset += W_INT; + std::memcpy(&value, + received.data() + entry_offset, + sizeof(value)); + entry_offset += sizeof(value); + if (irglb < 0 || irglb >= diagonal_size) + { + throw std::runtime_error( + "Matrix2d diagonal entry is outside global shape"); + } + values[static_cast(irglb)] += value; + } + } + } + } +#endif + if (distrib == nullptr || distrib->is_serial()) + { + for (const std::pair& entry : local_entries) + { + values[static_cast(entry.first)] += entry.second; + } + } + return values; +} + +template int sum(const Matrix2d& matrix); +template float sum(const Matrix2d& matrix); +template double sum(const Matrix2d& matrix); +template std::complex sum>( + const Matrix2d>& matrix); +template std::complex sum>( + const Matrix2d>& matrix); + +template int dot(const Matrix2d& left, const Matrix2d& right); +template float dot(const Matrix2d& left, + const Matrix2d& right); +template double dot(const Matrix2d& left, + const Matrix2d& right); +template std::complex dot>( + const Matrix2d>& left, + const Matrix2d>& right); +template std::complex dot>( + const Matrix2d>& left, + const Matrix2d>& right); + +template real_type norm(const Matrix2d& matrix); +template real_type norm(const Matrix2d& matrix); +template real_type norm(const Matrix2d& matrix); +template real_type> norm>( + const Matrix2d>& matrix); +template real_type> norm>( + const Matrix2d>& matrix); + +template real_type max_abs(const Matrix2d& matrix); +template real_type max_abs(const Matrix2d& matrix); +template real_type max_abs(const Matrix2d& matrix); +template real_type> max_abs>( + const Matrix2d>& matrix); +template real_type> max_abs>( + const Matrix2d>& matrix); + +template std::vector diagonal(const Matrix2d& matrix); +template std::vector diagonal(const Matrix2d& matrix); +template std::vector diagonal(const Matrix2d& matrix); +template std::vector> diagonal>( + const Matrix2d>& matrix); +template std::vector> diagonal>( + const Matrix2d>& matrix); +} // namespace matrix2d_impl diff --git a/source/source_base/matrix2d_reduction.h b/source/source_base/matrix2d_reduction.h new file mode 100644 index 00000000000..fd757b67d05 --- /dev/null +++ b/source/source_base/matrix2d_reduction.h @@ -0,0 +1,32 @@ +#ifndef ABACUS_SOURCE_SOURCE_BASE_MATRIX2D_REDUCTION_H +#define ABACUS_SOURCE_SOURCE_BASE_MATRIX2D_REDUCTION_H + +/** + * @file matrix2d_reduction.h + * @internal + * @brief Matrix2d reduction backend declarations. + * + * Callers should include `source_base/matrix2d.h` instead of this header. + */ + +#include "source_base/matrix2d.h" + +namespace matrix2d_impl +{ +template +T sum(const Matrix2d& matrix); + +template +T dot(const Matrix2d& left, const Matrix2d& right); + +template +real_type norm(const Matrix2d& matrix); + +template +real_type max_abs(const Matrix2d& matrix); + +template +std::vector diagonal(const Matrix2d& matrix); +} // namespace matrix2d_impl + +#endif diff --git a/source/source_base/matrix2d_scalapack.cpp b/source/source_base/matrix2d_scalapack.cpp new file mode 100644 index 00000000000..7b9814cad9a --- /dev/null +++ b/source/source_base/matrix2d_scalapack.cpp @@ -0,0 +1,409 @@ +#include "source_base/matrix2d_scalapack.h" + +#ifdef __MPI +#include "source_base/module_external/scalapack_connector.h" +#include "source_base/matrix2d_view.h" + +#include +#include +#include +#include + +namespace matrix2d_impl +{ +namespace scalapack +{ +void assert_compatible_layout(const int* left_desc, + const int* right_desc) +{ + if (left_desc == nullptr + || right_desc == nullptr + || left_desc[1] != right_desc[1] + || left_desc[4] != right_desc[4] + || left_desc[5] != right_desc[5] + || left_desc[6] != right_desc[6] + || left_desc[7] != right_desc[7]) + { + throw std::invalid_argument( + "matrix operations require compatible ScaLAPACK descriptors"); + } +} + +void transpose(Matrix2dView result, + Matrix2dView source) +{ + const int m = source.nrglb(); + const int n = source.ncglb(); + const double alpha = 1.0; + const double* source_data = source.data(); + const int ia = 1; + const int ja = 1; + const int* desc_src = source.desc(); + const double beta = 0.0; + double* result_data = result.data(); + const int ic = 1; + const int jc = 1; + const int* desc_res = result.desc(); + ScalapackConnector::tranu( + /* m= */ n, + /* n= */ m, + /* alpha= */ alpha, + /* a= */ source_data, + /* ia= */ ia, + /* ja= */ ja, + /* desca= */ desc_src, + /* beta= */ beta, + /* c= */ result_data, + /* ic= */ ic, + /* jc= */ jc, + /* descc= */ desc_res); +} + +void conjugate_transpose(Matrix2dView result, + Matrix2dView source) +{ + transpose(result, source); +} + +void transpose(Matrix2dView> result, + Matrix2dView> source) +{ + const int m = source.nrglb(); + const int n = source.ncglb(); + const std::complex alpha(1.0, 0.0); + const std::complex* source_data = source.data(); + const int ia = 1; + const int ja = 1; + const int* desc_src = source.desc(); + const std::complex beta(0.0, 0.0); + std::complex* result_data = result.data(); + const int ic = 1; + const int jc = 1; + const int* desc_res = result.desc(); + ScalapackConnector::tranu( + /* m= */ n, + /* n= */ m, + /* alpha= */ alpha, + /* a= */ source_data, + /* ia= */ ia, + /* ja= */ ja, + /* desca= */ desc_src, + /* beta= */ beta, + /* c= */ result_data, + /* ic= */ ic, + /* jc= */ jc, + /* descc= */ desc_res); +} + +void conjugate_transpose( + Matrix2dView> result, + Matrix2dView> source) +{ + const int m = source.nrglb(); + const int n = source.ncglb(); + const std::complex alpha(1.0, 0.0); + const std::complex* source_data = source.data(); + const int ia = 1; + const int ja = 1; + const int* desc_src = source.desc(); + const std::complex beta(0.0, 0.0); + std::complex* result_data = result.data(); + const int ic = 1; + const int jc = 1; + const int* desc_res = result.desc(); + ScalapackConnector::tranc( + /* m= */ n, + /* n= */ m, + /* alpha= */ alpha, + /* a= */ source_data, + /* ia= */ ia, + /* ja= */ ja, + /* desca= */ desc_src, + /* beta= */ beta, + /* c= */ result_data, + /* ic= */ ic, + /* jc= */ jc, + /* descc= */ desc_res); +} + +namespace +{ +void throw_scalapack_error(const char* operation, const int info) +{ + if (info < 0) + { + throw std::invalid_argument(std::string(operation) + + " received an invalid argument"); + } + if (info > 0) + { + throw std::runtime_error(std::string(operation) + + " failed because the matrix is singular"); + } +} + +template +int queried_workspace_size(const T& value) +{ + return static_cast(value); +} + +int queried_workspace_size(const std::complex& value) +{ + return static_cast(value.real()); +} +} // namespace + +void inv(Matrix2dView matrix) +{ + const int n = matrix.nrglb(); + const int ia = 1; + const int ja = 1; + const int* desc = matrix.desc(); + const int pivot_size = matrix.nrloc() + desc[4]; + std::vector ipiv(static_cast(pivot_size)); + int info = 0; + ScalapackConnector::getrf(n, + n, + matrix.data(), + ia, + ja, + desc, + ipiv.data(), + &info); + throw_scalapack_error("ScaLAPACK getrf", info); + + int lws = -1; + int liws = -1; + std::vector ws(1); + std::vector iws(1); + ScalapackConnector::getri(n, + matrix.data(), + ia, + ja, + desc, + ipiv.data(), + ws.data(), + &lws, + iws.data(), + &liws, + &info); + throw_scalapack_error("ScaLAPACK getri workspace query", info); + lws = queried_workspace_size(ws[0]); + liws = iws[0]; + ws.resize(static_cast(lws)); + iws.resize(static_cast(liws)); + ScalapackConnector::getri(n, + matrix.data(), + ia, + ja, + desc, + ipiv.data(), + ws.data(), + &lws, + iws.data(), + &liws, + &info); + throw_scalapack_error("ScaLAPACK getri", info); +} + +void inv(Matrix2dView> matrix) +{ + const int n = matrix.nrglb(); + const int ia = 1; + const int ja = 1; + const int* desc = matrix.desc(); + const int pivot_size = matrix.nrloc() + desc[4]; + std::vector ipiv(static_cast(pivot_size)); + int info = 0; + ScalapackConnector::getrf(n, + n, + matrix.data(), + ia, + ja, + desc, + ipiv.data(), + &info); + throw_scalapack_error("ScaLAPACK getrf", info); + + int lws = -1; + int liws = -1; + std::vector> ws(1); + std::vector iws(1); + ScalapackConnector::getri(n, + matrix.data(), + ia, + ja, + desc, + ipiv.data(), + ws.data(), + &lws, + iws.data(), + &liws, + &info); + throw_scalapack_error("ScaLAPACK getri workspace query", info); + lws = queried_workspace_size(ws[0]); + liws = iws[0]; + ws.resize(static_cast(lws)); + iws.resize(static_cast(liws)); + ScalapackConnector::getri(n, + matrix.data(), + ia, + ja, + desc, + ipiv.data(), + ws.data(), + &lws, + iws.data(), + &liws, + &info); + throw_scalapack_error("ScaLAPACK getri", info); +} + +void solve(Matrix2dView matrix, + Matrix2dView rhs) +{ + const int n = matrix.nrglb(); + const int nrhs = rhs.ncglb(); + const int ia = 1; + const int ja = 1; + const int ib = 1; + const int jb = 1; + const int pivot_size = matrix.nrloc() + matrix.desc()[4]; + std::vector ipiv(static_cast(pivot_size)); + int info = 0; + ScalapackConnector::gesv(n, + nrhs, + matrix.data(), + ia, + ja, + matrix.desc(), + ipiv.data(), + rhs.data(), + ib, + jb, + rhs.desc(), + &info); + throw_scalapack_error("ScaLAPACK gesv", info); +} + +void solve(Matrix2dView> matrix, + Matrix2dView> rhs) +{ + const int n = matrix.nrglb(); + const int nrhs = rhs.ncglb(); + const int ia = 1; + const int ja = 1; + const int ib = 1; + const int jb = 1; + const int pivot_size = matrix.nrloc() + matrix.desc()[4]; + std::vector ipiv(static_cast(pivot_size)); + int info = 0; + ScalapackConnector::gesv(n, + nrhs, + matrix.data(), + ia, + ja, + matrix.desc(), + ipiv.data(), + rhs.data(), + ib, + jb, + rhs.desc(), + &info); + throw_scalapack_error("ScaLAPACK gesv", info); +} + +void matmul(Matrix2dView result, + Matrix2dView left, + Matrix2dView right) +{ + const char transa = 'N'; + const char transb = 'N'; + const int m = left.nrglb(); + const int n = right.ncglb(); + const int k = left.ncglb(); + const double alpha = 1.0; + const double* left_data = left.data(); + const int ia = 1; + const int ja = 1; + const int* desc_lhs = left.desc(); // lhs = left operand + const double* right_data = right.data(); + const int ib = 1; + const int jb = 1; + const int* desc_rhs = right.desc(); // rhs = right operand + const double beta = 0.0; + double* result_data = result.data(); + const int ic = 1; + const int jc = 1; + const int* desc_res = result.desc(); + ScalapackConnector::gemm( + /* transa= */ transa, + /* transb= */ transb, + /* M= */ m, + /* N= */ n, + /* K= */ k, + /* alpha= */ alpha, + /* A= */ left_data, + /* IA= */ ia, + /* JA= */ ja, + /* DESCA= */ desc_lhs, + /* B= */ right_data, + /* IB= */ ib, + /* JB= */ jb, + /* DESCB= */ desc_rhs, + /* beta= */ beta, + /* C= */ result_data, + /* IC= */ ic, + /* JC= */ jc, + /* DESCC= */ desc_res); +} + +void matmul(Matrix2dView> result, + Matrix2dView> left, + Matrix2dView> right) +{ + const char transa = 'N'; + const char transb = 'N'; + const int m = left.nrglb(); + const int n = right.ncglb(); + const int k = left.ncglb(); + const std::complex alpha(1.0, 0.0); + const std::complex* left_data = left.data(); + const int ia = 1; + const int ja = 1; + const int* desc_lhs = left.desc(); + const std::complex* right_data = right.data(); + const int ib = 1; + const int jb = 1; + const int* desc_rhs = right.desc(); + const std::complex beta(0.0, 0.0); + std::complex* result_data = result.data(); + const int ic = 1; + const int jc = 1; + const int* desc_res = result.desc(); + ScalapackConnector::gemm( + /* transa= */ transa, + /* transb= */ transb, + /* M= */ m, + /* N= */ n, + /* K= */ k, + /* alpha= */ alpha, + /* A= */ left_data, + /* IA= */ ia, + /* JA= */ ja, + /* DESCA= */ desc_lhs, + /* B= */ right_data, + /* IB= */ ib, + /* JB= */ jb, + /* DESCB= */ desc_rhs, + /* beta= */ beta, + /* C= */ result_data, + /* IC= */ ic, + /* JC= */ jc, + /* DESCC= */ desc_res); +} + +} // namespace scalapack +} // namespace matrix2d_impl +#endif diff --git a/source/source_base/matrix2d_scalapack.h b/source/source_base/matrix2d_scalapack.h new file mode 100644 index 00000000000..ddfc5cc9357 --- /dev/null +++ b/source/source_base/matrix2d_scalapack.h @@ -0,0 +1,60 @@ +#ifndef ABACUS_SOURCE_SOURCE_BASE_MATRIX2D_SCALAPACK_H +#define ABACUS_SOURCE_SOURCE_BASE_MATRIX2D_SCALAPACK_H + +/** + * @file matrix2d_scalapack.h + * @internal + * @brief Matrix2d ScaLAPACK backend declarations. + * + * Callers should include `source_base/matrix2d_linalg.h` instead of this + * header. + */ + +#include + +template +class Matrix2dView; + +#ifdef __MPI +namespace matrix2d_impl +{ +namespace scalapack +{ +void assert_compatible_layout(const int* left_desc, const int* right_desc); + +void transpose(Matrix2dView result, + Matrix2dView source); +void transpose(Matrix2dView> result, + Matrix2dView> source); +void conjugate_transpose(Matrix2dView result, + Matrix2dView source); +void conjugate_transpose( + Matrix2dView> result, + Matrix2dView> source); +/** + * @brief Invert a square distributed matrix in place with P?GETRF and + * P?GETRI. + * + * @warning Explicit inversion has poorer numerical stability than solving a + * linear system directly. Use this function only when the inverse matrix + * itself is required. When solving `A * X = B`, call `solve()` instead. + */ +void inv(Matrix2dView matrix); +/** @copydoc inv(Matrix2dView) */ +void inv(Matrix2dView> matrix); +void solve(Matrix2dView matrix, + Matrix2dView rhs); +void solve(Matrix2dView> matrix, + Matrix2dView> rhs); +void matmul(Matrix2dView result, + Matrix2dView left, + Matrix2dView right); +void matmul(Matrix2dView> result, + Matrix2dView> left, + Matrix2dView> right); + +} // namespace scalapack +} // namespace matrix2d_impl +#endif + +#endif diff --git a/source/source_base/matrix2d_view.h b/source/source_base/matrix2d_view.h new file mode 100644 index 00000000000..22740229b30 --- /dev/null +++ b/source/source_base/matrix2d_view.h @@ -0,0 +1,210 @@ +#ifndef ABACUS_SOURCE_SOURCE_BASE_MATRIX2D_VIEW_H +#define ABACUS_SOURCE_SOURCE_BASE_MATRIX2D_VIEW_H + +/** + * @file matrix2d_view.h + * @brief Non-owning two-dimensional views over host or distributed storage. + * + * A `Matrix2dView` is a lightweight descriptor for an existing buffer. It + * can wrap caller-owned host data or the local buffer of a frozen + * `Parallel_Blkcyclic` distribution. Host views use logical row-major indexing. + * Distributed views use the local column-major layout reported by the + * distribution, including serial one-by-one process grids. + * + * The view never owns `data()`. The caller must keep the data buffer alive and + * unchanged in shape for the entire view lifetime. A distributed view shares + * ownership of its distribution handle so the descriptor metadata remains + * valid. For distributed storage, `lld()` is the column-major leading + * dimension; `atloc(i, j)` addresses column `j` at offset `j * lld() + i`. + * Local bounds violations are `assert()` failures rather than exceptions. + */ + +#include "source_base/parallel_blkcyc.h" + +#include +#include +#include +#include +#include +#include + +/** @brief Non-owning two-dimensional matrix view. */ +template +class Matrix2dView +{ + public: + /** + * @brief Convert a mutable view to a read-only view of the same buffer. + * + * The source view and its owner must outlive the converted view. No data + * elements are copied. + */ + template < + typename U, + typename std::enable_if::value, int>::type = 0> + Matrix2dView(const Matrix2dView& other) + : data_(other.data()), + nrglb_(other.nrglb()), + ncglb_(other.ncglb()), + nrloc_(other.nrloc()), + ncloc_(other.ncloc()), + lld_(other.lld()), + desc_(other.desc()), + distrib_(other.distribution()) + { + } + + /** + * @brief Construct a host view over an existing row-major buffer. + * + * @param data Caller-owned buffer with at least `nrglb * ncglb` elements. + * @param nrglb Number of global rows. + * @param ncglb Number of global columns. + */ + Matrix2dView(T* data, const int nrglb, const int ncglb) + : data_(data), + nrglb_(nrglb), + ncglb_(ncglb), + nrloc_(nrglb), + ncloc_(ncglb), + lld_(ncglb), + desc_(nullptr), + distrib_(nullptr) + { + assert(nrglb_ >= 0); + assert(ncglb_ >= 0); + } + + /** + * @brief Construct a view over a frozen block-cyclic local buffer. + * + * @param data Caller-owned column-major local buffer. + * @param distrib Distribution describing the local shape and leading + * dimension. The view shares ownership of this handle. + */ + Matrix2dView(T* data, + std::shared_ptr distrib) + : data_(data), + nrglb_(0), + ncglb_(0), + nrloc_(0), + ncloc_(0), + lld_(0), + desc_(nullptr), + distrib_(std::move(distrib)) + { + if (distrib_ == nullptr) + { + throw std::invalid_argument( + "matrix view distribution must not be null"); + } + const Parallel_Blkcyclic& distribution = *distrib_; + nrglb_ = distribution.nrglb(); + ncglb_ = distribution.ncglb(); + nrloc_ = distribution.nrloc(); + ncloc_ = distribution.ncloc(); + lld_ = distribution.lld(); +#ifdef __MPI + desc_ = distribution.desc(); +#endif + } + + /** + * @brief Return the caller-owned data pointer. + * + * The pointer is writable only when `T` is a non-const type. + */ + T* data() const { return data_; } + /** @brief Return the global row count. */ + int nrglb() const { return nrglb_; } + /** @brief Return the global column count. */ + int ncglb() const { return ncglb_; } + /** @brief Return the local row count. */ + int nrloc() const { return nrloc_; } + /** @brief Return the local column count. */ + int ncloc() const { return ncloc_; } + /** + * @brief Return the column-major leading dimension. + * + * Host views use the column count. Distributed views use the value from + * their frozen distribution and may include padding between columns. + */ + int lld() const { return lld_; } + /** @brief Return the number of logical local entries. */ + std::size_t size() const + { + return static_cast(nrloc_) + * static_cast(ncloc_); + } + + /** + * @brief Return whether a frozen distribution handle is attached. + * + * This includes the serial one-by-one layout. Use `is_active()` when only + * a non-serial MPI distribution should take the distributed code path. + */ + bool has_distribution() const { return distrib_ != nullptr; } + /** + * @brief Return whether an active non-serial MPI distribution is attached. + * + * A serial one-by-one frozen distribution has a handle but is not active. + */ + bool is_active() const + { + return distrib_ != nullptr && !distrib_->is_serial(); + } + /** + * @brief Return the attached distribution, or null for a host view. + * + * The returned shared pointer keeps the distribution metadata alive while + * it remains in scope. It does not own `data()`. + */ + const std::shared_ptr& + distribution() const + { + return distrib_; + } + + /** + * @brief Return the ScaLAPACK descriptor for a distributed MPI view. + * + * Returns null for host views and for all views in non-MPI builds. + */ + const int* desc() const + { + return desc_; + } + + /** + * @brief Access a local element without copying. + * + * Host views use row-major addressing. Distributed views use + * `j * lld() + i` column-major addressing. Index violations are checked + * with `assert()`, so they are not exceptions. + */ + T& atloc(const int i, const int j) const + { + assert(i >= 0); + assert(i < nrloc_); + assert(j >= 0); + assert(j < ncloc_); + const std::size_t offset = distrib_ == nullptr + ? static_cast(i) * static_cast(ncloc_) + + static_cast(j) + : static_cast(j) * static_cast(lld_) + + static_cast(i); + return data_[offset]; + } + + private: + T* data_; + int nrglb_; + int ncglb_; + int nrloc_; + int ncloc_; + int lld_; + const int* desc_; + std::shared_ptr distrib_; +}; + +#endif diff --git a/source/source_base/module_external/scalapack_connector.h b/source/source_base/module_external/scalapack_connector.h index b9fc79c0fee..95dcd50fde6 100644 --- a/source/source_base/module_external/scalapack_connector.h +++ b/source/source_base/module_external/scalapack_connector.h @@ -111,6 +111,10 @@ extern "C" const int *M, const int *N, std::complex *A, const int *IA, const int *JA, const int *DESCA, int *ipiv, int *info); + void pdgetrf_( + const int *M, const int *N, + double *A, const int *IA, const int *JA, const int *DESCA, + int *ipiv, int *info); void pzgesv_( const int *n, const int *nrhs, @@ -158,9 +162,13 @@ extern "C" void pzgetri_( - const int *n, - const std::complex *A, const int *ia, const int *ja, const int *desca, - int *ipiv, const std::complex *work, const int *lwork, const int *iwork, const int *liwork, const int *info); + const int *n, + std::complex *A, const int *ia, const int *ja, const int *desca, + int *ipiv, std::complex *work, int *lwork, int *iwork, int *liwork, int *info); + void pdgetri_( + const int *n, + double *A, const int *ia, const int *ja, const int *desca, + int *ipiv, double *work, int *lwork, int *iwork, int *liwork, int *info); void pzgeadd_( const char *transa, @@ -400,15 +408,33 @@ class ScalapackConnector pzgetrf_(&M, &N, A, &IA, &JA, DESCA, ipiv, info); } + static inline + void getrf( + const int M, const int N, + double *A, const int IA, const int JA, const int *DESCA, + int *ipiv, int *info) + { + pdgetrf_(&M, &N, A, &IA, &JA, DESCA, ipiv, info); + } + static inline void getri( - const int n, - const std::complex *A, const int ia, const int ja, const int *desca, int *ipiv, - const std::complex *work, const int *lwork, const int *iwork, const int *liwork, int *info) + const int n, + std::complex *A, const int ia, const int ja, const int *desca, int *ipiv, + std::complex *work, int *lwork, int *iwork, int *liwork, int *info) { pzgetri_(&n, A, &ia, &ja, desca, ipiv, work, lwork, iwork, liwork, info); } + static inline + void getri( + const int n, + double *A, const int ia, const int ja, const int *desca, int *ipiv, + double *work, int *lwork, int *iwork, int *liwork, int *info) + { + pdgetri_(&n, A, &ia, &ja, desca, ipiv, work, lwork, iwork, liwork, info); + } + static inline void gesv( const int n, const int nrhs, diff --git a/source/source_base/ndarray.h b/source/source_base/ndarray.h index a4a7f934caf..dd05a802074 100644 --- a/source/source_base/ndarray.h +++ b/source/source_base/ndarray.h @@ -26,8 +26,11 @@ * * @tparam T */ +template +class NDArray; + template -class NDArray +class NDArray { // align with STL container implementation, there are several functions compulsory to be implemented // constructor: default, copy, move, initializer_list diff --git a/source/source_base/parallel_blkcyc.cpp b/source/source_base/parallel_blkcyc.cpp index f876510e716..9004b58eaa0 100644 --- a/source/source_base/parallel_blkcyc.cpp +++ b/source/source_base/parallel_blkcyc.cpp @@ -8,6 +8,7 @@ #include #include #include +#include #include Parallel_Blkcyclic::~Parallel_Blkcyclic() @@ -34,6 +35,7 @@ Parallel_Blkcyclic& Parallel_Blkcyclic::operator=( rhs.owns_ictxt_ = false; ictxt_ = rhs.ictxt_; rhs.ictxt_ = UNOWNED_BLACS_CONTEXT; + context_owner_ = std::move(rhs.context_owner_); #endif nrloc_ = rhs.nrloc_; ncloc_ = rhs.ncloc_; @@ -94,6 +96,17 @@ int Parallel_Blkcyclic::ncglb() const return ncloc_; } +int Parallel_Blkcyclic::lld() const +{ +#ifdef __MPI + if (!is_serial_ && ictxt_ >= 0) + { + return desc_[DESC_LLD]; + } +#endif + return std::max(nrloc_, 1); +} + #ifdef __MPI MPI_Comm Parallel_Blkcyclic::comm() const { @@ -113,6 +126,7 @@ MPI_Comm Parallel_Blkcyclic::comm() const void Parallel_Blkcyclic::init_grid(const MPI_Comm comm, const bool swap_grid) { + context_owner_.reset(); // determine the number of rows and columns of the process grid // by factorizing n = p * q such that p, q are closest and p <= q const int num_proc = Parallel_Common::comm_size(comm); @@ -134,6 +148,17 @@ void Parallel_Blkcyclic::init_grid(const MPI_Comm comm, const bool swap_grid) Cblacs_gridinfo(ictxt_, &nrproc_, &ncproc_, &irproc_, &icproc_); } +void Parallel_Blkcyclic::init_grid(const MPI_Comm comm, + const int nrproc, + const int ncproc) +{ + context_owner_.reset(); + ictxt_ = Csys2blacs_handle(comm); + char order = 'R'; + Cblacs_gridinit(&ictxt_, &order, nrproc, ncproc); + Cblacs_gridinfo(ictxt_, &nrproc_, &ncproc_, &irproc_, &icproc_); +} + void Parallel_Blkcyclic::release_grid() { if (owns_ictxt_ && ictxt_ >= 0) @@ -209,6 +234,7 @@ int Parallel_Blkcyclic::bind_descriptor(const int nrglb, release_grid(); ictxt_ = ictxt; owns_ictxt_ = false; + context_owner_.reset(); Cblacs_gridinfo(ictxt, &nrproc_, &ncproc_, &irproc_, &icproc_); init_dist(nrglb, ncglb, nb); return nrloc_ == 0 || ncloc_ == 0; @@ -257,6 +283,7 @@ void Parallel_Blkcyclic::set_serial(const int nrglb, const int ncglb) is_serial_ = true; #ifdef __MPI release_grid(); + context_owner_.reset(); // A serial layout must not reference any BLACS grid: for borrowers // release_grid() is a no-op, so clear the handle explicitly; // otherwise the object keeps a reference to the old grid, which also @@ -264,3 +291,77 @@ void Parallel_Blkcyclic::set_serial(const int nrglb, const int ncglb) ictxt_ = UNOWNED_BLACS_CONTEXT; #endif } + +#ifdef __MPI +std::shared_ptr make_frozen_distribution( + const int nrglb, + const int ncglb, + const int nb, + const MPI_Comm comm) +{ + std::shared_ptr distrib + = std::make_shared(); + distrib->init(nrglb, ncglb, nb, comm, false); + return distrib; +} + +std::shared_ptr make_frozen_distribution( + const int nrglb, + const int ncglb, + const int nrproc, + const int ncproc, + const int nb, + const MPI_Comm comm) +{ + std::shared_ptr distrib + = std::make_shared(); + distrib->init_grid(comm, nrproc, ncproc); + distrib->init_dist(nrglb, ncglb, nb); + distrib->owns_ictxt_ = true; + return distrib; +} + +std::shared_ptr make_borrowed_distribution( + const int nrglb, + const int ncglb, + const int nb, + const int ictxt) +{ + std::shared_ptr distrib + = std::make_shared(); + distrib->set(nrglb, ncglb, nb, ictxt); + return distrib; +} + +std::shared_ptr make_borrowed_distribution( + const int nrglb, + const int ncglb, + const int nb, + const std::shared_ptr& owner) +{ + if (owner == nullptr) + { + throw std::invalid_argument("distribution owner must not be null"); + } + if (owner->is_serial() || owner->ictxt() < 0) + { + throw std::invalid_argument( + "distribution owner must have an active BLACS context"); + } + std::shared_ptr distrib + = std::make_shared(); + distrib->set(nrglb, ncglb, nb, owner->ictxt()); + distrib->context_owner_ = owner; + return distrib; +} +#endif + +std::shared_ptr make_frozen_distribution( + const int nrglb, + const int ncglb) +{ + std::shared_ptr distrib + = std::make_shared(); + distrib->set_serial(nrglb, ncglb); + return distrib; +} diff --git a/source/source_base/parallel_blkcyc.h b/source/source_base/parallel_blkcyc.h index 1ca7a650fbd..cbe2c02f831 100644 --- a/source/source_base/parallel_blkcyc.h +++ b/source/source_base/parallel_blkcyc.h @@ -3,6 +3,7 @@ #include #include +#include #include #ifdef __MPI @@ -55,6 +56,8 @@ class Parallel_Blkcyclic return nb_; } + int lld() const; + int nrproc() const { return nrproc_; @@ -151,6 +154,18 @@ class Parallel_Blkcyclic #endif private: +#ifdef __MPI + friend std::shared_ptr + make_frozen_distribution(int, int, int, MPI_Comm); + friend std::shared_ptr + make_frozen_distribution(int, int, int, int, int, MPI_Comm); + friend std::shared_ptr + make_borrowed_distribution(int, int, int, int); + friend std::shared_ptr + make_borrowed_distribution( + int, int, int, const std::shared_ptr&); +#endif + static constexpr int DESC_SIZE = 9; static constexpr int DESC_ICTXT = 1; static constexpr int DESC_M = 2; @@ -181,11 +196,45 @@ class Parallel_Blkcyclic #ifdef __MPI bool owns_ictxt_ = false; + std::shared_ptr context_owner_; void init_grid(const MPI_Comm comm, const bool swap_grid); + void init_grid(const MPI_Comm comm, const int nrproc, const int ncproc); void init_dist(const int nrglb, const int ncglb, const int nb); void release_grid(); #endif }; +#ifdef __MPI +std::shared_ptr make_frozen_distribution( + int nrglb, + int ncglb, + int nb, + MPI_Comm comm); + +std::shared_ptr make_frozen_distribution( + int nrglb, + int ncglb, + int nrproc, + int ncproc, + int nb, + MPI_Comm comm); + +std::shared_ptr make_borrowed_distribution( + int nrglb, + int ncglb, + int nb, + int ictxt); + +std::shared_ptr make_borrowed_distribution( + int nrglb, + int ncglb, + int nb, + const std::shared_ptr& owner); +#endif + +std::shared_ptr make_frozen_distribution( + int nrglb, + int ncglb); + #endif diff --git a/source/source_base/parallel_common.cpp b/source/source_base/parallel_common.cpp index 4cdeb408197..9c4b49936f2 100644 --- a/source/source_base/parallel_common.cpp +++ b/source/source_base/parallel_common.cpp @@ -122,6 +122,100 @@ void bcast_mpi_offset(MPI_Offset& object, const MPI_Comm& comm) { MPI_Bcast(&object, 1, MPI_OFFSET, 0, comm); } + +void barrier(const MPI_Comm comm) +{ + MPI_Barrier(comm); +} + +void gatherv_bytes(const void* sendbuf, + const int send, + void* recvbuf, + const int* recvcounts, + const int* rdispls, + const int root, + const MPI_Comm comm) +{ + MPI_Gatherv(sendbuf, + send, + MPI_BYTE, + recvbuf, + recvcounts, + rdispls, + MPI_BYTE, + root, + comm); +} + +void allgatherv_bytes(const void* sendbuf, + const int send, + void* recvbuf, + const int* recvcounts, + const int* rdispls, + const MPI_Comm comm) +{ + MPI_Allgatherv(sendbuf, + send, + MPI_BYTE, + recvbuf, + recvcounts, + rdispls, + MPI_BYTE, + comm); +} + +void scatterv_bytes(const void* sendbuf, + const int* sendcounts, + const int* sdispls, + void* recvbuf, + const int recv, + const int root, + const MPI_Comm comm) +{ + MPI_Scatterv(sendbuf, + sendcounts, + sdispls, + MPI_BYTE, + recvbuf, + recv, + MPI_BYTE, + root, + comm); +} + +void allreduce_sum(int& value, const MPI_Comm comm) +{ + MPI_Allreduce(MPI_IN_PLACE, &value, 1, MPI_INT, MPI_SUM, comm); +} + +void allreduce_sum(float& value, const MPI_Comm comm) +{ + MPI_Allreduce(MPI_IN_PLACE, &value, 1, MPI_FLOAT, MPI_SUM, comm); +} + +void allreduce_sum(double& value, const MPI_Comm comm) +{ + MPI_Allreduce(MPI_IN_PLACE, &value, 1, MPI_DOUBLE, MPI_SUM, comm); +} + +void allreduce_sum(std::complex& value, const MPI_Comm comm) +{ + float values[2] = {value.real(), value.imag()}; + MPI_Allreduce(MPI_IN_PLACE, values, 2, MPI_FLOAT, MPI_SUM, comm); + value = std::complex(values[0], values[1]); +} + +void allreduce_sum(std::complex& value, const MPI_Comm comm) +{ + double values[2] = {value.real(), value.imag()}; + MPI_Allreduce(MPI_IN_PLACE, values, 2, MPI_DOUBLE, MPI_SUM, comm); + value = std::complex(values[0], values[1]); +} + +void allreduce_max(double& value, const MPI_Comm comm) +{ + MPI_Allreduce(MPI_IN_PLACE, &value, 1, MPI_DOUBLE, MPI_MAX, comm); +} #endif } // namespace Parallel_Common diff --git a/source/source_base/parallel_common.h b/source/source_base/parallel_common.h index aab84fe7011..4364a71743c 100644 --- a/source/source_base/parallel_common.h +++ b/source/source_base/parallel_common.h @@ -5,6 +5,7 @@ #include "mpi.h" #endif +#include #include #include @@ -18,6 +19,23 @@ inline int comm_size(const MPI_Comm comm) MPI_Comm_size(comm, &size); return size; } + +inline int comm_rank(const MPI_Comm comm) +{ + int rank = 0; + MPI_Comm_rank(comm, &rank); + return rank; +} +#else +inline int comm_size() +{ + return 1; +} + +inline int comm_rank() +{ + return 0; +} #endif //(1) bcast array @@ -38,6 +56,89 @@ void bcast_bool(bool& object); //(3) bcast single on an explicit communicator, from the communicator's rank 0 void bcast_bool(bool& object, const MPI_Comm& comm); void bcast_mpi_offset(MPI_Offset& object, const MPI_Comm& comm); + +void barrier(const MPI_Comm comm); + +void gatherv_bytes(const void* sendbuf, + int send, + void* recvbuf, + const int* recvcounts, + const int* rdispls, + int root, + MPI_Comm comm); + +void allgatherv_bytes(const void* sendbuf, + int send, + void* recvbuf, + const int* recvcounts, + const int* rdispls, + MPI_Comm comm); + +void scatterv_bytes(const void* sendbuf, + const int* sendcounts, + const int* sdispls, + void* recvbuf, + int recv, + int root, + MPI_Comm comm); + +void allreduce_sum(int& value, MPI_Comm comm); +void allreduce_sum(float& value, MPI_Comm comm); +void allreduce_sum(double& value, MPI_Comm comm); +void allreduce_sum(std::complex& value, MPI_Comm comm); +void allreduce_sum(std::complex& value, MPI_Comm comm); +void allreduce_max(double& value, MPI_Comm comm); +#else +inline void barrier() +{ +} + +inline void gatherv_bytes(const void* sendbuf, + int send, + void* recvbuf, + const int*, + const int*, + int, + int) +{ + if (recvbuf != nullptr && send > 0) + { + std::copy(static_cast(sendbuf), + static_cast(sendbuf) + send, + static_cast(recvbuf)); + } +} + +inline void allgatherv_bytes(const void* sendbuf, + int send, + void* recvbuf, + const int*, + const int*, + int) +{ + if (recvbuf != nullptr && send > 0) + { + std::copy(static_cast(sendbuf), + static_cast(sendbuf) + send, + static_cast(recvbuf)); + } +} + +inline void scatterv_bytes(const void* sendbuf, + const int*, + const int*, + void* recvbuf, + int recv, + int, + int) +{ + if (recvbuf != nullptr && recv > 0) + { + std::copy(static_cast(sendbuf), + static_cast(sendbuf) + recv, + static_cast(recvbuf)); + } +} #endif } // namespace Parallel_Common diff --git a/source/source_base/unittests/CMakeLists.txt b/source/source_base/unittests/CMakeLists.txt index 5381e4f9f59..2e0fdfaa17e 100644 --- a/source/source_base/unittests/CMakeLists.txt +++ b/source/source_base/unittests/CMakeLists.txt @@ -11,3 +11,74 @@ AddTest( LIBS parameter base device SOURCES test_filename.cpp ) + +AddTest( + TARGET MODULE_BASE_matrix2d + LIBS parameter base device container + SOURCES test_matrix2d.cpp + KEEP_FEATURE_DEFINITIONS __MPI +) + +AddTest( + TARGET MODULE_BASE_matrix2d_linalg + LIBS parameter base device container + SOURCES test_matrix2d_linalg.cpp + KEEP_FEATURE_DEFINITIONS __MPI +) + +set_tests_properties( + MODULE_BASE_matrix2d + MODULE_BASE_matrix2d_linalg + PROPERTIES ENVIRONMENT + "OMP_NUM_THREADS=1;OMPI_ALLOW_RUN_AS_ROOT=1;OMPI_ALLOW_RUN_AS_ROOT_CONFIRM=1;HWLOC_COMPONENTS=-gl" +) + +if(ENABLE_MPI) + foreach(matrix2d_target IN ITEMS + MODULE_BASE_matrix2d + MODULE_BASE_matrix2d_linalg) + get_target_property( + matrix2d_kept_feature_definitions + ${matrix2d_target} + ABACUS_KEPT_FEATURE_DEFINITIONS) + list(FIND matrix2d_kept_feature_definitions "__MPI" mpi_feature_index) + if(mpi_feature_index EQUAL -1) + message( + FATAL_ERROR + "${matrix2d_target} must keep __MPI to match the linked base library") + endif() + endforeach() + + add_test( + NAME MODULE_BASE_matrix2d_2ranks + COMMAND ${MPIEXEC_EXECUTABLE} ${MPIEXEC_NUMPROC_FLAG} 2 + ${MPIEXEC_PREFLAGS} $ + ${MPIEXEC_POSTFLAGS} + ) + add_test( + NAME MODULE_BASE_matrix2d_4ranks + COMMAND ${MPIEXEC_EXECUTABLE} ${MPIEXEC_NUMPROC_FLAG} 4 + ${MPIEXEC_PREFLAGS} $ + ${MPIEXEC_POSTFLAGS} + ) + add_test( + NAME MODULE_BASE_matrix2d_linalg_2ranks + COMMAND ${MPIEXEC_EXECUTABLE} ${MPIEXEC_NUMPROC_FLAG} 2 + ${MPIEXEC_PREFLAGS} $ + ${MPIEXEC_POSTFLAGS} + ) + add_test( + NAME MODULE_BASE_matrix2d_linalg_4ranks + COMMAND ${MPIEXEC_EXECUTABLE} ${MPIEXEC_NUMPROC_FLAG} 4 + ${MPIEXEC_PREFLAGS} $ + ${MPIEXEC_POSTFLAGS} + ) + set_tests_properties( + MODULE_BASE_matrix2d_2ranks + MODULE_BASE_matrix2d_4ranks + MODULE_BASE_matrix2d_linalg_2ranks + MODULE_BASE_matrix2d_linalg_4ranks + PROPERTIES ENVIRONMENT + "OMP_NUM_THREADS=1;OMPI_ALLOW_RUN_AS_ROOT=1;OMPI_ALLOW_RUN_AS_ROOT_CONFIRM=1;HWLOC_COMPONENTS=-gl" + ) +endif() diff --git a/source/source_base/unittests/test_matrix2d.cpp b/source/source_base/unittests/test_matrix2d.cpp new file mode 100644 index 00000000000..76375c217ae --- /dev/null +++ b/source/source_base/unittests/test_matrix2d.cpp @@ -0,0 +1,1692 @@ +#ifdef NDEBUG +#undef NDEBUG +#endif + +#include "source_base/matrix2d.h" +#include "source_base/matrix2d_view.h" + +#ifdef __MPI +#include "source_base/parallel_common.h" +#endif + +#include "gtest/gtest.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static_assert(std::is_same, NDArray>::value, + "Matrix2d must be the same type as NDArray"); +static_assert(std::is_same, NDArray>::value, + "NDArray must remain the rank-zero specialization"); +static_assert(!std::is_same, NDArray>::value, + "Rank-zero and rank-two NDArray types must be distinct"); +static_assert(!std::is_base_of, Matrix2d>::value, + "Matrix2d must not inherit from the rank-zero NDArray"); +static_assert(std::is_copy_constructible>::value, + "Matrix2d must be copy constructible"); +static_assert(std::is_copy_assignable>::value, + "Matrix2d must be copy assignable"); +static_assert(std::is_nothrow_move_constructible>::value, + "Matrix2d move construction must be noexcept"); +static_assert(std::is_nothrow_move_assignable>::value, + "Matrix2d move assignment must be noexcept"); +static_assert(std::is_same, double>::value, + "Integer Matrix2d real scalar type must be double"); +static_assert(std::is_same, float>::value, + "Float Matrix2d real scalar type must be float"); +static_assert(std::is_same, double>::value, + "Double Matrix2d real scalar type must be double"); +static_assert(std::is_same>, float>::value, + "Complex float Matrix2d real scalar type must be float"); +static_assert(std::is_same>, double>::value, + "Complex double Matrix2d real scalar type must be double"); +static_assert( + std::is_same&>().norm()), + float>::value, + "Matrix2d::norm() must return float"); +static_assert( + std::is_same&>().max_abs()), + float>::value, + "Matrix2d::max_abs() must return float"); + +namespace +{ +template +class HasAt +{ + template + static auto test(int) -> decltype(std::declval().at(0), std::true_type()); + + template + static std::false_type test(...); + + public: + static constexpr bool value = decltype(test(0))::value; +}; + +template +class HasBegin +{ + template + static auto test(int) -> decltype(std::declval().begin(), std::true_type()); + + template + static std::false_type test(...); + + public: + static constexpr bool value = decltype(test(0))::value; +}; + +template +class HasReshape +{ + template + static auto test(int) -> decltype(std::declval().reshape(1, 1), std::true_type()); + + template + static std::false_type test(...); + + public: + static constexpr bool value = decltype(test(0))::value; +}; + +template +class HasShape +{ + template + static auto test(int) -> decltype(std::declval().shape(), std::true_type()); + + template + static std::false_type test(...); + + public: + static constexpr bool value = decltype(test(0))::value; +}; + +template +class HasSize +{ + template + static auto test(int) -> decltype(std::declval().size(), std::true_type()); + + template + static std::false_type test(...); + + public: + static constexpr bool value = decltype(test(0))::value; +}; + +static_assert(!HasAt>::value, + "Matrix2d must not expose the rank-zero at() interface"); +static_assert(!HasBegin>::value, + "Matrix2d must not expose rank-zero iterators"); +static_assert(!HasReshape>::value, + "Matrix2d must not expose rank-zero reshape()"); +static_assert(!HasShape>::value, + "Matrix2d must not expose a generic shape() container"); +static_assert(HasSize>::value, + "Matrix2d must expose the local element count as size()"); + +void check_host_layout() +{ + Matrix2d matrix(2, 3); + + EXPECT_FALSE(matrix.has_distribution()); + EXPECT_FALSE(matrix.is_active()); + EXPECT_EQ(matrix.distribution(), nullptr); + EXPECT_EQ(matrix.nrglb(), 2); + EXPECT_EQ(matrix.ncglb(), 3); + EXPECT_EQ(matrix.nrloc(), 2); + EXPECT_EQ(matrix.ncloc(), 3); + EXPECT_EQ(matrix.size(), 6); + EXPECT_EQ(matrix.nrproc(), 1); + EXPECT_EQ(matrix.ncproc(), 1); + EXPECT_EQ(matrix.irproc(), 0); + EXPECT_EQ(matrix.icproc(), 0); + EXPECT_EQ(matrix.lld(), 3); + EXPECT_EQ(matrix.desc(), nullptr); + EXPECT_EQ(matrix.ictxt(), -1); + EXPECT_EQ(matrix.data(), &matrix.atloc(0, 0)); + + double value = 1.0; + for (int ir = 0; ir < 2; ++ir) + { + for (int ic = 0; ic < 3; ++ic) + { + const std::size_t expected_index = static_cast(ir) * 3U + + static_cast(ic); + EXPECT_EQ(&matrix.atloc(ir, ic), matrix.data() + expected_index); + EXPECT_EQ(&matrix.atglb(ir, ic), &matrix.atloc(ir, ic)); + EXPECT_TRUE(matrix.in_this_processor(ir, ic)); + matrix.atloc(ir, ic) = value; + value += 1.0; + } + } + + EXPECT_EQ(matrix.data()[0], 1.0); + EXPECT_EQ(matrix.data()[1], 2.0); + EXPECT_EQ(matrix.data()[2], 3.0); + EXPECT_EQ(matrix.data()[3], 4.0); + EXPECT_EQ(matrix.data()[4], 5.0); + EXPECT_EQ(matrix.data()[5], 6.0); + + const Matrix2d& const_matrix = matrix; + EXPECT_EQ(const_matrix.data(), matrix.data()); + EXPECT_EQ(&const_matrix.atloc(1, 2), matrix.data() + 5); + EXPECT_EQ(&const_matrix.atglb(1, 2), matrix.data() + 5); +} + +void check_distribution_layout(Matrix2d& matrix, + const int nrglb, + const int ncglb) +{ + const std::shared_ptr& distrib + = matrix.distribution(); + ASSERT_NE(distrib, nullptr); + EXPECT_TRUE(matrix.has_distribution()); + EXPECT_EQ(matrix.is_active(), !distrib->is_serial()); + const Matrix2dView matrix_view = matrix.view(); + EXPECT_TRUE(matrix_view.has_distribution()); + EXPECT_EQ(matrix_view.is_active(), matrix.is_active()); + EXPECT_EQ(matrix.nrglb(), nrglb); + EXPECT_EQ(matrix.ncglb(), ncglb); + EXPECT_EQ(matrix.nrloc(), distrib->nrloc()); + EXPECT_EQ(matrix.ncloc(), distrib->ncloc()); + EXPECT_EQ(matrix.size(), + distrib->size()); + EXPECT_EQ(matrix.nrproc(), distrib->nrproc()); + EXPECT_EQ(matrix.ncproc(), distrib->ncproc()); + EXPECT_EQ(matrix.irproc(), distrib->irproc()); + EXPECT_EQ(matrix.icproc(), distrib->icproc()); + EXPECT_EQ(matrix.lld(), distrib->lld()); + + const int nrloc = matrix.nrloc(); + const int ncloc = matrix.ncloc(); + const std::size_t lld + = static_cast(matrix.lld()); + for (int irloc = 0; irloc < nrloc; ++irloc) + { + for (int icloc = 0; icloc < ncloc; ++icloc) + { + const std::size_t expected_index + = static_cast(icloc) * lld + + static_cast(irloc); + EXPECT_EQ(&matrix.atloc(irloc, icloc), matrix.data() + expected_index); + } + } + + for (int irglb = 0; irglb < nrglb; ++irglb) + { + for (int icglb = 0; icglb < ncglb; ++icglb) + { + const bool expected_owner = distrib->in_this_processor(irglb, icglb); + EXPECT_EQ(matrix.in_this_processor(irglb, icglb), expected_owner); + if (!expected_owner) + { + continue; + } + + const int irloc = distrib->irloc(irglb); + const int icloc = distrib->icloc(icglb); + ASSERT_NE(irloc, -1); + ASSERT_NE(icloc, -1); + EXPECT_EQ(&matrix.atglb(irglb, icglb), + &matrix.atloc(irloc, icloc)); + const double value = static_cast(irglb * ncglb + icglb); + matrix.atglb(irglb, icglb) = value; + EXPECT_EQ(matrix.atloc(irloc, icloc), value); + } + } + + const Matrix2d& const_matrix = matrix; + EXPECT_EQ(const_matrix.data(), matrix.data()); +} + +#ifdef __MPI +void check_mpi_descriptor(Matrix2d& matrix, + const int nrglb, + const int ncglb, + const int nrblk) +{ + constexpr int DESCRIPTOR_MATRIX_TYPE_INDEX = 0; + constexpr int DESCRIPTOR_BLACS_CONTEXT_INDEX = 1; + constexpr int DESCRIPTOR_GLOBAL_ROWS_INDEX = 2; + constexpr int DESCRIPTOR_GLOBAL_COLS_INDEX = 3; + constexpr int DESCRIPTOR_BLOCK_ROWS_INDEX = 4; + constexpr int DESCRIPTOR_BLOCK_COLS_INDEX = 5; + constexpr int DESCRIPTOR_LEADING_DIM_INDEX = 8; + + const int* const desc = matrix.desc(); + ASSERT_NE(desc, nullptr); + EXPECT_EQ(desc[DESCRIPTOR_MATRIX_TYPE_INDEX], 1); + EXPECT_EQ(desc[DESCRIPTOR_BLACS_CONTEXT_INDEX], matrix.ictxt()); + EXPECT_EQ(desc[DESCRIPTOR_GLOBAL_ROWS_INDEX], nrglb); + EXPECT_EQ(desc[DESCRIPTOR_GLOBAL_COLS_INDEX], ncglb); + EXPECT_EQ(desc[DESCRIPTOR_BLOCK_ROWS_INDEX], nrblk); + EXPECT_EQ(desc[DESCRIPTOR_BLOCK_COLS_INDEX], nrblk); + EXPECT_EQ(desc[DESCRIPTOR_LEADING_DIM_INDEX], matrix.lld()); + EXPECT_GE(matrix.ictxt(), 0); + EXPECT_EQ(matrix.nrproc() * matrix.ncproc(), + Parallel_Common::comm_size(MPI_COMM_WORLD)); +} +#endif +} // namespace + +namespace +{ +constexpr double DOUBLE_RELATIVE_TOLERANCE = 1.0e-12; +constexpr double COMPLEX_RELATIVE_TOLERANCE = 1.0e-6; + +void report_reduction_tolerances() +{ + std::cout << "Matrix2d reduction tolerance: double relative <= " + << DOUBLE_RELATIVE_TOLERANCE << ", complex relative <= " + << COMPLEX_RELATIVE_TOLERANCE << std::endl; +} + +template +double reduction_tolerance() +{ + return DOUBLE_RELATIVE_TOLERANCE; +} + +template <> +double reduction_tolerance>() +{ + return COMPLEX_RELATIVE_TOLERANCE; +} + +template +T test_value(const int ir, const int ic, const double offset) +{ + return static_cast(offset + 0.5 + 1.25 * ir - 0.75 * ic); +} + +template <> +std::complex test_value>(const int ir, + const int ic, + const double offset) +{ + return std::complex(offset + 0.5 + 1.25 * ir - 0.75 * ic, + 0.25 - 0.5 * ir + 0.875 * ic); +} + +template +T constant_value(const double real_part) +{ + return static_cast(real_part); +} + +template <> +std::complex constant_value>(const double real_part) +{ + return std::complex(real_part, -0.25 * real_part); +} + +template +double real_part(const T& value) +{ + return static_cast(value); +} + +template <> +double real_part>(const std::complex& value) +{ + return value.real(); +} + +template +double imaginary_part(const T&) +{ + return 0.0; +} + +template <> +double imaginary_part>(const std::complex& value) +{ + return value.imag(); +} + +template +T conjugate_value(const T& value) +{ + return value; +} + +template <> +std::complex conjugate_value>( + const std::complex& value) +{ + return std::conj(value); +} + +template +void expect_scalar_near(const T& actual, const T& expected) +{ + const double tolerance = reduction_tolerance(); + const double scale = std::max(1.0, std::abs(expected)); + EXPECT_NEAR(actual, expected, tolerance * scale); +} + +template <> +void expect_scalar_near>( + const std::complex& actual, + const std::complex& expected) +{ + const double tolerance = reduction_tolerance>(); + const double scale = std::max(1.0, std::abs(expected)); + EXPECT_NEAR(actual.real(), expected.real(), tolerance * scale); + EXPECT_NEAR(actual.imag(), expected.imag(), tolerance * scale); +} + +template +void fill_global_values(Matrix2d& matrix, const double offset = 0.0) +{ + for (int ir = 0; ir < matrix.nrglb(); ++ir) + { + for (int ic = 0; ic < matrix.ncglb(); ++ic) + { + if (matrix.in_this_processor(ir, ic)) + { + matrix.atglb(ir, ic) = test_value(ir, ic, offset); + } + } + } +} + +template +Matrix2d make_host_reference(const int nr, + const int nc, + const double offset = 0.0) +{ + Matrix2d reference(nr, nc); + for (int ir = 0; ir < nr; ++ir) + { + for (int ic = 0; ic < nc; ++ic) + { + reference.atloc(ir, ic) = test_value(ir, ic, offset); + } + } + return reference; +} + +template +void verify_global_matrix(const Matrix2d& actual, const Matrix2d& expected) +{ + ASSERT_FALSE(actual.has_distribution()); + ASSERT_FALSE(actual.is_active()); + ASSERT_EQ(actual.nrglb(), expected.nrglb()); + ASSERT_EQ(actual.ncglb(), expected.ncglb()); + for (int ir = 0; ir < expected.nrglb(); ++ir) + { + for (int ic = 0; ic < expected.ncglb(); ++ic) + { + const std::size_t c_order_index + = static_cast(ir) + * static_cast(expected.ncglb()) + + static_cast(ic); + expect_scalar_near(actual.data()[c_order_index], + expected.atloc(ir, ic)); + } + } +} + +template +void check_elementwise_operations(Matrix2d& matrix, Matrix2d& other) +{ + const int nr = matrix.nrglb(); + const int nc = matrix.ncglb(); + + Matrix2d filled = matrix; + const T fill_value = constant_value(3.5); + filled.fill(fill_value); + Matrix2d expected(nr, nc); + expected.fill(fill_value); + verify_global_matrix(filled.gather(), expected); + + filled = matrix; + filled.scale(constant_value(2.5)); + expected = make_host_reference(nr, nc); + for (int ir = 0; ir < nr; ++ir) + { + for (int ic = 0; ic < nc; ++ic) + { + expected.atloc(ir, ic) *= constant_value(2.5); + } + } + verify_global_matrix(filled.gather(), expected); + + filled = matrix; + filled += other; + expected = make_host_reference(nr, nc); + Matrix2d expected_other = make_host_reference(nr, nc, 10.0); + for (int ir = 0; ir < nr; ++ir) + { + for (int ic = 0; ic < nc; ++ic) + { + expected.atloc(ir, ic) += expected_other.atloc(ir, ic); + } + } + verify_global_matrix(filled.gather(), expected); + + filled = matrix; + filled -= other; + expected = make_host_reference(nr, nc); + for (int ir = 0; ir < nr; ++ir) + { + for (int ic = 0; ic < nc; ++ic) + { + expected.atloc(ir, ic) -= expected_other.atloc(ir, ic); + } + } + verify_global_matrix(filled.gather(), expected); + + filled = matrix; + filled *= other; + expected = make_host_reference(nr, nc); + for (int ir = 0; ir < nr; ++ir) + { + for (int ic = 0; ic < nc; ++ic) + { + expected.atloc(ir, ic) *= expected_other.atloc(ir, ic); + } + } + verify_global_matrix(filled.gather(), expected); + + filled = matrix; + filled.conjugate(); + expected = make_host_reference(nr, nc); + for (int ir = 0; ir < nr; ++ir) + { + for (int ic = 0; ic < nc; ++ic) + { + expected.atloc(ir, ic) + = conjugate_value(expected.atloc(ir, ic)); + } + } + verify_global_matrix(filled.gather(), expected); + + Matrix2d expected_real(nr, nc); + Matrix2d expected_imag(nr, nc); + const Matrix2d matrix_reference = make_host_reference(nr, nc); + for (int ir = 0; ir < nr; ++ir) + { + for (int ic = 0; ic < nc; ++ic) + { + const T& value = matrix_reference.atloc(ir, ic); + expected_real.atloc(ir, ic) = real_part(value); + expected_imag.atloc(ir, ic) = imaginary_part(value); + } + } + + verify_global_matrix(matrix.real().gather(), expected_real); + verify_global_matrix(matrix.imag().gather(), expected_imag); +} + +template +void check_reductions(Matrix2d& matrix, Matrix2d& other) +{ + const Matrix2d matrix_reference = make_host_reference( + matrix.nrglb(), + matrix.ncglb()); + const Matrix2d other_reference = make_host_reference( + matrix.nrglb(), + matrix.ncglb(), + 10.0); + T reference_sum = T(); + T reference_dot = T(); + double reference_norm_sq = 0.0; + double reference_max_abs = 0.0; + for (int ir = 0; ir < matrix.nrglb(); ++ir) + { + for (int ic = 0; ic < matrix.ncglb(); ++ic) + { + const T& value = matrix_reference.atloc(ir, ic); + const T& other_value = other_reference.atloc(ir, ic); + reference_sum += value; + reference_dot += conjugate_value(value) * other_value; + reference_norm_sq += real_part(value) * real_part(value) + + imaginary_part(value) * imaginary_part(value); + reference_max_abs = std::max(reference_max_abs, + static_cast(std::abs(value))); + } + } + + expect_scalar_near(matrix.sum(), reference_sum); + expect_scalar_near(matrix.dot(other), reference_dot); + const T expected_self_dot = static_cast(reference_norm_sq); + expect_scalar_near(matrix.dot(matrix), expected_self_dot); + expect_scalar_near(matrix.norm(), std::sqrt(reference_norm_sq)); + expect_scalar_near(matrix.max_abs(), reference_max_abs); + + const std::vector diagonal = matrix.diagonal(); + const int diagonal_size = std::min(matrix.nrglb(), matrix.ncglb()); + ASSERT_EQ(diagonal.size(), static_cast(diagonal_size)); + for (int i = 0; i < diagonal_size; ++i) + { + expect_scalar_near(diagonal[static_cast(i)], + matrix_reference.atloc(i, i)); + } +} + +template +void check_reduction_scalar_type(const T& first, + const T& second, + const real_type& expected_norm, + const real_type& expected_max_abs) +{ + Matrix2d matrix(1, 2); + matrix.atloc(0, 0) = first; + matrix.atloc(0, 1) = second; + + const real_type norm = matrix.norm(); + const real_type max_abs = matrix.max_abs(); + EXPECT_EQ(norm, expected_norm); + EXPECT_EQ(max_abs, expected_max_abs); +} + +template +void check_float_reduction_range(const T& value, const float expected) +{ + Matrix2d matrix(1, 1); + matrix.atloc(0, 0) = value; + + const float norm = matrix.norm(); + const float max_abs = matrix.max_abs(); + EXPECT_FLOAT_EQ(norm, expected); + EXPECT_FLOAT_EQ(max_abs, expected); +} + +template +void check_gather_scatter(Matrix2d& matrix) +{ + const int nr = matrix.nrglb(); + const int nc = matrix.ncglb(); + const Matrix2d expected = make_host_reference(nr, nc); + const Matrix2d gathered = matrix.gather(); + verify_global_matrix(gathered, expected); + EXPECT_EQ(std::memcmp(gathered.data(), + expected.data(), + static_cast(nr * nc) * sizeof(T)), + 0); + const Matrix2d gathered_again = matrix.gather(); + EXPECT_EQ(std::memcmp(gathered.data(), + gathered_again.data(), + static_cast(nr * nc) * sizeof(T)), + 0); + + Matrix2d restored(matrix.distribution()); + restored.scatter(gathered); + verify_global_matrix(restored.gather(), expected); + verify_global_matrix(matrix.gather(), expected); + +#ifdef __MPI + const int rank = Parallel_Common::comm_rank(MPI_COMM_WORLD); + const int root = Parallel_Common::comm_size(MPI_COMM_WORLD) - 1; + const Matrix2d root_result = matrix.gather_on_root(root); + if (rank == root) + { + verify_global_matrix(root_result, expected); + } + else + { + EXPECT_EQ(root_result.nrglb(), 0); + EXPECT_EQ(root_result.ncglb(), 0); + EXPECT_EQ(root_result.size(), 0); + EXPECT_EQ(root_result.lld(), 0); + EXPECT_FALSE(root_result.has_distribution()); + EXPECT_FALSE(root_result.is_active()); + } +#endif + + Matrix2d wrong_shape(nr + 1, nc); + EXPECT_THROW(restored.scatter(wrong_shape), std::invalid_argument); +} + +template +std::size_t expected_local_storage_size(const Matrix2d& matrix) +{ + const int lld = std::max(matrix.lld(), 1); + const std::size_t ncolmajor + = static_cast(lld) + * static_cast(matrix.ncloc()); + const std::size_t nrowmajor + = static_cast(matrix.nrloc()) + * static_cast(matrix.ncloc()); + const std::size_t nextent = std::max(ncolmajor, nrowmajor); + const std::size_t nstor_min = 1; + return std::max(nextent, nstor_min); +} + +template +std::vector set_padding_sentinel(Matrix2d& matrix, + const T& sentinel) +{ + const int nrloc = matrix.nrloc(); + const int ncloc = matrix.ncloc(); + const std::size_t lld = static_cast(matrix.lld()); + const std::size_t nstor = expected_local_storage_size(matrix); + std::vector is_logical(nstor, 0); + std::vector padding_indices; + for (int icloc = 0; icloc < ncloc; ++icloc) + { + for (int irloc = 0; irloc < nrloc; ++irloc) + { + const std::size_t index + = static_cast(icloc) * lld + + static_cast(irloc); + is_logical[index] = 1; + } + } + for (std::size_t index = 0; index < nstor; ++index) + { + if (is_logical[index] == 0) + { + matrix.data()[index] = sentinel; + padding_indices.push_back(index); + } + } + return padding_indices; +} + +template +void expect_padding_sentinel( + const Matrix2d& matrix, + const std::vector& padding_indices, + const T& sentinel) +{ + for (std::size_t padding_index = 0; + padding_index < padding_indices.size(); + ++padding_index) + { + const std::size_t index = padding_indices[padding_index]; + expect_scalar_near(matrix.data()[index], sentinel); + } +} + +std::vector> available_process_grids() +{ + std::vector> grids; +#ifdef __MPI + const int nproc = Parallel_Common::comm_size(MPI_COMM_WORLD); +#else + const int nproc = 1; +#endif + if (nproc == 1) + { + grids.push_back(std::make_pair(1, 1)); + } + if (nproc == 2) + { + grids.push_back(std::make_pair(1, 2)); + grids.push_back(std::make_pair(2, 1)); + } + if (nproc == 4) + { + grids.push_back(std::make_pair(1, 4)); + grids.push_back(std::make_pair(2, 2)); + grids.push_back(std::make_pair(4, 1)); + } + return grids; +} + +template +Matrix2d make_transpose_reference(const Matrix2d& source) +{ + const int nr = source.nrglb(); + const int nc = source.ncglb(); + Matrix2d reference(nc, nr); + for (int ir = 0; ir < nr; ++ir) + { + for (int ic = 0; ic < nc; ++ic) + { + reference.atloc(ic, ir) + = source.atloc(ir, ic); + } + } + return reference; +} + +template +Matrix2d make_dagger_reference(const Matrix2d& source) +{ + const int nr = source.nrglb(); + const int nc = source.ncglb(); + Matrix2d reference(nc, nr); + for (int ir = 0; ir < nr; ++ir) + { + for (int ic = 0; ic < nc; ++ic) + { + reference.atloc(ic, ir) + = conjugate_value(source.atloc(ir, ic)); + } + } + return reference; +} + +template +Matrix2d make_matmul_reference(const Matrix2d& left, + const Matrix2d& right) +{ + const int m = left.nrglb(); + const int k = left.ncglb(); + const int n = right.ncglb(); + Matrix2d reference(m, n); + for (int ir = 0; ir < m; ++ir) + { + for (int ic = 0; ic < n; ++ic) + { + T value = T(); + for (int ik = 0; ik < k; ++ik) + { + value += left.atloc(ir, ik) * right.atloc(ik, ic); + } + reference.atloc(ir, ic) = value; + } + } + return reference; +} + +template +Matrix2d make_host_transpose_reference(const int nr, + const int nc) +{ + return make_transpose_reference(make_host_reference(nr, nc)); +} + +template +Matrix2d make_host_matmul_reference(const int m, + const int k, + const int n) +{ + return make_matmul_reference(make_host_reference(m, k), + make_host_reference(k, n, 10.0)); +} + +template +void check_host_transpose(const int nr, const int nc) +{ + const Matrix2d source = make_host_reference(nr, nc); + const Matrix2d transposed = source.transpose(); + const Matrix2d dagger = source.dagger(); + const Matrix2d expected_transpose = make_transpose_reference(source); + const Matrix2d expected_dagger = make_dagger_reference(source); + + verify_global_matrix(transposed, expected_transpose); + verify_global_matrix(dagger, expected_dagger); + EXPECT_FALSE(transposed.has_distribution()); + EXPECT_FALSE(dagger.has_distribution()); + EXPECT_FALSE(transposed.is_active()); + EXPECT_FALSE(dagger.is_active()); + EXPECT_EQ(transposed.nrglb(), nc); + EXPECT_EQ(transposed.ncglb(), nr); + EXPECT_EQ(dagger.nrglb(), nc); + EXPECT_EQ(dagger.ncglb(), nr); +} + +template +void check_host_matmul(const int m, + const int k, + const int n) +{ + const Matrix2d left = make_host_reference(m, k); + const Matrix2d right = make_host_reference(k, n, 10.0); + const Matrix2d product = left.matmul(right); + const Matrix2d expected = make_matmul_reference(left, right); + + verify_global_matrix(product, expected); + EXPECT_FALSE(product.has_distribution()); + EXPECT_FALSE(product.is_active()); +} + +#ifdef __MPI +template +void check_mpi_descriptor_for_type(const Matrix2d& matrix, + const int nrglb, + const int ncglb, + const int nrblk) +{ + const int* const desc = matrix.desc(); + ASSERT_NE(desc, nullptr); + EXPECT_EQ(desc[0], 1); + EXPECT_EQ(desc[1], matrix.ictxt()); + EXPECT_EQ(desc[2], nrglb); + EXPECT_EQ(desc[3], ncglb); + EXPECT_EQ(desc[4], nrblk); + EXPECT_EQ(desc[5], nrblk); + EXPECT_EQ(desc[6], 0); + EXPECT_EQ(desc[7], 0); + EXPECT_GT(desc[8], 0); +} + +template +void check_distributed_transpose(const int nr, + const int nc, + const int nrproc, + const int ncproc, + const int nrblk) +{ + Matrix2d source(nr, + nc, + nrproc, + ncproc, + nrblk, + MPI_COMM_WORLD); + fill_global_values(source); + const int* const desc_src0 = source.desc(); + + const Matrix2d transposed = source.transpose(); + const Matrix2d dagger = source.dagger(); + const int* const desc_src1 = source.desc(); + const int* const desc_res = transposed.desc(); + const int* const desc_dag = dagger.desc(); + + ASSERT_TRUE(transposed.has_distribution()); + ASSERT_TRUE(dagger.has_distribution()); + ASSERT_TRUE(transposed.is_active()); + ASSERT_TRUE(dagger.is_active()); + EXPECT_EQ(desc_src1, desc_src0); + EXPECT_NE(desc_res, nullptr); + EXPECT_NE(desc_dag, nullptr); + EXPECT_EQ(source.ictxt(), transposed.ictxt()); + EXPECT_EQ(source.ictxt(), dagger.ictxt()); + check_mpi_descriptor_for_type(transposed, nc, nr, nrblk); + check_mpi_descriptor_for_type(dagger, nc, nr, nrblk); + verify_global_matrix(transposed.gather(), + make_host_transpose_reference(nr, nc)); + verify_global_matrix(dagger.gather(), + make_dagger_reference(source.gather())); + EXPECT_EQ(source.desc(), desc_src1); + EXPECT_EQ(transposed.desc(), desc_res); + EXPECT_EQ(dagger.desc(), desc_dag); +} + +template +Matrix2d make_transpose_without_source(const int nr, + const int nc, + const int nrproc, + const int ncproc, + const int nrblk) +{ + Matrix2d source(nr, + nc, + nrproc, + ncproc, + nrblk, + MPI_COMM_WORLD); + fill_global_values(source); + return source.transpose(); +} + +template +void check_distributed_matmul(const int m, + const int k, + const int n, + const int nrproc, + const int ncproc, + const int nrblk) +{ + Matrix2d left(m, + k, + nrproc, + ncproc, + nrblk, + MPI_COMM_WORLD); + const int ictxt = left.ictxt(); + const std::shared_ptr right_distrib + = make_borrowed_distribution(k, + n, + nrblk, + ictxt); + Matrix2d right(right_distrib); + fill_global_values(left); + fill_global_values(right, 10.0); + + const int* const desc_lhs0 = left.desc(); + const int* const desc_rhs0 = right.desc(); + const Matrix2d product = left.matmul(right); + const int* const desc_lhs1 = left.desc(); + const int* const desc_rhs1 = right.desc(); + const int* const desc_res = product.desc(); + + ASSERT_TRUE(product.has_distribution()); + ASSERT_TRUE(product.is_active()); + EXPECT_EQ(desc_lhs1, desc_lhs0); + EXPECT_EQ(desc_rhs1, desc_rhs0); + EXPECT_NE(desc_res, nullptr); + EXPECT_EQ(left.ictxt(), right.ictxt()); + EXPECT_EQ(left.ictxt(), product.ictxt()); + check_mpi_descriptor_for_type(product, m, n, nrblk); + verify_global_matrix(product.gather(), + make_host_matmul_reference(m, + k, + n)); + EXPECT_EQ(left.desc(), desc_lhs1); + EXPECT_EQ(right.desc(), desc_rhs1); + EXPECT_EQ(product.desc(), desc_res); +} +#endif +} // namespace + +TEST(Matrix2dTest, HostTransposeAndDaggerMatchReferences) +{ + check_host_transpose(5, 3); + check_host_transpose(3, 5); + check_host_transpose>(5, 3); + check_host_transpose>(3, 5); +} + +TEST(Matrix2dTest, HostMatmulMatchesTripleLoopReference) +{ + check_host_matmul(5, 4, 6); + check_host_matmul>(5, 4, 6); +} + +TEST(Matrix2dTest, SerialDegenerateDistributionTransposeAndMatmul) +{ + const std::shared_ptr transpose_distrib + = make_frozen_distribution(5, 3); + Matrix2d transpose_source(transpose_distrib); + fill_global_values(transpose_source); + verify_global_matrix(transpose_source.transpose().gather(), + make_host_transpose_reference(5, 3)); + verify_global_matrix(transpose_source.dagger().gather(), + make_host_transpose_reference(5, 3)); + + const std::shared_ptr left_distrib + = make_frozen_distribution(5, 4); + const std::shared_ptr right_distrib + = make_frozen_distribution(4, 6); + Matrix2d left(left_distrib); + Matrix2d right(right_distrib); + fill_global_values(left); + fill_global_values(right, 10.0); + verify_global_matrix(left.matmul(right).gather(), + make_host_matmul_reference(5, 4, 6)); + + const std::shared_ptr complex_transpose_distrib + = make_frozen_distribution(5, 3); + Matrix2d> complex_transpose_source(complex_transpose_distrib); + fill_global_values(complex_transpose_source); + verify_global_matrix( + complex_transpose_source.transpose().gather(), + make_host_transpose_reference>(5, 3)); + verify_global_matrix( + complex_transpose_source.dagger().gather(), + make_dagger_reference(complex_transpose_source.gather())); + + const std::shared_ptr complex_left_distrib + = make_frozen_distribution(5, 4); + const std::shared_ptr complex_right_distrib + = make_frozen_distribution(4, 6); + Matrix2d> complex_left(complex_left_distrib); + Matrix2d> complex_right(complex_right_distrib); + fill_global_values(complex_left); + fill_global_values(complex_right, 10.0); + verify_global_matrix( + complex_left.matmul(complex_right).gather(), + make_host_matmul_reference>(5, 4, 6)); +} + +#ifdef __MPI +TEST(Matrix2dTest, TransposeAndDaggerDistributedMatchHost) +{ + const std::vector> grids = available_process_grids(); + for (std::size_t igrid = 0; igrid < grids.size(); ++igrid) + { + check_distributed_transpose(5, 3, + grids[igrid].first, + grids[igrid].second, + 3); + check_distributed_transpose(3, 5, + grids[igrid].first, + grids[igrid].second, + 3); + check_distributed_transpose>(5, 3, + grids[igrid].first, + grids[igrid].second, + 3); + check_distributed_transpose>(3, 5, + grids[igrid].first, + grids[igrid].second, + 3); + } +} + +TEST(Matrix2dTest, DistributedResultRetainsBlacsContext) +{ + const std::vector> grids = available_process_grids(); + if (grids.empty()) + { + return; + } + + const int nrproc = grids.front().first; + const int ncproc = grids.front().second; + const Matrix2d transposed + = make_transpose_without_source(5, 3, nrproc, ncproc, 3); + + ASSERT_TRUE(transposed.has_distribution()); + ASSERT_TRUE(transposed.is_active()); + ASSERT_NE(transposed.distribution(), nullptr); + EXPECT_NE(transposed.distribution()->comm(), MPI_COMM_NULL); + verify_global_matrix(transposed.gather(), + make_host_transpose_reference(5, 3)); +} + +TEST(Matrix2dTest, MatmulDistributedMatchesHost) +{ + const std::vector> grids = available_process_grids(); + for (std::size_t igrid = 0; igrid < grids.size(); ++igrid) + { + check_distributed_matmul(5, 4, 6, + grids[igrid].first, + grids[igrid].second, + 3); + check_distributed_matmul>(5, 4, 6, + grids[igrid].first, + grids[igrid].second, + 3); + } +} + +TEST(Matrix2dTest, UnsupportedDistributedTypesThrow) +{ + const std::vector> grids = available_process_grids(); + const std::pair& grid = grids[0]; + const int nrblk = 3; + { + Matrix2d source(5, + 3, + grid.first, + grid.second, + nrblk, + MPI_COMM_WORLD); + EXPECT_THROW(source.transpose(), std::invalid_argument); + } + { + Matrix2d source(5, + 3, + grid.first, + grid.second, + nrblk, + MPI_COMM_WORLD); + EXPECT_THROW(source.transpose(), std::invalid_argument); + } + { + Matrix2d> source(5, + 3, + grid.first, + grid.second, + nrblk, + MPI_COMM_WORLD); + EXPECT_THROW(source.transpose(), std::invalid_argument); + } + { + Matrix2d left(5, + 4, + grid.first, + grid.second, + nrblk, + MPI_COMM_WORLD); + const std::shared_ptr right_distrib + = make_borrowed_distribution(4, 6, nrblk, left.ictxt()); + Matrix2d right(right_distrib); + EXPECT_THROW(left.matmul(right), std::invalid_argument); + } + { + Matrix2d left(5, + 4, + grid.first, + grid.second, + nrblk, + MPI_COMM_WORLD); + const std::shared_ptr right_distrib + = make_borrowed_distribution(4, 6, nrblk, left.ictxt()); + Matrix2d right(right_distrib); + EXPECT_THROW(left.matmul(right), std::invalid_argument); + } + { + Matrix2d> left(5, + 4, + grid.first, + grid.second, + nrblk, + MPI_COMM_WORLD); + const std::shared_ptr right_distrib + = make_borrowed_distribution(4, 6, nrblk, left.ictxt()); + Matrix2d> right(right_distrib); + EXPECT_THROW(left.matmul(right), std::invalid_argument); + } +} + +TEST(Matrix2dTest, IncompatibleDistributionThrows) +{ + const std::vector> grids = available_process_grids(); + const std::pair& grid = grids[0]; + const int nrblk = 3; + { + Matrix2d first(8, 6, grid.first, grid.second, nrblk, MPI_COMM_WORLD); + Matrix2d different_block( + 6, 8, grid.first, grid.second, nrblk + 1, MPI_COMM_WORLD); + fill_global_values(first); + fill_global_values(different_block, 10.0); + EXPECT_THROW(first.matmul(different_block), std::invalid_argument); + } + if (grids.size() > 1) + { + const std::pair& other_grid = grids[1]; + Matrix2d first(8, 6, grid.first, grid.second, nrblk, MPI_COMM_WORLD); + Matrix2d different_grid( + 6, 8, other_grid.first, other_grid.second, nrblk, MPI_COMM_WORLD); + fill_global_values(first); + fill_global_values(different_grid, 10.0); + EXPECT_THROW(first.matmul(different_grid), std::invalid_argument); + } + { + Matrix2d first(8, 6, grid.first, grid.second, nrblk, MPI_COMM_WORLD); + Matrix2d different_context( + 6, 8, grid.first, grid.second, nrblk, MPI_COMM_WORLD); + fill_global_values(first); + fill_global_values(different_context, 10.0); + EXPECT_THROW(first.matmul(different_context), std::invalid_argument); + } +} + +TEST(Matrix2dTest, DescriptorAddressStableAcrossOperators) +{ + const std::vector> grids = available_process_grids(); + const std::pair& grid = grids[0]; + const int nrblk = 3; + Matrix2d left(5, 4, grid.first, grid.second, nrblk, MPI_COMM_WORLD); + const int ictxt = left.ictxt(); + const std::shared_ptr right_distrib + = make_borrowed_distribution(4, 6, nrblk, ictxt); + Matrix2d right(right_distrib); + fill_global_values(left); + fill_global_values(right, 10.0); + + const int* const desc_lhs = left.desc(); + const int* const desc_rhs = right.desc(); + + const Matrix2d transposed = left.transpose(); + const Matrix2d product = left.matmul(right); + + EXPECT_EQ(left.desc(), desc_lhs); + EXPECT_EQ(right.desc(), desc_rhs); + EXPECT_EQ(left.ictxt(), transposed.ictxt()); + EXPECT_EQ(left.ictxt(), product.ictxt()); + + verify_global_matrix(product.gather(), + make_host_matmul_reference(5, 4, 6)); +} +#endif + +TEST(Matrix2dTest, HostConstructionAndRowMajorLayout) +{ + check_host_layout(); +} + +TEST(Matrix2dTest, HostCopyDeepCopiesStorage) +{ + Matrix2d source(2, 2); + source.atloc(0, 0) = 1.0; + source.atloc(0, 1) = 2.0; + source.atloc(1, 0) = 3.0; + source.atloc(1, 1) = 4.0; + + Matrix2d copy(source); + EXPECT_EQ(copy.distribution(), nullptr); + EXPECT_NE(copy.data(), source.data()); + EXPECT_EQ(copy.atloc(1, 1), 4.0); + copy.atloc(1, 1) = 9.0; + EXPECT_EQ(source.atloc(1, 1), 4.0); + + Matrix2d assigned(1, 1); + assigned = source; + EXPECT_NE(assigned.data(), source.data()); + EXPECT_EQ(assigned.atloc(0, 1), 2.0); +} + +TEST(Matrix2dTest, SerialDistributionHandleUsesColumnMajorLayout) +{ + const std::shared_ptr distrib + = make_frozen_distribution(3, 2); + Matrix2d matrix(distrib); + + EXPECT_TRUE(matrix.has_distribution()); + EXPECT_FALSE(matrix.is_active()); + EXPECT_EQ(matrix.distribution().get(), distrib.get()); + EXPECT_EQ(matrix.ictxt(), -1); + check_distribution_layout(matrix, 3, 2); +} + +TEST(Matrix2dTest, SerialDistributionTallSkinnyStorageUsesColumnExtent) +{ + const int nrglb = 1024; + const int ncglb = 1; + const std::shared_ptr distrib + = make_frozen_distribution(nrglb, ncglb); + Matrix2d matrix(distrib); + + const std::size_t nstor_expected + = static_cast(nrglb) + * static_cast(ncglb); + const std::size_t nrowmajor + = static_cast(matrix.nrloc()) + * static_cast(matrix.ncloc()); + EXPECT_EQ(matrix.local_storage_size(), nstor_expected); + EXPECT_LE(nrowmajor, matrix.local_storage_size()); +} + +#ifndef __MPI +TEST(Matrix2dTest, SerialDistributionViewMatchesColumnMajorStorageWithoutMpi) +{ + const std::shared_ptr distrib + = make_frozen_distribution(3, 2); + Matrix2d matrix(distrib); + fill_global_values(matrix); + + Matrix2dView matrix_view = matrix.view(); + ASSERT_TRUE(matrix_view.has_distribution()); + ASSERT_FALSE(matrix_view.is_active()); + EXPECT_EQ(matrix_view.nrglb(), matrix.nrglb()); + EXPECT_EQ(matrix_view.ncglb(), matrix.ncglb()); + EXPECT_EQ(matrix_view.nrloc(), matrix.nrloc()); + EXPECT_EQ(matrix_view.ncloc(), matrix.ncloc()); + EXPECT_EQ(matrix_view.lld(), matrix.lld()); + EXPECT_EQ(matrix_view.data(), matrix.data()); + for (int irloc = 0; irloc < matrix.nrloc(); ++irloc) + { + for (int icloc = 0; icloc < matrix.ncloc(); ++icloc) + { + EXPECT_EQ(&matrix_view.atloc(irloc, icloc), + &matrix.atloc(irloc, icloc)); + } + } + + const Matrix2d& const_matrix = matrix; + Matrix2dView const_view = const_matrix.view(); + EXPECT_EQ(const_view.data(), matrix.data()); + for (int irloc = 0; irloc < matrix.nrloc(); ++irloc) + { + for (int icloc = 0; icloc < matrix.ncloc(); ++icloc) + { + EXPECT_EQ(&const_view.atloc(irloc, icloc), + &matrix.atloc(irloc, icloc)); + } + } +} +#endif + +TEST(Matrix2dTest, CopiesShareDistributionAndDeepCopyStorage) +{ + const std::shared_ptr distrib + = make_frozen_distribution(3, 2); + Matrix2d source(distrib); + source.atloc(0, 0) = 7.0; + + Matrix2d copy(source); + EXPECT_EQ(copy.distribution().get(), distrib.get()); + EXPECT_EQ(source.distribution().get(), copy.distribution().get()); + EXPECT_NE(copy.data(), source.data()); + EXPECT_EQ(copy.atloc(0, 0), 7.0); + copy.atloc(0, 0) = 8.0; + EXPECT_EQ(source.atloc(0, 0), 7.0); +} + +TEST(Matrix2dTest, MatricesFromSameHandleShareContext) +{ + const std::shared_ptr distrib + = make_frozen_distribution(5, 4); + Matrix2d first(distrib); + Matrix2d second(distrib); + + EXPECT_EQ(first.distribution().get(), second.distribution().get()); + EXPECT_EQ(first.ictxt(), second.ictxt()); + EXPECT_NE(first.data(), second.data()); +} + +TEST(Matrix2dTest, RejectsNullDistribution) +{ + const std::shared_ptr distrib; + EXPECT_THROW( + { + Matrix2d matrix(distrib); + static_cast(matrix); + }, + std::invalid_argument); +} + +#ifdef __MPI +TEST(Matrix2dTest, BlockSizeConstructorAtLocalAndAtGlobal) +{ + const int nrglb = 8; + const int ncglb = 6; + const int nrblk = 2; + Matrix2d matrix(nrglb, ncglb, nrblk, MPI_COMM_WORLD); + + check_mpi_descriptor(matrix, nrglb, ncglb, nrblk); + check_distribution_layout(matrix, nrglb, ncglb); +} + +TEST(Matrix2dTest, UnitBlockConstructorAtLocalAndAtGlobal) +{ + const int nrglb = 5; + const int ncglb = 3; + Matrix2d matrix(nrglb, ncglb, MPI_COMM_WORLD); + + check_mpi_descriptor(matrix, nrglb, ncglb, 1); + check_distribution_layout(matrix, nrglb, ncglb); +} + +TEST(Matrix2dTest, FrozenHandleConstructorSharesBlacsContext) +{ + const int nrglb = 8; + const int ncglb = 6; + const int nrblk = 2; + const std::shared_ptr distrib + = make_frozen_distribution(nrglb, ncglb, nrblk, MPI_COMM_WORLD); + Matrix2d first(distrib); + Matrix2d second(distrib); + + const int ictxt = distrib->ictxt(); + EXPECT_GE(ictxt, 0); + EXPECT_EQ(first.distribution().get(), distrib.get()); + EXPECT_EQ(second.distribution().get(), distrib.get()); + EXPECT_EQ(first.ictxt(), ictxt); + EXPECT_EQ(second.ictxt(), ictxt); + check_mpi_descriptor(first, nrglb, ncglb, nrblk); +} +#endif + +TEST(Matrix2dTest, DistributedReshapeIsRejectedAtCompileTime) +{ + EXPECT_FALSE(HasReshape>::value); +} + +TEST(Matrix2dTest, HostElementwiseReductionsAndGatherScatter) +{ + Matrix2d matrix(3, 4); + Matrix2d other(3, 4); + fill_global_values(matrix); + fill_global_values(other, 10.0); + check_elementwise_operations(matrix, other); + check_reductions(matrix, other); + + const Matrix2d gathered = matrix.gather(); + EXPECT_NE(gathered.data(), matrix.data()); + verify_global_matrix(gathered, make_host_reference(3, 4)); + + Matrix2d restored(3, 4); + restored.scatter(gathered); + verify_global_matrix(restored, make_host_reference(3, 4)); + + const Matrix2d root_result = matrix.gather_on_root(0); + verify_global_matrix(root_result, make_host_reference(3, 4)); +} + +TEST(Matrix2dTest, HostComplexElementwiseAndReductions) +{ + Matrix2d> matrix(3, 4); + Matrix2d> other(3, 4); + fill_global_values(matrix); + fill_global_values(other, 10.0); + report_reduction_tolerances(); + check_elementwise_operations(matrix, other); + check_reductions(matrix, other); +} + +TEST(Matrix2dTest, MaxAbsWidensIntegerBeforeTakingAbsoluteValue) +{ + Matrix2d matrix(1, 2); + matrix.atloc(0, 0) = std::numeric_limits::min(); + matrix.atloc(0, 1) = std::numeric_limits::max(); + const double int_min_as_double + = static_cast(std::numeric_limits::min()); + const double expected = -int_min_as_double; + EXPECT_DOUBLE_EQ(matrix.max_abs(), expected); +} + +TEST(Matrix2dTest, NormWidensIntegerBeforeSquaring) +{ + Matrix2d matrix(1, 1); + matrix.atloc(0, 0) = std::numeric_limits::min(); + const double expected = 2147483648.0; + EXPECT_DOUBLE_EQ(matrix.norm(), expected); +} + +TEST(Matrix2dTest, ReductionsUseTheMatrixRealType) +{ + const std::complex complex_float_first(3.0f, 4.0f); + const std::complex complex_float_second(0.0f, 0.0f); + const std::complex complex_float_large(1.0e20f, 0.0f); + const std::complex complex_float_small(1.0e-30f, 0.0f); + const std::complex complex_double_first(3.0, 4.0); + const std::complex complex_double_second(0.0, 0.0); + check_reduction_scalar_type(3, 4, 5.0, 4.0); + check_reduction_scalar_type(3.0f, 4.0f, 5.0f, 4.0f); + check_reduction_scalar_type(3.0, 4.0, 5.0, 4.0); + check_reduction_scalar_type>( + complex_float_first, + complex_float_second, + 5.0f, + 5.0f); + check_reduction_scalar_type>( + complex_double_first, + complex_double_second, + 5.0, + 5.0); + check_float_reduction_range(1.0e20f, 1.0e20f); + check_float_reduction_range(1.0e-30f, 1.0e-30f); + check_float_reduction_range(complex_float_large, 1.0e20f); + check_float_reduction_range(complex_float_small, 1.0e-30f); +} + +TEST(Matrix2dTest, SerialDistributionGatherReturnsHostRowMajorCopy) +{ + const std::shared_ptr distrib + = make_frozen_distribution(3, 2); + Matrix2d matrix(distrib); + fill_global_values(matrix); + + const Matrix2d gathered = matrix.gather(); + EXPECT_FALSE(gathered.has_distribution()); + EXPECT_FALSE(gathered.is_active()); + verify_global_matrix(gathered, make_host_reference(3, 2)); + + const Matrix2d root_gathered = matrix.gather_on_root(0); + EXPECT_FALSE(root_gathered.has_distribution()); + EXPECT_FALSE(root_gathered.is_active()); + verify_global_matrix(root_gathered, make_host_reference(3, 2)); +} + +#ifdef __MPI +TEST(Matrix2dTest, DistributedDoubleAcrossBlocksAndProcessGrids) +{ + report_reduction_tolerances(); + const std::vector> grids = available_process_grids(); + const int nrblks[] = {2, 3, 4}; + for (std::size_t igrid = 0; igrid < grids.size(); ++igrid) + { + for (std::size_t iblk = 0; iblk < 3; ++iblk) + { + Matrix2d matrix(9, + 7, + grids[igrid].first, + grids[igrid].second, + nrblks[iblk], + MPI_COMM_WORLD); + Matrix2d other(matrix.distribution()); + fill_global_values(matrix); + fill_global_values(other, 10.0); + check_elementwise_operations(matrix, other); + check_reductions(matrix, other); + check_gather_scatter(matrix); + } + } +} + +TEST(Matrix2dTest, DistributedComplexAcrossBlocksAndProcessGrids) +{ + report_reduction_tolerances(); + const std::vector> grids = available_process_grids(); + const int nrblks[] = {2, 3, 4}; + for (std::size_t igrid = 0; igrid < grids.size(); ++igrid) + { + for (std::size_t iblk = 0; iblk < 3; ++iblk) + { + Matrix2d> matrix(9, + 7, + grids[igrid].first, + grids[igrid].second, + nrblks[iblk], + MPI_COMM_WORLD); + Matrix2d> other(matrix.distribution()); + fill_global_values(matrix); + fill_global_values(other, 10.0); + check_elementwise_operations(matrix, other); + check_reductions(matrix, other); + check_gather_scatter(matrix); + } + } +} + +TEST(Matrix2dTest, TallSkinnyPaddingDoesNotAffectOperatorsOrGather) +{ + const int nproc = Parallel_Common::comm_size(MPI_COMM_WORLD); + const int nrglb = 1025; + const int ncglb = 3; + const int nrblk = 7; + Matrix2d matrix(nrglb, + ncglb, + 1, + nproc, + nrblk, + MPI_COMM_WORLD); + Matrix2d other(matrix.distribution()); + fill_global_values(matrix); + fill_global_values(other, 10.0); + + const double sentinel = -98765.25; + const std::size_t nstor_expected + = expected_local_storage_size(matrix); + const std::size_t nlogical + = static_cast(matrix.nrloc()) + * static_cast(matrix.ncloc()); + EXPECT_EQ(matrix.local_storage_size(), nstor_expected); + EXPECT_LE(nlogical, matrix.local_storage_size()); + const std::vector padding_indices + = set_padding_sentinel(matrix, sentinel); + const std::size_t npadding_expected + = nstor_expected - nlogical; + EXPECT_EQ(padding_indices.size(), npadding_expected); + if (nproc > 1) + { + if (matrix.icproc() == 0) + { + EXPECT_GT(matrix.ncloc(), 0); + } + else + { + EXPECT_EQ(matrix.ncloc(), 0); + EXPECT_EQ(matrix.local_storage_size(), 1U); + EXPECT_EQ(padding_indices.size(), 1U); + } + } + set_padding_sentinel(other, 12345.5); + + matrix += other; + Matrix2d expected + = make_host_reference(nrglb, ncglb); + const Matrix2d other_reference + = make_host_reference(nrglb, ncglb, 10.0); + for (int ir = 0; ir < nrglb; ++ir) + { + for (int ic = 0; ic < ncglb; ++ic) + { + expected.atloc(ir, ic) += other_reference.atloc(ir, ic); + } + } + verify_global_matrix(matrix.gather(), expected); + expect_padding_sentinel(matrix, padding_indices, sentinel); + + matrix.fill(2.0); + expect_padding_sentinel(matrix, padding_indices, sentinel); + matrix.scale(3.0); + expect_padding_sentinel(matrix, padding_indices, sentinel); + + const Matrix2d scatter_reference + = make_host_reference(nrglb, ncglb); + matrix.scatter(scatter_reference); + verify_global_matrix(matrix.gather(), scatter_reference); + expect_padding_sentinel(matrix, padding_indices, sentinel); +} + +TEST(Matrix2dTest, RejectsIncompatibleDistributions) +{ + const int nproc = Parallel_Common::comm_size(MPI_COMM_WORLD); + const std::vector> grids = available_process_grids(); + Matrix2d first(8, + 6, + grids.front().first, + grids.front().second, + 2, + MPI_COMM_WORLD); + Matrix2d same_layout_other_handle(8, + 6, + grids.front().first, + grids.front().second, + 2, + MPI_COMM_WORLD); + EXPECT_THROW(first += same_layout_other_handle, std::invalid_argument); + + Matrix2d different_block(8, + 6, + grids.front().first, + grids.front().second, + 3, + MPI_COMM_WORLD); + EXPECT_THROW(first += different_block, std::invalid_argument); + + Matrix2d host(8, 6); + EXPECT_THROW(first += host, std::invalid_argument); + EXPECT_THROW(first.dot(host), std::invalid_argument); + + if (nproc > 1) + { + const std::pair& other_grid = grids[1]; + Matrix2d different_grid(8, + 6, + other_grid.first, + other_grid.second, + 2, + MPI_COMM_WORLD); + EXPECT_THROW(first += different_grid, std::invalid_argument); + } +} +#endif + +int main(int argc, char** argv) +{ +#ifdef __MPI + MPI_Init(&argc, &argv); +#endif + testing::InitGoogleTest(&argc, argv); + const int result = RUN_ALL_TESTS(); +#ifdef __MPI + MPI_Finalize(); +#endif + return result; +} diff --git a/source/source_base/unittests/test_matrix2d_linalg.cpp b/source/source_base/unittests/test_matrix2d_linalg.cpp new file mode 100644 index 00000000000..384546d8bcc --- /dev/null +++ b/source/source_base/unittests/test_matrix2d_linalg.cpp @@ -0,0 +1,817 @@ +#include "source_base/matrix2d_linalg.h" +#include "source_base/matrix2d.h" + +#ifdef __MPI +#include "source_base/parallel_common.h" +#endif + +#include "gtest/gtest.h" + +#include +#include +#include +#include +#include +#include +#include + +namespace +{ +void expect_near(const double actual, const double expected) +{ + EXPECT_NEAR(actual, expected, 1.0e-12); +} + +void expect_near(const std::complex& actual, + const std::complex& expected) +{ + EXPECT_NEAR(actual.real(), expected.real(), 1.0e-12); + EXPECT_NEAR(actual.imag(), expected.imag(), 1.0e-12); +} + +template +void expect_host_matrices_near(const Matrix2d& actual, + const Matrix2d& expected) +{ + ASSERT_EQ(actual.nrglb(), expected.nrglb()); + ASSERT_EQ(actual.ncglb(), expected.ncglb()); + for (int i = 0; i < expected.nrglb(); ++i) + { + for (int j = 0; j < expected.ncglb(); ++j) + { + expect_near(actual.atloc(i, j), expected.atloc(i, j)); + } + } +} + +template +class IsTwoArgumentSolveCallable +{ + private: + template + static auto test(int) -> decltype( + matrix2d_linalg::solve(std::declval(), std::declval()), + std::true_type()); + + template + static std::false_type test(...); + + public: + static const bool value + = decltype(test(0))::value; +}; + +template +class IsSolveInplaceCallable +{ + private: + template + static auto test(int) -> decltype( + matrix2d_linalg::solve_inplace(std::declval(), std::declval()), + std::true_type()); + + template + static std::false_type test(...); + + public: + static const bool value + = decltype(test(0))::value; +}; + +static_assert( + std::is_same< + decltype(matrix2d_linalg::solve( + std::declval&>(), + std::declval&>())), + Matrix2d>::value, + "two-argument solve must return Matrix2d by value"); +static_assert( + std::is_same< + decltype(matrix2d_linalg::solve( + std::declval&>(), + std::declval&>(), + std::declval&>())), + void>::value, + "three-argument solve must be the output-parameter overload"); +static_assert( + std::is_same< + decltype(matrix2d_linalg::matmul( + std::declval&>(), + std::declval&>())), + Matrix2d>::value, + "two-argument matmul must return Matrix2d by value"); +static_assert( + std::is_same< + decltype(matrix2d_linalg::inv( + std::declval&>())), + Matrix2d>::value, + "one-argument inv must return Matrix2d by value"); +static_assert(!IsTwoArgumentSolveCallable, + Matrix2dView>::value, + "views must use the explicitly named solve_inplace primitive"); +static_assert(IsSolveInplaceCallable, + Matrix2dView>::value, + "mutable views must bind to solve_inplace"); +static_assert(!IsSolveInplaceCallable, + Matrix2dView>::value, + "solve_inplace must not accept a const coefficient matrix"); +static_assert(!IsSolveInplaceCallable, + Matrix2dView>::value, + "solve_inplace must not accept a const right-hand side"); + +Matrix2d make_real_system() +{ + Matrix2d matrix(2, 2); + matrix.atloc(0, 0) = 4.0; + matrix.atloc(0, 1) = 1.0; + matrix.atloc(1, 0) = 2.0; + matrix.atloc(1, 1) = 3.0; + return matrix; +} + +Matrix2d make_real_rhs() +{ + Matrix2d rhs(2, 2); + rhs.atloc(0, 0) = 1.0; + rhs.atloc(0, 1) = 2.0; + rhs.atloc(1, 0) = 3.0; + rhs.atloc(1, 1) = 4.0; + return rhs; +} + +Matrix2d make_real_inverse_reference() +{ + Matrix2d inverse(2, 2); + inverse.atloc(0, 0) = 0.3; + inverse.atloc(0, 1) = -0.1; + inverse.atloc(1, 0) = -0.2; + inverse.atloc(1, 1) = 0.4; + return inverse; +} + +Matrix2d> make_complex_system() +{ + Matrix2d> matrix(2, 2); + matrix.atloc(0, 0) = std::complex(1.0, 1.0); + matrix.atloc(0, 1) = std::complex(2.0, 0.0); + matrix.atloc(1, 0) = std::complex(3.0, 0.0); + matrix.atloc(1, 1) = std::complex(4.0, -1.0); + return matrix; +} + +Matrix2d> make_complex_solution() +{ + Matrix2d> solution(2, 2); + solution.atloc(0, 0) = std::complex(1.0, 0.0); + solution.atloc(0, 1) = std::complex(0.0, 2.0); + solution.atloc(1, 0) = std::complex(3.0, 0.0); + solution.atloc(1, 1) = std::complex(4.0, 0.0); + return solution; +} + +#ifdef __MPI +std::vector> available_process_grids() +{ + const int nproc = Parallel_Common::comm_size(MPI_COMM_WORLD); + std::vector> grids; + if (nproc == 1) + { + grids.push_back(std::make_pair(1, 1)); + } + if (nproc == 2) + { + grids.push_back(std::make_pair(1, 2)); + grids.push_back(std::make_pair(2, 1)); + } + if (nproc == 4) + { + grids.push_back(std::make_pair(1, 4)); + grids.push_back(std::make_pair(2, 2)); + grids.push_back(std::make_pair(4, 1)); + } + return grids; +} + +Matrix2d make_distributed_real_system(const int size) +{ + Matrix2d matrix(size, size); + for (int i = 0; i < size; ++i) + { + for (int j = 0; j < size; ++j) + { + if (i == j) + { + matrix.atloc(i, j) = 6.0 + i; + } + else if (std::abs(i - j) == 1) + { + matrix.atloc(i, j) = 0.5; + } + else + { + matrix.atloc(i, j) = 0.0; + } + } + } + return matrix; +} + +Matrix2d make_distributed_real_solution(const int nr, + const int nc) +{ + Matrix2d solution(nr, nc); + for (int i = 0; i < nr; ++i) + { + for (int j = 0; j < nc; ++j) + { + solution.atloc(i, j) + = static_cast(1 + i + 2 * j); + } + } + return solution; +} + +Matrix2d> make_distributed_complex_system(const int size) +{ + Matrix2d> matrix(size, size); + for (int i = 0; i < size; ++i) + { + for (int j = 0; j < size; ++j) + { + if (i == j) + { + matrix.atloc(i, j) + = std::complex(6.0 + i, 0.5); + } + else if (j == i + 1) + { + matrix.atloc(i, j) + = std::complex(0.5, 0.25); + } + else if (j + 1 == i) + { + matrix.atloc(i, j) + = std::complex(0.5, -0.25); + } + else + { + matrix.atloc(i, j) = std::complex(0.0, 0.0); + } + } + } + return matrix; +} + +Matrix2d> make_distributed_complex_solution( + const int nr, + const int nc) +{ + Matrix2d> solution(nr, nc); + for (int i = 0; i < nr; ++i) + { + for (int j = 0; j < nc; ++j) + { + solution.atloc(i, j) + = std::complex(1 + i + 2 * j, i - j); + } + } + return solution; +} + +template +void expect_distributed_context(const Matrix2d& actual, + const Matrix2d& source) +{ + ASSERT_TRUE(actual.has_distribution()); + ASSERT_TRUE(source.has_distribution()); + EXPECT_TRUE(actual.is_active()); + EXPECT_EQ(actual.nrproc(), source.nrproc()); + EXPECT_EQ(actual.ncproc(), source.ncproc()); + EXPECT_EQ(actual.ictxt(), source.ictxt()); + EXPECT_EQ(actual.distribution()->nb(), source.distribution()->nb()); +} + +template +void check_distributed_solve(const Matrix2d& host_matrix, + const Matrix2d& host_solution, + const int nrproc, + const int ncproc, + const int nrblk) +{ + const Matrix2d host_rhs = host_matrix.matmul(host_solution); + Matrix2d matrix(host_matrix.nrglb(), + host_matrix.ncglb(), + nrproc, + ncproc, + nrblk, + MPI_COMM_WORLD); + const std::shared_ptr solution_distrib + = make_borrowed_distribution(host_solution.nrglb(), + host_solution.ncglb(), + nrblk, + matrix.ictxt()); + Matrix2d solution(solution_distrib); + matrix.scatter(host_matrix); + solution.scatter(host_solution); + const Matrix2d& matrix_input = matrix; + const Matrix2d& solution_input = solution; + const Matrix2d rhs + = matrix2d_linalg::matmul(matrix_input, solution_input); + expect_distributed_context(rhs, matrix_input); + expect_host_matrices_near(rhs.gather(), host_rhs); + expect_host_matrices_near(matrix.gather(), host_matrix); + expect_host_matrices_near(solution.gather(), host_solution); + + const Matrix2d solution_value + = matrix2d_linalg::solve(matrix_input, rhs); + EXPECT_EQ(solution_value.distribution(), rhs.distribution()); + expect_distributed_context(solution_value, rhs); + expect_host_matrices_near(solution_value.gather(), host_solution); + expect_host_matrices_near(matrix.gather(), host_matrix); + expect_host_matrices_near(rhs.gather(), host_rhs); + + Matrix2d solution_output(1, 1); + matrix2d_linalg::solve(matrix_input, rhs, solution_output); + EXPECT_EQ(solution_output.distribution(), rhs.distribution()); + expect_distributed_context(solution_output, rhs); + expect_host_matrices_near(solution_output.gather(), host_solution); + expect_host_matrices_near(matrix.gather(), host_matrix); + expect_host_matrices_near(rhs.gather(), host_rhs); + + Matrix2d product_output(1, 1); + matrix2d_linalg::matmul(matrix_input, + solution_input, + product_output); + expect_distributed_context(product_output, matrix_input); + expect_host_matrices_near(product_output.gather(), host_rhs); + expect_host_matrices_near(matrix.gather(), host_matrix); + expect_host_matrices_near(solution.gather(), host_solution); +} + +template +void check_distributed_inverse(const Matrix2d& host_matrix, + const int nrproc, + const int ncproc, + const int nrblk) +{ + const Matrix2d expected = matrix2d_linalg::inv(host_matrix); + const Matrix2d host_matrix_original = host_matrix; + expect_host_matrices_near(host_matrix, host_matrix_original); + + Matrix2d matrix(host_matrix.nrglb(), + host_matrix.ncglb(), + nrproc, + ncproc, + nrblk, + MPI_COMM_WORLD); + matrix.scatter(host_matrix); + const Matrix2d inverse_value = matrix2d_linalg::inv(matrix); + EXPECT_EQ(inverse_value.distribution(), matrix.distribution()); + expect_distributed_context(inverse_value, matrix); + expect_host_matrices_near(inverse_value.gather(), expected); + expect_host_matrices_near(matrix.gather(), host_matrix_original); + + Matrix2d inverse_output(1, 1); + matrix2d_linalg::inv(matrix, inverse_output); + EXPECT_EQ(inverse_output.distribution(), matrix.distribution()); + expect_distributed_context(inverse_output, matrix); + expect_host_matrices_near(inverse_output.gather(), expected); + expect_host_matrices_near(matrix.gather(), host_matrix_original); +} +#endif +} // namespace + +TEST(Matrix2dLinalgTest, HostRealInverseAndSolve) +{ + const Matrix2d matrix = make_real_system(); + const Matrix2d matrix_original = matrix; + const Matrix2d inverse_reference = make_real_inverse_reference(); + const Matrix2d inverse = matrix2d_linalg::inv(matrix); + expect_host_matrices_near(inverse, inverse_reference); + + Matrix2d inverse_output(1, 1); + matrix2d_linalg::inv(matrix, inverse_output); + expect_host_matrices_near(inverse_output, inverse_reference); + expect_host_matrices_near(matrix, matrix_original); + + const Matrix2d rhs = make_real_rhs(); + const Matrix2d rhs_original = rhs; + const Matrix2d expected + = matrix2d_linalg::matmul(inverse_reference, rhs); + + const Matrix2d solution = matrix2d_linalg::solve(matrix, rhs); + expect_host_matrices_near(solution, expected); + expect_host_matrices_near(rhs, rhs_original); + expect_host_matrices_near(matrix, matrix_original); + + Matrix2d solution_output(1, 1); + matrix2d_linalg::solve(matrix, rhs, solution_output); + expect_host_matrices_near(solution_output, expected); + expect_host_matrices_near(rhs, rhs_original); + expect_host_matrices_near(matrix, matrix_original); +} + +TEST(Matrix2dLinalgTest, OutputOverloadsMayAliasInputs) +{ + const Matrix2d matrix = make_real_system(); + const Matrix2d rhs = make_real_rhs(); + const Matrix2d expected = matrix2d_linalg::solve(matrix, rhs); + + Matrix2d aliased_rhs = rhs; + matrix2d_linalg::solve(matrix, aliased_rhs, aliased_rhs); + expect_host_matrices_near(aliased_rhs, expected); + + Matrix2d aliased_matrix = matrix; + matrix2d_linalg::solve(aliased_matrix, rhs, aliased_matrix); + expect_host_matrices_near(aliased_matrix, expected); + + Matrix2d aliased_inverse = matrix; + matrix2d_linalg::inv(aliased_inverse, aliased_inverse); + const Matrix2d inverse_reference = make_real_inverse_reference(); + expect_host_matrices_near(aliased_inverse, inverse_reference); + + Matrix2d product = make_real_system(); + matrix2d_linalg::matmul(matrix, product, product); + const Matrix2d expected_product + = matrix2d_linalg::matmul(matrix, matrix); + expect_host_matrices_near(product, expected_product); +} + +TEST(Matrix2dLinalgTest, HostOutputAndValueForms) +{ + const Matrix2d left = make_real_system(); + const Matrix2d right = make_real_inverse_reference(); + const Matrix2d product = matrix2d_linalg::matmul(left, right); + Matrix2d product_output(1, 1); + matrix2d_linalg::matmul(left, right, product_output); + const Matrix2d product_reference = left.matmul(right); + expect_host_matrices_near(product, product_reference); + expect_host_matrices_near(product_output, product); + + const Matrix2d combination + = matrix2d_linalg::axpby(2.0, left, -0.5, right); + Matrix2d combination_output(1, 1); + matrix2d_linalg::axpby(2.0, left, -0.5, right, combination_output); + expect_host_matrices_near(combination_output, combination); + + const Matrix2d scaled = matrix2d_linalg::scale(left, 3.0); + Matrix2d scaled_output(1, 1); + matrix2d_linalg::scale(left, 3.0, scaled_output); + expect_host_matrices_near(scaled_output, scaled); + const Matrix2d left_original = make_real_system(); + expect_host_matrices_near(left, left_original); + + const Matrix2d transposed = matrix2d_linalg::transpose(left); + const Matrix2d dagger = matrix2d_linalg::dagger(left); + const Matrix2d transposed_reference = left.transpose(); + const Matrix2d dagger_reference = left.dagger(); + expect_host_matrices_near(transposed, transposed_reference); + expect_host_matrices_near(dagger, dagger_reference); +} + +TEST(Matrix2dLinalgTest, ExplicitInverseSatisfiesInverseIdentity) +{ + const Matrix2d real_matrix = make_real_system(); + Matrix2d real_inverse = real_matrix; + Matrix2dView real_inverse_view = real_inverse.view(); + matrix2d_linalg::inv_inplace(real_inverse_view); + Matrix2d real_identity(2, 2); + Matrix2dView real_identity_view = real_identity.view(); + matrix2d_linalg::set_identity_inplace(real_identity_view); + const Matrix2d real_product + = matrix2d_linalg::matmul(real_matrix, real_inverse); + expect_host_matrices_near(real_product, real_identity); + + const Matrix2d> complex_matrix + = make_complex_system(); + const Matrix2d> complex_inverse + = matrix2d_linalg::inv(complex_matrix); + const Matrix2d> complex_identity + = matrix2d_linalg::eye>(2); + const Matrix2d> complex_product + = matrix2d_linalg::matmul(complex_matrix, complex_inverse); + expect_host_matrices_near(complex_product, complex_identity); +} + +TEST(Matrix2dLinalgTest, HostComplexSolve) +{ + const Matrix2d> matrix = make_complex_system(); + const Matrix2d> matrix_original = matrix; + const Matrix2d> expected = make_complex_solution(); + const Matrix2d> rhs + = matrix2d_linalg::matmul(matrix, expected); + const Matrix2d> rhs_original = rhs; + + const Matrix2d> solution + = matrix2d_linalg::solve(matrix, rhs); + expect_host_matrices_near(solution, expected); + expect_host_matrices_near(rhs, rhs_original); + expect_host_matrices_near(matrix, matrix_original); + + Matrix2d> solution_output(1, 1); + matrix2d_linalg::solve(matrix, rhs, solution_output); + expect_host_matrices_near(solution_output, expected); + + const Matrix2d> inverse + = matrix2d_linalg::inv(matrix); + Matrix2d> inverse_reference(2, 2); + inverse_reference.atloc(0, 0) = std::complex(-0.7, -1.1); + inverse_reference.atloc(0, 1) = std::complex(0.2, 0.6); + inverse_reference.atloc(1, 0) = std::complex(0.3, 0.9); + inverse_reference.atloc(1, 1) = std::complex(0.2, -0.4); + expect_host_matrices_near(inverse, inverse_reference); + expect_host_matrices_near(matrix, matrix_original); +} + +TEST(Matrix2dLinalgTest, SerialDistributionUsesLocalBackend) +{ + const std::shared_ptr distrib + = make_frozen_distribution(2, 2); + + Matrix2d matrix(distrib); + matrix.atloc(0, 0) = 4.0; + matrix.atloc(0, 1) = 1.0; + matrix.atloc(1, 0) = 2.0; + matrix.atloc(1, 1) = 3.0; + const Matrix2d matrix_original = matrix; + + Matrix2d rhs(distrib); + rhs.atloc(0, 0) = 1.0; + rhs.atloc(0, 1) = 2.0; + rhs.atloc(1, 0) = 3.0; + rhs.atloc(1, 1) = 4.0; + const Matrix2d rhs_original = rhs; + const Matrix2d inverse_reference = make_real_inverse_reference(); + const Matrix2d expected = inverse_reference.matmul(rhs); + const Matrix2d solution = matrix2d_linalg::solve(matrix, rhs); + expect_host_matrices_near(solution, expected); + EXPECT_EQ(solution.distribution(), rhs.distribution()); + expect_host_matrices_near(matrix, matrix_original); + expect_host_matrices_near(rhs, rhs_original); + + Matrix2d solution_output(1, 1); + matrix2d_linalg::solve(matrix, rhs, solution_output); + expect_host_matrices_near(solution_output, expected); + EXPECT_EQ(solution_output.distribution(), rhs.distribution()); + expect_host_matrices_near(matrix, matrix_original); + expect_host_matrices_near(rhs, rhs_original); + + const Matrix2d inverse = matrix2d_linalg::inv(matrix); + expect_host_matrices_near(inverse, inverse_reference); + EXPECT_EQ(inverse.distribution(), matrix.distribution()); + expect_host_matrices_near(matrix, matrix_original); +} + +TEST(Matrix2dLinalgTest, ExternalBufferViewDoesNotCopy) +{ + std::vector values = {4.0, 1.0, 2.0, 3.0}; + Matrix2dView matrix(values.data(), 2, 2); + Matrix2d rhs(2, 1); + rhs.atloc(0, 0) = 1.0; + rhs.atloc(1, 0) = 2.0; + matrix2d_linalg::solve_inplace(matrix, rhs.view()); + + expect_near(rhs.atloc(0, 0), 0.1); + expect_near(rhs.atloc(1, 0), 0.6); + EXPECT_EQ(matrix.data(), values.data()); +} + +TEST(Matrix2dLinalgTest, HostViewMatmulAndAxpby) +{ + const Matrix2d left = make_real_system(); + const Matrix2d right = make_real_inverse_reference(); + Matrix2d product(2, 2); + matrix2d_linalg::matmul_inplace(product.view(), + left.view(), + right.view()); + expect_host_matrices_near(product, left.matmul(right)); + + Matrix2d combined(2, 2); + matrix2d_linalg::axpby_inplace( + combined.view(), 2.0, left.view(), -0.5, right.view()); + Matrix2d combined_reference(2, 2); + for (int i = 0; i < 2; ++i) + { + for (int j = 0; j < 2; ++j) + { + combined_reference.atloc(i, j) + = 2.0 * left.atloc(i, j) + - 0.5 * right.atloc(i, j); + } + } + expect_host_matrices_near(combined, combined_reference); + + Matrix2d in_place = left; + const Matrix2d in_place_original = in_place; + const Matrix2d& in_place_input = in_place; + matrix2d_linalg::axpby_inplace(in_place.view(), + 2.0, + in_place_input.view(), + -0.5, + right.view()); + Matrix2d in_place_reference(2, 2); + for (int i = 0; i < 2; ++i) + { + for (int j = 0; j < 2; ++j) + { + in_place_reference.atloc(i, j) + = 2.0 * in_place_original.atloc(i, j) + - 0.5 * right.atloc(i, j); + } + } + expect_host_matrices_near(in_place, in_place_reference); + + matrix2d_linalg::scale_inplace(combined.view(), 3.0); + matrix2d_linalg::set_identity_inplace(product.view()); + const Matrix2d generated_identity + = matrix2d_linalg::eye(2); + const Matrix2d> generated_complex_identity + = matrix2d_linalg::eye>(2); + for (int i = 0; i < 2; ++i) + { + for (int j = 0; j < 2; ++j) + { + const double identity_value = i == j ? 1.0 : 0.0; + expect_near(combined.atloc(i, j), + 3.0 * combined_reference.atloc(i, j)); + expect_near(product.atloc(i, j), identity_value); + expect_near(generated_identity.atloc(i, j), identity_value); + expect_near(generated_complex_identity.atloc(i, j).real(), + identity_value); + expect_near(generated_complex_identity.atloc(i, j).imag(), 0.0); + } + } +} + +TEST(Matrix2dLinalgTest, RejectsSingularAndMismatchedMatrices) +{ + Matrix2d singular(2, 2); + singular.atloc(0, 0) = 1.0; + singular.atloc(0, 1) = 2.0; + singular.atloc(1, 0) = 2.0; + singular.atloc(1, 1) = 4.0; + EXPECT_THROW(matrix2d_linalg::inv(singular), std::runtime_error); + EXPECT_THROW(matrix2d_linalg::inv_inplace(singular.view()), + std::runtime_error); + + const Matrix2d matrix = make_real_system(); + const Matrix2d wrong_rhs(1, 1); + EXPECT_THROW(matrix2d_linalg::solve(matrix, wrong_rhs), + std::invalid_argument); +} + +TEST(Matrix2dLinalgTest, RejectsSerialDistributionAgainstHostLayout) +{ + const std::shared_ptr distrib + = make_frozen_distribution(2, 2); + Matrix2d distributed(distrib); + Matrix2d host(2, 2); + + ASSERT_TRUE(distributed.has_distribution()); + ASSERT_FALSE(distributed.is_active()); + EXPECT_THROW( + matrix2d_linalg::axpby_inplace(host.view(), + 1.0, + distributed.view(), + 0.0, + host.view()), + std::invalid_argument); +} + +#ifdef __MPI +TEST(Matrix2dLinalgTest, DistributedRealAndComplexSolve) +{ + const int size = 5; + const int nrhs = 3; + const Matrix2d real_matrix = make_distributed_real_system(size); + const Matrix2d real_solution + = make_distributed_real_solution(size, nrhs); + const Matrix2d> complex_matrix + = make_distributed_complex_system(size); + const Matrix2d> complex_solution + = make_distributed_complex_solution(size, nrhs); + const std::vector> grids = available_process_grids(); + const int nrblks[] = {2, 3}; + for (std::size_t igrid = 0; igrid < grids.size(); ++igrid) + { + for (std::size_t iblk = 0; iblk < 2; ++iblk) + { + check_distributed_solve(real_matrix, + real_solution, + grids[igrid].first, + grids[igrid].second, + nrblks[iblk]); + check_distributed_solve(complex_matrix, + complex_solution, + grids[igrid].first, + grids[igrid].second, + nrblks[iblk]); + } + } +} + +TEST(Matrix2dLinalgTest, DistributedRealAndComplexInverse) +{ + const int size = 5; + const Matrix2d real_matrix = make_distributed_real_system(size); + const Matrix2d> complex_matrix + = make_distributed_complex_system(size); + const std::vector> grids = available_process_grids(); + const int nrblks[] = {2, 3}; + for (std::size_t igrid = 0; igrid < grids.size(); ++igrid) + { + for (std::size_t iblk = 0; iblk < 2; ++iblk) + { + check_distributed_inverse(real_matrix, + grids[igrid].first, + grids[igrid].second, + nrblks[iblk]); + check_distributed_inverse(complex_matrix, + grids[igrid].first, + grids[igrid].second, + nrblks[iblk]); + } + } +} + +TEST(Matrix2dLinalgTest, DistributedIdentityAndAxpby) +{ + const int size = 5; + const int nrblks[] = {2, 3}; + const std::vector> grids = available_process_grids(); + for (std::size_t igrid = 0; igrid < grids.size(); ++igrid) + { + for (std::size_t iblk = 0; iblk < 2; ++iblk) + { + Matrix2d identity(size, + size, + grids[igrid].first, + grids[igrid].second, + nrblks[iblk], + MPI_COMM_WORLD); + matrix2d_linalg::set_identity_inplace(identity.view()); + Matrix2d identity_expected(size, size); + matrix2d_linalg::set_identity_inplace(identity_expected.view()); + expect_host_matrices_near(identity.gather(), identity_expected); + + const Matrix2d host_left = make_distributed_real_system(size); + Matrix2d left(identity.distribution()); + left.scatter(host_left); + const Matrix2d combined + = matrix2d_linalg::axpby(2.0, + left, + 0.5, + identity); + EXPECT_EQ(combined.distribution(), left.distribution()); + expect_distributed_context(combined, left); + + Matrix2d combined_output(1, 1); + matrix2d_linalg::axpby(2.0, + left, + 0.5, + identity, + combined_output); + EXPECT_EQ(combined_output.distribution(), left.distribution()); + expect_distributed_context(combined_output, left); + + const Matrix2d scaled + = matrix2d_linalg::scale(left, 3.0); + EXPECT_EQ(scaled.distribution(), left.distribution()); + expect_distributed_context(scaled, left); + + Matrix2d combined_expected(size, size); + Matrix2d scaled_expected(size, size); + for (int i = 0; i < size; ++i) + { + for (int j = 0; j < size; ++j) + { + combined_expected.atloc(i, j) + = 2.0 * host_left.atloc(i, j) + + 0.5 * identity_expected.atloc(i, j); + scaled_expected.atloc(i, j) + = 3.0 * host_left.atloc(i, j); + } + } + expect_host_matrices_near(combined.gather(), combined_expected); + expect_host_matrices_near(combined_output.gather(), + combined_expected); + expect_host_matrices_near(scaled.gather(), scaled_expected); + expect_host_matrices_near(left.gather(), host_left); + expect_host_matrices_near(identity.gather(), identity_expected); + } + } +} +#endif + +int main(int argc, char** argv) +{ +#ifdef __MPI + MPI_Init(&argc, &argv); +#endif + testing::InitGoogleTest(&argc, argv); + const int result = RUN_ALL_TESTS(); +#ifdef __MPI + MPI_Finalize(); +#endif + return result; +}