From 84b127fa58c76a19f42696b2b5024dc17f51589f Mon Sep 17 00:00:00 2001 From: kirk0830 Date: Fri, 13 Nov 2026 15:55:50 +0800 Subject: [PATCH 01/15] feat(base): add self-contained Matrix2d storage and math --- source/Makefile.Objects | 6 + source/source_base/CMakeLists.txt | 7 + source/source_base/matrix2d.cpp | 647 ++++++++ source/source_base/matrix2d.h | 359 +++++ source/source_base/matrix2d_collective.cpp | 515 ++++++ source/source_base/matrix2d_collective.h | 24 + source/source_base/matrix2d_lapack.cpp | 269 ++++ source/source_base/matrix2d_lapack.h | 23 + source/source_base/matrix2d_linalg.cpp | 366 +++++ source/source_base/matrix2d_linalg.h | 44 + source/source_base/matrix2d_reduction.cpp | 435 +++++ source/source_base/matrix2d_reduction.h | 27 + source/source_base/matrix2d_scalapack.cpp | 393 +++++ source/source_base/matrix2d_scalapack.h | 40 + source/source_base/matrix2d_view.h | 153 ++ .../module_external/scalapack_connector.h | 26 + source/source_base/ndarray.h | 5 +- source/source_base/parallel_blkcyc.cpp | 73 + source/source_base/parallel_blkcyc.h | 39 + source/source_base/parallel_common.cpp | 94 ++ source/source_base/parallel_common.h | 101 ++ source/source_base/unittests/CMakeLists.txt | 53 + .../source_base/unittests/test_matrix2d.cpp | 1399 +++++++++++++++++ .../unittests/test_matrix2d_linalg.cpp | 472 ++++++ 24 files changed, 5569 insertions(+), 1 deletion(-) create mode 100644 source/source_base/matrix2d.cpp create mode 100644 source/source_base/matrix2d.h create mode 100644 source/source_base/matrix2d_collective.cpp create mode 100644 source/source_base/matrix2d_collective.h create mode 100644 source/source_base/matrix2d_lapack.cpp create mode 100644 source/source_base/matrix2d_lapack.h create mode 100644 source/source_base/matrix2d_linalg.cpp create mode 100644 source/source_base/matrix2d_linalg.h create mode 100644 source/source_base/matrix2d_reduction.cpp create mode 100644 source/source_base/matrix2d_reduction.h create mode 100644 source/source_base/matrix2d_scalapack.cpp create mode 100644 source/source_base/matrix2d_scalapack.h create mode 100644 source/source_base/matrix2d_view.h create mode 100644 source/source_base/unittests/CMakeLists.txt create mode 100644 source/source_base/unittests/test_matrix2d.cpp create mode 100644 source/source_base/unittests/test_matrix2d_linalg.cpp diff --git a/source/Makefile.Objects b/source/Makefile.Objects index 72d816334a1..b3d08b3d753 100644 --- a/source/Makefile.Objects +++ b/source/Makefile.Objects @@ -176,6 +176,12 @@ 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_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 ffaf4dd0d38..cf43d152943 100644 --- a/source/source_base/CMakeLists.txt +++ b/source/source_base/CMakeLists.txt @@ -32,6 +32,12 @@ add_library( math_chebyshev.cpp mathzone_add1.cpp matrix.cpp + matrix2d.cpp + matrix2d_collective.cpp + matrix2d_lapack.cpp + matrix2d_linalg.cpp + matrix2d_reduction.cpp + matrix2d_scalapack.cpp matrix3.cpp memory_recorder.cpp mymath.cpp @@ -136,4 +142,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..20f682a1e81 --- /dev/null +++ b/source/source_base/matrix2d.cpp @@ -0,0 +1,647 @@ +#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 +{ +template +T conjugate_element(const T& value) +{ + return value; +} + +template <> +std::complex conjugate_element>( + const std::complex& value) +{ + return std::conj(value); +} + +template <> +std::complex conjugate_element>( + const std::complex& value) +{ + return std::conj(value); +} + +template +double real_element(const T& value) +{ + return static_cast(value); +} + +template <> +double real_element>(const std::complex& value) +{ + return static_cast(value.real()); +} + +template <> +double real_element>(const std::complex& value) +{ + return value.real(); +} + +template +double imaginary_element(const T&) +{ + return 0.0; +} + +template <> +double imaginary_element>(const std::complex& value) +{ + return static_cast(value.imag()); +} + +template <> +double imaginary_element>(const std::complex& value) +{ + return value.imag(); +} + +template +Matrix2d extract_real_or_imaginary(const Matrix2d& matrix, + const bool extract_real) +{ + Matrix2d result = matrix.is_distributed() + ? Matrix2d(matrix.distribution()) + : Matrix2d(matrix.nrglb(), + matrix.ncglb()); + + const int nrloc = matrix.nrloc(); + const int ncloc = matrix.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) + { + const T& value = matrix.at_local(i, j); + result.at_local(i, j) + = extract_real ? real_element(value) : imaginary_element(value); + } + } + return result; +} + +template +void write_real_or_imaginary(const Matrix2d& matrix, + Matrix2d& output, + const bool extract_real) +{ + const int nrloc = matrix.nrloc(); + const int ncloc = matrix.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) + { + const T& value = matrix.at_local(i, j); + output.at_local(i, j) + = extract_real ? real_element(value) : imaginary_element(value); + } + } +} + +} // 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 +Matrix2dView NDArray::view() +{ +#ifdef __MPI + if (dist_ != nullptr) + { + return Matrix2dView(data(), dist_); + } +#endif + return Matrix2dView(data(), nrglb(), ncglb()); +} + +template +Matrix2dView NDArray::view() const +{ +#ifdef __MPI + if (dist_ != nullptr) + { + return Matrix2dView(data(), dist_); + } +#endif + return Matrix2dView(data(), nrglb(), ncglb()); +} + +template +void NDArray::fill(const T& value) +{ + if (dist_ == 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) + { + at_local(irloc, icloc) = value; + } + } +} + +template +void NDArray::scale(const T& value) +{ + if (dist_ == 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) + { + at_local(irloc, icloc) *= value; + } + } +} + +template +NDArray& NDArray::operator+=(const NDArray& other) +{ + validate_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) + { + at_local(irloc, icloc) += other.at_local(irloc, icloc); + } + } + return *this; +} + +template +NDArray& NDArray::operator-=(const NDArray& other) +{ + validate_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) + { + at_local(irloc, icloc) -= other.at_local(irloc, icloc); + } + } + return *this; +} + +template +NDArray& NDArray::operator*=(const NDArray& other) +{ + validate_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) + { + at_local(irloc, icloc) *= other.at_local(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) + { + at_local(i, j) = conjugate_element(at_local(i, j)); + } + } + return *this; +} + +template +NDArray NDArray::transpose() const +{ + if (dist_ == nullptr || dist_->is_serial()) + { + // 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.at_local(j, i) = at_local(i, j); + } + } + return result; + } + +#ifdef __MPI + const int result_rows = ncglb(); + const int result_cols = nrglb(); + const int nb = dist_->nb(); + const int source_context = dist_->ictxt(); + const std::shared_ptr result_dist + = make_frozen_distribution(result_rows, result_cols, nb, source_context); + Matrix2d result(result_dist); + 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 (dist_ == nullptr || dist_->is_serial()) + { + 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.at_local(j, i) = conjugate_element(at_local(i, j)); + } + } + return result; + } + +#ifdef __MPI + const int result_rows = ncglb(); + const int result_cols = nrglb(); + const int nb = dist_->nb(); + const int source_context = dist_->ictxt(); + const std::shared_ptr result_dist + = make_frozen_distribution(result_rows, result_cols, nb, source_context); + Matrix2d result(result_dist); + 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 left_rows = nrglb(); + const int shared_dimension = ncglb(); + const int other_shared_dimension = other.nrglb(); + const int result_cols = other.ncglb(); + if (shared_dimension != other_shared_dimension) + { + throw std::invalid_argument("matrix inner dimensions are incompatible"); + } + + const bool this_is_serial + = dist_ == nullptr || dist_->is_serial(); + const bool other_is_serial + = other.distribution() == nullptr || other.distribution()->is_serial(); + if (this_is_serial != other_is_serial) + { + throw std::invalid_argument("host and distributed matrices are incompatible"); + } + + if (this_is_serial) + { + // Serial degenerate path: both sides are host or serial frozen + // distributions, so matmul degrades to the host triple loop. + Matrix2d result(left_rows, result_cols); +#ifdef _OPENMP +#pragma omp parallel for collapse(2) schedule(static) +#endif + for (int i = 0; i < left_rows; ++i) + { + for (int j = 0; j < result_cols; ++j) + { + T value = T(); + for (int k = 0; k < shared_dimension; ++k) + { + value += at_local(i, k) * other.at_local(k, j); + } + result.at_local(i, j) = value; + } + } + return result; + } + +#ifdef __MPI + const std::shared_ptr other_dist + = other.distribution(); + if (dist_->nb() != other_dist->nb()) + { + throw std::invalid_argument("matrix block sizes are incompatible"); + } + if (dist_->nrproc() != other_dist->nrproc() + || dist_->ncproc() != other_dist->ncproc()) + { + throw std::invalid_argument("matrix process grids are incompatible"); + } + if (dist_->ictxt() != other_dist->ictxt()) + { + throw std::invalid_argument("matrix BLACS contexts are incompatible"); + } + + const int nb = dist_->nb(); + const int source_context = dist_->ictxt(); + const std::shared_ptr result_dist + = make_frozen_distribution(left_rows, result_cols, nb, source_context); + Matrix2d result(result_dist); + 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 +{ + return extract_real_or_imaginary(*this, true); +} + +template +NDArray NDArray::imag() const +{ + return extract_real_or_imaginary(*this, false); +} + +template +void NDArray::real(NDArray& output) const +{ + validate_compatible_layout(output); + write_real_or_imaginary(*this, output, true); +} + +template +void NDArray::imag(NDArray& output) const +{ + validate_compatible_layout(output); + write_real_or_imaginary(*this, output, false); +} + +template +T NDArray::sum() const +{ + return matrix2d_impl::sum(*this); +} + +template +double NDArray::sum_squares() const +{ + return matrix2d_impl::sum_squares(*this); +} + +template +T NDArray::dot(const NDArray& other) const +{ + validate_compatible_layout(other); + return matrix2d_impl::dot(*this, other); +} + +template +double NDArray::norm2() const +{ + return matrix2d_impl::norm2(*this); +} + +template +double 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 (dist_ == nullptr) + { + return *this; + } + if (dist_->is_serial()) + { + Matrix2d result(nrglb(), ncglb()); + for (int irloc = 0; irloc < nrloc(); ++irloc) + { + const int irglb = dist_->irglb(irloc); + for (int icloc = 0; icloc < ncloc(); ++icloc) + { + const int icglb = dist_->icglb(icloc); + result.at_local(irglb, icglb) = at_local(irloc, icloc); + } + } + return result; + } +#ifdef __MPI + const MPI_Comm comm = dist_->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 (dist_ == nullptr) + { + if (iproot == 0) + { + return *this; + } + return NDArray(EmptyMatrixTag()); + } + if (dist_->is_serial()) + { + if (iproot != 0) + { + return NDArray(EmptyMatrixTag()); + } + Matrix2d result(nrglb(), ncglb()); + for (int irloc = 0; irloc < nrloc(); ++irloc) + { + const int irglb = dist_->irglb(irloc); + for (int icloc = 0; icloc < ncloc(); ++icloc) + { + const int icglb = dist_->icglb(icloc); + result.at_local(irglb, icglb) = at_local(irloc, icloc); + } + } + return result; + } +#ifdef __MPI + const MPI_Comm comm = dist_->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 (dist_ == nullptr) + { + if (matglb.is_distributed()) + { + 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 (dist_->is_serial()) + { + if (matglb.is_distributed()) + { + 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) + { + at_local(irloc, icloc) + = matglb.at_local(dist_->irglb(irloc), + dist_->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..df878029580 --- /dev/null +++ b/source/source_base/matrix2d.h @@ -0,0 +1,359 @@ +#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; + +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) + { + const std::shared_ptr dist + = make_frozen_distribution(nrglb, ncglb, 1, comm); + initialize_distributed_storage(dist); + } + + NDArray(const int nrglb, + const int ncglb, + const int nb, + const MPI_Comm comm) + { + const std::shared_ptr dist + = make_frozen_distribution(nrglb, ncglb, nb, comm); + initialize_distributed_storage(dist); + } + + NDArray(const int nrglb, + const int ncglb, + const int nrproc, + const int ncproc, + const int nb, + const MPI_Comm comm) + { + const std::shared_ptr dist + = make_frozen_distribution(nrglb, ncglb, nrproc, ncproc, nb, comm); + initialize_distributed_storage(dist); + } +#endif + + explicit NDArray(std::shared_ptr dist) + : dist_(std::move(dist)) + { + if (dist_ == 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; + + NDArray real() const; + NDArray imag() const; + void real(NDArray& output) const; + void imag(NDArray& output) const; + + T sum() const; + double sum_squares() const; + T dot(const NDArray& other) const; + double norm2() const; + double max_abs() const; + std::vector diagonal() const; + + NDArray gather() const; + NDArray gather_on_root(const int iproot) const; + void scatter(const NDArray& matglb); + + T& at_global(const int i, const int j) + { + assert(i >= 0); + assert(i < nrglb()); + assert(j >= 0); + assert(j < ncglb()); + + if (dist_ == nullptr) + { + return at_local(i, j); + } + + const std::size_t iglb = static_cast(i); + const std::size_t jglb = static_cast(j); + const bool owns = dist_->in_this_processor(iglb, jglb); + assert(owns); + + const int irloc = dist_->irloc(i); + const int icloc = dist_->icloc(j); + assert(irloc != -1); + assert(icloc != -1); + return at_local(irloc, icloc); + } + + const T& at_global(const int i, const int j) const + { + assert(i >= 0); + assert(i < nrglb()); + assert(j >= 0); + assert(j < ncglb()); + + if (dist_ == nullptr) + { + return at_local(i, j); + } + + const std::size_t iglb = static_cast(i); + const std::size_t jglb = static_cast(j); + const bool owns = dist_->in_this_processor(iglb, jglb); + assert(owns); + + const int irloc = dist_->irloc(i); + const int icloc = dist_->icloc(j); + assert(irloc != -1); + assert(icloc != -1); + return at_local(irloc, icloc); + } + + T& at_local(const int i, const int j) + { + assert(i >= 0); + assert(i < nrloc()); + assert(j >= 0); + assert(j < ncloc()); + + std::size_t ioff = 0; + if (dist_ == nullptr) + { + ioff = static_cast(i) * static_cast(ncloc_) + + static_cast(j); + } + else + { + const int lld = dist_->lld(); + ioff = static_cast(j) * static_cast(lld) + + static_cast(i); + } + assert(ioff < storage_.size()); + return storage_[ioff]; + } + + const T& at_local(const int i, const int j) const + { + assert(i >= 0); + assert(i < nrloc()); + assert(j >= 0); + assert(j < ncloc()); + + std::size_t ioff = 0; + if (dist_ == nullptr) + { + ioff = static_cast(i) * static_cast(ncloc_) + + static_cast(j); + } + else + { + const int lld = dist_->lld(); + ioff = static_cast(j) * static_cast(lld) + + static_cast(i); + } + assert(ioff < storage_.size()); + return storage_[ioff]; + } + + bool owns_global_index(const int i, const int j) const + { + assert(i >= 0); + assert(i < nrglb()); + assert(j >= 0); + assert(j < ncglb()); + if (dist_ == nullptr) + { + return true; + } + const std::size_t iglb = static_cast(i); + const std::size_t jglb = static_cast(j); + return dist_->in_this_processor(iglb, jglb); + } + + T* data() { return storage_.data(); } + const T* data() const { return storage_.data(); } + + int nrglb() const { return dist_ == nullptr ? nrloc_ : dist_->nrglb(); } + int ncglb() const { return dist_ == nullptr ? ncloc_ : dist_->ncglb(); } + int nrloc() const { return dist_ == nullptr ? nrloc_ : dist_->nrloc(); } + int ncloc() const { return dist_ == nullptr ? ncloc_ : dist_->ncloc(); } + std::size_t size() const + { + return dist_ == nullptr + ? static_cast(nrloc_) * static_cast(ncloc_) + : dist_->size(); + } + int nrproc() const { return dist_ == nullptr ? 1 : dist_->nrproc(); } + int ncproc() const { return dist_ == nullptr ? 1 : dist_->ncproc(); } + int irproc() const { return dist_ == nullptr ? 0 : dist_->irproc(); } + int icproc() const { return dist_ == nullptr ? 0 : dist_->icproc(); } + int lld() const { return dist_ == nullptr ? ncloc_ : dist_->lld(); } + + const int* desc() const + { +#ifdef __MPI + return dist_ != nullptr ? dist_->desc() : nullptr; +#else + return nullptr; +#endif + } + + int ictxt() const + { +#ifdef __MPI + return dist_ != nullptr ? dist_->ictxt() : -1; +#else + return -1; +#endif + } + + const std::shared_ptr& distribution() const { return dist_; } + bool is_distributed() const { return dist_ != nullptr; } + + Matrix2dView view(); + Matrix2dView view() const; + + private: + struct EmptyMatrixTag + { + }; + + explicit NDArray(EmptyMatrixTag) + { + } + + template + void validate_compatible_layout(const NDArray& other) const + { + if (nrglb() != other.nrglb() + || ncglb() != other.ncglb()) + { + throw std::invalid_argument("matrix global shapes are incompatible"); + } + + const bool this_is_distributed = dist_ != nullptr; + const bool other_is_distributed = other.distribution() != nullptr; + if (this_is_distributed != other_is_distributed) + { + throw std::invalid_argument("host and distributed matrices are incompatible"); + } + + if (!this_is_distributed) + { + return; + } + + if (dist_->nb() != other.distribution()->nb()) + { + throw std::invalid_argument("matrix block sizes are incompatible"); + } + if (dist_->nrproc() != other.distribution()->nrproc() + || dist_->ncproc() != other.distribution()->ncproc()) + { + throw std::invalid_argument("matrix process grids are incompatible"); + } + if (dist_ != other.distribution()) + { + throw std::invalid_argument("matrix distribution handles are incompatible"); + } + } + + void initialize_distributed_storage( + const std::shared_ptr& dist) + { + if (dist == nullptr) + { + throw std::invalid_argument("distribution must not be null"); + } + dist_ = dist; + initialize_distributed_storage(); + } + + void initialize_distributed_storage() + { + nrloc_ = dist_->nrloc(); + ncloc_ = dist_->ncloc(); + assert(nrloc_ >= 0); + assert(ncloc_ >= 0); + + const int lld = std::max(nrloc_, 1); + const int ncmax = std::max(ncloc_, lld); + const std::size_t ncm = static_cast(lld) * static_cast(ncloc_); + const std::size_t nrm = static_cast(nrloc_) * static_cast(ncmax); + const std::size_t n = std::max(ncm, nrm); + storage_.resize(n); + } + + int nrloc_ = 0; + int ncloc_ = 0; + std::vector storage_; + std::shared_ptr dist_; +}; + +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..38e03dd5feb --- /dev/null +++ b/source/source_base/matrix2d_collective.cpp @@ -0,0 +1,515 @@ +#include "source_base/matrix2d_collective.h" + +#ifdef __MPI +#include "source_base/parallel_common.h" + +#include +#include +#include +#include + +namespace +{ +constexpr int LOCAL_METADATA_SIZE = 6; + +int checked_mpi_count(const std::size_t count) +{ + if (count > static_cast(std::numeric_limits::max())) + { + throw std::invalid_argument("Matrix2d collective payload exceeds MPI count range"); + } + return static_cast(count); +} + +std::vector make_byte_displacements(const std::vector& counts) +{ + std::vector displacements(counts.size(), 0); + int displacement = 0; + for (std::size_t ip = 0; ip < counts.size(); ++ip) + { + displacements[ip] = displacement; + if (counts[ip] > std::numeric_limits::max() - displacement) + { + throw std::invalid_argument("Matrix2d collective payload size overflow"); + } + displacement += counts[ip]; + } + return displacements; +} + +std::vector allgather_byte_counts(const int local_count, const MPI_Comm comm) +{ + const int nproc = Parallel_Common::comm_size(comm); + std::vector receive_counts(nproc, checked_mpi_count(sizeof(int))); + const std::vector receive_displacements + = make_byte_displacements(receive_counts); + std::vector counts(nproc, 0); + + Parallel_Common::allgatherv_bytes(&local_count, + checked_mpi_count(sizeof(local_count)), + counts.data(), + receive_counts.data(), + receive_displacements.data(), + comm); + return counts; +} + +template +std::vector make_local_metadata(const Matrix2d& matrix) +{ + const std::shared_ptr dist + = matrix.distribution(); + std::vector metadata; + metadata.reserve(LOCAL_METADATA_SIZE + matrix.nrloc() + + matrix.ncloc()); + metadata.push_back(matrix.nrloc()); + metadata.push_back(matrix.ncloc()); + metadata.push_back(matrix.nrglb()); + metadata.push_back(matrix.ncglb()); + metadata.push_back(dist->irproc()); + metadata.push_back(dist->icproc()); + for (int irloc = 0; irloc < matrix.nrloc(); ++irloc) + { + metadata.push_back(dist->irglb(irloc)); + } + for (int icloc = 0; icloc < matrix.ncloc(); ++icloc) + { + metadata.push_back(dist->icglb(icloc)); + } + return metadata; +} + +template +std::vector make_local_payload(const Matrix2d& matrix) +{ + const std::vector metadata = make_local_metadata(matrix); + const std::size_t metadata_bytes = metadata.size() * sizeof(int); + const std::size_t data_elements = static_cast(matrix.nrloc()) + * static_cast(matrix.ncloc()); + const std::size_t data_bytes = data_elements * sizeof(T); + std::vector payload(metadata_bytes + data_bytes); + + std::memcpy(payload.data(), metadata.data(), metadata_bytes); + for (int irloc = 0; irloc < matrix.nrloc(); ++irloc) + { + for (int icloc = 0; icloc < matrix.ncloc(); ++icloc) + { + const std::size_t irloc_index = static_cast(irloc); + const std::size_t icloc_index = static_cast(icloc); + const std::size_t element_index + = irloc_index * static_cast(matrix.ncloc()) + + icloc_index; + const T& value = matrix.at_local(irloc, icloc); + std::memcpy(payload.data() + metadata_bytes + element_index * sizeof(T), + &value, + sizeof(T)); + } + } + return payload; +} + +struct LocalPayloadView +{ + 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; +}; + +template +LocalPayloadView view_local_payload(const std::vector& payload) +{ + if (payload.size() < LOCAL_METADATA_SIZE * sizeof(int)) + { + throw std::invalid_argument("Matrix2d collective payload is truncated"); + } + + int header[LOCAL_METADATA_SIZE] = {}; + std::memcpy(header, payload.data(), sizeof(header)); + LocalPayloadView 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 payload has invalid dimensions"); + } + + const std::size_t metadata_count + = static_cast(LOCAL_METADATA_SIZE) + view.nrloc + view.ncloc; + const std::size_t metadata_bytes = metadata_count * sizeof(int); + const std::size_t data_elements + = static_cast(view.nrloc) * static_cast(view.ncloc); + const std::size_t expected_bytes = metadata_bytes + data_elements * sizeof(T); + if (payload.size() != expected_bytes) + { + throw std::invalid_argument("Matrix2d collective payload has an invalid size"); + } + + std::vector metadata(metadata_count); + std::memcpy(metadata.data(), payload.data(), metadata_bytes); + 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 = payload.data() + metadata_bytes; + return view; +} + +template +Matrix2d rebuild_global_matrix( + const std::vector>& payloads) +{ + std::vector views; + views.reserve(payloads.size()); + int nrglb = 0; + int ncglb = 0; + for (std::size_t ip = 0; ip < payloads.size(); ++ip) + { + views.push_back(view_local_payload(payloads[ip])); + const LocalPayloadView& 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 LocalPayloadView& 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 element_index + = static_cast(irloc) + * static_cast(view.ncloc) + + static_cast(icloc); + T value; + std::memcpy(&value, view.data + element_index * sizeof(T), sizeof(T)); + result.at_local(irglb, icglb) = value; + } + } + } + return result; +} + +template +std::vector> allgather_payloads( + const Matrix2d& matrix, + const MPI_Comm comm) +{ + const std::vector local_payload = make_local_payload(matrix); + const int local_count = checked_mpi_count(local_payload.size()); + std::vector payload_counts = allgather_byte_counts(local_count, comm); + const std::vector payload_displacements + = make_byte_displacements(payload_counts); + const int total_bytes = payload_displacements.back() + payload_counts.back(); + std::vector received(total_bytes); + + Parallel_Common::allgatherv_bytes(local_payload.data(), + local_count, + received.data(), + payload_counts.data(), + payload_displacements.data(), + comm); + + std::vector> payloads(payload_counts.size()); + for (std::size_t ip = 0; ip < payload_counts.size(); ++ip) + { + const std::size_t begin = static_cast(payload_displacements[ip]); + const std::size_t end + = begin + static_cast(payload_counts[ip]); + payloads[ip].assign(received.begin() + begin, received.begin() + end); + } + return payloads; +} +} // namespace + +namespace matrix2d_impl +{ +template +Matrix2d allgather(const Matrix2d& matrix, const MPI_Comm comm) +{ + const std::vector> payloads + = allgather_payloads(matrix, comm); + return rebuild_global_matrix(payloads); +} + +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 local_payload = make_local_payload(matrix); + const int local_count = checked_mpi_count(local_payload.size()); + std::vector payload_counts = allgather_byte_counts(local_count, comm); + const std::vector payload_displacements + = make_byte_displacements(payload_counts); + const int total_bytes = payload_displacements.back() + payload_counts.back(); + std::vector received; + if (ip == iproot) + { + received.resize(total_bytes); + } + + unsigned char* const receive_buffer = ip == iproot ? received.data() : nullptr; + Parallel_Common::gatherv_bytes(local_payload.data(), + local_count, + receive_buffer, + payload_counts.data(), + payload_displacements.data(), + iproot, + comm); + if (ip != iproot) + { + return std::unique_ptr>(); + } + + std::vector> payloads(payload_counts.size()); + for (std::size_t ipsrc = 0; ipsrc < payload_counts.size(); ++ipsrc) + { + const std::size_t begin + = static_cast(payload_displacements[ipsrc]); + const std::size_t end + = begin + static_cast(payload_counts[ipsrc]); + payloads[ipsrc].assign(received.begin() + begin, received.begin() + end); + } + return std::unique_ptr>( + new Matrix2d(rebuild_global_matrix(payloads))); +} + +template +void scatter_from_host(const Matrix2d& matglb, Matrix2d& matloc) +{ + if (matglb.is_distributed()) + { + throw std::invalid_argument("scatter requires a host global matrix"); + } + + const std::shared_ptr dist + = matloc.distribution(); + const MPI_Comm comm = dist->comm(); + if (comm == MPI_COMM_NULL) + { + throw std::invalid_argument("scatter requires a valid MPI comm"); + } + + const std::vector local_meta = make_local_metadata(matloc); + const int local_metadata_bytes + = checked_mpi_count(local_meta.size() * sizeof(int)); + std::vector metadata_counts + = allgather_byte_counts(local_metadata_bytes, comm); + const std::vector metadata_displacements + = make_byte_displacements(metadata_counts); + const int metadata_total_bytes + = metadata_displacements.back() + metadata_counts.back(); + if (metadata_total_bytes % checked_mpi_count(sizeof(int)) != 0) + { + throw std::invalid_argument("Matrix2d scatter metadata has an invalid byte count"); + } + std::vector all_metadata(metadata_total_bytes / sizeof(int)); + + Parallel_Common::allgatherv_bytes(local_meta.data(), + local_metadata_bytes, + all_metadata.data(), + metadata_counts.data(), + metadata_displacements.data(), + comm); + + const int nproc = Parallel_Common::comm_size(comm); + const int ip = Parallel_Common::comm_rank(comm); + std::vector send_counts(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"); + } + LocalPayloadView 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 axes_count + = static_cast(view.nrloc + view.ncloc); + if (metadata_offset + axes_count > 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 += axes_count; + + 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 local_elements + = static_cast(view.nrloc) + * static_cast(view.ncloc); + send_counts[ipsrc] = checked_mpi_count(local_elements * sizeof(T)); + 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 send_displacements = make_byte_displacements(send_counts); + std::vector send_buffer; + if (ip == 0) + { + const int total_bytes = send_displacements.back() + send_counts.back(); + send_buffer.resize(total_bytes); + for (int ipdst = 0; ipdst < nproc; ++ipdst) + { + const LocalPayloadView& view = views[ipdst]; + 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 element_index + = static_cast(irloc) + * static_cast(view.ncloc) + + static_cast(icloc); + const T& value = matglb.at_local(irglb, icglb); + std::memcpy(send_buffer.data() + + send_displacements[ipdst] + + element_index * sizeof(T), + &value, + sizeof(T)); + } + } + } + } + + const std::size_t receive_elements + = static_cast(matloc.nrloc()) + * static_cast(matloc.ncloc()); + std::vector receive_buffer(receive_elements * sizeof(T)); + const unsigned char* receive_source = ip == 0 ? send_buffer.data() : nullptr; + Parallel_Common::scatterv_bytes(receive_source, + send_counts.data(), + send_displacements.data(), + receive_buffer.data(), + checked_mpi_count(receive_buffer.size()), + 0, + comm); + + for (int irloc = 0; irloc < matloc.nrloc(); ++irloc) + { + for (int icloc = 0; icloc < matloc.ncloc(); ++icloc) + { + const std::size_t element_index + = static_cast(irloc) + * static_cast(matloc.ncloc()) + + static_cast(icloc); + T value; + std::memcpy(&value, + receive_buffer.data() + element_index * sizeof(T), + sizeof(T)); + matloc.at_local(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..bcd5f9bd592 --- /dev/null +++ b/source/source_base/matrix2d_collective.h @@ -0,0 +1,24 @@ +#ifndef ABACUS_SOURCE_SOURCE_BASE_MATRIX2D_COLLECTIVE_H +#define ABACUS_SOURCE_SOURCE_BASE_MATRIX2D_COLLECTIVE_H + +#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..7820bc34a06 --- /dev/null +++ b/source/source_base/matrix2d_lapack.cpp @@ -0,0 +1,269 @@ +#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 + +namespace +{ +void check_host_layout(const Matrix2dView& matrix) +{ + if (matrix.is_distributed()) + { + throw std::invalid_argument("LAPACK requires a host matrix view"); + } +} + +void check_host_layout(const Matrix2dView>& matrix) +{ + if (matrix.is_distributed()) + { + throw std::invalid_argument("LAPACK requires a host matrix view"); + } +} + +void check_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 check_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) +{ + check_host_layout(matrix); + const int n = matrix.nrglb(); + check_inverse_dimensions(n, matrix.ncglb()); + + const int lda = matrix.lld(); + std::vector ipiv(static_cast(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 lwork = -1; + std::vector work(1); + container::lapackConnector::getri( + /* n= */ n, + /* a= */ matrix.data(), + /* lda= */ lda, + /* ipiv= */ ipiv.data(), + /* work= */ work.data(), + /* lwork= */ lwork, + /* info= */ info); + throw_lapack_error("LAPACK getri workspace query", info); + lwork = static_cast(work[0]); + work.resize(static_cast(lwork)); + container::lapackConnector::getri( + /* n= */ n, + /* a= */ matrix.data(), + /* lda= */ lda, + /* ipiv= */ ipiv.data(), + /* work= */ work.data(), + /* lwork= */ lwork, + /* info= */ info); + throw_lapack_error("LAPACK getri", info); +} + +void inv(Matrix2dView> matrix) +{ + check_host_layout(matrix); + const int n = matrix.nrglb(); + check_inverse_dimensions(n, matrix.ncglb()); + + const int lda = matrix.lld(); + std::vector ipiv(static_cast(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 lwork = -1; + std::vector> work(1); + container::lapackConnector::getri( + /* n= */ n, + /* a= */ matrix.data(), + /* lda= */ lda, + /* ipiv= */ ipiv.data(), + /* work= */ work.data(), + /* lwork= */ lwork, + /* info= */ info); + throw_lapack_error("LAPACK getri workspace query", info); + lwork = static_cast(work[0].real()); + work.resize(static_cast(lwork)); + container::lapackConnector::getri( + /* n= */ n, + /* a= */ matrix.data(), + /* lda= */ lda, + /* ipiv= */ ipiv.data(), + /* work= */ work.data(), + /* lwork= */ lwork, + /* info= */ info); + throw_lapack_error("LAPACK getri", info); +} + +void solve(Matrix2dView matrix, + Matrix2dView rhs) +{ + check_host_layout(matrix); + check_host_layout(rhs); + const int n = matrix.nrglb(); + const int nrhs = rhs.ncglb(); + check_solve_dimensions(n, matrix.ncglb(), rhs.nrglb()); + + const int lda = matrix.lld(); + std::vector ipiv(static_cast(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); + + std::vector rhs_column_major( + static_cast(n) * static_cast(nrhs)); + for (int i = 0; i < n; ++i) + { + for (int j = 0; j < nrhs; ++j) + { + rhs_column_major[static_cast(i) + + static_cast(j) + * static_cast(n)] + = rhs.at_local(i, j); + } + } + + const char trans = 'T'; + container::lapackConnector::getrs( + /* trans= */ trans, + /* n= */ n, + /* nrhs= */ nrhs, + /* a= */ matrix.data(), + /* lda= */ lda, + /* ipiv= */ ipiv.data(), + /* b= */ rhs_column_major.data(), + /* ldb= */ n, + /* info= */ info); + throw_lapack_error("LAPACK getrs", info); + + for (int i = 0; i < n; ++i) + { + for (int j = 0; j < nrhs; ++j) + { + rhs.at_local(i, j) + = rhs_column_major[static_cast(i) + + static_cast(j) + * static_cast(n)]; + } + } +} + +void solve(Matrix2dView> matrix, + Matrix2dView> rhs) +{ + check_host_layout(matrix); + check_host_layout(rhs); + const int n = matrix.nrglb(); + const int nrhs = rhs.ncglb(); + check_solve_dimensions(n, matrix.ncglb(), rhs.nrglb()); + + const int lda = matrix.lld(); + std::vector ipiv(static_cast(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); + + std::vector> rhs_column_major( + static_cast(n) * static_cast(nrhs)); + for (int i = 0; i < n; ++i) + { + for (int j = 0; j < nrhs; ++j) + { + rhs_column_major[static_cast(i) + + static_cast(j) + * static_cast(n)] + = rhs.at_local(i, j); + } + } + + const char trans = 'T'; + container::lapackConnector::getrs( + /* trans= */ trans, + /* n= */ n, + /* nrhs= */ nrhs, + /* a= */ matrix.data(), + /* lda= */ lda, + /* ipiv= */ ipiv.data(), + /* b= */ rhs_column_major.data(), + /* ldb= */ n, + /* info= */ info); + throw_lapack_error("LAPACK getrs", info); + + for (int i = 0; i < n; ++i) + { + for (int j = 0; j < nrhs; ++j) + { + rhs.at_local(i, j) + = rhs_column_major[static_cast(i) + + static_cast(j) + * static_cast(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..3a46eb2831a --- /dev/null +++ b/source/source_base/matrix2d_lapack.h @@ -0,0 +1,23 @@ +#ifndef ABACUS_SOURCE_SOURCE_BASE_MATRIX2D_LAPACK_H +#define ABACUS_SOURCE_SOURCE_BASE_MATRIX2D_LAPACK_H + +#include + +template +class Matrix2dView; + +namespace matrix2d_impl +{ +namespace lapack +{ +void inv(Matrix2dView matrix); +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..080ef3f4e10 --- /dev/null +++ b/source/source_base/matrix2d_linalg.cpp @@ -0,0 +1,366 @@ +#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 + +namespace +{ +template +void check_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 check_compatible_layout(const Matrix2dView& left, + const Matrix2dView& right) +{ + if (left.is_distributed() != right.is_distributed()) + { + throw std::invalid_argument( + "matrix operations require matching host or distributed layouts"); + } + if (!left.is_distributed()) + { + return; + } + 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 distributed layouts"); + } +} + +template +void check_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"); + } + check_compatible_layout(result, left); + check_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.at_local(i, k) * right.at_local(k, j); + } + result.at_local(i, j) = value; + } + } +} + +template +void linear_combination_impl(Matrix2dView result, + const T alpha, + Matrix2dView left, + const T beta, + Matrix2dView right) +{ + check_same_shape(result, left); + check_same_shape(result, right); + check_compatible_layout(result, left); + check_compatible_layout(result, right); + for (int i = 0; i < result.nrloc(); ++i) + { + for (int j = 0; j < result.ncloc(); ++j) + { + result.at_local(i, j) + = alpha * left.at_local(i, j) + beta * right.at_local(i, j); + } + } +} + +template +void scale_impl(Matrix2dView matrix, const T factor) +{ + for (int i = 0; i < matrix.nrloc(); ++i) + { + for (int j = 0; j < matrix.ncloc(); ++j) + { + matrix.at_local(i, j) *= factor; + } + } +} + +template +void set_identity_impl(Matrix2dView matrix) +{ + if (matrix.nrglb() != matrix.ncglb()) + { + throw std::invalid_argument("identity requires a square matrix"); + } + std::shared_ptr dist + = matrix.distribution(); +#ifdef __MPI + if (matrix.is_distributed() && dist == nullptr) + { + if (matrix.desc() == nullptr) + { + throw std::invalid_argument( + "distributed identity requires a valid descriptor"); + } + const int nb = matrix.desc()[4]; + const int blacs_ctxt = matrix.desc()[1]; + dist = make_frozen_distribution(matrix.nrglb(), + matrix.ncglb(), + nb, + blacs_ctxt); + } +#endif + for (int i = 0; i < matrix.nrloc(); ++i) + { + for (int j = 0; j < matrix.ncloc(); ++j) + { + const int irglb = dist == nullptr ? i : dist->irglb(i); + const int icglb = dist == nullptr ? j : dist->icglb(j); + matrix.at_local(i, j) = irglb == icglb ? T(1.0) : T(); + } + } +} + +void check_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 check_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 check_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.is_distributed() != rhs.is_distributed()) + { + throw std::invalid_argument( + "linear solve requires matching host or distributed layouts"); + } + if (matrix.is_distributed() + && (matrix.desc() == nullptr + || rhs.desc() == nullptr + || matrix.desc()[1] != rhs.desc()[1] + || matrix.desc()[4] != rhs.desc()[4] + || matrix.desc()[5] != rhs.desc()[5] + || matrix.desc()[6] != rhs.desc()[6] + || matrix.desc()[7] != rhs.desc()[7])) + { + throw std::invalid_argument( + "linear solve requires compatible distributed layouts"); + } +} + +void check_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.is_distributed() != rhs.is_distributed()) + { + throw std::invalid_argument( + "linear solve requires matching host or distributed layouts"); + } + if (matrix.is_distributed() + && (matrix.desc() == nullptr + || rhs.desc() == nullptr + || matrix.desc()[1] != rhs.desc()[1] + || matrix.desc()[4] != rhs.desc()[4] + || matrix.desc()[5] != rhs.desc()[5] + || matrix.desc()[6] != rhs.desc()[6] + || matrix.desc()[7] != rhs.desc()[7])) + { + throw std::invalid_argument( + "linear solve requires compatible distributed layouts"); + } +} +} // namespace + +namespace matrix2d_linalg +{ +void inv(Matrix2dView matrix) +{ + check_inverse_view(matrix); + if (matrix.is_distributed()) + { +#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(Matrix2dView> matrix) +{ + check_inverse_view(matrix); + if (matrix.is_distributed()) + { +#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(Matrix2dView matrix, + Matrix2dView rhs) +{ + check_solve_views(matrix, rhs); + if (matrix.is_distributed()) + { +#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(Matrix2dView> matrix, + Matrix2dView> rhs) +{ + check_solve_views(matrix, rhs); + if (matrix.is_distributed()) + { +#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(Matrix2dView result, + Matrix2dView left, + Matrix2dView right) +{ + check_matmul_views(result, left, right); + if (result.is_distributed()) + { +#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(Matrix2dView> result, + Matrix2dView> left, + Matrix2dView> right) +{ + check_matmul_views(result, left, right); + if (result.is_distributed()) + { +#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 linear_combination(Matrix2dView result, + const double alpha, + Matrix2dView left, + const double beta, + Matrix2dView right) +{ + linear_combination_impl(result, alpha, left, beta, right); +} + +void linear_combination( + Matrix2dView> result, + const std::complex alpha, + Matrix2dView> left, + const std::complex beta, + Matrix2dView> right) +{ + linear_combination_impl(result, alpha, left, beta, right); +} + +void scale(Matrix2dView matrix, const double factor) +{ + scale_impl(matrix, factor); +} + +void scale(Matrix2dView> matrix, + const std::complex factor) +{ + scale_impl(matrix, factor); +} + +void set_identity(Matrix2dView matrix) +{ + set_identity_impl(matrix); +} + +void set_identity(Matrix2dView> matrix) +{ + set_identity_impl(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..71a7a0d1624 --- /dev/null +++ b/source/source_base/matrix2d_linalg.h @@ -0,0 +1,44 @@ +#ifndef ABACUS_SOURCE_SOURCE_BASE_MATRIX2D_LINALG_H +#define ABACUS_SOURCE_SOURCE_BASE_MATRIX2D_LINALG_H + +#include "source_base/matrix2d_view.h" + +#include +namespace matrix2d_linalg +{ +void inv(Matrix2dView matrix); +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); + +void linear_combination(Matrix2dView result, + const double alpha, + Matrix2dView left, + const double beta, + Matrix2dView right); +void linear_combination( + Matrix2dView> result, + const std::complex alpha, + Matrix2dView> left, + const std::complex beta, + Matrix2dView> right); + +void scale(Matrix2dView matrix, const double factor); +void scale(Matrix2dView> matrix, + const std::complex factor); + +void set_identity(Matrix2dView matrix); +void set_identity(Matrix2dView> matrix); +} // namespace matrix2d_linalg + +#endif diff --git a/source/source_base/matrix2d_reduction.cpp b/source/source_base/matrix2d_reduction.cpp new file mode 100644 index 00000000000..aa439ef665b --- /dev/null +++ b/source/source_base/matrix2d_reduction.cpp @@ -0,0 +1,435 @@ +#include "source_base/matrix2d_reduction.h" + +#include "source_base/parallel_common.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef _OPENMP +#include +#endif + +namespace +{ +template +T conjugate_value(const T& value) +{ + return value; +} + +template +std::complex conjugate_value(const std::complex& value) +{ + return std::conj(value); +} + +template +double absolute_square(const T& value) +{ + const double real_value = static_cast(value); + return real_value * real_value; +} + +template +double absolute_square(const std::complex& value) +{ + const double real_value = static_cast(value.real()); + const double imaginary_value = static_cast(value.imag()); + return real_value * real_value + imaginary_value * imaginary_value; +} + +template +void reduce_sum_over_processes(Value& value, const Matrix2d& matrix) +{ +#ifdef __MPI + const std::shared_ptr dist + = matrix.distribution(); + if (dist != nullptr && !dist->is_serial()) + { + const MPI_Comm comm = dist->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 dist + = matrix.distribution(); + if (dist != nullptr && !dist->is_serial()) + { + const MPI_Comm comm = dist->comm(); + if (comm != MPI_COMM_NULL) + { + Parallel_Common::allreduce_max(value, comm); + } + } +#else + static_cast(value); + static_cast(matrix); +#endif +} + +int checked_mpi_count(const std::size_t count) +{ + if (count > static_cast(std::numeric_limits::max())) + { + throw std::invalid_argument("Matrix2d diagonal payload exceeds MPI count range"); + } + return static_cast(count); +} + +std::vector make_byte_displacements(const std::vector& counts) +{ + std::vector displacements(counts.size(), 0); + int displacement = 0; + for (std::size_t ip = 0; ip < counts.size(); ++ip) + { + displacements[ip] = displacement; + if (counts[ip] > std::numeric_limits::max() - displacement) + { + throw std::invalid_argument("Matrix2d diagonal payload size overflow"); + } + displacement += counts[ip]; + } + return displacements; +} + +#ifdef __MPI +std::vector gather_byte_counts(const int local_count, const MPI_Comm comm) +{ + const int nproc = Parallel_Common::comm_size(comm); + const std::vector receive_counts( + static_cast(nproc), + checked_mpi_count(sizeof(int))); + const std::vector receive_displacements + = make_byte_displacements(receive_counts); + std::vector counts(static_cast(nproc), 0); + Parallel_Common::allgatherv_bytes(&local_count, + checked_mpi_count(sizeof(local_count)), + counts.data(), + receive_counts.data(), + receive_displacements.data(), + comm); + return counts; +} +#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.at_local(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.at_local(i, j); + } + } +#endif + reduce_sum_over_processes(value, matrix); + return value; +} + +template +double sum_squares(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) + { + value += absolute_square(matrix.at_local(i, j)); + } + } + reduce_sum_over_processes(value, matrix); + return value; +} + +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] + += conjugate_value(left.at_local(i, j)) + * right.at_local(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 += conjugate_value(left.at_local(i, j)) + * right.at_local(i, j); + } + } +#endif + reduce_sum_over_processes(value, left); + return value; +} + +template +double norm2(const Matrix2d& matrix) +{ + return std::sqrt(sum_squares(matrix)); +} + +template +double max_abs(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(max : value) schedule(static) +#endif + for (int i = 0; i < nrloc; ++i) + { + for (int j = 0; j < ncloc; ++j) + { + value = std::max( + value, + static_cast(std::abs(matrix.at_local(i, j)))); + } + } + reduce_max_over_processes(value, matrix); + return value; +} + +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 dist + = matrix.distribution(); + std::vector> local_entries; + for (int irloc = 0; irloc < nrloc; ++irloc) + { + for (int icloc = 0; icloc < ncloc; ++icloc) + { + const int irglb = dist == nullptr ? irloc : dist->irglb(irloc); + const int icglb = dist == nullptr ? icloc : dist->icglb(icloc); + if (irglb == icglb && irglb < diagonal_size) + { + local_entries.push_back( + std::make_pair(irglb, matrix.at_local(irloc, icloc))); + } + } + } +#ifdef __MPI + if (dist != nullptr && !dist->is_serial()) + { + const MPI_Comm comm = dist->comm(); + if (comm != MPI_COMM_NULL) + { + const std::size_t entry_bytes = sizeof(int) + sizeof(T); + const std::size_t local_payload_bytes + = sizeof(int) + local_entries.size() * entry_bytes; + std::vector local_payload(local_payload_bytes); + const int local_entry_count + = checked_mpi_count(local_entries.size()); + std::memcpy(local_payload.data(), + &local_entry_count, + sizeof(local_entry_count)); + std::size_t offset = sizeof(local_entry_count); + for (const std::pair& entry : local_entries) + { + std::memcpy(local_payload.data() + offset, + &entry.first, + sizeof(entry.first)); + offset += sizeof(entry.first); + std::memcpy(local_payload.data() + offset, + &entry.second, + sizeof(entry.second)); + offset += sizeof(entry.second); + } + + const int local_count = checked_mpi_count(local_payload.size()); + const std::vector payload_counts + = gather_byte_counts(local_count, comm); + const std::vector payload_displacements + = make_byte_displacements(payload_counts); + const int total_bytes + = payload_displacements.back() + payload_counts.back(); + std::vector received( + static_cast(total_bytes)); + Parallel_Common::allgatherv_bytes(local_payload.data(), + local_count, + received.data(), + payload_counts.data(), + payload_displacements.data(), + comm); + + for (std::size_t ip = 0; ip < payload_counts.size(); ++ip) + { + const std::size_t begin + = static_cast(payload_displacements[ip]); + const std::size_t end + = begin + static_cast(payload_counts[ip]); + if (end - begin < sizeof(int)) + { + throw std::runtime_error( + "Matrix2d diagonal payload is truncated"); + } + int entry_count = 0; + std::memcpy(&entry_count, + received.data() + begin, + sizeof(entry_count)); + const std::size_t expected_bytes + = static_cast(entry_count) * entry_bytes; + if (entry_count < 0 + || end - begin != sizeof(int) + expected_bytes) + { + throw std::runtime_error( + "Matrix2d diagonal payload has an invalid size"); + } + std::size_t entry_offset = begin + sizeof(entry_count); + for (int ientry = 0; ientry < entry_count; ++ientry) + { + int index = 0; + T value = T(); + std::memcpy(&index, + received.data() + entry_offset, + sizeof(index)); + entry_offset += sizeof(index); + std::memcpy(&value, + received.data() + entry_offset, + sizeof(value)); + entry_offset += sizeof(value); + if (index < 0 || index >= diagonal_size) + { + throw std::runtime_error( + "Matrix2d diagonal index is outside global shape"); + } + values[static_cast(index)] += value; + } + } + } + } +#endif + if (dist == nullptr || dist->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 double sum_squares(const Matrix2d& matrix); +template double sum_squares(const Matrix2d& matrix); +template double sum_squares(const Matrix2d& matrix); +template double sum_squares>( + const Matrix2d>& matrix); +template double sum_squares>( + 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 double norm2(const Matrix2d& matrix); +template double norm2(const Matrix2d& matrix); +template double norm2(const Matrix2d& matrix); +template double norm2>( + const Matrix2d>& matrix); +template double norm2>( + const Matrix2d>& matrix); + +template double max_abs(const Matrix2d& matrix); +template double max_abs(const Matrix2d& matrix); +template double max_abs(const Matrix2d& matrix); +template double max_abs>( + const Matrix2d>& matrix); +template double 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..488f97f0588 --- /dev/null +++ b/source/source_base/matrix2d_reduction.h @@ -0,0 +1,27 @@ +#ifndef ABACUS_SOURCE_SOURCE_BASE_MATRIX2D_REDUCTION_H +#define ABACUS_SOURCE_SOURCE_BASE_MATRIX2D_REDUCTION_H + +#include "source_base/matrix2d.h" + +namespace matrix2d_impl +{ +template +T sum(const Matrix2d& matrix); + +template +double sum_squares(const Matrix2d& matrix); + +template +T dot(const Matrix2d& left, const Matrix2d& right); + +template +double norm2(const Matrix2d& matrix); + +template +double 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..76d4c8de043 --- /dev/null +++ b/source/source_base/matrix2d_scalapack.cpp @@ -0,0 +1,393 @@ +#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 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* source_descriptor = source.desc(); + const double beta = 0.0; + double* result_data = result.data(); + const int ic = 1; + const int jc = 1; + const int* result_descriptor = result.desc(); + ScalapackConnector::tranu( + /* m= */ n, + /* n= */ m, + /* alpha= */ alpha, + /* a= */ source_data, + /* ia= */ ia, + /* ja= */ ja, + /* desca= */ source_descriptor, + /* beta= */ beta, + /* c= */ result_data, + /* ic= */ ic, + /* jc= */ jc, + /* descc= */ result_descriptor); +} + +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* source_descriptor = 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* result_descriptor = result.desc(); + ScalapackConnector::tranu( + /* m= */ n, + /* n= */ m, + /* alpha= */ alpha, + /* a= */ source_data, + /* ia= */ ia, + /* ja= */ ja, + /* desca= */ source_descriptor, + /* beta= */ beta, + /* c= */ result_data, + /* ic= */ ic, + /* jc= */ jc, + /* descc= */ result_descriptor); +} + +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* source_descriptor = 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* result_descriptor = result.desc(); + ScalapackConnector::tranc( + /* m= */ n, + /* n= */ m, + /* alpha= */ alpha, + /* a= */ source_data, + /* ia= */ ia, + /* ja= */ ja, + /* desca= */ source_descriptor, + /* beta= */ beta, + /* c= */ result_data, + /* ic= */ ic, + /* jc= */ jc, + /* descc= */ result_descriptor); +} + +namespace +{ +void check_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* descriptor = matrix.desc(); + const int pivot_size = matrix.nrloc() + descriptor[4]; + std::vector ipiv(static_cast(pivot_size)); + int info = 0; + ScalapackConnector::getrf(n, + n, + matrix.data(), + ia, + ja, + descriptor, + ipiv.data(), + &info); + check_scalapack_error("ScaLAPACK getrf", info); + + int lwork = -1; + int liwork = -1; + std::vector work(1); + std::vector iwork(1); + ScalapackConnector::getri(n, + matrix.data(), + ia, + ja, + descriptor, + ipiv.data(), + work.data(), + &lwork, + iwork.data(), + &liwork, + &info); + check_scalapack_error("ScaLAPACK getri workspace query", info); + lwork = queried_workspace_size(work[0]); + liwork = iwork[0]; + work.resize(static_cast(lwork)); + iwork.resize(static_cast(liwork)); + ScalapackConnector::getri(n, + matrix.data(), + ia, + ja, + descriptor, + ipiv.data(), + work.data(), + &lwork, + iwork.data(), + &liwork, + &info); + check_scalapack_error("ScaLAPACK getri", info); +} + +void inv(Matrix2dView> matrix) +{ + const int n = matrix.nrglb(); + const int ia = 1; + const int ja = 1; + const int* descriptor = matrix.desc(); + const int pivot_size = matrix.nrloc() + descriptor[4]; + std::vector ipiv(static_cast(pivot_size)); + int info = 0; + ScalapackConnector::getrf(n, + n, + matrix.data(), + ia, + ja, + descriptor, + ipiv.data(), + &info); + check_scalapack_error("ScaLAPACK getrf", info); + + int lwork = -1; + int liwork = -1; + std::vector> work(1); + std::vector iwork(1); + ScalapackConnector::getri(n, + matrix.data(), + ia, + ja, + descriptor, + ipiv.data(), + work.data(), + &lwork, + iwork.data(), + &liwork, + &info); + check_scalapack_error("ScaLAPACK getri workspace query", info); + lwork = queried_workspace_size(work[0]); + liwork = iwork[0]; + work.resize(static_cast(lwork)); + iwork.resize(static_cast(liwork)); + ScalapackConnector::getri(n, + matrix.data(), + ia, + ja, + descriptor, + ipiv.data(), + work.data(), + &lwork, + iwork.data(), + &liwork, + &info); + check_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); + check_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); + check_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* left_descriptor = left.desc(); + const double* right_data = right.data(); + const int ib = 1; + const int jb = 1; + const int* right_descriptor = right.desc(); + const double beta = 0.0; + double* result_data = result.data(); + const int ic = 1; + const int jc = 1; + const int* result_descriptor = result.desc(); + ScalapackConnector::gemm( + /* transa= */ transa, + /* transb= */ transb, + /* M= */ m, + /* N= */ n, + /* K= */ k, + /* alpha= */ alpha, + /* A= */ left_data, + /* IA= */ ia, + /* JA= */ ja, + /* DESCA= */ left_descriptor, + /* B= */ right_data, + /* IB= */ ib, + /* JB= */ jb, + /* DESCB= */ right_descriptor, + /* beta= */ beta, + /* C= */ result_data, + /* IC= */ ic, + /* JC= */ jc, + /* DESCC= */ result_descriptor); +} + +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* left_descriptor = left.desc(); + const std::complex* right_data = right.data(); + const int ib = 1; + const int jb = 1; + const int* right_descriptor = 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* result_descriptor = result.desc(); + ScalapackConnector::gemm( + /* transa= */ transa, + /* transb= */ transb, + /* M= */ m, + /* N= */ n, + /* K= */ k, + /* alpha= */ alpha, + /* A= */ left_data, + /* IA= */ ia, + /* JA= */ ja, + /* DESCA= */ left_descriptor, + /* B= */ right_data, + /* IB= */ ib, + /* JB= */ jb, + /* DESCB= */ right_descriptor, + /* beta= */ beta, + /* C= */ result_data, + /* IC= */ ic, + /* JC= */ jc, + /* DESCC= */ result_descriptor); +} + +} // 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..4c5bc80203e --- /dev/null +++ b/source/source_base/matrix2d_scalapack.h @@ -0,0 +1,40 @@ +#ifndef ABACUS_SOURCE_SOURCE_BASE_MATRIX2D_SCALAPACK_H +#define ABACUS_SOURCE_SOURCE_BASE_MATRIX2D_SCALAPACK_H + +#include + +template +class Matrix2dView; + +#ifdef __MPI +namespace matrix2d_impl +{ +namespace scalapack +{ +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); +void inv(Matrix2dView matrix); +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..4b7d7538efa --- /dev/null +++ b/source/source_base/matrix2d_view.h @@ -0,0 +1,153 @@ +#ifndef ABACUS_SOURCE_SOURCE_BASE_MATRIX2D_VIEW_H +#define ABACUS_SOURCE_SOURCE_BASE_MATRIX2D_VIEW_H + +#include "source_base/parallel_blkcyc.h" + +#include +#include +#include +#include +#include +#include + +/** + * @brief Non-owning two-dimensional matrix view. + * + * Host views use row-major storage. Distributed views borrow a frozen + * block-cyclic distribution and use its local column-major layout. + */ +template +class Matrix2dView +{ + public: + 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()), + distributed_(other.is_distributed()), + desc_(other.desc()), + dist_(other.distribution()) + { + } + + Matrix2dView(T* data, const int nrglb, const int ncglb) + : data_(data), + nrglb_(nrglb), + ncglb_(ncglb), + nrloc_(nrglb), + ncloc_(ncglb), + lld_(ncglb), + distributed_(false), + desc_(nullptr) + { + assert(nrglb_ >= 0); + assert(ncglb_ >= 0); + } + +#ifdef __MPI + Matrix2dView(T* data, + std::shared_ptr dist) + : data_(data), + nrglb_(checked_distribution(dist).nrglb()), + ncglb_(checked_distribution(dist).ncglb()), + nrloc_(checked_distribution(dist).nrloc()), + ncloc_(checked_distribution(dist).ncloc()), + lld_(checked_distribution(dist).lld()), + distributed_(true), + desc_(dist->desc()), + dist_(std::move(dist)) + { + } + + Matrix2dView(T* data, + const int nrloc, + const int ncloc, + const int* desc) + : data_(data), + nrglb_(checked_descriptor(desc)[2]), + ncglb_(checked_descriptor(desc)[3]), + nrloc_(nrloc), + ncloc_(ncloc), + lld_(checked_descriptor(desc)[8]), + distributed_(true), + desc_(desc) + { + } +#endif + + T* data() const { return data_; } + int nrglb() const { return nrglb_; } + int ncglb() const { return ncglb_; } + int nrloc() const { return nrloc_; } + int ncloc() const { return ncloc_; } + int lld() const { return lld_; } + std::size_t size() const + { + return static_cast(nrloc_) + * static_cast(ncloc_); + } + + bool is_distributed() const { return distributed_; } + const std::shared_ptr& + distribution() const + { + return dist_; + } + + const int* desc() const + { + return desc_; + } + + T& at_local(const int i, const int j) const + { + assert(i >= 0); + assert(i < nrloc_); + assert(j >= 0); + assert(j < ncloc_); + const std::size_t offset = dist_ == nullptr + ? static_cast(i) * static_cast(ncloc_) + + static_cast(j) + : static_cast(j) * static_cast(lld_) + + static_cast(i); + return data_[offset]; + } + + private: + static const Parallel_Blkcyclic& checked_distribution( + const std::shared_ptr& dist) + { + if (dist == nullptr) + { + throw std::invalid_argument("matrix view distribution must not be null"); + } + return *dist; + } + + static const int* checked_descriptor(const int* desc) + { + if (desc == nullptr) + { + throw std::invalid_argument("matrix view descriptor must not be null"); + } + return desc; + } + + T* data_; + int nrglb_; + int ncglb_; + int nrloc_; + int ncloc_; + int lld_; + bool distributed_; + const int* desc_; + std::shared_ptr dist_; +}; + +#endif diff --git a/source/source_base/module_external/scalapack_connector.h b/source/source_base/module_external/scalapack_connector.h index b9fc79c0fee..2276d3ed48e 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, @@ -161,6 +165,10 @@ extern "C" 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); + void pdgetri_( + const int *n, + double *A, const int *ia, const int *ja, const int *desca, + int *ipiv, double *work, const int *lwork, const int *iwork, const int *liwork, const int *info); void pzgeadd_( const char *transa, @@ -400,6 +408,15 @@ 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, @@ -409,6 +426,15 @@ class ScalapackConnector 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, const int *lwork, const int *iwork, const 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..9c92a2485fa 100644 --- a/source/source_base/parallel_blkcyc.cpp +++ b/source/source_base/parallel_blkcyc.cpp @@ -94,6 +94,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 { @@ -134,6 +145,16 @@ 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) +{ + 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) @@ -264,3 +285,55 @@ 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 dist + = std::make_shared(); + dist->init(nrglb, ncglb, nb, comm, false); + return dist; +} + +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 dist + = std::make_shared(); + dist->init_grid(comm, nrproc, ncproc); + dist->init_dist(nrglb, ncglb, nb); + dist->owns_ictxt_ = true; + return dist; +} + +std::shared_ptr make_frozen_distribution( + const int nrglb, + const int ncglb, + const int nb, + const int ictxt) +{ + std::shared_ptr dist + = std::make_shared(); + dist->set(nrglb, ncglb, nb, ictxt); + return dist; +} +#endif + +std::shared_ptr make_frozen_distribution( + const int nrglb, + const int ncglb) +{ + std::shared_ptr dist + = std::make_shared(); + dist->set_serial(nrglb, ncglb); + return dist; +} diff --git a/source/source_base/parallel_blkcyc.h b/source/source_base/parallel_blkcyc.h index 1ca7a650fbd..a3b5a113cae 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,15 @@ 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_frozen_distribution(int, int, int, int); +#endif + static constexpr int DESC_SIZE = 9; static constexpr int DESC_ICTXT = 1; static constexpr int DESC_M = 2; @@ -183,9 +195,36 @@ class Parallel_Blkcyclic bool owns_ictxt_ = false; 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_frozen_distribution( + int nrglb, + int ncglb, + int nb, + int ictxt); +#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 90073b9d535..7e1ce75bd89 100644 --- a/source/source_base/parallel_common.cpp +++ b/source/source_base/parallel_common.cpp @@ -113,6 +113,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* send_buffer, + const int send_count, + void* receive_buffer, + const int* receive_counts, + const int* receive_displacements, + const int root, + const MPI_Comm comm) +{ + MPI_Gatherv(send_buffer, + send_count, + MPI_BYTE, + receive_buffer, + receive_counts, + receive_displacements, + MPI_BYTE, + root, + comm); +} + +void allgatherv_bytes(const void* send_buffer, + const int send_count, + void* receive_buffer, + const int* receive_counts, + const int* receive_displacements, + const MPI_Comm comm) +{ + MPI_Allgatherv(send_buffer, + send_count, + MPI_BYTE, + receive_buffer, + receive_counts, + receive_displacements, + MPI_BYTE, + comm); +} + +void scatterv_bytes(const void* send_buffer, + const int* send_counts, + const int* send_displacements, + void* receive_buffer, + const int receive_count, + const int root, + const MPI_Comm comm) +{ + MPI_Scatterv(send_buffer, + send_counts, + send_displacements, + MPI_BYTE, + receive_buffer, + receive_count, + 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 bbb4aaf1d0d..3ef57180cb3 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 @@ -37,6 +55,89 @@ void bcast_bool(bool& object); #ifdef __MPI //(3) bcast single on an explicit communicator, from the communicator's rank 0 void bcast_mpi_offset(MPI_Offset& object, const MPI_Comm& comm); + +void barrier(const MPI_Comm comm); + +void gatherv_bytes(const void* send_buffer, + int send_count, + void* receive_buffer, + const int* receive_counts, + const int* receive_displacements, + int root, + MPI_Comm comm); + +void allgatherv_bytes(const void* send_buffer, + int send_count, + void* receive_buffer, + const int* receive_counts, + const int* receive_displacements, + MPI_Comm comm); + +void scatterv_bytes(const void* send_buffer, + const int* send_counts, + const int* send_displacements, + void* receive_buffer, + int receive_count, + 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* send_buffer, + int send_count, + void* receive_buffer, + const int*, + const int*, + int, + int) +{ + if (receive_buffer != nullptr && send_count > 0) + { + std::copy(static_cast(send_buffer), + static_cast(send_buffer) + send_count, + static_cast(receive_buffer)); + } +} + +inline void allgatherv_bytes(const void* send_buffer, + int send_count, + void* receive_buffer, + const int*, + const int*, + int) +{ + if (receive_buffer != nullptr && send_count > 0) + { + std::copy(static_cast(send_buffer), + static_cast(send_buffer) + send_count, + static_cast(receive_buffer)); + } +} + +inline void scatterv_bytes(const void* send_buffer, + const int*, + const int*, + void* receive_buffer, + int receive_count, + int, + int) +{ + if (receive_buffer != nullptr && receive_count > 0) + { + std::copy(static_cast(send_buffer), + static_cast(send_buffer) + receive_count, + static_cast(receive_buffer)); + } +} #endif } // namespace Parallel_Common diff --git a/source/source_base/unittests/CMakeLists.txt b/source/source_base/unittests/CMakeLists.txt new file mode 100644 index 00000000000..3a8963419db --- /dev/null +++ b/source/source_base/unittests/CMakeLists.txt @@ -0,0 +1,53 @@ +AddTest( + TARGET MODULE_BASE_matrix2d + LIBS parameter base device container + SOURCES test_matrix2d.cpp +) + +AddTest( + TARGET MODULE_BASE_matrix2d_linalg + LIBS parameter base device container + SOURCES test_matrix2d_linalg.cpp +) + +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) + 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..ed361fda938 --- /dev/null +++ b/source/source_base/unittests/test_matrix2d.cpp @@ -0,0 +1,1399 @@ +#ifdef NDEBUG +#undef NDEBUG +#endif + +#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 +#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"); + +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.is_distributed()); + 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.at_local(0, 0)); + + double value = 1.0; + for (int row = 0; row < 2; ++row) + { + for (int col = 0; col < 3; ++col) + { + const std::size_t expected_index = static_cast(row) * 3U + + static_cast(col); + EXPECT_EQ(&matrix.at_local(row, col), matrix.data() + expected_index); + EXPECT_EQ(&matrix.at_global(row, col), &matrix.at_local(row, col)); + EXPECT_TRUE(matrix.owns_global_index(row, col)); + matrix.at_local(row, col) = 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.at_local(1, 2), matrix.data() + 5); + EXPECT_EQ(&const_matrix.at_global(1, 2), matrix.data() + 5); +} + +void check_distribution_layout(Matrix2d& matrix, + const int global_rows, + const int global_cols) +{ + const std::shared_ptr& distribution + = matrix.distribution(); + ASSERT_NE(distribution, nullptr); + EXPECT_EQ(matrix.nrglb(), global_rows); + EXPECT_EQ(matrix.ncglb(), global_cols); + EXPECT_EQ(matrix.nrloc(), distribution->nrloc()); + EXPECT_EQ(matrix.ncloc(), distribution->ncloc()); + EXPECT_EQ(matrix.size(), + distribution->size()); + EXPECT_EQ(matrix.nrproc(), distribution->nrproc()); + EXPECT_EQ(matrix.ncproc(), distribution->ncproc()); + EXPECT_EQ(matrix.irproc(), distribution->irproc()); + EXPECT_EQ(matrix.icproc(), distribution->icproc()); + EXPECT_EQ(matrix.lld(), distribution->lld()); + + const int local_rows = matrix.nrloc(); + const int local_cols = matrix.ncloc(); + const std::size_t leading_dimension + = static_cast(matrix.lld()); + for (int local_row = 0; local_row < local_rows; ++local_row) + { + for (int local_col = 0; local_col < local_cols; ++local_col) + { + const std::size_t expected_index + = static_cast(local_col) * leading_dimension + + static_cast(local_row); + EXPECT_EQ(&matrix.at_local(local_row, local_col), matrix.data() + expected_index); + } + } + + for (int global_row = 0; global_row < global_rows; ++global_row) + { + for (int global_col = 0; global_col < global_cols; ++global_col) + { + const bool expected_owner = distribution->in_this_processor(global_row, global_col); + EXPECT_EQ(matrix.owns_global_index(global_row, global_col), expected_owner); + if (!expected_owner) + { + continue; + } + + const int local_row = distribution->irloc(global_row); + const int local_col = distribution->icloc(global_col); + ASSERT_NE(local_row, -1); + ASSERT_NE(local_col, -1); + EXPECT_EQ(&matrix.at_global(global_row, global_col), + &matrix.at_local(local_row, local_col)); + const double value = static_cast(global_row * global_cols + global_col); + matrix.at_global(global_row, global_col) = value; + EXPECT_EQ(matrix.at_local(local_row, local_col), value); + } + } + + const Matrix2d& const_matrix = matrix; + EXPECT_EQ(const_matrix.data(), matrix.data()); +} + +#ifdef __MPI +void check_mpi_descriptor(Matrix2d& matrix, + const int global_rows, + const int global_cols, + const int block_size) +{ + constexpr int kDescriptorMatrixTypeIndex = 0; + constexpr int kDescriptorBlacsContextIndex = 1; + constexpr int kDescriptorGlobalRowsIndex = 2; + constexpr int kDescriptorGlobalColsIndex = 3; + constexpr int kDescriptorBlockRowsIndex = 4; + constexpr int kDescriptorBlockColsIndex = 5; + constexpr int kDescriptorLeadingDimIndex = 8; + + const int* const descriptor = matrix.desc(); + ASSERT_NE(descriptor, nullptr); + EXPECT_EQ(descriptor[kDescriptorMatrixTypeIndex], 1); + EXPECT_EQ(descriptor[kDescriptorBlacsContextIndex], matrix.ictxt()); + EXPECT_EQ(descriptor[kDescriptorGlobalRowsIndex], global_rows); + EXPECT_EQ(descriptor[kDescriptorGlobalColsIndex], global_cols); + EXPECT_EQ(descriptor[kDescriptorBlockRowsIndex], block_size); + EXPECT_EQ(descriptor[kDescriptorBlockColsIndex], block_size); + EXPECT_EQ(descriptor[kDescriptorLeadingDimIndex], 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 row, const int col, const double offset) +{ + return static_cast(offset + 0.5 + 1.25 * row - 0.75 * col); +} + +template <> +std::complex test_value>(const int row, + const int col, + const double offset) +{ + return std::complex(offset + 0.5 + 1.25 * row - 0.75 * col, + 0.25 - 0.5 * row + 0.875 * col); +} + +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 row = 0; row < matrix.nrglb(); ++row) + { + for (int col = 0; col < matrix.ncglb(); ++col) + { + if (matrix.owns_global_index(row, col)) + { + matrix.at_global(row, col) = test_value(row, col, offset); + } + } + } +} + +template +Matrix2d make_host_reference(const int rows, + const int cols, + const double offset = 0.0) +{ + Matrix2d reference(rows, cols); + for (int row = 0; row < rows; ++row) + { + for (int col = 0; col < cols; ++col) + { + reference.at_local(row, col) = test_value(row, col, offset); + } + } + return reference; +} + +template +void verify_global_matrix(const Matrix2d& actual, const Matrix2d& expected) +{ + ASSERT_FALSE(actual.is_distributed()); + ASSERT_EQ(actual.nrglb(), expected.nrglb()); + ASSERT_EQ(actual.ncglb(), expected.ncglb()); + for (int row = 0; row < expected.nrglb(); ++row) + { + for (int col = 0; col < expected.ncglb(); ++col) + { + const std::size_t c_order_index + = static_cast(row) + * static_cast(expected.ncglb()) + + static_cast(col); + expect_scalar_near(actual.data()[c_order_index], + expected.at_local(row, col)); + } + } +} + +template +void check_elementwise_operations(Matrix2d& matrix, Matrix2d& other) +{ + const int rows = matrix.nrglb(); + const int cols = matrix.ncglb(); + + Matrix2d filled = matrix; + const T fill_value = constant_value(3.5); + filled.fill(fill_value); + Matrix2d expected(rows, cols); + expected.fill(fill_value); + verify_global_matrix(filled.gather(), expected); + + filled = matrix; + filled.scale(constant_value(2.5)); + expected = make_host_reference(rows, cols); + for (int row = 0; row < rows; ++row) + { + for (int col = 0; col < cols; ++col) + { + expected.at_local(row, col) *= constant_value(2.5); + } + } + verify_global_matrix(filled.gather(), expected); + + filled = matrix; + filled += other; + expected = make_host_reference(rows, cols); + Matrix2d expected_other = make_host_reference(rows, cols, 10.0); + for (int row = 0; row < rows; ++row) + { + for (int col = 0; col < cols; ++col) + { + expected.at_local(row, col) += expected_other.at_local(row, col); + } + } + verify_global_matrix(filled.gather(), expected); + + filled = matrix; + filled -= other; + expected = make_host_reference(rows, cols); + for (int row = 0; row < rows; ++row) + { + for (int col = 0; col < cols; ++col) + { + expected.at_local(row, col) -= expected_other.at_local(row, col); + } + } + verify_global_matrix(filled.gather(), expected); + + filled = matrix; + filled *= other; + expected = make_host_reference(rows, cols); + for (int row = 0; row < rows; ++row) + { + for (int col = 0; col < cols; ++col) + { + expected.at_local(row, col) *= expected_other.at_local(row, col); + } + } + verify_global_matrix(filled.gather(), expected); + + filled = matrix; + filled.conjugate(); + expected = make_host_reference(rows, cols); + for (int row = 0; row < rows; ++row) + { + for (int col = 0; col < cols; ++col) + { + expected.at_local(row, col) + = conjugate_value(expected.at_local(row, col)); + } + } + verify_global_matrix(filled.gather(), expected); + + Matrix2d expected_real(rows, cols); + Matrix2d expected_imag(rows, cols); + const Matrix2d matrix_reference = make_host_reference(rows, cols); + for (int row = 0; row < rows; ++row) + { + for (int col = 0; col < cols; ++col) + { + const T& value = matrix_reference.at_local(row, col); + expected_real.at_local(row, col) = real_part(value); + expected_imag.at_local(row, col) = imaginary_part(value); + } + } + + Matrix2d real_output = matrix.is_distributed() + ? Matrix2d(matrix.distribution()) + : Matrix2d(rows, cols); + Matrix2d imaginary_output = matrix.is_distributed() + ? Matrix2d(matrix.distribution()) + : Matrix2d(rows, cols); + matrix.real(real_output); + matrix.imag(imaginary_output); + verify_global_matrix(real_output.gather(), expected_real); + verify_global_matrix(imaginary_output.gather(), expected_imag); + 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_sum_squares = 0.0; + double reference_max_abs = 0.0; + for (int row = 0; row < matrix.nrglb(); ++row) + { + for (int col = 0; col < matrix.ncglb(); ++col) + { + const T& value = matrix_reference.at_local(row, col); + const T& other_value = other_reference.at_local(row, col); + reference_sum += value; + reference_dot += conjugate_value(value) * other_value; + reference_sum_squares += 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(matrix.sum_squares()); + expect_scalar_near(matrix.dot(matrix), expected_self_dot); + expect_scalar_near(matrix.sum_squares(), reference_sum_squares); + expect_scalar_near(matrix.norm2(), std::sqrt(reference_sum_squares)); + 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.at_local(i, i)); + } +} + +template +void check_gather_scatter(Matrix2d& matrix) +{ + const int rows = matrix.nrglb(); + const int cols = matrix.ncglb(); + const Matrix2d expected = make_host_reference(rows, cols); + const Matrix2d gathered = matrix.gather(); + verify_global_matrix(gathered, expected); + EXPECT_EQ(std::memcmp(gathered.data(), + expected.data(), + static_cast(rows * cols) * sizeof(T)), + 0); + const Matrix2d gathered_again = matrix.gather(); + EXPECT_EQ(std::memcmp(gathered.data(), + gathered_again.data(), + static_cast(rows * cols) * 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_rank = Parallel_Common::comm_size(MPI_COMM_WORLD) - 1; + const Matrix2d root_result = matrix.gather_on_root(root_rank); + if (rank == root_rank) + { + 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.is_distributed()); + } +#endif + + Matrix2d wrong_shape(rows + 1, cols); + EXPECT_THROW(restored.scatter(wrong_shape), std::invalid_argument); +} + +template +std::size_t set_padding_sentinel(Matrix2d& matrix, const T& sentinel) +{ + const int local_rows = matrix.nrloc(); + const int local_cols = matrix.ncloc(); + const std::size_t leading_dimension + = static_cast(std::max(local_rows, 1)); + const std::size_t column_major_elements + = leading_dimension * static_cast(local_cols); + const std::size_t row_major_elements + = static_cast(local_rows) + * std::max(static_cast(local_cols), leading_dimension); + const std::size_t storage_elements = std::max(column_major_elements, row_major_elements); + const std::size_t logical_elements + = static_cast(local_rows) * static_cast(local_cols); + for (std::size_t index = logical_elements; index < storage_elements; ++index) + { + matrix.data()[index] = sentinel; + } + return storage_elements - logical_elements; +} + +template +void expect_padding_sentinel(const Matrix2d& matrix, + const std::size_t padding_elements, + const T& sentinel) +{ + const int local_rows = matrix.nrloc(); + const int local_cols = matrix.ncloc(); + const std::size_t logical_elements + = static_cast(local_rows) * static_cast(local_cols); + for (std::size_t index = 0; index < padding_elements; ++index) + { + expect_scalar_near(matrix.data()[logical_elements + index], sentinel); + } +} + +std::vector> available_process_grids() +{ + std::vector> grids; +#ifdef __MPI + const int number_of_ranks = Parallel_Common::comm_size(MPI_COMM_WORLD); +#else + const int number_of_ranks = 1; +#endif + if (number_of_ranks == 1) + { + grids.push_back(std::make_pair(1, 1)); + } + if (number_of_ranks == 2) + { + grids.push_back(std::make_pair(1, 2)); + grids.push_back(std::make_pair(2, 1)); + } + if (number_of_ranks == 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 source_rows = source.nrglb(); + const int source_cols = source.ncglb(); + Matrix2d reference(source_cols, source_rows); + for (int row = 0; row < source_rows; ++row) + { + for (int col = 0; col < source_cols; ++col) + { + reference.at_local(col, row) + = source.at_local(row, col); + } + } + return reference; +} + +template +Matrix2d make_dagger_reference(const Matrix2d& source) +{ + const int source_rows = source.nrglb(); + const int source_cols = source.ncglb(); + Matrix2d reference(source_cols, source_rows); + for (int row = 0; row < source_rows; ++row) + { + for (int col = 0; col < source_cols; ++col) + { + reference.at_local(col, row) + = conjugate_value(source.at_local(row, col)); + } + } + return reference; +} + +template +Matrix2d make_matmul_reference(const Matrix2d& left, + const Matrix2d& right) +{ + const int rows = left.nrglb(); + const int shared = left.ncglb(); + const int cols = right.ncglb(); + Matrix2d reference(rows, cols); + for (int row = 0; row < rows; ++row) + { + for (int col = 0; col < cols; ++col) + { + T value = T(); + for (int inner = 0; inner < shared; ++inner) + { + value += left.at_local(row, inner) * right.at_local(inner, col); + } + reference.at_local(row, col) = value; + } + } + return reference; +} + +template +Matrix2d make_host_transpose_reference(const int rows, + const int cols) +{ + return make_transpose_reference(make_host_reference(rows, cols)); +} + +template +Matrix2d make_host_matmul_reference(const int left_rows, + const int shared_cols, + const int right_cols) +{ + return make_matmul_reference(make_host_reference(left_rows, shared_cols), + make_host_reference(shared_cols, right_cols, 10.0)); +} + +template +void check_host_transpose(const int rows, const int cols) +{ + const Matrix2d source = make_host_reference(rows, cols); + 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.is_distributed()); + EXPECT_FALSE(dagger.is_distributed()); + EXPECT_EQ(transposed.nrglb(), cols); + EXPECT_EQ(transposed.ncglb(), rows); + EXPECT_EQ(dagger.nrglb(), cols); + EXPECT_EQ(dagger.ncglb(), rows); +} + +template +void check_host_matmul(const int left_rows, + const int shared_cols, + const int right_cols) +{ + const Matrix2d left = make_host_reference(left_rows, shared_cols); + const Matrix2d right = make_host_reference(shared_cols, right_cols, 10.0); + const Matrix2d product = left.matmul(right); + const Matrix2d expected = make_matmul_reference(left, right); + + verify_global_matrix(product, expected); + EXPECT_FALSE(product.is_distributed()); +} + +#ifdef __MPI +template +void check_mpi_descriptor_for_type(const Matrix2d& matrix, + const int global_rows, + const int global_cols, + const int block_size) +{ + const int* const descriptor = matrix.desc(); + ASSERT_NE(descriptor, nullptr); + EXPECT_EQ(descriptor[0], 1); + EXPECT_EQ(descriptor[1], matrix.ictxt()); + EXPECT_EQ(descriptor[2], global_rows); + EXPECT_EQ(descriptor[3], global_cols); + EXPECT_EQ(descriptor[4], block_size); + EXPECT_EQ(descriptor[5], block_size); + EXPECT_EQ(descriptor[6], 0); + EXPECT_EQ(descriptor[7], 0); + EXPECT_GT(descriptor[8], 0); +} + +template +void check_distributed_transpose(const int rows, + const int cols, + const int grid_rows, + const int grid_cols, + const int block_size) +{ + Matrix2d source(rows, + cols, + grid_rows, + grid_cols, + block_size, + MPI_COMM_WORLD); + fill_global_values(source); + const int* const source_descriptor_before = source.desc(); + + const Matrix2d transposed = source.transpose(); + const Matrix2d dagger = source.dagger(); + const int* const source_descriptor_after = source.desc(); + const int* const result_descriptor = transposed.desc(); + const int* const dagger_descriptor = dagger.desc(); + + ASSERT_TRUE(transposed.is_distributed()); + ASSERT_TRUE(dagger.is_distributed()); + EXPECT_EQ(source_descriptor_after, source_descriptor_before); + EXPECT_NE(result_descriptor, nullptr); + EXPECT_NE(dagger_descriptor, nullptr); + EXPECT_EQ(source.ictxt(), transposed.ictxt()); + EXPECT_EQ(source.ictxt(), dagger.ictxt()); + check_mpi_descriptor_for_type(transposed, cols, rows, block_size); + check_mpi_descriptor_for_type(dagger, cols, rows, block_size); + verify_global_matrix(transposed.gather(), + make_host_transpose_reference(rows, cols)); + verify_global_matrix(dagger.gather(), + make_dagger_reference(source.gather())); + EXPECT_EQ(source.desc(), source_descriptor_after); + EXPECT_EQ(transposed.desc(), result_descriptor); + EXPECT_EQ(dagger.desc(), dagger_descriptor); +} + +template +void check_distributed_matmul(const int left_rows, + const int shared_cols, + const int right_cols, + const int grid_rows, + const int grid_cols, + const int block_size) +{ + Matrix2d left(left_rows, + shared_cols, + grid_rows, + grid_cols, + block_size, + MPI_COMM_WORLD); + const int left_blacs_context = left.ictxt(); + const std::shared_ptr right_distribution + = make_frozen_distribution(shared_cols, + right_cols, + block_size, + left_blacs_context); + Matrix2d right(right_distribution); + fill_global_values(left); + fill_global_values(right, 10.0); + + const int* const left_descriptor_before = left.desc(); + const int* const right_descriptor_before = right.desc(); + const Matrix2d product = left.matmul(right); + const int* const left_descriptor_after = left.desc(); + const int* const right_descriptor_after = right.desc(); + const int* const result_descriptor = product.desc(); + + ASSERT_TRUE(product.is_distributed()); + EXPECT_EQ(left_descriptor_after, left_descriptor_before); + EXPECT_EQ(right_descriptor_after, right_descriptor_before); + EXPECT_NE(result_descriptor, nullptr); + EXPECT_EQ(left.ictxt(), right.ictxt()); + EXPECT_EQ(left.ictxt(), product.ictxt()); + check_mpi_descriptor_for_type(product, left_rows, right_cols, block_size); + verify_global_matrix(product.gather(), + make_host_matmul_reference(left_rows, + shared_cols, + right_cols)); + EXPECT_EQ(left.desc(), left_descriptor_after); + EXPECT_EQ(right.desc(), right_descriptor_after); + EXPECT_EQ(product.desc(), result_descriptor); +} +#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_distribution + = make_frozen_distribution(5, 3); + Matrix2d transpose_source(transpose_distribution); + 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_distribution + = make_frozen_distribution(5, 4); + const std::shared_ptr right_distribution + = make_frozen_distribution(4, 6); + Matrix2d left(left_distribution); + Matrix2d right(right_distribution); + 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_distribution + = make_frozen_distribution(5, 3); + Matrix2d> complex_transpose_source(complex_transpose_distribution); + 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_distribution + = make_frozen_distribution(5, 4); + const std::shared_ptr complex_right_distribution + = make_frozen_distribution(4, 6); + Matrix2d> complex_left(complex_left_distribution); + Matrix2d> complex_right(complex_right_distribution); + 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 grid_index = 0; grid_index < grids.size(); ++grid_index) + { + check_distributed_transpose(5, 3, + grids[grid_index].first, + grids[grid_index].second, + 3); + check_distributed_transpose(3, 5, + grids[grid_index].first, + grids[grid_index].second, + 3); + check_distributed_transpose>(5, 3, + grids[grid_index].first, + grids[grid_index].second, + 3); + check_distributed_transpose>(3, 5, + grids[grid_index].first, + grids[grid_index].second, + 3); + } +} + +TEST(Matrix2dTest, MatmulDistributedMatchesHost) +{ + const std::vector> grids = available_process_grids(); + for (std::size_t grid_index = 0; grid_index < grids.size(); ++grid_index) + { + check_distributed_matmul(5, 4, 6, + grids[grid_index].first, + grids[grid_index].second, + 3); + check_distributed_matmul>(5, 4, 6, + grids[grid_index].first, + grids[grid_index].second, + 3); + } +} + +TEST(Matrix2dTest, UnsupportedDistributedTypesThrow) +{ + const std::vector> grids = available_process_grids(); + const std::pair& grid = grids[0]; + { + Matrix2d source(5, 3, grid.first, grid.second, 3, MPI_COMM_WORLD); + EXPECT_THROW(source.transpose(), std::invalid_argument); + } + { + Matrix2d source(5, 3, grid.first, grid.second, 3, MPI_COMM_WORLD); + EXPECT_THROW(source.transpose(), std::invalid_argument); + } + { + Matrix2d> source(5, 3, grid.first, grid.second, 3, MPI_COMM_WORLD); + EXPECT_THROW(source.transpose(), std::invalid_argument); + } + { + Matrix2d left(5, 4, grid.first, grid.second, 3, MPI_COMM_WORLD); + Matrix2d right(4, 6, grid.first, grid.second, 3, MPI_COMM_WORLD); + EXPECT_THROW(left.matmul(right), std::invalid_argument); + } + { + Matrix2d left(5, 4, grid.first, grid.second, 3, MPI_COMM_WORLD); + Matrix2d right(4, 6, grid.first, grid.second, 3, MPI_COMM_WORLD); + EXPECT_THROW(left.matmul(right), std::invalid_argument); + } + { + Matrix2d> left(5, 4, grid.first, grid.second, 3, MPI_COMM_WORLD); + Matrix2d> right(4, 6, grid.first, grid.second, 3, MPI_COMM_WORLD); + 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 block = 3; + { + Matrix2d first(8, 6, grid.first, grid.second, block, MPI_COMM_WORLD); + Matrix2d different_block(6, 8, grid.first, grid.second, block + 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, block, MPI_COMM_WORLD); + Matrix2d different_grid(6, 8, other_grid.first, other_grid.second, block, 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, block, MPI_COMM_WORLD); + Matrix2d different_context(6, 8, grid.first, grid.second, block, 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 block = 3; + Matrix2d left(5, 4, grid.first, grid.second, block, MPI_COMM_WORLD); + const int left_blacs_context = left.ictxt(); + const std::shared_ptr right_distribution + = make_frozen_distribution(4, 6, block, left_blacs_context); + Matrix2d right(right_distribution); + fill_global_values(left); + fill_global_values(right, 10.0); + + const int* const left_descriptor = left.desc(); + const int* const right_descriptor = right.desc(); + + const Matrix2d transposed = left.transpose(); + const Matrix2d product = left.matmul(right); + + EXPECT_EQ(left.desc(), left_descriptor); + EXPECT_EQ(right.desc(), right_descriptor); + 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.at_local(0, 0) = 1.0; + source.at_local(0, 1) = 2.0; + source.at_local(1, 0) = 3.0; + source.at_local(1, 1) = 4.0; + + Matrix2d copy(source); + EXPECT_EQ(copy.distribution(), nullptr); + EXPECT_NE(copy.data(), source.data()); + EXPECT_EQ(copy.at_local(1, 1), 4.0); + copy.at_local(1, 1) = 9.0; + EXPECT_EQ(source.at_local(1, 1), 4.0); + + Matrix2d assigned(1, 1); + assigned = source; + EXPECT_NE(assigned.data(), source.data()); + EXPECT_EQ(assigned.at_local(0, 1), 2.0); +} + +TEST(Matrix2dTest, SerialDistributionHandleUsesColumnMajorLayout) +{ + const std::shared_ptr distribution + = make_frozen_distribution(3, 2); + Matrix2d matrix(distribution); + + EXPECT_TRUE(matrix.is_distributed()); + EXPECT_EQ(matrix.distribution().get(), distribution.get()); + EXPECT_EQ(matrix.ictxt(), -1); + check_distribution_layout(matrix, 3, 2); +} + +TEST(Matrix2dTest, CopiesShareDistributionAndDeepCopyStorage) +{ + const std::shared_ptr distribution + = make_frozen_distribution(3, 2); + Matrix2d source(distribution); + source.at_local(0, 0) = 7.0; + + Matrix2d copy(source); + EXPECT_EQ(copy.distribution().get(), distribution.get()); + EXPECT_EQ(source.distribution().get(), copy.distribution().get()); + EXPECT_NE(copy.data(), source.data()); + EXPECT_EQ(copy.at_local(0, 0), 7.0); + copy.at_local(0, 0) = 8.0; + EXPECT_EQ(source.at_local(0, 0), 7.0); +} + +TEST(Matrix2dTest, MatricesFromSameHandleShareContext) +{ + const std::shared_ptr distribution + = make_frozen_distribution(5, 4); + Matrix2d first(distribution); + Matrix2d second(distribution); + + 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 distribution; + EXPECT_THROW( + { + Matrix2d matrix(distribution); + static_cast(matrix); + }, + std::invalid_argument); +} + +#ifdef __MPI +TEST(Matrix2dTest, BlockSizeConstructorAtLocalAndAtGlobal) +{ + const int global_rows = 8; + const int global_cols = 6; + const int block_size = 2; + Matrix2d matrix(global_rows, global_cols, block_size, MPI_COMM_WORLD); + + check_mpi_descriptor(matrix, global_rows, global_cols, block_size); + check_distribution_layout(matrix, global_rows, global_cols); +} + +TEST(Matrix2dTest, UnitBlockConstructorAtLocalAndAtGlobal) +{ + const int global_rows = 5; + const int global_cols = 3; + Matrix2d matrix(global_rows, global_cols, MPI_COMM_WORLD); + + check_mpi_descriptor(matrix, global_rows, global_cols, 1); + check_distribution_layout(matrix, global_rows, global_cols); +} + +TEST(Matrix2dTest, FrozenHandleConstructorSharesBlacsContext) +{ + const int global_rows = 8; + const int global_cols = 6; + const int block_size = 2; + const std::shared_ptr distribution + = make_frozen_distribution(global_rows, global_cols, block_size, MPI_COMM_WORLD); + Matrix2d first(distribution); + Matrix2d second(distribution); + + const int distribution_context = distribution->ictxt(); + EXPECT_GE(distribution_context, 0); + EXPECT_EQ(first.distribution().get(), distribution.get()); + EXPECT_EQ(second.distribution().get(), distribution.get()); + EXPECT_EQ(first.ictxt(), distribution_context); + EXPECT_EQ(second.ictxt(), distribution_context); + check_mpi_descriptor(first, global_rows, global_cols, block_size); +} +#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, SerialDistributionGatherReturnsHostRowMajorCopy) +{ + const std::shared_ptr distribution + = make_frozen_distribution(3, 2); + Matrix2d matrix(distribution); + fill_global_values(matrix); + + const Matrix2d gathered = matrix.gather(); + EXPECT_FALSE(gathered.is_distributed()); + verify_global_matrix(gathered, make_host_reference(3, 2)); + + const Matrix2d root_gathered = matrix.gather_on_root(0); + EXPECT_FALSE(root_gathered.is_distributed()); + 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 blocks[] = {2, 3, 4}; + for (std::size_t grid_index = 0; grid_index < grids.size(); ++grid_index) + { + for (std::size_t block_index = 0; block_index < 3; ++block_index) + { + Matrix2d matrix(9, + 7, + grids[grid_index].first, + grids[grid_index].second, + blocks[block_index], + 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 blocks[] = {2, 3, 4}; + for (std::size_t grid_index = 0; grid_index < grids.size(); ++grid_index) + { + for (std::size_t block_index = 0; block_index < 3; ++block_index) + { + Matrix2d> matrix(9, + 7, + grids[grid_index].first, + grids[grid_index].second, + blocks[block_index], + 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, PaddingDoesNotAffectOperatorsOrGather) +{ + const int number_of_ranks = Parallel_Common::comm_size(MPI_COMM_WORLD); + Matrix2d matrix(9, 4, 1, number_of_ranks, 2, 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 padding_elements = set_padding_sentinel(matrix, sentinel); + ASSERT_GT(padding_elements, 0U); + set_padding_sentinel(other, 12345.5); + + matrix += other; + Matrix2d expected = make_host_reference(9, 4); + const Matrix2d other_reference = make_host_reference(9, 4, 10.0); + for (int row = 0; row < 9; ++row) + { + for (int col = 0; col < 4; ++col) + { + expected.at_local(row, col) += other_reference.at_local(row, col); + } + } + verify_global_matrix(matrix.gather(), expected); + expect_padding_sentinel(matrix, padding_elements, sentinel); + + matrix.fill(2.0); + expect_padding_sentinel(matrix, padding_elements, sentinel); + matrix.scale(3.0); + expect_padding_sentinel(matrix, padding_elements, sentinel); + + const Matrix2d scatter_reference = make_host_reference(9, 4); + matrix.scatter(scatter_reference); + verify_global_matrix(matrix.gather(), scatter_reference); + expect_padding_sentinel(matrix, padding_elements, sentinel); +} + +TEST(Matrix2dTest, RejectsIncompatibleDistributions) +{ + const int number_of_ranks = 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 (number_of_ranks > 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..665ff483245 --- /dev/null +++ b/source/source_base/unittests/test_matrix2d_linalg.cpp @@ -0,0 +1,472 @@ +#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 + +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.at_local(i, j), expected.at_local(i, j)); + } + } +} + +Matrix2d make_real_system() +{ + Matrix2d matrix(2, 2); + matrix.at_local(0, 0) = 4.0; + matrix.at_local(0, 1) = 1.0; + matrix.at_local(1, 0) = 2.0; + matrix.at_local(1, 1) = 3.0; + return matrix; +} + +Matrix2d make_real_inverse_reference() +{ + Matrix2d inverse(2, 2); + inverse.at_local(0, 0) = 0.3; + inverse.at_local(0, 1) = -0.1; + inverse.at_local(1, 0) = -0.2; + inverse.at_local(1, 1) = 0.4; + return inverse; +} + +Matrix2d> make_complex_system() +{ + Matrix2d> matrix(2, 2); + matrix.at_local(0, 0) = std::complex(1.0, 1.0); + matrix.at_local(0, 1) = std::complex(2.0, 0.0); + matrix.at_local(1, 0) = std::complex(3.0, 0.0); + matrix.at_local(1, 1) = std::complex(4.0, -1.0); + return matrix; +} + +Matrix2d> make_complex_solution() +{ + Matrix2d> solution(2, 2); + solution.at_local(0, 0) = std::complex(1.0, 0.0); + solution.at_local(0, 1) = std::complex(0.0, 2.0); + solution.at_local(1, 0) = std::complex(3.0, 0.0); + solution.at_local(1, 1) = std::complex(4.0, 0.0); + return solution; +} + +#ifdef __MPI +std::vector> available_process_grids() +{ + const int number_of_ranks = Parallel_Common::comm_size(MPI_COMM_WORLD); + std::vector> grids; + if (number_of_ranks == 1) + { + grids.push_back(std::make_pair(1, 1)); + } + if (number_of_ranks == 2) + { + grids.push_back(std::make_pair(1, 2)); + grids.push_back(std::make_pair(2, 1)); + } + if (number_of_ranks == 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.at_local(i, j) = 6.0 + i; + } + else if (std::abs(i - j) == 1) + { + matrix.at_local(i, j) = 0.5; + } + else + { + matrix.at_local(i, j) = 0.0; + } + } + } + return matrix; +} + +Matrix2d make_distributed_real_solution(const int rows, + const int cols) +{ + Matrix2d solution(rows, cols); + for (int i = 0; i < rows; ++i) + { + for (int j = 0; j < cols; ++j) + { + solution.at_local(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.at_local(i, j) + = std::complex(6.0 + i, 0.5); + } + else if (j == i + 1) + { + matrix.at_local(i, j) + = std::complex(0.5, 0.25); + } + else if (j + 1 == i) + { + matrix.at_local(i, j) + = std::complex(0.5, -0.25); + } + else + { + matrix.at_local(i, j) = std::complex(0.0, 0.0); + } + } + } + return matrix; +} + +Matrix2d> make_distributed_complex_solution( + const int rows, + const int cols) +{ + Matrix2d> solution(rows, cols); + for (int i = 0; i < rows; ++i) + { + for (int j = 0; j < cols; ++j) + { + solution.at_local(i, j) + = std::complex(1 + i + 2 * j, i - j); + } + } + return solution; +} + +template +void check_distributed_solve(const Matrix2d& host_matrix, + const Matrix2d& host_solution, + const int grid_rows, + const int grid_cols, + const int block_size) +{ + const Matrix2d host_rhs = host_matrix.matmul(host_solution); + Matrix2d matrix(host_matrix.nrglb(), + host_matrix.ncglb(), + grid_rows, + grid_cols, + block_size, + MPI_COMM_WORLD); + const std::shared_ptr solution_dist + = make_frozen_distribution(host_solution.nrglb(), + host_solution.ncglb(), + block_size, + matrix.ictxt()); + const std::shared_ptr rhs_dist + = make_frozen_distribution(host_rhs.nrglb(), + host_rhs.ncglb(), + block_size, + matrix.ictxt()); + Matrix2d solution(solution_dist); + Matrix2d rhs(rhs_dist); + matrix.scatter(host_matrix); + solution.scatter(host_solution); + const Matrix2d& matrix_input = matrix; + const Matrix2d& solution_input = solution; + matrix2d_linalg::matmul(rhs.view(), + matrix_input.view(), + solution_input.view()); + + matrix2d_linalg::solve(matrix.view(), rhs.view()); + + expect_host_matrices_near(rhs.gather(), host_solution); +} + +template +void check_distributed_inverse(const Matrix2d& host_matrix, + const int grid_rows, + const int grid_cols, + const int block_size) +{ + Matrix2d expected = host_matrix; + matrix2d_linalg::inv(expected.view()); + + Matrix2d matrix(host_matrix.nrglb(), + host_matrix.ncglb(), + grid_rows, + grid_cols, + block_size, + MPI_COMM_WORLD); + matrix.scatter(host_matrix); + matrix2d_linalg::inv(matrix.view()); + + expect_host_matrices_near(matrix.gather(), expected); +} +#endif +} // namespace + +TEST(Matrix2dLinalgTest, HostRealInverseAndSolve) +{ + Matrix2d inverse = make_real_system(); + matrix2d_linalg::inv(inverse.view()); + expect_host_matrices_near(inverse, make_real_inverse_reference()); + + Matrix2d rhs(2, 2); + rhs.at_local(0, 0) = 1.0; + rhs.at_local(0, 1) = 2.0; + rhs.at_local(1, 0) = 3.0; + rhs.at_local(1, 1) = 4.0; + const Matrix2d expected = make_real_inverse_reference().matmul(rhs); + Matrix2d matrix = make_real_system(); + matrix2d_linalg::solve(matrix.view(), rhs.view()); + expect_host_matrices_near(rhs, expected); +} + +TEST(Matrix2dLinalgTest, HostComplexSolve) +{ + Matrix2d> matrix = make_complex_system(); + const Matrix2d> expected = make_complex_solution(); + Matrix2d> rhs = matrix.matmul(expected); + + matrix2d_linalg::solve(matrix.view(), rhs.view()); + + expect_host_matrices_near(rhs, expected); + + Matrix2d> inverse = make_complex_system(); + matrix2d_linalg::inv(inverse.view()); + Matrix2d> inverse_reference(2, 2); + inverse_reference.at_local(0, 0) = std::complex(-0.7, -1.1); + inverse_reference.at_local(0, 1) = std::complex(0.2, 0.6); + inverse_reference.at_local(1, 0) = std::complex(0.3, 0.9); + inverse_reference.at_local(1, 1) = std::complex(0.2, -0.4); + expect_host_matrices_near(inverse, inverse_reference); +} + +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.at_local(0, 0) = 1.0; + rhs.at_local(1, 0) = 2.0; + matrix2d_linalg::solve(matrix, rhs.view()); + + expect_near(rhs.at_local(0, 0), 0.1); + expect_near(rhs.at_local(1, 0), 0.6); + EXPECT_EQ(matrix.data(), values.data()); +} + +TEST(Matrix2dLinalgTest, HostViewMatmulAndLinearCombination) +{ + const Matrix2d left = make_real_system(); + const Matrix2d right = make_real_inverse_reference(); + Matrix2d product(2, 2); + matrix2d_linalg::matmul(product.view(), left.view(), right.view()); + expect_host_matrices_near(product, left.matmul(right)); + + Matrix2d combined(2, 2); + matrix2d_linalg::linear_combination( + 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.at_local(i, j) + = 2.0 * left.at_local(i, j) + - 0.5 * right.at_local(i, j); + } + } + expect_host_matrices_near(combined, combined_reference); + + matrix2d_linalg::scale(combined.view(), 3.0); + matrix2d_linalg::set_identity(product.view()); + 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.at_local(i, j), + 3.0 * combined_reference.at_local(i, j)); + expect_near(product.at_local(i, j), identity_value); + } + } +} + +TEST(Matrix2dLinalgTest, RejectsSingularAndMismatchedMatrices) +{ + Matrix2d singular(2, 2); + singular.at_local(0, 0) = 1.0; + singular.at_local(0, 1) = 2.0; + singular.at_local(1, 0) = 2.0; + singular.at_local(1, 1) = 4.0; + EXPECT_THROW(matrix2d_linalg::inv(singular.view()), std::runtime_error); + + Matrix2d matrix = make_real_system(); + Matrix2d wrong_rhs(1, 1); + EXPECT_THROW(matrix2d_linalg::solve(matrix.view(), wrong_rhs.view()), + std::invalid_argument); +} + +#ifdef __MPI +TEST(Matrix2dLinalgTest, DistributedRealAndComplexSolve) +{ + const int size = 5; + const int rhs_columns = 3; + const Matrix2d real_matrix = make_distributed_real_system(size); + const Matrix2d real_solution + = make_distributed_real_solution(size, rhs_columns); + const Matrix2d> complex_matrix + = make_distributed_complex_system(size); + const Matrix2d> complex_solution + = make_distributed_complex_solution(size, rhs_columns); + const std::vector> grids = available_process_grids(); + const int blocks[] = {2, 3}; + for (std::size_t grid_index = 0; grid_index < grids.size(); ++grid_index) + { + for (std::size_t block_index = 0; block_index < 2; ++block_index) + { + check_distributed_solve(real_matrix, + real_solution, + grids[grid_index].first, + grids[grid_index].second, + blocks[block_index]); + check_distributed_solve(complex_matrix, + complex_solution, + grids[grid_index].first, + grids[grid_index].second, + blocks[block_index]); + } + } +} + +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 blocks[] = {2, 3}; + for (std::size_t grid_index = 0; grid_index < grids.size(); ++grid_index) + { + for (std::size_t block_index = 0; block_index < 2; ++block_index) + { + check_distributed_inverse(real_matrix, + grids[grid_index].first, + grids[grid_index].second, + blocks[block_index]); + check_distributed_inverse(complex_matrix, + grids[grid_index].first, + grids[grid_index].second, + blocks[block_index]); + } + } +} + +TEST(Matrix2dLinalgTest, DistributedIdentityAndLinearCombination) +{ + const int size = 5; + const int blocks[] = {2, 3}; + const std::vector> grids = available_process_grids(); + for (std::size_t grid_index = 0; grid_index < grids.size(); ++grid_index) + { + for (std::size_t block_index = 0; block_index < 2; ++block_index) + { + Matrix2d identity(size, + size, + grids[grid_index].first, + grids[grid_index].second, + blocks[block_index], + MPI_COMM_WORLD); + matrix2d_linalg::set_identity(identity.view()); + Matrix2d identity_expected(size, size); + matrix2d_linalg::set_identity(identity_expected.view()); + expect_host_matrices_near(identity.gather(), identity_expected); + + const Matrix2d host_left = make_distributed_real_system(size); + Matrix2d left(identity.distribution()); + Matrix2d combined(identity.distribution()); + left.scatter(host_left); + matrix2d_linalg::linear_combination(combined.view(), + 2.0, + left.view(), + 0.5, + identity.view()); + Matrix2d combined_expected(size, size); + for (int i = 0; i < size; ++i) + { + for (int j = 0; j < size; ++j) + { + combined_expected.at_local(i, j) + = 2.0 * host_left.at_local(i, j) + + 0.5 * identity_expected.at_local(i, j); + } + } + expect_host_matrices_near(combined.gather(), combined_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; +} From 868873e0ffb937f0c5e022b3189b5a18f5f4a8ec Mon Sep 17 00:00:00 2001 From: kirk0830 Date: Sat, 14 Nov 2026 00:08:27 +0800 Subject: [PATCH 02/15] fix(base): make Matrix2d layouts self-owning Retain borrowed BLACS contexts for derived distributed matrices, reject the unused raw-descriptor view path, and route serial frozen layouts through the local linear algebra backend. Add lifetime and serial-layout coverage. --- source/source_base/matrix2d.cpp | 9 +-- source/source_base/matrix2d_lapack.cpp | 8 +-- source/source_base/matrix2d_linalg.cpp | 71 +++++++++++++------ source/source_base/matrix2d_linalg.h | 1 + source/source_base/matrix2d_reduction.cpp | 4 +- source/source_base/matrix2d_view.h | 52 +++++--------- source/source_base/parallel_blkcyc.cpp | 28 ++++++++ source/source_base/parallel_blkcyc.h | 10 +++ .../source_base/unittests/test_matrix2d.cpp | 65 +++++++++++++---- .../unittests/test_matrix2d_linalg.cpp | 30 ++++++++ 10 files changed, 193 insertions(+), 85 deletions(-) diff --git a/source/source_base/matrix2d.cpp b/source/source_base/matrix2d.cpp index 20f682a1e81..33b7e42630d 100644 --- a/source/source_base/matrix2d.cpp +++ b/source/source_base/matrix2d.cpp @@ -329,9 +329,8 @@ NDArray NDArray::transpose() const const int result_rows = ncglb(); const int result_cols = nrglb(); const int nb = dist_->nb(); - const int source_context = dist_->ictxt(); const std::shared_ptr result_dist - = make_frozen_distribution(result_rows, result_cols, nb, source_context); + = make_frozen_distribution(result_rows, result_cols, nb, dist_); Matrix2d result(result_dist); matrix2d_impl::scalapack::transpose(result.view(), view()); return result; @@ -363,9 +362,8 @@ NDArray NDArray::dagger() const const int result_rows = ncglb(); const int result_cols = nrglb(); const int nb = dist_->nb(); - const int source_context = dist_->ictxt(); const std::shared_ptr result_dist - = make_frozen_distribution(result_rows, result_cols, nb, source_context); + = make_frozen_distribution(result_rows, result_cols, nb, dist_); Matrix2d result(result_dist); matrix2d_impl::scalapack::conjugate_transpose(result.view(), view()); return result; @@ -437,9 +435,8 @@ NDArray NDArray::matmul(const NDArray& other) const } const int nb = dist_->nb(); - const int source_context = dist_->ictxt(); const std::shared_ptr result_dist - = make_frozen_distribution(left_rows, result_cols, nb, source_context); + = make_frozen_distribution(left_rows, result_cols, nb, dist_); Matrix2d result(result_dist); matrix2d_impl::scalapack::matmul(result.view(), view(), other.view()); return result; diff --git a/source/source_base/matrix2d_lapack.cpp b/source/source_base/matrix2d_lapack.cpp index 7820bc34a06..a0632b48ed3 100644 --- a/source/source_base/matrix2d_lapack.cpp +++ b/source/source_base/matrix2d_lapack.cpp @@ -12,7 +12,7 @@ namespace { void check_host_layout(const Matrix2dView& matrix) { - if (matrix.is_distributed()) + if (matrix.is_distributed() && !matrix.distribution()->is_serial()) { throw std::invalid_argument("LAPACK requires a host matrix view"); } @@ -20,7 +20,7 @@ void check_host_layout(const Matrix2dView& matrix) void check_host_layout(const Matrix2dView>& matrix) { - if (matrix.is_distributed()) + if (matrix.is_distributed() && !matrix.distribution()->is_serial()) { throw std::invalid_argument("LAPACK requires a host matrix view"); } @@ -182,7 +182,7 @@ void solve(Matrix2dView matrix, } } - const char trans = 'T'; + const char trans = matrix.is_distributed() ? 'N' : 'T'; container::lapackConnector::getrs( /* trans= */ trans, /* n= */ n, @@ -241,7 +241,7 @@ void solve(Matrix2dView> matrix, } } - const char trans = 'T'; + const char trans = matrix.is_distributed() ? 'N' : 'T'; container::lapackConnector::getrs( /* trans= */ trans, /* n= */ n, diff --git a/source/source_base/matrix2d_linalg.cpp b/source/source_base/matrix2d_linalg.cpp index 080ef3f4e10..1a8d227fb38 100644 --- a/source/source_base/matrix2d_linalg.cpp +++ b/source/source_base/matrix2d_linalg.cpp @@ -12,6 +12,18 @@ namespace { +template +bool has_active_distribution(const Matrix2dView& matrix) +{ + return matrix.is_distributed() && !matrix.distribution()->is_serial(); +} + +template +bool has_serial_distribution(const Matrix2dView& matrix) +{ + return matrix.is_distributed() && matrix.distribution()->is_serial(); +} + template void check_same_shape(const Matrix2dView& left, const Matrix2dView& right) @@ -35,6 +47,17 @@ void check_compatible_layout(const Matrix2dView& left, { return; } + const bool left_is_serial = has_serial_distribution(left); + const bool right_is_serial = has_serial_distribution(right); + if (left_is_serial != right_is_serial) + { + throw std::invalid_argument( + "matrix operations require matching serial or parallel distributions"); + } + if (left_is_serial) + { + return; + } if (left.desc() == nullptr || right.desc() == nullptr || left.desc()[1] != right.desc()[1] @@ -122,24 +145,8 @@ void set_identity_impl(Matrix2dView matrix) { throw std::invalid_argument("identity requires a square matrix"); } - std::shared_ptr dist + const std::shared_ptr dist = matrix.distribution(); -#ifdef __MPI - if (matrix.is_distributed() && dist == nullptr) - { - if (matrix.desc() == nullptr) - { - throw std::invalid_argument( - "distributed identity requires a valid descriptor"); - } - const int nb = matrix.desc()[4]; - const int blacs_ctxt = matrix.desc()[1]; - dist = make_frozen_distribution(matrix.nrglb(), - matrix.ncglb(), - nb, - blacs_ctxt); - } -#endif for (int i = 0; i < matrix.nrloc(); ++i) { for (int j = 0; j < matrix.ncloc(); ++j) @@ -182,6 +189,15 @@ void check_solve_views(const Matrix2dView& matrix, throw std::invalid_argument( "linear solve requires matching host or distributed layouts"); } + if (has_serial_distribution(matrix) != has_serial_distribution(rhs)) + { + throw std::invalid_argument( + "linear solve requires matching serial or parallel distributions"); + } + if (has_serial_distribution(matrix)) + { + return; + } if (matrix.is_distributed() && (matrix.desc() == nullptr || rhs.desc() == nullptr @@ -211,6 +227,15 @@ void check_solve_views(const Matrix2dView>& matrix, throw std::invalid_argument( "linear solve requires matching host or distributed layouts"); } + if (has_serial_distribution(matrix) != has_serial_distribution(rhs)) + { + throw std::invalid_argument( + "linear solve requires matching serial or parallel distributions"); + } + if (has_serial_distribution(matrix)) + { + return; + } if (matrix.is_distributed() && (matrix.desc() == nullptr || rhs.desc() == nullptr @@ -231,7 +256,7 @@ namespace matrix2d_linalg void inv(Matrix2dView matrix) { check_inverse_view(matrix); - if (matrix.is_distributed()) + if (has_active_distribution(matrix)) { #ifdef __MPI matrix2d_impl::scalapack::inv(matrix); @@ -246,7 +271,7 @@ void inv(Matrix2dView matrix) void inv(Matrix2dView> matrix) { check_inverse_view(matrix); - if (matrix.is_distributed()) + if (has_active_distribution(matrix)) { #ifdef __MPI matrix2d_impl::scalapack::inv(matrix); @@ -262,7 +287,7 @@ void solve(Matrix2dView matrix, Matrix2dView rhs) { check_solve_views(matrix, rhs); - if (matrix.is_distributed()) + if (has_active_distribution(matrix)) { #ifdef __MPI matrix2d_impl::scalapack::solve(matrix, rhs); @@ -278,7 +303,7 @@ void solve(Matrix2dView> matrix, Matrix2dView> rhs) { check_solve_views(matrix, rhs); - if (matrix.is_distributed()) + if (has_active_distribution(matrix)) { #ifdef __MPI matrix2d_impl::scalapack::solve(matrix, rhs); @@ -295,7 +320,7 @@ void matmul(Matrix2dView result, Matrix2dView right) { check_matmul_views(result, left, right); - if (result.is_distributed()) + if (has_active_distribution(result)) { #ifdef __MPI matrix2d_impl::scalapack::matmul(result, left, right); @@ -312,7 +337,7 @@ void matmul(Matrix2dView> result, Matrix2dView> right) { check_matmul_views(result, left, right); - if (result.is_distributed()) + if (has_active_distribution(result)) { #ifdef __MPI matrix2d_impl::scalapack::matmul(result, left, right); diff --git a/source/source_base/matrix2d_linalg.h b/source/source_base/matrix2d_linalg.h index 71a7a0d1624..bb1a4e4b1da 100644 --- a/source/source_base/matrix2d_linalg.h +++ b/source/source_base/matrix2d_linalg.h @@ -4,6 +4,7 @@ #include "source_base/matrix2d_view.h" #include + namespace matrix2d_linalg { void inv(Matrix2dView matrix); diff --git a/source/source_base/matrix2d_reduction.cpp b/source/source_base/matrix2d_reduction.cpp index aa439ef665b..b4ded3bfa37 100644 --- a/source/source_base/matrix2d_reduction.cpp +++ b/source/source_base/matrix2d_reduction.cpp @@ -275,8 +275,8 @@ std::vector diagonal(const Matrix2d& matrix) const int icglb = dist == nullptr ? icloc : dist->icglb(icloc); if (irglb == icglb && irglb < diagonal_size) { - local_entries.push_back( - std::make_pair(irglb, matrix.at_local(irloc, icloc))); + const T value = matrix.at_local(irloc, icloc); + local_entries.push_back(std::pair(irglb, value)); } } } diff --git a/source/source_base/matrix2d_view.h b/source/source_base/matrix2d_view.h index 4b7d7538efa..21f911c5e7e 100644 --- a/source/source_base/matrix2d_view.h +++ b/source/source_base/matrix2d_view.h @@ -30,7 +30,6 @@ class Matrix2dView nrloc_(other.nrloc()), ncloc_(other.ncloc()), lld_(other.lld()), - distributed_(other.is_distributed()), desc_(other.desc()), dist_(other.distribution()) { @@ -43,8 +42,8 @@ class Matrix2dView nrloc_(nrglb), ncloc_(ncglb), lld_(ncglb), - distributed_(false), - desc_(nullptr) + desc_(nullptr), + dist_(nullptr) { assert(nrglb_ >= 0); assert(ncglb_ >= 0); @@ -54,30 +53,21 @@ class Matrix2dView Matrix2dView(T* data, std::shared_ptr dist) : data_(data), - nrglb_(checked_distribution(dist).nrglb()), - ncglb_(checked_distribution(dist).ncglb()), - nrloc_(checked_distribution(dist).nrloc()), - ncloc_(checked_distribution(dist).ncloc()), - lld_(checked_distribution(dist).lld()), - distributed_(true), - desc_(dist->desc()), + nrglb_(0), + ncglb_(0), + nrloc_(0), + ncloc_(0), + lld_(0), + desc_(nullptr), dist_(std::move(dist)) { - } - - Matrix2dView(T* data, - const int nrloc, - const int ncloc, - const int* desc) - : data_(data), - nrglb_(checked_descriptor(desc)[2]), - ncglb_(checked_descriptor(desc)[3]), - nrloc_(nrloc), - ncloc_(ncloc), - lld_(checked_descriptor(desc)[8]), - distributed_(true), - desc_(desc) - { + const Parallel_Blkcyclic& distribution = checked_distribution(dist_); + nrglb_ = distribution.nrglb(); + ncglb_ = distribution.ncglb(); + nrloc_ = distribution.nrloc(); + ncloc_ = distribution.ncloc(); + lld_ = distribution.lld(); + desc_ = distribution.desc(); } #endif @@ -93,7 +83,7 @@ class Matrix2dView * static_cast(ncloc_); } - bool is_distributed() const { return distributed_; } + bool is_distributed() const { return dist_ != nullptr; } const std::shared_ptr& distribution() const { @@ -130,22 +120,12 @@ class Matrix2dView return *dist; } - static const int* checked_descriptor(const int* desc) - { - if (desc == nullptr) - { - throw std::invalid_argument("matrix view descriptor must not be null"); - } - return desc; - } - T* data_; int nrglb_; int ncglb_; int nrloc_; int ncloc_; int lld_; - bool distributed_; const int* desc_; std::shared_ptr dist_; }; diff --git a/source/source_base/parallel_blkcyc.cpp b/source/source_base/parallel_blkcyc.cpp index 9c92a2485fa..0a9b0ec9eda 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_; @@ -124,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); @@ -149,6 +152,7 @@ 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); @@ -230,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; @@ -278,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 @@ -326,6 +332,28 @@ std::shared_ptr make_frozen_distribution( dist->set(nrglb, ncglb, nb, ictxt); return dist; } + +std::shared_ptr make_frozen_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 dist + = std::make_shared(); + dist->set(nrglb, ncglb, nb, owner->ictxt()); + dist->context_owner_ = owner; + return dist; +} #endif std::shared_ptr make_frozen_distribution( diff --git a/source/source_base/parallel_blkcyc.h b/source/source_base/parallel_blkcyc.h index a3b5a113cae..a70e9a79fdd 100644 --- a/source/source_base/parallel_blkcyc.h +++ b/source/source_base/parallel_blkcyc.h @@ -161,6 +161,9 @@ class Parallel_Blkcyclic make_frozen_distribution(int, int, int, int, int, MPI_Comm); friend std::shared_ptr make_frozen_distribution(int, int, int, int); + friend std::shared_ptr + make_frozen_distribution( + int, int, int, const std::shared_ptr&); #endif static constexpr int DESC_SIZE = 9; @@ -193,6 +196,7 @@ 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); @@ -221,6 +225,12 @@ std::shared_ptr make_frozen_distribution( int ncglb, int nb, int ictxt); + +std::shared_ptr make_frozen_distribution( + int nrglb, + int ncglb, + int nb, + const std::shared_ptr& owner); #endif std::shared_ptr make_frozen_distribution( diff --git a/source/source_base/unittests/test_matrix2d.cpp b/source/source_base/unittests/test_matrix2d.cpp index ed361fda938..6d4afa3f6ad 100644 --- a/source/source_base/unittests/test_matrix2d.cpp +++ b/source/source_base/unittests/test_matrix2d.cpp @@ -234,23 +234,23 @@ void check_mpi_descriptor(Matrix2d& matrix, const int global_cols, const int block_size) { - constexpr int kDescriptorMatrixTypeIndex = 0; - constexpr int kDescriptorBlacsContextIndex = 1; - constexpr int kDescriptorGlobalRowsIndex = 2; - constexpr int kDescriptorGlobalColsIndex = 3; - constexpr int kDescriptorBlockRowsIndex = 4; - constexpr int kDescriptorBlockColsIndex = 5; - constexpr int kDescriptorLeadingDimIndex = 8; + 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 descriptor = matrix.desc(); ASSERT_NE(descriptor, nullptr); - EXPECT_EQ(descriptor[kDescriptorMatrixTypeIndex], 1); - EXPECT_EQ(descriptor[kDescriptorBlacsContextIndex], matrix.ictxt()); - EXPECT_EQ(descriptor[kDescriptorGlobalRowsIndex], global_rows); - EXPECT_EQ(descriptor[kDescriptorGlobalColsIndex], global_cols); - EXPECT_EQ(descriptor[kDescriptorBlockRowsIndex], block_size); - EXPECT_EQ(descriptor[kDescriptorBlockColsIndex], block_size); - EXPECT_EQ(descriptor[kDescriptorLeadingDimIndex], matrix.lld()); + EXPECT_EQ(descriptor[DESCRIPTOR_MATRIX_TYPE_INDEX], 1); + EXPECT_EQ(descriptor[DESCRIPTOR_BLACS_CONTEXT_INDEX], matrix.ictxt()); + EXPECT_EQ(descriptor[DESCRIPTOR_GLOBAL_ROWS_INDEX], global_rows); + EXPECT_EQ(descriptor[DESCRIPTOR_GLOBAL_COLS_INDEX], global_cols); + EXPECT_EQ(descriptor[DESCRIPTOR_BLOCK_ROWS_INDEX], block_size); + EXPECT_EQ(descriptor[DESCRIPTOR_BLOCK_COLS_INDEX], block_size); + EXPECT_EQ(descriptor[DESCRIPTOR_LEADING_DIM_INDEX], matrix.lld()); EXPECT_GE(matrix.ictxt(), 0); EXPECT_EQ(matrix.nrproc() * matrix.ncproc(), Parallel_Common::comm_size(MPI_COMM_WORLD)); @@ -839,6 +839,23 @@ void check_distributed_transpose(const int rows, EXPECT_EQ(dagger.desc(), dagger_descriptor); } +template +Matrix2d make_transpose_without_source(const int rows, + const int cols, + const int grid_rows, + const int grid_cols, + const int block_size) +{ + Matrix2d source(rows, + cols, + grid_rows, + grid_cols, + block_size, + MPI_COMM_WORLD); + fill_global_values(source); + return source.transpose(); +} + template void check_distributed_matmul(const int left_rows, const int shared_cols, @@ -973,6 +990,26 @@ TEST(Matrix2dTest, TransposeAndDaggerDistributedMatchHost) } } +TEST(Matrix2dTest, DistributedResultRetainsBlacsContext) +{ + const std::vector> grids = available_process_grids(); + if (grids.empty()) + { + return; + } + + const int grid_rows = grids.front().first; + const int grid_cols = grids.front().second; + const Matrix2d transposed + = make_transpose_without_source(5, 3, grid_rows, grid_cols, 3); + + ASSERT_TRUE(transposed.is_distributed()); + 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(); diff --git a/source/source_base/unittests/test_matrix2d_linalg.cpp b/source/source_base/unittests/test_matrix2d_linalg.cpp index 665ff483245..aad3b5b2bc9 100644 --- a/source/source_base/unittests/test_matrix2d_linalg.cpp +++ b/source/source_base/unittests/test_matrix2d_linalg.cpp @@ -291,6 +291,36 @@ TEST(Matrix2dLinalgTest, HostComplexSolve) expect_host_matrices_near(inverse, inverse_reference); } +TEST(Matrix2dLinalgTest, SerialDistributionUsesLocalBackend) +{ + const std::shared_ptr distribution + = make_frozen_distribution(2, 2); + + Matrix2d matrix(distribution); + matrix.at_local(0, 0) = 4.0; + matrix.at_local(0, 1) = 1.0; + matrix.at_local(1, 0) = 2.0; + matrix.at_local(1, 1) = 3.0; + + Matrix2d rhs(distribution); + rhs.at_local(0, 0) = 1.0; + rhs.at_local(0, 1) = 2.0; + rhs.at_local(1, 0) = 3.0; + rhs.at_local(1, 1) = 4.0; + const Matrix2d expected = make_real_inverse_reference().matmul(rhs); + + matrix2d_linalg::solve(matrix.view(), rhs.view()); + expect_host_matrices_near(rhs, expected); + + Matrix2d inverse(distribution); + inverse.at_local(0, 0) = 4.0; + inverse.at_local(0, 1) = 1.0; + inverse.at_local(1, 0) = 2.0; + inverse.at_local(1, 1) = 3.0; + matrix2d_linalg::inv(inverse.view()); + expect_host_matrices_near(inverse, make_real_inverse_reference()); +} + TEST(Matrix2dLinalgTest, ExternalBufferViewDoesNotCopy) { std::vector values = {4.0, 1.0, 2.0, 3.0}; From 25fec9923f516c82e1392877c62b836a0402759c Mon Sep 17 00:00:00 2001 From: kirk0830 Date: Sat, 14 Nov 2026 01:54:50 +0800 Subject: [PATCH 03/15] fix(base): avoid Intel MPI communicator overload collision Name borrowed BLACS-context factories separately from communicator-owned factories because Intel MPI defines MPI_Comm as int. Update Matrix2d and tests to use the explicit borrowed-distribution API. --- source/source_base/matrix2d.cpp | 6 +++--- source/source_base/parallel_blkcyc.cpp | 4 ++-- source/source_base/parallel_blkcyc.h | 8 ++++---- source/source_base/unittests/test_matrix2d.cpp | 10 +++++----- .../unittests/test_matrix2d_linalg.cpp | 16 ++++++++-------- 5 files changed, 22 insertions(+), 22 deletions(-) diff --git a/source/source_base/matrix2d.cpp b/source/source_base/matrix2d.cpp index 33b7e42630d..b359e80270a 100644 --- a/source/source_base/matrix2d.cpp +++ b/source/source_base/matrix2d.cpp @@ -330,7 +330,7 @@ NDArray NDArray::transpose() const const int result_cols = nrglb(); const int nb = dist_->nb(); const std::shared_ptr result_dist - = make_frozen_distribution(result_rows, result_cols, nb, dist_); + = make_borrowed_distribution(result_rows, result_cols, nb, dist_); Matrix2d result(result_dist); matrix2d_impl::scalapack::transpose(result.view(), view()); return result; @@ -363,7 +363,7 @@ NDArray NDArray::dagger() const const int result_cols = nrglb(); const int nb = dist_->nb(); const std::shared_ptr result_dist - = make_frozen_distribution(result_rows, result_cols, nb, dist_); + = make_borrowed_distribution(result_rows, result_cols, nb, dist_); Matrix2d result(result_dist); matrix2d_impl::scalapack::conjugate_transpose(result.view(), view()); return result; @@ -436,7 +436,7 @@ NDArray NDArray::matmul(const NDArray& other) const const int nb = dist_->nb(); const std::shared_ptr result_dist - = make_frozen_distribution(left_rows, result_cols, nb, dist_); + = make_borrowed_distribution(left_rows, result_cols, nb, dist_); Matrix2d result(result_dist); matrix2d_impl::scalapack::matmul(result.view(), view(), other.view()); return result; diff --git a/source/source_base/parallel_blkcyc.cpp b/source/source_base/parallel_blkcyc.cpp index 0a9b0ec9eda..297a8eb186d 100644 --- a/source/source_base/parallel_blkcyc.cpp +++ b/source/source_base/parallel_blkcyc.cpp @@ -321,7 +321,7 @@ std::shared_ptr make_frozen_distribution( return dist; } -std::shared_ptr make_frozen_distribution( +std::shared_ptr make_borrowed_distribution( const int nrglb, const int ncglb, const int nb, @@ -333,7 +333,7 @@ std::shared_ptr make_frozen_distribution( return dist; } -std::shared_ptr make_frozen_distribution( +std::shared_ptr make_borrowed_distribution( const int nrglb, const int ncglb, const int nb, diff --git a/source/source_base/parallel_blkcyc.h b/source/source_base/parallel_blkcyc.h index a70e9a79fdd..cbe2c02f831 100644 --- a/source/source_base/parallel_blkcyc.h +++ b/source/source_base/parallel_blkcyc.h @@ -160,9 +160,9 @@ class Parallel_Blkcyclic friend std::shared_ptr make_frozen_distribution(int, int, int, int, int, MPI_Comm); friend std::shared_ptr - make_frozen_distribution(int, int, int, int); + make_borrowed_distribution(int, int, int, int); friend std::shared_ptr - make_frozen_distribution( + make_borrowed_distribution( int, int, int, const std::shared_ptr&); #endif @@ -220,13 +220,13 @@ std::shared_ptr make_frozen_distribution( int nb, MPI_Comm comm); -std::shared_ptr make_frozen_distribution( +std::shared_ptr make_borrowed_distribution( int nrglb, int ncglb, int nb, int ictxt); -std::shared_ptr make_frozen_distribution( +std::shared_ptr make_borrowed_distribution( int nrglb, int ncglb, int nb, diff --git a/source/source_base/unittests/test_matrix2d.cpp b/source/source_base/unittests/test_matrix2d.cpp index 6d4afa3f6ad..47c24fb6442 100644 --- a/source/source_base/unittests/test_matrix2d.cpp +++ b/source/source_base/unittests/test_matrix2d.cpp @@ -872,10 +872,10 @@ void check_distributed_matmul(const int left_rows, MPI_COMM_WORLD); const int left_blacs_context = left.ictxt(); const std::shared_ptr right_distribution - = make_frozen_distribution(shared_cols, - right_cols, - block_size, - left_blacs_context); + = make_borrowed_distribution(shared_cols, + right_cols, + block_size, + left_blacs_context); Matrix2d right(right_distribution); fill_global_values(left); fill_global_values(right, 10.0); @@ -1097,7 +1097,7 @@ TEST(Matrix2dTest, DescriptorAddressStableAcrossOperators) Matrix2d left(5, 4, grid.first, grid.second, block, MPI_COMM_WORLD); const int left_blacs_context = left.ictxt(); const std::shared_ptr right_distribution - = make_frozen_distribution(4, 6, block, left_blacs_context); + = make_borrowed_distribution(4, 6, block, left_blacs_context); Matrix2d right(right_distribution); fill_global_values(left); fill_global_values(right, 10.0); diff --git a/source/source_base/unittests/test_matrix2d_linalg.cpp b/source/source_base/unittests/test_matrix2d_linalg.cpp index aad3b5b2bc9..ecd64f11120 100644 --- a/source/source_base/unittests/test_matrix2d_linalg.cpp +++ b/source/source_base/unittests/test_matrix2d_linalg.cpp @@ -207,15 +207,15 @@ void check_distributed_solve(const Matrix2d& host_matrix, block_size, MPI_COMM_WORLD); const std::shared_ptr solution_dist - = make_frozen_distribution(host_solution.nrglb(), - host_solution.ncglb(), - block_size, - matrix.ictxt()); + = make_borrowed_distribution(host_solution.nrglb(), + host_solution.ncglb(), + block_size, + matrix.ictxt()); const std::shared_ptr rhs_dist - = make_frozen_distribution(host_rhs.nrglb(), - host_rhs.ncglb(), - block_size, - matrix.ictxt()); + = make_borrowed_distribution(host_rhs.nrglb(), + host_rhs.ncglb(), + block_size, + matrix.ictxt()); Matrix2d solution(solution_dist); Matrix2d rhs(rhs_dist); matrix.scatter(host_matrix); From 5db95a7b18881cf5bd6cdc0b130a6b7298459011 Mon Sep 17 00:00:00 2001 From: kirk0830 Date: Wed, 18 Nov 2026 23:43:03 +0800 Subject: [PATCH 04/15] fix(base): address PR bot review findings in Matrix2d Address the blocking findings: preserve serial view layout, support tall/skinny matrix storage, and remove INT_MIN negation UB. Also address non-blocking findings: clarify API contracts, use named locals in conditional call arguments, make matmul tests fail on internal errors instead of passing falsely, and document view overlap constraints. --- source/source_base/matrix2d.cpp | 4 - source/source_base/matrix2d.h | 48 +++- source/source_base/matrix2d_collective.cpp | 55 ++-- source/source_base/matrix2d_linalg.h | 9 + source/source_base/matrix2d_reduction.cpp | 27 +- source/source_base/matrix2d_view.h | 9 +- .../source_base/unittests/test_matrix2d.cpp | 258 +++++++++++++++--- 7 files changed, 324 insertions(+), 86 deletions(-) diff --git a/source/source_base/matrix2d.cpp b/source/source_base/matrix2d.cpp index b359e80270a..8137fe37034 100644 --- a/source/source_base/matrix2d.cpp +++ b/source/source_base/matrix2d.cpp @@ -157,24 +157,20 @@ void matmul(Matrix2dView result, template Matrix2dView NDArray::view() { -#ifdef __MPI if (dist_ != nullptr) { return Matrix2dView(data(), dist_); } -#endif return Matrix2dView(data(), nrglb(), ncglb()); } template Matrix2dView NDArray::view() const { -#ifdef __MPI if (dist_ != nullptr) { return Matrix2dView(data(), dist_); } -#endif return Matrix2dView(data(), nrglb(), ncglb()); } diff --git a/source/source_base/matrix2d.h b/source/source_base/matrix2d.h index df878029580..11117fb0013 100644 --- a/source/source_base/matrix2d.h +++ b/source/source_base/matrix2d.h @@ -114,7 +114,25 @@ class NDArray final 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 payload passed + * by communicator rank zero is read; payloads on other ranks are ignored. + */ void scatter(const NDArray& matglb); T& at_global(const int i, const int j) @@ -239,6 +257,14 @@ class NDArray final ? static_cast(nrloc_) * static_cast(ncloc_) : dist_->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 dist_ == nullptr ? 1 : dist_->nrproc(); } int ncproc() const { return dist_ == nullptr ? 1 : dist_->ncproc(); } int irproc() const { return dist_ == nullptr ? 0 : dist_->irproc(); } @@ -332,12 +358,22 @@ class NDArray final assert(nrloc_ >= 0); assert(ncloc_ >= 0); - const int lld = std::max(nrloc_, 1); - const int ncmax = std::max(ncloc_, lld); - const std::size_t ncm = static_cast(lld) * static_cast(ncloc_); - const std::size_t nrm = static_cast(nrloc_) * static_cast(ncmax); - const std::size_t n = std::max(ncm, nrm); - storage_.resize(n); + const int distribution_lld = dist_->lld(); + const int lld = std::max(distribution_lld, 1); + const std::size_t leading_dimension = static_cast(lld); + // The actual BLACS/LAPACK buffer is column-major. The row-major extent + // is kept in the maximum as a guard for local logical accesses. + const std::size_t column_major_elements + = leading_dimension * static_cast(ncloc_); + const std::size_t row_major_elements + = static_cast(nrloc_) + * static_cast(ncloc_); + const std::size_t logical_extent + = std::max(column_major_elements, row_major_elements); + const std::size_t empty_rank_minimum = 1; + const std::size_t storage_elements + = std::max(logical_extent, empty_rank_minimum); + storage_.resize(storage_elements); } int nrloc_ = 0; diff --git a/source/source_base/matrix2d_collective.cpp b/source/source_base/matrix2d_collective.cpp index 38e03dd5feb..2accf8f327a 100644 --- a/source/source_base/matrix2d_collective.cpp +++ b/source/source_base/matrix2d_collective.cpp @@ -40,13 +40,15 @@ std::vector make_byte_displacements(const std::vector& counts) std::vector allgather_byte_counts(const int local_count, const MPI_Comm comm) { const int nproc = Parallel_Common::comm_size(comm); - std::vector receive_counts(nproc, checked_mpi_count(sizeof(int))); + const int integer_bytes = checked_mpi_count(sizeof(int)); + std::vector receive_counts(nproc, integer_bytes); const std::vector receive_displacements = make_byte_displacements(receive_counts); std::vector counts(nproc, 0); + const int local_count_bytes = checked_mpi_count(sizeof(local_count)); Parallel_Common::allgatherv_bytes(&local_count, - checked_mpi_count(sizeof(local_count)), + local_count_bytes, counts.data(), receive_counts.data(), receive_displacements.data(), @@ -87,7 +89,8 @@ std::vector make_local_payload(const Matrix2d& matrix) const std::size_t data_elements = static_cast(matrix.nrloc()) * static_cast(matrix.ncloc()); const std::size_t data_bytes = data_elements * sizeof(T); - std::vector payload(metadata_bytes + data_bytes); + const std::size_t payload_bytes = metadata_bytes + data_bytes; + std::vector payload(payload_bytes); std::memcpy(payload.data(), metadata.data(), metadata_bytes); for (int irloc = 0; irloc < matrix.nrloc(); ++irloc) @@ -100,9 +103,11 @@ std::vector make_local_payload(const Matrix2d& matrix) = irloc_index * static_cast(matrix.ncloc()) + icloc_index; const T& value = matrix.at_local(irloc, icloc); - std::memcpy(payload.data() + metadata_bytes + element_index * sizeof(T), - &value, - sizeof(T)); + const std::size_t destination_offset + = metadata_bytes + element_index * sizeof(T); + unsigned char* const destination + = payload.data() + destination_offset; + std::memcpy(destination, &value, sizeof(T)); } } return payload; @@ -329,19 +334,23 @@ void scatter_from_host(const Matrix2d& matglb, Matrix2d& matloc) } const std::vector local_meta = make_local_metadata(matloc); + const std::size_t local_metadata_size + = local_meta.size() * sizeof(int); const int local_metadata_bytes - = checked_mpi_count(local_meta.size() * sizeof(int)); + = checked_mpi_count(local_metadata_size); std::vector metadata_counts = allgather_byte_counts(local_metadata_bytes, comm); const std::vector metadata_displacements = make_byte_displacements(metadata_counts); const int metadata_total_bytes = metadata_displacements.back() + metadata_counts.back(); - if (metadata_total_bytes % checked_mpi_count(sizeof(int)) != 0) + const int metadata_element_bytes = checked_mpi_count(sizeof(int)); + if (metadata_total_bytes % metadata_element_bytes != 0) { throw std::invalid_argument("Matrix2d scatter metadata has an invalid byte count"); } - std::vector all_metadata(metadata_total_bytes / sizeof(int)); + const int metadata_elements = metadata_total_bytes / metadata_element_bytes; + std::vector all_metadata(metadata_elements); Parallel_Common::allgatherv_bytes(local_meta.data(), local_metadata_bytes, @@ -393,7 +402,9 @@ void scatter_from_host(const Matrix2d& matglb, Matrix2d& matloc) const std::size_t local_elements = static_cast(view.nrloc) * static_cast(view.ncloc); - send_counts[ipsrc] = checked_mpi_count(local_elements * sizeof(T)); + const std::size_t local_payload_size = local_elements * sizeof(T); + const int local_payload_bytes = checked_mpi_count(local_payload_size); + send_counts[ipsrc] = local_payload_bytes; views.push_back(view); } if (metadata_offset != all_metadata.size()) @@ -425,11 +436,12 @@ void scatter_from_host(const Matrix2d& matglb, Matrix2d& matloc) * static_cast(view.ncloc) + static_cast(icloc); const T& value = matglb.at_local(irglb, icglb); - std::memcpy(send_buffer.data() - + send_displacements[ipdst] - + element_index * sizeof(T), - &value, - sizeof(T)); + const std::size_t send_offset + = static_cast(send_displacements[ipdst]) + + element_index * sizeof(T); + unsigned char* const destination + = send_buffer.data() + send_offset; + std::memcpy(destination, &value, sizeof(T)); } } } @@ -438,13 +450,15 @@ void scatter_from_host(const Matrix2d& matglb, Matrix2d& matloc) const std::size_t receive_elements = static_cast(matloc.nrloc()) * static_cast(matloc.ncloc()); - std::vector receive_buffer(receive_elements * sizeof(T)); + const std::size_t receive_payload_bytes = receive_elements * sizeof(T); + std::vector receive_buffer(receive_payload_bytes); + const int receive_count = checked_mpi_count(receive_payload_bytes); const unsigned char* receive_source = ip == 0 ? send_buffer.data() : nullptr; Parallel_Common::scatterv_bytes(receive_source, send_counts.data(), send_displacements.data(), receive_buffer.data(), - checked_mpi_count(receive_buffer.size()), + receive_count, 0, comm); @@ -456,10 +470,11 @@ void scatter_from_host(const Matrix2d& matglb, Matrix2d& matloc) = static_cast(irloc) * static_cast(matloc.ncloc()) + static_cast(icloc); + const std::size_t receive_offset = element_index * sizeof(T); + const unsigned char* const source + = receive_buffer.data() + receive_offset; T value; - std::memcpy(&value, - receive_buffer.data() + element_index * sizeof(T), - sizeof(T)); + std::memcpy(&value, source, sizeof(T)); matloc.at_local(irloc, icloc) = value; } } diff --git a/source/source_base/matrix2d_linalg.h b/source/source_base/matrix2d_linalg.h index bb1a4e4b1da..c25e530cfc2 100644 --- a/source/source_base/matrix2d_linalg.h +++ b/source/source_base/matrix2d_linalg.h @@ -15,9 +15,18 @@ void solve(Matrix2dView matrix, void solve(Matrix2dView> matrix, Matrix2dView> rhs); +/** + * @brief Multiply two matrix views into result. + * + * The result view must not overlap either input view. The host implementation + * writes result while still reading left and right. + */ void matmul(Matrix2dView result, Matrix2dView left, Matrix2dView right); +/** + * @copydoc matmul(Matrix2dView,Matrix2dView,Matrix2dView) + */ void matmul(Matrix2dView> result, Matrix2dView> left, Matrix2dView> right); diff --git a/source/source_base/matrix2d_reduction.cpp b/source/source_base/matrix2d_reduction.cpp index b4ded3bfa37..53926d36ff0 100644 --- a/source/source_base/matrix2d_reduction.cpp +++ b/source/source_base/matrix2d_reduction.cpp @@ -44,6 +44,19 @@ double absolute_square(const std::complex& value) return real_value * real_value + imaginary_value * imaginary_value; } +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) +{ + return static_cast(std::abs(value)); +} + template void reduce_sum_over_processes(Value& value, const Matrix2d& matrix) { @@ -238,23 +251,23 @@ double norm2(const Matrix2d& matrix) template double max_abs(const Matrix2d& matrix) { - double value = 0.0; + 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 : value) schedule(static) +#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) { - value = std::max( - value, - static_cast(std::abs(matrix.at_local(i, j)))); + const T& element = matrix.at_local(i, j); + const double element_abs = absolute_value(element); + max_value = std::max(max_value, element_abs); } } - reduce_max_over_processes(value, matrix); - return value; + reduce_max_over_processes(max_value, matrix); + return max_value; } template diff --git a/source/source_base/matrix2d_view.h b/source/source_base/matrix2d_view.h index 21f911c5e7e..3c1bfcfb0c2 100644 --- a/source/source_base/matrix2d_view.h +++ b/source/source_base/matrix2d_view.h @@ -13,8 +13,9 @@ /** * @brief Non-owning two-dimensional matrix view. * - * Host views use row-major storage. Distributed views borrow a frozen - * block-cyclic distribution and use its local column-major layout. + * Host views use row-major storage. Views backed by a frozen block-cyclic + * distribution use its local column-major layout, including serial frozen + * distributions in non-MPI builds. */ template class Matrix2dView @@ -49,7 +50,6 @@ class Matrix2dView assert(ncglb_ >= 0); } -#ifdef __MPI Matrix2dView(T* data, std::shared_ptr dist) : data_(data), @@ -67,9 +67,10 @@ class Matrix2dView nrloc_ = distribution.nrloc(); ncloc_ = distribution.ncloc(); lld_ = distribution.lld(); +#ifdef __MPI desc_ = distribution.desc(); - } #endif + } T* data() const { return data_; } int nrglb() const { return nrglb_; } diff --git a/source/source_base/unittests/test_matrix2d.cpp b/source/source_base/unittests/test_matrix2d.cpp index 47c24fb6442..e1c28a3eec7 100644 --- a/source/source_base/unittests/test_matrix2d.cpp +++ b/source/source_base/unittests/test_matrix2d.cpp @@ -6,6 +6,8 @@ #ifdef __MPI #include "source_base/parallel_common.h" +#else +#include "source_base/matrix2d_view.h" #endif #include "gtest/gtest.h" @@ -611,39 +613,66 @@ void check_gather_scatter(Matrix2d& matrix) } template -std::size_t set_padding_sentinel(Matrix2d& matrix, const T& sentinel) +std::size_t expected_local_storage_size(const Matrix2d& matrix) { - const int local_rows = matrix.nrloc(); - const int local_cols = matrix.ncloc(); - const std::size_t leading_dimension - = static_cast(std::max(local_rows, 1)); + const int lld = matrix.lld(); + const int leading_dimension = std::max(lld, 1); const std::size_t column_major_elements - = leading_dimension * static_cast(local_cols); + = static_cast(leading_dimension) + * static_cast(matrix.ncloc()); const std::size_t row_major_elements - = static_cast(local_rows) - * std::max(static_cast(local_cols), leading_dimension); - const std::size_t storage_elements = std::max(column_major_elements, row_major_elements); - const std::size_t logical_elements - = static_cast(local_rows) * static_cast(local_cols); - for (std::size_t index = logical_elements; index < storage_elements; ++index) - { - matrix.data()[index] = sentinel; - } - return storage_elements - logical_elements; + = static_cast(matrix.nrloc()) + * static_cast(matrix.ncloc()); + const std::size_t logical_extent + = std::max(column_major_elements, row_major_elements); + const std::size_t empty_rank_minimum = 1; + return std::max(logical_extent, empty_rank_minimum); } template -void expect_padding_sentinel(const Matrix2d& matrix, - const std::size_t padding_elements, - const T& sentinel) +std::vector set_padding_sentinel(Matrix2d& matrix, + const T& sentinel) { const int local_rows = matrix.nrloc(); const int local_cols = matrix.ncloc(); - const std::size_t logical_elements - = static_cast(local_rows) * static_cast(local_cols); - for (std::size_t index = 0; index < padding_elements; ++index) + const int lld = matrix.lld(); + const std::size_t leading_dimension = static_cast(lld); + const std::size_t storage_elements = expected_local_storage_size(matrix); + std::vector is_logical(storage_elements, 0); + std::vector padding_indices; + for (int local_col = 0; local_col < local_cols; ++local_col) { - expect_scalar_near(matrix.data()[logical_elements + index], sentinel); + for (int local_row = 0; local_row < local_rows; ++local_row) + { + const std::size_t index + = static_cast(local_col) * leading_dimension + + static_cast(local_row); + is_logical[index] = 1; + } + } + for (std::size_t index = 0; index < storage_elements; ++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); } } @@ -1030,31 +1059,68 @@ TEST(Matrix2dTest, UnsupportedDistributedTypesThrow) { const std::vector> grids = available_process_grids(); const std::pair& grid = grids[0]; + const int block_size = 3; { - Matrix2d source(5, 3, grid.first, grid.second, 3, MPI_COMM_WORLD); + Matrix2d source(5, + 3, + grid.first, + grid.second, + block_size, + MPI_COMM_WORLD); EXPECT_THROW(source.transpose(), std::invalid_argument); } { - Matrix2d source(5, 3, grid.first, grid.second, 3, MPI_COMM_WORLD); + Matrix2d source(5, + 3, + grid.first, + grid.second, + block_size, + MPI_COMM_WORLD); EXPECT_THROW(source.transpose(), std::invalid_argument); } { - Matrix2d> source(5, 3, grid.first, grid.second, 3, MPI_COMM_WORLD); + Matrix2d> source(5, + 3, + grid.first, + grid.second, + block_size, + MPI_COMM_WORLD); EXPECT_THROW(source.transpose(), std::invalid_argument); } { - Matrix2d left(5, 4, grid.first, grid.second, 3, MPI_COMM_WORLD); - Matrix2d right(4, 6, grid.first, grid.second, 3, MPI_COMM_WORLD); + Matrix2d left(5, + 4, + grid.first, + grid.second, + block_size, + MPI_COMM_WORLD); + const std::shared_ptr right_distribution + = make_borrowed_distribution(4, 6, block_size, left.ictxt()); + Matrix2d right(right_distribution); EXPECT_THROW(left.matmul(right), std::invalid_argument); } { - Matrix2d left(5, 4, grid.first, grid.second, 3, MPI_COMM_WORLD); - Matrix2d right(4, 6, grid.first, grid.second, 3, MPI_COMM_WORLD); + Matrix2d left(5, + 4, + grid.first, + grid.second, + block_size, + MPI_COMM_WORLD); + const std::shared_ptr right_distribution + = make_borrowed_distribution(4, 6, block_size, left.ictxt()); + Matrix2d right(right_distribution); EXPECT_THROW(left.matmul(right), std::invalid_argument); } { - Matrix2d> left(5, 4, grid.first, grid.second, 3, MPI_COMM_WORLD); - Matrix2d> right(4, 6, grid.first, grid.second, 3, MPI_COMM_WORLD); + Matrix2d> left(5, + 4, + grid.first, + grid.second, + block_size, + MPI_COMM_WORLD); + const std::shared_ptr right_distribution + = make_borrowed_distribution(4, 6, block_size, left.ictxt()); + Matrix2d> right(right_distribution); EXPECT_THROW(left.matmul(right), std::invalid_argument); } } @@ -1156,6 +1222,63 @@ TEST(Matrix2dTest, SerialDistributionHandleUsesColumnMajorLayout) check_distribution_layout(matrix, 3, 2); } +TEST(Matrix2dTest, SerialDistributionTallSkinnyStorageUsesColumnExtent) +{ + const int global_rows = 1024; + const int global_cols = 1; + const std::shared_ptr distribution + = make_frozen_distribution(global_rows, global_cols); + Matrix2d matrix(distribution); + + const std::size_t expected_storage_elements + = static_cast(global_rows) + * static_cast(global_cols); + const std::size_t row_major_elements + = static_cast(matrix.nrloc()) + * static_cast(matrix.ncloc()); + EXPECT_EQ(matrix.local_storage_size(), expected_storage_elements); + EXPECT_LE(row_major_elements, matrix.local_storage_size()); +} + +#ifndef __MPI +TEST(Matrix2dTest, SerialDistributionViewMatchesColumnMajorStorageWithoutMpi) +{ + const std::shared_ptr distribution + = make_frozen_distribution(3, 2); + Matrix2d matrix(distribution); + fill_global_values(matrix); + + Matrix2dView matrix_view = matrix.view(); + ASSERT_TRUE(matrix_view.is_distributed()); + 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 local_row = 0; local_row < matrix.nrloc(); ++local_row) + { + for (int local_col = 0; local_col < matrix.ncloc(); ++local_col) + { + EXPECT_EQ(&matrix_view.at_local(local_row, local_col), + &matrix.at_local(local_row, local_col)); + } + } + + const Matrix2d& const_matrix = matrix; + Matrix2dView const_view = const_matrix.view(); + EXPECT_EQ(const_view.data(), matrix.data()); + for (int local_row = 0; local_row < matrix.nrloc(); ++local_row) + { + for (int local_col = 0; local_col < matrix.ncloc(); ++local_col) + { + EXPECT_EQ(&const_view.at_local(local_row, local_col), + &matrix.at_local(local_row, local_col)); + } + } +} +#endif + TEST(Matrix2dTest, CopiesShareDistributionAndDeepCopyStorage) { const std::shared_ptr distribution @@ -1274,6 +1397,17 @@ TEST(Matrix2dTest, HostComplexElementwiseAndReductions) check_reductions(matrix, other); } +TEST(Matrix2dTest, MaxAbsWidensIntegerBeforeTakingAbsoluteValue) +{ + Matrix2d matrix(1, 2); + matrix.at_local(0, 0) = std::numeric_limits::min(); + matrix.at_local(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, SerialDistributionGatherReturnsHostRowMajorCopy) { const std::shared_ptr distribution @@ -1341,41 +1475,75 @@ TEST(Matrix2dTest, DistributedComplexAcrossBlocksAndProcessGrids) } } -TEST(Matrix2dTest, PaddingDoesNotAffectOperatorsOrGather) +TEST(Matrix2dTest, TallSkinnyPaddingDoesNotAffectOperatorsOrGather) { const int number_of_ranks = Parallel_Common::comm_size(MPI_COMM_WORLD); - Matrix2d matrix(9, 4, 1, number_of_ranks, 2, MPI_COMM_WORLD); + const int global_rows = 1025; + const int global_cols = 3; + const int block_size = 7; + Matrix2d matrix(global_rows, + global_cols, + 1, + number_of_ranks, + block_size, + 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 padding_elements = set_padding_sentinel(matrix, sentinel); - ASSERT_GT(padding_elements, 0U); + const std::size_t expected_storage_elements + = expected_local_storage_size(matrix); + const std::size_t logical_elements + = static_cast(matrix.nrloc()) + * static_cast(matrix.ncloc()); + EXPECT_EQ(matrix.local_storage_size(), expected_storage_elements); + EXPECT_LE(logical_elements, matrix.local_storage_size()); + const std::vector padding_indices + = set_padding_sentinel(matrix, sentinel); + const std::size_t expected_padding_elements + = expected_storage_elements - logical_elements; + EXPECT_EQ(padding_indices.size(), expected_padding_elements); + if (number_of_ranks > 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(9, 4); - const Matrix2d other_reference = make_host_reference(9, 4, 10.0); - for (int row = 0; row < 9; ++row) + Matrix2d expected + = make_host_reference(global_rows, global_cols); + const Matrix2d other_reference + = make_host_reference(global_rows, global_cols, 10.0); + for (int row = 0; row < global_rows; ++row) { - for (int col = 0; col < 4; ++col) + for (int col = 0; col < global_cols; ++col) { expected.at_local(row, col) += other_reference.at_local(row, col); } } verify_global_matrix(matrix.gather(), expected); - expect_padding_sentinel(matrix, padding_elements, sentinel); + expect_padding_sentinel(matrix, padding_indices, sentinel); matrix.fill(2.0); - expect_padding_sentinel(matrix, padding_elements, sentinel); + expect_padding_sentinel(matrix, padding_indices, sentinel); matrix.scale(3.0); - expect_padding_sentinel(matrix, padding_elements, sentinel); + expect_padding_sentinel(matrix, padding_indices, sentinel); - const Matrix2d scatter_reference = make_host_reference(9, 4); + const Matrix2d scatter_reference + = make_host_reference(global_rows, global_cols); matrix.scatter(scatter_reference); verify_global_matrix(matrix.gather(), scatter_reference); - expect_padding_sentinel(matrix, padding_elements, sentinel); + expect_padding_sentinel(matrix, padding_indices, sentinel); } TEST(Matrix2dTest, RejectsIncompatibleDistributions) From afad34366f1a9f488dfcbc1b90720bdd2201e4ab Mon Sep 17 00:00:00 2001 From: kirk0830 Date: Thu, 19 Nov 2026 10:15:35 +0800 Subject: [PATCH 05/15] refactor(base): use domain-conventional variable names in Matrix2d --- source/source_base/matrix2d.cpp | 34 +- source/source_base/matrix2d.h | 8 +- source/source_base/matrix2d_collective.cpp | 146 ++-- source/source_base/matrix2d_reduction.cpp | 36 +- source/source_base/matrix2d_scalapack.cpp | 68 +- source/source_base/matrix2d_view.h | 14 +- .../source_base/unittests/test_matrix2d.cpp | 758 +++++++++--------- .../unittests/test_matrix2d_linalg.cpp | 70 +- 8 files changed, 567 insertions(+), 567 deletions(-) diff --git a/source/source_base/matrix2d.cpp b/source/source_base/matrix2d.cpp index 8137fe37034..c69e5fe676d 100644 --- a/source/source_base/matrix2d.cpp +++ b/source/source_base/matrix2d.cpp @@ -322,11 +322,11 @@ NDArray NDArray::transpose() const } #ifdef __MPI - const int result_rows = ncglb(); - const int result_cols = nrglb(); + const int nr = ncglb(); + const int nc = nrglb(); const int nb = dist_->nb(); const std::shared_ptr result_dist - = make_borrowed_distribution(result_rows, result_cols, nb, dist_); + = make_borrowed_distribution(nr, nc, nb, dist_); Matrix2d result(result_dist); matrix2d_impl::scalapack::transpose(result.view(), view()); return result; @@ -355,11 +355,11 @@ NDArray NDArray::dagger() const } #ifdef __MPI - const int result_rows = ncglb(); - const int result_cols = nrglb(); + const int nr = ncglb(); + const int nc = nrglb(); const int nb = dist_->nb(); const std::shared_ptr result_dist - = make_borrowed_distribution(result_rows, result_cols, nb, dist_); + = make_borrowed_distribution(nr, nc, nb, dist_); Matrix2d result(result_dist); matrix2d_impl::scalapack::conjugate_transpose(result.view(), view()); return result; @@ -372,11 +372,11 @@ NDArray NDArray::dagger() const template NDArray NDArray::matmul(const NDArray& other) const { - const int left_rows = nrglb(); - const int shared_dimension = ncglb(); - const int other_shared_dimension = other.nrglb(); - const int result_cols = other.ncglb(); - if (shared_dimension != other_shared_dimension) + const int m = nrglb(); + const int k = ncglb(); + const int k2 = other.nrglb(); + const int n = other.ncglb(); + if (k != k2) { throw std::invalid_argument("matrix inner dimensions are incompatible"); } @@ -394,18 +394,18 @@ NDArray NDArray::matmul(const NDArray& other) const { // Serial degenerate path: both sides are host or serial frozen // distributions, so matmul degrades to the host triple loop. - Matrix2d result(left_rows, result_cols); + Matrix2d result(m, n); #ifdef _OPENMP #pragma omp parallel for collapse(2) schedule(static) #endif - for (int i = 0; i < left_rows; ++i) + for (int i = 0; i < m; ++i) { - for (int j = 0; j < result_cols; ++j) + for (int j = 0; j < n; ++j) { T value = T(); - for (int k = 0; k < shared_dimension; ++k) + for (int kk = 0; kk < k; ++kk) { - value += at_local(i, k) * other.at_local(k, j); + value += at_local(i, kk) * other.at_local(kk, j); } result.at_local(i, j) = value; } @@ -432,7 +432,7 @@ NDArray NDArray::matmul(const NDArray& other) const const int nb = dist_->nb(); const std::shared_ptr result_dist - = make_borrowed_distribution(left_rows, result_cols, nb, dist_); + = make_borrowed_distribution(m, n, nb, dist_); Matrix2d result(result_dist); matrix2d_impl::scalapack::matmul(result.view(), view(), other.view()); return result; diff --git a/source/source_base/matrix2d.h b/source/source_base/matrix2d.h index 11117fb0013..7b863a96bbe 100644 --- a/source/source_base/matrix2d.h +++ b/source/source_base/matrix2d.h @@ -358,13 +358,13 @@ class NDArray final assert(nrloc_ >= 0); assert(ncloc_ >= 0); - const int distribution_lld = dist_->lld(); - const int lld = std::max(distribution_lld, 1); - const std::size_t leading_dimension = static_cast(lld); + const int distrib_lld = dist_->lld(); + const int lld = std::max(distrib_lld, 1); + const std::size_t ld = static_cast(lld); // The actual BLACS/LAPACK buffer is column-major. The row-major extent // is kept in the maximum as a guard for local logical accesses. const std::size_t column_major_elements - = leading_dimension * static_cast(ncloc_); + = ld * static_cast(ncloc_); const std::size_t row_major_elements = static_cast(nrloc_) * static_cast(ncloc_); diff --git a/source/source_base/matrix2d_collective.cpp b/source/source_base/matrix2d_collective.cpp index 2accf8f327a..d69a124325f 100644 --- a/source/source_base/matrix2d_collective.cpp +++ b/source/source_base/matrix2d_collective.cpp @@ -24,15 +24,15 @@ int checked_mpi_count(const std::size_t count) std::vector make_byte_displacements(const std::vector& counts) { std::vector displacements(counts.size(), 0); - int displacement = 0; + int off = 0; for (std::size_t ip = 0; ip < counts.size(); ++ip) { - displacements[ip] = displacement; - if (counts[ip] > std::numeric_limits::max() - displacement) + displacements[ip] = off; + if (counts[ip] > std::numeric_limits::max() - off) { throw std::invalid_argument("Matrix2d collective payload size overflow"); } - displacement += counts[ip]; + off += counts[ip]; } return displacements; } @@ -41,17 +41,17 @@ std::vector allgather_byte_counts(const int local_count, const MPI_Comm com { const int nproc = Parallel_Common::comm_size(comm); const int integer_bytes = checked_mpi_count(sizeof(int)); - std::vector receive_counts(nproc, integer_bytes); - const std::vector receive_displacements - = make_byte_displacements(receive_counts); + std::vector recv(nproc, integer_bytes); + const std::vector rdispls + = make_byte_displacements(recv); std::vector counts(nproc, 0); const int local_count_bytes = checked_mpi_count(sizeof(local_count)); Parallel_Common::allgatherv_bytes(&local_count, local_count_bytes, counts.data(), - receive_counts.data(), - receive_displacements.data(), + recv.data(), + rdispls.data(), comm); return counts; } @@ -85,28 +85,28 @@ template std::vector make_local_payload(const Matrix2d& matrix) { const std::vector metadata = make_local_metadata(matrix); - const std::size_t metadata_bytes = metadata.size() * sizeof(int); + const std::size_t nmeta = metadata.size() * sizeof(int); const std::size_t data_elements = static_cast(matrix.nrloc()) * static_cast(matrix.ncloc()); const std::size_t data_bytes = data_elements * sizeof(T); - const std::size_t payload_bytes = metadata_bytes + data_bytes; + const std::size_t payload_bytes = nmeta + data_bytes; std::vector payload(payload_bytes); - std::memcpy(payload.data(), metadata.data(), metadata_bytes); + std::memcpy(payload.data(), metadata.data(), nmeta); for (int irloc = 0; irloc < matrix.nrloc(); ++irloc) { for (int icloc = 0; icloc < matrix.ncloc(); ++icloc) { const std::size_t irloc_index = static_cast(irloc); const std::size_t icloc_index = static_cast(icloc); - const std::size_t element_index + const std::size_t idx = irloc_index * static_cast(matrix.ncloc()) + icloc_index; const T& value = matrix.at_local(irloc, icloc); - const std::size_t destination_offset - = metadata_bytes + element_index * sizeof(T); + const std::size_t off + = nmeta + idx * sizeof(T); unsigned char* const destination - = payload.data() + destination_offset; + = payload.data() + off; std::memcpy(destination, &value, sizeof(T)); } } @@ -152,22 +152,22 @@ LocalPayloadView view_local_payload(const std::vector& payload) const std::size_t metadata_count = static_cast(LOCAL_METADATA_SIZE) + view.nrloc + view.ncloc; - const std::size_t metadata_bytes = metadata_count * sizeof(int); + const std::size_t nmeta = metadata_count * sizeof(int); const std::size_t data_elements = static_cast(view.nrloc) * static_cast(view.ncloc); - const std::size_t expected_bytes = metadata_bytes + data_elements * sizeof(T); + const std::size_t expected_bytes = nmeta + data_elements * sizeof(T); if (payload.size() != expected_bytes) { throw std::invalid_argument("Matrix2d collective payload has an invalid size"); } std::vector metadata(metadata_count); - std::memcpy(metadata.data(), payload.data(), metadata_bytes); + std::memcpy(metadata.data(), payload.data(), nmeta); 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 = payload.data() + metadata_bytes; + view.data = payload.data() + nmeta; return view; } @@ -212,12 +212,12 @@ Matrix2d rebuild_global_matrix( { throw std::invalid_argument("Matrix2d column axis is outside global shape"); } - const std::size_t element_index + const std::size_t idx = static_cast(irloc) * static_cast(view.ncloc) + static_cast(icloc); T value; - std::memcpy(&value, view.data + element_index * sizeof(T), sizeof(T)); + std::memcpy(&value, view.data + idx * sizeof(T), sizeof(T)); result.at_local(irglb, icglb) = value; } } @@ -232,25 +232,25 @@ std::vector> allgather_payloads( { const std::vector local_payload = make_local_payload(matrix); const int local_count = checked_mpi_count(local_payload.size()); - std::vector payload_counts = allgather_byte_counts(local_count, comm); - const std::vector payload_displacements - = make_byte_displacements(payload_counts); - const int total_bytes = payload_displacements.back() + payload_counts.back(); + std::vector pcounts = allgather_byte_counts(local_count, comm); + const std::vector pdispls + = make_byte_displacements(pcounts); + const int total_bytes = pdispls.back() + pcounts.back(); std::vector received(total_bytes); Parallel_Common::allgatherv_bytes(local_payload.data(), local_count, received.data(), - payload_counts.data(), - payload_displacements.data(), + pcounts.data(), + pdispls.data(), comm); - std::vector> payloads(payload_counts.size()); - for (std::size_t ip = 0; ip < payload_counts.size(); ++ip) + std::vector> payloads(pcounts.size()); + for (std::size_t ip = 0; ip < pcounts.size(); ++ip) { - const std::size_t begin = static_cast(payload_displacements[ip]); + const std::size_t begin = static_cast(pdispls[ip]); const std::size_t end - = begin + static_cast(payload_counts[ip]); + = begin + static_cast(pcounts[ip]); payloads[ip].assign(received.begin() + begin, received.begin() + end); } return payloads; @@ -281,22 +281,22 @@ std::unique_ptr> gather_on_root(const Matrix2d& matrix, const std::vector local_payload = make_local_payload(matrix); const int local_count = checked_mpi_count(local_payload.size()); - std::vector payload_counts = allgather_byte_counts(local_count, comm); - const std::vector payload_displacements - = make_byte_displacements(payload_counts); - const int total_bytes = payload_displacements.back() + payload_counts.back(); + std::vector pcounts = allgather_byte_counts(local_count, comm); + const std::vector pdispls + = make_byte_displacements(pcounts); + const int total_bytes = pdispls.back() + pcounts.back(); std::vector received; if (ip == iproot) { received.resize(total_bytes); } - unsigned char* const receive_buffer = ip == iproot ? received.data() : nullptr; + unsigned char* const recvbuf = ip == iproot ? received.data() : nullptr; Parallel_Common::gatherv_bytes(local_payload.data(), local_count, - receive_buffer, - payload_counts.data(), - payload_displacements.data(), + recvbuf, + pcounts.data(), + pdispls.data(), iproot, comm); if (ip != iproot) @@ -304,13 +304,13 @@ std::unique_ptr> gather_on_root(const Matrix2d& matrix, return std::unique_ptr>(); } - std::vector> payloads(payload_counts.size()); - for (std::size_t ipsrc = 0; ipsrc < payload_counts.size(); ++ipsrc) + std::vector> payloads(pcounts.size()); + for (std::size_t ipsrc = 0; ipsrc < pcounts.size(); ++ipsrc) { const std::size_t begin - = static_cast(payload_displacements[ipsrc]); + = static_cast(pdispls[ipsrc]); const std::size_t end - = begin + static_cast(payload_counts[ipsrc]); + = begin + static_cast(pcounts[ipsrc]); payloads[ipsrc].assign(received.begin() + begin, received.begin() + end); } return std::unique_ptr>( @@ -336,14 +336,14 @@ void scatter_from_host(const Matrix2d& matglb, Matrix2d& matloc) const std::vector local_meta = make_local_metadata(matloc); const std::size_t local_metadata_size = local_meta.size() * sizeof(int); - const int local_metadata_bytes + const int nmeta = checked_mpi_count(local_metadata_size); - std::vector metadata_counts - = allgather_byte_counts(local_metadata_bytes, comm); - const std::vector metadata_displacements - = make_byte_displacements(metadata_counts); + std::vector mcounts + = allgather_byte_counts(nmeta, comm); + const std::vector mdispls + = make_byte_displacements(mcounts); const int metadata_total_bytes - = metadata_displacements.back() + metadata_counts.back(); + = mdispls.back() + mcounts.back(); const int metadata_element_bytes = checked_mpi_count(sizeof(int)); if (metadata_total_bytes % metadata_element_bytes != 0) { @@ -353,15 +353,15 @@ void scatter_from_host(const Matrix2d& matglb, Matrix2d& matloc) std::vector all_metadata(metadata_elements); Parallel_Common::allgatherv_bytes(local_meta.data(), - local_metadata_bytes, + nmeta, all_metadata.data(), - metadata_counts.data(), - metadata_displacements.data(), + mcounts.data(), + mdispls.data(), comm); const int nproc = Parallel_Common::comm_size(comm); const int ip = Parallel_Common::comm_rank(comm); - std::vector send_counts(nproc, 0); + std::vector send(nproc, 0); std::vector views; views.reserve(nproc); std::size_t metadata_offset = 0; @@ -404,7 +404,7 @@ void scatter_from_host(const Matrix2d& matglb, Matrix2d& matloc) * static_cast(view.ncloc); const std::size_t local_payload_size = local_elements * sizeof(T); const int local_payload_bytes = checked_mpi_count(local_payload_size); - send_counts[ipsrc] = local_payload_bytes; + send[ipsrc] = local_payload_bytes; views.push_back(view); } if (metadata_offset != all_metadata.size()) @@ -416,12 +416,12 @@ void scatter_from_host(const Matrix2d& matglb, Matrix2d& matloc) throw std::invalid_argument("scatter global matrix shape does not match distribution"); } - const std::vector send_displacements = make_byte_displacements(send_counts); - std::vector send_buffer; + const std::vector sdispls = make_byte_displacements(send); + std::vector sendbuf; if (ip == 0) { - const int total_bytes = send_displacements.back() + send_counts.back(); - send_buffer.resize(total_bytes); + const int total_bytes = sdispls.back() + send.back(); + sendbuf.resize(total_bytes); for (int ipdst = 0; ipdst < nproc; ++ipdst) { const LocalPayloadView& view = views[ipdst]; @@ -431,16 +431,16 @@ void scatter_from_host(const Matrix2d& matglb, Matrix2d& matloc) for (int icloc = 0; icloc < view.ncloc; ++icloc) { const int icglb = view.icglb[icloc]; - const std::size_t element_index + const std::size_t idx = static_cast(irloc) * static_cast(view.ncloc) + static_cast(icloc); const T& value = matglb.at_local(irglb, icglb); const std::size_t send_offset - = static_cast(send_displacements[ipdst]) - + element_index * sizeof(T); + = static_cast(sdispls[ipdst]) + + idx * sizeof(T); unsigned char* const destination - = send_buffer.data() + send_offset; + = sendbuf.data() + send_offset; std::memcpy(destination, &value, sizeof(T)); } } @@ -451,14 +451,14 @@ void scatter_from_host(const Matrix2d& matglb, Matrix2d& matloc) = static_cast(matloc.nrloc()) * static_cast(matloc.ncloc()); const std::size_t receive_payload_bytes = receive_elements * sizeof(T); - std::vector receive_buffer(receive_payload_bytes); - const int receive_count = checked_mpi_count(receive_payload_bytes); - const unsigned char* receive_source = ip == 0 ? send_buffer.data() : nullptr; + std::vector recvbuf(receive_payload_bytes); + const int recv = checked_mpi_count(receive_payload_bytes); + const unsigned char* receive_source = ip == 0 ? sendbuf.data() : nullptr; Parallel_Common::scatterv_bytes(receive_source, - send_counts.data(), - send_displacements.data(), - receive_buffer.data(), - receive_count, + send.data(), + sdispls.data(), + recvbuf.data(), + recv, 0, comm); @@ -466,13 +466,13 @@ void scatter_from_host(const Matrix2d& matglb, Matrix2d& matloc) { for (int icloc = 0; icloc < matloc.ncloc(); ++icloc) { - const std::size_t element_index + const std::size_t idx = static_cast(irloc) * static_cast(matloc.ncloc()) + static_cast(icloc); - const std::size_t receive_offset = element_index * sizeof(T); + const std::size_t receive_offset = idx * sizeof(T); const unsigned char* const source - = receive_buffer.data() + receive_offset; + = recvbuf.data() + receive_offset; T value; std::memcpy(&value, source, sizeof(T)); matloc.at_local(irloc, icloc) = value; diff --git a/source/source_base/matrix2d_reduction.cpp b/source/source_base/matrix2d_reduction.cpp index 53926d36ff0..de03f98d125 100644 --- a/source/source_base/matrix2d_reduction.cpp +++ b/source/source_base/matrix2d_reduction.cpp @@ -109,15 +109,15 @@ int checked_mpi_count(const std::size_t count) std::vector make_byte_displacements(const std::vector& counts) { std::vector displacements(counts.size(), 0); - int displacement = 0; + int off = 0; for (std::size_t ip = 0; ip < counts.size(); ++ip) { - displacements[ip] = displacement; - if (counts[ip] > std::numeric_limits::max() - displacement) + displacements[ip] = off; + if (counts[ip] > std::numeric_limits::max() - off) { throw std::invalid_argument("Matrix2d diagonal payload size overflow"); } - displacement += counts[ip]; + off += counts[ip]; } return displacements; } @@ -126,17 +126,17 @@ std::vector make_byte_displacements(const std::vector& counts) std::vector gather_byte_counts(const int local_count, const MPI_Comm comm) { const int nproc = Parallel_Common::comm_size(comm); - const std::vector receive_counts( + const std::vector recv( static_cast(nproc), checked_mpi_count(sizeof(int))); - const std::vector receive_displacements - = make_byte_displacements(receive_counts); + const std::vector rdispls + = make_byte_displacements(recv); std::vector counts(static_cast(nproc), 0); Parallel_Common::allgatherv_bytes(&local_count, checked_mpi_count(sizeof(local_count)), counts.data(), - receive_counts.data(), - receive_displacements.data(), + recv.data(), + rdispls.data(), comm); return counts; } @@ -322,27 +322,27 @@ std::vector diagonal(const Matrix2d& matrix) } const int local_count = checked_mpi_count(local_payload.size()); - const std::vector payload_counts + const std::vector pcounts = gather_byte_counts(local_count, comm); - const std::vector payload_displacements - = make_byte_displacements(payload_counts); + const std::vector pdispls + = make_byte_displacements(pcounts); const int total_bytes - = payload_displacements.back() + payload_counts.back(); + = pdispls.back() + pcounts.back(); std::vector received( static_cast(total_bytes)); Parallel_Common::allgatherv_bytes(local_payload.data(), local_count, received.data(), - payload_counts.data(), - payload_displacements.data(), + pcounts.data(), + pdispls.data(), comm); - for (std::size_t ip = 0; ip < payload_counts.size(); ++ip) + for (std::size_t ip = 0; ip < pcounts.size(); ++ip) { const std::size_t begin - = static_cast(payload_displacements[ip]); + = static_cast(pdispls[ip]); const std::size_t end - = begin + static_cast(payload_counts[ip]); + = begin + static_cast(pcounts[ip]); if (end - begin < sizeof(int)) { throw std::runtime_error( diff --git a/source/source_base/matrix2d_scalapack.cpp b/source/source_base/matrix2d_scalapack.cpp index 76d4c8de043..812e3f5b4a3 100644 --- a/source/source_base/matrix2d_scalapack.cpp +++ b/source/source_base/matrix2d_scalapack.cpp @@ -22,12 +22,12 @@ void transpose(Matrix2dView result, const double* source_data = source.data(); const int ia = 1; const int ja = 1; - const int* source_descriptor = source.desc(); + 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* result_descriptor = result.desc(); + const int* desc_res = result.desc(); ScalapackConnector::tranu( /* m= */ n, /* n= */ m, @@ -35,12 +35,12 @@ void transpose(Matrix2dView result, /* a= */ source_data, /* ia= */ ia, /* ja= */ ja, - /* desca= */ source_descriptor, + /* desca= */ desc_src, /* beta= */ beta, /* c= */ result_data, /* ic= */ ic, /* jc= */ jc, - /* descc= */ result_descriptor); + /* descc= */ desc_res); } void conjugate_transpose(Matrix2dView result, @@ -58,12 +58,12 @@ void transpose(Matrix2dView> result, const std::complex* source_data = source.data(); const int ia = 1; const int ja = 1; - const int* source_descriptor = source.desc(); + 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* result_descriptor = result.desc(); + const int* desc_res = result.desc(); ScalapackConnector::tranu( /* m= */ n, /* n= */ m, @@ -71,12 +71,12 @@ void transpose(Matrix2dView> result, /* a= */ source_data, /* ia= */ ia, /* ja= */ ja, - /* desca= */ source_descriptor, + /* desca= */ desc_src, /* beta= */ beta, /* c= */ result_data, /* ic= */ ic, /* jc= */ jc, - /* descc= */ result_descriptor); + /* descc= */ desc_res); } void conjugate_transpose( @@ -89,12 +89,12 @@ void conjugate_transpose( const std::complex* source_data = source.data(); const int ia = 1; const int ja = 1; - const int* source_descriptor = source.desc(); + 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* result_descriptor = result.desc(); + const int* desc_res = result.desc(); ScalapackConnector::tranc( /* m= */ n, /* n= */ m, @@ -102,12 +102,12 @@ void conjugate_transpose( /* a= */ source_data, /* ia= */ ia, /* ja= */ ja, - /* desca= */ source_descriptor, + /* desca= */ desc_src, /* beta= */ beta, /* c= */ result_data, /* ic= */ ic, /* jc= */ jc, - /* descc= */ result_descriptor); + /* descc= */ desc_res); } namespace @@ -143,8 +143,8 @@ void inv(Matrix2dView matrix) const int n = matrix.nrglb(); const int ia = 1; const int ja = 1; - const int* descriptor = matrix.desc(); - const int pivot_size = matrix.nrloc() + descriptor[4]; + 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, @@ -152,7 +152,7 @@ void inv(Matrix2dView matrix) matrix.data(), ia, ja, - descriptor, + desc, ipiv.data(), &info); check_scalapack_error("ScaLAPACK getrf", info); @@ -165,7 +165,7 @@ void inv(Matrix2dView matrix) matrix.data(), ia, ja, - descriptor, + desc, ipiv.data(), work.data(), &lwork, @@ -181,7 +181,7 @@ void inv(Matrix2dView matrix) matrix.data(), ia, ja, - descriptor, + desc, ipiv.data(), work.data(), &lwork, @@ -196,8 +196,8 @@ void inv(Matrix2dView> matrix) const int n = matrix.nrglb(); const int ia = 1; const int ja = 1; - const int* descriptor = matrix.desc(); - const int pivot_size = matrix.nrloc() + descriptor[4]; + 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, @@ -205,7 +205,7 @@ void inv(Matrix2dView> matrix) matrix.data(), ia, ja, - descriptor, + desc, ipiv.data(), &info); check_scalapack_error("ScaLAPACK getrf", info); @@ -218,7 +218,7 @@ void inv(Matrix2dView> matrix) matrix.data(), ia, ja, - descriptor, + desc, ipiv.data(), work.data(), &lwork, @@ -234,7 +234,7 @@ void inv(Matrix2dView> matrix) matrix.data(), ia, ja, - descriptor, + desc, ipiv.data(), work.data(), &lwork, @@ -311,16 +311,16 @@ void matmul(Matrix2dView result, const double* left_data = left.data(); const int ia = 1; const int ja = 1; - const int* left_descriptor = left.desc(); + 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* right_descriptor = right.desc(); + 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* result_descriptor = result.desc(); + const int* desc_res = result.desc(); ScalapackConnector::gemm( /* transa= */ transa, /* transb= */ transb, @@ -331,16 +331,16 @@ void matmul(Matrix2dView result, /* A= */ left_data, /* IA= */ ia, /* JA= */ ja, - /* DESCA= */ left_descriptor, + /* DESCA= */ desc_lhs, /* B= */ right_data, /* IB= */ ib, /* JB= */ jb, - /* DESCB= */ right_descriptor, + /* DESCB= */ desc_rhs, /* beta= */ beta, /* C= */ result_data, /* IC= */ ic, /* JC= */ jc, - /* DESCC= */ result_descriptor); + /* DESCC= */ desc_res); } void matmul(Matrix2dView> result, @@ -356,16 +356,16 @@ void matmul(Matrix2dView> result, const std::complex* left_data = left.data(); const int ia = 1; const int ja = 1; - const int* left_descriptor = left.desc(); + const int* desc_lhs = left.desc(); const std::complex* right_data = right.data(); const int ib = 1; const int jb = 1; - const int* right_descriptor = right.desc(); + 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* result_descriptor = result.desc(); + const int* desc_res = result.desc(); ScalapackConnector::gemm( /* transa= */ transa, /* transb= */ transb, @@ -376,16 +376,16 @@ void matmul(Matrix2dView> result, /* A= */ left_data, /* IA= */ ia, /* JA= */ ja, - /* DESCA= */ left_descriptor, + /* DESCA= */ desc_lhs, /* B= */ right_data, /* IB= */ ib, /* JB= */ jb, - /* DESCB= */ right_descriptor, + /* DESCB= */ desc_rhs, /* beta= */ beta, /* C= */ result_data, /* IC= */ ic, /* JC= */ jc, - /* DESCC= */ result_descriptor); + /* DESCC= */ desc_res); } } // namespace scalapack diff --git a/source/source_base/matrix2d_view.h b/source/source_base/matrix2d_view.h index 3c1bfcfb0c2..64ac4971418 100644 --- a/source/source_base/matrix2d_view.h +++ b/source/source_base/matrix2d_view.h @@ -61,14 +61,14 @@ class Matrix2dView desc_(nullptr), dist_(std::move(dist)) { - const Parallel_Blkcyclic& distribution = checked_distribution(dist_); - nrglb_ = distribution.nrglb(); - ncglb_ = distribution.ncglb(); - nrloc_ = distribution.nrloc(); - ncloc_ = distribution.ncloc(); - lld_ = distribution.lld(); + const Parallel_Blkcyclic& distrib = checked_distribution(dist_); + nrglb_ = distrib.nrglb(); + ncglb_ = distrib.ncglb(); + nrloc_ = distrib.nrloc(); + ncloc_ = distrib.ncloc(); + lld_ = distrib.lld(); #ifdef __MPI - desc_ = distribution.desc(); + desc_ = distrib.desc(); #endif } diff --git a/source/source_base/unittests/test_matrix2d.cpp b/source/source_base/unittests/test_matrix2d.cpp index e1c28a3eec7..9c8a4689192 100644 --- a/source/source_base/unittests/test_matrix2d.cpp +++ b/source/source_base/unittests/test_matrix2d.cpp @@ -142,16 +142,16 @@ void check_host_layout() EXPECT_EQ(matrix.data(), &matrix.at_local(0, 0)); double value = 1.0; - for (int row = 0; row < 2; ++row) + for (int ir = 0; ir < 2; ++ir) { - for (int col = 0; col < 3; ++col) + for (int ic = 0; ic < 3; ++ic) { - const std::size_t expected_index = static_cast(row) * 3U - + static_cast(col); - EXPECT_EQ(&matrix.at_local(row, col), matrix.data() + expected_index); - EXPECT_EQ(&matrix.at_global(row, col), &matrix.at_local(row, col)); - EXPECT_TRUE(matrix.owns_global_index(row, col)); - matrix.at_local(row, col) = value; + const std::size_t expected_index = static_cast(ir) * 3U + + static_cast(ic); + EXPECT_EQ(&matrix.at_local(ir, ic), matrix.data() + expected_index); + EXPECT_EQ(&matrix.at_global(ir, ic), &matrix.at_local(ir, ic)); + EXPECT_TRUE(matrix.owns_global_index(ir, ic)); + matrix.at_local(ir, ic) = value; value += 1.0; } } @@ -170,59 +170,59 @@ void check_host_layout() } void check_distribution_layout(Matrix2d& matrix, - const int global_rows, - const int global_cols) + const int nrglb, + const int ncglb) { - const std::shared_ptr& distribution + const std::shared_ptr& distrib = matrix.distribution(); - ASSERT_NE(distribution, nullptr); - EXPECT_EQ(matrix.nrglb(), global_rows); - EXPECT_EQ(matrix.ncglb(), global_cols); - EXPECT_EQ(matrix.nrloc(), distribution->nrloc()); - EXPECT_EQ(matrix.ncloc(), distribution->ncloc()); + ASSERT_NE(distrib, nullptr); + 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(), - distribution->size()); - EXPECT_EQ(matrix.nrproc(), distribution->nrproc()); - EXPECT_EQ(matrix.ncproc(), distribution->ncproc()); - EXPECT_EQ(matrix.irproc(), distribution->irproc()); - EXPECT_EQ(matrix.icproc(), distribution->icproc()); - EXPECT_EQ(matrix.lld(), distribution->lld()); - - const int local_rows = matrix.nrloc(); - const int local_cols = matrix.ncloc(); - const std::size_t leading_dimension + 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 local_row = 0; local_row < local_rows; ++local_row) + for (int irloc = 0; irloc < nrloc; ++irloc) { - for (int local_col = 0; local_col < local_cols; ++local_col) + for (int icloc = 0; icloc < ncloc; ++icloc) { const std::size_t expected_index - = static_cast(local_col) * leading_dimension - + static_cast(local_row); - EXPECT_EQ(&matrix.at_local(local_row, local_col), matrix.data() + expected_index); + = static_cast(icloc) * lld + + static_cast(irloc); + EXPECT_EQ(&matrix.at_local(irloc, icloc), matrix.data() + expected_index); } } - for (int global_row = 0; global_row < global_rows; ++global_row) + for (int irglb = 0; irglb < nrglb; ++irglb) { - for (int global_col = 0; global_col < global_cols; ++global_col) + for (int icglb = 0; icglb < ncglb; ++icglb) { - const bool expected_owner = distribution->in_this_processor(global_row, global_col); - EXPECT_EQ(matrix.owns_global_index(global_row, global_col), expected_owner); + const bool expected_owner = distrib->in_this_processor(irglb, icglb); + EXPECT_EQ(matrix.owns_global_index(irglb, icglb), expected_owner); if (!expected_owner) { continue; } - const int local_row = distribution->irloc(global_row); - const int local_col = distribution->icloc(global_col); - ASSERT_NE(local_row, -1); - ASSERT_NE(local_col, -1); - EXPECT_EQ(&matrix.at_global(global_row, global_col), - &matrix.at_local(local_row, local_col)); - const double value = static_cast(global_row * global_cols + global_col); - matrix.at_global(global_row, global_col) = value; - EXPECT_EQ(matrix.at_local(local_row, local_col), value); + const int irloc = distrib->irloc(irglb); + const int icloc = distrib->icloc(icglb); + ASSERT_NE(irloc, -1); + ASSERT_NE(icloc, -1); + EXPECT_EQ(&matrix.at_global(irglb, icglb), + &matrix.at_local(irloc, icloc)); + const double value = static_cast(irglb * ncglb + icglb); + matrix.at_global(irglb, icglb) = value; + EXPECT_EQ(matrix.at_local(irloc, icloc), value); } } @@ -232,9 +232,9 @@ void check_distribution_layout(Matrix2d& matrix, #ifdef __MPI void check_mpi_descriptor(Matrix2d& matrix, - const int global_rows, - const int global_cols, - const int block_size) + const int nrglb, + const int ncglb, + const int nrblk) { constexpr int DESCRIPTOR_MATRIX_TYPE_INDEX = 0; constexpr int DESCRIPTOR_BLACS_CONTEXT_INDEX = 1; @@ -244,15 +244,15 @@ void check_mpi_descriptor(Matrix2d& matrix, constexpr int DESCRIPTOR_BLOCK_COLS_INDEX = 5; constexpr int DESCRIPTOR_LEADING_DIM_INDEX = 8; - const int* const descriptor = matrix.desc(); - ASSERT_NE(descriptor, nullptr); - EXPECT_EQ(descriptor[DESCRIPTOR_MATRIX_TYPE_INDEX], 1); - EXPECT_EQ(descriptor[DESCRIPTOR_BLACS_CONTEXT_INDEX], matrix.ictxt()); - EXPECT_EQ(descriptor[DESCRIPTOR_GLOBAL_ROWS_INDEX], global_rows); - EXPECT_EQ(descriptor[DESCRIPTOR_GLOBAL_COLS_INDEX], global_cols); - EXPECT_EQ(descriptor[DESCRIPTOR_BLOCK_ROWS_INDEX], block_size); - EXPECT_EQ(descriptor[DESCRIPTOR_BLOCK_COLS_INDEX], block_size); - EXPECT_EQ(descriptor[DESCRIPTOR_LEADING_DIM_INDEX], matrix.lld()); + 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)); @@ -285,18 +285,18 @@ double reduction_tolerance>() } template -T test_value(const int row, const int col, const double offset) +T test_value(const int ir, const int ic, const double offset) { - return static_cast(offset + 0.5 + 1.25 * row - 0.75 * col); + return static_cast(offset + 0.5 + 1.25 * ir - 0.75 * ic); } template <> -std::complex test_value>(const int row, - const int col, +std::complex test_value>(const int ir, + const int ic, const double offset) { - return std::complex(offset + 0.5 + 1.25 * row - 0.75 * col, - 0.25 - 0.5 * row + 0.875 * col); + return std::complex(offset + 0.5 + 1.25 * ir - 0.75 * ic, + 0.25 - 0.5 * ir + 0.875 * ic); } template @@ -370,29 +370,29 @@ void expect_scalar_near>( template void fill_global_values(Matrix2d& matrix, const double offset = 0.0) { - for (int row = 0; row < matrix.nrglb(); ++row) + for (int ir = 0; ir < matrix.nrglb(); ++ir) { - for (int col = 0; col < matrix.ncglb(); ++col) + for (int ic = 0; ic < matrix.ncglb(); ++ic) { - if (matrix.owns_global_index(row, col)) + if (matrix.owns_global_index(ir, ic)) { - matrix.at_global(row, col) = test_value(row, col, offset); + matrix.at_global(ir, ic) = test_value(ir, ic, offset); } } } } template -Matrix2d make_host_reference(const int rows, - const int cols, +Matrix2d make_host_reference(const int nr, + const int nc, const double offset = 0.0) { - Matrix2d reference(rows, cols); - for (int row = 0; row < rows; ++row) + Matrix2d reference(nr, nc); + for (int ir = 0; ir < nr; ++ir) { - for (int col = 0; col < cols; ++col) + for (int ic = 0; ic < nc; ++ic) { - reference.at_local(row, col) = test_value(row, col, offset); + reference.at_local(ir, ic) = test_value(ir, ic, offset); } } return reference; @@ -404,16 +404,16 @@ void verify_global_matrix(const Matrix2d& actual, const Matrix2d& expected ASSERT_FALSE(actual.is_distributed()); ASSERT_EQ(actual.nrglb(), expected.nrglb()); ASSERT_EQ(actual.ncglb(), expected.ncglb()); - for (int row = 0; row < expected.nrglb(); ++row) + for (int ir = 0; ir < expected.nrglb(); ++ir) { - for (int col = 0; col < expected.ncglb(); ++col) + for (int ic = 0; ic < expected.ncglb(); ++ic) { const std::size_t c_order_index - = static_cast(row) + = static_cast(ir) * static_cast(expected.ncglb()) - + static_cast(col); + + static_cast(ic); expect_scalar_near(actual.data()[c_order_index], - expected.at_local(row, col)); + expected.at_local(ir, ic)); } } } @@ -421,97 +421,97 @@ void verify_global_matrix(const Matrix2d& actual, const Matrix2d& expected template void check_elementwise_operations(Matrix2d& matrix, Matrix2d& other) { - const int rows = matrix.nrglb(); - const int cols = matrix.ncglb(); + 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(rows, cols); + 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(rows, cols); - for (int row = 0; row < rows; ++row) + expected = make_host_reference(nr, nc); + for (int ir = 0; ir < nr; ++ir) { - for (int col = 0; col < cols; ++col) + for (int ic = 0; ic < nc; ++ic) { - expected.at_local(row, col) *= constant_value(2.5); + expected.at_local(ir, ic) *= constant_value(2.5); } } verify_global_matrix(filled.gather(), expected); filled = matrix; filled += other; - expected = make_host_reference(rows, cols); - Matrix2d expected_other = make_host_reference(rows, cols, 10.0); - for (int row = 0; row < rows; ++row) + 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 col = 0; col < cols; ++col) + for (int ic = 0; ic < nc; ++ic) { - expected.at_local(row, col) += expected_other.at_local(row, col); + expected.at_local(ir, ic) += expected_other.at_local(ir, ic); } } verify_global_matrix(filled.gather(), expected); filled = matrix; filled -= other; - expected = make_host_reference(rows, cols); - for (int row = 0; row < rows; ++row) + expected = make_host_reference(nr, nc); + for (int ir = 0; ir < nr; ++ir) { - for (int col = 0; col < cols; ++col) + for (int ic = 0; ic < nc; ++ic) { - expected.at_local(row, col) -= expected_other.at_local(row, col); + expected.at_local(ir, ic) -= expected_other.at_local(ir, ic); } } verify_global_matrix(filled.gather(), expected); filled = matrix; filled *= other; - expected = make_host_reference(rows, cols); - for (int row = 0; row < rows; ++row) + expected = make_host_reference(nr, nc); + for (int ir = 0; ir < nr; ++ir) { - for (int col = 0; col < cols; ++col) + for (int ic = 0; ic < nc; ++ic) { - expected.at_local(row, col) *= expected_other.at_local(row, col); + expected.at_local(ir, ic) *= expected_other.at_local(ir, ic); } } verify_global_matrix(filled.gather(), expected); filled = matrix; filled.conjugate(); - expected = make_host_reference(rows, cols); - for (int row = 0; row < rows; ++row) + expected = make_host_reference(nr, nc); + for (int ir = 0; ir < nr; ++ir) { - for (int col = 0; col < cols; ++col) + for (int ic = 0; ic < nc; ++ic) { - expected.at_local(row, col) - = conjugate_value(expected.at_local(row, col)); + expected.at_local(ir, ic) + = conjugate_value(expected.at_local(ir, ic)); } } verify_global_matrix(filled.gather(), expected); - Matrix2d expected_real(rows, cols); - Matrix2d expected_imag(rows, cols); - const Matrix2d matrix_reference = make_host_reference(rows, cols); - for (int row = 0; row < rows; ++row) + 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 col = 0; col < cols; ++col) + for (int ic = 0; ic < nc; ++ic) { - const T& value = matrix_reference.at_local(row, col); - expected_real.at_local(row, col) = real_part(value); - expected_imag.at_local(row, col) = imaginary_part(value); + const T& value = matrix_reference.at_local(ir, ic); + expected_real.at_local(ir, ic) = real_part(value); + expected_imag.at_local(ir, ic) = imaginary_part(value); } } Matrix2d real_output = matrix.is_distributed() ? Matrix2d(matrix.distribution()) - : Matrix2d(rows, cols); + : Matrix2d(nr, nc); Matrix2d imaginary_output = matrix.is_distributed() ? Matrix2d(matrix.distribution()) - : Matrix2d(rows, cols); + : Matrix2d(nr, nc); matrix.real(real_output); matrix.imag(imaginary_output); verify_global_matrix(real_output.gather(), expected_real); @@ -534,12 +534,12 @@ void check_reductions(Matrix2d& matrix, Matrix2d& other) T reference_dot = T(); double reference_sum_squares = 0.0; double reference_max_abs = 0.0; - for (int row = 0; row < matrix.nrglb(); ++row) + for (int ir = 0; ir < matrix.nrglb(); ++ir) { - for (int col = 0; col < matrix.ncglb(); ++col) + for (int ic = 0; ic < matrix.ncglb(); ++ic) { - const T& value = matrix_reference.at_local(row, col); - const T& other_value = other_reference.at_local(row, col); + const T& value = matrix_reference.at_local(ir, ic); + const T& other_value = other_reference.at_local(ir, ic); reference_sum += value; reference_dot += conjugate_value(value) * other_value; reference_sum_squares += real_part(value) * real_part(value) @@ -570,19 +570,19 @@ void check_reductions(Matrix2d& matrix, Matrix2d& other) template void check_gather_scatter(Matrix2d& matrix) { - const int rows = matrix.nrglb(); - const int cols = matrix.ncglb(); - const Matrix2d expected = make_host_reference(rows, cols); + 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(rows * cols) * sizeof(T)), + static_cast(nr * nc) * sizeof(T)), 0); const Matrix2d gathered_again = matrix.gather(); EXPECT_EQ(std::memcmp(gathered.data(), gathered_again.data(), - static_cast(rows * cols) * sizeof(T)), + static_cast(nr * nc) * sizeof(T)), 0); Matrix2d restored(matrix.distribution()); @@ -592,9 +592,9 @@ void check_gather_scatter(Matrix2d& matrix) #ifdef __MPI const int rank = Parallel_Common::comm_rank(MPI_COMM_WORLD); - const int root_rank = Parallel_Common::comm_size(MPI_COMM_WORLD) - 1; - const Matrix2d root_result = matrix.gather_on_root(root_rank); - if (rank == root_rank) + 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); } @@ -608,17 +608,17 @@ void check_gather_scatter(Matrix2d& matrix) } #endif - Matrix2d wrong_shape(rows + 1, cols); + 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 = matrix.lld(); - const int leading_dimension = std::max(lld, 1); + const int lld_dist = matrix.lld(); + const int lld = std::max(lld_dist, 1); const std::size_t column_major_elements - = static_cast(leading_dimension) + = static_cast(lld) * static_cast(matrix.ncloc()); const std::size_t row_major_elements = static_cast(matrix.nrloc()) @@ -633,20 +633,20 @@ template std::vector set_padding_sentinel(Matrix2d& matrix, const T& sentinel) { - const int local_rows = matrix.nrloc(); - const int local_cols = matrix.ncloc(); - const int lld = matrix.lld(); - const std::size_t leading_dimension = static_cast(lld); + const int nrloc = matrix.nrloc(); + const int ncloc = matrix.ncloc(); + const int lld_dist = matrix.lld(); + const std::size_t lld = static_cast(lld_dist); const std::size_t storage_elements = expected_local_storage_size(matrix); std::vector is_logical(storage_elements, 0); std::vector padding_indices; - for (int local_col = 0; local_col < local_cols; ++local_col) + for (int icloc = 0; icloc < ncloc; ++icloc) { - for (int local_row = 0; local_row < local_rows; ++local_row) + for (int irloc = 0; irloc < nrloc; ++irloc) { const std::size_t index - = static_cast(local_col) * leading_dimension - + static_cast(local_row); + = static_cast(icloc) * lld + + static_cast(irloc); is_logical[index] = 1; } } @@ -680,20 +680,20 @@ std::vector> available_process_grids() { std::vector> grids; #ifdef __MPI - const int number_of_ranks = Parallel_Common::comm_size(MPI_COMM_WORLD); + const int nproc = Parallel_Common::comm_size(MPI_COMM_WORLD); #else - const int number_of_ranks = 1; + const int nproc = 1; #endif - if (number_of_ranks == 1) + if (nproc == 1) { grids.push_back(std::make_pair(1, 1)); } - if (number_of_ranks == 2) + if (nproc == 2) { grids.push_back(std::make_pair(1, 2)); grids.push_back(std::make_pair(2, 1)); } - if (number_of_ranks == 4) + if (nproc == 4) { grids.push_back(std::make_pair(1, 4)); grids.push_back(std::make_pair(2, 2)); @@ -705,15 +705,15 @@ std::vector> available_process_grids() template Matrix2d make_transpose_reference(const Matrix2d& source) { - const int source_rows = source.nrglb(); - const int source_cols = source.ncglb(); - Matrix2d reference(source_cols, source_rows); - for (int row = 0; row < source_rows; ++row) + const int nr = source.nrglb(); + const int nc = source.ncglb(); + Matrix2d reference(nc, nr); + for (int ir = 0; ir < nr; ++ir) { - for (int col = 0; col < source_cols; ++col) + for (int ic = 0; ic < nc; ++ic) { - reference.at_local(col, row) - = source.at_local(row, col); + reference.at_local(ic, ir) + = source.at_local(ir, ic); } } return reference; @@ -722,15 +722,15 @@ Matrix2d make_transpose_reference(const Matrix2d& source) template Matrix2d make_dagger_reference(const Matrix2d& source) { - const int source_rows = source.nrglb(); - const int source_cols = source.ncglb(); - Matrix2d reference(source_cols, source_rows); - for (int row = 0; row < source_rows; ++row) + const int nr = source.nrglb(); + const int nc = source.ncglb(); + Matrix2d reference(nc, nr); + for (int ir = 0; ir < nr; ++ir) { - for (int col = 0; col < source_cols; ++col) + for (int ic = 0; ic < nc; ++ic) { - reference.at_local(col, row) - = conjugate_value(source.at_local(row, col)); + reference.at_local(ic, ir) + = conjugate_value(source.at_local(ir, ic)); } } return reference; @@ -740,45 +740,45 @@ template Matrix2d make_matmul_reference(const Matrix2d& left, const Matrix2d& right) { - const int rows = left.nrglb(); - const int shared = left.ncglb(); - const int cols = right.ncglb(); - Matrix2d reference(rows, cols); - for (int row = 0; row < rows; ++row) + 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 col = 0; col < cols; ++col) + for (int ic = 0; ic < n; ++ic) { T value = T(); - for (int inner = 0; inner < shared; ++inner) + for (int kk = 0; kk < k; ++kk) { - value += left.at_local(row, inner) * right.at_local(inner, col); + value += left.at_local(ir, kk) * right.at_local(kk, ic); } - reference.at_local(row, col) = value; + reference.at_local(ir, ic) = value; } } return reference; } template -Matrix2d make_host_transpose_reference(const int rows, - const int cols) +Matrix2d make_host_transpose_reference(const int nr, + const int nc) { - return make_transpose_reference(make_host_reference(rows, cols)); + return make_transpose_reference(make_host_reference(nr, nc)); } template -Matrix2d make_host_matmul_reference(const int left_rows, - const int shared_cols, - const int right_cols) +Matrix2d make_host_matmul_reference(const int m, + const int k, + const int n) { - return make_matmul_reference(make_host_reference(left_rows, shared_cols), - make_host_reference(shared_cols, right_cols, 10.0)); + return make_matmul_reference(make_host_reference(m, k), + make_host_reference(k, n, 10.0)); } template -void check_host_transpose(const int rows, const int cols) +void check_host_transpose(const int nr, const int nc) { - const Matrix2d source = make_host_reference(rows, cols); + 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); @@ -788,19 +788,19 @@ void check_host_transpose(const int rows, const int cols) verify_global_matrix(dagger, expected_dagger); EXPECT_FALSE(transposed.is_distributed()); EXPECT_FALSE(dagger.is_distributed()); - EXPECT_EQ(transposed.nrglb(), cols); - EXPECT_EQ(transposed.ncglb(), rows); - EXPECT_EQ(dagger.nrglb(), cols); - EXPECT_EQ(dagger.ncglb(), rows); + 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 left_rows, - const int shared_cols, - const int right_cols) +void check_host_matmul(const int m, + const int k, + const int n) { - const Matrix2d left = make_host_reference(left_rows, shared_cols); - const Matrix2d right = make_host_reference(shared_cols, right_cols, 10.0); + 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); @@ -811,125 +811,125 @@ void check_host_matmul(const int left_rows, #ifdef __MPI template void check_mpi_descriptor_for_type(const Matrix2d& matrix, - const int global_rows, - const int global_cols, - const int block_size) -{ - const int* const descriptor = matrix.desc(); - ASSERT_NE(descriptor, nullptr); - EXPECT_EQ(descriptor[0], 1); - EXPECT_EQ(descriptor[1], matrix.ictxt()); - EXPECT_EQ(descriptor[2], global_rows); - EXPECT_EQ(descriptor[3], global_cols); - EXPECT_EQ(descriptor[4], block_size); - EXPECT_EQ(descriptor[5], block_size); - EXPECT_EQ(descriptor[6], 0); - EXPECT_EQ(descriptor[7], 0); - EXPECT_GT(descriptor[8], 0); + 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 rows, - const int cols, - const int grid_rows, - const int grid_cols, - const int block_size) -{ - Matrix2d source(rows, - cols, - grid_rows, - grid_cols, - block_size, +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 source_descriptor_before = source.desc(); + const int* const desc_src0 = source.desc(); const Matrix2d transposed = source.transpose(); const Matrix2d dagger = source.dagger(); - const int* const source_descriptor_after = source.desc(); - const int* const result_descriptor = transposed.desc(); - const int* const dagger_descriptor = dagger.desc(); + const int* const desc_src1 = source.desc(); + const int* const desc_res = transposed.desc(); + const int* const desc_dag = dagger.desc(); ASSERT_TRUE(transposed.is_distributed()); ASSERT_TRUE(dagger.is_distributed()); - EXPECT_EQ(source_descriptor_after, source_descriptor_before); - EXPECT_NE(result_descriptor, nullptr); - EXPECT_NE(dagger_descriptor, nullptr); + 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, cols, rows, block_size); - check_mpi_descriptor_for_type(dagger, cols, rows, block_size); + 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(rows, cols)); + make_host_transpose_reference(nr, nc)); verify_global_matrix(dagger.gather(), make_dagger_reference(source.gather())); - EXPECT_EQ(source.desc(), source_descriptor_after); - EXPECT_EQ(transposed.desc(), result_descriptor); - EXPECT_EQ(dagger.desc(), dagger_descriptor); + 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 rows, - const int cols, - const int grid_rows, - const int grid_cols, - const int block_size) -{ - Matrix2d source(rows, - cols, - grid_rows, - grid_cols, - block_size, +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 left_rows, - const int shared_cols, - const int right_cols, - const int grid_rows, - const int grid_cols, - const int block_size) -{ - Matrix2d left(left_rows, - shared_cols, - grid_rows, - grid_cols, - block_size, +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 left_blacs_context = left.ictxt(); - const std::shared_ptr right_distribution - = make_borrowed_distribution(shared_cols, - right_cols, - block_size, - left_blacs_context); - Matrix2d right(right_distribution); + 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 left_descriptor_before = left.desc(); - const int* const right_descriptor_before = right.desc(); + const int* const desc_lhs0 = left.desc(); + const int* const desc_rhs0 = right.desc(); const Matrix2d product = left.matmul(right); - const int* const left_descriptor_after = left.desc(); - const int* const right_descriptor_after = right.desc(); - const int* const result_descriptor = product.desc(); + const int* const desc_lhs1 = left.desc(); + const int* const desc_rhs1 = right.desc(); + const int* const desc_res = product.desc(); ASSERT_TRUE(product.is_distributed()); - EXPECT_EQ(left_descriptor_after, left_descriptor_before); - EXPECT_EQ(right_descriptor_after, right_descriptor_before); - EXPECT_NE(result_descriptor, nullptr); + 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, left_rows, right_cols, block_size); + check_mpi_descriptor_for_type(product, m, n, nrblk); verify_global_matrix(product.gather(), - make_host_matmul_reference(left_rows, - shared_cols, - right_cols)); - EXPECT_EQ(left.desc(), left_descriptor_after); - EXPECT_EQ(right.desc(), right_descriptor_after); - EXPECT_EQ(product.desc(), result_descriptor); + 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 @@ -950,29 +950,29 @@ TEST(Matrix2dTest, HostMatmulMatchesTripleLoopReference) TEST(Matrix2dTest, SerialDegenerateDistributionTransposeAndMatmul) { - const std::shared_ptr transpose_distribution + const std::shared_ptr transpose_distrib = make_frozen_distribution(5, 3); - Matrix2d transpose_source(transpose_distribution); + 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_distribution + const std::shared_ptr left_distrib = make_frozen_distribution(5, 4); - const std::shared_ptr right_distribution + const std::shared_ptr right_distrib = make_frozen_distribution(4, 6); - Matrix2d left(left_distribution); - Matrix2d right(right_distribution); + 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_distribution + const std::shared_ptr complex_transpose_distrib = make_frozen_distribution(5, 3); - Matrix2d> complex_transpose_source(complex_transpose_distribution); + Matrix2d> complex_transpose_source(complex_transpose_distrib); fill_global_values(complex_transpose_source); verify_global_matrix( complex_transpose_source.transpose().gather(), @@ -981,12 +981,12 @@ TEST(Matrix2dTest, SerialDegenerateDistributionTransposeAndMatmul) complex_transpose_source.dagger().gather(), make_dagger_reference(complex_transpose_source.gather())); - const std::shared_ptr complex_left_distribution + const std::shared_ptr complex_left_distrib = make_frozen_distribution(5, 4); - const std::shared_ptr complex_right_distribution + const std::shared_ptr complex_right_distrib = make_frozen_distribution(4, 6); - Matrix2d> complex_left(complex_left_distribution); - Matrix2d> complex_right(complex_right_distribution); + 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( @@ -1027,10 +1027,10 @@ TEST(Matrix2dTest, DistributedResultRetainsBlacsContext) return; } - const int grid_rows = grids.front().first; - const int grid_cols = grids.front().second; + const int nrproc = grids.front().first; + const int ncproc = grids.front().second; const Matrix2d transposed - = make_transpose_without_source(5, 3, grid_rows, grid_cols, 3); + = make_transpose_without_source(5, 3, nrproc, ncproc, 3); ASSERT_TRUE(transposed.is_distributed()); ASSERT_NE(transposed.distribution(), nullptr); @@ -1059,13 +1059,13 @@ TEST(Matrix2dTest, UnsupportedDistributedTypesThrow) { const std::vector> grids = available_process_grids(); const std::pair& grid = grids[0]; - const int block_size = 3; + const int nrblk = 3; { Matrix2d source(5, 3, grid.first, grid.second, - block_size, + nrblk, MPI_COMM_WORLD); EXPECT_THROW(source.transpose(), std::invalid_argument); } @@ -1074,7 +1074,7 @@ TEST(Matrix2dTest, UnsupportedDistributedTypesThrow) 3, grid.first, grid.second, - block_size, + nrblk, MPI_COMM_WORLD); EXPECT_THROW(source.transpose(), std::invalid_argument); } @@ -1083,7 +1083,7 @@ TEST(Matrix2dTest, UnsupportedDistributedTypesThrow) 3, grid.first, grid.second, - block_size, + nrblk, MPI_COMM_WORLD); EXPECT_THROW(source.transpose(), std::invalid_argument); } @@ -1092,11 +1092,11 @@ TEST(Matrix2dTest, UnsupportedDistributedTypesThrow) 4, grid.first, grid.second, - block_size, + nrblk, MPI_COMM_WORLD); - const std::shared_ptr right_distribution - = make_borrowed_distribution(4, 6, block_size, left.ictxt()); - Matrix2d right(right_distribution); + 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); } { @@ -1104,11 +1104,11 @@ TEST(Matrix2dTest, UnsupportedDistributedTypesThrow) 4, grid.first, grid.second, - block_size, + nrblk, MPI_COMM_WORLD); - const std::shared_ptr right_distribution - = make_borrowed_distribution(4, 6, block_size, left.ictxt()); - Matrix2d right(right_distribution); + 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); } { @@ -1116,11 +1116,11 @@ TEST(Matrix2dTest, UnsupportedDistributedTypesThrow) 4, grid.first, grid.second, - block_size, + nrblk, MPI_COMM_WORLD); - const std::shared_ptr right_distribution - = make_borrowed_distribution(4, 6, block_size, left.ictxt()); - Matrix2d> right(right_distribution); + 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); } } @@ -1161,21 +1161,21 @@ TEST(Matrix2dTest, DescriptorAddressStableAcrossOperators) const std::pair& grid = grids[0]; const int block = 3; Matrix2d left(5, 4, grid.first, grid.second, block, MPI_COMM_WORLD); - const int left_blacs_context = left.ictxt(); - const std::shared_ptr right_distribution - = make_borrowed_distribution(4, 6, block, left_blacs_context); - Matrix2d right(right_distribution); + const int ictxt = left.ictxt(); + const std::shared_ptr right_distrib + = make_borrowed_distribution(4, 6, block, ictxt); + Matrix2d right(right_distrib); fill_global_values(left); fill_global_values(right, 10.0); - const int* const left_descriptor = left.desc(); - const int* const right_descriptor = right.desc(); + 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(), left_descriptor); - EXPECT_EQ(right.desc(), right_descriptor); + EXPECT_EQ(left.desc(), desc_lhs); + EXPECT_EQ(right.desc(), desc_rhs); EXPECT_EQ(left.ictxt(), transposed.ictxt()); EXPECT_EQ(left.ictxt(), product.ictxt()); @@ -1212,27 +1212,27 @@ TEST(Matrix2dTest, HostCopyDeepCopiesStorage) TEST(Matrix2dTest, SerialDistributionHandleUsesColumnMajorLayout) { - const std::shared_ptr distribution + const std::shared_ptr distrib = make_frozen_distribution(3, 2); - Matrix2d matrix(distribution); + Matrix2d matrix(distrib); EXPECT_TRUE(matrix.is_distributed()); - EXPECT_EQ(matrix.distribution().get(), distribution.get()); + EXPECT_EQ(matrix.distribution().get(), distrib.get()); EXPECT_EQ(matrix.ictxt(), -1); check_distribution_layout(matrix, 3, 2); } TEST(Matrix2dTest, SerialDistributionTallSkinnyStorageUsesColumnExtent) { - const int global_rows = 1024; - const int global_cols = 1; - const std::shared_ptr distribution - = make_frozen_distribution(global_rows, global_cols); - Matrix2d matrix(distribution); + 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 expected_storage_elements - = static_cast(global_rows) - * static_cast(global_cols); + = static_cast(nrglb) + * static_cast(ncglb); const std::size_t row_major_elements = static_cast(matrix.nrloc()) * static_cast(matrix.ncloc()); @@ -1243,9 +1243,9 @@ TEST(Matrix2dTest, SerialDistributionTallSkinnyStorageUsesColumnExtent) #ifndef __MPI TEST(Matrix2dTest, SerialDistributionViewMatchesColumnMajorStorageWithoutMpi) { - const std::shared_ptr distribution + const std::shared_ptr distrib = make_frozen_distribution(3, 2); - Matrix2d matrix(distribution); + Matrix2d matrix(distrib); fill_global_values(matrix); Matrix2dView matrix_view = matrix.view(); @@ -1256,24 +1256,24 @@ TEST(Matrix2dTest, SerialDistributionViewMatchesColumnMajorStorageWithoutMpi) EXPECT_EQ(matrix_view.ncloc(), matrix.ncloc()); EXPECT_EQ(matrix_view.lld(), matrix.lld()); EXPECT_EQ(matrix_view.data(), matrix.data()); - for (int local_row = 0; local_row < matrix.nrloc(); ++local_row) + for (int irloc = 0; irloc < matrix.nrloc(); ++irloc) { - for (int local_col = 0; local_col < matrix.ncloc(); ++local_col) + for (int icloc = 0; icloc < matrix.ncloc(); ++icloc) { - EXPECT_EQ(&matrix_view.at_local(local_row, local_col), - &matrix.at_local(local_row, local_col)); + EXPECT_EQ(&matrix_view.at_local(irloc, icloc), + &matrix.at_local(irloc, icloc)); } } const Matrix2d& const_matrix = matrix; Matrix2dView const_view = const_matrix.view(); EXPECT_EQ(const_view.data(), matrix.data()); - for (int local_row = 0; local_row < matrix.nrloc(); ++local_row) + for (int irloc = 0; irloc < matrix.nrloc(); ++irloc) { - for (int local_col = 0; local_col < matrix.ncloc(); ++local_col) + for (int icloc = 0; icloc < matrix.ncloc(); ++icloc) { - EXPECT_EQ(&const_view.at_local(local_row, local_col), - &matrix.at_local(local_row, local_col)); + EXPECT_EQ(&const_view.at_local(irloc, icloc), + &matrix.at_local(irloc, icloc)); } } } @@ -1281,13 +1281,13 @@ TEST(Matrix2dTest, SerialDistributionViewMatchesColumnMajorStorageWithoutMpi) TEST(Matrix2dTest, CopiesShareDistributionAndDeepCopyStorage) { - const std::shared_ptr distribution + const std::shared_ptr distrib = make_frozen_distribution(3, 2); - Matrix2d source(distribution); + Matrix2d source(distrib); source.at_local(0, 0) = 7.0; Matrix2d copy(source); - EXPECT_EQ(copy.distribution().get(), distribution.get()); + EXPECT_EQ(copy.distribution().get(), distrib.get()); EXPECT_EQ(source.distribution().get(), copy.distribution().get()); EXPECT_NE(copy.data(), source.data()); EXPECT_EQ(copy.at_local(0, 0), 7.0); @@ -1297,10 +1297,10 @@ TEST(Matrix2dTest, CopiesShareDistributionAndDeepCopyStorage) TEST(Matrix2dTest, MatricesFromSameHandleShareContext) { - const std::shared_ptr distribution + const std::shared_ptr distrib = make_frozen_distribution(5, 4); - Matrix2d first(distribution); - Matrix2d second(distribution); + Matrix2d first(distrib); + Matrix2d second(distrib); EXPECT_EQ(first.distribution().get(), second.distribution().get()); EXPECT_EQ(first.ictxt(), second.ictxt()); @@ -1309,10 +1309,10 @@ TEST(Matrix2dTest, MatricesFromSameHandleShareContext) TEST(Matrix2dTest, RejectsNullDistribution) { - const std::shared_ptr distribution; + const std::shared_ptr distrib; EXPECT_THROW( { - Matrix2d matrix(distribution); + Matrix2d matrix(distrib); static_cast(matrix); }, std::invalid_argument); @@ -1321,42 +1321,42 @@ TEST(Matrix2dTest, RejectsNullDistribution) #ifdef __MPI TEST(Matrix2dTest, BlockSizeConstructorAtLocalAndAtGlobal) { - const int global_rows = 8; - const int global_cols = 6; - const int block_size = 2; - Matrix2d matrix(global_rows, global_cols, block_size, MPI_COMM_WORLD); + const int nrglb = 8; + const int ncglb = 6; + const int nrblk = 2; + Matrix2d matrix(nrglb, ncglb, nrblk, MPI_COMM_WORLD); - check_mpi_descriptor(matrix, global_rows, global_cols, block_size); - check_distribution_layout(matrix, global_rows, global_cols); + check_mpi_descriptor(matrix, nrglb, ncglb, nrblk); + check_distribution_layout(matrix, nrglb, ncglb); } TEST(Matrix2dTest, UnitBlockConstructorAtLocalAndAtGlobal) { - const int global_rows = 5; - const int global_cols = 3; - Matrix2d matrix(global_rows, global_cols, MPI_COMM_WORLD); + const int nrglb = 5; + const int ncglb = 3; + Matrix2d matrix(nrglb, ncglb, MPI_COMM_WORLD); - check_mpi_descriptor(matrix, global_rows, global_cols, 1); - check_distribution_layout(matrix, global_rows, global_cols); + check_mpi_descriptor(matrix, nrglb, ncglb, 1); + check_distribution_layout(matrix, nrglb, ncglb); } TEST(Matrix2dTest, FrozenHandleConstructorSharesBlacsContext) { - const int global_rows = 8; - const int global_cols = 6; - const int block_size = 2; - const std::shared_ptr distribution - = make_frozen_distribution(global_rows, global_cols, block_size, MPI_COMM_WORLD); - Matrix2d first(distribution); - Matrix2d second(distribution); - - const int distribution_context = distribution->ictxt(); - EXPECT_GE(distribution_context, 0); - EXPECT_EQ(first.distribution().get(), distribution.get()); - EXPECT_EQ(second.distribution().get(), distribution.get()); - EXPECT_EQ(first.ictxt(), distribution_context); - EXPECT_EQ(second.ictxt(), distribution_context); - check_mpi_descriptor(first, global_rows, global_cols, block_size); + 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 @@ -1410,9 +1410,9 @@ TEST(Matrix2dTest, MaxAbsWidensIntegerBeforeTakingAbsoluteValue) TEST(Matrix2dTest, SerialDistributionGatherReturnsHostRowMajorCopy) { - const std::shared_ptr distribution + const std::shared_ptr distrib = make_frozen_distribution(3, 2); - Matrix2d matrix(distribution); + Matrix2d matrix(distrib); fill_global_values(matrix); const Matrix2d gathered = matrix.gather(); @@ -1477,15 +1477,15 @@ TEST(Matrix2dTest, DistributedComplexAcrossBlocksAndProcessGrids) TEST(Matrix2dTest, TallSkinnyPaddingDoesNotAffectOperatorsOrGather) { - const int number_of_ranks = Parallel_Common::comm_size(MPI_COMM_WORLD); - const int global_rows = 1025; - const int global_cols = 3; - const int block_size = 7; - Matrix2d matrix(global_rows, - global_cols, + 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, - number_of_ranks, - block_size, + nproc, + nrblk, MPI_COMM_WORLD); Matrix2d other(matrix.distribution()); fill_global_values(matrix); @@ -1504,7 +1504,7 @@ TEST(Matrix2dTest, TallSkinnyPaddingDoesNotAffectOperatorsOrGather) const std::size_t expected_padding_elements = expected_storage_elements - logical_elements; EXPECT_EQ(padding_indices.size(), expected_padding_elements); - if (number_of_ranks > 1) + if (nproc > 1) { if (matrix.icproc() == 0) { @@ -1521,14 +1521,14 @@ TEST(Matrix2dTest, TallSkinnyPaddingDoesNotAffectOperatorsOrGather) matrix += other; Matrix2d expected - = make_host_reference(global_rows, global_cols); + = make_host_reference(nrglb, ncglb); const Matrix2d other_reference - = make_host_reference(global_rows, global_cols, 10.0); - for (int row = 0; row < global_rows; ++row) + = make_host_reference(nrglb, ncglb, 10.0); + for (int ir = 0; ir < nrglb; ++ir) { - for (int col = 0; col < global_cols; ++col) + for (int ic = 0; ic < ncglb; ++ic) { - expected.at_local(row, col) += other_reference.at_local(row, col); + expected.at_local(ir, ic) += other_reference.at_local(ir, ic); } } verify_global_matrix(matrix.gather(), expected); @@ -1540,7 +1540,7 @@ TEST(Matrix2dTest, TallSkinnyPaddingDoesNotAffectOperatorsOrGather) expect_padding_sentinel(matrix, padding_indices, sentinel); const Matrix2d scatter_reference - = make_host_reference(global_rows, global_cols); + = make_host_reference(nrglb, ncglb); matrix.scatter(scatter_reference); verify_global_matrix(matrix.gather(), scatter_reference); expect_padding_sentinel(matrix, padding_indices, sentinel); @@ -1548,7 +1548,7 @@ TEST(Matrix2dTest, TallSkinnyPaddingDoesNotAffectOperatorsOrGather) TEST(Matrix2dTest, RejectsIncompatibleDistributions) { - const int number_of_ranks = Parallel_Common::comm_size(MPI_COMM_WORLD); + const int nproc = Parallel_Common::comm_size(MPI_COMM_WORLD); const std::vector> grids = available_process_grids(); Matrix2d first(8, 6, @@ -1576,7 +1576,7 @@ TEST(Matrix2dTest, RejectsIncompatibleDistributions) EXPECT_THROW(first += host, std::invalid_argument); EXPECT_THROW(first.dot(host), std::invalid_argument); - if (number_of_ranks > 1) + if (nproc > 1) { const std::pair& other_grid = grids[1]; Matrix2d different_grid(8, diff --git a/source/source_base/unittests/test_matrix2d_linalg.cpp b/source/source_base/unittests/test_matrix2d_linalg.cpp index ecd64f11120..e4e240e8118 100644 --- a/source/source_base/unittests/test_matrix2d_linalg.cpp +++ b/source/source_base/unittests/test_matrix2d_linalg.cpp @@ -86,18 +86,18 @@ Matrix2d> make_complex_solution() #ifdef __MPI std::vector> available_process_grids() { - const int number_of_ranks = Parallel_Common::comm_size(MPI_COMM_WORLD); + const int nproc = Parallel_Common::comm_size(MPI_COMM_WORLD); std::vector> grids; - if (number_of_ranks == 1) + if (nproc == 1) { grids.push_back(std::make_pair(1, 1)); } - if (number_of_ranks == 2) + if (nproc == 2) { grids.push_back(std::make_pair(1, 2)); grids.push_back(std::make_pair(2, 1)); } - if (number_of_ranks == 4) + if (nproc == 4) { grids.push_back(std::make_pair(1, 4)); grids.push_back(std::make_pair(2, 2)); @@ -130,13 +130,13 @@ Matrix2d make_distributed_real_system(const int size) return matrix; } -Matrix2d make_distributed_real_solution(const int rows, - const int cols) +Matrix2d make_distributed_real_solution(const int nr, + const int nc) { - Matrix2d solution(rows, cols); - for (int i = 0; i < rows; ++i) + Matrix2d solution(nr, nc); + for (int i = 0; i < nr; ++i) { - for (int j = 0; j < cols; ++j) + for (int j = 0; j < nc; ++j) { solution.at_local(i, j) = static_cast(1 + i + 2 * j); @@ -177,13 +177,13 @@ Matrix2d> make_distributed_complex_system(const int size) } Matrix2d> make_distributed_complex_solution( - const int rows, - const int cols) + const int nr, + const int nc) { - Matrix2d> solution(rows, cols); - for (int i = 0; i < rows; ++i) + Matrix2d> solution(nr, nc); + for (int i = 0; i < nr; ++i) { - for (int j = 0; j < cols; ++j) + for (int j = 0; j < nc; ++j) { solution.at_local(i, j) = std::complex(1 + i + 2 * j, i - j); @@ -195,26 +195,26 @@ Matrix2d> make_distributed_complex_solution( template void check_distributed_solve(const Matrix2d& host_matrix, const Matrix2d& host_solution, - const int grid_rows, - const int grid_cols, - const int block_size) + 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(), - grid_rows, - grid_cols, - block_size, + nrproc, + ncproc, + nrblk, MPI_COMM_WORLD); const std::shared_ptr solution_dist = make_borrowed_distribution(host_solution.nrglb(), host_solution.ncglb(), - block_size, + nrblk, matrix.ictxt()); const std::shared_ptr rhs_dist = make_borrowed_distribution(host_rhs.nrglb(), host_rhs.ncglb(), - block_size, + nrblk, matrix.ictxt()); Matrix2d solution(solution_dist); Matrix2d rhs(rhs_dist); @@ -233,18 +233,18 @@ void check_distributed_solve(const Matrix2d& host_matrix, template void check_distributed_inverse(const Matrix2d& host_matrix, - const int grid_rows, - const int grid_cols, - const int block_size) + const int nrproc, + const int ncproc, + const int nrblk) { Matrix2d expected = host_matrix; matrix2d_linalg::inv(expected.view()); Matrix2d matrix(host_matrix.nrglb(), host_matrix.ncglb(), - grid_rows, - grid_cols, - block_size, + nrproc, + ncproc, + nrblk, MPI_COMM_WORLD); matrix.scatter(host_matrix); matrix2d_linalg::inv(matrix.view()); @@ -293,16 +293,16 @@ TEST(Matrix2dLinalgTest, HostComplexSolve) TEST(Matrix2dLinalgTest, SerialDistributionUsesLocalBackend) { - const std::shared_ptr distribution + const std::shared_ptr distrib = make_frozen_distribution(2, 2); - Matrix2d matrix(distribution); + Matrix2d matrix(distrib); matrix.at_local(0, 0) = 4.0; matrix.at_local(0, 1) = 1.0; matrix.at_local(1, 0) = 2.0; matrix.at_local(1, 1) = 3.0; - Matrix2d rhs(distribution); + Matrix2d rhs(distrib); rhs.at_local(0, 0) = 1.0; rhs.at_local(0, 1) = 2.0; rhs.at_local(1, 0) = 3.0; @@ -312,7 +312,7 @@ TEST(Matrix2dLinalgTest, SerialDistributionUsesLocalBackend) matrix2d_linalg::solve(matrix.view(), rhs.view()); expect_host_matrices_near(rhs, expected); - Matrix2d inverse(distribution); + Matrix2d inverse(distrib); inverse.at_local(0, 0) = 4.0; inverse.at_local(0, 1) = 1.0; inverse.at_local(1, 0) = 2.0; @@ -391,14 +391,14 @@ TEST(Matrix2dLinalgTest, RejectsSingularAndMismatchedMatrices) TEST(Matrix2dLinalgTest, DistributedRealAndComplexSolve) { const int size = 5; - const int rhs_columns = 3; + const int nrhs = 3; const Matrix2d real_matrix = make_distributed_real_system(size); const Matrix2d real_solution - = make_distributed_real_solution(size, rhs_columns); + = make_distributed_real_solution(size, nrhs); const Matrix2d> complex_matrix = make_distributed_complex_system(size); const Matrix2d> complex_solution - = make_distributed_complex_solution(size, rhs_columns); + = make_distributed_complex_solution(size, nrhs); const std::vector> grids = available_process_grids(); const int blocks[] = {2, 3}; for (std::size_t grid_index = 0; grid_index < grids.size(); ++grid_index) From ae4a521e8e514271302bdc925bfe9c0a73f73f3f Mon Sep 17 00:00:00 2001 From: kirk0830 Date: Thu, 19 Nov 2026 11:04:51 +0800 Subject: [PATCH 06/15] refactor(base): replace non-domain terms in Matrix2d naming --- source/source_base/matrix2d.cpp | 12 ++- source/source_base/matrix2d.h | 5 +- source/source_base/matrix2d_collective.cpp | 110 +++++++++++---------- source/source_base/matrix2d_reduction.cpp | 26 ++--- 4 files changed, 84 insertions(+), 69 deletions(-) diff --git a/source/source_base/matrix2d.cpp b/source/source_base/matrix2d.cpp index c69e5fe676d..be807f6f4ae 100644 --- a/source/source_base/matrix2d.cpp +++ b/source/source_base/matrix2d.cpp @@ -374,11 +374,13 @@ NDArray NDArray::matmul(const NDArray& other) const { const int m = nrglb(); const int k = ncglb(); - const int k2 = other.nrglb(); const int n = other.ncglb(); - if (k != k2) { - throw std::invalid_argument("matrix inner dimensions are incompatible"); + const int k_ = other.nrglb(); + if (k != k_) + { + throw std::invalid_argument("matrix inner dimensions are incompatible"); + } } const bool this_is_serial @@ -403,9 +405,9 @@ NDArray NDArray::matmul(const NDArray& other) const for (int j = 0; j < n; ++j) { T value = T(); - for (int kk = 0; kk < k; ++kk) + for (int k_ = 0; k_ < k; ++k_) { - value += at_local(i, kk) * other.at_local(kk, j); + value += at_local(i, k_) * other.at_local(k_, j); } result.at_local(i, j) = value; } diff --git a/source/source_base/matrix2d.h b/source/source_base/matrix2d.h index 7b863a96bbe..9928804341f 100644 --- a/source/source_base/matrix2d.h +++ b/source/source_base/matrix2d.h @@ -130,8 +130,9 @@ class NDArray final * @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 payload passed - * by communicator rank zero is read; payloads on other ranks are ignored. + * 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); diff --git a/source/source_base/matrix2d_collective.cpp b/source/source_base/matrix2d_collective.cpp index d69a124325f..f7ccfec1147 100644 --- a/source/source_base/matrix2d_collective.cpp +++ b/source/source_base/matrix2d_collective.cpp @@ -16,7 +16,8 @@ int checked_mpi_count(const std::size_t count) { if (count > static_cast(std::numeric_limits::max())) { - throw std::invalid_argument("Matrix2d collective payload exceeds MPI count range"); + throw std::invalid_argument( + "Matrix2d collective matrix buffer exceeds MPI count range"); } return static_cast(count); } @@ -30,7 +31,8 @@ std::vector make_byte_displacements(const std::vector& counts) displacements[ip] = off; if (counts[ip] > std::numeric_limits::max() - off) { - throw std::invalid_argument("Matrix2d collective payload size overflow"); + throw std::invalid_argument( + "Matrix2d collective matrix buffer size overflow"); } off += counts[ip]; } @@ -82,17 +84,17 @@ std::vector make_local_metadata(const Matrix2d& matrix) } template -std::vector make_local_payload(const Matrix2d& matrix) +std::vector make_local_matrix_buffer(const Matrix2d& matrix) { const std::vector metadata = make_local_metadata(matrix); const std::size_t nmeta = metadata.size() * sizeof(int); const std::size_t data_elements = static_cast(matrix.nrloc()) * static_cast(matrix.ncloc()); const std::size_t data_bytes = data_elements * sizeof(T); - const std::size_t payload_bytes = nmeta + data_bytes; - std::vector payload(payload_bytes); + const std::size_t buffer_bytes = nmeta + data_bytes; + std::vector buffer(buffer_bytes); - std::memcpy(payload.data(), metadata.data(), nmeta); + std::memcpy(buffer.data(), metadata.data(), nmeta); for (int irloc = 0; irloc < matrix.nrloc(); ++irloc) { for (int icloc = 0; icloc < matrix.ncloc(); ++icloc) @@ -106,14 +108,14 @@ std::vector make_local_payload(const Matrix2d& matrix) const std::size_t off = nmeta + idx * sizeof(T); unsigned char* const destination - = payload.data() + off; + = buffer.data() + off; std::memcpy(destination, &value, sizeof(T)); } } - return payload; + return buffer; } -struct LocalPayloadView +struct LocalMatrixBufferView { int nrloc = 0; int ncloc = 0; @@ -127,16 +129,18 @@ struct LocalPayloadView }; template -LocalPayloadView view_local_payload(const std::vector& payload) +LocalMatrixBufferView view_local_matrix_buffer( + const std::vector& buffer) { - if (payload.size() < LOCAL_METADATA_SIZE * sizeof(int)) + if (buffer.size() < LOCAL_METADATA_SIZE * sizeof(int)) { - throw std::invalid_argument("Matrix2d collective payload is truncated"); + throw std::invalid_argument( + "Matrix2d collective matrix buffer is truncated"); } int header[LOCAL_METADATA_SIZE] = {}; - std::memcpy(header, payload.data(), sizeof(header)); - LocalPayloadView view; + std::memcpy(header, buffer.data(), sizeof(header)); + LocalMatrixBufferView view; view.nrloc = header[0]; view.ncloc = header[1]; view.nrglb = header[2]; @@ -147,7 +151,8 @@ LocalPayloadView view_local_payload(const std::vector& payload) if (view.nrloc < 0 || view.ncloc < 0 || view.nrglb <= 0 || view.ncglb <= 0) { - throw std::invalid_argument("Matrix2d collective payload has invalid dimensions"); + throw std::invalid_argument( + "Matrix2d collective matrix buffer has invalid dimensions"); } const std::size_t metadata_count @@ -156,33 +161,34 @@ LocalPayloadView view_local_payload(const std::vector& payload) const std::size_t data_elements = static_cast(view.nrloc) * static_cast(view.ncloc); const std::size_t expected_bytes = nmeta + data_elements * sizeof(T); - if (payload.size() != expected_bytes) + if (buffer.size() != expected_bytes) { - throw std::invalid_argument("Matrix2d collective payload has an invalid size"); + throw std::invalid_argument( + "Matrix2d collective matrix buffer has an invalid size"); } std::vector metadata(metadata_count); - std::memcpy(metadata.data(), payload.data(), nmeta); + std::memcpy(metadata.data(), buffer.data(), nmeta); 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 = payload.data() + nmeta; + view.data = buffer.data() + nmeta; return view; } template Matrix2d rebuild_global_matrix( - const std::vector>& payloads) + const std::vector>& buffers) { - std::vector views; - views.reserve(payloads.size()); + std::vector views; + views.reserve(buffers.size()); int nrglb = 0; int ncglb = 0; - for (std::size_t ip = 0; ip < payloads.size(); ++ip) + for (std::size_t ip = 0; ip < buffers.size(); ++ip) { - views.push_back(view_local_payload(payloads[ip])); - const LocalPayloadView& view = views.back(); + views.push_back(view_local_matrix_buffer(buffers[ip])); + const LocalMatrixBufferView& view = views.back(); if (ip == 0) { nrglb = view.nrglb; @@ -197,7 +203,7 @@ Matrix2d rebuild_global_matrix( Matrix2d result(nrglb, ncglb); for (std::size_t ip = 0; ip < views.size(); ++ip) { - const LocalPayloadView& view = views[ip]; + const LocalMatrixBufferView& view = views[ip]; for (int irloc = 0; irloc < view.nrloc; ++irloc) { const int irglb = view.irglb[irloc]; @@ -226,34 +232,35 @@ Matrix2d rebuild_global_matrix( } template -std::vector> allgather_payloads( +std::vector> allgather_local_matrix_buffers( const Matrix2d& matrix, const MPI_Comm comm) { - const std::vector local_payload = make_local_payload(matrix); - const int local_count = checked_mpi_count(local_payload.size()); + const std::vector local_buffer + = make_local_matrix_buffer(matrix); + const int local_count = checked_mpi_count(local_buffer.size()); std::vector pcounts = allgather_byte_counts(local_count, comm); const std::vector pdispls = make_byte_displacements(pcounts); const int total_bytes = pdispls.back() + pcounts.back(); std::vector received(total_bytes); - Parallel_Common::allgatherv_bytes(local_payload.data(), + Parallel_Common::allgatherv_bytes(local_buffer.data(), local_count, received.data(), pcounts.data(), pdispls.data(), comm); - std::vector> payloads(pcounts.size()); + std::vector> buffers(pcounts.size()); for (std::size_t ip = 0; ip < pcounts.size(); ++ip) { const std::size_t begin = static_cast(pdispls[ip]); const std::size_t end = begin + static_cast(pcounts[ip]); - payloads[ip].assign(received.begin() + begin, received.begin() + end); + buffers[ip].assign(received.begin() + begin, received.begin() + end); } - return payloads; + return buffers; } } // namespace @@ -262,9 +269,9 @@ namespace matrix2d_impl template Matrix2d allgather(const Matrix2d& matrix, const MPI_Comm comm) { - const std::vector> payloads - = allgather_payloads(matrix, comm); - return rebuild_global_matrix(payloads); + const std::vector> buffers + = allgather_local_matrix_buffers(matrix, comm); + return rebuild_global_matrix(buffers); } template @@ -279,8 +286,9 @@ std::unique_ptr> gather_on_root(const Matrix2d& matrix, throw std::invalid_argument("gather root rank is outside the communicator"); } - const std::vector local_payload = make_local_payload(matrix); - const int local_count = checked_mpi_count(local_payload.size()); + const std::vector local_buffer + = make_local_matrix_buffer(matrix); + const int local_count = checked_mpi_count(local_buffer.size()); std::vector pcounts = allgather_byte_counts(local_count, comm); const std::vector pdispls = make_byte_displacements(pcounts); @@ -292,7 +300,7 @@ std::unique_ptr> gather_on_root(const Matrix2d& matrix, } unsigned char* const recvbuf = ip == iproot ? received.data() : nullptr; - Parallel_Common::gatherv_bytes(local_payload.data(), + Parallel_Common::gatherv_bytes(local_buffer.data(), local_count, recvbuf, pcounts.data(), @@ -304,17 +312,17 @@ std::unique_ptr> gather_on_root(const Matrix2d& matrix, return std::unique_ptr>(); } - std::vector> payloads(pcounts.size()); + std::vector> buffers(pcounts.size()); for (std::size_t ipsrc = 0; ipsrc < pcounts.size(); ++ipsrc) { const std::size_t begin = static_cast(pdispls[ipsrc]); const std::size_t end = begin + static_cast(pcounts[ipsrc]); - payloads[ipsrc].assign(received.begin() + begin, received.begin() + end); + buffers[ipsrc].assign(received.begin() + begin, received.begin() + end); } return std::unique_ptr>( - new Matrix2d(rebuild_global_matrix(payloads))); + new Matrix2d(rebuild_global_matrix(buffers))); } template @@ -362,7 +370,7 @@ void scatter_from_host(const Matrix2d& matglb, Matrix2d& matloc) const int nproc = Parallel_Common::comm_size(comm); const int ip = Parallel_Common::comm_rank(comm); std::vector send(nproc, 0); - std::vector views; + std::vector views; views.reserve(nproc); std::size_t metadata_offset = 0; const int nrglb = matloc.nrglb(); @@ -373,7 +381,7 @@ void scatter_from_host(const Matrix2d& matglb, Matrix2d& matloc) { throw std::invalid_argument("Matrix2d scatter metadata is truncated"); } - LocalPayloadView view; + LocalMatrixBufferView view; view.nrloc = all_metadata[metadata_offset]; view.ncloc = all_metadata[metadata_offset + 1]; view.nrglb = all_metadata[metadata_offset + 2]; @@ -402,9 +410,9 @@ void scatter_from_host(const Matrix2d& matglb, Matrix2d& matloc) const std::size_t local_elements = static_cast(view.nrloc) * static_cast(view.ncloc); - const std::size_t local_payload_size = local_elements * sizeof(T); - const int local_payload_bytes = checked_mpi_count(local_payload_size); - send[ipsrc] = local_payload_bytes; + const std::size_t local_buffer_size = local_elements * sizeof(T); + const int local_buffer_bytes = checked_mpi_count(local_buffer_size); + send[ipsrc] = local_buffer_bytes; views.push_back(view); } if (metadata_offset != all_metadata.size()) @@ -424,7 +432,7 @@ void scatter_from_host(const Matrix2d& matglb, Matrix2d& matloc) sendbuf.resize(total_bytes); for (int ipdst = 0; ipdst < nproc; ++ipdst) { - const LocalPayloadView& view = views[ipdst]; + const LocalMatrixBufferView& view = views[ipdst]; for (int irloc = 0; irloc < view.nrloc; ++irloc) { const int irglb = view.irglb[irloc]; @@ -450,9 +458,9 @@ void scatter_from_host(const Matrix2d& matglb, Matrix2d& matloc) const std::size_t receive_elements = static_cast(matloc.nrloc()) * static_cast(matloc.ncloc()); - const std::size_t receive_payload_bytes = receive_elements * sizeof(T); - std::vector recvbuf(receive_payload_bytes); - const int recv = checked_mpi_count(receive_payload_bytes); + const std::size_t receive_buffer_bytes = receive_elements * sizeof(T); + std::vector recvbuf(receive_buffer_bytes); + const int recv = checked_mpi_count(receive_buffer_bytes); const unsigned char* receive_source = ip == 0 ? sendbuf.data() : nullptr; Parallel_Common::scatterv_bytes(receive_source, send.data(), diff --git a/source/source_base/matrix2d_reduction.cpp b/source/source_base/matrix2d_reduction.cpp index de03f98d125..2dedfc797e7 100644 --- a/source/source_base/matrix2d_reduction.cpp +++ b/source/source_base/matrix2d_reduction.cpp @@ -101,7 +101,8 @@ int checked_mpi_count(const std::size_t count) { if (count > static_cast(std::numeric_limits::max())) { - throw std::invalid_argument("Matrix2d diagonal payload exceeds MPI count range"); + throw std::invalid_argument( + "Matrix2d diagonal data buffer exceeds MPI count range"); } return static_cast(count); } @@ -115,7 +116,8 @@ std::vector make_byte_displacements(const std::vector& counts) displacements[ip] = off; if (counts[ip] > std::numeric_limits::max() - off) { - throw std::invalid_argument("Matrix2d diagonal payload size overflow"); + throw std::invalid_argument( + "Matrix2d diagonal data buffer size overflow"); } off += counts[ip]; } @@ -300,28 +302,30 @@ std::vector diagonal(const Matrix2d& matrix) if (comm != MPI_COMM_NULL) { const std::size_t entry_bytes = sizeof(int) + sizeof(T); - const std::size_t local_payload_bytes + const std::size_t local_diagonal_buffer_bytes = sizeof(int) + local_entries.size() * entry_bytes; - std::vector local_payload(local_payload_bytes); + std::vector local_diagonal_buffer( + local_diagonal_buffer_bytes); const int local_entry_count = checked_mpi_count(local_entries.size()); - std::memcpy(local_payload.data(), + std::memcpy(local_diagonal_buffer.data(), &local_entry_count, sizeof(local_entry_count)); std::size_t offset = sizeof(local_entry_count); for (const std::pair& entry : local_entries) { - std::memcpy(local_payload.data() + offset, + std::memcpy(local_diagonal_buffer.data() + offset, &entry.first, sizeof(entry.first)); offset += sizeof(entry.first); - std::memcpy(local_payload.data() + offset, + std::memcpy(local_diagonal_buffer.data() + offset, &entry.second, sizeof(entry.second)); offset += sizeof(entry.second); } - const int local_count = checked_mpi_count(local_payload.size()); + const int local_count + = checked_mpi_count(local_diagonal_buffer.size()); const std::vector pcounts = gather_byte_counts(local_count, comm); const std::vector pdispls @@ -330,7 +334,7 @@ std::vector diagonal(const Matrix2d& matrix) = pdispls.back() + pcounts.back(); std::vector received( static_cast(total_bytes)); - Parallel_Common::allgatherv_bytes(local_payload.data(), + Parallel_Common::allgatherv_bytes(local_diagonal_buffer.data(), local_count, received.data(), pcounts.data(), @@ -346,7 +350,7 @@ std::vector diagonal(const Matrix2d& matrix) if (end - begin < sizeof(int)) { throw std::runtime_error( - "Matrix2d diagonal payload is truncated"); + "Matrix2d diagonal data buffer is truncated"); } int entry_count = 0; std::memcpy(&entry_count, @@ -358,7 +362,7 @@ std::vector diagonal(const Matrix2d& matrix) || end - begin != sizeof(int) + expected_bytes) { throw std::runtime_error( - "Matrix2d diagonal payload has an invalid size"); + "Matrix2d diagonal data buffer has an invalid size"); } std::size_t entry_offset = begin + sizeof(entry_count); for (int ientry = 0; ientry < entry_count; ++ientry) From 1ee1702422da34226e070e811fde4a27096f1b55 Mon Sep 17 00:00:00 2001 From: kirk0830 Date: Thu, 19 Nov 2026 16:22:12 +0800 Subject: [PATCH 07/15] refactor(base): align Matrix2d naming with scientific-computing conventions --- source/source_base/matrix2d.cpp | 256 ++++++++---------- source/source_base/matrix2d.h | 219 +++++++-------- source/source_base/matrix2d_collective.cpp | 222 +++++++-------- source/source_base/matrix2d_lapack.cpp | 40 +-- source/source_base/matrix2d_linalg.cpp | 76 +++--- source/source_base/matrix2d_reduction.cpp | 205 +++++++------- source/source_base/matrix2d_reduction.h | 5 +- source/source_base/matrix2d_scalapack.cpp | 18 +- source/source_base/matrix2d_view.h | 47 ++-- source/source_base/parallel_blkcyc.cpp | 36 +-- source/source_base/parallel_common.cpp | 60 ++-- source/source_base/parallel_common.h | 72 ++--- .../source_base/unittests/test_matrix2d.cpp | 212 +++++++-------- .../unittests/test_matrix2d_linalg.cpp | 182 ++++++------- 14 files changed, 796 insertions(+), 854 deletions(-) diff --git a/source/source_base/matrix2d.cpp b/source/source_base/matrix2d.cpp index be807f6f4ae..b3ade48ebd3 100644 --- a/source/source_base/matrix2d.cpp +++ b/source/source_base/matrix2d.cpp @@ -12,108 +12,56 @@ namespace { +namespace elementwise +{ template -T conjugate_element(const T& value) +T conj(const T& value) { return value; } -template <> -std::complex conjugate_element>( - const std::complex& value) +inline std::complex conj(const std::complex& value) { return std::conj(value); } -template <> -std::complex conjugate_element>( - const std::complex& value) +inline std::complex conj(const std::complex& value) { return std::conj(value); } template -double real_element(const T& value) +double real(const T& value) { return static_cast(value); } -template <> -double real_element>(const std::complex& value) +inline double real(const std::complex& value) { return static_cast(value.real()); } -template <> -double real_element>(const std::complex& value) +inline double real(const std::complex& value) { return value.real(); } template -double imaginary_element(const T&) +double imag(const T&) { return 0.0; } -template <> -double imaginary_element>(const std::complex& value) +inline double imag(const std::complex& value) { return static_cast(value.imag()); } -template <> -double imaginary_element>(const std::complex& value) +inline double imag(const std::complex& value) { return value.imag(); } - -template -Matrix2d extract_real_or_imaginary(const Matrix2d& matrix, - const bool extract_real) -{ - Matrix2d result = matrix.is_distributed() - ? Matrix2d(matrix.distribution()) - : Matrix2d(matrix.nrglb(), - matrix.ncglb()); - - const int nrloc = matrix.nrloc(); - const int ncloc = matrix.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) - { - const T& value = matrix.at_local(i, j); - result.at_local(i, j) - = extract_real ? real_element(value) : imaginary_element(value); - } - } - return result; -} - -template -void write_real_or_imaginary(const Matrix2d& matrix, - Matrix2d& output, - const bool extract_real) -{ - const int nrloc = matrix.nrloc(); - const int ncloc = matrix.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) - { - const T& value = matrix.at_local(i, j); - output.at_local(i, j) - = extract_real ? real_element(value) : imaginary_element(value); - } - } -} +} // namespace elementwise } // namespace @@ -157,9 +105,9 @@ void matmul(Matrix2dView result, template Matrix2dView NDArray::view() { - if (dist_ != nullptr) + if (distrib_ != nullptr) { - return Matrix2dView(data(), dist_); + return Matrix2dView(data(), distrib_); } return Matrix2dView(data(), nrglb(), ncglb()); } @@ -167,9 +115,9 @@ Matrix2dView NDArray::view() template Matrix2dView NDArray::view() const { - if (dist_ != nullptr) + if (distrib_ != nullptr) { - return Matrix2dView(data(), dist_); + return Matrix2dView(data(), distrib_); } return Matrix2dView(data(), nrglb(), ncglb()); } @@ -177,7 +125,7 @@ Matrix2dView NDArray::view() const template void NDArray::fill(const T& value) { - if (dist_ == nullptr) + if (distrib_ == nullptr) { std::fill(storage_.begin(), storage_.end(), value); return; @@ -191,7 +139,7 @@ void NDArray::fill(const T& value) { for (int icloc = 0; icloc < ncloc; ++icloc) { - at_local(irloc, icloc) = value; + atloc(irloc, icloc) = value; } } } @@ -199,7 +147,7 @@ void NDArray::fill(const T& value) template void NDArray::scale(const T& value) { - if (dist_ == nullptr) + if (distrib_ == nullptr) { #ifdef _OPENMP #pragma omp parallel for schedule(static) @@ -219,7 +167,7 @@ void NDArray::scale(const T& value) { for (int icloc = 0; icloc < ncloc; ++icloc) { - at_local(irloc, icloc) *= value; + atloc(irloc, icloc) *= value; } } } @@ -227,7 +175,7 @@ void NDArray::scale(const T& value) template NDArray& NDArray::operator+=(const NDArray& other) { - validate_compatible_layout(other); + assert_compatible_layout(other); const int nrloc = this->nrloc(); const int ncloc = this->ncloc(); #ifdef _OPENMP @@ -237,7 +185,7 @@ NDArray& NDArray::operator+=(const NDArray& other) { for (int icloc = 0; icloc < ncloc; ++icloc) { - at_local(irloc, icloc) += other.at_local(irloc, icloc); + atloc(irloc, icloc) += other.atloc(irloc, icloc); } } return *this; @@ -246,7 +194,7 @@ NDArray& NDArray::operator+=(const NDArray& other) template NDArray& NDArray::operator-=(const NDArray& other) { - validate_compatible_layout(other); + assert_compatible_layout(other); const int nrloc = this->nrloc(); const int ncloc = this->ncloc(); #ifdef _OPENMP @@ -256,7 +204,7 @@ NDArray& NDArray::operator-=(const NDArray& other) { for (int icloc = 0; icloc < ncloc; ++icloc) { - at_local(irloc, icloc) -= other.at_local(irloc, icloc); + atloc(irloc, icloc) -= other.atloc(irloc, icloc); } } return *this; @@ -265,7 +213,7 @@ NDArray& NDArray::operator-=(const NDArray& other) template NDArray& NDArray::operator*=(const NDArray& other) { - validate_compatible_layout(other); + assert_compatible_layout(other); const int nrloc = this->nrloc(); const int ncloc = this->ncloc(); #ifdef _OPENMP @@ -275,7 +223,7 @@ NDArray& NDArray::operator*=(const NDArray& other) { for (int icloc = 0; icloc < ncloc; ++icloc) { - at_local(irloc, icloc) *= other.at_local(irloc, icloc); + atloc(irloc, icloc) *= other.atloc(irloc, icloc); } } return *this; @@ -293,7 +241,7 @@ NDArray& NDArray::conjugate() { for (int j = 0; j < ncloc; ++j) { - at_local(i, j) = conjugate_element(at_local(i, j)); + atloc(i, j) = elementwise::conj(atloc(i, j)); } } return *this; @@ -302,7 +250,7 @@ NDArray& NDArray::conjugate() template NDArray NDArray::transpose() const { - if (dist_ == nullptr || dist_->is_serial()) + if (distrib_ == nullptr || distrib_->is_serial()) { // Serial degenerate path: a serial frozen distribution owns the full // matrix on one rank with column-major local layout; treat it like the @@ -315,7 +263,7 @@ NDArray NDArray::transpose() const { for (int j = 0; j < ncloc_; ++j) { - result.at_local(j, i) = at_local(i, j); + result.atloc(j, i) = atloc(i, j); } } return result; @@ -324,10 +272,10 @@ NDArray NDArray::transpose() const #ifdef __MPI const int nr = ncglb(); const int nc = nrglb(); - const int nb = dist_->nb(); - const std::shared_ptr result_dist - = make_borrowed_distribution(nr, nc, nb, dist_); - Matrix2d result(result_dist); + 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 @@ -338,7 +286,7 @@ NDArray NDArray::transpose() const template NDArray NDArray::dagger() const { - if (dist_ == nullptr || dist_->is_serial()) + if (distrib_ == nullptr || distrib_->is_serial()) { Matrix2d result(ncloc_, nrloc_); #ifdef _OPENMP @@ -348,7 +296,7 @@ NDArray NDArray::dagger() const { for (int j = 0; j < ncloc_; ++j) { - result.at_local(j, i) = conjugate_element(at_local(i, j)); + result.atloc(j, i) = elementwise::conj(atloc(i, j)); } } return result; @@ -357,10 +305,10 @@ NDArray NDArray::dagger() const #ifdef __MPI const int nr = ncglb(); const int nc = nrglb(); - const int nb = dist_->nb(); - const std::shared_ptr result_dist - = make_borrowed_distribution(nr, nc, nb, dist_); - Matrix2d result(result_dist); + 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 @@ -383,16 +331,16 @@ NDArray NDArray::matmul(const NDArray& other) const } } - const bool this_is_serial - = dist_ == nullptr || dist_->is_serial(); - const bool other_is_serial + const bool serial + = distrib_ == nullptr || distrib_->is_serial(); + const bool serial_ = other.distribution() == nullptr || other.distribution()->is_serial(); - if (this_is_serial != other_is_serial) + if (serial != serial_) { throw std::invalid_argument("host and distributed matrices are incompatible"); } - if (this_is_serial) + if (serial) { // Serial degenerate path: both sides are host or serial frozen // distributions, so matmul degrades to the host triple loop. @@ -407,35 +355,35 @@ NDArray NDArray::matmul(const NDArray& other) const T value = T(); for (int k_ = 0; k_ < k; ++k_) { - value += at_local(i, k_) * other.at_local(k_, j); + value += atloc(i, k_) * other.atloc(k_, j); } - result.at_local(i, j) = value; + result.atloc(i, j) = value; } } return result; } #ifdef __MPI - const std::shared_ptr other_dist + const std::shared_ptr other_distrib = other.distribution(); - if (dist_->nb() != other_dist->nb()) + if (distrib_->nb() != other_distrib->nb()) { throw std::invalid_argument("matrix block sizes are incompatible"); } - if (dist_->nrproc() != other_dist->nrproc() - || dist_->ncproc() != other_dist->ncproc()) + if (distrib_->nrproc() != other_distrib->nrproc() + || distrib_->ncproc() != other_distrib->ncproc()) { throw std::invalid_argument("matrix process grids are incompatible"); } - if (dist_->ictxt() != other_dist->ictxt()) + if (distrib_->ictxt() != other_distrib->ictxt()) { throw std::invalid_argument("matrix BLACS contexts are incompatible"); } - const int nb = dist_->nb(); - const std::shared_ptr result_dist - = make_borrowed_distribution(m, n, nb, dist_); - Matrix2d result(result_dist); + 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 @@ -446,27 +394,43 @@ NDArray NDArray::matmul(const NDArray& other) const template NDArray NDArray::real() const { - return extract_real_or_imaginary(*this, true); + Matrix2d result = is_distributed() + ? 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 { - return extract_real_or_imaginary(*this, false); -} - -template -void NDArray::real(NDArray& output) const -{ - validate_compatible_layout(output); - write_real_or_imaginary(*this, output, true); -} - -template -void NDArray::imag(NDArray& output) const -{ - validate_compatible_layout(output); - write_real_or_imaginary(*this, output, false); + Matrix2d result = is_distributed() + ? 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 @@ -475,23 +439,17 @@ T NDArray::sum() const return matrix2d_impl::sum(*this); } -template -double NDArray::sum_squares() const -{ - return matrix2d_impl::sum_squares(*this); -} - template T NDArray::dot(const NDArray& other) const { - validate_compatible_layout(other); + assert_compatible_layout(other); return matrix2d_impl::dot(*this, other); } template -double NDArray::norm2() const +double NDArray::norm() const { - return matrix2d_impl::norm2(*this); + return matrix2d_impl::norm(*this); } template @@ -509,26 +467,26 @@ std::vector NDArray::diagonal() const template NDArray NDArray::gather() const { - if (dist_ == nullptr) + if (distrib_ == nullptr) { return *this; } - if (dist_->is_serial()) + if (distrib_->is_serial()) { Matrix2d result(nrglb(), ncglb()); for (int irloc = 0; irloc < nrloc(); ++irloc) { - const int irglb = dist_->irglb(irloc); + const int irglb = distrib_->irglb(irloc); for (int icloc = 0; icloc < ncloc(); ++icloc) { - const int icglb = dist_->icglb(icloc); - result.at_local(irglb, icglb) = at_local(irloc, icloc); + const int icglb = distrib_->icglb(icloc); + result.atloc(irglb, icglb) = atloc(irloc, icloc); } } return result; } #ifdef __MPI - const MPI_Comm comm = dist_->comm(); + const MPI_Comm comm = distrib_->comm(); if (comm == MPI_COMM_NULL) { throw std::invalid_argument("gather requires a valid MPI comm"); @@ -542,7 +500,7 @@ NDArray NDArray::gather() const template NDArray NDArray::gather_on_root(const int iproot) const { - if (dist_ == nullptr) + if (distrib_ == nullptr) { if (iproot == 0) { @@ -550,7 +508,7 @@ NDArray NDArray::gather_on_root(const int iproot) const } return NDArray(EmptyMatrixTag()); } - if (dist_->is_serial()) + if (distrib_->is_serial()) { if (iproot != 0) { @@ -559,17 +517,17 @@ NDArray NDArray::gather_on_root(const int iproot) const Matrix2d result(nrglb(), ncglb()); for (int irloc = 0; irloc < nrloc(); ++irloc) { - const int irglb = dist_->irglb(irloc); + const int irglb = distrib_->irglb(irloc); for (int icloc = 0; icloc < ncloc(); ++icloc) { - const int icglb = dist_->icglb(icloc); - result.at_local(irglb, icglb) = at_local(irloc, icloc); + const int icglb = distrib_->icglb(icloc); + result.atloc(irglb, icglb) = atloc(irloc, icloc); } } return result; } #ifdef __MPI - const MPI_Comm comm = dist_->comm(); + const MPI_Comm comm = distrib_->comm(); if (comm == MPI_COMM_NULL) { throw std::invalid_argument("gather_on_root requires a valid MPI comm"); @@ -590,7 +548,7 @@ NDArray NDArray::gather_on_root(const int iproot) const template void NDArray::scatter(const NDArray& matglb) { - if (dist_ == nullptr) + if (distrib_ == nullptr) { if (matglb.is_distributed()) { @@ -605,7 +563,7 @@ void NDArray::scatter(const NDArray& matglb) return; } - if (dist_->is_serial()) + if (distrib_->is_serial()) { if (matglb.is_distributed()) { @@ -620,9 +578,9 @@ void NDArray::scatter(const NDArray& matglb) { for (int icloc = 0; icloc < ncloc(); ++icloc) { - at_local(irloc, icloc) - = matglb.at_local(dist_->irglb(irloc), - dist_->icglb(icloc)); + atloc(irloc, icloc) + = matglb.atloc(distrib_->irglb(irloc), + distrib_->icglb(icloc)); } } return; diff --git a/source/source_base/matrix2d.h b/source/source_base/matrix2d.h index 9928804341f..21b99e24c7e 100644 --- a/source/source_base/matrix2d.h +++ b/source/source_base/matrix2d.h @@ -45,9 +45,9 @@ class NDArray final const int ncglb, const MPI_Comm comm) { - const std::shared_ptr dist + const std::shared_ptr distrib // distribution, not distance = make_frozen_distribution(nrglb, ncglb, 1, comm); - initialize_distributed_storage(dist); + initialize_distributed_storage(distrib); } NDArray(const int nrglb, @@ -55,9 +55,9 @@ class NDArray final const int nb, const MPI_Comm comm) { - const std::shared_ptr dist + const std::shared_ptr distrib = make_frozen_distribution(nrglb, ncglb, nb, comm); - initialize_distributed_storage(dist); + initialize_distributed_storage(distrib); } NDArray(const int nrglb, @@ -67,16 +67,16 @@ class NDArray final const int nb, const MPI_Comm comm) { - const std::shared_ptr dist + const std::shared_ptr distrib = make_frozen_distribution(nrglb, ncglb, nrproc, ncproc, nb, comm); - initialize_distributed_storage(dist); + initialize_distributed_storage(distrib); } #endif - explicit NDArray(std::shared_ptr dist) - : dist_(std::move(dist)) + explicit NDArray(std::shared_ptr distrib) + : distrib_(std::move(distrib)) { - if (dist_ == nullptr) + if (distrib_ == nullptr) { throw std::invalid_argument("distribution must not be null"); } @@ -101,15 +101,15 @@ class NDArray final 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; - void real(NDArray& output) const; - void imag(NDArray& output) const; T sum() const; - double sum_squares() const; T dot(const NDArray& other) const; - double norm2() const; + /** Return the Frobenius norm sqrt(sum_ij |a_ij|^2). */ + double norm() const; double max_abs() const; std::vector diagonal() const; @@ -136,127 +136,130 @@ class NDArray final */ void scatter(const NDArray& matglb); - T& at_global(const int i, const int j) + /** Access an owned element by global row and column indices. */ + T& atglb(const int irglb, const int icglb) { - assert(i >= 0); - assert(i < nrglb()); - assert(j >= 0); - assert(j < ncglb()); + assert(irglb >= 0); + assert(irglb < nrglb()); + assert(icglb >= 0); + assert(icglb < ncglb()); - if (dist_ == nullptr) + if (distrib_ == nullptr) { - return at_local(i, j); + return atloc(irglb, icglb); } - const std::size_t iglb = static_cast(i); - const std::size_t jglb = static_cast(j); - const bool owns = dist_->in_this_processor(iglb, jglb); + const bool owns = distrib_->in_this_processor(irglb, icglb); assert(owns); - const int irloc = dist_->irloc(i); - const int icloc = dist_->icloc(j); + const int irloc = distrib_->irloc(irglb); + const int icloc = distrib_->icloc(icglb); assert(irloc != -1); assert(icloc != -1); - return at_local(irloc, icloc); + return atloc(irloc, icloc); } - const T& at_global(const int i, const int j) const + /** Access an owned element by global row and column indices. */ + const T& atglb(const int irglb, const int icglb) const { - assert(i >= 0); - assert(i < nrglb()); - assert(j >= 0); - assert(j < ncglb()); + assert(irglb >= 0); + assert(irglb < nrglb()); + assert(icglb >= 0); + assert(icglb < ncglb()); - if (dist_ == nullptr) + if (distrib_ == nullptr) { - return at_local(i, j); + return atloc(irglb, icglb); } - const std::size_t iglb = static_cast(i); - const std::size_t jglb = static_cast(j); - const bool owns = dist_->in_this_processor(iglb, jglb); + const bool owns = distrib_->in_this_processor(irglb, icglb); assert(owns); - const int irloc = dist_->irloc(i); - const int icloc = dist_->icloc(j); + const int irloc = distrib_->irloc(irglb); + const int icloc = distrib_->icloc(icglb); assert(irloc != -1); assert(icloc != -1); - return at_local(irloc, icloc); + return atloc(irloc, icloc); } - T& at_local(const int i, const int j) + /** Access an element by local row and column indices. */ + T& atloc(const int irloc, const int icloc) { - assert(i >= 0); - assert(i < nrloc()); - assert(j >= 0); - assert(j < ncloc()); + assert(irloc >= 0); + assert(irloc < nrloc()); + assert(icloc >= 0); + assert(icloc < ncloc()); - std::size_t ioff = 0; - if (dist_ == nullptr) + std::size_t offset = 0; + if (distrib_ == nullptr) { - ioff = static_cast(i) * static_cast(ncloc_) - + static_cast(j); + offset = static_cast(irloc) + * static_cast(ncloc_) + + static_cast(icloc); } else { - const int lld = dist_->lld(); - ioff = static_cast(j) * static_cast(lld) - + static_cast(i); + const int lld = distrib_->lld(); + offset = static_cast(icloc) + * static_cast(lld) + + static_cast(irloc); } - assert(ioff < storage_.size()); - return storage_[ioff]; + assert(offset < storage_.size()); + return storage_[offset]; } - const T& at_local(const int i, const int j) const + /** Access an element by local row and column indices. */ + const T& atloc(const int irloc, const int icloc) const { - assert(i >= 0); - assert(i < nrloc()); - assert(j >= 0); - assert(j < ncloc()); + assert(irloc >= 0); + assert(irloc < nrloc()); + assert(icloc >= 0); + assert(icloc < ncloc()); - std::size_t ioff = 0; - if (dist_ == nullptr) + std::size_t offset = 0; + if (distrib_ == nullptr) { - ioff = static_cast(i) * static_cast(ncloc_) - + static_cast(j); + offset = static_cast(irloc) + * static_cast(ncloc_) + + static_cast(icloc); } else { - const int lld = dist_->lld(); - ioff = static_cast(j) * static_cast(lld) - + static_cast(i); + const int lld = distrib_->lld(); + offset = static_cast(icloc) + * static_cast(lld) + + static_cast(irloc); } - assert(ioff < storage_.size()); - return storage_[ioff]; + assert(offset < storage_.size()); + return storage_[offset]; } - bool owns_global_index(const int i, const int j) const + /** Return whether this processor owns the given global indices. */ + bool in_this_processor(const int irglb, const int icglb) const { - assert(i >= 0); - assert(i < nrglb()); - assert(j >= 0); - assert(j < ncglb()); - if (dist_ == nullptr) + assert(irglb >= 0); + assert(irglb < nrglb()); + assert(icglb >= 0); + assert(icglb < ncglb()); + if (distrib_ == nullptr) { return true; } - const std::size_t iglb = static_cast(i); - const std::size_t jglb = static_cast(j); - return dist_->in_this_processor(iglb, jglb); + return distrib_->in_this_processor(irglb, icglb); } T* data() { return storage_.data(); } const T* data() const { return storage_.data(); } - int nrglb() const { return dist_ == nullptr ? nrloc_ : dist_->nrglb(); } - int ncglb() const { return dist_ == nullptr ? ncloc_ : dist_->ncglb(); } - int nrloc() const { return dist_ == nullptr ? nrloc_ : dist_->nrloc(); } - int ncloc() const { return dist_ == nullptr ? ncloc_ : dist_->ncloc(); } + 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 dist_ == nullptr + return distrib_ == nullptr ? static_cast(nrloc_) * static_cast(ncloc_) - : dist_->size(); + : distrib_->size(); } /** @@ -266,16 +269,16 @@ class NDArray final * ranks that own no local rows or columns. */ std::size_t local_storage_size() const { return storage_.size(); } - int nrproc() const { return dist_ == nullptr ? 1 : dist_->nrproc(); } - int ncproc() const { return dist_ == nullptr ? 1 : dist_->ncproc(); } - int irproc() const { return dist_ == nullptr ? 0 : dist_->irproc(); } - int icproc() const { return dist_ == nullptr ? 0 : dist_->icproc(); } - int lld() const { return dist_ == nullptr ? ncloc_ : dist_->lld(); } + 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 dist_ != nullptr ? dist_->desc() : nullptr; + return distrib_ != nullptr ? distrib_->desc() : nullptr; #else return nullptr; #endif @@ -284,14 +287,14 @@ class NDArray final int ictxt() const { #ifdef __MPI - return dist_ != nullptr ? dist_->ictxt() : -1; + return distrib_ != nullptr ? distrib_->ictxt() : -1; #else return -1; #endif } - const std::shared_ptr& distribution() const { return dist_; } - bool is_distributed() const { return dist_ != nullptr; } + const std::shared_ptr& distribution() const { return distrib_; } + bool is_distributed() const { return distrib_ != nullptr; } Matrix2dView view(); Matrix2dView view() const; @@ -306,7 +309,7 @@ class NDArray final } template - void validate_compatible_layout(const NDArray& other) const + void assert_compatible_layout(const NDArray& other) const { if (nrglb() != other.nrglb() || ncglb() != other.ncglb()) @@ -314,53 +317,53 @@ class NDArray final throw std::invalid_argument("matrix global shapes are incompatible"); } - const bool this_is_distributed = dist_ != nullptr; - const bool other_is_distributed = other.distribution() != nullptr; - if (this_is_distributed != other_is_distributed) + const bool distributed = distrib_ != nullptr; + const bool distributed_ = other.distribution() != nullptr; + if (distributed != distributed_) { throw std::invalid_argument("host and distributed matrices are incompatible"); } - if (!this_is_distributed) + if (!distributed) { return; } - if (dist_->nb() != other.distribution()->nb()) + if (distrib_->nb() != other.distribution()->nb()) { throw std::invalid_argument("matrix block sizes are incompatible"); } - if (dist_->nrproc() != other.distribution()->nrproc() - || dist_->ncproc() != other.distribution()->ncproc()) + if (distrib_->nrproc() != other.distribution()->nrproc() + || distrib_->ncproc() != other.distribution()->ncproc()) { throw std::invalid_argument("matrix process grids are incompatible"); } - if (dist_ != other.distribution()) + if (distrib_ != other.distribution()) { throw std::invalid_argument("matrix distribution handles are incompatible"); } } void initialize_distributed_storage( - const std::shared_ptr& dist) + const std::shared_ptr& distrib) { - if (dist == nullptr) + if (distrib == nullptr) { throw std::invalid_argument("distribution must not be null"); } - dist_ = dist; + distrib_ = distrib; initialize_distributed_storage(); } void initialize_distributed_storage() { - nrloc_ = dist_->nrloc(); - ncloc_ = dist_->ncloc(); + nrloc_ = distrib_->nrloc(); + ncloc_ = distrib_->ncloc(); assert(nrloc_ >= 0); assert(ncloc_ >= 0); - const int distrib_lld = dist_->lld(); - const int lld = std::max(distrib_lld, 1); + const int lld_distrib = distrib_->lld(); + const int lld = std::max(lld_distrib, 1); const std::size_t ld = static_cast(lld); // The actual BLACS/LAPACK buffer is column-major. The row-major extent // is kept in the maximum as a guard for local logical accesses. @@ -380,7 +383,7 @@ class NDArray final int nrloc_ = 0; int ncloc_ = 0; std::vector storage_; - std::shared_ptr dist_; + std::shared_ptr distrib_; }; template diff --git a/source/source_base/matrix2d_collective.cpp b/source/source_base/matrix2d_collective.cpp index f7ccfec1147..70a4a792013 100644 --- a/source/source_base/matrix2d_collective.cpp +++ b/source/source_base/matrix2d_collective.cpp @@ -12,56 +12,59 @@ namespace { constexpr int LOCAL_METADATA_SIZE = 6; -int checked_mpi_count(const std::size_t count) +void assert_valid_mpi_count(const std::size_t nbytes) { - if (count > static_cast(std::numeric_limits::max())) + if (nbytes > static_cast(std::numeric_limits::max())) { throw std::invalid_argument( "Matrix2d collective matrix buffer exceeds MPI count range"); } - return static_cast(count); } -std::vector make_byte_displacements(const std::vector& counts) +int mpi_count(const std::size_t nbytes) { - std::vector displacements(counts.size(), 0); - int off = 0; - for (std::size_t ip = 0; ip < counts.size(); ++ip) + return static_cast(nbytes); +} + +std::vector make_byte_displs(const std::vector& nbytes) +{ + std::vector displs(nbytes.size(), 0); + int offset = 0; + for (std::size_t ip = 0; ip < nbytes.size(); ++ip) { - displacements[ip] = off; - if (counts[ip] > std::numeric_limits::max() - off) + displs[ip] = offset; + if (nbytes[ip] > std::numeric_limits::max() - offset) { throw std::invalid_argument( "Matrix2d collective matrix buffer size overflow"); } - off += counts[ip]; + offset += nbytes[ip]; } - return displacements; + return displs; } -std::vector allgather_byte_counts(const int local_count, const MPI_Comm comm) +std::vector allgather_nbytes(const int nbytes_local, const MPI_Comm comm) { const int nproc = Parallel_Common::comm_size(comm); - const int integer_bytes = checked_mpi_count(sizeof(int)); - std::vector recv(nproc, integer_bytes); + const int nbytes_int = static_cast(sizeof(int)); + std::vector recvcounts(static_cast(nproc), nbytes_int); const std::vector rdispls - = make_byte_displacements(recv); - std::vector counts(nproc, 0); - const int local_count_bytes = checked_mpi_count(sizeof(local_count)); - - Parallel_Common::allgatherv_bytes(&local_count, - local_count_bytes, - counts.data(), - recv.data(), + = make_byte_displs(recvcounts); + std::vector nbytes(static_cast(nproc), 0); + + Parallel_Common::allgatherv_bytes(&nbytes_local, + nbytes_int, + nbytes.data(), + recvcounts.data(), rdispls.data(), comm); - return counts; + return nbytes; } template std::vector make_local_metadata(const Matrix2d& matrix) { - const std::shared_ptr dist + const std::shared_ptr distrib = matrix.distribution(); std::vector metadata; metadata.reserve(LOCAL_METADATA_SIZE + matrix.nrloc() @@ -70,15 +73,15 @@ std::vector make_local_metadata(const Matrix2d& matrix) metadata.push_back(matrix.ncloc()); metadata.push_back(matrix.nrglb()); metadata.push_back(matrix.ncglb()); - metadata.push_back(dist->irproc()); - metadata.push_back(dist->icproc()); + metadata.push_back(distrib->irproc()); + metadata.push_back(distrib->icproc()); for (int irloc = 0; irloc < matrix.nrloc(); ++irloc) { - metadata.push_back(dist->irglb(irloc)); + metadata.push_back(distrib->irglb(irloc)); } for (int icloc = 0; icloc < matrix.ncloc(); ++icloc) { - metadata.push_back(dist->icglb(icloc)); + metadata.push_back(distrib->icglb(icloc)); } return metadata; } @@ -87,28 +90,27 @@ template std::vector make_local_matrix_buffer(const Matrix2d& matrix) { const std::vector metadata = make_local_metadata(matrix); - const std::size_t nmeta = metadata.size() * sizeof(int); + const std::size_t nmeta = metadata.size(); + const std::size_t nmeta_bytes = nmeta * sizeof(int); const std::size_t data_elements = static_cast(matrix.nrloc()) * static_cast(matrix.ncloc()); const std::size_t data_bytes = data_elements * sizeof(T); - const std::size_t buffer_bytes = nmeta + data_bytes; - std::vector buffer(buffer_bytes); + const std::size_t nbytes_buffer = nmeta_bytes + data_bytes; + std::vector buffer(nbytes_buffer); - std::memcpy(buffer.data(), metadata.data(), nmeta); + std::memcpy(buffer.data(), metadata.data(), nmeta_bytes); for (int irloc = 0; irloc < matrix.nrloc(); ++irloc) { for (int icloc = 0; icloc < matrix.ncloc(); ++icloc) { - const std::size_t irloc_index = static_cast(irloc); - const std::size_t icloc_index = static_cast(icloc); + const std::size_t uirloc = static_cast(irloc); + const std::size_t uicloc = static_cast(icloc); const std::size_t idx - = irloc_index * static_cast(matrix.ncloc()) - + icloc_index; - const T& value = matrix.at_local(irloc, icloc); - const std::size_t off - = nmeta + idx * sizeof(T); + = uirloc * static_cast(matrix.ncloc()) + uicloc; + const T& value = matrix.atloc(irloc, icloc); + const std::size_t offset = nmeta_bytes + idx * sizeof(T); unsigned char* const destination - = buffer.data() + off; + = buffer.data() + offset; std::memcpy(destination, &value, sizeof(T)); } } @@ -155,25 +157,25 @@ LocalMatrixBufferView view_local_matrix_buffer( "Matrix2d collective matrix buffer has invalid dimensions"); } - const std::size_t metadata_count + const std::size_t nmeta = static_cast(LOCAL_METADATA_SIZE) + view.nrloc + view.ncloc; - const std::size_t nmeta = metadata_count * sizeof(int); + const std::size_t nmeta_bytes = nmeta * sizeof(int); const std::size_t data_elements = static_cast(view.nrloc) * static_cast(view.ncloc); - const std::size_t expected_bytes = nmeta + data_elements * sizeof(T); + const std::size_t expected_bytes = nmeta_bytes + data_elements * sizeof(T); if (buffer.size() != expected_bytes) { throw std::invalid_argument( "Matrix2d collective matrix buffer has an invalid size"); } - std::vector metadata(metadata_count); - std::memcpy(metadata.data(), buffer.data(), nmeta); + std::vector metadata(nmeta); + std::memcpy(metadata.data(), buffer.data(), nmeta_bytes); 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() + nmeta; + view.data = buffer.data() + nmeta_bytes; return view; } @@ -224,7 +226,7 @@ Matrix2d rebuild_global_matrix( + static_cast(icloc); T value; std::memcpy(&value, view.data + idx * sizeof(T), sizeof(T)); - result.at_local(irglb, icglb) = value; + result.atloc(irglb, icglb) = value; } } } @@ -238,26 +240,28 @@ std::vector> allgather_local_matrix_buffers( { const std::vector local_buffer = make_local_matrix_buffer(matrix); - const int local_count = checked_mpi_count(local_buffer.size()); - std::vector pcounts = allgather_byte_counts(local_count, comm); - const std::vector pdispls - = make_byte_displacements(pcounts); - const int total_bytes = pdispls.back() + pcounts.back(); + assert_valid_mpi_count(local_buffer.size()); + const int nbytes_local_mpi = mpi_count(local_buffer.size()); + const std::vector recvcounts + = allgather_nbytes(nbytes_local_mpi, comm); + const std::vector rdispls + = make_byte_displs(recvcounts); + const int total_bytes = rdispls.back() + recvcounts.back(); std::vector received(total_bytes); Parallel_Common::allgatherv_bytes(local_buffer.data(), - local_count, + nbytes_local_mpi, received.data(), - pcounts.data(), - pdispls.data(), + recvcounts.data(), + rdispls.data(), comm); - std::vector> buffers(pcounts.size()); - for (std::size_t ip = 0; ip < pcounts.size(); ++ip) + std::vector> buffers(recvcounts.size()); + for (std::size_t ip = 0; ip < recvcounts.size(); ++ip) { - const std::size_t begin = static_cast(pdispls[ip]); + const std::size_t begin = static_cast(rdispls[ip]); const std::size_t end - = begin + static_cast(pcounts[ip]); + = begin + static_cast(recvcounts[ip]); buffers[ip].assign(received.begin() + begin, received.begin() + end); } return buffers; @@ -288,11 +292,13 @@ std::unique_ptr> gather_on_root(const Matrix2d& matrix, const std::vector local_buffer = make_local_matrix_buffer(matrix); - const int local_count = checked_mpi_count(local_buffer.size()); - std::vector pcounts = allgather_byte_counts(local_count, comm); - const std::vector pdispls - = make_byte_displacements(pcounts); - const int total_bytes = pdispls.back() + pcounts.back(); + assert_valid_mpi_count(local_buffer.size()); + const int nbytes_local_mpi = mpi_count(local_buffer.size()); + const std::vector recvcounts + = allgather_nbytes(nbytes_local_mpi, comm); + const std::vector rdispls + = make_byte_displs(recvcounts); + const int total_bytes = rdispls.back() + recvcounts.back(); std::vector received; if (ip == iproot) { @@ -301,10 +307,10 @@ std::unique_ptr> gather_on_root(const Matrix2d& matrix, unsigned char* const recvbuf = ip == iproot ? received.data() : nullptr; Parallel_Common::gatherv_bytes(local_buffer.data(), - local_count, + nbytes_local_mpi, recvbuf, - pcounts.data(), - pdispls.data(), + recvcounts.data(), + rdispls.data(), iproot, comm); if (ip != iproot) @@ -312,13 +318,13 @@ std::unique_ptr> gather_on_root(const Matrix2d& matrix, return std::unique_ptr>(); } - std::vector> buffers(pcounts.size()); - for (std::size_t ipsrc = 0; ipsrc < pcounts.size(); ++ipsrc) + std::vector> buffers(recvcounts.size()); + for (std::size_t ipsrc = 0; ipsrc < recvcounts.size(); ++ipsrc) { const std::size_t begin - = static_cast(pdispls[ipsrc]); + = static_cast(rdispls[ipsrc]); const std::size_t end - = begin + static_cast(pcounts[ipsrc]); + = begin + static_cast(recvcounts[ipsrc]); buffers[ipsrc].assign(received.begin() + begin, received.begin() + end); } return std::unique_ptr>( @@ -333,43 +339,42 @@ void scatter_from_host(const Matrix2d& matglb, Matrix2d& matloc) throw std::invalid_argument("scatter requires a host global matrix"); } - const std::shared_ptr dist + const std::shared_ptr distrib = matloc.distribution(); - const MPI_Comm comm = dist->comm(); + const MPI_Comm comm = distrib->comm(); if (comm == MPI_COMM_NULL) { throw std::invalid_argument("scatter requires a valid MPI comm"); } - const std::vector local_meta = make_local_metadata(matloc); - const std::size_t local_metadata_size - = local_meta.size() * sizeof(int); - const int nmeta - = checked_mpi_count(local_metadata_size); - std::vector mcounts - = allgather_byte_counts(nmeta, comm); - const std::vector mdispls - = make_byte_displacements(mcounts); + const std::vector metadata = make_local_metadata(matloc); + const std::size_t nmeta = metadata.size(); + const std::size_t nmeta_bytes = nmeta * sizeof(int); + assert_valid_mpi_count(nmeta_bytes); + const int nmeta_mpi = mpi_count(nmeta_bytes); + const std::vector metacounts = allgather_nbytes(nmeta_mpi, comm); + const std::vector metadispls + = make_byte_displs(metacounts); const int metadata_total_bytes - = mdispls.back() + mcounts.back(); - const int metadata_element_bytes = checked_mpi_count(sizeof(int)); - if (metadata_total_bytes % metadata_element_bytes != 0) + = metadispls.back() + metacounts.back(); + const int nbytes_int = static_cast(sizeof(int)); + if (metadata_total_bytes % nbytes_int != 0) { throw std::invalid_argument("Matrix2d scatter metadata has an invalid byte count"); } - const int metadata_elements = metadata_total_bytes / metadata_element_bytes; - std::vector all_metadata(metadata_elements); + const int nmeta_all = metadata_total_bytes / nbytes_int; + std::vector all_metadata(nmeta_all); - Parallel_Common::allgatherv_bytes(local_meta.data(), - nmeta, + Parallel_Common::allgatherv_bytes(metadata.data(), + nmeta_mpi, all_metadata.data(), - mcounts.data(), - mdispls.data(), + metacounts.data(), + metadispls.data(), comm); const int nproc = Parallel_Common::comm_size(comm); const int ip = Parallel_Common::comm_rank(comm); - std::vector send(nproc, 0); + std::vector sendcounts(nproc, 0); std::vector views; views.reserve(nproc); std::size_t metadata_offset = 0; @@ -389,9 +394,9 @@ void scatter_from_host(const Matrix2d& matglb, Matrix2d& matloc) view.iprow = all_metadata[metadata_offset + 4]; view.ipcol = all_metadata[metadata_offset + 5]; metadata_offset += LOCAL_METADATA_SIZE; - const std::size_t axes_count + const std::size_t naxes = static_cast(view.nrloc + view.ncloc); - if (metadata_offset + axes_count > all_metadata.size()) + if (metadata_offset + naxes > all_metadata.size()) { throw std::invalid_argument("Matrix2d scatter axes are truncated"); } @@ -400,19 +405,19 @@ void scatter_from_host(const Matrix2d& matglb, Matrix2d& matloc) view.icglb.assign(all_metadata.begin() + metadata_offset + view.nrloc, all_metadata.begin() + metadata_offset + view.nrloc + view.ncloc); - metadata_offset += axes_count; + 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 local_elements + const std::size_t nelem_local = static_cast(view.nrloc) * static_cast(view.ncloc); - const std::size_t local_buffer_size = local_elements * sizeof(T); - const int local_buffer_bytes = checked_mpi_count(local_buffer_size); - send[ipsrc] = local_buffer_bytes; + const std::size_t nbytes_local = nelem_local * sizeof(T); + assert_valid_mpi_count(nbytes_local); + sendcounts[ipsrc] = mpi_count(nbytes_local); views.push_back(view); } if (metadata_offset != all_metadata.size()) @@ -424,11 +429,11 @@ void scatter_from_host(const Matrix2d& matglb, Matrix2d& matloc) throw std::invalid_argument("scatter global matrix shape does not match distribution"); } - const std::vector sdispls = make_byte_displacements(send); + const std::vector sdispls = make_byte_displs(sendcounts); std::vector sendbuf; if (ip == 0) { - const int total_bytes = sdispls.back() + send.back(); + const int total_bytes = sdispls.back() + sendcounts.back(); sendbuf.resize(total_bytes); for (int ipdst = 0; ipdst < nproc; ++ipdst) { @@ -443,7 +448,7 @@ void scatter_from_host(const Matrix2d& matglb, Matrix2d& matloc) = static_cast(irloc) * static_cast(view.ncloc) + static_cast(icloc); - const T& value = matglb.at_local(irglb, icglb); + const T& value = matglb.atloc(irglb, icglb); const std::size_t send_offset = static_cast(sdispls[ipdst]) + idx * sizeof(T); @@ -455,15 +460,16 @@ void scatter_from_host(const Matrix2d& matglb, Matrix2d& matloc) } } - const std::size_t receive_elements + const std::size_t nelem_recv = static_cast(matloc.nrloc()) * static_cast(matloc.ncloc()); - const std::size_t receive_buffer_bytes = receive_elements * sizeof(T); - std::vector recvbuf(receive_buffer_bytes); - const int recv = checked_mpi_count(receive_buffer_bytes); + const std::size_t nbytes_recv = nelem_recv * sizeof(T); + std::vector recvbuf(nbytes_recv); + assert_valid_mpi_count(nbytes_recv); + const int recv = mpi_count(nbytes_recv); const unsigned char* receive_source = ip == 0 ? sendbuf.data() : nullptr; Parallel_Common::scatterv_bytes(receive_source, - send.data(), + sendcounts.data(), sdispls.data(), recvbuf.data(), recv, @@ -483,7 +489,7 @@ void scatter_from_host(const Matrix2d& matglb, Matrix2d& matloc) = recvbuf.data() + receive_offset; T value; std::memcpy(&value, source, sizeof(T)); - matloc.at_local(irloc, icloc) = value; + matloc.atloc(irloc, icloc) = value; } } } diff --git a/source/source_base/matrix2d_lapack.cpp b/source/source_base/matrix2d_lapack.cpp index a0632b48ed3..a378f94daa9 100644 --- a/source/source_base/matrix2d_lapack.cpp +++ b/source/source_base/matrix2d_lapack.cpp @@ -10,7 +10,7 @@ namespace { -void check_host_layout(const Matrix2dView& matrix) +void assert_host_layout(const Matrix2dView& matrix) { if (matrix.is_distributed() && !matrix.distribution()->is_serial()) { @@ -18,7 +18,7 @@ void check_host_layout(const Matrix2dView& matrix) } } -void check_host_layout(const Matrix2dView>& matrix) +void assert_host_layout(const Matrix2dView>& matrix) { if (matrix.is_distributed() && !matrix.distribution()->is_serial()) { @@ -26,7 +26,7 @@ void check_host_layout(const Matrix2dView>& matrix) } } -void check_inverse_dimensions(const int nr, const int nc) +void assert_inverse_dimensions(const int nr, const int nc) { if (nr <= 0 || nr != nc) { @@ -34,9 +34,9 @@ void check_inverse_dimensions(const int nr, const int nc) } } -void check_solve_dimensions(const int nr, - const int nc, - const int rhs_nr) +void assert_solve_dimensions(const int nr, + const int nc, + const int rhs_nr) { if (nr <= 0 || nr != nc || rhs_nr != nr) { @@ -66,9 +66,9 @@ namespace lapack { void inv(Matrix2dView matrix) { - check_host_layout(matrix); + assert_host_layout(matrix); const int n = matrix.nrglb(); - check_inverse_dimensions(n, matrix.ncglb()); + assert_inverse_dimensions(n, matrix.ncglb()); const int lda = matrix.lld(); std::vector ipiv(static_cast(n)); @@ -108,9 +108,9 @@ void inv(Matrix2dView matrix) void inv(Matrix2dView> matrix) { - check_host_layout(matrix); + assert_host_layout(matrix); const int n = matrix.nrglb(); - check_inverse_dimensions(n, matrix.ncglb()); + assert_inverse_dimensions(n, matrix.ncglb()); const int lda = matrix.lld(); std::vector ipiv(static_cast(n)); @@ -151,11 +151,11 @@ void inv(Matrix2dView> matrix) void solve(Matrix2dView matrix, Matrix2dView rhs) { - check_host_layout(matrix); - check_host_layout(rhs); + assert_host_layout(matrix); + assert_host_layout(rhs); const int n = matrix.nrglb(); const int nrhs = rhs.ncglb(); - check_solve_dimensions(n, matrix.ncglb(), rhs.nrglb()); + assert_solve_dimensions(n, matrix.ncglb(), rhs.nrglb()); const int lda = matrix.lld(); std::vector ipiv(static_cast(n)); @@ -178,7 +178,7 @@ void solve(Matrix2dView matrix, rhs_column_major[static_cast(i) + static_cast(j) * static_cast(n)] - = rhs.at_local(i, j); + = rhs.atloc(i, j); } } @@ -199,7 +199,7 @@ void solve(Matrix2dView matrix, { for (int j = 0; j < nrhs; ++j) { - rhs.at_local(i, j) + rhs.atloc(i, j) = rhs_column_major[static_cast(i) + static_cast(j) * static_cast(n)]; @@ -210,11 +210,11 @@ void solve(Matrix2dView matrix, void solve(Matrix2dView> matrix, Matrix2dView> rhs) { - check_host_layout(matrix); - check_host_layout(rhs); + assert_host_layout(matrix); + assert_host_layout(rhs); const int n = matrix.nrglb(); const int nrhs = rhs.ncglb(); - check_solve_dimensions(n, matrix.ncglb(), rhs.nrglb()); + assert_solve_dimensions(n, matrix.ncglb(), rhs.nrglb()); const int lda = matrix.lld(); std::vector ipiv(static_cast(n)); @@ -237,7 +237,7 @@ void solve(Matrix2dView> matrix, rhs_column_major[static_cast(i) + static_cast(j) * static_cast(n)] - = rhs.at_local(i, j); + = rhs.atloc(i, j); } } @@ -258,7 +258,7 @@ void solve(Matrix2dView> matrix, { for (int j = 0; j < nrhs; ++j) { - rhs.at_local(i, j) + rhs.atloc(i, j) = rhs_column_major[static_cast(i) + static_cast(j) * static_cast(n)]; diff --git a/source/source_base/matrix2d_linalg.cpp b/source/source_base/matrix2d_linalg.cpp index 1a8d227fb38..1249f51f177 100644 --- a/source/source_base/matrix2d_linalg.cpp +++ b/source/source_base/matrix2d_linalg.cpp @@ -25,8 +25,8 @@ bool has_serial_distribution(const Matrix2dView& matrix) } template -void check_same_shape(const Matrix2dView& left, - const Matrix2dView& right) +void assert_same_shape(const Matrix2dView& left, + const Matrix2dView& right) { if (left.nrglb() != right.nrglb() || left.ncglb() != right.ncglb()) { @@ -35,8 +35,8 @@ void check_same_shape(const Matrix2dView& left, } template -void check_compatible_layout(const Matrix2dView& left, - const Matrix2dView& right) +void assert_compatible_layout(const Matrix2dView& left, + const Matrix2dView& right) { if (left.is_distributed() != right.is_distributed()) { @@ -47,14 +47,14 @@ void check_compatible_layout(const Matrix2dView& left, { return; } - const bool left_is_serial = has_serial_distribution(left); - const bool right_is_serial = has_serial_distribution(right); - if (left_is_serial != right_is_serial) + const bool serial = has_serial_distribution(left); + const bool serial_ = has_serial_distribution(right); + if (serial != serial_) { throw std::invalid_argument( "matrix operations require matching serial or parallel distributions"); } - if (left_is_serial) + if (serial) { return; } @@ -72,9 +72,9 @@ void check_compatible_layout(const Matrix2dView& left, } template -void check_matmul_views(Matrix2dView result, - Matrix2dView left, - Matrix2dView right) +void assert_matmul_views(Matrix2dView result, + Matrix2dView left, + Matrix2dView right) { if (left.ncglb() != right.nrglb() || result.nrglb() != left.nrglb() @@ -82,8 +82,8 @@ void check_matmul_views(Matrix2dView result, { throw std::invalid_argument("matrix multiplication dimensions are incompatible"); } - check_compatible_layout(result, left); - check_compatible_layout(result, right); + assert_compatible_layout(result, left); + assert_compatible_layout(result, right); } template @@ -98,9 +98,9 @@ void matmul_host(Matrix2dView result, T value = T(); for (int k = 0; k < left.ncglb(); ++k) { - value += left.at_local(i, k) * right.at_local(k, j); + value += left.atloc(i, k) * right.atloc(k, j); } - result.at_local(i, j) = value; + result.atloc(i, j) = value; } } } @@ -112,16 +112,16 @@ void linear_combination_impl(Matrix2dView result, const T beta, Matrix2dView right) { - check_same_shape(result, left); - check_same_shape(result, right); - check_compatible_layout(result, left); - check_compatible_layout(result, right); + assert_same_shape(result, left); + assert_same_shape(result, right); + assert_compatible_layout(result, left); + assert_compatible_layout(result, right); for (int i = 0; i < result.nrloc(); ++i) { for (int j = 0; j < result.ncloc(); ++j) { - result.at_local(i, j) - = alpha * left.at_local(i, j) + beta * right.at_local(i, j); + result.atloc(i, j) + = alpha * left.atloc(i, j) + beta * right.atloc(i, j); } } } @@ -133,7 +133,7 @@ void scale_impl(Matrix2dView matrix, const T factor) { for (int j = 0; j < matrix.ncloc(); ++j) { - matrix.at_local(i, j) *= factor; + matrix.atloc(i, j) *= factor; } } } @@ -145,20 +145,20 @@ void set_identity_impl(Matrix2dView matrix) { throw std::invalid_argument("identity requires a square matrix"); } - const std::shared_ptr dist + 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 = dist == nullptr ? i : dist->irglb(i); - const int icglb = dist == nullptr ? j : dist->icglb(j); - matrix.at_local(i, j) = irglb == icglb ? T(1.0) : T(); + 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 check_inverse_view(const Matrix2dView& matrix) +void assert_inverse_view(const Matrix2dView& matrix) { if (matrix.nrglb() <= 0 || matrix.nrglb() != matrix.ncglb()) { @@ -166,7 +166,7 @@ void check_inverse_view(const Matrix2dView& matrix) } } -void check_inverse_view(const Matrix2dView>& matrix) +void assert_inverse_view(const Matrix2dView>& matrix) { if (matrix.nrglb() <= 0 || matrix.nrglb() != matrix.ncglb()) { @@ -174,8 +174,8 @@ void check_inverse_view(const Matrix2dView>& matrix) } } -void check_solve_views(const Matrix2dView& matrix, - const Matrix2dView& rhs) +void assert_solve_views(const Matrix2dView& matrix, + const Matrix2dView& rhs) { if (matrix.nrglb() <= 0 || matrix.nrglb() != matrix.ncglb() @@ -212,8 +212,8 @@ void check_solve_views(const Matrix2dView& matrix, } } -void check_solve_views(const Matrix2dView>& matrix, - const Matrix2dView>& rhs) +void assert_solve_views(const Matrix2dView>& matrix, + const Matrix2dView>& rhs) { if (matrix.nrglb() <= 0 || matrix.nrglb() != matrix.ncglb() @@ -255,7 +255,7 @@ namespace matrix2d_linalg { void inv(Matrix2dView matrix) { - check_inverse_view(matrix); + assert_inverse_view(matrix); if (has_active_distribution(matrix)) { #ifdef __MPI @@ -270,7 +270,7 @@ void inv(Matrix2dView matrix) void inv(Matrix2dView> matrix) { - check_inverse_view(matrix); + assert_inverse_view(matrix); if (has_active_distribution(matrix)) { #ifdef __MPI @@ -286,7 +286,7 @@ void inv(Matrix2dView> matrix) void solve(Matrix2dView matrix, Matrix2dView rhs) { - check_solve_views(matrix, rhs); + assert_solve_views(matrix, rhs); if (has_active_distribution(matrix)) { #ifdef __MPI @@ -302,7 +302,7 @@ void solve(Matrix2dView matrix, void solve(Matrix2dView> matrix, Matrix2dView> rhs) { - check_solve_views(matrix, rhs); + assert_solve_views(matrix, rhs); if (has_active_distribution(matrix)) { #ifdef __MPI @@ -319,7 +319,7 @@ void matmul(Matrix2dView result, Matrix2dView left, Matrix2dView right) { - check_matmul_views(result, left, right); + assert_matmul_views(result, left, right); if (has_active_distribution(result)) { #ifdef __MPI @@ -336,7 +336,7 @@ void matmul(Matrix2dView> result, Matrix2dView> left, Matrix2dView> right) { - check_matmul_views(result, left, right); + assert_matmul_views(result, left, right); if (has_active_distribution(result)) { #ifdef __MPI diff --git a/source/source_base/matrix2d_reduction.cpp b/source/source_base/matrix2d_reduction.cpp index 2dedfc797e7..c517c9039e3 100644 --- a/source/source_base/matrix2d_reduction.cpp +++ b/source/source_base/matrix2d_reduction.cpp @@ -17,17 +17,20 @@ namespace { +namespace elementwise +{ template -T conjugate_value(const T& value) +T conj(const T& value) { return value; } template -std::complex conjugate_value(const std::complex& value) +std::complex conj(const std::complex& value) { return std::conj(value); } +} // namespace elementwise template double absolute_square(const T& value) @@ -39,9 +42,9 @@ double absolute_square(const T& value) template double absolute_square(const std::complex& value) { - const double real_value = static_cast(value.real()); - const double imaginary_value = static_cast(value.imag()); - return real_value * real_value + imaginary_value * imaginary_value; + const double real = static_cast(value.real()); + const double imag = static_cast(value.imag()); + return real * real + imag * imag; } template @@ -61,11 +64,11 @@ template void reduce_sum_over_processes(Value& value, const Matrix2d& matrix) { #ifdef __MPI - const std::shared_ptr dist + const std::shared_ptr distrib = matrix.distribution(); - if (dist != nullptr && !dist->is_serial()) + if (distrib != nullptr && !distrib->is_serial()) { - const MPI_Comm comm = dist->comm(); + const MPI_Comm comm = distrib->comm(); if (comm != MPI_COMM_NULL) { Parallel_Common::allreduce_sum(value, comm); @@ -81,11 +84,11 @@ template void reduce_max_over_processes(double& value, const Matrix2d& matrix) { #ifdef __MPI - const std::shared_ptr dist + const std::shared_ptr distrib = matrix.distribution(); - if (dist != nullptr && !dist->is_serial()) + if (distrib != nullptr && !distrib->is_serial()) { - const MPI_Comm comm = dist->comm(); + const MPI_Comm comm = distrib->comm(); if (comm != MPI_COMM_NULL) { Parallel_Common::allreduce_max(value, comm); @@ -97,50 +100,54 @@ void reduce_max_over_processes(double& value, const Matrix2d& matrix) #endif } -int checked_mpi_count(const std::size_t count) +void assert_valid_mpi_count(const std::size_t nbytes) { - if (count > static_cast(std::numeric_limits::max())) + if (nbytes > static_cast(std::numeric_limits::max())) { throw std::invalid_argument( "Matrix2d diagonal data buffer exceeds MPI count range"); } - return static_cast(count); } -std::vector make_byte_displacements(const std::vector& counts) +int mpi_count(const std::size_t nbytes) +{ + return static_cast(nbytes); +} + +std::vector make_byte_displs(const std::vector& nbytes) { - std::vector displacements(counts.size(), 0); - int off = 0; - for (std::size_t ip = 0; ip < counts.size(); ++ip) + std::vector displs(nbytes.size(), 0); + int offset = 0; + for (std::size_t ip = 0; ip < nbytes.size(); ++ip) { - displacements[ip] = off; - if (counts[ip] > std::numeric_limits::max() - off) + displs[ip] = offset; + if (nbytes[ip] > std::numeric_limits::max() - offset) { throw std::invalid_argument( "Matrix2d diagonal data buffer size overflow"); } - off += counts[ip]; + offset += nbytes[ip]; } - return displacements; + return displs; } #ifdef __MPI -std::vector gather_byte_counts(const int local_count, const MPI_Comm comm) +std::vector gather_nbytes(const int nbytes_local, const MPI_Comm comm) { const int nproc = Parallel_Common::comm_size(comm); - const std::vector recv( - static_cast(nproc), - checked_mpi_count(sizeof(int))); + const int nbytes_int = static_cast(sizeof(int)); + const std::vector recvcounts(static_cast(nproc), + nbytes_int); const std::vector rdispls - = make_byte_displacements(recv); - std::vector counts(static_cast(nproc), 0); - Parallel_Common::allgatherv_bytes(&local_count, - checked_mpi_count(sizeof(local_count)), - counts.data(), - recv.data(), + = make_byte_displs(recvcounts); + std::vector nbytes(static_cast(nproc), 0); + Parallel_Common::allgatherv_bytes(&nbytes_local, + nbytes_int, + nbytes.data(), + recvcounts.data(), rdispls.data(), comm); - return counts; + return nbytes; } #endif } // namespace @@ -163,7 +170,7 @@ T sum(const Matrix2d& matrix) { for (int j = 0; j < ncloc; ++j) { - partial_sums[ip] += matrix.at_local(i, j); + partial_sums[ip] += matrix.atloc(i, j); } } } @@ -176,7 +183,7 @@ T sum(const Matrix2d& matrix) { for (int j = 0; j < ncloc; ++j) { - value += matrix.at_local(i, j); + value += matrix.atloc(i, j); } } #endif @@ -185,7 +192,7 @@ T sum(const Matrix2d& matrix) } template -double sum_squares(const Matrix2d& matrix) +double norm(const Matrix2d& matrix) { double value = 0.0; const int nrloc = matrix.nrloc(); @@ -197,11 +204,11 @@ double sum_squares(const Matrix2d& matrix) { for (int j = 0; j < ncloc; ++j) { - value += absolute_square(matrix.at_local(i, j)); + value += absolute_square(matrix.atloc(i, j)); } } reduce_sum_over_processes(value, matrix); - return value; + return std::sqrt(value); } template @@ -220,9 +227,8 @@ T dot(const Matrix2d& left, const Matrix2d& right) { for (int j = 0; j < ncloc; ++j) { - partial_sums[ip] - += conjugate_value(left.at_local(i, j)) - * right.at_local(i, j); + partial_sums[ip] += elementwise::conj(left.atloc(i, j)) + * right.atloc(i, j); } } } @@ -235,8 +241,8 @@ T dot(const Matrix2d& left, const Matrix2d& right) { for (int j = 0; j < ncloc; ++j) { - value += conjugate_value(left.at_local(i, j)) - * right.at_local(i, j); + value += elementwise::conj(left.atloc(i, j)) + * right.atloc(i, j); } } #endif @@ -244,12 +250,6 @@ T dot(const Matrix2d& left, const Matrix2d& right) return value; } -template -double norm2(const Matrix2d& matrix) -{ - return std::sqrt(sum_squares(matrix)); -} - template double max_abs(const Matrix2d& matrix) { @@ -263,7 +263,7 @@ double max_abs(const Matrix2d& matrix) { for (int j = 0; j < ncloc; ++j) { - const T& element = matrix.at_local(i, j); + const T& element = matrix.atloc(i, j); const double element_abs = absolute_value(element); max_value = std::max(max_value, element_abs); } @@ -279,39 +279,38 @@ std::vector diagonal(const Matrix2d& matrix) std::vector values(static_cast(diagonal_size), T()); const int nrloc = matrix.nrloc(); const int ncloc = matrix.ncloc(); - const std::shared_ptr dist + 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 = dist == nullptr ? irloc : dist->irglb(irloc); - const int icglb = dist == nullptr ? icloc : dist->icglb(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.at_local(irloc, icloc); + const T value = matrix.atloc(irloc, icloc); local_entries.push_back(std::pair(irglb, value)); } } } #ifdef __MPI - if (dist != nullptr && !dist->is_serial()) + if (distrib != nullptr && !distrib->is_serial()) { - const MPI_Comm comm = dist->comm(); + const MPI_Comm comm = distrib->comm(); if (comm != MPI_COMM_NULL) { - const std::size_t entry_bytes = sizeof(int) + sizeof(T); - const std::size_t local_diagonal_buffer_bytes - = sizeof(int) + local_entries.size() * entry_bytes; - std::vector local_diagonal_buffer( - local_diagonal_buffer_bytes); - const int local_entry_count - = checked_mpi_count(local_entries.size()); + const std::size_t nbytes_entry = sizeof(int) + sizeof(T); + const std::size_t nbytes_local + = sizeof(int) + local_entries.size() * nbytes_entry; + std::vector local_diagonal_buffer(nbytes_local); + assert_valid_mpi_count(local_entries.size()); + const int nentry_local = mpi_count(local_entries.size()); std::memcpy(local_diagonal_buffer.data(), - &local_entry_count, - sizeof(local_entry_count)); - std::size_t offset = sizeof(local_entry_count); + &nentry_local, + sizeof(nentry_local)); + std::size_t offset = sizeof(nentry_local); for (const std::pair& entry : local_entries) { std::memcpy(local_diagonal_buffer.data() + offset, @@ -324,71 +323,71 @@ std::vector diagonal(const Matrix2d& matrix) offset += sizeof(entry.second); } - const int local_count - = checked_mpi_count(local_diagonal_buffer.size()); - const std::vector pcounts - = gather_byte_counts(local_count, comm); - const std::vector pdispls - = make_byte_displacements(pcounts); + assert_valid_mpi_count(nbytes_local); + const int nbytes_local_mpi = mpi_count(nbytes_local); + const std::vector recvcounts + = gather_nbytes(nbytes_local_mpi, comm); + const std::vector rdispls + = make_byte_displs(recvcounts); const int total_bytes - = pdispls.back() + pcounts.back(); + = rdispls.back() + recvcounts.back(); std::vector received( static_cast(total_bytes)); Parallel_Common::allgatherv_bytes(local_diagonal_buffer.data(), - local_count, + nbytes_local_mpi, received.data(), - pcounts.data(), - pdispls.data(), + recvcounts.data(), + rdispls.data(), comm); - for (std::size_t ip = 0; ip < pcounts.size(); ++ip) + for (std::size_t ip = 0; ip < recvcounts.size(); ++ip) { const std::size_t begin - = static_cast(pdispls[ip]); + = static_cast(rdispls[ip]); const std::size_t end - = begin + static_cast(pcounts[ip]); + = begin + static_cast(recvcounts[ip]); if (end - begin < sizeof(int)) { throw std::runtime_error( "Matrix2d diagonal data buffer is truncated"); } - int entry_count = 0; - std::memcpy(&entry_count, + int nentry = 0; + std::memcpy(&nentry, received.data() + begin, - sizeof(entry_count)); + sizeof(nentry)); const std::size_t expected_bytes - = static_cast(entry_count) * entry_bytes; - if (entry_count < 0 + = static_cast(nentry) * nbytes_entry; + if (nentry < 0 || end - begin != sizeof(int) + expected_bytes) { throw std::runtime_error( "Matrix2d diagonal data buffer has an invalid size"); } - std::size_t entry_offset = begin + sizeof(entry_count); - for (int ientry = 0; ientry < entry_count; ++ientry) + std::size_t entry_offset = begin + sizeof(nentry); + for (int ientry = 0; ientry < nentry; ++ientry) { - int index = 0; + int irglb = 0; T value = T(); - std::memcpy(&index, + std::memcpy(&irglb, received.data() + entry_offset, - sizeof(index)); - entry_offset += sizeof(index); + sizeof(irglb)); + entry_offset += sizeof(irglb); std::memcpy(&value, received.data() + entry_offset, sizeof(value)); entry_offset += sizeof(value); - if (index < 0 || index >= diagonal_size) + if (irglb < 0 || irglb >= diagonal_size) { throw std::runtime_error( - "Matrix2d diagonal index is outside global shape"); + "Matrix2d diagonal entry is outside global shape"); } - values[static_cast(index)] += value; + values[static_cast(irglb)] += value; } } } } #endif - if (dist == nullptr || dist->is_serial()) + if (distrib == nullptr || distrib->is_serial()) { for (const std::pair& entry : local_entries) { @@ -406,14 +405,6 @@ template std::complex sum>( template std::complex sum>( const Matrix2d>& matrix); -template double sum_squares(const Matrix2d& matrix); -template double sum_squares(const Matrix2d& matrix); -template double sum_squares(const Matrix2d& matrix); -template double sum_squares>( - const Matrix2d>& matrix); -template double sum_squares>( - const Matrix2d>& matrix); - template int dot(const Matrix2d& left, const Matrix2d& right); template float dot(const Matrix2d& left, const Matrix2d& right); @@ -426,12 +417,12 @@ template std::complex dot>( const Matrix2d>& left, const Matrix2d>& right); -template double norm2(const Matrix2d& matrix); -template double norm2(const Matrix2d& matrix); -template double norm2(const Matrix2d& matrix); -template double norm2>( +template double norm(const Matrix2d& matrix); +template double norm(const Matrix2d& matrix); +template double norm(const Matrix2d& matrix); +template double norm>( const Matrix2d>& matrix); -template double norm2>( +template double norm>( const Matrix2d>& matrix); template double max_abs(const Matrix2d& matrix); diff --git a/source/source_base/matrix2d_reduction.h b/source/source_base/matrix2d_reduction.h index 488f97f0588..a91ee6fbc34 100644 --- a/source/source_base/matrix2d_reduction.h +++ b/source/source_base/matrix2d_reduction.h @@ -8,14 +8,11 @@ namespace matrix2d_impl template T sum(const Matrix2d& matrix); -template -double sum_squares(const Matrix2d& matrix); - template T dot(const Matrix2d& left, const Matrix2d& right); template -double norm2(const Matrix2d& matrix); +double norm(const Matrix2d& matrix); template double max_abs(const Matrix2d& matrix); diff --git a/source/source_base/matrix2d_scalapack.cpp b/source/source_base/matrix2d_scalapack.cpp index 812e3f5b4a3..f728d2f5b49 100644 --- a/source/source_base/matrix2d_scalapack.cpp +++ b/source/source_base/matrix2d_scalapack.cpp @@ -112,7 +112,7 @@ void conjugate_transpose( namespace { -void check_scalapack_error(const char* operation, const int info) +void throw_scalapack_error(const char* operation, const int info) { if (info < 0) { @@ -155,7 +155,7 @@ void inv(Matrix2dView matrix) desc, ipiv.data(), &info); - check_scalapack_error("ScaLAPACK getrf", info); + throw_scalapack_error("ScaLAPACK getrf", info); int lwork = -1; int liwork = -1; @@ -172,7 +172,7 @@ void inv(Matrix2dView matrix) iwork.data(), &liwork, &info); - check_scalapack_error("ScaLAPACK getri workspace query", info); + throw_scalapack_error("ScaLAPACK getri workspace query", info); lwork = queried_workspace_size(work[0]); liwork = iwork[0]; work.resize(static_cast(lwork)); @@ -188,7 +188,7 @@ void inv(Matrix2dView matrix) iwork.data(), &liwork, &info); - check_scalapack_error("ScaLAPACK getri", info); + throw_scalapack_error("ScaLAPACK getri", info); } void inv(Matrix2dView> matrix) @@ -208,7 +208,7 @@ void inv(Matrix2dView> matrix) desc, ipiv.data(), &info); - check_scalapack_error("ScaLAPACK getrf", info); + throw_scalapack_error("ScaLAPACK getrf", info); int lwork = -1; int liwork = -1; @@ -225,7 +225,7 @@ void inv(Matrix2dView> matrix) iwork.data(), &liwork, &info); - check_scalapack_error("ScaLAPACK getri workspace query", info); + throw_scalapack_error("ScaLAPACK getri workspace query", info); lwork = queried_workspace_size(work[0]); liwork = iwork[0]; work.resize(static_cast(lwork)); @@ -241,7 +241,7 @@ void inv(Matrix2dView> matrix) iwork.data(), &liwork, &info); - check_scalapack_error("ScaLAPACK getri", info); + throw_scalapack_error("ScaLAPACK getri", info); } void solve(Matrix2dView matrix, @@ -268,7 +268,7 @@ void solve(Matrix2dView matrix, jb, rhs.desc(), &info); - check_scalapack_error("ScaLAPACK gesv", info); + throw_scalapack_error("ScaLAPACK gesv", info); } void solve(Matrix2dView> matrix, @@ -295,7 +295,7 @@ void solve(Matrix2dView> matrix, jb, rhs.desc(), &info); - check_scalapack_error("ScaLAPACK gesv", info); + throw_scalapack_error("ScaLAPACK gesv", info); } void matmul(Matrix2dView result, diff --git a/source/source_base/matrix2d_view.h b/source/source_base/matrix2d_view.h index 64ac4971418..17f878401af 100644 --- a/source/source_base/matrix2d_view.h +++ b/source/source_base/matrix2d_view.h @@ -32,7 +32,7 @@ class Matrix2dView ncloc_(other.ncloc()), lld_(other.lld()), desc_(other.desc()), - dist_(other.distribution()) + distrib_(other.distribution()) { } @@ -44,14 +44,14 @@ class Matrix2dView ncloc_(ncglb), lld_(ncglb), desc_(nullptr), - dist_(nullptr) + distrib_(nullptr) { assert(nrglb_ >= 0); assert(ncglb_ >= 0); } Matrix2dView(T* data, - std::shared_ptr dist) + std::shared_ptr distrib) : data_(data), nrglb_(0), ncglb_(0), @@ -59,16 +59,21 @@ class Matrix2dView ncloc_(0), lld_(0), desc_(nullptr), - dist_(std::move(dist)) + distrib_(std::move(distrib)) { - const Parallel_Blkcyclic& distrib = checked_distribution(dist_); - nrglb_ = distrib.nrglb(); - ncglb_ = distrib.ncglb(); - nrloc_ = distrib.nrloc(); - ncloc_ = distrib.ncloc(); - lld_ = distrib.lld(); + 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_ = distrib.desc(); + desc_ = distribution.desc(); #endif } @@ -84,11 +89,11 @@ class Matrix2dView * static_cast(ncloc_); } - bool is_distributed() const { return dist_ != nullptr; } + bool is_distributed() const { return distrib_ != nullptr; } const std::shared_ptr& distribution() const { - return dist_; + return distrib_; } const int* desc() const @@ -96,13 +101,13 @@ class Matrix2dView return desc_; } - T& at_local(const int i, const int j) const + 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 = dist_ == nullptr + const std::size_t offset = distrib_ == nullptr ? static_cast(i) * static_cast(ncloc_) + static_cast(j) : static_cast(j) * static_cast(lld_) @@ -111,16 +116,6 @@ class Matrix2dView } private: - static const Parallel_Blkcyclic& checked_distribution( - const std::shared_ptr& dist) - { - if (dist == nullptr) - { - throw std::invalid_argument("matrix view distribution must not be null"); - } - return *dist; - } - T* data_; int nrglb_; int ncglb_; @@ -128,7 +123,7 @@ class Matrix2dView int ncloc_; int lld_; const int* desc_; - std::shared_ptr dist_; + std::shared_ptr distrib_; }; #endif diff --git a/source/source_base/parallel_blkcyc.cpp b/source/source_base/parallel_blkcyc.cpp index 297a8eb186d..9004b58eaa0 100644 --- a/source/source_base/parallel_blkcyc.cpp +++ b/source/source_base/parallel_blkcyc.cpp @@ -299,10 +299,10 @@ std::shared_ptr make_frozen_distribution( const int nb, const MPI_Comm comm) { - std::shared_ptr dist + std::shared_ptr distrib = std::make_shared(); - dist->init(nrglb, ncglb, nb, comm, false); - return dist; + distrib->init(nrglb, ncglb, nb, comm, false); + return distrib; } std::shared_ptr make_frozen_distribution( @@ -313,12 +313,12 @@ std::shared_ptr make_frozen_distribution( const int nb, const MPI_Comm comm) { - std::shared_ptr dist + std::shared_ptr distrib = std::make_shared(); - dist->init_grid(comm, nrproc, ncproc); - dist->init_dist(nrglb, ncglb, nb); - dist->owns_ictxt_ = true; - return dist; + distrib->init_grid(comm, nrproc, ncproc); + distrib->init_dist(nrglb, ncglb, nb); + distrib->owns_ictxt_ = true; + return distrib; } std::shared_ptr make_borrowed_distribution( @@ -327,10 +327,10 @@ std::shared_ptr make_borrowed_distribution( const int nb, const int ictxt) { - std::shared_ptr dist + std::shared_ptr distrib = std::make_shared(); - dist->set(nrglb, ncglb, nb, ictxt); - return dist; + distrib->set(nrglb, ncglb, nb, ictxt); + return distrib; } std::shared_ptr make_borrowed_distribution( @@ -348,11 +348,11 @@ std::shared_ptr make_borrowed_distribution( throw std::invalid_argument( "distribution owner must have an active BLACS context"); } - std::shared_ptr dist + std::shared_ptr distrib = std::make_shared(); - dist->set(nrglb, ncglb, nb, owner->ictxt()); - dist->context_owner_ = owner; - return dist; + distrib->set(nrglb, ncglb, nb, owner->ictxt()); + distrib->context_owner_ = owner; + return distrib; } #endif @@ -360,8 +360,8 @@ std::shared_ptr make_frozen_distribution( const int nrglb, const int ncglb) { - std::shared_ptr dist + std::shared_ptr distrib = std::make_shared(); - dist->set_serial(nrglb, ncglb); - return dist; + distrib->set_serial(nrglb, ncglb); + return distrib; } diff --git a/source/source_base/parallel_common.cpp b/source/source_base/parallel_common.cpp index 7e1ce75bd89..a56a5e0fab6 100644 --- a/source/source_base/parallel_common.cpp +++ b/source/source_base/parallel_common.cpp @@ -119,56 +119,56 @@ void barrier(const MPI_Comm comm) MPI_Barrier(comm); } -void gatherv_bytes(const void* send_buffer, - const int send_count, - void* receive_buffer, - const int* receive_counts, - const int* receive_displacements, +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(send_buffer, - send_count, + MPI_Gatherv(sendbuf, + send, MPI_BYTE, - receive_buffer, - receive_counts, - receive_displacements, + recvbuf, + recvcounts, + rdispls, MPI_BYTE, root, comm); } -void allgatherv_bytes(const void* send_buffer, - const int send_count, - void* receive_buffer, - const int* receive_counts, - const int* receive_displacements, +void allgatherv_bytes(const void* sendbuf, + const int send, + void* recvbuf, + const int* recvcounts, + const int* rdispls, const MPI_Comm comm) { - MPI_Allgatherv(send_buffer, - send_count, + MPI_Allgatherv(sendbuf, + send, MPI_BYTE, - receive_buffer, - receive_counts, - receive_displacements, + recvbuf, + recvcounts, + rdispls, MPI_BYTE, comm); } -void scatterv_bytes(const void* send_buffer, - const int* send_counts, - const int* send_displacements, - void* receive_buffer, - const int receive_count, +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(send_buffer, - send_counts, - send_displacements, + MPI_Scatterv(sendbuf, + sendcounts, + sdispls, MPI_BYTE, - receive_buffer, - receive_count, + recvbuf, + recv, MPI_BYTE, root, comm); diff --git a/source/source_base/parallel_common.h b/source/source_base/parallel_common.h index 3ef57180cb3..4d844b113de 100644 --- a/source/source_base/parallel_common.h +++ b/source/source_base/parallel_common.h @@ -58,26 +58,26 @@ void bcast_mpi_offset(MPI_Offset& object, const MPI_Comm& comm); void barrier(const MPI_Comm comm); -void gatherv_bytes(const void* send_buffer, - int send_count, - void* receive_buffer, - const int* receive_counts, - const int* receive_displacements, +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* send_buffer, - int send_count, - void* receive_buffer, - const int* receive_counts, - const int* receive_displacements, +void allgatherv_bytes(const void* sendbuf, + int send, + void* recvbuf, + const int* recvcounts, + const int* rdispls, MPI_Comm comm); -void scatterv_bytes(const void* send_buffer, - const int* send_counts, - const int* send_displacements, - void* receive_buffer, - int receive_count, +void scatterv_bytes(const void* sendbuf, + const int* sendcounts, + const int* sdispls, + void* recvbuf, + int recv, int root, MPI_Comm comm); @@ -92,50 +92,50 @@ inline void barrier() { } -inline void gatherv_bytes(const void* send_buffer, - int send_count, - void* receive_buffer, +inline void gatherv_bytes(const void* sendbuf, + int send, + void* recvbuf, const int*, const int*, int, int) { - if (receive_buffer != nullptr && send_count > 0) + if (recvbuf != nullptr && send > 0) { - std::copy(static_cast(send_buffer), - static_cast(send_buffer) + send_count, - static_cast(receive_buffer)); + std::copy(static_cast(sendbuf), + static_cast(sendbuf) + send, + static_cast(recvbuf)); } } -inline void allgatherv_bytes(const void* send_buffer, - int send_count, - void* receive_buffer, +inline void allgatherv_bytes(const void* sendbuf, + int send, + void* recvbuf, const int*, const int*, int) { - if (receive_buffer != nullptr && send_count > 0) + if (recvbuf != nullptr && send > 0) { - std::copy(static_cast(send_buffer), - static_cast(send_buffer) + send_count, - static_cast(receive_buffer)); + std::copy(static_cast(sendbuf), + static_cast(sendbuf) + send, + static_cast(recvbuf)); } } -inline void scatterv_bytes(const void* send_buffer, +inline void scatterv_bytes(const void* sendbuf, const int*, const int*, - void* receive_buffer, - int receive_count, + void* recvbuf, + int recv, int, int) { - if (receive_buffer != nullptr && receive_count > 0) + if (recvbuf != nullptr && recv > 0) { - std::copy(static_cast(send_buffer), - static_cast(send_buffer) + receive_count, - static_cast(receive_buffer)); + std::copy(static_cast(sendbuf), + static_cast(sendbuf) + recv, + static_cast(recvbuf)); } } #endif diff --git a/source/source_base/unittests/test_matrix2d.cpp b/source/source_base/unittests/test_matrix2d.cpp index 9c8a4689192..d2108d4a1a6 100644 --- a/source/source_base/unittests/test_matrix2d.cpp +++ b/source/source_base/unittests/test_matrix2d.cpp @@ -139,7 +139,7 @@ void check_host_layout() EXPECT_EQ(matrix.lld(), 3); EXPECT_EQ(matrix.desc(), nullptr); EXPECT_EQ(matrix.ictxt(), -1); - EXPECT_EQ(matrix.data(), &matrix.at_local(0, 0)); + EXPECT_EQ(matrix.data(), &matrix.atloc(0, 0)); double value = 1.0; for (int ir = 0; ir < 2; ++ir) @@ -148,10 +148,10 @@ void check_host_layout() { const std::size_t expected_index = static_cast(ir) * 3U + static_cast(ic); - EXPECT_EQ(&matrix.at_local(ir, ic), matrix.data() + expected_index); - EXPECT_EQ(&matrix.at_global(ir, ic), &matrix.at_local(ir, ic)); - EXPECT_TRUE(matrix.owns_global_index(ir, ic)); - matrix.at_local(ir, ic) = value; + 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; } } @@ -165,8 +165,8 @@ void check_host_layout() const Matrix2d& const_matrix = matrix; EXPECT_EQ(const_matrix.data(), matrix.data()); - EXPECT_EQ(&const_matrix.at_local(1, 2), matrix.data() + 5); - EXPECT_EQ(&const_matrix.at_global(1, 2), matrix.data() + 5); + 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, @@ -199,7 +199,7 @@ void check_distribution_layout(Matrix2d& matrix, const std::size_t expected_index = static_cast(icloc) * lld + static_cast(irloc); - EXPECT_EQ(&matrix.at_local(irloc, icloc), matrix.data() + expected_index); + EXPECT_EQ(&matrix.atloc(irloc, icloc), matrix.data() + expected_index); } } @@ -208,7 +208,7 @@ void check_distribution_layout(Matrix2d& matrix, for (int icglb = 0; icglb < ncglb; ++icglb) { const bool expected_owner = distrib->in_this_processor(irglb, icglb); - EXPECT_EQ(matrix.owns_global_index(irglb, icglb), expected_owner); + EXPECT_EQ(matrix.in_this_processor(irglb, icglb), expected_owner); if (!expected_owner) { continue; @@ -218,11 +218,11 @@ void check_distribution_layout(Matrix2d& matrix, const int icloc = distrib->icloc(icglb); ASSERT_NE(irloc, -1); ASSERT_NE(icloc, -1); - EXPECT_EQ(&matrix.at_global(irglb, icglb), - &matrix.at_local(irloc, icloc)); + EXPECT_EQ(&matrix.atglb(irglb, icglb), + &matrix.atloc(irloc, icloc)); const double value = static_cast(irglb * ncglb + icglb); - matrix.at_global(irglb, icglb) = value; - EXPECT_EQ(matrix.at_local(irloc, icloc), value); + matrix.atglb(irglb, icglb) = value; + EXPECT_EQ(matrix.atloc(irloc, icloc), value); } } @@ -374,9 +374,9 @@ void fill_global_values(Matrix2d& matrix, const double offset = 0.0) { for (int ic = 0; ic < matrix.ncglb(); ++ic) { - if (matrix.owns_global_index(ir, ic)) + if (matrix.in_this_processor(ir, ic)) { - matrix.at_global(ir, ic) = test_value(ir, ic, offset); + matrix.atglb(ir, ic) = test_value(ir, ic, offset); } } } @@ -392,7 +392,7 @@ Matrix2d make_host_reference(const int nr, { for (int ic = 0; ic < nc; ++ic) { - reference.at_local(ir, ic) = test_value(ir, ic, offset); + reference.atloc(ir, ic) = test_value(ir, ic, offset); } } return reference; @@ -413,7 +413,7 @@ void verify_global_matrix(const Matrix2d& actual, const Matrix2d& expected * static_cast(expected.ncglb()) + static_cast(ic); expect_scalar_near(actual.data()[c_order_index], - expected.at_local(ir, ic)); + expected.atloc(ir, ic)); } } } @@ -438,7 +438,7 @@ void check_elementwise_operations(Matrix2d& matrix, Matrix2d& other) { for (int ic = 0; ic < nc; ++ic) { - expected.at_local(ir, ic) *= constant_value(2.5); + expected.atloc(ir, ic) *= constant_value(2.5); } } verify_global_matrix(filled.gather(), expected); @@ -451,7 +451,7 @@ void check_elementwise_operations(Matrix2d& matrix, Matrix2d& other) { for (int ic = 0; ic < nc; ++ic) { - expected.at_local(ir, ic) += expected_other.at_local(ir, ic); + expected.atloc(ir, ic) += expected_other.atloc(ir, ic); } } verify_global_matrix(filled.gather(), expected); @@ -463,7 +463,7 @@ void check_elementwise_operations(Matrix2d& matrix, Matrix2d& other) { for (int ic = 0; ic < nc; ++ic) { - expected.at_local(ir, ic) -= expected_other.at_local(ir, ic); + expected.atloc(ir, ic) -= expected_other.atloc(ir, ic); } } verify_global_matrix(filled.gather(), expected); @@ -475,7 +475,7 @@ void check_elementwise_operations(Matrix2d& matrix, Matrix2d& other) { for (int ic = 0; ic < nc; ++ic) { - expected.at_local(ir, ic) *= expected_other.at_local(ir, ic); + expected.atloc(ir, ic) *= expected_other.atloc(ir, ic); } } verify_global_matrix(filled.gather(), expected); @@ -487,8 +487,8 @@ void check_elementwise_operations(Matrix2d& matrix, Matrix2d& other) { for (int ic = 0; ic < nc; ++ic) { - expected.at_local(ir, ic) - = conjugate_value(expected.at_local(ir, ic)); + expected.atloc(ir, ic) + = conjugate_value(expected.atloc(ir, ic)); } } verify_global_matrix(filled.gather(), expected); @@ -500,22 +500,12 @@ void check_elementwise_operations(Matrix2d& matrix, Matrix2d& other) { for (int ic = 0; ic < nc; ++ic) { - const T& value = matrix_reference.at_local(ir, ic); - expected_real.at_local(ir, ic) = real_part(value); - expected_imag.at_local(ir, ic) = imaginary_part(value); + const T& value = matrix_reference.atloc(ir, ic); + expected_real.atloc(ir, ic) = real_part(value); + expected_imag.atloc(ir, ic) = imaginary_part(value); } } - Matrix2d real_output = matrix.is_distributed() - ? Matrix2d(matrix.distribution()) - : Matrix2d(nr, nc); - Matrix2d imaginary_output = matrix.is_distributed() - ? Matrix2d(matrix.distribution()) - : Matrix2d(nr, nc); - matrix.real(real_output); - matrix.imag(imaginary_output); - verify_global_matrix(real_output.gather(), expected_real); - verify_global_matrix(imaginary_output.gather(), expected_imag); verify_global_matrix(matrix.real().gather(), expected_real); verify_global_matrix(matrix.imag().gather(), expected_imag); } @@ -532,17 +522,17 @@ void check_reductions(Matrix2d& matrix, Matrix2d& other) 10.0); T reference_sum = T(); T reference_dot = T(); - double reference_sum_squares = 0.0; + 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.at_local(ir, ic); - const T& other_value = other_reference.at_local(ir, 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_sum_squares += real_part(value) * real_part(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))); @@ -551,10 +541,9 @@ void check_reductions(Matrix2d& matrix, Matrix2d& other) expect_scalar_near(matrix.sum(), reference_sum); expect_scalar_near(matrix.dot(other), reference_dot); - const T expected_self_dot = static_cast(matrix.sum_squares()); + const T expected_self_dot = static_cast(reference_norm_sq); expect_scalar_near(matrix.dot(matrix), expected_self_dot); - expect_scalar_near(matrix.sum_squares(), reference_sum_squares); - expect_scalar_near(matrix.norm2(), std::sqrt(reference_sum_squares)); + 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(); @@ -563,7 +552,7 @@ void check_reductions(Matrix2d& matrix, Matrix2d& other) for (int i = 0; i < diagonal_size; ++i) { expect_scalar_near(diagonal[static_cast(i)], - matrix_reference.at_local(i, i)); + matrix_reference.atloc(i, i)); } } @@ -615,8 +604,8 @@ void check_gather_scatter(Matrix2d& matrix) template std::size_t expected_local_storage_size(const Matrix2d& matrix) { - const int lld_dist = matrix.lld(); - const int lld = std::max(lld_dist, 1); + const int lld_distrib = matrix.lld(); + const int lld = std::max(lld_distrib, 1); const std::size_t column_major_elements = static_cast(lld) * static_cast(matrix.ncloc()); @@ -635,8 +624,8 @@ std::vector set_padding_sentinel(Matrix2d& matrix, { const int nrloc = matrix.nrloc(); const int ncloc = matrix.ncloc(); - const int lld_dist = matrix.lld(); - const std::size_t lld = static_cast(lld_dist); + const int lld_distrib = matrix.lld(); + const std::size_t lld = static_cast(lld_distrib); const std::size_t storage_elements = expected_local_storage_size(matrix); std::vector is_logical(storage_elements, 0); std::vector padding_indices; @@ -712,8 +701,8 @@ Matrix2d make_transpose_reference(const Matrix2d& source) { for (int ic = 0; ic < nc; ++ic) { - reference.at_local(ic, ir) - = source.at_local(ir, ic); + reference.atloc(ic, ir) + = source.atloc(ir, ic); } } return reference; @@ -729,8 +718,8 @@ Matrix2d make_dagger_reference(const Matrix2d& source) { for (int ic = 0; ic < nc; ++ic) { - reference.at_local(ic, ir) - = conjugate_value(source.at_local(ir, ic)); + reference.atloc(ic, ir) + = conjugate_value(source.atloc(ir, ic)); } } return reference; @@ -749,11 +738,11 @@ Matrix2d make_matmul_reference(const Matrix2d& left, for (int ic = 0; ic < n; ++ic) { T value = T(); - for (int kk = 0; kk < k; ++kk) + for (int ik = 0; ik < k; ++ik) { - value += left.at_local(ir, kk) * right.at_local(kk, ic); + value += left.atloc(ir, ik) * right.atloc(ik, ic); } - reference.at_local(ir, ic) = value; + reference.atloc(ir, ic) = value; } } return reference; @@ -998,23 +987,23 @@ TEST(Matrix2dTest, SerialDegenerateDistributionTransposeAndMatmul) TEST(Matrix2dTest, TransposeAndDaggerDistributedMatchHost) { const std::vector> grids = available_process_grids(); - for (std::size_t grid_index = 0; grid_index < grids.size(); ++grid_index) + for (std::size_t igrid = 0; igrid < grids.size(); ++igrid) { check_distributed_transpose(5, 3, - grids[grid_index].first, - grids[grid_index].second, + grids[igrid].first, + grids[igrid].second, 3); check_distributed_transpose(3, 5, - grids[grid_index].first, - grids[grid_index].second, + grids[igrid].first, + grids[igrid].second, 3); check_distributed_transpose>(5, 3, - grids[grid_index].first, - grids[grid_index].second, + grids[igrid].first, + grids[igrid].second, 3); check_distributed_transpose>(3, 5, - grids[grid_index].first, - grids[grid_index].second, + grids[igrid].first, + grids[igrid].second, 3); } } @@ -1042,15 +1031,15 @@ TEST(Matrix2dTest, DistributedResultRetainsBlacsContext) TEST(Matrix2dTest, MatmulDistributedMatchesHost) { const std::vector> grids = available_process_grids(); - for (std::size_t grid_index = 0; grid_index < grids.size(); ++grid_index) + for (std::size_t igrid = 0; igrid < grids.size(); ++igrid) { check_distributed_matmul(5, 4, 6, - grids[grid_index].first, - grids[grid_index].second, + grids[igrid].first, + grids[igrid].second, 3); check_distributed_matmul>(5, 4, 6, - grids[grid_index].first, - grids[grid_index].second, + grids[igrid].first, + grids[igrid].second, 3); } } @@ -1129,10 +1118,11 @@ TEST(Matrix2dTest, IncompatibleDistributionThrows) { const std::vector> grids = available_process_grids(); const std::pair& grid = grids[0]; - const int block = 3; + const int nrblk = 3; { - Matrix2d first(8, 6, grid.first, grid.second, block, MPI_COMM_WORLD); - Matrix2d different_block(6, 8, grid.first, grid.second, block + 1, MPI_COMM_WORLD); + 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); @@ -1140,15 +1130,17 @@ TEST(Matrix2dTest, IncompatibleDistributionThrows) if (grids.size() > 1) { const std::pair& other_grid = grids[1]; - Matrix2d first(8, 6, grid.first, grid.second, block, MPI_COMM_WORLD); - Matrix2d different_grid(6, 8, other_grid.first, other_grid.second, block, MPI_COMM_WORLD); + 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, block, MPI_COMM_WORLD); - Matrix2d different_context(6, 8, grid.first, grid.second, block, MPI_COMM_WORLD); + 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); @@ -1159,11 +1151,11 @@ TEST(Matrix2dTest, DescriptorAddressStableAcrossOperators) { const std::vector> grids = available_process_grids(); const std::pair& grid = grids[0]; - const int block = 3; - Matrix2d left(5, 4, grid.first, grid.second, block, MPI_COMM_WORLD); + 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, block, ictxt); + = make_borrowed_distribution(4, 6, nrblk, ictxt); Matrix2d right(right_distrib); fill_global_values(left); fill_global_values(right, 10.0); @@ -1192,22 +1184,22 @@ TEST(Matrix2dTest, HostConstructionAndRowMajorLayout) TEST(Matrix2dTest, HostCopyDeepCopiesStorage) { Matrix2d source(2, 2); - source.at_local(0, 0) = 1.0; - source.at_local(0, 1) = 2.0; - source.at_local(1, 0) = 3.0; - source.at_local(1, 1) = 4.0; + 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.at_local(1, 1), 4.0); - copy.at_local(1, 1) = 9.0; - EXPECT_EQ(source.at_local(1, 1), 4.0); + 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.at_local(0, 1), 2.0); + EXPECT_EQ(assigned.atloc(0, 1), 2.0); } TEST(Matrix2dTest, SerialDistributionHandleUsesColumnMajorLayout) @@ -1260,8 +1252,8 @@ TEST(Matrix2dTest, SerialDistributionViewMatchesColumnMajorStorageWithoutMpi) { for (int icloc = 0; icloc < matrix.ncloc(); ++icloc) { - EXPECT_EQ(&matrix_view.at_local(irloc, icloc), - &matrix.at_local(irloc, icloc)); + EXPECT_EQ(&matrix_view.atloc(irloc, icloc), + &matrix.atloc(irloc, icloc)); } } @@ -1272,8 +1264,8 @@ TEST(Matrix2dTest, SerialDistributionViewMatchesColumnMajorStorageWithoutMpi) { for (int icloc = 0; icloc < matrix.ncloc(); ++icloc) { - EXPECT_EQ(&const_view.at_local(irloc, icloc), - &matrix.at_local(irloc, icloc)); + EXPECT_EQ(&const_view.atloc(irloc, icloc), + &matrix.atloc(irloc, icloc)); } } } @@ -1284,15 +1276,15 @@ TEST(Matrix2dTest, CopiesShareDistributionAndDeepCopyStorage) const std::shared_ptr distrib = make_frozen_distribution(3, 2); Matrix2d source(distrib); - source.at_local(0, 0) = 7.0; + 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.at_local(0, 0), 7.0); - copy.at_local(0, 0) = 8.0; - EXPECT_EQ(source.at_local(0, 0), 7.0); + 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) @@ -1400,8 +1392,8 @@ TEST(Matrix2dTest, HostComplexElementwiseAndReductions) TEST(Matrix2dTest, MaxAbsWidensIntegerBeforeTakingAbsoluteValue) { Matrix2d matrix(1, 2); - matrix.at_local(0, 0) = std::numeric_limits::min(); - matrix.at_local(0, 1) = std::numeric_limits::max(); + 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; @@ -1429,16 +1421,16 @@ TEST(Matrix2dTest, DistributedDoubleAcrossBlocksAndProcessGrids) { report_reduction_tolerances(); const std::vector> grids = available_process_grids(); - const int blocks[] = {2, 3, 4}; - for (std::size_t grid_index = 0; grid_index < grids.size(); ++grid_index) + const int nrblks[] = {2, 3, 4}; + for (std::size_t igrid = 0; igrid < grids.size(); ++igrid) { - for (std::size_t block_index = 0; block_index < 3; ++block_index) + for (std::size_t iblk = 0; iblk < 3; ++iblk) { Matrix2d matrix(9, 7, - grids[grid_index].first, - grids[grid_index].second, - blocks[block_index], + grids[igrid].first, + grids[igrid].second, + nrblks[iblk], MPI_COMM_WORLD); Matrix2d other(matrix.distribution()); fill_global_values(matrix); @@ -1454,16 +1446,16 @@ TEST(Matrix2dTest, DistributedComplexAcrossBlocksAndProcessGrids) { report_reduction_tolerances(); const std::vector> grids = available_process_grids(); - const int blocks[] = {2, 3, 4}; - for (std::size_t grid_index = 0; grid_index < grids.size(); ++grid_index) + const int nrblks[] = {2, 3, 4}; + for (std::size_t igrid = 0; igrid < grids.size(); ++igrid) { - for (std::size_t block_index = 0; block_index < 3; ++block_index) + for (std::size_t iblk = 0; iblk < 3; ++iblk) { Matrix2d> matrix(9, 7, - grids[grid_index].first, - grids[grid_index].second, - blocks[block_index], + grids[igrid].first, + grids[igrid].second, + nrblks[iblk], MPI_COMM_WORLD); Matrix2d> other(matrix.distribution()); fill_global_values(matrix); @@ -1528,7 +1520,7 @@ TEST(Matrix2dTest, TallSkinnyPaddingDoesNotAffectOperatorsOrGather) { for (int ic = 0; ic < ncglb; ++ic) { - expected.at_local(ir, ic) += other_reference.at_local(ir, ic); + expected.atloc(ir, ic) += other_reference.atloc(ir, ic); } } verify_global_matrix(matrix.gather(), expected); diff --git a/source/source_base/unittests/test_matrix2d_linalg.cpp b/source/source_base/unittests/test_matrix2d_linalg.cpp index e4e240e8118..7639fcd7f9b 100644 --- a/source/source_base/unittests/test_matrix2d_linalg.cpp +++ b/source/source_base/unittests/test_matrix2d_linalg.cpp @@ -38,7 +38,7 @@ void expect_host_matrices_near(const Matrix2d& actual, { for (int j = 0; j < expected.ncglb(); ++j) { - expect_near(actual.at_local(i, j), expected.at_local(i, j)); + expect_near(actual.atloc(i, j), expected.atloc(i, j)); } } } @@ -46,40 +46,40 @@ void expect_host_matrices_near(const Matrix2d& actual, Matrix2d make_real_system() { Matrix2d matrix(2, 2); - matrix.at_local(0, 0) = 4.0; - matrix.at_local(0, 1) = 1.0; - matrix.at_local(1, 0) = 2.0; - matrix.at_local(1, 1) = 3.0; + 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_inverse_reference() { Matrix2d inverse(2, 2); - inverse.at_local(0, 0) = 0.3; - inverse.at_local(0, 1) = -0.1; - inverse.at_local(1, 0) = -0.2; - inverse.at_local(1, 1) = 0.4; + 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.at_local(0, 0) = std::complex(1.0, 1.0); - matrix.at_local(0, 1) = std::complex(2.0, 0.0); - matrix.at_local(1, 0) = std::complex(3.0, 0.0); - matrix.at_local(1, 1) = std::complex(4.0, -1.0); + 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.at_local(0, 0) = std::complex(1.0, 0.0); - solution.at_local(0, 1) = std::complex(0.0, 2.0); - solution.at_local(1, 0) = std::complex(3.0, 0.0); - solution.at_local(1, 1) = std::complex(4.0, 0.0); + 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; } @@ -115,15 +115,15 @@ Matrix2d make_distributed_real_system(const int size) { if (i == j) { - matrix.at_local(i, j) = 6.0 + i; + matrix.atloc(i, j) = 6.0 + i; } else if (std::abs(i - j) == 1) { - matrix.at_local(i, j) = 0.5; + matrix.atloc(i, j) = 0.5; } else { - matrix.at_local(i, j) = 0.0; + matrix.atloc(i, j) = 0.0; } } } @@ -138,7 +138,7 @@ Matrix2d make_distributed_real_solution(const int nr, { for (int j = 0; j < nc; ++j) { - solution.at_local(i, j) + solution.atloc(i, j) = static_cast(1 + i + 2 * j); } } @@ -154,22 +154,22 @@ Matrix2d> make_distributed_complex_system(const int size) { if (i == j) { - matrix.at_local(i, j) + matrix.atloc(i, j) = std::complex(6.0 + i, 0.5); } else if (j == i + 1) { - matrix.at_local(i, j) + matrix.atloc(i, j) = std::complex(0.5, 0.25); } else if (j + 1 == i) { - matrix.at_local(i, j) + matrix.atloc(i, j) = std::complex(0.5, -0.25); } else { - matrix.at_local(i, j) = std::complex(0.0, 0.0); + matrix.atloc(i, j) = std::complex(0.0, 0.0); } } } @@ -185,7 +185,7 @@ Matrix2d> make_distributed_complex_solution( { for (int j = 0; j < nc; ++j) { - solution.at_local(i, j) + solution.atloc(i, j) = std::complex(1 + i + 2 * j, i - j); } } @@ -206,18 +206,18 @@ void check_distributed_solve(const Matrix2d& host_matrix, ncproc, nrblk, MPI_COMM_WORLD); - const std::shared_ptr solution_dist + const std::shared_ptr solution_distrib = make_borrowed_distribution(host_solution.nrglb(), host_solution.ncglb(), nrblk, matrix.ictxt()); - const std::shared_ptr rhs_dist + const std::shared_ptr rhs_distrib = make_borrowed_distribution(host_rhs.nrglb(), host_rhs.ncglb(), nrblk, matrix.ictxt()); - Matrix2d solution(solution_dist); - Matrix2d rhs(rhs_dist); + Matrix2d solution(solution_distrib); + Matrix2d rhs(rhs_distrib); matrix.scatter(host_matrix); solution.scatter(host_solution); const Matrix2d& matrix_input = matrix; @@ -261,10 +261,10 @@ TEST(Matrix2dLinalgTest, HostRealInverseAndSolve) expect_host_matrices_near(inverse, make_real_inverse_reference()); Matrix2d rhs(2, 2); - rhs.at_local(0, 0) = 1.0; - rhs.at_local(0, 1) = 2.0; - rhs.at_local(1, 0) = 3.0; - rhs.at_local(1, 1) = 4.0; + 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 expected = make_real_inverse_reference().matmul(rhs); Matrix2d matrix = make_real_system(); matrix2d_linalg::solve(matrix.view(), rhs.view()); @@ -284,10 +284,10 @@ TEST(Matrix2dLinalgTest, HostComplexSolve) Matrix2d> inverse = make_complex_system(); matrix2d_linalg::inv(inverse.view()); Matrix2d> inverse_reference(2, 2); - inverse_reference.at_local(0, 0) = std::complex(-0.7, -1.1); - inverse_reference.at_local(0, 1) = std::complex(0.2, 0.6); - inverse_reference.at_local(1, 0) = std::complex(0.3, 0.9); - inverse_reference.at_local(1, 1) = std::complex(0.2, -0.4); + 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); } @@ -297,26 +297,26 @@ TEST(Matrix2dLinalgTest, SerialDistributionUsesLocalBackend) = make_frozen_distribution(2, 2); Matrix2d matrix(distrib); - matrix.at_local(0, 0) = 4.0; - matrix.at_local(0, 1) = 1.0; - matrix.at_local(1, 0) = 2.0; - matrix.at_local(1, 1) = 3.0; + matrix.atloc(0, 0) = 4.0; + matrix.atloc(0, 1) = 1.0; + matrix.atloc(1, 0) = 2.0; + matrix.atloc(1, 1) = 3.0; Matrix2d rhs(distrib); - rhs.at_local(0, 0) = 1.0; - rhs.at_local(0, 1) = 2.0; - rhs.at_local(1, 0) = 3.0; - rhs.at_local(1, 1) = 4.0; + 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 expected = make_real_inverse_reference().matmul(rhs); matrix2d_linalg::solve(matrix.view(), rhs.view()); expect_host_matrices_near(rhs, expected); Matrix2d inverse(distrib); - inverse.at_local(0, 0) = 4.0; - inverse.at_local(0, 1) = 1.0; - inverse.at_local(1, 0) = 2.0; - inverse.at_local(1, 1) = 3.0; + inverse.atloc(0, 0) = 4.0; + inverse.atloc(0, 1) = 1.0; + inverse.atloc(1, 0) = 2.0; + inverse.atloc(1, 1) = 3.0; matrix2d_linalg::inv(inverse.view()); expect_host_matrices_near(inverse, make_real_inverse_reference()); } @@ -326,12 +326,12 @@ 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.at_local(0, 0) = 1.0; - rhs.at_local(1, 0) = 2.0; + rhs.atloc(0, 0) = 1.0; + rhs.atloc(1, 0) = 2.0; matrix2d_linalg::solve(matrix, rhs.view()); - expect_near(rhs.at_local(0, 0), 0.1); - expect_near(rhs.at_local(1, 0), 0.6); + expect_near(rhs.atloc(0, 0), 0.1); + expect_near(rhs.atloc(1, 0), 0.6); EXPECT_EQ(matrix.data(), values.data()); } @@ -351,9 +351,9 @@ TEST(Matrix2dLinalgTest, HostViewMatmulAndLinearCombination) { for (int j = 0; j < 2; ++j) { - combined_reference.at_local(i, j) - = 2.0 * left.at_local(i, j) - - 0.5 * right.at_local(i, 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); @@ -365,9 +365,9 @@ TEST(Matrix2dLinalgTest, HostViewMatmulAndLinearCombination) for (int j = 0; j < 2; ++j) { const double identity_value = i == j ? 1.0 : 0.0; - expect_near(combined.at_local(i, j), - 3.0 * combined_reference.at_local(i, j)); - expect_near(product.at_local(i, j), identity_value); + expect_near(combined.atloc(i, j), + 3.0 * combined_reference.atloc(i, j)); + expect_near(product.atloc(i, j), identity_value); } } } @@ -375,10 +375,10 @@ TEST(Matrix2dLinalgTest, HostViewMatmulAndLinearCombination) TEST(Matrix2dLinalgTest, RejectsSingularAndMismatchedMatrices) { Matrix2d singular(2, 2); - singular.at_local(0, 0) = 1.0; - singular.at_local(0, 1) = 2.0; - singular.at_local(1, 0) = 2.0; - singular.at_local(1, 1) = 4.0; + 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.view()), std::runtime_error); Matrix2d matrix = make_real_system(); @@ -400,21 +400,21 @@ TEST(Matrix2dLinalgTest, DistributedRealAndComplexSolve) const Matrix2d> complex_solution = make_distributed_complex_solution(size, nrhs); const std::vector> grids = available_process_grids(); - const int blocks[] = {2, 3}; - for (std::size_t grid_index = 0; grid_index < grids.size(); ++grid_index) + const int nrblks[] = {2, 3}; + for (std::size_t igrid = 0; igrid < grids.size(); ++igrid) { - for (std::size_t block_index = 0; block_index < 2; ++block_index) + for (std::size_t iblk = 0; iblk < 2; ++iblk) { check_distributed_solve(real_matrix, real_solution, - grids[grid_index].first, - grids[grid_index].second, - blocks[block_index]); + grids[igrid].first, + grids[igrid].second, + nrblks[iblk]); check_distributed_solve(complex_matrix, complex_solution, - grids[grid_index].first, - grids[grid_index].second, - blocks[block_index]); + grids[igrid].first, + grids[igrid].second, + nrblks[iblk]); } } } @@ -426,19 +426,19 @@ TEST(Matrix2dLinalgTest, DistributedRealAndComplexInverse) const Matrix2d> complex_matrix = make_distributed_complex_system(size); const std::vector> grids = available_process_grids(); - const int blocks[] = {2, 3}; - for (std::size_t grid_index = 0; grid_index < grids.size(); ++grid_index) + const int nrblks[] = {2, 3}; + for (std::size_t igrid = 0; igrid < grids.size(); ++igrid) { - for (std::size_t block_index = 0; block_index < 2; ++block_index) + for (std::size_t iblk = 0; iblk < 2; ++iblk) { check_distributed_inverse(real_matrix, - grids[grid_index].first, - grids[grid_index].second, - blocks[block_index]); + grids[igrid].first, + grids[igrid].second, + nrblks[iblk]); check_distributed_inverse(complex_matrix, - grids[grid_index].first, - grids[grid_index].second, - blocks[block_index]); + grids[igrid].first, + grids[igrid].second, + nrblks[iblk]); } } } @@ -446,17 +446,17 @@ TEST(Matrix2dLinalgTest, DistributedRealAndComplexInverse) TEST(Matrix2dLinalgTest, DistributedIdentityAndLinearCombination) { const int size = 5; - const int blocks[] = {2, 3}; + const int nrblks[] = {2, 3}; const std::vector> grids = available_process_grids(); - for (std::size_t grid_index = 0; grid_index < grids.size(); ++grid_index) + for (std::size_t igrid = 0; igrid < grids.size(); ++igrid) { - for (std::size_t block_index = 0; block_index < 2; ++block_index) + for (std::size_t iblk = 0; iblk < 2; ++iblk) { Matrix2d identity(size, size, - grids[grid_index].first, - grids[grid_index].second, - blocks[block_index], + grids[igrid].first, + grids[igrid].second, + nrblks[iblk], MPI_COMM_WORLD); matrix2d_linalg::set_identity(identity.view()); Matrix2d identity_expected(size, size); @@ -477,9 +477,9 @@ TEST(Matrix2dLinalgTest, DistributedIdentityAndLinearCombination) { for (int j = 0; j < size; ++j) { - combined_expected.at_local(i, j) - = 2.0 * host_left.at_local(i, j) - + 0.5 * identity_expected.at_local(i, j); + combined_expected.atloc(i, j) + = 2.0 * host_left.atloc(i, j) + + 0.5 * identity_expected.atloc(i, j); } } expect_host_matrices_near(combined.gather(), combined_expected); From fbaf698331b85b712f37c8e80eef6b007125da9d Mon Sep 17 00:00:00 2001 From: kirk0830 Date: Sun, 22 Nov 2026 20:12:00 +0800 Subject: [PATCH 08/15] refactor(base): align Matrix2d naming and docs with review (part A) --- source/source_base/matrix2d.h | 46 +++-- source/source_base/matrix2d_collective.cpp | 183 ++++++++++-------- source/source_base/matrix2d_lapack.cpp | 62 +++--- source/source_base/matrix2d_linalg.cpp | 77 +++++--- source/source_base/matrix2d_linalg.h | 40 +++- source/source_base/matrix2d_reduction.cpp | 55 +++--- source/source_base/matrix2d_scalapack.cpp | 64 +++--- source/source_base/matrix2d_view.h | 86 +++++++- .../source_base/unittests/test_matrix2d.cpp | 45 ++--- .../unittests/test_matrix2d_linalg.cpp | 24 ++- 10 files changed, 417 insertions(+), 265 deletions(-) diff --git a/source/source_base/matrix2d.h b/source/source_base/matrix2d.h index 21b99e24c7e..c663b422db4 100644 --- a/source/source_base/matrix2d.h +++ b/source/source_base/matrix2d.h @@ -17,6 +17,14 @@ template class Matrix2dView; +/** + * @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 { @@ -294,12 +302,24 @@ class NDArray final } const std::shared_ptr& distribution() const { return distrib_; } + /** + * @brief Return whether a frozen distribution handle is attached. + * + * A serial one-by-one distribution also returns true. This predicate does + * not mean that an active multi-rank distribution is present. + */ bool is_distributed() const { return distrib_ != nullptr; } 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 { }; @@ -362,22 +382,20 @@ class NDArray final assert(nrloc_ >= 0); assert(ncloc_ >= 0); - const int lld_distrib = distrib_->lld(); - const int lld = std::max(lld_distrib, 1); - const std::size_t ld = static_cast(lld); - // The actual BLACS/LAPACK buffer is column-major. The row-major extent - // is kept in the maximum as a guard for local logical accesses. - const std::size_t column_major_elements - = ld * static_cast(ncloc_); - const std::size_t row_major_elements + 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 logical_extent - = std::max(column_major_elements, row_major_elements); - const std::size_t empty_rank_minimum = 1; - const std::size_t storage_elements - = std::max(logical_extent, empty_rank_minimum); - storage_.resize(storage_elements); + 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; diff --git a/source/source_base/matrix2d_collective.cpp b/source/source_base/matrix2d_collective.cpp index 70a4a792013..5ce4f80954d 100644 --- a/source/source_base/matrix2d_collective.cpp +++ b/source/source_base/matrix2d_collective.cpp @@ -6,23 +6,22 @@ #include #include #include +#include #include namespace { 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); -void assert_valid_mpi_count(const std::size_t nbytes) +int checked_mpi_count(const std::size_t nbytes) { if (nbytes > static_cast(std::numeric_limits::max())) { throw std::invalid_argument( "Matrix2d collective matrix buffer exceeds MPI count range"); } -} - -int mpi_count(const std::size_t nbytes) -{ return static_cast(nbytes); } @@ -46,24 +45,36 @@ std::vector make_byte_displs(const std::vector& nbytes) std::vector allgather_nbytes(const int nbytes_local, const MPI_Comm comm) { const int nproc = Parallel_Common::comm_size(comm); - const int nbytes_int = static_cast(sizeof(int)); - std::vector recvcounts(static_cast(nproc), nbytes_int); + const std::vector nbytes_recv(static_cast(nproc), W_INT); const std::vector rdispls - = make_byte_displs(recvcounts); + = make_byte_displs(nbytes_recv); std::vector nbytes(static_cast(nproc), 0); Parallel_Common::allgatherv_bytes(&nbytes_local, - nbytes_int, + W_INT, nbytes.data(), - recvcounts.data(), + nbytes_recv.data(), rdispls.data(), comm); return nbytes; } +/** + * @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(); std::vector metadata; @@ -87,28 +98,30 @@ std::vector make_local_metadata(const Matrix2d& matrix) } template -std::vector make_local_matrix_buffer(const Matrix2d& matrix) +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 nmeta_bytes = nmeta * sizeof(int); - const std::size_t data_elements = static_cast(matrix.nrloc()) + 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 data_bytes = data_elements * sizeof(T); - const std::size_t nbytes_buffer = nmeta_bytes + data_bytes; - std::vector buffer(nbytes_buffer); + 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(), nmeta_bytes); + 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 = nmeta_bytes + idx * sizeof(T); + const std::size_t offset = nbytes_meta + idx * sizeof(T); unsigned char* const destination = buffer.data() + offset; std::memcpy(destination, &value, sizeof(T)); @@ -117,7 +130,7 @@ std::vector make_local_matrix_buffer(const Matrix2d& matrix) return buffer; } -struct LocalMatrixBufferView +struct LocalBufferView { int nrloc = 0; int ncloc = 0; @@ -131,10 +144,10 @@ struct LocalMatrixBufferView }; template -LocalMatrixBufferView view_local_matrix_buffer( +LocalBufferView view_local_buffer( const std::vector& buffer) { - if (buffer.size() < LOCAL_METADATA_SIZE * sizeof(int)) + if (buffer.size() < LOCAL_METADATA_SIZE * W_INT) { throw std::invalid_argument( "Matrix2d collective matrix buffer is truncated"); @@ -142,7 +155,7 @@ LocalMatrixBufferView view_local_matrix_buffer( int header[LOCAL_METADATA_SIZE] = {}; std::memcpy(header, buffer.data(), sizeof(header)); - LocalMatrixBufferView view; + LocalBufferView view; view.nrloc = header[0]; view.ncloc = header[1]; view.nrglb = header[2]; @@ -159,38 +172,38 @@ LocalMatrixBufferView view_local_matrix_buffer( const std::size_t nmeta = static_cast(LOCAL_METADATA_SIZE) + view.nrloc + view.ncloc; - const std::size_t nmeta_bytes = nmeta * sizeof(int); - const std::size_t data_elements + 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 expected_bytes = nmeta_bytes + data_elements * sizeof(T); - if (buffer.size() != expected_bytes) + 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(), nmeta_bytes); + 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() + nmeta_bytes; + view.data = buffer.data() + nbytes_meta; return view; } template -Matrix2d rebuild_global_matrix( +Matrix2d rebuild_global( const std::vector>& buffers) { - std::vector views; + 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_matrix_buffer(buffers[ip])); - const LocalMatrixBufferView& view = views.back(); + views.push_back(view_local_buffer(buffers[ip])); + const LocalBufferView& view = views.back(); if (ip == 0) { nrglb = view.nrglb; @@ -205,7 +218,7 @@ Matrix2d rebuild_global_matrix( Matrix2d result(nrglb, ncglb); for (std::size_t ip = 0; ip < views.size(); ++ip) { - const LocalMatrixBufferView& view = views[ip]; + const LocalBufferView& view = views[ip]; for (int irloc = 0; irloc < view.nrloc; ++irloc) { const int irglb = view.irglb[irloc]; @@ -234,35 +247,37 @@ Matrix2d rebuild_global_matrix( } template -std::vector> allgather_local_matrix_buffers( +std::vector> allgather_local_buffers( const Matrix2d& matrix, const MPI_Comm comm) { - const std::vector local_buffer - = make_local_matrix_buffer(matrix); - assert_valid_mpi_count(local_buffer.size()); - const int nbytes_local_mpi = mpi_count(local_buffer.size()); - const std::vector recvcounts + const std::vector locbuf + = make_local_buffer(matrix); + const int nbytes_local_mpi = checked_mpi_count(locbuf.size()); + const std::vector nbytes_recv = allgather_nbytes(nbytes_local_mpi, comm); const std::vector rdispls - = make_byte_displs(recvcounts); - const int total_bytes = rdispls.back() + recvcounts.back(); - std::vector received(total_bytes); + = make_byte_displs(nbytes_recv); + const int nbytes_total = rdispls.back() + nbytes_recv.back(); + std::vector rxbuf(nbytes_total); - Parallel_Common::allgatherv_bytes(local_buffer.data(), + Parallel_Common::allgatherv_bytes(locbuf.data(), nbytes_local_mpi, - received.data(), - recvcounts.data(), + rxbuf.data(), + nbytes_recv.data(), rdispls.data(), comm); - std::vector> buffers(recvcounts.size()); - for (std::size_t ip = 0; ip < recvcounts.size(); ++ip) + std::vector> buffers(nbytes_recv.size()); + // Iterate in communicator rank order and split the contiguous receive + // buffer into per-rank byte segments, as required by MPI_Allgatherv. + 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(recvcounts[ip]); - buffers[ip].assign(received.begin() + begin, received.begin() + end); + const auto rank_begin = static_cast(rdispls[ip]); + const auto rank_end + = rank_begin + static_cast(nbytes_recv[ip]); + buffers[ip].assign(rxbuf.begin() + rank_begin, + rxbuf.begin() + rank_end); } return buffers; } @@ -274,8 +289,8 @@ template Matrix2d allgather(const Matrix2d& matrix, const MPI_Comm comm) { const std::vector> buffers - = allgather_local_matrix_buffers(matrix, comm); - return rebuild_global_matrix(buffers); + = allgather_local_buffers(matrix, comm); + return rebuild_global(buffers); } template @@ -290,26 +305,25 @@ std::unique_ptr> gather_on_root(const Matrix2d& matrix, throw std::invalid_argument("gather root rank is outside the communicator"); } - const std::vector local_buffer - = make_local_matrix_buffer(matrix); - assert_valid_mpi_count(local_buffer.size()); - const int nbytes_local_mpi = mpi_count(local_buffer.size()); - const std::vector recvcounts + const std::vector locbuf + = make_local_buffer(matrix); + const int nbytes_local_mpi = checked_mpi_count(locbuf.size()); + const std::vector nbytes_recv = allgather_nbytes(nbytes_local_mpi, comm); const std::vector rdispls - = make_byte_displs(recvcounts); - const int total_bytes = rdispls.back() + recvcounts.back(); - std::vector received; + = make_byte_displs(nbytes_recv); + const int nbytes_total = rdispls.back() + nbytes_recv.back(); + std::vector rxbuf; if (ip == iproot) { - received.resize(total_bytes); + rxbuf.resize(nbytes_total); } - unsigned char* const recvbuf = ip == iproot ? received.data() : nullptr; - Parallel_Common::gatherv_bytes(local_buffer.data(), + unsigned char* const recvbuf = ip == iproot ? rxbuf.data() : nullptr; + Parallel_Common::gatherv_bytes(locbuf.data(), nbytes_local_mpi, recvbuf, - recvcounts.data(), + nbytes_recv.data(), rdispls.data(), iproot, comm); @@ -318,17 +332,20 @@ std::unique_ptr> gather_on_root(const Matrix2d& matrix, return std::unique_ptr>(); } - std::vector> buffers(recvcounts.size()); - for (std::size_t ipsrc = 0; ipsrc < recvcounts.size(); ++ipsrc) + std::vector> buffers(nbytes_recv.size()); + // Iterate in communicator rank order to split the contiguous receive + // buffer into the same per-rank segments used by gatherv_bytes. + for (std::size_t ipsrc = 0; ipsrc < nbytes_recv.size(); ++ipsrc) { - const std::size_t begin + const auto rank_begin = static_cast(rdispls[ipsrc]); - const std::size_t end - = begin + static_cast(recvcounts[ipsrc]); - buffers[ipsrc].assign(received.begin() + begin, received.begin() + end); + const auto rank_end + = rank_begin + static_cast(nbytes_recv[ipsrc]); + buffers[ipsrc].assign(rxbuf.begin() + rank_begin, + rxbuf.begin() + rank_end); } return std::unique_ptr>( - new Matrix2d(rebuild_global_matrix(buffers))); + new Matrix2d(rebuild_global(buffers))); } template @@ -349,20 +366,18 @@ void scatter_from_host(const Matrix2d& matglb, Matrix2d& matloc) const std::vector metadata = make_local_metadata(matloc); const std::size_t nmeta = metadata.size(); - const std::size_t nmeta_bytes = nmeta * sizeof(int); - assert_valid_mpi_count(nmeta_bytes); - const int nmeta_mpi = mpi_count(nmeta_bytes); + const std::size_t nbytes_meta = nmeta * W_INT; + const int nmeta_mpi = checked_mpi_count(nbytes_meta); const std::vector metacounts = allgather_nbytes(nmeta_mpi, comm); const std::vector metadispls = make_byte_displs(metacounts); const int metadata_total_bytes = metadispls.back() + metacounts.back(); - const int nbytes_int = static_cast(sizeof(int)); - if (metadata_total_bytes % nbytes_int != 0) + 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 / nbytes_int; + const int nmeta_all = metadata_total_bytes / W_INT; std::vector all_metadata(nmeta_all); Parallel_Common::allgatherv_bytes(metadata.data(), @@ -375,7 +390,7 @@ void scatter_from_host(const Matrix2d& matglb, Matrix2d& matloc) const int nproc = Parallel_Common::comm_size(comm); const int ip = Parallel_Common::comm_rank(comm); std::vector sendcounts(nproc, 0); - std::vector views; + std::vector views; views.reserve(nproc); std::size_t metadata_offset = 0; const int nrglb = matloc.nrglb(); @@ -386,7 +401,7 @@ void scatter_from_host(const Matrix2d& matglb, Matrix2d& matloc) { throw std::invalid_argument("Matrix2d scatter metadata is truncated"); } - LocalMatrixBufferView view; + LocalBufferView view; view.nrloc = all_metadata[metadata_offset]; view.ncloc = all_metadata[metadata_offset + 1]; view.nrglb = all_metadata[metadata_offset + 2]; @@ -416,8 +431,7 @@ void scatter_from_host(const Matrix2d& matglb, Matrix2d& matloc) = static_cast(view.nrloc) * static_cast(view.ncloc); const std::size_t nbytes_local = nelem_local * sizeof(T); - assert_valid_mpi_count(nbytes_local); - sendcounts[ipsrc] = mpi_count(nbytes_local); + sendcounts[ipsrc] = checked_mpi_count(nbytes_local); views.push_back(view); } if (metadata_offset != all_metadata.size()) @@ -437,7 +451,7 @@ void scatter_from_host(const Matrix2d& matglb, Matrix2d& matloc) sendbuf.resize(total_bytes); for (int ipdst = 0; ipdst < nproc; ++ipdst) { - const LocalMatrixBufferView& view = views[ipdst]; + const LocalBufferView& view = views[ipdst]; for (int irloc = 0; irloc < view.nrloc; ++irloc) { const int irglb = view.irglb[irloc]; @@ -465,8 +479,7 @@ void scatter_from_host(const Matrix2d& matglb, Matrix2d& matloc) * static_cast(matloc.ncloc()); const std::size_t nbytes_recv = nelem_recv * sizeof(T); std::vector recvbuf(nbytes_recv); - assert_valid_mpi_count(nbytes_recv); - const int recv = mpi_count(nbytes_recv); + const int recv = checked_mpi_count(nbytes_recv); const unsigned char* receive_source = ip == 0 ? sendbuf.data() : nullptr; Parallel_Common::scatterv_bytes(receive_source, sendcounts.data(), diff --git a/source/source_base/matrix2d_lapack.cpp b/source/source_base/matrix2d_lapack.cpp index a378f94daa9..6ad145448ae 100644 --- a/source/source_base/matrix2d_lapack.cpp +++ b/source/source_base/matrix2d_lapack.cpp @@ -82,26 +82,26 @@ void inv(Matrix2dView matrix) /* info= */ info); throw_lapack_error("LAPACK getrf", info); - int lwork = -1; - std::vector work(1); + int lws = -1; + std::vector ws(1); container::lapackConnector::getri( /* n= */ n, /* a= */ matrix.data(), /* lda= */ lda, /* ipiv= */ ipiv.data(), - /* work= */ work.data(), - /* lwork= */ lwork, + /* work= */ ws.data(), + /* lwork= */ lws, /* info= */ info); throw_lapack_error("LAPACK getri workspace query", info); - lwork = static_cast(work[0]); - work.resize(static_cast(lwork)); + lws = static_cast(ws[0]); + ws.resize(static_cast(lws)); container::lapackConnector::getri( /* n= */ n, /* a= */ matrix.data(), /* lda= */ lda, /* ipiv= */ ipiv.data(), - /* work= */ work.data(), - /* lwork= */ lwork, + /* work= */ ws.data(), + /* lwork= */ lws, /* info= */ info); throw_lapack_error("LAPACK getri", info); } @@ -124,26 +124,26 @@ void inv(Matrix2dView> matrix) /* info= */ info); throw_lapack_error("LAPACK getrf", info); - int lwork = -1; - std::vector> work(1); + int lws = -1; + std::vector> ws(1); container::lapackConnector::getri( /* n= */ n, /* a= */ matrix.data(), /* lda= */ lda, /* ipiv= */ ipiv.data(), - /* work= */ work.data(), - /* lwork= */ lwork, + /* work= */ ws.data(), + /* lwork= */ lws, /* info= */ info); throw_lapack_error("LAPACK getri workspace query", info); - lwork = static_cast(work[0].real()); - work.resize(static_cast(lwork)); + lws = static_cast(ws[0].real()); + ws.resize(static_cast(lws)); container::lapackConnector::getri( /* n= */ n, /* a= */ matrix.data(), /* lda= */ lda, /* ipiv= */ ipiv.data(), - /* work= */ work.data(), - /* lwork= */ lwork, + /* work= */ ws.data(), + /* lwork= */ lws, /* info= */ info); throw_lapack_error("LAPACK getri", info); } @@ -169,15 +169,15 @@ void solve(Matrix2dView matrix, /* info= */ info); throw_lapack_error("LAPACK getrf", info); - std::vector rhs_column_major( + // Column-major LAPACK right-hand side for A * X = B. + std::vector b( static_cast(n) * static_cast(nrhs)); for (int i = 0; i < n; ++i) { for (int j = 0; j < nrhs; ++j) { - rhs_column_major[static_cast(i) - + static_cast(j) - * static_cast(n)] + b[static_cast(i) + + static_cast(j) * static_cast(n)] = rhs.atloc(i, j); } } @@ -190,7 +190,7 @@ void solve(Matrix2dView matrix, /* a= */ matrix.data(), /* lda= */ lda, /* ipiv= */ ipiv.data(), - /* b= */ rhs_column_major.data(), + /* b= */ b.data(), /* ldb= */ n, /* info= */ info); throw_lapack_error("LAPACK getrs", info); @@ -200,9 +200,8 @@ void solve(Matrix2dView matrix, for (int j = 0; j < nrhs; ++j) { rhs.atloc(i, j) - = rhs_column_major[static_cast(i) - + static_cast(j) - * static_cast(n)]; + = b[static_cast(i) + + static_cast(j) * static_cast(n)]; } } } @@ -228,15 +227,15 @@ void solve(Matrix2dView> matrix, /* info= */ info); throw_lapack_error("LAPACK getrf", info); - std::vector> rhs_column_major( + // Column-major LAPACK right-hand side for A * X = B. + std::vector> b( static_cast(n) * static_cast(nrhs)); for (int i = 0; i < n; ++i) { for (int j = 0; j < nrhs; ++j) { - rhs_column_major[static_cast(i) - + static_cast(j) - * static_cast(n)] + b[static_cast(i) + + static_cast(j) * static_cast(n)] = rhs.atloc(i, j); } } @@ -249,7 +248,7 @@ void solve(Matrix2dView> matrix, /* a= */ matrix.data(), /* lda= */ lda, /* ipiv= */ ipiv.data(), - /* b= */ rhs_column_major.data(), + /* b= */ b.data(), /* ldb= */ n, /* info= */ info); throw_lapack_error("LAPACK getrs", info); @@ -259,9 +258,8 @@ void solve(Matrix2dView> matrix, for (int j = 0; j < nrhs; ++j) { rhs.atloc(i, j) - = rhs_column_major[static_cast(i) - + static_cast(j) - * static_cast(n)]; + = b[static_cast(i) + + static_cast(j) * static_cast(n)]; } } } diff --git a/source/source_base/matrix2d_linalg.cpp b/source/source_base/matrix2d_linalg.cpp index 1249f51f177..36b3e1f6b25 100644 --- a/source/source_base/matrix2d_linalg.cpp +++ b/source/source_base/matrix2d_linalg.cpp @@ -9,17 +9,26 @@ #include #include +#include namespace { +/** + * @brief Return true when a distribution handle exists and is not the serial + * one-by-one layout. + */ template -bool has_active_distribution(const Matrix2dView& matrix) +bool distribution_is_active(const Matrix2dView& matrix) { return matrix.is_distributed() && !matrix.distribution()->is_serial(); } +/** + * @brief Return true when a distribution handle exists and describes the + * serial one-by-one layout. + */ template -bool has_serial_distribution(const Matrix2dView& matrix) +bool distribution_is_serial(const Matrix2dView& matrix) { return matrix.is_distributed() && matrix.distribution()->is_serial(); } @@ -47,8 +56,8 @@ void assert_compatible_layout(const Matrix2dView& left, { return; } - const bool serial = has_serial_distribution(left); - const bool serial_ = has_serial_distribution(right); + const bool serial = distribution_is_serial(left); + const bool serial_ = distribution_is_serial(right); if (serial != serial_) { throw std::invalid_argument( @@ -106,11 +115,11 @@ void matmul_host(Matrix2dView result, } template -void linear_combination_impl(Matrix2dView result, - const T alpha, - Matrix2dView left, - const T beta, - Matrix2dView right) +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); @@ -189,12 +198,12 @@ void assert_solve_views(const Matrix2dView& matrix, throw std::invalid_argument( "linear solve requires matching host or distributed layouts"); } - if (has_serial_distribution(matrix) != has_serial_distribution(rhs)) + if (distribution_is_serial(matrix) != distribution_is_serial(rhs)) { throw std::invalid_argument( "linear solve requires matching serial or parallel distributions"); } - if (has_serial_distribution(matrix)) + if (distribution_is_serial(matrix)) { return; } @@ -227,12 +236,12 @@ void assert_solve_views(const Matrix2dView>& matrix, throw std::invalid_argument( "linear solve requires matching host or distributed layouts"); } - if (has_serial_distribution(matrix) != has_serial_distribution(rhs)) + if (distribution_is_serial(matrix) != distribution_is_serial(rhs)) { throw std::invalid_argument( "linear solve requires matching serial or parallel distributions"); } - if (has_serial_distribution(matrix)) + if (distribution_is_serial(matrix)) { return; } @@ -256,7 +265,7 @@ namespace matrix2d_linalg void inv(Matrix2dView matrix) { assert_inverse_view(matrix); - if (has_active_distribution(matrix)) + if (distribution_is_active(matrix)) { #ifdef __MPI matrix2d_impl::scalapack::inv(matrix); @@ -271,7 +280,7 @@ void inv(Matrix2dView matrix) void inv(Matrix2dView> matrix) { assert_inverse_view(matrix); - if (has_active_distribution(matrix)) + if (distribution_is_active(matrix)) { #ifdef __MPI matrix2d_impl::scalapack::inv(matrix); @@ -287,7 +296,7 @@ void solve(Matrix2dView matrix, Matrix2dView rhs) { assert_solve_views(matrix, rhs); - if (has_active_distribution(matrix)) + if (distribution_is_active(matrix)) { #ifdef __MPI matrix2d_impl::scalapack::solve(matrix, rhs); @@ -303,7 +312,7 @@ void solve(Matrix2dView> matrix, Matrix2dView> rhs) { assert_solve_views(matrix, rhs); - if (has_active_distribution(matrix)) + if (distribution_is_active(matrix)) { #ifdef __MPI matrix2d_impl::scalapack::solve(matrix, rhs); @@ -320,7 +329,7 @@ void matmul(Matrix2dView result, Matrix2dView right) { assert_matmul_views(result, left, right); - if (has_active_distribution(result)) + if (distribution_is_active(result)) { #ifdef __MPI matrix2d_impl::scalapack::matmul(result, left, right); @@ -337,7 +346,7 @@ void matmul(Matrix2dView> result, Matrix2dView> right) { assert_matmul_views(result, left, right); - if (has_active_distribution(result)) + if (distribution_is_active(result)) { #ifdef __MPI matrix2d_impl::scalapack::matmul(result, left, right); @@ -349,23 +358,23 @@ void matmul(Matrix2dView> result, matmul_host(result, left, right); } -void linear_combination(Matrix2dView result, - const double alpha, - Matrix2dView left, - const double beta, - Matrix2dView right) +void axpby(Matrix2dView result, + const double alpha, + Matrix2dView left, + const double beta, + Matrix2dView right) { - linear_combination_impl(result, alpha, left, beta, right); + axpby_impl(result, alpha, left, beta, right); } -void linear_combination( +void axpby( Matrix2dView> result, const std::complex alpha, Matrix2dView> left, const std::complex beta, Matrix2dView> right) { - linear_combination_impl(result, alpha, left, beta, right); + axpby_impl(result, alpha, left, beta, right); } void scale(Matrix2dView matrix, const double factor) @@ -388,4 +397,18 @@ void set_identity(Matrix2dView> matrix) { set_identity_impl(matrix); } + +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_impl(matrix.view()); + return matrix; +} + +template Matrix2d eye(const int n); +template Matrix2d> eye>(const int n); } // namespace matrix2d_linalg diff --git a/source/source_base/matrix2d_linalg.h b/source/source_base/matrix2d_linalg.h index c25e530cfc2..be1afab2112 100644 --- a/source/source_base/matrix2d_linalg.h +++ b/source/source_base/matrix2d_linalg.h @@ -1,6 +1,7 @@ #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 @@ -31,12 +32,22 @@ void matmul(Matrix2dView> result, Matrix2dView> left, Matrix2dView> right); -void linear_combination(Matrix2dView result, - const double alpha, - Matrix2dView left, - const double beta, - Matrix2dView right); -void linear_combination( +/** + * @brief Compute `result = alpha * left + beta * right`. + * + * All views must have the same global shape and compatible host or distributed + * layouts. The result may overlap either input because each element is read + * before it is written. + */ +void axpby(Matrix2dView result, + const double alpha, + Matrix2dView left, + const double beta, + Matrix2dView right); +/** + * @copydoc axpby(Matrix2dView,double,Matrix2dView,double,Matrix2dView) + */ +void axpby( Matrix2dView> result, const std::complex alpha, Matrix2dView> left, @@ -47,8 +58,25 @@ void scale(Matrix2dView matrix, const double factor); void scale(Matrix2dView> matrix, const std::complex factor); +/** + * @brief Write the identity matrix into an existing square view. + * + * This operation mutates `matrix` in place and does not allocate a new matrix. + */ void set_identity(Matrix2dView matrix); +/** @copydoc set_identity(Matrix2dView) */ void set_identity(Matrix2dView> matrix); + +/** + * @brief Create a new `n` by `n` identity matrix. + * + * The returned matrix owns host storage. Use `set_identity()` when an existing + * view should be overwritten in place. + * + * @tparam T Either `double` or `std::complex`. + */ +template +Matrix2d eye(const int n); } // namespace matrix2d_linalg #endif diff --git a/source/source_base/matrix2d_reduction.cpp b/source/source_base/matrix2d_reduction.cpp index c517c9039e3..aaac3c87d50 100644 --- a/source/source_base/matrix2d_reduction.cpp +++ b/source/source_base/matrix2d_reduction.cpp @@ -17,6 +17,9 @@ namespace { +// Width in bytes of a native int in the homogeneous diagonal wire format. +constexpr int W_INT = sizeof(int); + namespace elementwise { template @@ -100,17 +103,13 @@ void reduce_max_over_processes(double& value, const Matrix2d& matrix) #endif } -void assert_valid_mpi_count(const std::size_t nbytes) +int checked_mpi_count(const std::size_t nbytes) { if (nbytes > static_cast(std::numeric_limits::max())) { throw std::invalid_argument( "Matrix2d diagonal data buffer exceeds MPI count range"); } -} - -int mpi_count(const std::size_t nbytes) -{ return static_cast(nbytes); } @@ -135,16 +134,14 @@ std::vector make_byte_displs(const std::vector& nbytes) std::vector gather_nbytes(const int nbytes_local, const MPI_Comm comm) { const int nproc = Parallel_Common::comm_size(comm); - const int nbytes_int = static_cast(sizeof(int)); - const std::vector recvcounts(static_cast(nproc), - nbytes_int); + const std::vector nbytes_recv(static_cast(nproc), W_INT); const std::vector rdispls - = make_byte_displs(recvcounts); + = make_byte_displs(nbytes_recv); std::vector nbytes(static_cast(nproc), 0); Parallel_Common::allgatherv_bytes(&nbytes_local, - nbytes_int, + W_INT, nbytes.data(), - recvcounts.data(), + nbytes_recv.data(), rdispls.data(), comm); return nbytes; @@ -301,16 +298,15 @@ std::vector diagonal(const Matrix2d& matrix) const MPI_Comm comm = distrib->comm(); if (comm != MPI_COMM_NULL) { - const std::size_t nbytes_entry = sizeof(int) + sizeof(T); + const std::size_t nbytes_entry = W_INT + sizeof(T); const std::size_t nbytes_local - = sizeof(int) + local_entries.size() * nbytes_entry; + = W_INT + local_entries.size() * nbytes_entry; std::vector local_diagonal_buffer(nbytes_local); - assert_valid_mpi_count(local_entries.size()); - const int nentry_local = mpi_count(local_entries.size()); + const int nentry_local = checked_mpi_count(local_entries.size()); std::memcpy(local_diagonal_buffer.data(), &nentry_local, - sizeof(nentry_local)); - std::size_t offset = sizeof(nentry_local); + W_INT); + std::size_t offset = W_INT; for (const std::pair& entry : local_entries) { std::memcpy(local_diagonal_buffer.data() + offset, @@ -323,30 +319,29 @@ std::vector diagonal(const Matrix2d& matrix) offset += sizeof(entry.second); } - assert_valid_mpi_count(nbytes_local); - const int nbytes_local_mpi = mpi_count(nbytes_local); - const std::vector recvcounts + const int nbytes_local_mpi = checked_mpi_count(nbytes_local); + const std::vector nbytes_recv = gather_nbytes(nbytes_local_mpi, comm); const std::vector rdispls - = make_byte_displs(recvcounts); + = make_byte_displs(nbytes_recv); const int total_bytes - = rdispls.back() + recvcounts.back(); + = 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(), - recvcounts.data(), + nbytes_recv.data(), rdispls.data(), comm); - for (std::size_t ip = 0; ip < recvcounts.size(); ++ip) + 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(recvcounts[ip]); - if (end - begin < sizeof(int)) + = begin + static_cast(nbytes_recv[ip]); + if (end - begin < W_INT) { throw std::runtime_error( "Matrix2d diagonal data buffer is truncated"); @@ -355,10 +350,10 @@ std::vector diagonal(const Matrix2d& matrix) std::memcpy(&nentry, received.data() + begin, sizeof(nentry)); - const std::size_t expected_bytes + const std::size_t nbytes_expected = static_cast(nentry) * nbytes_entry; if (nentry < 0 - || end - begin != sizeof(int) + expected_bytes) + || end - begin != W_INT + nbytes_expected) { throw std::runtime_error( "Matrix2d diagonal data buffer has an invalid size"); @@ -370,8 +365,8 @@ std::vector diagonal(const Matrix2d& matrix) T value = T(); std::memcpy(&irglb, received.data() + entry_offset, - sizeof(irglb)); - entry_offset += sizeof(irglb); + W_INT); + entry_offset += W_INT; std::memcpy(&value, received.data() + entry_offset, sizeof(value)); diff --git a/source/source_base/matrix2d_scalapack.cpp b/source/source_base/matrix2d_scalapack.cpp index f728d2f5b49..242c6e41d73 100644 --- a/source/source_base/matrix2d_scalapack.cpp +++ b/source/source_base/matrix2d_scalapack.cpp @@ -157,36 +157,36 @@ void inv(Matrix2dView matrix) &info); throw_scalapack_error("ScaLAPACK getrf", info); - int lwork = -1; - int liwork = -1; - std::vector work(1); - std::vector iwork(1); + int lws = -1; + int liws = -1; + std::vector ws(1); + std::vector iws(1); ScalapackConnector::getri(n, matrix.data(), ia, ja, desc, ipiv.data(), - work.data(), - &lwork, - iwork.data(), - &liwork, + ws.data(), + &lws, + iws.data(), + &liws, &info); throw_scalapack_error("ScaLAPACK getri workspace query", info); - lwork = queried_workspace_size(work[0]); - liwork = iwork[0]; - work.resize(static_cast(lwork)); - iwork.resize(static_cast(liwork)); + 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(), - work.data(), - &lwork, - iwork.data(), - &liwork, + ws.data(), + &lws, + iws.data(), + &liws, &info); throw_scalapack_error("ScaLAPACK getri", info); } @@ -210,36 +210,36 @@ void inv(Matrix2dView> matrix) &info); throw_scalapack_error("ScaLAPACK getrf", info); - int lwork = -1; - int liwork = -1; - std::vector> work(1); - std::vector iwork(1); + int lws = -1; + int liws = -1; + std::vector> ws(1); + std::vector iws(1); ScalapackConnector::getri(n, matrix.data(), ia, ja, desc, ipiv.data(), - work.data(), - &lwork, - iwork.data(), - &liwork, + ws.data(), + &lws, + iws.data(), + &liws, &info); throw_scalapack_error("ScaLAPACK getri workspace query", info); - lwork = queried_workspace_size(work[0]); - liwork = iwork[0]; - work.resize(static_cast(lwork)); - iwork.resize(static_cast(liwork)); + 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(), - work.data(), - &lwork, - iwork.data(), - &liwork, + ws.data(), + &lws, + iws.data(), + &liws, &info); throw_scalapack_error("ScaLAPACK getri", info); } diff --git a/source/source_base/matrix2d_view.h b/source/source_base/matrix2d_view.h index 17f878401af..8cba2dcd46f 100644 --- a/source/source_base/matrix2d_view.h +++ b/source/source_base/matrix2d_view.h @@ -1,6 +1,24 @@ #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 @@ -10,17 +28,17 @@ #include #include -/** - * @brief Non-owning two-dimensional matrix view. - * - * Host views use row-major storage. Views backed by a frozen block-cyclic - * distribution use its local column-major layout, including serial frozen - * distributions in non-MPI builds. - */ +/** @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> @@ -36,6 +54,13 @@ class Matrix2dView { } + /** + * @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), @@ -50,6 +75,13 @@ class Matrix2dView 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), @@ -77,30 +109,70 @@ class Matrix2dView #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 distribution handle is attached. + * + * This includes serial frozen distributions; it does not imply that more + * than one MPI rank participates. + */ bool is_distributed() const { return distrib_ != nullptr; } + /** + * @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); diff --git a/source/source_base/unittests/test_matrix2d.cpp b/source/source_base/unittests/test_matrix2d.cpp index d2108d4a1a6..03a3456fb33 100644 --- a/source/source_base/unittests/test_matrix2d.cpp +++ b/source/source_base/unittests/test_matrix2d.cpp @@ -604,18 +604,16 @@ void check_gather_scatter(Matrix2d& matrix) template std::size_t expected_local_storage_size(const Matrix2d& matrix) { - const int lld_distrib = matrix.lld(); - const int lld = std::max(lld_distrib, 1); - const std::size_t column_major_elements + const int lld = std::max(matrix.lld(), 1); + const std::size_t ncolmajor = static_cast(lld) * static_cast(matrix.ncloc()); - const std::size_t row_major_elements + const std::size_t nrowmajor = static_cast(matrix.nrloc()) * static_cast(matrix.ncloc()); - const std::size_t logical_extent - = std::max(column_major_elements, row_major_elements); - const std::size_t empty_rank_minimum = 1; - return std::max(logical_extent, empty_rank_minimum); + const std::size_t nextent = std::max(ncolmajor, nrowmajor); + const std::size_t nstor_min = 1; + return std::max(nextent, nstor_min); } template @@ -624,10 +622,9 @@ std::vector set_padding_sentinel(Matrix2d& matrix, { const int nrloc = matrix.nrloc(); const int ncloc = matrix.ncloc(); - const int lld_distrib = matrix.lld(); - const std::size_t lld = static_cast(lld_distrib); - const std::size_t storage_elements = expected_local_storage_size(matrix); - std::vector is_logical(storage_elements, 0); + 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) { @@ -639,7 +636,7 @@ std::vector set_padding_sentinel(Matrix2d& matrix, is_logical[index] = 1; } } - for (std::size_t index = 0; index < storage_elements; ++index) + for (std::size_t index = 0; index < nstor; ++index) { if (is_logical[index] == 0) { @@ -1222,14 +1219,14 @@ TEST(Matrix2dTest, SerialDistributionTallSkinnyStorageUsesColumnExtent) = make_frozen_distribution(nrglb, ncglb); Matrix2d matrix(distrib); - const std::size_t expected_storage_elements + const std::size_t nstor_expected = static_cast(nrglb) * static_cast(ncglb); - const std::size_t row_major_elements + const std::size_t nrowmajor = static_cast(matrix.nrloc()) * static_cast(matrix.ncloc()); - EXPECT_EQ(matrix.local_storage_size(), expected_storage_elements); - EXPECT_LE(row_major_elements, matrix.local_storage_size()); + EXPECT_EQ(matrix.local_storage_size(), nstor_expected); + EXPECT_LE(nrowmajor, matrix.local_storage_size()); } #ifndef __MPI @@ -1484,18 +1481,18 @@ TEST(Matrix2dTest, TallSkinnyPaddingDoesNotAffectOperatorsOrGather) fill_global_values(other, 10.0); const double sentinel = -98765.25; - const std::size_t expected_storage_elements + const std::size_t nstor_expected = expected_local_storage_size(matrix); - const std::size_t logical_elements + const std::size_t nlogical = static_cast(matrix.nrloc()) * static_cast(matrix.ncloc()); - EXPECT_EQ(matrix.local_storage_size(), expected_storage_elements); - EXPECT_LE(logical_elements, matrix.local_storage_size()); + 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 expected_padding_elements - = expected_storage_elements - logical_elements; - EXPECT_EQ(padding_indices.size(), expected_padding_elements); + const std::size_t npadding_expected + = nstor_expected - nlogical; + EXPECT_EQ(padding_indices.size(), npadding_expected); if (nproc > 1) { if (matrix.icproc() == 0) diff --git a/source/source_base/unittests/test_matrix2d_linalg.cpp b/source/source_base/unittests/test_matrix2d_linalg.cpp index 7639fcd7f9b..3c1cbae90e7 100644 --- a/source/source_base/unittests/test_matrix2d_linalg.cpp +++ b/source/source_base/unittests/test_matrix2d_linalg.cpp @@ -335,7 +335,7 @@ TEST(Matrix2dLinalgTest, ExternalBufferViewDoesNotCopy) EXPECT_EQ(matrix.data(), values.data()); } -TEST(Matrix2dLinalgTest, HostViewMatmulAndLinearCombination) +TEST(Matrix2dLinalgTest, HostViewMatmulAndAxpby) { const Matrix2d left = make_real_system(); const Matrix2d right = make_real_inverse_reference(); @@ -344,7 +344,7 @@ TEST(Matrix2dLinalgTest, HostViewMatmulAndLinearCombination) expect_host_matrices_near(product, left.matmul(right)); Matrix2d combined(2, 2); - matrix2d_linalg::linear_combination( + matrix2d_linalg::axpby( combined.view(), 2.0, left.view(), -0.5, right.view()); Matrix2d combined_reference(2, 2); for (int i = 0; i < 2; ++i) @@ -360,6 +360,10 @@ TEST(Matrix2dLinalgTest, HostViewMatmulAndLinearCombination) matrix2d_linalg::scale(combined.view(), 3.0); matrix2d_linalg::set_identity(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) @@ -368,6 +372,10 @@ TEST(Matrix2dLinalgTest, HostViewMatmulAndLinearCombination) 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); } } } @@ -443,7 +451,7 @@ TEST(Matrix2dLinalgTest, DistributedRealAndComplexInverse) } } -TEST(Matrix2dLinalgTest, DistributedIdentityAndLinearCombination) +TEST(Matrix2dLinalgTest, DistributedIdentityAndAxpby) { const int size = 5; const int nrblks[] = {2, 3}; @@ -467,11 +475,11 @@ TEST(Matrix2dLinalgTest, DistributedIdentityAndLinearCombination) Matrix2d left(identity.distribution()); Matrix2d combined(identity.distribution()); left.scatter(host_left); - matrix2d_linalg::linear_combination(combined.view(), - 2.0, - left.view(), - 0.5, - identity.view()); + matrix2d_linalg::axpby(combined.view(), + 2.0, + left.view(), + 0.5, + identity.view()); Matrix2d combined_expected(size, size); for (int i = 0; i < size; ++i) { From 0ac210ae37ba6f718d27594b60e2cbf7a8acc646 Mon Sep 17 00:00:00 2001 From: kirk0830 Date: Sun, 22 Nov 2026 20:21:01 +0800 Subject: [PATCH 09/15] refactor(base): address review structure/MPI/OMP findings (part B) --- source/Makefile.Objects | 1 + source/source_base/CMakeLists.txt | 1 + source/source_base/matrix2d.cpp | 55 +++- source/source_base/matrix2d.h | 67 ++--- source/source_base/matrix2d_collective.cpp | 266 ++++++++---------- source/source_base/matrix2d_collective.h | 8 + source/source_base/matrix2d_lapack.cpp | 59 ++-- source/source_base/matrix2d_lapack.h | 9 + source/source_base/matrix2d_linalg.cpp | 74 ++--- source/source_base/matrix2d_mpi.cpp | 62 ++++ source/source_base/matrix2d_mpi.h | 33 +++ source/source_base/matrix2d_reduction.cpp | 62 +--- source/source_base/matrix2d_reduction.h | 8 + source/source_base/matrix2d_scalapack.cpp | 16 ++ source/source_base/matrix2d_scalapack.h | 11 + source/source_base/matrix2d_view.h | 17 +- .../module_external/scalapack_connector.h | 16 +- .../source_base/unittests/test_matrix2d.cpp | 50 ++-- .../unittests/test_matrix2d_linalg.cpp | 18 ++ 19 files changed, 495 insertions(+), 338 deletions(-) create mode 100644 source/source_base/matrix2d_mpi.cpp create mode 100644 source/source_base/matrix2d_mpi.h diff --git a/source/Makefile.Objects b/source/Makefile.Objects index 8eaf168fa10..48ab8fc6407 100644 --- a/source/Makefile.Objects +++ b/source/Makefile.Objects @@ -183,6 +183,7 @@ OBJS_BASE=assoc_laguerre.o\ matrix2d_collective.o\ matrix2d_lapack.o\ matrix2d_linalg.o\ + matrix2d_mpi.o\ matrix2d_reduction.o\ matrix2d_scalapack.o\ matrix3.o\ diff --git a/source/source_base/CMakeLists.txt b/source/source_base/CMakeLists.txt index cf43d152943..656fb958741 100644 --- a/source/source_base/CMakeLists.txt +++ b/source/source_base/CMakeLists.txt @@ -36,6 +36,7 @@ add_library( matrix2d_collective.cpp matrix2d_lapack.cpp matrix2d_linalg.cpp + matrix2d_mpi.cpp matrix2d_reduction.cpp matrix2d_scalapack.cpp matrix3.cpp diff --git a/source/source_base/matrix2d.cpp b/source/source_base/matrix2d.cpp index b3ade48ebd3..4f1e23b356f 100644 --- a/source/source_base/matrix2d.cpp +++ b/source/source_base/matrix2d.cpp @@ -102,6 +102,43 @@ void matmul(Matrix2dView result, } // 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() { @@ -250,7 +287,7 @@ NDArray& NDArray::conjugate() template NDArray NDArray::transpose() const { - if (distrib_ == nullptr || distrib_->is_serial()) + 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 @@ -286,7 +323,7 @@ NDArray NDArray::transpose() const template NDArray NDArray::dagger() const { - if (distrib_ == nullptr || distrib_->is_serial()) + if (!is_active()) { Matrix2d result(ncloc_, nrloc_); #ifdef _OPENMP @@ -331,10 +368,8 @@ NDArray NDArray::matmul(const NDArray& other) const } } - const bool serial - = distrib_ == nullptr || distrib_->is_serial(); - const bool serial_ - = other.distribution() == nullptr || other.distribution()->is_serial(); + const bool serial = !is_active(); + const bool serial_ = !other.is_active(); if (serial != serial_) { throw std::invalid_argument("host and distributed matrices are incompatible"); @@ -394,7 +429,7 @@ NDArray NDArray::matmul(const NDArray& other) const template NDArray NDArray::real() const { - Matrix2d result = is_distributed() + Matrix2d result = has_distribution() ? Matrix2d(distribution()) : Matrix2d(nrglb(), ncglb()); const int nrloc = this->nrloc(); @@ -415,7 +450,7 @@ NDArray NDArray::real() const template NDArray NDArray::imag() const { - Matrix2d result = is_distributed() + Matrix2d result = has_distribution() ? Matrix2d(distribution()) : Matrix2d(nrglb(), ncglb()); const int nrloc = this->nrloc(); @@ -550,7 +585,7 @@ void NDArray::scatter(const NDArray& matglb) { if (distrib_ == nullptr) { - if (matglb.is_distributed()) + if (matglb.has_distribution()) { throw std::invalid_argument("host scatter requires a host global matrix"); } @@ -565,7 +600,7 @@ void NDArray::scatter(const NDArray& matglb) if (distrib_->is_serial()) { - if (matglb.is_distributed()) + if (matglb.has_distribution()) { throw std::invalid_argument("scatter requires a host global matrix"); } diff --git a/source/source_base/matrix2d.h b/source/source_base/matrix2d.h index c663b422db4..234862a14ae 100644 --- a/source/source_base/matrix2d.h +++ b/source/source_base/matrix2d.h @@ -53,9 +53,9 @@ class NDArray final const int ncglb, const MPI_Comm comm) { - const std::shared_ptr distrib // distribution, not distance + std::shared_ptr distrib // distribution, not distance = make_frozen_distribution(nrglb, ncglb, 1, comm); - initialize_distributed_storage(distrib); + initialize_distributed_storage(std::move(distrib)); } NDArray(const int nrglb, @@ -63,9 +63,9 @@ class NDArray final const int nb, const MPI_Comm comm) { - const std::shared_ptr distrib + std::shared_ptr distrib = make_frozen_distribution(nrglb, ncglb, nb, comm); - initialize_distributed_storage(distrib); + initialize_distributed_storage(std::move(distrib)); } NDArray(const int nrglb, @@ -75,9 +75,9 @@ class NDArray final const int nb, const MPI_Comm comm) { - const std::shared_ptr distrib + std::shared_ptr distrib = make_frozen_distribution(nrglb, ncglb, nrproc, ncproc, nb, comm); - initialize_distributed_storage(distrib); + initialize_distributed_storage(std::move(distrib)); } #endif @@ -305,10 +305,19 @@ class NDArray final /** * @brief Return whether a frozen distribution handle is attached. * - * A serial one-by-one distribution also returns true. This predicate does - * not mean that an active multi-rank distribution is present. + * 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 is_distributed() const { return distrib_ != nullptr; } + 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; @@ -328,50 +337,16 @@ class NDArray final { } - template - void 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 = distrib_ != nullptr; - const bool distributed_ = other.distribution() != nullptr; - 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"); - } - } + void assert_compatible_layout(const NDArray& other) const; void initialize_distributed_storage( - const std::shared_ptr& distrib) + std::shared_ptr distrib) { if (distrib == nullptr) { throw std::invalid_argument("distribution must not be null"); } - distrib_ = distrib; + distrib_ = std::move(distrib); initialize_distributed_storage(); } diff --git a/source/source_base/matrix2d_collective.cpp b/source/source_base/matrix2d_collective.cpp index 5ce4f80954d..b8508dd7563 100644 --- a/source/source_base/matrix2d_collective.cpp +++ b/source/source_base/matrix2d_collective.cpp @@ -1,64 +1,33 @@ #include "source_base/matrix2d_collective.h" #ifdef __MPI +#include "source_base/matrix2d_mpi.h" #include "source_base/parallel_common.h" #include -#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); -int checked_mpi_count(const std::size_t nbytes) -{ - if (nbytes > static_cast(std::numeric_limits::max())) - { - throw std::invalid_argument( - "Matrix2d collective matrix buffer exceeds MPI count range"); - } - return static_cast(nbytes); -} - -std::vector make_byte_displs(const std::vector& nbytes) -{ - std::vector displs(nbytes.size(), 0); - int offset = 0; - for (std::size_t ip = 0; ip < nbytes.size(); ++ip) - { - displs[ip] = offset; - if (nbytes[ip] > std::numeric_limits::max() - offset) - { - throw std::invalid_argument( - "Matrix2d collective matrix buffer size overflow"); - } - offset += nbytes[ip]; - } - return displs; -} - -std::vector allgather_nbytes(const int nbytes_local, const MPI_Comm comm) -{ - const int nproc = Parallel_Common::comm_size(comm); - const std::vector nbytes_recv(static_cast(nproc), W_INT); - const std::vector rdispls - = make_byte_displs(nbytes_recv); - std::vector nbytes(static_cast(nproc), 0); - - Parallel_Common::allgatherv_bytes(&nbytes_local, - W_INT, - nbytes.data(), - nbytes_recv.data(), - rdispls.data(), - comm); - return nbytes; -} - /** * @brief Pack rank-local axis metadata for Matrix2d collective transfers. * @@ -77,22 +46,24 @@ std::vector make_local_metadata(const Matrix2d& matrix) "Matrix2d collective buffers require trivially copyable T"); const std::shared_ptr distrib = matrix.distribution(); - std::vector metadata; - metadata.reserve(LOCAL_METADATA_SIZE + matrix.nrloc() - + matrix.ncloc()); - metadata.push_back(matrix.nrloc()); - metadata.push_back(matrix.ncloc()); - metadata.push_back(matrix.nrglb()); - metadata.push_back(matrix.ncglb()); - metadata.push_back(distrib->irproc()); - metadata.push_back(distrib->icproc()); + 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.push_back(distrib->irglb(irloc)); + metadata[offset++] = distrib->irglb(irloc); } for (int icloc = 0; icloc < matrix.ncloc(); ++icloc) { - metadata.push_back(distrib->icglb(icloc)); + metadata[offset++] = distrib->icglb(icloc); } return metadata; } @@ -130,6 +101,12 @@ std::vector make_local_buffer(const Matrix2d& matrix) return buffer; } +struct RankBufferView +{ + const unsigned char* data = nullptr; + std::size_t size = 0; +}; + struct LocalBufferView { int nrloc = 0; @@ -143,18 +120,47 @@ struct LocalBufferView 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); + std::memcpy(destination + idx * sizeof(T), &value, sizeof(T)); + } + } +} + template LocalBufferView view_local_buffer( - const std::vector& buffer) + const RankBufferView& buffer) { - if (buffer.size() < LOCAL_METADATA_SIZE * W_INT) + 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)); + std::memcpy(header, buffer.data, sizeof(header)); LocalBufferView view; view.nrloc = header[0]; view.ncloc = header[1]; @@ -176,25 +182,49 @@ LocalBufferView view_local_buffer( 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) + 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); + 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; + 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) + const std::vector& buffers) { std::vector views; views.reserve(buffers.size()); @@ -246,50 +276,29 @@ Matrix2d rebuild_global( return result; } +} // namespace + +namespace matrix2d_impl +{ template -std::vector> allgather_local_buffers( - const Matrix2d& matrix, - const MPI_Comm comm) +Matrix2d allgather(const Matrix2d& matrix, const MPI_Comm comm) { - const std::vector locbuf - = make_local_buffer(matrix); - const int nbytes_local_mpi = checked_mpi_count(locbuf.size()); + const std::vector locbuf = make_local_buffer(matrix); + const int nbytes_local_mpi = mpi::checked_mpi_count(locbuf.size()); const std::vector nbytes_recv - = allgather_nbytes(nbytes_local_mpi, comm); - const std::vector rdispls - = make_byte_displs(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(nbytes_total); - + std::vector recvbuf( + static_cast(nbytes_total)); Parallel_Common::allgatherv_bytes(locbuf.data(), nbytes_local_mpi, - rxbuf.data(), + recvbuf.data(), nbytes_recv.data(), rdispls.data(), comm); - - std::vector> buffers(nbytes_recv.size()); - // Iterate in communicator rank order and split the contiguous receive - // buffer into per-rank byte segments, as required by MPI_Allgatherv. - for (std::size_t ip = 0; ip < nbytes_recv.size(); ++ip) - { - const auto rank_begin = static_cast(rdispls[ip]); - const auto rank_end - = rank_begin + static_cast(nbytes_recv[ip]); - buffers[ip].assign(rxbuf.begin() + rank_begin, - rxbuf.begin() + rank_end); - } - return buffers; -} -} // namespace - -namespace matrix2d_impl -{ -template -Matrix2d allgather(const Matrix2d& matrix, const MPI_Comm comm) -{ - const std::vector> buffers - = allgather_local_buffers(matrix, comm); + const std::vector buffers + = make_rank_buffer_views(recvbuf, nbytes_recv, rdispls); return rebuild_global(buffers); } @@ -305,13 +314,11 @@ std::unique_ptr> gather_on_root(const Matrix2d& matrix, throw std::invalid_argument("gather root rank is outside the communicator"); } - const std::vector locbuf - = make_local_buffer(matrix); - const int nbytes_local_mpi = checked_mpi_count(locbuf.size()); + const std::vector locbuf = make_local_buffer(matrix); + const int nbytes_local_mpi = mpi::checked_mpi_count(locbuf.size()); const std::vector nbytes_recv - = allgather_nbytes(nbytes_local_mpi, comm); - const std::vector rdispls - = make_byte_displs(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) @@ -332,18 +339,8 @@ std::unique_ptr> gather_on_root(const Matrix2d& matrix, return std::unique_ptr>(); } - std::vector> buffers(nbytes_recv.size()); - // Iterate in communicator rank order to split the contiguous receive - // buffer into the same per-rank segments used by gatherv_bytes. - for (std::size_t ipsrc = 0; ipsrc < nbytes_recv.size(); ++ipsrc) - { - const auto rank_begin - = static_cast(rdispls[ipsrc]); - const auto rank_end - = rank_begin + static_cast(nbytes_recv[ipsrc]); - buffers[ipsrc].assign(rxbuf.begin() + rank_begin, - rxbuf.begin() + rank_end); - } + const std::vector buffers + = make_rank_buffer_views(rxbuf, nbytes_recv, rdispls); return std::unique_ptr>( new Matrix2d(rebuild_global(buffers))); } @@ -351,7 +348,7 @@ std::unique_ptr> gather_on_root(const Matrix2d& matrix, template void scatter_from_host(const Matrix2d& matglb, Matrix2d& matloc) { - if (matglb.is_distributed()) + if (matglb.has_distribution()) { throw std::invalid_argument("scatter requires a host global matrix"); } @@ -367,10 +364,11 @@ void scatter_from_host(const Matrix2d& matglb, Matrix2d& matloc) 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 = checked_mpi_count(nbytes_meta); - const std::vector metacounts = allgather_nbytes(nmeta_mpi, comm); + const int nmeta_mpi = mpi::checked_mpi_count(nbytes_meta); + const std::vector metacounts + = mpi::allgather_nbytes(nmeta_mpi, comm); const std::vector metadispls - = make_byte_displs(metacounts); + = mpi::make_byte_offsets(metacounts); const int metadata_total_bytes = metadispls.back() + metacounts.back(); if (metadata_total_bytes % W_INT != 0) @@ -431,7 +429,7 @@ void scatter_from_host(const Matrix2d& matglb, Matrix2d& matloc) = static_cast(view.nrloc) * static_cast(view.ncloc); const std::size_t nbytes_local = nelem_local * sizeof(T); - sendcounts[ipsrc] = checked_mpi_count(nbytes_local); + sendcounts[ipsrc] = mpi::checked_mpi_count(nbytes_local); views.push_back(view); } if (metadata_offset != all_metadata.size()) @@ -443,7 +441,7 @@ void scatter_from_host(const Matrix2d& matglb, Matrix2d& matloc) throw std::invalid_argument("scatter global matrix shape does not match distribution"); } - const std::vector sdispls = make_byte_displs(sendcounts); + const std::vector sdispls = mpi::make_byte_offsets(sendcounts); std::vector sendbuf; if (ip == 0) { @@ -452,25 +450,9 @@ void scatter_from_host(const Matrix2d& matglb, Matrix2d& matloc) for (int ipdst = 0; ipdst < nproc; ++ipdst) { const LocalBufferView& view = views[ipdst]; - 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 send_offset - = static_cast(sdispls[ipdst]) - + idx * sizeof(T); - unsigned char* const destination - = sendbuf.data() + send_offset; - std::memcpy(destination, &value, sizeof(T)); - } - } + unsigned char* const destination + = sendbuf.data() + static_cast(sdispls[ipdst]); + pack_rank_values(matglb, view, destination); } } @@ -479,7 +461,7 @@ void scatter_from_host(const Matrix2d& matglb, Matrix2d& matloc) * static_cast(matloc.ncloc()); const std::size_t nbytes_recv = nelem_recv * sizeof(T); std::vector recvbuf(nbytes_recv); - const int recv = checked_mpi_count(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(), diff --git a/source/source_base/matrix2d_collective.h b/source/source_base/matrix2d_collective.h index bcd5f9bd592..8b950c7b84b 100644 --- a/source/source_base/matrix2d_collective.h +++ b/source/source_base/matrix2d_collective.h @@ -1,6 +1,14 @@ #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 diff --git a/source/source_base/matrix2d_lapack.cpp b/source/source_base/matrix2d_lapack.cpp index 6ad145448ae..f3f42352ffb 100644 --- a/source/source_base/matrix2d_lapack.cpp +++ b/source/source_base/matrix2d_lapack.cpp @@ -4,6 +4,7 @@ #include "source_base/matrix2d_view.h" #include +#include #include #include #include @@ -12,7 +13,7 @@ namespace { void assert_host_layout(const Matrix2dView& matrix) { - if (matrix.is_distributed() && !matrix.distribution()->is_serial()) + if (matrix.is_active()) { throw std::invalid_argument("LAPACK requires a host matrix view"); } @@ -20,7 +21,7 @@ void assert_host_layout(const Matrix2dView& matrix) void assert_host_layout(const Matrix2dView>& matrix) { - if (matrix.is_distributed() && !matrix.distribution()->is_serial()) + if (matrix.is_active()) { throw std::invalid_argument("LAPACK requires a host matrix view"); } @@ -69,9 +70,10 @@ 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(static_cast(n)); + std::vector ipiv(n_); int info = 0; container::lapackConnector::getrf( /* m= */ n, @@ -94,7 +96,8 @@ void inv(Matrix2dView matrix) /* info= */ info); throw_lapack_error("LAPACK getri workspace query", info); lws = static_cast(ws[0]); - ws.resize(static_cast(lws)); + const std::size_t lws_ = static_cast(lws); + ws.resize(lws_); container::lapackConnector::getri( /* n= */ n, /* a= */ matrix.data(), @@ -111,9 +114,10 @@ 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(static_cast(n)); + std::vector ipiv(n_); int info = 0; container::lapackConnector::getrf( /* m= */ n, @@ -136,7 +140,8 @@ void inv(Matrix2dView> matrix) /* info= */ info); throw_lapack_error("LAPACK getri workspace query", info); lws = static_cast(ws[0].real()); - ws.resize(static_cast(lws)); + const std::size_t lws_ = static_cast(lws); + ws.resize(lws_); container::lapackConnector::getri( /* n= */ n, /* a= */ matrix.data(), @@ -156,9 +161,11 @@ void solve(Matrix2dView matrix, 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(static_cast(n)); + std::vector ipiv(n_); int info = 0; container::lapackConnector::getrf( /* m= */ n, @@ -170,19 +177,18 @@ void solve(Matrix2dView matrix, throw_lapack_error("LAPACK getrf", info); // Column-major LAPACK right-hand side for A * X = B. - std::vector b( - static_cast(n) * static_cast(nrhs)); + 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) { - b[static_cast(i) - + static_cast(j) * static_cast(n)] - = rhs.atloc(i, j); + const std::size_t j_ = static_cast(j); + b[i_ + j_ * n_] = rhs.atloc(i, j); } } - const char trans = matrix.is_distributed() ? 'N' : 'T'; + const char trans = matrix.has_distribution() ? 'N' : 'T'; container::lapackConnector::getrs( /* trans= */ trans, /* n= */ n, @@ -197,11 +203,11 @@ void solve(Matrix2dView matrix, for (int i = 0; i < n; ++i) { + const std::size_t i_ = static_cast(i); for (int j = 0; j < nrhs; ++j) { - rhs.atloc(i, j) - = b[static_cast(i) - + static_cast(j) * static_cast(n)]; + const std::size_t j_ = static_cast(j); + rhs.atloc(i, j) = b[i_ + j_ * n_]; } } } @@ -214,9 +220,11 @@ void solve(Matrix2dView> matrix, 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(static_cast(n)); + std::vector ipiv(n_); int info = 0; container::lapackConnector::getrf( /* m= */ n, @@ -228,19 +236,18 @@ void solve(Matrix2dView> matrix, throw_lapack_error("LAPACK getrf", info); // Column-major LAPACK right-hand side for A * X = B. - std::vector> b( - static_cast(n) * static_cast(nrhs)); + 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) { - b[static_cast(i) - + static_cast(j) * static_cast(n)] - = rhs.atloc(i, j); + const std::size_t j_ = static_cast(j); + b[i_ + j_ * n_] = rhs.atloc(i, j); } } - const char trans = matrix.is_distributed() ? 'N' : 'T'; + const char trans = matrix.has_distribution() ? 'N' : 'T'; container::lapackConnector::getrs( /* trans= */ trans, /* n= */ n, @@ -255,11 +262,11 @@ void solve(Matrix2dView> matrix, for (int i = 0; i < n; ++i) { + const std::size_t i_ = static_cast(i); for (int j = 0; j < nrhs; ++j) { - rhs.atloc(i, j) - = b[static_cast(i) - + static_cast(j) * static_cast(n)]; + const std::size_t j_ = static_cast(j); + rhs.atloc(i, j) = b[i_ + j_ * n_]; } } } diff --git a/source/source_base/matrix2d_lapack.h b/source/source_base/matrix2d_lapack.h index 3a46eb2831a..543ee69928b 100644 --- a/source/source_base/matrix2d_lapack.h +++ b/source/source_base/matrix2d_lapack.h @@ -1,6 +1,15 @@ #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 diff --git a/source/source_base/matrix2d_linalg.cpp b/source/source_base/matrix2d_linalg.cpp index 36b3e1f6b25..2877544aca0 100644 --- a/source/source_base/matrix2d_linalg.cpp +++ b/source/source_base/matrix2d_linalg.cpp @@ -20,7 +20,7 @@ namespace template bool distribution_is_active(const Matrix2dView& matrix) { - return matrix.is_distributed() && !matrix.distribution()->is_serial(); + return matrix.is_active(); } /** @@ -30,7 +30,7 @@ bool distribution_is_active(const Matrix2dView& matrix) template bool distribution_is_serial(const Matrix2dView& matrix) { - return matrix.is_distributed() && matrix.distribution()->is_serial(); + return matrix.has_distribution() && matrix.distribution()->is_serial(); } template @@ -47,12 +47,12 @@ template void assert_compatible_layout(const Matrix2dView& left, const Matrix2dView& right) { - if (left.is_distributed() != right.is_distributed()) + if (left.has_distribution() != right.has_distribution()) { throw std::invalid_argument( "matrix operations require matching host or distributed layouts"); } - if (!left.is_distributed()) + if (!left.has_distribution()) { return; } @@ -67,17 +67,13 @@ void assert_compatible_layout(const Matrix2dView& left, { return; } - 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 distributed layouts"); - } +#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 @@ -125,6 +121,9 @@ void axpby_impl(Matrix2dView result, 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) @@ -138,6 +137,9 @@ void axpby_impl(Matrix2dView result, 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) @@ -193,7 +195,7 @@ void assert_solve_views(const Matrix2dView& matrix, throw std::invalid_argument( "linear solve requires a square matrix and matching right-hand side"); } - if (matrix.is_distributed() != rhs.is_distributed()) + if (matrix.has_distribution() != rhs.has_distribution()) { throw std::invalid_argument( "linear solve requires matching host or distributed layouts"); @@ -207,18 +209,17 @@ void assert_solve_views(const Matrix2dView& matrix, { return; } - if (matrix.is_distributed() - && (matrix.desc() == nullptr - || rhs.desc() == nullptr - || matrix.desc()[1] != rhs.desc()[1] - || matrix.desc()[4] != rhs.desc()[4] - || matrix.desc()[5] != rhs.desc()[5] - || matrix.desc()[6] != rhs.desc()[6] - || matrix.desc()[7] != rhs.desc()[7])) + if (!matrix.has_distribution()) { - throw std::invalid_argument( - "linear solve requires compatible distributed layouts"); + 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, @@ -231,7 +232,7 @@ void assert_solve_views(const Matrix2dView>& matrix, throw std::invalid_argument( "linear solve requires a square matrix and matching right-hand side"); } - if (matrix.is_distributed() != rhs.is_distributed()) + if (matrix.has_distribution() != rhs.has_distribution()) { throw std::invalid_argument( "linear solve requires matching host or distributed layouts"); @@ -245,18 +246,17 @@ void assert_solve_views(const Matrix2dView>& matrix, { return; } - if (matrix.is_distributed() - && (matrix.desc() == nullptr - || rhs.desc() == nullptr - || matrix.desc()[1] != rhs.desc()[1] - || matrix.desc()[4] != rhs.desc()[4] - || matrix.desc()[5] != rhs.desc()[5] - || matrix.desc()[6] != rhs.desc()[6] - || matrix.desc()[7] != rhs.desc()[7])) + if (!matrix.has_distribution()) { - throw std::invalid_argument( - "linear solve requires compatible distributed layouts"); + 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 } } // namespace 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 index aaac3c87d50..f9157e022cb 100644 --- a/source/source_base/matrix2d_reduction.cpp +++ b/source/source_base/matrix2d_reduction.cpp @@ -1,12 +1,14 @@ #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 #include @@ -20,6 +22,10 @@ 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 @@ -103,50 +109,6 @@ void reduce_max_over_processes(double& value, const Matrix2d& matrix) #endif } -int checked_mpi_count(const std::size_t nbytes) -{ - if (nbytes > static_cast(std::numeric_limits::max())) - { - throw std::invalid_argument( - "Matrix2d diagonal data buffer exceeds MPI count range"); - } - return static_cast(nbytes); -} - -std::vector make_byte_displs(const std::vector& nbytes) -{ - std::vector displs(nbytes.size(), 0); - int offset = 0; - for (std::size_t ip = 0; ip < nbytes.size(); ++ip) - { - displs[ip] = offset; - if (nbytes[ip] > std::numeric_limits::max() - offset) - { - throw std::invalid_argument( - "Matrix2d diagonal data buffer size overflow"); - } - offset += nbytes[ip]; - } - return displs; -} - -#ifdef __MPI -std::vector gather_nbytes(const int nbytes_local, const MPI_Comm comm) -{ - const int nproc = Parallel_Common::comm_size(comm); - const std::vector nbytes_recv(static_cast(nproc), W_INT); - const std::vector rdispls - = make_byte_displs(nbytes_recv); - std::vector nbytes(static_cast(nproc), 0); - Parallel_Common::allgatherv_bytes(&nbytes_local, - W_INT, - nbytes.data(), - nbytes_recv.data(), - rdispls.data(), - comm); - return nbytes; -} -#endif } // namespace namespace matrix2d_impl @@ -302,7 +264,8 @@ std::vector diagonal(const Matrix2d& matrix) const std::size_t nbytes_local = W_INT + local_entries.size() * nbytes_entry; std::vector local_diagonal_buffer(nbytes_local); - const int nentry_local = checked_mpi_count(local_entries.size()); + const int nentry_local + = mpi::checked_mpi_count(local_entries.size()); std::memcpy(local_diagonal_buffer.data(), &nentry_local, W_INT); @@ -319,11 +282,12 @@ std::vector diagonal(const Matrix2d& matrix) offset += sizeof(entry.second); } - const int nbytes_local_mpi = checked_mpi_count(nbytes_local); + const int nbytes_local_mpi + = mpi::checked_mpi_count(nbytes_local); const std::vector nbytes_recv - = gather_nbytes(nbytes_local_mpi, comm); + = mpi::allgather_nbytes(nbytes_local_mpi, comm); const std::vector rdispls - = make_byte_displs(nbytes_recv); + = mpi::make_byte_offsets(nbytes_recv); const int total_bytes = rdispls.back() + nbytes_recv.back(); std::vector received( diff --git a/source/source_base/matrix2d_reduction.h b/source/source_base/matrix2d_reduction.h index a91ee6fbc34..f0b57118aad 100644 --- a/source/source_base/matrix2d_reduction.h +++ b/source/source_base/matrix2d_reduction.h @@ -1,6 +1,14 @@ #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 diff --git a/source/source_base/matrix2d_scalapack.cpp b/source/source_base/matrix2d_scalapack.cpp index 242c6e41d73..7b9814cad9a 100644 --- a/source/source_base/matrix2d_scalapack.cpp +++ b/source/source_base/matrix2d_scalapack.cpp @@ -13,6 +13,22 @@ 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) { diff --git a/source/source_base/matrix2d_scalapack.h b/source/source_base/matrix2d_scalapack.h index 4c5bc80203e..cf6d1b6a16e 100644 --- a/source/source_base/matrix2d_scalapack.h +++ b/source/source_base/matrix2d_scalapack.h @@ -1,6 +1,15 @@ #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 @@ -11,6 +20,8 @@ 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, diff --git a/source/source_base/matrix2d_view.h b/source/source_base/matrix2d_view.h index 8cba2dcd46f..22740229b30 100644 --- a/source/source_base/matrix2d_view.h +++ b/source/source_base/matrix2d_view.h @@ -138,12 +138,21 @@ class Matrix2dView } /** - * @brief Return whether a distribution handle is attached. + * @brief Return whether a frozen distribution handle is attached. * - * This includes serial frozen distributions; it does not imply that more - * than one MPI rank participates. + * 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 is_distributed() const { return distrib_ != nullptr; } + 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. * diff --git a/source/source_base/module_external/scalapack_connector.h b/source/source_base/module_external/scalapack_connector.h index 2276d3ed48e..95dcd50fde6 100644 --- a/source/source_base/module_external/scalapack_connector.h +++ b/source/source_base/module_external/scalapack_connector.h @@ -162,13 +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, const int *lwork, const int *iwork, const int *liwork, const int *info); + int *ipiv, double *work, int *lwork, int *iwork, int *liwork, int *info); void pzgeadd_( const char *transa, @@ -419,9 +419,9 @@ class ScalapackConnector 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); } @@ -430,7 +430,7 @@ class ScalapackConnector void getri( const int n, double *A, const int ia, const int ja, const int *desca, int *ipiv, - double *work, const int *lwork, const int *iwork, const int *liwork, int *info) + double *work, int *lwork, int *iwork, int *liwork, int *info) { pdgetri_(&n, A, &ia, &ja, desca, ipiv, work, lwork, iwork, liwork, info); } diff --git a/source/source_base/unittests/test_matrix2d.cpp b/source/source_base/unittests/test_matrix2d.cpp index 03a3456fb33..db263fcfb1a 100644 --- a/source/source_base/unittests/test_matrix2d.cpp +++ b/source/source_base/unittests/test_matrix2d.cpp @@ -3,11 +3,10 @@ #endif #include "source_base/matrix2d.h" +#include "source_base/matrix2d_view.h" #ifdef __MPI #include "source_base/parallel_common.h" -#else -#include "source_base/matrix2d_view.h" #endif #include "gtest/gtest.h" @@ -125,7 +124,8 @@ void check_host_layout() { Matrix2d matrix(2, 3); - EXPECT_FALSE(matrix.is_distributed()); + 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); @@ -176,6 +176,11 @@ void check_distribution_layout(Matrix2d& matrix, 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()); @@ -401,7 +406,8 @@ Matrix2d make_host_reference(const int nr, template void verify_global_matrix(const Matrix2d& actual, const Matrix2d& expected) { - ASSERT_FALSE(actual.is_distributed()); + 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) @@ -593,7 +599,8 @@ void check_gather_scatter(Matrix2d& matrix) EXPECT_EQ(root_result.ncglb(), 0); EXPECT_EQ(root_result.size(), 0); EXPECT_EQ(root_result.lld(), 0); - EXPECT_FALSE(root_result.is_distributed()); + EXPECT_FALSE(root_result.has_distribution()); + EXPECT_FALSE(root_result.is_active()); } #endif @@ -772,8 +779,10 @@ void check_host_transpose(const int nr, const int nc) verify_global_matrix(transposed, expected_transpose); verify_global_matrix(dagger, expected_dagger); - EXPECT_FALSE(transposed.is_distributed()); - EXPECT_FALSE(dagger.is_distributed()); + 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); @@ -791,7 +800,8 @@ void check_host_matmul(const int m, const Matrix2d expected = make_matmul_reference(left, right); verify_global_matrix(product, expected); - EXPECT_FALSE(product.is_distributed()); + EXPECT_FALSE(product.has_distribution()); + EXPECT_FALSE(product.is_active()); } #ifdef __MPI @@ -836,8 +846,10 @@ void check_distributed_transpose(const int nr, const int* const desc_res = transposed.desc(); const int* const desc_dag = dagger.desc(); - ASSERT_TRUE(transposed.is_distributed()); - ASSERT_TRUE(dagger.is_distributed()); + 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); @@ -902,7 +914,8 @@ void check_distributed_matmul(const int m, const int* const desc_rhs1 = right.desc(); const int* const desc_res = product.desc(); - ASSERT_TRUE(product.is_distributed()); + 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); @@ -1018,7 +1031,8 @@ TEST(Matrix2dTest, DistributedResultRetainsBlacsContext) const Matrix2d transposed = make_transpose_without_source(5, 3, nrproc, ncproc, 3); - ASSERT_TRUE(transposed.is_distributed()); + 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(), @@ -1205,7 +1219,8 @@ TEST(Matrix2dTest, SerialDistributionHandleUsesColumnMajorLayout) = make_frozen_distribution(3, 2); Matrix2d matrix(distrib); - EXPECT_TRUE(matrix.is_distributed()); + 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); @@ -1238,7 +1253,8 @@ TEST(Matrix2dTest, SerialDistributionViewMatchesColumnMajorStorageWithoutMpi) fill_global_values(matrix); Matrix2dView matrix_view = matrix.view(); - ASSERT_TRUE(matrix_view.is_distributed()); + 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()); @@ -1405,11 +1421,13 @@ TEST(Matrix2dTest, SerialDistributionGatherReturnsHostRowMajorCopy) fill_global_values(matrix); const Matrix2d gathered = matrix.gather(); - EXPECT_FALSE(gathered.is_distributed()); + 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.is_distributed()); + EXPECT_FALSE(root_gathered.has_distribution()); + EXPECT_FALSE(root_gathered.is_active()); verify_global_matrix(root_gathered, make_host_reference(3, 2)); } diff --git a/source/source_base/unittests/test_matrix2d_linalg.cpp b/source/source_base/unittests/test_matrix2d_linalg.cpp index 3c1cbae90e7..7276c1b255e 100644 --- a/source/source_base/unittests/test_matrix2d_linalg.cpp +++ b/source/source_base/unittests/test_matrix2d_linalg.cpp @@ -395,6 +395,24 @@ TEST(Matrix2dLinalgTest, RejectsSingularAndMismatchedMatrices) 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(host.view(), + 1.0, + distributed.view(), + 0.0, + host.view()), + std::invalid_argument); +} + #ifdef __MPI TEST(Matrix2dLinalgTest, DistributedRealAndComplexSolve) { From 782c9e505e92f477250af3291ebfbc6f98a88827 Mon Sep 17 00:00:00 2001 From: kirk0830 Date: Sun, 22 Nov 2026 20:21:26 +0800 Subject: [PATCH 10/15] docs: record part B review fix verification --- BATCH_B_result.md | 114 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 114 insertions(+) create mode 100644 BATCH_B_result.md diff --git a/BATCH_B_result.md b/BATCH_B_result.md new file mode 100644 index 00000000000..308499e50b2 --- /dev/null +++ b/BATCH_B_result.md @@ -0,0 +1,114 @@ +# PR #8317 第 B 批修复结果 + +## 1. 本批完成项 + +### B 类审阅意见 + +- `4628814647`:`make_local_metadata()` 改为先计算精确 `nmeta`,构造 + `std::vector(nmeta)` 后按偏移赋值,不再 `reserve + push_back`。 +- `4628880948`:保留 `int` 作为 BLACS/ScaLAPACK 边界类型;在 + `matrix2d_mpi.cpp::checked_mpi_count()` 的 `size_t -> int` 边界保留 + `FIXME`,没有机械改成 `size_t`。 +- `4629051593`:公共内部 helper 使用 `make_byte_offsets()` 命名,保留显式 + scan,没有为缩短代码强改为 STL 累加。 +- `4629082027`:`allgather_nbytes()` 保留两阶段流程;第一阶段通过临时 + `ParaWorld::make_mpi(tag, comm)` 调用现有 + `Parallel::allgather_int()` 收集各 rank 的 byte count,第二阶段继续使用 + `allgatherv_bytes()`。没有新增 `Parallel_Common` wrapper API。 +- `4657484541`:为 collective/LAPACK/reduction/ScaLAPACK 后端头和新的 MPI + helper 增加 `@internal` 文档,明确调用者应只 include + `matrix2d.h`/`matrix2d_linalg.h`;未改 PIMPL。 +- `4657491818`:`assert_compatible_layout()` 改为非模板私有成员,实现移入 + `matrix2d.cpp`;原有显式类实例化保留。 +- `4657493928`:分布句柄初始化函数改为按值接收 + `std::shared_ptr` 并 `std::move` 到成员; + `Matrix2dView` 继续持有 `shared_ptr`。 +- `4657511707` / `4657523602`:删除每个 rank 一份 + `vector` 的复制;all-gather/gather 只在单个连续 + `recvbuf` 上工作,并通过轻量 `RankBufferView {data, size}` 反序列化。 +- `4657536301` / `4657539879`:保留自定义 gather/scatter。新增文件级说明, + 明确真正的 block-cyclic owner map 由 + `Parallel_Blkcyclic`/`Cblacs_gridinit`/`numroc_`/`descinit_` 定义;scatter + 打包循环提取为 `pack_rank_values()`,这里只按已有 owner map 搬值。 +- `4657554100`:LAPACK 的 `n`/`nrhs`/`lda` 仍为 `int`;增加 `n_` 及 + `nrhs_` 作为 `std::size_t`,统一用于 vector size 和下标。 +- `4657566089`:linalg dispatcher 继续统一执行 shape/layout 前置校验;仅将 + `desc[...]` 比较提取为 ScaLAPACK 专用 + `matrix2d_impl::scalapack::assert_compatible_layout()`。 +- `4657568182` / `4657568544`:`axpby_impl()` 与 `scale_impl()` 外层循环增加 + `_OPENMP` 守卫及 + `#pragma omp parallel for collapse(2) schedule(static)`。 +- `4657580013`:新增 `matrix2d_mpi.{h,cpp}`,集中 + `checked_mpi_count()`、`make_byte_offsets()` 和 rank-count gather; + collective 与 reduction 共用,MPI 聚合通过 `ParaWorld` 调用现有 wrapper。 +- `4657597193`:`Matrix2dView` 保持 `T* data_` 与分布共享句柄,没有改为 + `weak_ptr`。 +- 额外发现:修正 ScaLAPACK `p[dz]getri_()` 和 `ScalapackConnector::getri()` + 输出参数上的错误 `const`,包括 `A`、workspace、workspace size、`iwork` + 与 `info`。 + +### 用户拍板 + +- 拍板③:按值接收 `shared_ptr` 后 move,`Matrix2dView` 继续共享句柄。 +- 拍板④:在 `size_t -> int` 检查处保留 `FIXME`,未改成普通约束说明。 +- 拍板⑥:dispatcher 保留统一 shape/layout 检查;低层 descriptor 判断进入 + ScaLAPACK helper。 +- 拍板⑦:公共 API 拆为 `has_distribution()`(含 serial 1x1 handle)和 + `is_active()`(非 serial 的 active MPI 分布);内部继续使用 + `distribution_is_active()`/`distribution_is_serial()`。所有调用点已按语义 + 迁移,例如 LAPACK 的 `trans` 依据 column-major handle 使用 + `has_distribution()`,算法分派使用 `is_active()`。 + +## 2. W_INT 核对 + +批 A 已使用 `W_INT = sizeof(int)`,没有使用 `NBYTES_INT`。collective 和 +reduction 的定义处均已有注释,说明其是 native `int` 的 byte 数,因此本批 +无需再改名。 + +## 3. 跳过项 + +- 未发现因 develop merge 而消失、需要单独跳过的 B 类符号。 +- C 批的数值返回类型/API 项(`real_type`、`abs2`、`inv` 数值告警等)按用户 + 要求未做。 +- 工作树中未找到 `THOROUGH_review_plan.md`;本批依据用户消息中的 B 类清单、 + 拍板项和只读 GitHub 审阅评论上下文执行,没有据此遗漏列表中的 B 类条目。 + +## 4. 验证 + +所有构建和测试均在 `module load abacus-dev/1.0` 后执行。 + +- `cmake --build build-matrix2d-cxx11 --target base -j2` + - 退出码 0;编译命令为 `-std=gnu++11`。 +- `cmake --build build-matrix2d-mpi-cxx11 --target base -j2` + - 退出码 0;编译命令为 `-std=gnu++11`。 +- `cmake --build build-matrix2d-serial --target MODULE_BASE_matrix2d MODULE_BASE_matrix2d_linalg -j2` + - 退出码 0。 +- `cmake --build build-matrix2d-mpi --target MODULE_BASE_matrix2d MODULE_BASE_matrix2d_linalg -j2` + - 退出码 0。 +- `OMP_NUM_THREADS=1 ctest --test-dir build-matrix2d-serial --output-on-failure -R 'MODULE_BASE_matrix2d'` + - 退出码 0,2/2 通过。 +- `OMP_NUM_THREADS=1 ctest --test-dir build-matrix2d-mpi --output-on-failure -R 'MODULE_BASE_matrix2d'` + - 退出码 0,6/6 通过;包含 serial 2 项及 MPI 2-rank/4-rank 各 2 项。 +- OMP 防竞争复跑使用 `OMP_NUM_THREADS=2`: + - serial 2/2 通过。 + - MPI 6/6 通过。 +- `git diff --check` + - 退出码 0。 +- `python3 tools/03_code_analysis/agent_governance_check.py --staged --format text` + - 退出码 0;仅保留 `matrix2d_mpi.h` 的直接 include 警告和本地无 PR body 的 + documentation-sync 警告。 +- `agent_governance_check.py --base fbaf69833 --head 0ac210ae3` + - 退出码 0,无 blocker;warning 同上。 +- `code_quality_score.py` 扫描 17 个改动 C++ 文件,15/17 达到 60 分。 + - 未达线历史结构项为既有 612 行 `scalapack_connector.h` 和 1612 行 + `test_matrix2d.cpp`;其问题是文件规模等既有债务,不是新增确定性错误。 + +## 5. Commit + +- B 类实现 commit:`0ac210ae3` + - `refactor(base): address review structure/MPI/OMP findings (part B)` +- 本结果文件使用紧随其后的独立 docs commit 记录。 + +## 6. 工作树 + +报告提交后工作树干净;未 push、未修改 auto-merge、未回复 PR thread。 From 3bf1d7f7ff3eb1895d1b11b20288f4eb4ef8d51f Mon Sep 17 00:00:00 2001 From: kirk0830 Date: Sun, 22 Nov 2026 20:57:32 +0800 Subject: [PATCH 11/15] refactor(base): align Matrix2d numeric API with review (part C) --- source/source_base/matrix2d.cpp | 4 +- source/source_base/matrix2d.h | 48 +++++++++++++- source/source_base/matrix2d_lapack.h | 8 +++ source/source_base/matrix2d_linalg.h | 8 +++ source/source_base/matrix2d_reduction.cpp | 60 ++++++++++-------- source/source_base/matrix2d_reduction.h | 4 +- source/source_base/matrix2d_scalapack.h | 9 +++ .../source_base/unittests/test_matrix2d.cpp | 63 +++++++++++++++++++ .../unittests/test_matrix2d_linalg.cpp | 27 ++++++++ 9 files changed, 198 insertions(+), 33 deletions(-) diff --git a/source/source_base/matrix2d.cpp b/source/source_base/matrix2d.cpp index 4f1e23b356f..5094b6be5c8 100644 --- a/source/source_base/matrix2d.cpp +++ b/source/source_base/matrix2d.cpp @@ -482,13 +482,13 @@ T NDArray::dot(const NDArray& other) const } template -double NDArray::norm() const +real_type NDArray::norm() const { return matrix2d_impl::norm(*this); } template -double NDArray::max_abs() const +real_type NDArray::max_abs() const { return matrix2d_impl::max_abs(*this); } diff --git a/source/source_base/matrix2d.h b/source/source_base/matrix2d.h index 234862a14ae..16706117043 100644 --- a/source/source_base/matrix2d.h +++ b/source/source_base/matrix2d.h @@ -17,6 +17,49 @@ 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. @@ -117,8 +160,9 @@ class NDArray final T sum() const; T dot(const NDArray& other) const; /** Return the Frobenius norm sqrt(sum_ij |a_ij|^2). */ - double norm() const; - double max_abs() const; + real_type norm() const; + /** Return max_ij |a_ij|. */ + real_type max_abs() const; std::vector diagonal() const; NDArray gather() const; diff --git a/source/source_base/matrix2d_lapack.h b/source/source_base/matrix2d_lapack.h index 543ee69928b..19f034caed1 100644 --- a/source/source_base/matrix2d_lapack.h +++ b/source/source_base/matrix2d_lapack.h @@ -19,7 +19,15 @@ 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, diff --git a/source/source_base/matrix2d_linalg.h b/source/source_base/matrix2d_linalg.h index be1afab2112..4ced1eb00a6 100644 --- a/source/source_base/matrix2d_linalg.h +++ b/source/source_base/matrix2d_linalg.h @@ -8,7 +8,15 @@ namespace matrix2d_linalg { +/** + * @brief Invert a square matrix in place using an explicit matrix inverse. + * + * @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, diff --git a/source/source_base/matrix2d_reduction.cpp b/source/source_base/matrix2d_reduction.cpp index f9157e022cb..718046e71e6 100644 --- a/source/source_base/matrix2d_reduction.cpp +++ b/source/source_base/matrix2d_reduction.cpp @@ -42,31 +42,32 @@ std::complex conj(const std::complex& value) } // namespace elementwise template -double absolute_square(const T& value) +real_type abs2(const T& value) { - const double real_value = static_cast(value); + const real_type real_value = static_cast>(value); return real_value * real_value; } template -double absolute_square(const std::complex& value) +real_type> abs2(const std::complex& value) { - const double real = static_cast(value.real()); - const double imag = static_cast(value.imag()); + using Real = real_type>; + const Real real = static_cast(value.real()); + const Real imag = static_cast(value.imag()); return real * real + imag * imag; } template -double absolute_value(const T& value) +real_type absolute_value(const T& value) { - const double widened_value = static_cast(value); + const real_type widened_value = static_cast>(value); return std::abs(widened_value); } template -double absolute_value(const std::complex& value) +real_type> absolute_value(const std::complex& value) { - return static_cast(std::abs(value)); + return static_cast>>(std::abs(value)); } template @@ -90,7 +91,7 @@ void reduce_sum_over_processes(Value& value, const Matrix2d& matrix) } template -void reduce_max_over_processes(double& value, const Matrix2d& matrix) +void reduce_max_over_processes(real_type& value, const Matrix2d& matrix) { #ifdef __MPI const std::shared_ptr distrib @@ -100,7 +101,11 @@ void reduce_max_over_processes(double& value, const Matrix2d& matrix) const MPI_Comm comm = distrib->comm(); if (comm != MPI_COMM_NULL) { - Parallel_Common::allreduce_max(value, comm); + // The guarded wrapper currently exposes only double. Widening the + // collective value does not change the maximum or the public type. + double collective_value = value; + Parallel_Common::allreduce_max(collective_value, comm); + value = static_cast>(collective_value); } } #else @@ -151,9 +156,9 @@ T sum(const Matrix2d& matrix) } template -double norm(const Matrix2d& matrix) +real_type norm(const Matrix2d& matrix) { - double value = 0.0; + real_type value = real_type(); const int nrloc = matrix.nrloc(); const int ncloc = matrix.ncloc(); #ifdef _OPENMP @@ -163,7 +168,8 @@ double norm(const Matrix2d& matrix) { for (int j = 0; j < ncloc; ++j) { - value += absolute_square(matrix.atloc(i, j)); + const T& element = matrix.atloc(i, j); + value += abs2(element); } } reduce_sum_over_processes(value, matrix); @@ -210,9 +216,9 @@ T dot(const Matrix2d& left, const Matrix2d& right) } template -double max_abs(const Matrix2d& matrix) +real_type max_abs(const Matrix2d& matrix) { - double max_value = 0.0; + real_type max_value = real_type(); const int nrloc = matrix.nrloc(); const int ncloc = matrix.ncloc(); #ifdef _OPENMP @@ -223,7 +229,7 @@ double max_abs(const Matrix2d& matrix) for (int j = 0; j < ncloc; ++j) { const T& element = matrix.atloc(i, j); - const double element_abs = absolute_value(element); + const real_type element_abs = absolute_value(element); max_value = std::max(max_value, element_abs); } } @@ -376,20 +382,20 @@ template std::complex dot>( const Matrix2d>& left, const Matrix2d>& right); -template double norm(const Matrix2d& matrix); -template double norm(const Matrix2d& matrix); -template double norm(const Matrix2d& matrix); -template double norm>( +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 double norm>( +template real_type> norm>( const Matrix2d>& matrix); -template double max_abs(const Matrix2d& matrix); -template double max_abs(const Matrix2d& matrix); -template double max_abs(const Matrix2d& matrix); -template double max_abs>( +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 double max_abs>( +template real_type> max_abs>( const Matrix2d>& matrix); template std::vector diagonal(const Matrix2d& matrix); diff --git a/source/source_base/matrix2d_reduction.h b/source/source_base/matrix2d_reduction.h index f0b57118aad..fd757b67d05 100644 --- a/source/source_base/matrix2d_reduction.h +++ b/source/source_base/matrix2d_reduction.h @@ -20,10 +20,10 @@ template T dot(const Matrix2d& left, const Matrix2d& right); template -double norm(const Matrix2d& matrix); +real_type norm(const Matrix2d& matrix); template -double max_abs(const Matrix2d& matrix); +real_type max_abs(const Matrix2d& matrix); template std::vector diagonal(const Matrix2d& matrix); diff --git a/source/source_base/matrix2d_scalapack.h b/source/source_base/matrix2d_scalapack.h index cf6d1b6a16e..ddfc5cc9357 100644 --- a/source/source_base/matrix2d_scalapack.h +++ b/source/source_base/matrix2d_scalapack.h @@ -31,7 +31,16 @@ void conjugate_transpose(Matrix2dView result, 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); diff --git a/source/source_base/unittests/test_matrix2d.cpp b/source/source_base/unittests/test_matrix2d.cpp index db263fcfb1a..07837d783fb 100644 --- a/source/source_base/unittests/test_matrix2d.cpp +++ b/source/source_base/unittests/test_matrix2d.cpp @@ -41,6 +41,24 @@ 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 { @@ -562,6 +580,22 @@ void check_reductions(Matrix2d& matrix, Matrix2d& other) } } +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_gather_scatter(Matrix2d& matrix) { @@ -1413,6 +1447,35 @@ TEST(Matrix2dTest, MaxAbsWidensIntegerBeforeTakingAbsoluteValue) 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_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); +} + TEST(Matrix2dTest, SerialDistributionGatherReturnsHostRowMajorCopy) { const std::shared_ptr distrib diff --git a/source/source_base/unittests/test_matrix2d_linalg.cpp b/source/source_base/unittests/test_matrix2d_linalg.cpp index 7276c1b255e..d114820852b 100644 --- a/source/source_base/unittests/test_matrix2d_linalg.cpp +++ b/source/source_base/unittests/test_matrix2d_linalg.cpp @@ -271,6 +271,33 @@ TEST(Matrix2dLinalgTest, HostRealInverseAndSolve) expect_host_matrices_near(rhs, expected); } +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(real_inverse_view); + Matrix2d real_identity(2, 2); + Matrix2dView real_identity_view = real_identity.view(); + matrix2d_linalg::set_identity(real_identity_view); + const Matrix2d real_product = real_matrix.matmul(real_inverse); + expect_host_matrices_near(real_product, real_identity); + + const Matrix2d> complex_matrix + = make_complex_system(); + Matrix2d> complex_inverse = complex_matrix; + Matrix2dView> complex_inverse_view + = complex_inverse.view(); + matrix2d_linalg::inv(complex_inverse_view); + Matrix2d> complex_identity(2, 2); + Matrix2dView> complex_identity_view + = complex_identity.view(); + matrix2d_linalg::set_identity(complex_identity_view); + const Matrix2d> complex_product + = complex_matrix.matmul(complex_inverse); + expect_host_matrices_near(complex_product, complex_identity); +} + TEST(Matrix2dLinalgTest, HostComplexSolve) { Matrix2d> matrix = make_complex_system(); From fbbcadb540ee3baccbaf4f7a3a4040b6aa0e7af4 Mon Sep 17 00:00:00 2001 From: kirk0830 Date: Sun, 22 Nov 2026 20:58:31 +0800 Subject: [PATCH 12/15] chore: move review report out of source tree --- BATCH_B_result.md | 114 ---------------------------------------------- 1 file changed, 114 deletions(-) delete mode 100644 BATCH_B_result.md diff --git a/BATCH_B_result.md b/BATCH_B_result.md deleted file mode 100644 index 308499e50b2..00000000000 --- a/BATCH_B_result.md +++ /dev/null @@ -1,114 +0,0 @@ -# PR #8317 第 B 批修复结果 - -## 1. 本批完成项 - -### B 类审阅意见 - -- `4628814647`:`make_local_metadata()` 改为先计算精确 `nmeta`,构造 - `std::vector(nmeta)` 后按偏移赋值,不再 `reserve + push_back`。 -- `4628880948`:保留 `int` 作为 BLACS/ScaLAPACK 边界类型;在 - `matrix2d_mpi.cpp::checked_mpi_count()` 的 `size_t -> int` 边界保留 - `FIXME`,没有机械改成 `size_t`。 -- `4629051593`:公共内部 helper 使用 `make_byte_offsets()` 命名,保留显式 - scan,没有为缩短代码强改为 STL 累加。 -- `4629082027`:`allgather_nbytes()` 保留两阶段流程;第一阶段通过临时 - `ParaWorld::make_mpi(tag, comm)` 调用现有 - `Parallel::allgather_int()` 收集各 rank 的 byte count,第二阶段继续使用 - `allgatherv_bytes()`。没有新增 `Parallel_Common` wrapper API。 -- `4657484541`:为 collective/LAPACK/reduction/ScaLAPACK 后端头和新的 MPI - helper 增加 `@internal` 文档,明确调用者应只 include - `matrix2d.h`/`matrix2d_linalg.h`;未改 PIMPL。 -- `4657491818`:`assert_compatible_layout()` 改为非模板私有成员,实现移入 - `matrix2d.cpp`;原有显式类实例化保留。 -- `4657493928`:分布句柄初始化函数改为按值接收 - `std::shared_ptr` 并 `std::move` 到成员; - `Matrix2dView` 继续持有 `shared_ptr`。 -- `4657511707` / `4657523602`:删除每个 rank 一份 - `vector` 的复制;all-gather/gather 只在单个连续 - `recvbuf` 上工作,并通过轻量 `RankBufferView {data, size}` 反序列化。 -- `4657536301` / `4657539879`:保留自定义 gather/scatter。新增文件级说明, - 明确真正的 block-cyclic owner map 由 - `Parallel_Blkcyclic`/`Cblacs_gridinit`/`numroc_`/`descinit_` 定义;scatter - 打包循环提取为 `pack_rank_values()`,这里只按已有 owner map 搬值。 -- `4657554100`:LAPACK 的 `n`/`nrhs`/`lda` 仍为 `int`;增加 `n_` 及 - `nrhs_` 作为 `std::size_t`,统一用于 vector size 和下标。 -- `4657566089`:linalg dispatcher 继续统一执行 shape/layout 前置校验;仅将 - `desc[...]` 比较提取为 ScaLAPACK 专用 - `matrix2d_impl::scalapack::assert_compatible_layout()`。 -- `4657568182` / `4657568544`:`axpby_impl()` 与 `scale_impl()` 外层循环增加 - `_OPENMP` 守卫及 - `#pragma omp parallel for collapse(2) schedule(static)`。 -- `4657580013`:新增 `matrix2d_mpi.{h,cpp}`,集中 - `checked_mpi_count()`、`make_byte_offsets()` 和 rank-count gather; - collective 与 reduction 共用,MPI 聚合通过 `ParaWorld` 调用现有 wrapper。 -- `4657597193`:`Matrix2dView` 保持 `T* data_` 与分布共享句柄,没有改为 - `weak_ptr`。 -- 额外发现:修正 ScaLAPACK `p[dz]getri_()` 和 `ScalapackConnector::getri()` - 输出参数上的错误 `const`,包括 `A`、workspace、workspace size、`iwork` - 与 `info`。 - -### 用户拍板 - -- 拍板③:按值接收 `shared_ptr` 后 move,`Matrix2dView` 继续共享句柄。 -- 拍板④:在 `size_t -> int` 检查处保留 `FIXME`,未改成普通约束说明。 -- 拍板⑥:dispatcher 保留统一 shape/layout 检查;低层 descriptor 判断进入 - ScaLAPACK helper。 -- 拍板⑦:公共 API 拆为 `has_distribution()`(含 serial 1x1 handle)和 - `is_active()`(非 serial 的 active MPI 分布);内部继续使用 - `distribution_is_active()`/`distribution_is_serial()`。所有调用点已按语义 - 迁移,例如 LAPACK 的 `trans` 依据 column-major handle 使用 - `has_distribution()`,算法分派使用 `is_active()`。 - -## 2. W_INT 核对 - -批 A 已使用 `W_INT = sizeof(int)`,没有使用 `NBYTES_INT`。collective 和 -reduction 的定义处均已有注释,说明其是 native `int` 的 byte 数,因此本批 -无需再改名。 - -## 3. 跳过项 - -- 未发现因 develop merge 而消失、需要单独跳过的 B 类符号。 -- C 批的数值返回类型/API 项(`real_type`、`abs2`、`inv` 数值告警等)按用户 - 要求未做。 -- 工作树中未找到 `THOROUGH_review_plan.md`;本批依据用户消息中的 B 类清单、 - 拍板项和只读 GitHub 审阅评论上下文执行,没有据此遗漏列表中的 B 类条目。 - -## 4. 验证 - -所有构建和测试均在 `module load abacus-dev/1.0` 后执行。 - -- `cmake --build build-matrix2d-cxx11 --target base -j2` - - 退出码 0;编译命令为 `-std=gnu++11`。 -- `cmake --build build-matrix2d-mpi-cxx11 --target base -j2` - - 退出码 0;编译命令为 `-std=gnu++11`。 -- `cmake --build build-matrix2d-serial --target MODULE_BASE_matrix2d MODULE_BASE_matrix2d_linalg -j2` - - 退出码 0。 -- `cmake --build build-matrix2d-mpi --target MODULE_BASE_matrix2d MODULE_BASE_matrix2d_linalg -j2` - - 退出码 0。 -- `OMP_NUM_THREADS=1 ctest --test-dir build-matrix2d-serial --output-on-failure -R 'MODULE_BASE_matrix2d'` - - 退出码 0,2/2 通过。 -- `OMP_NUM_THREADS=1 ctest --test-dir build-matrix2d-mpi --output-on-failure -R 'MODULE_BASE_matrix2d'` - - 退出码 0,6/6 通过;包含 serial 2 项及 MPI 2-rank/4-rank 各 2 项。 -- OMP 防竞争复跑使用 `OMP_NUM_THREADS=2`: - - serial 2/2 通过。 - - MPI 6/6 通过。 -- `git diff --check` - - 退出码 0。 -- `python3 tools/03_code_analysis/agent_governance_check.py --staged --format text` - - 退出码 0;仅保留 `matrix2d_mpi.h` 的直接 include 警告和本地无 PR body 的 - documentation-sync 警告。 -- `agent_governance_check.py --base fbaf69833 --head 0ac210ae3` - - 退出码 0,无 blocker;warning 同上。 -- `code_quality_score.py` 扫描 17 个改动 C++ 文件,15/17 达到 60 分。 - - 未达线历史结构项为既有 612 行 `scalapack_connector.h` 和 1612 行 - `test_matrix2d.cpp`;其问题是文件规模等既有债务,不是新增确定性错误。 - -## 5. Commit - -- B 类实现 commit:`0ac210ae3` - - `refactor(base): address review structure/MPI/OMP findings (part B)` -- 本结果文件使用紧随其后的独立 docs commit 记录。 - -## 6. 工作树 - -报告提交后工作树干净;未 push、未修改 auto-merge、未回复 PR thread。 From 5085c5811297fc84d62dbe0bf05080b3684a4f34 Mon Sep 17 00:00:00 2001 From: kirk0830 Date: Mon, 23 Nov 2026 10:28:06 +0800 Subject: [PATCH 13/15] fix(build): keep __MPI in Matrix2d unit test targets --- source/source_base/unittests/CMakeLists.txt | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/source/source_base/unittests/CMakeLists.txt b/source/source_base/unittests/CMakeLists.txt index 92f9b0c417d..2e0fdfaa17e 100644 --- a/source/source_base/unittests/CMakeLists.txt +++ b/source/source_base/unittests/CMakeLists.txt @@ -16,12 +16,14 @@ 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( @@ -32,6 +34,21 @@ set_tests_properties( ) 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 From 5ebd75f65ef4cd56ff931ea5be25ce788eaf5146 Mon Sep 17 00:00:00 2001 From: kirk0830 Date: Mon, 23 Nov 2026 18:49:25 +0800 Subject: [PATCH 14/15] fix(base): address bot review on numeric precision and overlap contract --- source/source_base/matrix2d_collective.cpp | 10 ++++- source/source_base/matrix2d_linalg.h | 12 ++++-- source/source_base/matrix2d_reduction.cpp | 41 +++++++++---------- .../source_base/unittests/test_matrix2d.cpp | 18 ++++++++ .../unittests/test_matrix2d_linalg.cpp | 20 +++++++++ 5 files changed, 74 insertions(+), 27 deletions(-) diff --git a/source/source_base/matrix2d_collective.cpp b/source/source_base/matrix2d_collective.cpp index b8508dd7563..decf0bd4fd4 100644 --- a/source/source_base/matrix2d_collective.cpp +++ b/source/source_base/matrix2d_collective.cpp @@ -144,7 +144,10 @@ void pack_rank_values(const Matrix2d& matglb, * static_cast(view.ncloc) + static_cast(icloc); const T& value = matglb.atloc(irglb, icglb); - std::memcpy(destination + idx * sizeof(T), &value, sizeof(T)); + 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)); } } } @@ -267,8 +270,11 @@ Matrix2d rebuild_global( = 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, view.data + idx * sizeof(T), sizeof(T)); + std::memcpy(&value, source, sizeof(T)); result.atloc(irglb, icglb) = value; } } diff --git a/source/source_base/matrix2d_linalg.h b/source/source_base/matrix2d_linalg.h index 4ced1eb00a6..5eb7c64b9d9 100644 --- a/source/source_base/matrix2d_linalg.h +++ b/source/source_base/matrix2d_linalg.h @@ -27,8 +27,9 @@ void solve(Matrix2dView> matrix, /** * @brief Multiply two matrix views into result. * - * The result view must not overlap either input view. The host implementation - * writes result while still reading left and right. + * 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. */ void matmul(Matrix2dView result, Matrix2dView left, @@ -44,8 +45,11 @@ void matmul(Matrix2dView> result, * @brief Compute `result = alpha * left + beta * right`. * * All views must have the same global shape and compatible host or distributed - * layouts. The result may overlap either input because each element is read - * before it is written. + * 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. */ void axpby(Matrix2dView result, const double alpha, diff --git a/source/source_base/matrix2d_reduction.cpp b/source/source_base/matrix2d_reduction.cpp index 718046e71e6..5e17ec5512c 100644 --- a/source/source_base/matrix2d_reduction.cpp +++ b/source/source_base/matrix2d_reduction.cpp @@ -42,32 +42,33 @@ std::complex conj(const std::complex& value) } // namespace elementwise template -real_type abs2(const T& value) +double abs2(const T& value) { - const real_type real_value = static_cast>(value); + const double real_value = static_cast(value); return real_value * real_value; } template -real_type> abs2(const std::complex& value) +double abs2(const std::complex& value) { - using Real = real_type>; - const Real real = static_cast(value.real()); - const Real imag = static_cast(value.imag()); + const double real = static_cast(value.real()); + const double imag = static_cast(value.imag()); return real * real + imag * imag; } template -real_type absolute_value(const T& value) +double absolute_value(const T& value) { - const real_type widened_value = static_cast>(value); + const double widened_value = static_cast(value); return std::abs(widened_value); } template -real_type> absolute_value(const std::complex& value) +double absolute_value(const std::complex& value) { - return static_cast>>(std::abs(value)); + const double real = static_cast(value.real()); + const double imag = static_cast(value.imag()); + return std::hypot(real, imag); } template @@ -91,7 +92,7 @@ void reduce_sum_over_processes(Value& value, const Matrix2d& matrix) } template -void reduce_max_over_processes(real_type& value, const Matrix2d& matrix) +void reduce_max_over_processes(double& value, const Matrix2d& matrix) { #ifdef __MPI const std::shared_ptr distrib @@ -101,11 +102,7 @@ void reduce_max_over_processes(real_type& value, const Matrix2d& matrix) const MPI_Comm comm = distrib->comm(); if (comm != MPI_COMM_NULL) { - // The guarded wrapper currently exposes only double. Widening the - // collective value does not change the maximum or the public type. - double collective_value = value; - Parallel_Common::allreduce_max(collective_value, comm); - value = static_cast>(collective_value); + Parallel_Common::allreduce_max(value, comm); } } #else @@ -158,7 +155,7 @@ T sum(const Matrix2d& matrix) template real_type norm(const Matrix2d& matrix) { - real_type value = real_type(); + double value = 0.0; const int nrloc = matrix.nrloc(); const int ncloc = matrix.ncloc(); #ifdef _OPENMP @@ -173,7 +170,8 @@ real_type norm(const Matrix2d& matrix) } } reduce_sum_over_processes(value, matrix); - return std::sqrt(value); + const real_type result = static_cast>(std::sqrt(value)); + return result; } template @@ -218,7 +216,7 @@ T dot(const Matrix2d& left, const Matrix2d& right) template real_type max_abs(const Matrix2d& matrix) { - real_type max_value = real_type(); + double max_value = 0.0; const int nrloc = matrix.nrloc(); const int ncloc = matrix.ncloc(); #ifdef _OPENMP @@ -229,12 +227,13 @@ real_type max_abs(const Matrix2d& matrix) for (int j = 0; j < ncloc; ++j) { const T& element = matrix.atloc(i, j); - const real_type element_abs = absolute_value(element); + const double element_abs = absolute_value(element); max_value = std::max(max_value, element_abs); } } reduce_max_over_processes(max_value, matrix); - return max_value; + const real_type result = static_cast>(max_value); + return result; } template diff --git a/source/source_base/unittests/test_matrix2d.cpp b/source/source_base/unittests/test_matrix2d.cpp index 07837d783fb..76375c217ae 100644 --- a/source/source_base/unittests/test_matrix2d.cpp +++ b/source/source_base/unittests/test_matrix2d.cpp @@ -596,6 +596,18 @@ void check_reduction_scalar_type(const T& first, 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) { @@ -1459,6 +1471,8 @@ 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); @@ -1474,6 +1488,10 @@ TEST(Matrix2dTest, ReductionsUseTheMatrixRealType) 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) diff --git a/source/source_base/unittests/test_matrix2d_linalg.cpp b/source/source_base/unittests/test_matrix2d_linalg.cpp index d114820852b..f732bed2cb2 100644 --- a/source/source_base/unittests/test_matrix2d_linalg.cpp +++ b/source/source_base/unittests/test_matrix2d_linalg.cpp @@ -385,6 +385,26 @@ TEST(Matrix2dLinalgTest, HostViewMatmulAndAxpby) } 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(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(combined.view(), 3.0); matrix2d_linalg::set_identity(product.view()); const Matrix2d generated_identity From 664c8df94b051b71271941572f0edb08e218a14c Mon Sep 17 00:00:00 2001 From: kirk0830 Date: Mon, 23 Nov 2026 23:20:59 +0800 Subject: [PATCH 15/15] feat(base): add numpy-style Matrix2d linalg overloads --- source/source_base/matrix2d_linalg.cpp | 281 +++++++++++- source/source_base/matrix2d_linalg.h | 225 ++++++++-- .../unittests/test_matrix2d_linalg.cpp | 420 ++++++++++++++---- 3 files changed, 781 insertions(+), 145 deletions(-) diff --git a/source/source_base/matrix2d_linalg.cpp b/source/source_base/matrix2d_linalg.cpp index 2877544aca0..76723ea0e21 100644 --- a/source/source_base/matrix2d_linalg.cpp +++ b/source/source_base/matrix2d_linalg.cpp @@ -10,6 +10,7 @@ #include #include #include +#include namespace { @@ -258,11 +259,51 @@ void assert_solve_views(const Matrix2dView>& matrix, "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(Matrix2dView matrix) +void inv_inplace(Matrix2dView matrix) { assert_inverse_view(matrix); if (distribution_is_active(matrix)) @@ -277,7 +318,7 @@ void inv(Matrix2dView matrix) matrix2d_impl::lapack::inv(matrix); } -void inv(Matrix2dView> matrix) +void inv_inplace(Matrix2dView> matrix) { assert_inverse_view(matrix); if (distribution_is_active(matrix)) @@ -292,8 +333,8 @@ void inv(Matrix2dView> matrix) matrix2d_impl::lapack::inv(matrix); } -void solve(Matrix2dView matrix, - Matrix2dView rhs) +void solve_inplace(Matrix2dView matrix, + Matrix2dView rhs) { assert_solve_views(matrix, rhs); if (distribution_is_active(matrix)) @@ -308,8 +349,8 @@ void solve(Matrix2dView matrix, matrix2d_impl::lapack::solve(matrix, rhs); } -void solve(Matrix2dView> matrix, - Matrix2dView> rhs) +void solve_inplace(Matrix2dView> matrix, + Matrix2dView> rhs) { assert_solve_views(matrix, rhs); if (distribution_is_active(matrix)) @@ -324,9 +365,9 @@ void solve(Matrix2dView> matrix, matrix2d_impl::lapack::solve(matrix, rhs); } -void matmul(Matrix2dView result, - Matrix2dView left, - Matrix2dView right) +void matmul_inplace(Matrix2dView result, + Matrix2dView left, + Matrix2dView right) { assert_matmul_views(result, left, right); if (distribution_is_active(result)) @@ -341,9 +382,9 @@ void matmul(Matrix2dView result, matmul_host(result, left, right); } -void matmul(Matrix2dView> result, - Matrix2dView> left, - Matrix2dView> right) +void matmul_inplace(Matrix2dView> result, + Matrix2dView> left, + Matrix2dView> right) { assert_matmul_views(result, left, right); if (distribution_is_active(result)) @@ -358,16 +399,16 @@ void matmul(Matrix2dView> result, matmul_host(result, left, right); } -void axpby(Matrix2dView result, - const double alpha, - Matrix2dView left, - const double beta, - Matrix2dView 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( +void axpby_inplace( Matrix2dView> result, const std::complex alpha, Matrix2dView> left, @@ -377,27 +418,132 @@ void axpby( axpby_impl(result, alpha, left, beta, right); } -void scale(Matrix2dView matrix, const double factor) +void scale_inplace(Matrix2dView matrix, const double factor) { scale_impl(matrix, factor); } -void scale(Matrix2dView> matrix, - const std::complex factor) +void scale_inplace(Matrix2dView> matrix, + const std::complex factor) { scale_impl(matrix, factor); } -void set_identity(Matrix2dView matrix) +void set_identity_inplace(Matrix2dView matrix) { set_identity_impl(matrix); } -void set_identity(Matrix2dView> 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) { @@ -405,10 +551,97 @@ Matrix2d eye(const int n) || std::is_same>::value, "eye supports double and std::complex"); Matrix2d matrix(n, n); - set_identity_impl(matrix.view()); + 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 index 5eb7c64b9d9..02393e913ff 100644 --- a/source/source_base/matrix2d_linalg.h +++ b/source/source_base/matrix2d_linalg.h @@ -9,20 +9,119 @@ namespace matrix2d_linalg { /** - * @brief Invert a square matrix in place using an explicit matrix inverse. + * 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`. */ -void inv(Matrix2dView matrix); -/** @copydoc inv(Matrix2dView) */ -void inv(Matrix2dView> matrix); +template +void solve(const Matrix2d& matrix, + const Matrix2d& rhs, + Matrix2d& solution); -void solve(Matrix2dView matrix, - Matrix2dView rhs); -void solve(Matrix2dView> matrix, - Matrix2dView> rhs); +/** + * @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. @@ -30,19 +129,51 @@ void solve(Matrix2dView> matrix, * 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(Matrix2dView result, - Matrix2dView left, - Matrix2dView right); +void matmul_inplace(Matrix2dView result, + Matrix2dView left, + Matrix2dView right); +/** + * @copydoc matmul_inplace(Matrix2dView,Matrix2dView,Matrix2dView) + */ +void matmul_inplace(Matrix2dView> result, + Matrix2dView> left, + Matrix2dView> right); + /** - * @copydoc matmul(Matrix2dView,Matrix2dView,Matrix2dView) + * @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`. */ -void matmul(Matrix2dView> result, - Matrix2dView> left, - Matrix2dView> right); +template +Matrix2d axpby(const T alpha, + const Matrix2d& left, + const T beta, + const Matrix2d& right); /** - * @brief Compute `result = alpha * left + beta * 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 @@ -50,45 +181,75 @@ void matmul(Matrix2dView> result, * 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(Matrix2dView result, - const double alpha, - Matrix2dView left, - const double beta, - Matrix2dView right); +void axpby_inplace(Matrix2dView result, + const double alpha, + Matrix2dView left, + const double beta, + Matrix2dView right); /** - * @copydoc axpby(Matrix2dView,double,Matrix2dView,double,Matrix2dView) + * @copydoc axpby_inplace(Matrix2dView,double,Matrix2dView,double,Matrix2dView) */ -void axpby( +void axpby_inplace( Matrix2dView> result, const std::complex alpha, Matrix2dView> left, const std::complex beta, Matrix2dView> right); -void scale(Matrix2dView matrix, const double factor); -void scale(Matrix2dView> matrix, - const std::complex factor); +/** @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. * - * This operation mutates `matrix` in place and does not allocate a new matrix. + * @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(Matrix2dView matrix); -/** @copydoc set_identity(Matrix2dView) */ -void set_identity(Matrix2dView> matrix); +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()` when an existing - * view should be overwritten in place. + * 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/unittests/test_matrix2d_linalg.cpp b/source/source_base/unittests/test_matrix2d_linalg.cpp index f732bed2cb2..384546d8bcc 100644 --- a/source/source_base/unittests/test_matrix2d_linalg.cpp +++ b/source/source_base/unittests/test_matrix2d_linalg.cpp @@ -11,6 +11,7 @@ #include #include #include +#include #include #include @@ -43,6 +44,81 @@ void expect_host_matrices_near(const Matrix2d& actual, } } +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); @@ -53,6 +129,16 @@ Matrix2d make_real_system() 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); @@ -192,6 +278,19 @@ Matrix2d> make_distributed_complex_solution( 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, @@ -211,24 +310,42 @@ void check_distributed_solve(const Matrix2d& host_matrix, host_solution.ncglb(), nrblk, matrix.ictxt()); - const std::shared_ptr rhs_distrib - = make_borrowed_distribution(host_rhs.nrglb(), - host_rhs.ncglb(), - nrblk, - matrix.ictxt()); Matrix2d solution(solution_distrib); - Matrix2d rhs(rhs_distrib); matrix.scatter(host_matrix); solution.scatter(host_solution); const Matrix2d& matrix_input = matrix; const Matrix2d& solution_input = solution; - matrix2d_linalg::matmul(rhs.view(), - matrix_input.view(), - solution_input.view()); - - matrix2d_linalg::solve(matrix.view(), rhs.view()); - - expect_host_matrices_near(rhs.gather(), host_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 @@ -237,8 +354,9 @@ void check_distributed_inverse(const Matrix2d& host_matrix, const int ncproc, const int nrblk) { - Matrix2d expected = host_matrix; - matrix2d_linalg::inv(expected.view()); + 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(), @@ -247,28 +365,108 @@ void check_distributed_inverse(const Matrix2d& host_matrix, nrblk, MPI_COMM_WORLD); matrix.scatter(host_matrix); - matrix2d_linalg::inv(matrix.view()); - - expect_host_matrices_near(matrix.gather(), expected); + 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) { - Matrix2d inverse = make_real_system(); - matrix2d_linalg::inv(inverse.view()); - expect_host_matrices_near(inverse, make_real_inverse_reference()); + 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 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; - const Matrix2d expected = make_real_inverse_reference().matmul(rhs); - Matrix2d matrix = make_real_system(); - matrix2d_linalg::solve(matrix.view(), rhs.view()); - expect_host_matrices_near(rhs, expected); + 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) @@ -276,46 +474,53 @@ 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(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(real_identity_view); - const Matrix2d real_product = real_matrix.matmul(real_inverse); + 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(); - Matrix2d> complex_inverse = complex_matrix; - Matrix2dView> complex_inverse_view - = complex_inverse.view(); - matrix2d_linalg::inv(complex_inverse_view); - Matrix2d> complex_identity(2, 2); - Matrix2dView> complex_identity_view - = complex_identity.view(); - matrix2d_linalg::set_identity(complex_identity_view); + const Matrix2d> complex_inverse + = matrix2d_linalg::inv(complex_matrix); + const Matrix2d> complex_identity + = matrix2d_linalg::eye>(2); const Matrix2d> complex_product - = complex_matrix.matmul(complex_inverse); + = matrix2d_linalg::matmul(complex_matrix, complex_inverse); expect_host_matrices_near(complex_product, complex_identity); } TEST(Matrix2dLinalgTest, HostComplexSolve) { - Matrix2d> matrix = make_complex_system(); + const Matrix2d> matrix = make_complex_system(); + const Matrix2d> matrix_original = matrix; const Matrix2d> expected = make_complex_solution(); - Matrix2d> rhs = matrix.matmul(expected); - - matrix2d_linalg::solve(matrix.view(), rhs.view()); - - expect_host_matrices_near(rhs, expected); - - Matrix2d> inverse = make_complex_system(); - matrix2d_linalg::inv(inverse.view()); + 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) @@ -328,24 +533,33 @@ TEST(Matrix2dLinalgTest, SerialDistributionUsesLocalBackend) 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 expected = make_real_inverse_reference().matmul(rhs); - - matrix2d_linalg::solve(matrix.view(), rhs.view()); - expect_host_matrices_near(rhs, expected); - - Matrix2d inverse(distrib); - inverse.atloc(0, 0) = 4.0; - inverse.atloc(0, 1) = 1.0; - inverse.atloc(1, 0) = 2.0; - inverse.atloc(1, 1) = 3.0; - matrix2d_linalg::inv(inverse.view()); - expect_host_matrices_near(inverse, make_real_inverse_reference()); + 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) @@ -355,7 +569,7 @@ TEST(Matrix2dLinalgTest, ExternalBufferViewDoesNotCopy) Matrix2d rhs(2, 1); rhs.atloc(0, 0) = 1.0; rhs.atloc(1, 0) = 2.0; - matrix2d_linalg::solve(matrix, rhs.view()); + matrix2d_linalg::solve_inplace(matrix, rhs.view()); expect_near(rhs.atloc(0, 0), 0.1); expect_near(rhs.atloc(1, 0), 0.6); @@ -367,11 +581,13 @@ TEST(Matrix2dLinalgTest, HostViewMatmulAndAxpby) const Matrix2d left = make_real_system(); const Matrix2d right = make_real_inverse_reference(); Matrix2d product(2, 2); - matrix2d_linalg::matmul(product.view(), left.view(), right.view()); + 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( + 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) @@ -388,11 +604,11 @@ TEST(Matrix2dLinalgTest, HostViewMatmulAndAxpby) Matrix2d in_place = left; const Matrix2d in_place_original = in_place; const Matrix2d& in_place_input = in_place; - matrix2d_linalg::axpby(in_place.view(), - 2.0, - in_place_input.view(), - -0.5, - right.view()); + 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) { @@ -405,8 +621,8 @@ TEST(Matrix2dLinalgTest, HostViewMatmulAndAxpby) } expect_host_matrices_near(in_place, in_place_reference); - matrix2d_linalg::scale(combined.view(), 3.0); - matrix2d_linalg::set_identity(product.view()); + 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 @@ -434,11 +650,13 @@ TEST(Matrix2dLinalgTest, RejectsSingularAndMismatchedMatrices) singular.atloc(0, 1) = 2.0; singular.atloc(1, 0) = 2.0; singular.atloc(1, 1) = 4.0; - EXPECT_THROW(matrix2d_linalg::inv(singular.view()), std::runtime_error); + EXPECT_THROW(matrix2d_linalg::inv(singular), std::runtime_error); + EXPECT_THROW(matrix2d_linalg::inv_inplace(singular.view()), + std::runtime_error); - Matrix2d matrix = make_real_system(); - Matrix2d wrong_rhs(1, 1); - EXPECT_THROW(matrix2d_linalg::solve(matrix.view(), wrong_rhs.view()), + const Matrix2d matrix = make_real_system(); + const Matrix2d wrong_rhs(1, 1); + EXPECT_THROW(matrix2d_linalg::solve(matrix, wrong_rhs), std::invalid_argument); } @@ -452,11 +670,11 @@ TEST(Matrix2dLinalgTest, RejectsSerialDistributionAgainstHostLayout) ASSERT_TRUE(distributed.has_distribution()); ASSERT_FALSE(distributed.is_active()); EXPECT_THROW( - matrix2d_linalg::axpby(host.view(), - 1.0, - distributed.view(), - 0.0, - host.view()), + matrix2d_linalg::axpby_inplace(host.view(), + 1.0, + distributed.view(), + 0.0, + host.view()), std::invalid_argument); } @@ -531,21 +749,38 @@ TEST(Matrix2dLinalgTest, DistributedIdentityAndAxpby) grids[igrid].second, nrblks[iblk], MPI_COMM_WORLD); - matrix2d_linalg::set_identity(identity.view()); + matrix2d_linalg::set_identity_inplace(identity.view()); Matrix2d identity_expected(size, size); - matrix2d_linalg::set_identity(identity_expected.view()); + 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()); - Matrix2d combined(identity.distribution()); left.scatter(host_left); - matrix2d_linalg::axpby(combined.view(), - 2.0, - left.view(), + 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.view()); + 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) @@ -553,9 +788,16 @@ TEST(Matrix2dLinalgTest, DistributedIdentityAndAxpby) 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); } } }