diff --git a/source/Makefile.Objects b/source/Makefile.Objects index 502f29b9e05..8d0f34a6af5 100644 --- a/source/Makefile.Objects +++ b/source/Makefile.Objects @@ -515,6 +515,10 @@ OBJS_HSOLVER=diago_cg.o\ diago_david.o\ diago_dav_subspace.o\ diago_bpcg.o\ + diago_lobpcg.o\ + lobpcg_subspace.o\ + lobpcg_recovery.o\ + dense_eigensolver.o\ para_lin_tf.o\ hsolver.o\ hsolver_pw.o\ diff --git a/source/source_base/CMakeLists.txt b/source/source_base/CMakeLists.txt index 8098e18da3f..7bccf581f83 100644 --- a/source/source_base/CMakeLists.txt +++ b/source/source_base/CMakeLists.txt @@ -127,6 +127,7 @@ if(BUILD_TESTING) ) add_subdirectory(unittests) add_subdirectory(test) + target_sources(MODULE_BASE_timer PRIVATE unittests/test_timer.cpp) add_subdirectory(test_parallel) add_subdirectory(kernels/test) add_subdirectory(module_mixing/test) diff --git a/source/source_base/kernels/cuda/math_kernel_op.cu b/source/source_base/kernels/cuda/math_kernel_op.cu index 35bd5af02b9..c803bae997b 100644 --- a/source/source_base/kernels/cuda/math_kernel_op.cu +++ b/source/source_base/kernels/cuda/math_kernel_op.cu @@ -217,6 +217,51 @@ void gemv_op, base_device::DEVICE_GPU>::operator()(const ch CHECK_CUBLAS(cublasZgemv(cublas_handle, cutrans, m, n, &alpha, (cuDoubleComplex*)A, lda, (cuDoubleComplex*)X, incx, &beta, (cuDoubleComplex*)Y, incy)); } + +template <> +void trmm_op, base_device::DEVICE_GPU>::operator()( + const char& side, const char& uplo, const char& trans, const char& diag, + const int& m, const int& n, const std::complex* alpha, + const std::complex* a, const int& lda, std::complex* b, const int& ldb) +{ + if (m == 0 || n == 0) + { + return; + } + const cublasSideMode_t gpu_side = side == 'L' ? CUBLAS_SIDE_LEFT : CUBLAS_SIDE_RIGHT; + const cublasFillMode_t gpu_uplo = uplo == 'U' ? CUBLAS_FILL_MODE_UPPER : CUBLAS_FILL_MODE_LOWER; + const cublasOperation_t gpu_trans = GetCublasOperation(trans, true); + const cublasDiagType_t gpu_diag = diag == 'U' ? CUBLAS_DIAG_UNIT : CUBLAS_DIAG_NON_UNIT; + const cuComplex gpu_alpha = make_cuComplex(alpha->real(), alpha->imag()); + const cuComplex* gpu_a = reinterpret_cast(a); + cuComplex* gpu_b = reinterpret_cast(b); + // TRMM permits identical input/output B with the same leading dimension. + CHECK_CUBLAS(cublasCtrmm(cublas_handle, gpu_side, gpu_uplo, gpu_trans, gpu_diag, + m, n, &gpu_alpha, gpu_a, lda, gpu_b, ldb, gpu_b, ldb)); +} + +template <> +void trmm_op, base_device::DEVICE_GPU>::operator()( + const char& side, const char& uplo, const char& trans, const char& diag, + const int& m, const int& n, const std::complex* alpha, + const std::complex* a, const int& lda, std::complex* b, const int& ldb) +{ + if (m == 0 || n == 0) + { + return; + } + const cublasSideMode_t gpu_side = side == 'L' ? CUBLAS_SIDE_LEFT : CUBLAS_SIDE_RIGHT; + const cublasFillMode_t gpu_uplo = uplo == 'U' ? CUBLAS_FILL_MODE_UPPER : CUBLAS_FILL_MODE_LOWER; + const cublasOperation_t gpu_trans = GetCublasOperation(trans, true); + const cublasDiagType_t gpu_diag = diag == 'U' ? CUBLAS_DIAG_UNIT : CUBLAS_DIAG_NON_UNIT; + const cuDoubleComplex gpu_alpha = make_cuDoubleComplex(alpha->real(), alpha->imag()); + const cuDoubleComplex* gpu_a = reinterpret_cast(a); + cuDoubleComplex* gpu_b = reinterpret_cast(b); + // TRMM permits identical input/output B with the same leading dimension. + CHECK_CUBLAS(cublasZtrmm(cublas_handle, gpu_side, gpu_uplo, gpu_trans, gpu_diag, + m, n, &gpu_alpha, gpu_a, lda, gpu_b, ldb, gpu_b, ldb)); +} + template <> void gemm_op::operator()(const char& transa, const char& transb, diff --git a/source/source_base/kernels/math_kernel_op.cpp b/source/source_base/kernels/math_kernel_op.cpp index 307da6c65d8..47692e1ead8 100644 --- a/source/source_base/kernels/math_kernel_op.cpp +++ b/source/source_base/kernels/math_kernel_op.cpp @@ -7,6 +7,43 @@ namespace ModuleBase { +template <> +void trmm_op, base_device::DEVICE_CPU>::operator()( + const char& side, const char& uplo, const char& trans, const char& diag, + const int& m, const int& n, const std::complex* alpha, + const std::complex* a, const int& lda, std::complex* b, const int& ldb) +{ + if (m == 0 || n == 0) + { + return; + } + ctrmm_(&side, &uplo, &trans, &diag, &m, &n, alpha, a, &lda, b, &ldb); +} + +template <> +void trmm_op, base_device::DEVICE_CPU>::operator()( + const char& side, const char& uplo, const char& trans, const char& diag, + const int& m, const int& n, const std::complex* alpha, + const std::complex* a, const int& lda, std::complex* b, const int& ldb) +{ + if (m == 0 || n == 0) + { + return; + } + ztrmm_(&side, &uplo, &trans, &diag, &m, &n, alpha, a, &lda, b, &ldb); +} + + +void gram_herk_cpu(int ld, int dim, int bands, const std::complex* x, + std::complex* output) +{ + const char uplo = 'U'; + const char trans = 'C'; + const double one = 1.0; + const double zero = 0.0; + zherk_(&uplo, &trans, &bands, &dim, &one, x, &ld, &zero, output, &bands); +} + template struct gemv_op { diff --git a/source/source_base/kernels/math_kernel_op.h b/source/source_base/kernels/math_kernel_op.h index 4b9ca8e8ded..ef2b3615bbd 100644 --- a/source/source_base/kernels/math_kernel_op.h +++ b/source/source_base/kernels/math_kernel_op.h @@ -17,6 +17,14 @@ namespace ModuleBase { +/** Compute the upper triangle of column-major X^H X in double precision. + * X has dim valid rows, bands columns and leading dimension ld. Output has + * leading dimension bands; its lower triangle is not read or written. + * Pointers belong to CPU. The caller completes the Hermitian matrix. + */ +void gram_herk_cpu(int ld, int dim, int bands, const std::complex* x, + std::complex* output); + //--------------------------------------------------------------------------------- //-----------------------------0. Tool Functions----------------------------------- //--------------------------------------------------------------------------------- @@ -267,6 +275,25 @@ template struct gemv_op { const int &incy); }; +template struct trmm_op +{ + /// @brief In-place column-major B = alpha*op(A)*B or B = alpha*B*op(A). + /// @param side 'L' for left multiplication, 'R' for right multiplication. + /// @param uplo Stored triangle of A: 'U' or 'L'. + /// @param trans Operation on A: 'N', 'T' or 'C'. + /// @param diag 'U' for an implicit unit diagonal, 'N' for an explicit diagonal. + /// @param m Number of rows of B. + /// @param n Number of columns of B. + /// @param alpha Host scalar multiplying the product. + /// @param a Triangular matrix on Device, stored separately from B. + /// @param lda Leading dimension of A, whose order is m (left) or n (right). + /// @param b Input/output matrix on Device; row padding is preserved. + /// @param ldb Leading dimension of B. Empty matrices are no-ops. + void operator()(const char& side, const char& uplo, const char& trans, const char& diag, + const int& m, const int& n, const T* alpha, const T* a, const int& lda, + T* b, const int& ldb); +}; + // compute C = alpha * op(A) * op(B) + beta * C template struct gemm_op { /// @brief C = alpha * op(A) * op(B) + beta * C diff --git a/source/source_base/kernels/rocm/math_kernel_op.hip.cu b/source/source_base/kernels/rocm/math_kernel_op.hip.cu index 94ac05b0caa..2d6f471b3c9 100644 --- a/source/source_base/kernels/rocm/math_kernel_op.hip.cu +++ b/source/source_base/kernels/rocm/math_kernel_op.hip.cu @@ -224,6 +224,51 @@ void gemv_op, base_device::DEVICE_GPU>::operator()(const ch hipblasErrcheck(hipblasZgemv(cublas_handle, cutrans, m, n, (hipblasDoubleComplex*)alpha, (hipblasDoubleComplex*)A, lda, (hipblasDoubleComplex*)X, incx, (hipblasDoubleComplex*)beta, (hipblasDoubleComplex*)Y, incy)); } + +template <> +void trmm_op, base_device::DEVICE_GPU>::operator()( + const char& side, const char& uplo, const char& trans, const char& diag, + const int& m, const int& n, const std::complex* alpha, + const std::complex* a, const int& lda, std::complex* b, const int& ldb) +{ + if (m == 0 || n == 0) + { + return; + } + const hipblasSideMode_t gpu_side = side == 'L' ? HIPBLAS_SIDE_LEFT : HIPBLAS_SIDE_RIGHT; + const hipblasFillMode_t gpu_uplo = uplo == 'U' ? HIPBLAS_FILL_MODE_UPPER : HIPBLAS_FILL_MODE_LOWER; + const hipblasOperation_t gpu_trans = judge_trans_op(true, trans, "trmm_op"); + const hipblasDiagType_t gpu_diag = diag == 'U' ? HIPBLAS_DIAG_UNIT : HIPBLAS_DIAG_NON_UNIT; + const hipblasComplex* gpu_alpha = reinterpret_cast(alpha); + const hipblasComplex* gpu_a = reinterpret_cast(a); + hipblasComplex* gpu_b = reinterpret_cast(b); + // TRMM permits identical input/output B with the same leading dimension. + hipblasErrcheck(hipblasCtrmm(cublas_handle, gpu_side, gpu_uplo, gpu_trans, gpu_diag, + m, n, gpu_alpha, gpu_a, lda, gpu_b, ldb, gpu_b, ldb)); +} + +template <> +void trmm_op, base_device::DEVICE_GPU>::operator()( + const char& side, const char& uplo, const char& trans, const char& diag, + const int& m, const int& n, const std::complex* alpha, + const std::complex* a, const int& lda, std::complex* b, const int& ldb) +{ + if (m == 0 || n == 0) + { + return; + } + const hipblasSideMode_t gpu_side = side == 'L' ? HIPBLAS_SIDE_LEFT : HIPBLAS_SIDE_RIGHT; + const hipblasFillMode_t gpu_uplo = uplo == 'U' ? HIPBLAS_FILL_MODE_UPPER : HIPBLAS_FILL_MODE_LOWER; + const hipblasOperation_t gpu_trans = judge_trans_op(true, trans, "trmm_op"); + const hipblasDiagType_t gpu_diag = diag == 'U' ? HIPBLAS_DIAG_UNIT : HIPBLAS_DIAG_NON_UNIT; + const hipblasDoubleComplex* gpu_alpha = reinterpret_cast(alpha); + const hipblasDoubleComplex* gpu_a = reinterpret_cast(a); + hipblasDoubleComplex* gpu_b = reinterpret_cast(b); + // TRMM permits identical input/output B with the same leading dimension. + hipblasErrcheck(hipblasZtrmm(cublas_handle, gpu_side, gpu_uplo, gpu_trans, gpu_diag, + m, n, gpu_alpha, gpu_a, lda, gpu_b, ldb, gpu_b, ldb)); +} + template <> void gemm_op::operator()(const char& transa, const char& transb, diff --git a/source/source_base/module_container/base/third_party/blas.h b/source/source_base/module_container/base/third_party/blas.h index 987f43ec3c7..5b2755c85ab 100644 --- a/source/source_base/module_container/base/third_party/blas.h +++ b/source/source_base/module_container/base/third_party/blas.h @@ -143,6 +143,16 @@ namespace container { // Usage example: BlasConnector::functionname(parameter list). namespace BlasConnector { +// Column-major triangular solve; B is overwritten by the solution. +static inline +void trsm(const char side, const char uplo, const char transa, const char diag, + const int m, const int n, const std::complex alpha, + const std::complex* a, const int lda, + std::complex* b, const int ldb) +{ + ztrsm_(&side, &uplo, &transa, &diag, &m, &n, &alpha, a, &lda, b, &ldb); +} + // Column-major rank-one update; preserve the supplied vector strides and leading dimension. static inline void ger(const int m, const int n, const double alpha, diff --git a/source/source_base/module_container/base/third_party/lapack.h b/source/source_base/module_container/base/third_party/lapack.h index 1bb3a25bebc..0f785d3fc5a 100644 --- a/source/source_base/module_container/base/third_party/lapack.h +++ b/source/source_base/module_container/base/third_party/lapack.h @@ -368,6 +368,22 @@ void hegvx(const int itype, const char jobz, const char range, const char uplo, } +// Return the computed eigenpair count through m. +static inline +void hegvx(const int itype, const char jobz, const char range, const char uplo, const int n, + std::complex* a, const int lda, std::complex* b, const int ldb, + const double vl, const double vu, const int il, const int iu, const double abstol, + int* m, double* w, std::complex* z, const int ldz, + std::complex* work, const int lwork, double* rwork, int* iwork, int* ifail, int& info) +{ + zhegvx_(&itype, &jobz, &range, &uplo, &n, + a, &lda, b, &ldb, + &vl, &vu, &il, &iu, + &abstol, m, w, z, &ldz, + work, &lwork, rwork, iwork, ifail, &info); +} + + // Column-major general eigenproblems; preserve the supplied workspace/query policy. static inline void geev(const char jobvl, const char jobvr, const int n, double* a, const int lda, diff --git a/source/source_base/module_external/blas_connector.h b/source/source_base/module_external/blas_connector.h index e78c4a00843..e28a6fa9ea6 100644 --- a/source/source_base/module_external/blas_connector.h +++ b/source/source_base/module_external/blas_connector.h @@ -82,6 +82,13 @@ void zgerc_(const int *m, const int *n, // Level 3 BLAS +void ctrmm_(const char* side, const char* uplo, const char* trans, const char* diag, + const int* m, const int* n, const std::complex* alpha, + const std::complex* a, const int* lda, std::complex* b, const int* ldb); +void ztrmm_(const char* side, const char* uplo, const char* trans, const char* diag, + const int* m, const int* n, const std::complex* alpha, + const std::complex* a, const int* lda, std::complex* b, const int* ldb); + void sgemm_(const char *transa, const char *transb, const int *m, const int *n, const int *k, const float *alpha, diff --git a/source/source_base/parallel_device.cpp b/source/source_base/parallel_device.cpp index 8ba8c3ae8ed..b5c56e8eece 100644 --- a/source/source_base/parallel_device.cpp +++ b/source/source_base/parallel_device.cpp @@ -322,6 +322,19 @@ void reduce_data(std::complex* object, const int& n, const MPI_Comm& com { MPI_Allreduce(MPI_IN_PLACE, object, n * 2, MPI_DOUBLE, MPI_SUM, comm); } +void reduce_data_to_root(std::complex* object, const int n, const MPI_Comm& comm, const int root) +{ + int rank = 0; + MPI_Comm_rank(comm, &rank); + if (rank == root) + { + MPI_Reduce(MPI_IN_PLACE, object, n, MPI_DOUBLE_COMPLEX, MPI_SUM, root, comm); + } + else + { + MPI_Reduce(object, nullptr, n, MPI_DOUBLE_COMPLEX, MPI_SUM, root, comm); + } +} void reduce_data(std::complex* object, const int& n, const MPI_Comm& comm) { MPI_Allreduce(MPI_IN_PLACE, object, n * 2, MPI_FLOAT, MPI_SUM, comm); diff --git a/source/source_base/parallel_device.h b/source/source_base/parallel_device.h index 7826e4b4653..af4665203ca 100644 --- a/source/source_base/parallel_device.h +++ b/source/source_base/parallel_device.h @@ -24,6 +24,8 @@ void bcast_data(std::complex* object, const int& n, const MPI_Comm& comm, void bcast_data(double* object, const int& n, const MPI_Comm& comm, int root = 0); void bcast_data(float* object, const int& n, const MPI_Comm& comm, int root = 0); void reduce_data(std::complex* object, const int& n, const MPI_Comm& comm); +// Sum host data into the same buffer on root. Non-root buffers are unchanged. +void reduce_data_to_root(std::complex* object, const int n, const MPI_Comm& comm, const int root); void reduce_data(std::complex* object, const int& n, const MPI_Comm& comm); void reduce_data(double* object, const int& n, const MPI_Comm& comm); void reduce_data(float* object, const int& n, const MPI_Comm& comm); diff --git a/source/source_base/timer.h b/source/source_base/timer.h index 9f49280c148..a34e9f50ebe 100644 --- a/source/source_base/timer.h +++ b/source/source_base/timer.h @@ -39,6 +39,28 @@ class timer static void start(const std::string &class_name_in, const std::string &name_in); static void end(const std::string &class_name_in, const std::string &name_in); + /** Function-wide timing, including early returns and exceptional exits. + * The borrowed names must outlive the scope. No device synchronization. + */ + class Scope + { + public: + Scope(const char* owner, const char* function) : owner_(owner), function_(function) + { + timer::start(owner_, function_); + } + ~Scope() + { + timer::end(owner_, function_); + } + Scope(const Scope&) = delete; + Scope& operator=(const Scope&) = delete; + + private: + const char* owner_; + const char* function_; + }; + /** * @brief Start total time calculation * diff --git a/source/source_base/unittests/test_timer.cpp b/source/source_base/unittests/test_timer.cpp new file mode 100644 index 00000000000..59b985fac37 --- /dev/null +++ b/source/source_base/unittests/test_timer.cpp @@ -0,0 +1,47 @@ +#include "source_base/timer.h" + +#include +#include + +namespace +{ +int timed_return(const bool early) +{ + ModuleBase::timer::Scope scope("TimerScopeTest", "timed_return"); + if (early) + { + return 1; + } + return 2; +} + +void timed_exception() +{ + ModuleBase::timer::Scope scope("TimerScopeTest", "timed_exception"); + throw std::runtime_error("test exception"); +} +} // namespace + +TEST(TimerScope, EarlyReturnClosesAndAllowsReuse) +{ + EXPECT_EQ(timed_return(true), 1); + const ModuleBase::timer::Timer_One& timer = ModuleBase::timer::timer_pool.at("TimerScopeTest").at("timed_return"); + EXPECT_TRUE(timer.start_flag); + EXPECT_EQ(timer.calls, 1U); + EXPECT_EQ(timed_return(false), 2); + EXPECT_TRUE(timer.start_flag); + EXPECT_EQ(timer.calls, 2U); + ModuleBase::timer::timer_pool.erase("TimerScopeTest"); +} + +TEST(TimerScope, ExceptionClosesAndAllowsReuse) +{ + EXPECT_THROW(timed_exception(), std::runtime_error); + const ModuleBase::timer::Timer_One& timer = ModuleBase::timer::timer_pool.at("TimerScopeTest").at("timed_exception"); + EXPECT_TRUE(timer.start_flag); + EXPECT_EQ(timer.calls, 1U); + EXPECT_THROW(timed_exception(), std::runtime_error); + EXPECT_TRUE(timer.start_flag); + EXPECT_EQ(timer.calls, 2U); + ModuleBase::timer::timer_pool.erase("TimerScopeTest"); +} diff --git a/source/source_esolver/esolver_ks_pw.cpp b/source/source_esolver/esolver_ks_pw.cpp index cfcf5b297af..f9569701f6d 100644 --- a/source/source_esolver/esolver_ks_pw.cpp +++ b/source/source_esolver/esolver_ks_pw.cpp @@ -271,7 +271,8 @@ void ESolver_KS_PW::hamilt2rho_single( PARAM.globalv.use_uspp, this->inp_->nspin, hsolver::DiagoIterAssist::SCF_ITER, hsolver::DiagoIterAssist::PW_DIAG_NMAX, hsolver::DiagoIterAssist::PW_DIAG_THR, hsolver::DiagoIterAssist::need_subspace, this->inp_->nbands, this->inp_->diago_smooth_ethr, - this->inp_->pw_diag_ndim, this->inp_->diag_subspace, this->inp_->nb2d, this->inp_->use_k_continuity); + this->inp_->pw_diag_ndim, this->inp_->lobpcg_extra_bands, this->inp_->lobpcg_locking, + this->inp_->diag_subspace, this->inp_->nb2d, this->inp_->use_k_continuity); // the iterative eigensolvers see the Hamiltonian only through this operator hamilt::HamiltHSOperator op(static_cast *>(this->p_hamilt), this->pw_wfc); diff --git a/source/source_esolver/esolver_sdft_pw.cpp b/source/source_esolver/esolver_sdft_pw.cpp index c0872d2e447..d45587e9c05 100644 --- a/source/source_esolver/esolver_sdft_pw.cpp +++ b/source/source_esolver/esolver_sdft_pw.cpp @@ -157,7 +157,8 @@ void ESolver_SDFT_PW::hamilt2rho_single( this->inp_->basis_type, this->inp_->ks_solver, PARAM.globalv.use_uspp, this->inp_->nspin, hsolver::DiagoIterAssist::SCF_ITER, hsolver::DiagoIterAssist::PW_DIAG_NMAX, hsolver::DiagoIterAssist::PW_DIAG_THR, hsolver::DiagoIterAssist::need_subspace, - this->inp_->nbands, this->inp_->diago_smooth_ethr, this->inp_->pw_diag_ndim, this->inp_->diag_subspace, + this->inp_->nbands, this->inp_->diago_smooth_ethr, this->inp_->pw_diag_ndim, this->inp_->lobpcg_extra_bands, + this->inp_->lobpcg_locking, this->inp_->diag_subspace, this->inp_->nb2d, PARAM.globalv.ks_run, PARAM.globalv.all_ks_run, this->inp_->bndpar); sto_hsolver_pw_obj.solve( diff --git a/source/source_estate/elecstate_print.cpp b/source/source_estate/elecstate_print.cpp index 4c4a2d9edf5..f129585164f 100644 --- a/source/source_estate/elecstate_print.cpp +++ b/source/source_estate/elecstate_print.cpp @@ -54,6 +54,7 @@ void print_scf_iterinfo(const std::string& ks_solver, {"elpa", "EL"}, {"dav", "DA"}, {"dav_subspace", "DS"}, + {"lobpcg", "LB"}, {"scalapack_gvx", "GV"}, {"cusolver", "CU"}, {"bpcg", "BP"}, diff --git a/source/source_hsolver/CMakeLists.txt b/source/source_hsolver/CMakeLists.txt index a415316e101..3019823e125 100644 --- a/source/source_hsolver/CMakeLists.txt +++ b/source/source_hsolver/CMakeLists.txt @@ -6,6 +6,10 @@ list( diago_david.cpp diago_dav_subspace.cpp diago_bpcg.cpp + diago_lobpcg.cpp + lobpcg_subspace.cpp + lobpcg_recovery.cpp + dense_eigensolver.cpp para_lin_tf.cpp hsolver_pw.cpp hsolver_lcaopw.cpp diff --git a/source/source_hsolver/dense_eigensolver.cpp b/source/source_hsolver/dense_eigensolver.cpp new file mode 100644 index 00000000000..fb99d8769fb --- /dev/null +++ b/source/source_hsolver/dense_eigensolver.cpp @@ -0,0 +1,701 @@ +#include "dense_eigensolver.h" +#include "source_base/memory_recorder.h" +#include "source_base/module_container/base/third_party/lapack.h" +#include "source_base/timer.h" +#ifdef __MPI +#include "source_base/module_external/blacs_connector.h" +#include "source_base/module_external/scalapack_connector.h" +#include "source_base/parallel_blkcyc.h" +#endif +#ifdef __CUDA +#include +#include +#endif +#include +#include +#include +#include +#include +#include +#include + +namespace hsolver +{ +namespace dense +{ +std::size_t SerialGvWorkspace::storage_bytes() const +{ + return h_.buffer().GetAllocatedBytes() + g_.buffer().GetAllocatedBytes() + work_.buffer().GetAllocatedBytes() + + real_work_.buffer().GetAllocatedBytes() + int_work_.capacity() * sizeof(int) + + failures_.capacity() * sizeof(int); +} + +int SerialGvWorkspace::solve( + const Wide* h, const Wide* g, const int dimension, const int wanted, double* values, Wide* vectors) +{ + ModuleBase::timer::Scope timer("SerialGvWorkspace", "solve"); + const int64_t square = static_cast(dimension) * dimension; + const int type = 1; + const char job = 'V'; + const char range = 'I'; + const char triangle = 'U'; + const double bound = 0; + const double tolerance = 0; + const int first = 1; + int found = 0; + int info = 0; + if (dimension > capacity_dimension_) + { + h_.resize({square}); + g_.resize({square}); + const int64_t real_work_size = static_cast(7) * dimension; + real_work_.resize({real_work_size}); + int_work_.resize(static_cast(5) * dimension); + failures_.resize(dimension); + const int query_size = -1; + Wide query(0); + ct::lapackConnector::hegvx(type, + job, + range, + triangle, + dimension, + h_.data(), + dimension, + g_.data(), + dimension, + bound, + bound, + first, + wanted, + tolerance, + &found, + values, + vectors, + dimension, + &query, + query_size, + real_work_.data(), + int_work_.data(), + failures_.data(), + info); + if (info != 0) + { + return info; + } + const double requested = query.real(); + if (!std::isfinite(requested) || requested > std::numeric_limits::max() || + dimension > std::numeric_limits::max() / 2) + { + return -1001; + } + work_size_ = std::max(2 * dimension, static_cast(requested)); + work_.resize({work_size_}); + capacity_dimension_ = dimension; + } + const std::size_t bytes = storage_bytes(); + ModuleBase::Memory::record("RR::serial_gv", bytes, false); + std::copy_n(h, square, h_.data()); + std::copy_n(g, square, g_.data()); + ct::lapackConnector::hegvx(type, + job, + range, + triangle, + dimension, + h_.data(), + dimension, + g_.data(), + dimension, + bound, + bound, + first, + wanted, + tolerance, + &found, + values, + vectors, + dimension, + work_.data(), + work_size_, + real_work_.data(), + int_work_.data(), + failures_.data(), + info); + if (info == 0 && found != wanted) + { + return -1002; + } + return info; +} + +#ifdef __MPI +namespace +{ +template +void grow_workspace(std::vector& buffer, const std::size_t count) +{ + if (count > buffer.size()) + { + buffer.resize(count); + } +} + +int checked_workspace_size(const double size) +{ + if (!std::isfinite(size) || size < 1 || size > std::numeric_limits::max()) + { + throw std::runtime_error("Invalid ScaLAPACK workspace size."); + } + return static_cast(std::ceil(size)); +} +class GvxWorkspace +{ + using T = std::complex; + using Real = double; + + public: + GvxWorkspace() = default; + GvxWorkspace(const GvxWorkspace&) = delete; + GvxWorkspace& operator=(const GvxWorkspace&) = delete; + + // A BLACS context integer may be recycled after rebinding a communicator. + void invalidate_layout() { bands_ = 0; } + + std::size_t storage_bytes() const; + + void solve(const int* desc, + const int nrow, + const int ncol, + const int nbands, + const T* h, + const T* s, + double* values, + T* vectors); + + private: + std::array descriptor_ = {}; + int bands_ = 0; + int lwork_ = 0; + int lrwork_base_ = 0; + int liwork_ = 0; + std::vector h_; + std::vector s_; + std::vector work_; + std::vector rwork_; + std::vector gap_; + std::vector iwork_; + std::vector ifail_; + std::vector iclustr_; +}; + +std::size_t GvxWorkspace::storage_bytes() const +{ + return sizeof(T) * (h_.capacity() + s_.capacity() + work_.capacity()) + + sizeof(Real) * (rwork_.capacity() + gap_.capacity()) + + sizeof(int) * (iwork_.capacity() + ifail_.capacity() + iclustr_.capacity()); +} + +void GvxWorkspace::solve( + const int* desc, const int nrow, const int ncol, const int nbands, const T* h, const T* s, Real* values, T* vectors) +{ + ModuleBase::timer::Scope timer("GvxWorkspace", "solve"); + ModuleBase::Memory::record("RR::gvx_work", 0, false); + int nprow = 1; + int npcol = 1; + int myprow = 0; + int mypcol = 0; + Cblacs_gridinfo(desc[1], &nprow, &npcol, &myprow, &mypcol); + const int n = desc[2]; + const int dsize = nprow * npcol; + const std::size_t local_size = static_cast(desc[8]) * ncol; + const std::size_t storage_size = std::max(1, local_size); + grow_workspace(h_, storage_size); + grow_workspace(s_, storage_size); + const int cluster_entries = 2 * dsize; + ifail_.resize(n); + iclustr_.resize(cluster_entries); + gap_.resize(dsize); + const char jobz = 'V'; + const char range = 'I'; + const char uplo = 'U'; + const int itype = 1; + const int one = 1; + const Real abstol = SCALAPACK_ABSTOL; + const Real orfac = SCALAPACK_ORFAC; + const Real zero = 0; + int m = 0; + int nz = 0; + int info = 0; + const bool new_query = bands_ != nbands || !std::equal(descriptor_.begin(), descriptor_.end(), desc); + if (new_query) + { + T work_query[3] = {}; + Real real_query[3] = {}; + int int_query[3] = {}; + int lwork = -1; + int lrwork = -1; + int liwork = -1; + pzhegvx_(&itype, + &jobz, + &range, + &uplo, + &n, + h_.data(), + &one, + &one, + desc, + s_.data(), + &one, + &one, + desc, + &zero, + &zero, + &one, + &nbands, + &abstol, + &m, + &nz, + values, + &orfac, + vectors, + &one, + &one, + desc, + work_query, + &lwork, + real_query, + &lrwork, + int_query, + &liwork, + ifail_.data(), + iclustr_.data(), + gap_.data(), + &info); + + if (info != 0) + { + throw std::runtime_error("ScaLAPACK GVX query: info=" + std::to_string(info)); + } + const double work_size = std::real(work_query[0]); + lwork_ = checked_workspace_size(work_size); + const double int_size = int_query[0]; + liwork_ = checked_workspace_size(int_size); + const double real_size = real_query[0]; + lrwork_base_ = checked_workspace_size(real_size); + const int work_storage = std::max(3, lwork_); + grow_workspace(work_, work_storage); + grow_workspace(iwork_, liwork_); + std::copy(desc, desc + 9, descriptor_.begin()); + bands_ = nbands; + } + + // PZHEGVX requires query RWORK plus (CLUSTERSIZE-1)*N for cluster + // reorthogonalization. Reserve the full N-eigenvalue cluster once. + // Restore this call's original inputs: GVX overwrites both matrices. + for (int j = 0; j < ncol; ++j) + { + for (int i = 0; i < nrow; ++i) + { + const std::size_t index = i + static_cast(j) * desc[8]; + h_[index] = h[index]; + s_[index] = s[index]; + } + } + const double real_size = lrwork_base_ + static_cast(n - 1) * n; + int lrwork = checked_workspace_size(real_size); + const int real_storage = std::max(3, lrwork); + grow_workspace(rwork_, real_storage); + const std::size_t bytes = storage_bytes(); + ModuleBase::Memory::record("RR::gvx_work", bytes, false); + pzhegvx_(&itype, + &jobz, + &range, + &uplo, + &n, + h_.data(), + &one, + &one, + desc, + s_.data(), + &one, + &one, + desc, + &zero, + &zero, + &one, + &nbands, + &abstol, + &m, + &nz, + values, + &orfac, + vectors, + &one, + &one, + desc, + work_.data(), + &lwork_, + rwork_.data(), + &lrwork, + iwork_.data(), + &liwork_, + ifail_.data(), + iclustr_.data(), + gap_.data(), + &info); + if (info != 0) + { + throw std::runtime_error("ScaLAPACK GVX failed: info=" + std::to_string(info)); + } + if (m != nbands || nz != nbands) + { + throw std::runtime_error("ScaLAPACK GVX returned an incomplete eigensystem."); + } +} + +} // namespace + +struct ParallelDenseEigensolver::Impl +{ + using Z = std::complex; + MPI_Comm communicator = MPI_COMM_NULL; + Parallel_Blkcyclic local; + Parallel_Blkcyclic root; + int dimension = 0; + int block = 0; + std::vector h; + std::vector s; + std::vector vectors; + GvxWorkspace gvx; + + void prepare(const int n, const int bands, const MPI_Comm& comm, const int block_size) + { + int nb = block_size; + if (nb == 0) + { + nb = bands > 500 ? 32 : 16; + } + // Each communicator handle gets its own BLACS grid. + if (comm != communicator || n != dimension || nb != block) + { + if (comm != communicator) + { + local.init(n, n, nb, comm, false); + communicator = comm; + gvx.invalidate_layout(); + } + else + { + local.set(n, n, nb, local.ictxt()); + } + root.set(n, n, n, local.ictxt()); + dimension = n; + block = nb; + } + const int columns = local.ncloc(); + const std::size_t elements = static_cast(local.desc()[8]) * columns; + const std::size_t storage = std::max(1, elements); + grow_workspace(h, storage); + grow_workspace(s, storage); + grow_workspace(vectors, storage); + } + + void scatter(const Z* input, Z* output) + { + // GEMR2D only reads its source; the connector accepts a mutable pointer. + Z* source = const_cast(input); + Cpxgemr2d(dimension, dimension, source, 1, 1, root.desc(), output, 1, 1, local.desc(), local.ictxt()); + } + + void gather(Z* output, const int columns) + { + Cpxgemr2d(dimension, columns, vectors.data(), 1, 1, local.desc(), output, 1, 1, root.desc(), local.ictxt()); + } +}; + +ParallelDenseEigensolver::ParallelDenseEigensolver() = default; +ParallelDenseEigensolver::~ParallelDenseEigensolver() = default; + +std::size_t ParallelDenseEigensolver::storage_bytes() const +{ + if (!impl_) + { + return 0; + } + const Impl& p = *impl_; + return sizeof(Impl::Z) * (p.h.capacity() + p.s.capacity() + p.vectors.capacity()) + p.gvx.storage_bytes(); +} + +void ParallelDenseEigensolver::solve_generalized(const std::complex* h, + const std::complex* s, + const int n, + const int bands, + double* values, + std::complex* vectors, + const MPI_Comm& comm, + const int block_size) +{ + ModuleBase::timer::Scope timer("ParallelDenseEigensolver", "solve_generalized"); + ModuleBase::Memory::record("RR::parallel_stage", 0, false); + if (!impl_) + { + impl_.reset(new Impl); + } + Impl& p = *impl_; + p.prepare(n, bands, comm, block_size); + p.scatter(h, p.h.data()); + p.scatter(s, p.s.data()); + const int rows = p.local.nrloc(); + const int columns = p.local.ncloc(); + p.gvx.solve(p.local.desc(), rows, columns, bands, p.h.data(), p.s.data(), values, p.vectors.data()); + p.gather(vectors, bands); + const std::size_t stage_bytes = + (p.h.capacity() + p.s.capacity() + p.vectors.capacity()) * sizeof(std::complex); + ModuleBase::Memory::record("RR::parallel_stage", stage_bytes, false); +} + +#endif // __MPI + +namespace +{ +#ifdef __CUDA +void check_cuda(const cudaError_t status, const char* operation) +{ + if (status != cudaSuccess) + { + throw std::runtime_error(std::string(operation) + ": " + cudaGetErrorString(status)); + } +} + +void check_solver(const cusolverStatus_t status, const char* operation) +{ + if (status != CUSOLVER_STATUS_SUCCESS) + { + throw std::runtime_error(std::string(operation) + ": cuSOLVER status " + std::to_string(status)); + } +} + +#endif +} // namespace + +struct GpuDenseEigensolver::Impl +{ +#ifdef __CUDA + cusolverDnHandle_t handle = nullptr; + int query_n = 0; + int query_wanted = 0; + int lwork = 0; + ct::Tensor matrix{ct::DataType::DT_COMPLEX_DOUBLE, ct::DeviceType::GpuDevice, {0}}; + ct::Tensor metric{ct::DataType::DT_COMPLEX_DOUBLE, ct::DeviceType::GpuDevice, {0}}; + ct::Tensor eigenvalues{ct::DataType::DT_DOUBLE, ct::DeviceType::GpuDevice, {0}}; + ct::Tensor info{ct::DataType::DT_INT, ct::DeviceType::GpuDevice, {0}}; + ct::Tensor work{ct::DataType::DT_COMPLEX_DOUBLE, ct::DeviceType::GpuDevice, {0}}; + + std::size_t storage_bytes() const + { + return matrix.buffer().GetAllocatedBytes() + metric.buffer().GetAllocatedBytes() + + eigenvalues.buffer().GetAllocatedBytes() + info.buffer().GetAllocatedBytes() + + work.buffer().GetAllocatedBytes(); + } + + void reserve(ct::Tensor& buffer, const int64_t count) + { + const std::size_t previous = buffer.buffer().GetAllocatedBytes(); + buffer.resize({count}); + // The container allocator returns null on allocation failure. + if (count > 0 && buffer.data() == nullptr) + { + throw std::runtime_error("GPU RR allocation failed."); + } + const std::size_t capacity = buffer.buffer().GetAllocatedBytes(); + if (capacity > previous) + { + ModuleBase::Memory::record("RR::gpu_work", 0, false); + const std::size_t bytes = storage_bytes(); + ModuleBase::Memory::record_gpu("RR::gpu_work", bytes, false); + } + } + + Impl() + { + const cusolverStatus_t status = cusolverDnCreate(&handle); + check_solver(status, "GPU RR handle creation"); + } + + ~Impl() { cusolverDnDestroy(handle); } +#endif +}; + +GpuDenseEigensolver::GpuDenseEigensolver() = default; +GpuDenseEigensolver::~GpuDenseEigensolver() = default; + +bool GpuDenseEigensolver::available() +{ +#ifdef __CUDA + return true; +#else + return false; +#endif +} + +std::size_t GpuDenseEigensolver::storage_bytes() const +{ +#ifdef __CUDA + if (impl_) + { + return impl_->storage_bytes(); + } +#endif + return 0; +} + +bool GpuDenseEigensolver::solve_generalized(const std::complex* matrix, + const std::complex* metric, + const int n, + const int wanted, + double* values, + std::complex* vectors) +{ + ModuleBase::timer::Scope timer("GpuDenseEigensolver", "solve_generalized"); +#ifdef __CUDA + if (!impl_) + { + impl_.reset(new Impl); + } + Impl& state = *impl_; + const std::size_t elements = static_cast(n) * n; + const std::size_t matrix_bytes = elements * sizeof(std::complex); + const std::size_t info_bytes = sizeof(int); + const int64_t matrix_size = elements; + state.reserve(state.matrix, matrix_size); + state.reserve(state.metric, matrix_size); + state.reserve(state.eigenvalues, n); + state.reserve(state.info, 1); + cuDoubleComplex* a = static_cast(state.matrix.data()); + cuDoubleComplex* b = static_cast(state.metric.data()); + double* eigenvalues = state.eigenvalues.data(); + int* device_info = state.info.data(); + const cudaError_t copy_h = cudaMemcpy(a, matrix, matrix_bytes, cudaMemcpyHostToDevice); + check_cuda(copy_h, "GPU GV matrix upload"); + const cudaError_t copy_g = cudaMemcpy(b, metric, matrix_bytes, cudaMemcpyHostToDevice); + check_cuda(copy_g, "GPU GV metric upload"); + const bool partial = wanted < n; + const cusolverEigRange_t range = partial ? CUSOLVER_EIG_RANGE_I : CUSOLVER_EIG_RANGE_ALL; + int found = 0; + if (state.query_n != n || state.query_wanted != wanted) + { + int lwork = 0; + cusolverStatus_t status; + if (!partial) + { + status = cusolverDnZhegvd_bufferSize(state.handle, + CUSOLVER_EIG_TYPE_1, + CUSOLVER_EIG_MODE_VECTOR, + CUBLAS_FILL_MODE_UPPER, + n, + a, + n, + b, + n, + eigenvalues, + &lwork); + } + else + { + status = cusolverDnZhegvdx_bufferSize(state.handle, + CUSOLVER_EIG_TYPE_1, + CUSOLVER_EIG_MODE_VECTOR, + range, + CUBLAS_FILL_MODE_UPPER, + n, + a, + n, + b, + n, + 0.0, + 0.0, + 1, + wanted, + &found, + eigenvalues, + &lwork); + } + check_solver(status, "GPU GV workspace query"); + if (lwork < 1) + { + throw std::runtime_error("Invalid GPU GV workspace query result."); + } + state.reserve(state.work, lwork); + state.lwork = lwork; + state.query_n = n; + state.query_wanted = wanted; + } + cuDoubleComplex* work = static_cast(state.work.data()); + cusolverStatus_t status; + if (!partial) + { + status = cusolverDnZhegvd(state.handle, + CUSOLVER_EIG_TYPE_1, + CUSOLVER_EIG_MODE_VECTOR, + CUBLAS_FILL_MODE_UPPER, + n, + a, + n, + b, + n, + eigenvalues, + work, + state.lwork, + device_info); + } + else + { + status = cusolverDnZhegvdx(state.handle, + CUSOLVER_EIG_TYPE_1, + CUSOLVER_EIG_MODE_VECTOR, + range, + CUBLAS_FILL_MODE_UPPER, + n, + a, + n, + b, + n, + 0.0, + 0.0, + 1, + wanted, + &found, + eigenvalues, + work, + state.lwork, + device_info); + } + check_solver(status, "GPU GV eigensolve"); + + int info = 0; + const cudaError_t copy_info = cudaMemcpy(&info, device_info, info_bytes, cudaMemcpyDeviceToHost); + check_cuda(copy_info, "GPU GV status download"); + if (info > n && info <= 2 * static_cast(n)) + { + + return false; + } + if (info != 0 || (partial && found != wanted)) + { + + throw std::runtime_error("GPU GV failed: INFO=" + std::to_string(info) + ", found=" + std::to_string(found)); + } + const std::size_t returned = static_cast(n) * wanted; + const std::size_t returned_value_bytes = static_cast(wanted) * sizeof(double); + const std::size_t returned_vector_bytes = returned * sizeof(std::complex); + const cudaError_t copy_values = cudaMemcpy(values, eigenvalues, returned_value_bytes, cudaMemcpyDeviceToHost); + check_cuda(copy_values, "GPU GV eigenvalue download"); + const cudaError_t copy_vectors = cudaMemcpy(vectors, a, returned_vector_bytes, cudaMemcpyDeviceToHost); + check_cuda(copy_vectors, "GPU GV coefficients download"); + return true; +#else + throw std::runtime_error("GPU generalized RR requires a CUDA build."); +#endif +} + +} // namespace dense +} // namespace hsolver diff --git a/source/source_hsolver/dense_eigensolver.h b/source/source_hsolver/dense_eigensolver.h new file mode 100644 index 00000000000..1b565573603 --- /dev/null +++ b/source/source_hsolver/dense_eigensolver.h @@ -0,0 +1,113 @@ +#ifndef HSOLVER_DENSE_EIGENSOLVER_H +#define HSOLVER_DENSE_EIGENSOLVER_H + +#include "source_base/module_container/ATen/core/tensor.h" +#include +#include +#include +#include +#ifdef __MPI +#include +#endif + +namespace hsolver +{ +namespace dense +{ +// Dense generalized Hermitian eigensolvers, with 1 <= wanted <= dimension. +// Column-major buffers hold dimension^2 input entries, dimension values +// and dimension*wanted eigenvector coefficients. +// Root-local HEGVX scratch; reuse one instance across consecutive RR solves. +struct SerialGvWorkspace +{ + using Wide = std::complex; + // Inputs are preserved. Return LAPACK INFO, or a negative workspace/output status. + int solve(const Wide* h, const Wide* g, int dimension, int wanted, double* values, Wide* vectors); + // Local owned capacity; an unused workspace contributes zero on nonroot ranks. + std::size_t storage_bytes() const; + + private: + int capacity_dimension_ = 0; + int work_size_ = 0; + ct::Tensor h_{ct::DataType::DT_COMPLEX_DOUBLE, ct::DeviceType::CpuDevice, {0}}; + ct::Tensor g_{ct::DataType::DT_COMPLEX_DOUBLE, ct::DeviceType::CpuDevice, {0}}; + ct::Tensor work_{ct::DataType::DT_COMPLEX_DOUBLE, ct::DeviceType::CpuDevice, {0}}; + ct::Tensor real_work_{ct::DataType::DT_DOUBLE, ct::DeviceType::CpuDevice, {0}}; + std::vector int_work_; + std::vector failures_; +}; + +/** ScaLAPACK generalized eigensolver with reusable block-cyclic storage and workspace. + * Calls are collective; rank zero supplies the matrices and receives eigenvectors. + * The borrowed communicator stays alive until this object is destroyed or rebound. + * A positive block_size sets the block width; zero selects it automatically. + * Buffers retain their largest allocated capacity across solves. + */ +class ParallelDenseEigensolver +{ + public: +#ifdef __MPI + ParallelDenseEigensolver(); + ~ParallelDenseEigensolver(); + ParallelDenseEigensolver(const ParallelDenseEigensolver&) = delete; + ParallelDenseEigensolver& operator=(const ParallelDenseEigensolver&) = delete; + + // Returns wanted eigenvalues and n*wanted column-major coefficients on rank zero. + void solve_generalized(const std::complex* h, + const std::complex* s, + const int n, + const int bands, + double* values, + std::complex* vectors, + const MPI_Comm& comm, + const int block_size); + + // Local owned workspace capacity; zero before the first solve. + std::size_t storage_bytes() const; + + private: + struct Impl; + std::unique_ptr impl_; +#endif +}; + +/** CUDA generalized Hermitian eigensolver with reusable cuSOLVER resources. + * Inputs and outputs are host, column-major complex. The first wanted + * eigenpairs are returned, with vector leading dimension n. The upper triangle + * defines each input matrix, whose contents are preserved. + * Resources are allocated on the first solve and reused across subsequent calls. + * Calls on an instance are serialized on one CUDA device, which remains current + * through destruction. + */ +class GpuDenseEigensolver +{ + public: + GpuDenseEigensolver(); + ~GpuDenseEigensolver(); + GpuDenseEigensolver(const GpuDenseEigensolver&) = delete; + GpuDenseEigensolver& operator=(const GpuDenseEigensolver&) = delete; + + static bool available(); + + // Solve H C = S C Lambda (type 1). + // Use HEGVDX for a partial spectrum, HEGVD for the full spectrum. + // False means the overlap is not positive definite; other numerical or + // API failures throw. + bool solve_generalized(const std::complex* matrix, + const std::complex* metric, + const int n, + const int wanted, + double* values, + std::complex* vectors); + + // Local owned workspace capacity; zero before the first solve. + std::size_t storage_bytes() const; + + private: + struct Impl; + std::unique_ptr impl_; +}; + +} // namespace dense +} // namespace hsolver +#endif diff --git a/source/source_hsolver/diago_lobpcg.cpp b/source/source_hsolver/diago_lobpcg.cpp new file mode 100644 index 00000000000..ff85682a851 --- /dev/null +++ b/source/source_hsolver/diago_lobpcg.cpp @@ -0,0 +1,775 @@ +#include "diago_lobpcg.h" +#include "lobpcg_internal.h" +#include "dense_eigensolver.h" +#include "source_base/kernels/math_kernel_op.h" +#include "source_base/memory_recorder.h" +#include "source_base/module_container/ATen/kernels/memory.h" +#include "source_base/parallel_device.h" +#include "source_base/timer.h" +#include "source_base/tool_quit.h" + +#include +#include +#include +#include +#include +#include + +namespace hsolver +{ +using lobpcg_internal::host_tensor; +using lobpcg_internal::host_tensor_cast_or_view; + +/// Store the caller configuration and allocate Device wavefunction and host RR workspaces. +template +DiagoLOBPCG::DiagoLOBPCG(const Real* precondition, + const int nband, + const int ndim, + const int nmax, + const LobpcgBasisLayout& layout, + const diag_comm_info& comm, + const int para_rr_method, + const int para_rr_block_size, + const bool use_overlap, + const LobpcgLocking locking, + dense::ParallelDenseEigensolver& rr_solver, + dense::GpuDenseEigensolver& gpu_rr_solver) + : n_band_(nband), n_dim_(ndim), n_max_(nmax), layout_(layout), comm_(comm), para_rr_method_(para_rr_method), + para_rr_bs_(para_rr_block_size), use_overlap_(use_overlap), locking_(locking), rr_solver_(rr_solver), + gpu_rr_solver_(gpu_rr_solver), algebra_(comm) +{ + if (n_max_ < n_band_) + { + ModuleBase::WARNING_QUIT("DiagoLOBPCG", "LOBPCG block must contain all requested bands."); + } + r_type_ = ct::DataTypeToEnum::value; + t_type_ = ct::DataTypeToEnum::value; + device_type_ = ct::DeviceTypeToEnum::value; + + prec_ = ct::Tensor(r_type_, device_type_, {n_dim_}); + syncmem_var_h2d_op()(prec_.data(), precondition, n_dim_); + allocate_workspace(); +} + +/// Record the final owned algebra workspace capacity before its buffers are released. +template +DiagoLOBPCG::~DiagoLOBPCG() +{ + const std::size_t host_bytes = algebra_.storage_bytes(ct::DeviceType::CpuDevice); + ModuleBase::Memory::record("LOBPCG::algebra", host_bytes, false); +#if defined(__CUDA) || defined(__ROCM) + const std::size_t device_bytes = algebra_.storage_bytes(ct::DeviceType::GpuDevice); + ModuleBase::Memory::record_gpu("LOBPCG::algebra", device_bytes, false); +#endif +} + +// Entry and generalized iteration. +/// Solve H X = S X Lambda by generalized RR in [X,P,W], with prefix locking and failure-only repair. +template +bool DiagoLOBPCG::diag(const HSOperator& op, + T* psi_in, + const int ld_psi, + Real* eigenvalue_in, + const double tolerance, + const int max_iter, + const std::vector& ethr_band) +{ + ModuleBase::timer::Scope timer("DiagoLOBPCG", "diag"); + iterations_ = 0; + error_message_.clear(); + + double global_dim = static_cast(layout_.npw) * layout_.npol; +#ifdef __MPI + if (comm_.nproc > 1) + { + Parallel_Common::reduce_data(&global_dim, 1, comm_.comm); + } +#endif + // A full [X,P,W] block needs at least 3*b physical rows; trim only optional buffer bands. + if (3 * n_max_ > global_dim) + { + if (n_band_ > static_cast(global_dim) / 3) + { + ModuleBase::WARNING_QUIT("DiagoLOBPCG::diag", "The requested bands cannot form a full-rank LOBPCG space."); + } + n_max_ = static_cast(global_dim) / 3; + allocate_workspace(); + } + + // Register optional labels in a common order across pools with different iteration paths. + const char* optional_work[] = {"LOBPCG::Cp", + "LOBPCG::retained", + "LOBPCG::cache_work", + "LOBPCG::p_work", + "LOBPCG::recovery_reference", + "LOBPCG::ortho_work", + "LOBPCG::basis_scratch"}; + for (const char* name : optional_work) + { + ModuleBase::Memory::record(name, 0, false); + } +#if defined(__CUDA) || defined(__ROCM) + ModuleBase::Memory::record_gpu("LOBPCG::cache_work", 0, false); + ModuleBase::Memory::record_gpu("LOBPCG::basis_scratch", 0, false); +#endif + + // 1. Prepare X, then obtain its initial Ritz pairs and residual. + initialize(psi_in, ld_psi); + SerialGvWorkspace serial_workspace; + bool initially_exact = true; + { // Initial RR: release temporary K/G, coefficient views and norms before the main loop. + const VectorImages initial = basis_images(0); + if (use_overlap_) + { + op.spsi(initial.x, initial.sx, n_dim_, n_max_); + project_padding(initial.sx, n_max_); + } + op.hpsi(initial.x, initial.hx, n_dim_, n_max_); + project_padding(initial.hx, n_max_); + ct::Tensor k = host_tensor(0, Wide(0)); + ct::Tensor g = host_tensor(0, Wide(0)); + form_projected_matrices(initial, n_max_, nullptr, k, g); + ModuleBase::Memory::record("LOBPCG::K", k.buffer().GetAllocatedBytes(), false); + ModuleBase::Memory::record("LOBPCG::G", g.buffer().GetAllocatedBytes(), false); + if (!solve_projected(k, g, n_max_, n_max_, serial_workspace)) + { + ModuleBase::WARNING_QUIT("DiagoLOBPCG::diag", error_message_); + } + std::copy_n(e_red_.data(), n_max_, eig_.data()); + const int coefficient_count = n_max_ * n_max_; + const ct::Tensor coefficients = host_tensor_cast_or_view(ritz_coefficients_.data(), coefficient_count); + ModuleBase::Memory::record("LOBPCG::Cx", coefficients.buffer().GetAllocatedBytes(), false); + const T* prepared = prepare_rotation_coefficients(coefficients); + rotate_images(initial, n_max_, n_max_, prepared, initial, evec_.data()); + // R = HX - SX*Lambda. Exclude roundoff-only directions before normalizing W; + // if every requested residual vanishes, these Ritz pairs already solve H/S. + form_residual(initial, n_max_, eig_.data(), residual_.data()); + ct::Tensor residual_norm_squared = host_tensor(n_max_, Real(0)); + for (int i = 0; i < n_max_; ++i) + { + const T* column = residual_.data() + i * n_dim_; + const Real norm = nrm2_op_(n_dim_, column, 1); + residual_norm_squared.data()[i] = norm * norm; + } +#ifdef __MPI + if (comm_.nproc > 1) + { + Parallel_Common::reduce_data(residual_norm_squared.data(), n_max_, comm_.comm); + } +#endif + for (int i = 0; i < n_max_; ++i) + { + const Real norm = std::sqrt(residual_norm_squared.data()[i]); + const Real scale = std::max(static_cast(1), std::abs(eig_.data()[i])); + const Real roundoff = static_cast(32) * std::numeric_limits::epsilon() * scale; + if (i < n_band_) + { + initially_exact = initially_exact && norm <= roundoff; + } + if (norm <= roundoff) + { + T* column = residual_.data() + i * n_dim_; + setmem_complex_op()(column, zero_, n_dim_); + } + } + } // End initial RR and roundoff-residual filtering. + // All requested residuals are roundoff-sized: return these Ritz pairs without constructing W. + if (initially_exact) + { + copy_op_(n_dim_ * n_max_, space_.data(), 1, x_new_.data(), 1); + write_results(psi_in, ld_psi, eigenvalue_in); + return true; + } + const bool soft = locking_ == LobpcgLocking::Soft; + int first_active = 0; + int first_w = n_max_; + int n_w = build_search(op, 0, n_max_, n_max_); + if (n_w <= 0) + { + error_message_ = "No nonzero initial search directions."; + ModuleBase::WARNING_QUIT("DiagoLOBPCG::diag", error_message_); + } + int working_columns = n_max_ + n_w; + + ct::Tensor eig_prev(eig_); + ct::Tensor tol_band = host_tensor(n_max_, static_cast(tolerance)); + for (int i = 0; i < n_band_ && i < static_cast(ethr_band.size()); ++i) + { + tol_band.data()[i] = static_cast(ethr_band[i]); + } + + // H is fixed only within this call. Start with a full projection; + // normal updates reuse the retained X/P blocks of K and G. + ProjectionCache cache; + + for (int iter = 0; iter < max_iter; ++iter) + { + iterations_ = iter + 1; + // 2. Apply H to new W and assemble the current K/G pair. + if (n_w > 0) + { + const VectorImages search = basis_images(first_w); + op.hpsi(search.x, search.hx, n_dim_, n_w); + project_padding(search.hx, n_w); + } + const int rr_off = soft ? 0 : first_active; + int rr_dim = working_columns - rr_off; + const int x_columns = n_max_ - rr_off; + const VectorImages rr = basis_images(rr_off); + ct::Tensor projected = host_tensor(0, Wide(0)); + ct::Tensor gram = host_tensor(0, Wide(0)); + form_projected_matrices(rr, rr_dim, &cache, projected, gram); + ModuleBase::Memory::record("LOBPCG::K", projected.buffer().GetAllocatedBytes(), false); + ModuleBase::Memory::record("LOBPCG::G", gram.buffer().GetAllocatedBytes(), false); + // 3. Solve generalized RR; only actual failure enters recovery. + if (!solve_projected(projected, gram, rr_dim, x_columns, serial_workspace)) + { + // Release stale projections while retaining reusable scratch capacity. + cache.columns = 0; + cache.k = host_tensor(0, Wide(0)); + cache.g = host_tensor(0, Wide(0)); + if (!recover_projected(op, rr, working_columns, x_columns, projected, gram, serial_workspace)) + { + ModuleBase::WARNING_QUIT("DiagoLOBPCG::diag", error_message_); + } + rr_dim = working_columns - rr_off; + } + // 4. Rotate X/SX and decide convergence before any next-step work. + Real* active_eigenvalues = eig_.data() + rr_off; + std::copy_n(e_red_.data(), x_columns, active_eigenvalues); + + const int active_offset = rr_off * n_dim_; + T* active_sx = use_overlap_ ? sx_new_.data() + active_offset : nullptr; + const VectorImages active = {x_new_.data() + active_offset, hx_new_.data() + active_offset, active_sx}; + const int coefficient_count = rr_dim * x_columns; + const ct::Tensor coefficients = host_tensor_cast_or_view(ritz_coefficients_.data(), coefficient_count); + ModuleBase::Memory::record("LOBPCG::Cx", coefficients.buffer().GetAllocatedBytes(), false); + // Rotate X/SX now; only the needed HX columns are rotated below. + const VectorImages ritz_source = {rr.x, nullptr, rr.sx}; + // Share the prepared coefficients across X/SX and HX rotations. + const T* prepared = prepare_rotation_coefficients(coefficients); + rotate_images(ritz_source, rr_dim, x_columns, prepared, active, nullptr); + + if (lock_converged(eig_prev, tol_band, first_active)) + { + write_results(psi_in, ld_psi, eigenvalue_in); + return true; + } + + const int active_columns = n_max_ - first_active; + if (iter + 1 == max_iter) + { + // Return the current Ritz pairs when the iteration budget is exhausted. + break; + } + // 5. Form the active residual, rotating only the required HX. + // Newly locked columns never enter the next residual/search block. + const int search_offset = first_active * n_dim_; + T* search_sx = use_overlap_ ? sx_new_.data() + search_offset : nullptr; + const VectorImages search_ritz = { + x_new_.data() + search_offset, hx_new_.data() + search_offset, search_sx}; + const int hx_columns = soft ? x_columns : active_columns; + const int first_hx_column = soft ? 0 : x_columns - active_columns; + const VectorImages hx_target = soft ? active : search_ritz; + const T* hx_coefficients = prepared + first_hx_column * rr_dim; + algebra_.expand_prepared(n_dim_, n_dim_, rr_dim, hx_columns, rr.hx, hx_coefficients, hx_target.hx, zero_); + const Real* search_eigenvalues = eig_.data() + first_active; + T* active_residual = residual_.data() + first_active * n_dim_; + form_residual(search_ritz, active_columns, search_eigenvalues, active_residual); + + // 6. Build P/HP/SP and their consistently scaled coefficients. + const int n_p = build_direction(rr, rr_dim, x_columns, active_columns, coefficients, gram); + // 7. Retain the new X/P projections before overwriting the old basis. + const Real* retained_values = active_eigenvalues + first_hx_column; + // Expansion zeroes these rows exactly; normalization preserves them. + // New locks remove this structure. + const int p_zero_prefix = x_columns == active_columns ? x_columns : 0; + retain_pair(projected, + gram, + rr_dim, + coefficients, + first_hx_column, + hx_columns, + n_p, + retained_values, + p_zero_prefix, + cache); + first_w = n_max_ + n_p; + + const int x_elements = n_dim_ * x_columns; + copy_op_(x_elements, active.x, 1, rr.x, 1); + // Soft locking retains every X in RR; their complete H images must + // remain valid even while only the active suffix generates residuals. + const int hx_elements = n_dim_ * hx_columns; + const int next_hx_first = soft ? 0 : first_active; + const VectorImages next_active = basis_images(next_hx_first); + copy_op_(hx_elements, hx_target.hx, 1, next_active.hx, 1); + if (use_overlap_) + { + copy_op_(x_elements, active.sx, 1, rr.sx, 1); + } + // 8. Prepare W for the next iteration. Its H image is deferred. + n_w = build_search(op, first_active, active_columns, first_w); + if (n_w == 0 && n_p == 0) + { + error_message_ = "No nonzero search or history directions remain."; + write_results(psi_in, ld_psi, eigenvalue_in); + ModuleBase::WARNING_QUIT("DiagoLOBPCG::diag", error_message_); + } + working_columns = n_max_ + n_p + n_w; + } + iterations_ = max_iter; + for (int i = 0; i < n_band_; ++i) + { + if (!std::isfinite(eig_.data()[i])) + { + error_message_ = "Non-finite target Ritz eigenvalue."; + ModuleBase::WARNING_QUIT("DiagoLOBPCG::diag", error_message_); + } + } + write_results(psi_in, ld_psi, eigenvalue_in); + return false; +} + +// Main algorithm operations, in execution order. +/// Copy the input X, seed optional buffer bands, and zero inactive rows in each spinor component. +template +void DiagoLOBPCG::initialize(T* psi_in, const int ld_psi) +{ + ModuleBase::timer::Scope function_timer("DiagoLOBPCG", "initialize"); + T* x = space_.data(); + syncmem_complex_2d_op()(x, n_dim_, psi_in, ld_psi, n_dim_, n_band_); + const int stride = n_dim_ / layout_.npol; + for (int j = n_band_; j < n_max_; ++j) + { + ct::Tensor seed = host_tensor(n_dim_, zero_); + std::seed_seq seed_key{comm_.rank, j}; + std::mt19937 generator(seed_key); + std::uniform_real_distribution uniform(-0.5, 0.5); + for (int component = 0; component < layout_.npol; ++component) + { + for (int ig = 0; ig < layout_.npw; ++ig) + { + seed.data()[component * stride + ig] = static_cast(uniform(generator)); + } + } + syncmem_complex_h2d_op()(x + j * n_dim_, seed.data(), n_dim_); + } + // Seeded buffer columns already have zero padding; only the caller's columns need clearing. + project_padding(x, n_band_); +} + +/// Form R = HX - SX*Lambda for the supplied block; a null SX means S = I. +template +void DiagoLOBPCG::form_residual( + const VectorImages& vectors, const int count, const Real* eigenvalues, T* residual) +{ + ModuleBase::timer::Scope function_timer("DiagoLOBPCG", "form_residual"); + const int elements = n_dim_ * count; + copy_op_(elements, vectors.hx, 1, residual, 1); + const T* metric_x = vectors.sx == nullptr ? vectors.x : vectors.sx; + for (int i = 0; i < count; ++i) + { + const T alpha = static_cast(-eigenvalues[i]); + const T* column = metric_x + i * n_dim_; + T* r = residual + i * n_dim_; + axpy_op_(n_dim_, &alpha, column, 1, r, 1); + } +} + +/// Precondition the active residual, project out the locked prefix, then normalize and compact W. +template +int DiagoLOBPCG::build_search( + const HSOperator& op, const int locked, const int count, const int first_w) +{ + ModuleBase::timer::Scope function_timer("DiagoLOBPCG", "build_search"); + const int n = n_dim_; + const VectorImages block = basis_images(first_w); + const T* residual = residual_.data() + locked * n; + const Real* values = eig_.data() + locked; + const int elements = n * count; + copy_op_(elements, residual, 1, block.x, 1); + syncmem_var_h2d_op()(eig_device_.data(), values, count); + // Residual padding is zero; division by the positive preconditioner preserves it. + precondition_op_(n_dim_, space_.data(), first_w, count, prec_.data(), eig_device_.data()); + if (use_overlap_) + { + op.spsi(block.x, block.sx, n_dim_, count); + project_padding(block.sx, count); + } + if (locked > 0) + { + const VectorImages reference = basis_images(0); + const T* metric = block.sx == nullptr ? block.x : block.sx; + const ct::Tensor cross = algebra_.cross_tensor(n, n, locked, count, reference.x, metric); + const T* prepared = prepare_rotation_coefficients(cross); + const T minus_one(-1); + algebra_.expand_prepared(n, n, locked, count, reference.x, prepared, block.x, minus_one); + if (block.sx != nullptr) + { + algebra_.expand_prepared(n, n, locked, count, reference.sx, prepared, block.sx, minus_one); + } + } + const VectorImages search = {block.x, nullptr, block.sx}; + return normalize_columns(search, count, nullptr, 0); +} + +/// Lock the leading bands satisfying the eigenvalue-change tolerance; soft locking can reactivate them. +template +bool DiagoLOBPCG::lock_converged(ct::Tensor& eig_prev, const ct::Tensor& tol_band, int& locked) +{ + ModuleBase::timer::Scope function_timer("DiagoLOBPCG", "lock_converged"); + const int previous_locked = locked; + locked = 0; + const bool soft = locking_ == LobpcgLocking::Soft; + bool prefix = true; + for (int i = 0; i < n_max_; ++i) + { + const double delta = std::abs(eig_.data()[i] - eig_prev.data()[i]); + const double band_tolerance = tol_band.data()[i]; + const bool band_ok = delta < band_tolerance; + // Hard retains locked vectors; soft lets their prefix reactivate. + const bool previous = !soft && i < previous_locked; + prefix = prefix && (previous || band_ok); + locked += prefix; + eig_prev.data()[i] = eig_.data()[i]; + } + return locked >= n_band_; +} + +/// Form P from the non-X Ritz coefficients, removing new locked components before normalization. +template +int DiagoLOBPCG::build_direction(const VectorImages& basis, + const int dimension, + const int q, + const int active, + const ct::Tensor& x_coefficients, + const ct::Tensor& g) +{ + ModuleBase::timer::Scope function_timer("DiagoLOBPCG", "build_direction"); + T* direction = u_p_.data(); + const int coefficient_count = dimension * active; + std::size_t p_bytes = 0; + { + const int locked_columns = q - active; + const Wide* coefficients = x_coefficients.data(); + Wide* projected_direction = reinterpret_cast(direction); + ct::Tensor direction_wide = host_tensor(0, Wide(0)); + if (!std::is_same::value && comm_.rank == 0) + { + const int64_t direction_size = static_cast(dimension) * active; + direction_wide.resize({direction_size}); + projected_direction = direction_wide.data(); + p_bytes = direction_wide.buffer().GetAllocatedBytes(); + } + if (comm_.rank == 0) + { + const Wide* active_coefficients = coefficients + locked_columns * dimension; + std::copy_n(active_coefficients, dimension * active, projected_direction); + for (int j = 0; j < active; ++j) + { + std::fill_n(projected_direction + j * dimension, q, Wide(0)); + } + if (locked_columns > 0) + { + ct::Tensor left = host_tensor(static_cast(locked_columns) * dimension, Wide(0)); + ct::Tensor cross = host_tensor(static_cast(locked_columns) * active, Wide(0)); + p_bytes = left.buffer().GetAllocatedBytes() + cross.buffer().GetAllocatedBytes() + + direction_wide.buffer().GetAllocatedBytes(); + const Wide one(1); + const Wide zero(0); + const Wide minus_one(-1); + ModuleBase::gemm_op()('C', + 'N', + locked_columns, + dimension, + dimension, + &one, + coefficients, + dimension, + g.data(), + dimension, + &zero, + left.data(), + locked_columns); + ModuleBase::gemm_op()('N', + 'N', + locked_columns, + active, + dimension, + &one, + left.data(), + locked_columns, + projected_direction, + dimension, + &zero, + cross.template data(), + locked_columns); + ModuleBase::gemm_op()('N', + 'N', + dimension, + active, + locked_columns, + &minus_one, + coefficients, + dimension, + cross.template data(), + locked_columns, + &one, + projected_direction, + dimension); + } + } + if (!std::is_same::value && comm_.rank == 0) + { + for (int i = 0; i < dimension * active; ++i) + { + direction[i] = static_cast(projected_direction[i]); + } + } + ModuleBase::Memory::record("LOBPCG::p_work", p_bytes, false); + broadcast(direction, coefficient_count); + } + const ct::Tensor p_coefficients = host_tensor_cast_or_view(direction, coefficient_count); + ModuleBase::Memory::record("LOBPCG::Cp", p_coefficients.buffer().GetAllocatedBytes(), false); + const VectorImages history = basis_images(n_max_); + const T* prepared = prepare_rotation_coefficients(p_coefficients); + rotate_images(basis, dimension, active, prepared, history, evec_.data()); + return normalize_columns(history, active, direction, dimension); +} + +/// Copy only the requested Ritz pairs back to the caller, preserving its leading dimension. +template +void DiagoLOBPCG::write_results(T* psi_in, const int ld_psi, Real* eigenvalue_in) +{ + syncmem_complex_2d_op()(psi_in, ld_psi, x_new_.data(), n_dim_, n_dim_, n_band_); + std::copy_n(eig_.data(), n_band_, eigenvalue_in); +} + +// Shared vector transformations and storage. +/// Apply the same right coefficient matrix to each supplied X/HX/SX image; scratch permits overlap. +template +void DiagoLOBPCG::rotate_images(const VectorImages& source, + const int source_columns, + const int target_columns, + const T* coefficients, + const VectorImages& target, + T* scratch) +{ + ModuleBase::timer::Scope function_timer("DiagoLOBPCG", "rotate_images"); + const T* inputs[] = {source.x, source.hx, source.sx}; + T* outputs[] = {target.x, target.hx, target.sx}; + const int elements = n_dim_ * target_columns; + for (int image = 0; image < 3; ++image) + { + if (inputs[image] == nullptr) + { + continue; + } + T* destination = scratch == nullptr ? outputs[image] : scratch; + algebra_.expand_prepared( + n_dim_, n_dim_, source_columns, target_columns, inputs[image], coefficients, destination, zero_); + if (scratch != nullptr) + { + copy_op_(elements, scratch, 1, outputs[image], 1); + } + } +} + +/// Scale nonzero columns by their global Euclidean norm and compact images and coefficients together. +template +int DiagoLOBPCG::normalize_columns( + const VectorImages& block, const int columns, T* coefficients, const int coefficient_rows) +{ + ModuleBase::timer::Scope function_timer("DiagoLOBPCG", "normalize_columns"); + const int n = n_dim_; + ct::Tensor norms = host_tensor(columns, 0.0); + if (std::is_same::value) + { + for (int j = 0; j < columns; ++j) + { + for (int i = 0; i < n; ++i) + { + const Wide value = static_cast(block.x[i + j * n]); + norms.data()[j] += std::norm(value); + } + } +#ifdef __MPI + Parallel_Common::reduce_data(norms.data(), columns, comm_.comm); +#endif + } + else + { + // dots_tensor returns globally reduced products for corresponding columns. + const int stride = n * columns; + const ct::Tensor dots = algebra_.dots_tensor(n, n, columns, 1, stride, block.x, block.x); + for (int j = 0; j < columns; ++j) + { + norms.data()[j] = dots.template data()[j].real(); + } + } + int kept = 0; + for (int j = 0; j < columns; ++j) + { + if (!std::isfinite(norms.data()[j])) + { + ModuleBase::WARNING_QUIT("DiagoLOBPCG::normalize_columns", "Nonfinite LOBPCG search direction."); + } + if (norms.data()[j] <= std::numeric_limits::min()) + { + continue; + } + const Real scale = static_cast(1.0 / std::sqrt(norms.data()[j])); + // Compaction is monotone (kept <= j); no unread column is overwritten. + for (T* image : {block.x, block.hx, block.sx}) + { + if (image == nullptr) + { + continue; + } + T* target = image + kept * n; + const T* source = image + j * n; + if (std::is_same::value) + { + // A serial loop avoids the vector kernel's per-column OpenMP overhead. + for (int i = 0; i < n; ++i) + { + target[i] = source[i] * scale; + } + } + else + { + ModuleBase::vector_mul_real_op()(n, target, source, scale); + } + } + if (coefficients != nullptr) + { + for (int i = 0; i < coefficient_rows; ++i) + { + coefficients[i + kept * coefficient_rows] = coefficients[i + j * coefficient_rows] * scale; + } + } + ++kept; + } + return kept; +} + +/// Borrow host double coefficients on CPU, or convert/upload them into reusable algebra scratch. +template +const T* DiagoLOBPCG::prepare_rotation_coefficients(const ct::Tensor& coefficients) +{ + // CPU double BLAS can consume the caller-owned coefficients directly. + // The caller retains them through every synchronous local rotation. + const Wide* input = coefficients.data(); + if (std::is_same::value && std::is_same::value) + { + return reinterpret_cast(input); + } + const int64_t count = coefficients.NumElements(); + return algebra_.prepare_coefficients(input, count); +} + +/// Return non-owning X/HX/SX pointers at one column offset in the shared trial-basis storage. +template +typename DiagoLOBPCG::VectorImages DiagoLOBPCG::basis_images(const int first) +{ + const int offset = first * n_dim_; + T* sx = use_overlap_ ? sspace_.data() + offset : nullptr; + return {space_.data() + offset, hspace_.data() + offset, sx}; +} + +/// Zero unused rows of every spinor component so full-stride BLAS products exclude nonphysical entries. +template +void DiagoLOBPCG::project_padding(T* x, const int columns) const +{ + const int stride = n_dim_ / layout_.npol; + for (int j = 0; j < columns; ++j) + { + for (int component = 0; component < layout_.npol; ++component) + { + T* first = x + j * n_dim_ + component * stride; + const int padding = stride - layout_.npw; + if (padding > 0) + { + setmem_complex_op()(first + layout_.npw, zero_, padding); + } + } + } +} + +/// Allocate wavefunction blocks and small RR buffers for the current internal width, and record capacity. +template +void DiagoLOBPCG::allocate_workspace() +{ + ModuleBase::timer::Scope function_timer("DiagoLOBPCG", "allocate_workspace"); + const int len_space = 3 * n_max_; + const ct::DeviceType host = ct::DeviceType::CpuDevice; + eig_ = ct::Tensor(r_type_, host, {n_max_}); + eig_device_ = ct::Tensor(r_type_, device_type_, {n_max_}); + evec_ = ct::Tensor(t_type_, device_type_, {n_dim_, n_max_}); + space_ = ct::Tensor(t_type_, device_type_, {n_dim_, len_space}); + hspace_ = ct::Tensor(t_type_, device_type_, {n_dim_, len_space}); + // C has at most (3*b) rows and b requested Ritz columns. + ritz_coefficients_ = ct::Tensor(t_type_, host, {len_space, n_max_}); + e_red_ = ct::Tensor(r_type_, host, {len_space}); + x_new_ = ct::Tensor(t_type_, device_type_, {n_dim_, n_max_}); + hx_new_ = ct::Tensor(t_type_, device_type_, {n_dim_, n_max_}); + if (use_overlap_) + { + sspace_ = ct::Tensor(t_type_, device_type_, {n_dim_, len_space}); + sx_new_ = ct::Tensor(t_type_, device_type_, {n_dim_, n_max_}); + sspace_.zero(); + sx_new_.zero(); + } + residual_ = ct::Tensor(t_type_, device_type_, {n_dim_, n_max_}); + u_p_ = ct::Tensor(t_type_, host, {len_space, n_max_}); + + for (ct::Tensor* buffer : + {&eig_, &space_, &hspace_, &ritz_coefficients_, &e_red_, &x_new_, &hx_new_, &residual_, &u_p_}) + { + buffer->zero(); + } + + const std::pair allocations[] = {{"LOBPCG::prec", &prec_}, + {"LOBPCG::eig", &eig_}, + {"LOBPCG::eig_device", &eig_device_}, + {"LOBPCG::evec", &evec_}, + {"LOBPCG::space", &space_}, + {"LOBPCG::hspace", &hspace_}, + {"LOBPCG::sspace", &sspace_}, + {"LOBPCG::ritz_coefficients", &ritz_coefficients_}, + {"LOBPCG::e_red", &e_red_}, + {"LOBPCG::x_new", &x_new_}, + {"LOBPCG::hx_new", &hx_new_}, + {"LOBPCG::sx_new", &sx_new_}, + {"LOBPCG::residual", &residual_}, + {"LOBPCG::u_p", &u_p_}}; + for (const std::pair& allocation : allocations) + { + const std::size_t bytes = allocation.second->buffer().GetAllocatedBytes(); + if (allocation.second->device_type() == ct::DeviceType::CpuDevice) + { + ModuleBase::Memory::record(allocation.first, bytes, false); + } +#if defined(__CUDA) || defined(__ROCM) + else + { + ModuleBase::Memory::record_gpu(allocation.first, bytes, false); + } +#endif + } + const std::size_t host_bytes = algebra_.storage_bytes(ct::DeviceType::CpuDevice); + ModuleBase::Memory::record("LOBPCG::algebra", host_bytes, false); +#if defined(__CUDA) || defined(__ROCM) + const std::size_t device_bytes = algebra_.storage_bytes(ct::DeviceType::GpuDevice); + ModuleBase::Memory::record_gpu("LOBPCG::algebra", device_bytes, false); +#endif +} + +template class DiagoLOBPCG, base_device::DEVICE_CPU>; +template class DiagoLOBPCG, base_device::DEVICE_CPU>; +#if defined(__CUDA) || defined(__ROCM) +template class DiagoLOBPCG, base_device::DEVICE_GPU>; +template class DiagoLOBPCG, base_device::DEVICE_GPU>; +#endif +} // namespace hsolver diff --git a/source/source_hsolver/diago_lobpcg.h b/source/source_hsolver/diago_lobpcg.h new file mode 100644 index 00000000000..5a53634f5d3 --- /dev/null +++ b/source/source_hsolver/diago_lobpcg.h @@ -0,0 +1,222 @@ +#ifndef DIAGO_LOBPCG_H_ +#define DIAGO_LOBPCG_H_ + +#include "source_base/module_container/ATen/core/tensor.h" +#include "source_base/module_container/ATen/kernels/blas.h" +#include "source_hsolver/diag_comm_info.h" +#include "source_hsolver/hs_operator.h" +#include "source_hsolver/kernels/bpcg_kernel_op.h" +#include "source_hsolver/module_linalg/linear_algebra.h" + +#include +#include +#include + +namespace hsolver +{ + +namespace dense +{ +class ParallelDenseEigensolver; +class GpuDenseEigensolver; +struct SerialGvWorkspace; +} // namespace dense + +enum class LobpcgLocking +{ + Hard, + Soft +}; + +/** Valid rows per spinor component; the component stride is ndim / npol. */ +struct LobpcgBasisLayout +{ + int npw; ///< Local physical plane-wave rows in each spinor component. + int npol; ///< Spinor components sharing the column storage stride ndim / npol. +}; + +template , typename Device = base_device::DEVICE_CPU> +class DiagoLOBPCG +{ + friend class LobpcgProjectionTest; + + private: + using Real = typename GetTypeReal::type; ///< Real precision of the stored wavefunctions T. + using Wide = std::complex; ///< Accumulation and projected eigensolver precision. + using CtDevice = typename ct::PsiToContainer::type; + + public: + // Internal block: nmax >= nband > 0. Vectors and preconditioner have ndim entries. + // Layout has npol > 0 dividing ndim and 0 <= npw <= ndim / npol. + DiagoLOBPCG(const Real* precondition, + const int nband, + const int ndim, + const int nmax, + const LobpcgBasisLayout& layout, + const diag_comm_info& comm, + const int para_rr_method, + const int para_rr_block_size, + const bool use_overlap, + const LobpcgLocking locking, + dense::ParallelDenseEigensolver& rr_solver, + dense::GpuDenseEigensolver& gpu_rr_solver); + ~DiagoLOBPCG(); + + // Start from a full-rank block of n_band_ vectors with ld_psi >= n_dim_. + // max_iter and tolerance are positive; false indicates iteration-budget exhaustion. + bool diag(const HSOperator& op, + T* psi_in, + const int ld_psi, + Real* eigenvalue_in, + const double tolerance, + const int max_iter, + const std::vector& ethr_band); + + int iterations() const { return iterations_; } + + private: + // Non-owning Device views; sx is null for the identity metric. + struct VectorImages + { + T* x; ///< Borrowed column block on Device. + T* hx; ///< Matching H images; null when a transformation does not need them. + T* sx; ///< Matching S images; null denotes S = I. + }; + + using SerialGvWorkspace = dense::SerialGvWorkspace; + + // One diag lifetime: root-owned K/G of retained [X,P] and reusable scratch. + // All ranks need columns when assembling the new W panel. + struct ProjectionCache + { + int columns = 0; ///< Width of the retained [X,P] block, also known on nonroot ranks. + /// Root-owned projections of [X,P]; empty on other ranks. + ct::Tensor k{ct::DataType::DT_COMPLEX_DOUBLE, ct::DeviceType::CpuDevice, {0}}; + ct::Tensor g{ct::DataType::DT_COMPLEX_DOUBLE, ct::DeviceType::CpuDevice, {0}}; + /// Host scratch for Q*C_P and the packed coefficient matrix [C_X,C_P]. + ct::Tensor h_product{ct::DataType::DT_COMPLEX_DOUBLE, ct::DeviceType::CpuDevice, {0}}; + ct::Tensor structural_coefficients{ct::DataType::DT_COMPLEX_DOUBLE, ct::DeviceType::CpuDevice, {0}}; + /// Device scratch for the same retained-block products; host K/G remain authoritative. + ct::Tensor device_matrix; + ct::Tensor device_coefficients; + ct::Tensor device_product; + ct::Tensor device_result; + ~ProjectionCache(); + }; + + int n_band_ = 0; ///< Number of requested eigenpairs returned to the caller. + int n_dim_ = 0; ///< Local column leading dimension, including spinor padding. + int n_max_ = 0; ///< Internal block width: requested bands plus dimension-limited buffer bands. + int iterations_ = 0; ///< Main-loop RR iterations in the last diag call; excludes initial RR. + std::string error_message_; ///< Failure reason supplied by RR or recovery. + + const LobpcgBasisLayout layout_; ///< Physical rows and spinor count within each stored column. + const diag_comm_info comm_; ///< Communicator/rank for distributed rows of one eigensolve. + const int para_rr_method_ = 0; ///< RR backend: local (0) or ScaLAPACK (2). + const int para_rr_bs_ = 0; ///< Distributed RR block size; zero selects automatically. + const bool use_overlap_; ///< Store and apply explicit S images instead of S = I. + const LobpcgLocking locking_; ///< Hard freezes the converged prefix; soft retains all X in RR. + dense::ParallelDenseEigensolver& rr_solver_; ///< Borrowed, reusable distributed CPU RR resources. + dense::GpuDenseEigensolver& gpu_rr_solver_; ///< Borrowed, reusable CUDA RR resources. + + ct::DataType r_type_ = ct::DataType::DT_INVALID; ///< Tensor element type corresponding to Real. + ct::DataType t_type_ = ct::DataType::DT_INVALID; ///< Tensor element type corresponding to T. + ct::DeviceType device_type_ = ct::DeviceType::UnKnown; ///< Wavefunction/scratch storage device. + + ct::Tensor prec_; ///< Device copy of the caller's diagonal preconditioner input, n_dim_ entries. + // Large wavefunction blocks reside on Device; small spectra, RR matrices + // and lock state reside on CPU on both backends. + ct::Tensor eig_; ///< Host Ritz values for all n_max_ columns, including locked columns. + ct::Tensor eig_device_; ///< Active Ritz values on Device for preconditioning. + ct::Tensor evec_; ///< Device rotation scratch, n_dim_ by n_max_. + ct::Tensor space_; ///< Device basis [X,P,W], capacity n_dim_ by 3*n_max_. + ct::Tensor hspace_; ///< H images matching the columns of space_. + ct::Tensor sspace_; ///< Explicit S images matching space_; unused for S = I. + ct::Tensor ritz_coefficients_; ///< Host T coefficients C, capacity 3*n_max_ by n_max_. + ct::Tensor e_red_; ///< Host eigenvalue output of the current reduced problem. + ct::Tensor x_new_; ///< Device updated Ritz vectors; hard-locked prefix stays unchanged. + ct::Tensor hx_new_; ///< Updated H images needed by residuals and the next trial basis. + ct::Tensor sx_new_; ///< Updated S images; unused for S = I. + ct::Tensor residual_; ///< Device residuals HX - SX*Lambda, active columns at their band offsets. + ct::Tensor u_p_; ///< Host T history coefficients C_P, compacted/scaled together with P. + + const T zero_ = static_cast(0.0); + + using syncmem_complex_2d_op = base_device::memory::synchronize_memory_2d_op; + using syncmem_var_h2d_op = ct::kernels::synchronize_memory; + using setmem_complex_op = ct::kernels::set_memory; + using syncmem_complex_h2d_op = ct::kernels::synchronize_memory; + using copy_op = ct::kernels::blas_copy; + using axpy_op = ct::kernels::blas_axpy; + using nrm2_op = ct::kernels::blas_nrm2; + + copy_op copy_op_; + axpy_op axpy_op_; + nrm2_op nrm2_op_; + precondition_op precondition_op_; + + LinearAlgebra algebra_; ///< Distributed products and reusable conversion/rotation scratch. + + // Main algorithm operations. + void initialize(T* psi_in, const int ld_psi); + void form_residual(const VectorImages& vectors, const int count, const Real* eigenvalues, T* residual); + int build_search(const HSOperator& op, const int locked, const int count, const int first_w); + bool lock_converged(ct::Tensor& eig_prev, const ct::Tensor& tol_band, int& locked); + // The caller supplies a nonempty active suffix; rank compaction follows rotation. + int build_direction(const VectorImages& basis, + const int dimension, + const int q, + const int active, + const ct::Tensor& x_coefficients, + const ct::Tensor& g); + void write_results(T* psi_in, const int ld_psi, Real* eigenvalue_in); + + // Shared vector transformations and storage. + void rotate_images(const VectorImages& source, + const int source_columns, + const int target_columns, + const T* coefficients, + const VectorImages& target, + T* scratch); + int normalize_columns(const VectorImages& block, const int columns, T* coefficients, const int coefficient_rows); + const T* prepare_rotation_coefficients(const ct::Tensor& coefficients); + VectorImages basis_images(const int first); + void project_padding(T* x, const int columns) const; + template + void broadcast(Value* data, const int count) const; + void allocate_workspace(); + + // Projected matrices, generalized RR and retained directions. + void form_projected_matrices( + const VectorImages& basis, const int columns, const ProjectionCache* retained, ct::Tensor& k, ct::Tensor& g); + bool solve_projected(const ct::Tensor& k, + const ct::Tensor& g, + const int dimension, + const int wanted, + SerialGvWorkspace& serial_workspace); + void retain_pair(const ct::Tensor& k, + const ct::Tensor& g, + const int rows, + const ct::Tensor& x_coefficients, + const int first_x, + const int x_columns, + const int p_columns, + const Real* ritz_values, + const int zero_prefix, + ProjectionCache& cache); + + // Exception-only physical-metric and rank recovery. + bool recover_projected(const HSOperator& op, + const VectorImages& basis, + int& working_columns, + const int wanted, + ct::Tensor& projected, + ct::Tensor& gram, + SerialGvWorkspace& workspace); + int repair_basis(const HSOperator& op, const int added); + int rank_orthonormalize(const int m, T* x, T* sx); +}; + +} // namespace hsolver + +#endif // DIAGO_LOBPCG_H_ diff --git a/source/source_hsolver/diago_params.cpp b/source/source_hsolver/diago_params.cpp index 28e1040a974..cc06ae93604 100644 --- a/source/source_hsolver/diago_params.cpp +++ b/source/source_hsolver/diago_params.cpp @@ -16,10 +16,7 @@ void setup_diago_params_pw(const int istep, DiagoIterAssist::SCF_ITER = iter; DiagoIterAssist::PW_DIAG_THR = ethr; - if (inp.calculation != "nscf") - { - DiagoIterAssist::PW_DIAG_NMAX = inp.pw_diag_nmax; - } + DiagoIterAssist::PW_DIAG_NMAX = inp.pw_diag_nmax; } template diff --git a/source/source_hsolver/hsolver_pw.cpp b/source/source_hsolver/hsolver_pw.cpp index edb3a2c18f1..70d2653ecb2 100644 --- a/source/source_hsolver/hsolver_pw.cpp +++ b/source/source_hsolver/hsolver_pw.cpp @@ -10,11 +10,14 @@ #include "source_hsolver/diago_cg.h" #include "source_hsolver/diago_dav_subspace.h" #include "source_hsolver/diago_david.h" +#include "source_hsolver/diago_lobpcg.h" #include "source_hsolver/diago_iter_assist.h" #include "source_psi/psi.h" #include +#include #include +#include #include namespace hsolver @@ -79,7 +82,7 @@ void HSolverPW::solve(HSOperator& op, this->nproc_in_pool = nproc_in_pool_in; // report if the specified diagonalization method is not supported - const std::initializer_list _methods = {"cg", "dav", "dav_subspace", "bpcg"}; + const std::initializer_list _methods = {"cg", "dav", "dav_subspace", "bpcg", "lobpcg"}; if (std::find(std::begin(_methods), std::end(_methods), this->method) == std::end(_methods)) { ModuleBase::WARNING_QUIT("HSolverPW::solve", "This type of eigensolver is not supported!"); @@ -347,6 +350,45 @@ void HSolverPW::hamiltSolvePsiK(const HSOperator& op, ntry_max, notconv_max)); } + else if (this->method == "lobpcg") + { + const int dim = psi.get_current_ngk(); + const int nband = psi.get_nbands(); + const int largest_block = std::numeric_limits::max() / 3; + if (this->lobpcg_extra_bands > largest_block - nband) + { + ModuleBase::WARNING_QUIT("HSolverPW::hamiltSolvePsiK", "Invalid lobpcg_extra_bands: block dimension is out of range."); + } + const int nmax = nband + this->lobpcg_extra_bands; + const int ld_psi = psi.get_nbasis(); + const double tolerance = this->diag_thr; + const std::vector uniform_thresholds; + const std::vector& lobpcg_ethr = this->diago_smooth_ethr ? this->ethr_band : uniform_thresholds; + const int npol = psi.get_npol(); + const LobpcgBasisLayout layout = {cur_nbasis, npol}; + const LobpcgLocking locking = this->lobpcg_locking == "soft" ? LobpcgLocking::Soft : LobpcgLocking::Hard; + DiagoLOBPCG lobpcg(pre_condition.data(), nband, dim, nmax, layout, comm_info, + this->diag_subspace, this->nb2d, this->use_uspp, locking, this->rr_solver, + this->gpu_rr_solver); + const bool converged = lobpcg.diag(op, psi.get_pointer(), ld_psi, eigenvalue, tolerance, + this->diag_iter_max, lobpcg_ethr); + if (!converged) + { + // SCF, relax, cell-relax and MD can refine approximate Ritz pairs + // in later electronic steps; NSCF has no such outer update. + if (this->calculation_type == "nscf") + { + ModuleBase::WARNING_QUIT("HSolverPW::hamiltSolvePsiK", "LOBPCG iteration budget exhausted in NSCF."); + } + const int kpoint = psi.get_current_k() + 1; + std::ostringstream message; + message << "LOBPCG reached the iteration limit at SCF step " << this->scf_iter + << ", k-point " << kpoint << " (" << lobpcg.iterations() + << " iterations); continuing SCF with approximate Ritz pairs."; + ModuleBase::WARNING("HSolverPW::hamiltSolvePsiK", message.str()); + } + DiagoIterAssist::avg_iter += static_cast(lobpcg.iterations()); + } ModuleBase::timer::end("HSolverPW", "solve_psik"); return; } diff --git a/source/source_hsolver/hsolver_pw.h b/source/source_hsolver/hsolver_pw.h index db6764154c8..a586bcd173c 100644 --- a/source/source_hsolver/hsolver_pw.h +++ b/source/source_hsolver/hsolver_pw.h @@ -5,6 +5,7 @@ #include "source_basis/module_pw/pw_basis_k.h" #include "source_estate/elecstate.h" #include "source_hsolver/hs_operator.h" +#include "source_hsolver/dense_eigensolver.h" #include #include @@ -44,6 +45,8 @@ class HSolverPW const int nbands_in, const bool diago_smooth_ethr_in, const int pw_diag_ndim_in, + const int lobpcg_extra_bands_in, + const std::string& lobpcg_locking_in, const int diag_subspace_in, const int nb2d_in, const bool use_k_continuity_in = false) @@ -51,6 +54,7 @@ class HSolverPW use_uspp(use_uspp_in), nspin(nspin_in), scf_iter(scf_iter_in), diag_iter_max(diag_iter_max_in), diag_thr(diag_thr_in), need_subspace(need_subspace_in), nbands(nbands_in), diago_smooth_ethr(diago_smooth_ethr_in), pw_diag_ndim(pw_diag_ndim_in), + lobpcg_extra_bands(lobpcg_extra_bands_in), lobpcg_locking(lobpcg_locking_in), diag_subspace(diag_subspace_in), nb2d(nb2d_in), use_k_continuity(use_k_continuity_in) {}; @@ -98,8 +102,10 @@ class HSolverPW const int nbands; // global number of bands, may differ from psi.get_nbands() under band parallelism const bool diago_smooth_ethr; // use a band-wise smoothed threshold for all iter methods const int pw_diag_ndim; // dimension of the workspace for Davidson-type methods - const int diag_subspace; // subspace eigensolver for dav_subspace: 0 Lapack, 1 elpa, 2 scalapack - const int nb2d; // 2d block size used by the dav_subspace scalapack path + const int lobpcg_extra_bands; // internal columns beyond the requested LOBPCG bands + const std::string lobpcg_locking; // hard or soft locking of converged LOBPCG bands + const int diag_subspace; // subspace eigensolver for dav_subspace and lobpcg: 0 Lapack, 1 elpa, 2 scalapack + const int nb2d; // 2d block size used by the distributed subspace eigensolvers const bool use_k_continuity; @@ -111,6 +117,10 @@ class HSolverPW std::vector ethr_band; + // Reused across k/spin solves within this HSolverPW lifetime (one SCF step). + dense::ParallelDenseEigensolver rr_solver; + dense::GpuDenseEigensolver gpu_rr_solver; + private: /// @brief calculate the threshold for iterative-diagonalization for each band void cal_smooth_ethr(const double& wk, const double* wg, const double& ethr, std::vector& ethrs); diff --git a/source/source_hsolver/lobpcg_internal.h b/source/source_hsolver/lobpcg_internal.h new file mode 100644 index 00000000000..4fc91b4c252 --- /dev/null +++ b/source/source_hsolver/lobpcg_internal.h @@ -0,0 +1,60 @@ +#ifndef HSOLVER_LOBPCG_INTERNAL_H_ +#define HSOLVER_LOBPCG_INTERNAL_H_ + +// Shared implementation details, included only by the LOBPCG .cpp files. +#include "diago_lobpcg.h" +#include "source_base/module_container/ATen/core/tensor_map.h" +#include "source_base/parallel_device.h" + +#include +#include +#include +#include + +namespace hsolver +{ +namespace lobpcg_internal +{ +/// Allocate and fill a host Tensor for small projected matrices or scalar work arrays. +template +ct::Tensor host_tensor(const int64_t count, const T value) +{ + const ct::DataType type = ct::DataTypeToEnum::value; + ct::Tensor tensor(type, ct::DeviceType::CpuDevice, {count}); + std::fill_n(tensor.data(), count, value); + return tensor; +} + +/// Borrow host storage when types match; otherwise own a converted copy. The view must not outlive input. +template +ct::Tensor host_tensor_cast_or_view(U* input, const int64_t count) +{ + const ct::DataType type = ct::DataTypeToEnum::value; + if (std::is_same::value) + { + ct::TensorMap view(input, type, ct::DeviceType::CpuDevice, {count}); + return ct::Tensor(std::move(view)); + } + ct::Tensor tensor(type, ct::DeviceType::CpuDevice, {count}); + std::copy_n(input, count, tensor.data()); + return tensor; +} + +} // namespace lobpcg_internal + +/// Share root-owned coefficients or status within the eigensolve communicator. +template +template +void DiagoLOBPCG::broadcast(Value* data, const int count) const +{ +#ifdef __MPI + if (comm_.nproc > 1) + { + Parallel_Common::bcast_data(data, count, comm_.comm, 0); + } +#endif +} + +} // namespace hsolver + +#endif // HSOLVER_LOBPCG_INTERNAL_H_ diff --git a/source/source_hsolver/lobpcg_recovery.cpp b/source/source_hsolver/lobpcg_recovery.cpp new file mode 100644 index 00000000000..a1fa6ec473a --- /dev/null +++ b/source/source_hsolver/lobpcg_recovery.cpp @@ -0,0 +1,479 @@ +#include "diago_lobpcg.h" +#include "lobpcg_internal.h" +#include "source_base/kernels/math_kernel_op.h" +#include "source_base/memory_recorder.h" +#include "source_base/module_container/ATen/kernels/lapack.h" +#include "source_base/module_container/base/third_party/blas.h" +#include "source_base/timer.h" + +#include +#include +#include +#include +#include + +namespace hsolver +{ +using lobpcg_internal::host_tensor; + +namespace +{ +bool finite_projection(const ct::Tensor& matrix) +{ + const std::complex* values = matrix.data>(); + for (int64_t i = 0; i < matrix.NumElements(); ++i) + { + if (!std::isfinite(values[i].real()) || !std::isfinite(values[i].imag())) + { + return false; + } + } + return true; +} + +// For G = U^H U, ||G||_1 bounds lambda_max and +// 1 / (||U^-1||_1 ||U^-1||_inf) bounds lambda_min from below. +// Use Cholesky for well-conditioned full-rank blocks; otherwise use EVD +// to determine the rank. The caller checks the transformed block. +bool cholesky_rank_transform(const ct::Tensor& gram, const int m, const double relative, ct::Tensor& transform) +{ + using C = std::complex; + double upper = 0.0; + for (int j = 0; j < m; ++j) + { + double sum = 0.0; + for (int i = 0; i < m; ++i) + { + sum += std::abs(gram.data>()[i + j * m]); + } + upper = std::max(upper, sum); + } + transform = gram; + int info = 0; + ct::lapackConnector::potrf('U', m, transform.data>(), m, info); + if (info != 0) + { + return false; + } + ct::lapackConnector::trtri('U', 'N', m, transform.data>(), m, info); + if (info != 0) + { + return false; + } + double norm_one = 0.0; + double norm_inf = 0.0; + for (int j = 0; j < m; ++j) + { + for (int i = j + 1; i < m; ++i) + { + transform.data>()[i + j * m] = C(0); + } + } + for (int j = 0; j < m; ++j) + { + double column = 0.0; + double row = 0.0; + for (int i = 0; i < m; ++i) + { + column += std::abs(transform.data>()[i + j * m]); + row += std::abs(transform.data>()[j + i * m]); + } + norm_one = std::max(norm_one, column); + norm_inf = std::max(norm_inf, row); + } + const double inverse_bound = norm_one * norm_inf; + const double cutoff = relative * upper; + const double condition_bound = upper * inverse_bound; + return std::isfinite(condition_bound) && condition_bound <= 1e4 && inverse_bound > 0.0 && + 1.0 / inverse_bound > cutoff; +} + +} // namespace + +/// After GV metric failure, refresh true H/S images and retry; if needed, repair only the increments. +template +bool DiagoLOBPCG::recover_projected(const HSOperator& op, + const VectorImages& basis, + int& working_columns, + const int wanted, + ct::Tensor& projected, + ct::Tensor& gram, + SerialGvWorkspace& workspace) +{ + ModuleBase::timer::Scope timer("DiagoLOBPCG", "recover_projected"); + const int offset = n_max_ - wanted; + int columns = working_columns - offset; + // Reapply the physical operators: independently rotated images can lose + // accuracy when trial directions nearly cancel. + op.hpsi(basis.x, basis.hx, n_dim_, columns); + project_padding(basis.hx, columns); + if (use_overlap_) + { + op.spsi(basis.x, basis.sx, n_dim_, columns); + project_padding(basis.sx, columns); + } + form_projected_matrices(basis, columns, nullptr, projected, gram); + if (solve_projected(projected, gram, columns, wanted, workspace)) + { + return true; + } + const int added = working_columns - n_max_; + const int kept = repair_basis(op, added); + if (kept <= 0) + { + error_message_ += "; basis recovery failed, retained increments=" + std::to_string(kept); + return false; + } + working_columns = n_max_ + kept; + columns = working_columns - offset; + form_projected_matrices(basis, columns, nullptr, projected, gram); + return solve_projected(projected, gram, columns, wanted, workspace); +} + +/// Preserve X, project increments with its actual S metric, then repair their rank and refresh H images. +template +int DiagoLOBPCG::repair_basis(const HSOperator& op, const int added) +{ + ModuleBase::timer::Scope function_timer("DiagoLOBPCG", "repair_basis"); + const int n = n_dim_; + const int reference_columns = n_max_; + const VectorImages reference = basis_images(0); + const VectorImages increments = basis_images(reference_columns); + const double epsilon = std::numeric_limits::epsilon(); + const Real tolerance = std::max(static_cast(1e-10), static_cast(100 * epsilon)); + const T minus_one(-1); + int kept = added; + if (use_overlap_) + { + op.spsi(reference.x, reference.sx, n_dim_, reference_columns); + project_padding(reference.sx, reference_columns); + } + // Use the actual metric M = X^H S X for projection in finite precision. + ct::Tensor reference_factor = + reference.sx == nullptr + ? algebra_.gram_tensor(n, n, reference_columns, reference.x) + : algebra_.cross_tensor(n, n, reference_columns, reference_columns, reference.x, reference.sx); + const std::size_t reference_bytes = reference_factor.buffer().GetAllocatedBytes(); + ModuleBase::Memory::record("LOBPCG::recovery_reference", reference_bytes, false); + int factor_info = 0; + if (comm_.rank == 0) + { + if (finite_projection(reference_factor)) + { + ct::lapackConnector::potrf( + 'U', reference_columns, reference_factor.data(), reference_columns, factor_info); + } + else + { + factor_info = -1; + } + } + Real shared_info = static_cast(factor_info); + broadcast(&shared_info, 1); + if (shared_info != 0) + { + return -1; + } + if (use_overlap_ && kept > 0) + { + op.spsi(increments.x, increments.sx, n_dim_, kept); + project_padding(increments.sx, kept); + } + for (int pass = 0; pass < 3 && kept > 0; ++pass) + { + const T* metric_image = increments.sx != nullptr ? increments.sx : increments.x; + ct::Tensor cross = algebra_.cross_tensor(n, n, reference_columns, kept, reference.x, metric_image); + if (comm_.rank == 0) + { + // M = R^H R: solve M C = X^H S D without forming an inverse. + const char left = 'L'; + const char upper = 'U'; + const char adjoint = 'C'; + const char normal = 'N'; + const Wide one(1); + ct::BlasConnector::trsm(left, + upper, + adjoint, + normal, + reference_columns, + kept, + one, + reference_factor.data(), + reference_columns, + cross.template data(), + reference_columns); + ct::BlasConnector::trsm(left, + upper, + normal, + normal, + reference_columns, + kept, + one, + reference_factor.data(), + reference_columns, + cross.template data(), + reference_columns); + } + const int cross_size = reference_columns * kept; + broadcast(cross.template data(), cross_size); + const T* coefficients = prepare_rotation_coefficients(cross); + algebra_.expand_prepared(n, n, reference_columns, kept, reference.x, coefficients, increments.x, minus_one); + if (use_overlap_) + { + op.spsi(increments.x, increments.sx, n_dim_, kept); + project_padding(increments.sx, kept); + } + kept = rank_orthonormalize(kept, increments.x, increments.sx); + if (kept <= 0) + { + return kept; + } + if (use_overlap_) + { + op.spsi(increments.x, increments.sx, n_dim_, kept); + project_padding(increments.sx, kept); + } + metric_image = increments.sx != nullptr ? increments.sx : increments.x; + const ct::Tensor overlap = algebra_.cross_tensor(n, n, reference_columns, kept, reference.x, metric_image); + double coupling = 0.0; + for (int64_t i = 0; i < overlap.NumElements(); ++i) + { + const Wide& value = overlap.template data()[i]; + coupling = std::max(coupling, std::abs(value)); + } + // Recovery acceptance: both coupling to X and the self metric must pass. + bool orthonormal = true; + { + const ct::Tensor gram = increments.sx == nullptr + ? algebra_.gram_tensor(n, n, kept, increments.x) + : algebra_.cross_tensor(n, n, kept, kept, increments.x, increments.sx); + for (int j = 0; j < kept && orthonormal; ++j) + { + for (int i = 0; i < kept; ++i) + { + const Wide expected = i == j ? Wide(1) : Wide(0); + const Real deviation = std::abs(gram.data()[i + j * kept] - expected); + if (!std::isfinite(deviation) || deviation > tolerance) + { + orthonormal = false; + break; + } + } + } + } + if (coupling <= tolerance && orthonormal) + { + op.hpsi(increments.x, increments.hx, n_dim_, kept); + project_padding(increments.hx, kept); + return kept; + } + } + return -1; +} + +/// Recovery-only metric normalization: use Cholesky for a well-conditioned block, otherwise spectral rank truncation. +template +int DiagoLOBPCG::rank_orthonormalize(const int m, T* x, T* sx) +{ + ModuleBase::timer::Scope function_timer("DiagoLOBPCG", "rank_orthonormalize"); + ct::Tensor gram = + sx == nullptr ? algebra_.gram_tensor(n_dim_, n_dim_, m, x) : algebra_.cross_tensor(n_dim_, n_dim_, m, m, x, sx); + ct::Tensor transform = host_tensor(0, Wide(0)); + const double eps = std::numeric_limits::epsilon(); + // Set the rank cutoff by wavefunction precision before inverse-square-root + // scaling amplifies roundoff. Explicit S images can introduce O(eps) + // negative Gram eigenvalues. + const double relative = 64 * std::max(std::numeric_limits::epsilon(), eps); + int rank = -1; + bool triangular = false; + std::size_t orthogonal_work = 0; + if (comm_.rank == 0) + { + try + { + for (int64_t i = 0; i < gram.NumElements(); ++i) + { + const Wide& value = gram.data()[i]; + if (!std::isfinite(std::abs(value))) + { + throw std::runtime_error("Non-finite LOBPCG Gram matrix."); + } + } + if (cholesky_rank_transform(gram, m, relative, transform)) + { + rank = m; + triangular = true; + } + else + { + ct::Tensor u(gram); + ct::Tensor values = host_tensor(m, double(0)); + orthogonal_work = gram.buffer().GetAllocatedBytes() + transform.buffer().GetAllocatedBytes() + + 2 * u.buffer().GetAllocatedBytes() + values.buffer().GetAllocatedBytes(); + ct::kernels::lapack_heevd solve; + solve(m, u.data(), m, values.data()); + const double cutoff = relative * std::max(0.0, values.data()[values.NumElements() - 1]); + if (sx != nullptr && values.data()[0] < -cutoff) + { + throw std::runtime_error("LOBPCG requires a positive overlap metric."); + } + int first = 0; + while (first < m && values.data()[first] <= cutoff) + { + ++first; + } + rank = m - first; + const int64_t scaled_size = static_cast(m) * rank; + ct::Tensor scaled = host_tensor(scaled_size, Wide(0)); + for (int j = 0; j < rank; ++j) + { + const int source = first + j; + const double scale = 1 / std::sqrt(values.data()[source]); + for (int i = 0; i < m; ++i) + { + scaled.data()[i + j * m] = u.data()[i + source * m] * scale; + } + } + if (rank < m) + { + transform = std::move(scaled); + } + else + { + // Preserve U Lambda^-1/2 U^H at full rank, U_r Lambda_r^-1/2 otherwise. + const int64_t transform_size = static_cast(m) * m; + transform = host_tensor(transform_size, Wide(0)); + const Wide one(1); + const Wide zero(0); + ModuleBase::gemm_op()('N', + 'C', + m, + m, + m, + &one, + scaled.data(), + m, + u.data(), + m, + &zero, + transform.data(), + m); + } + } + } + catch (const std::exception&) + { + rank = -1; + } + } + ModuleBase::Memory::record("LOBPCG::ortho_work", orthogonal_work, false); + // Broadcast rank and transform type to select TRMM or GEMM on every rank. + double metadata[2] = {static_cast(rank), static_cast(triangular)}; + broadcast(metadata, 2); + rank = static_cast(metadata[0]); + triangular = metadata[1] != 0.0; + if (rank <= 0) + { + return rank; + } + const int64_t transform_size = static_cast(m) * rank; + transform.resize({transform_size}); + const int count = m * rank; + broadcast(transform.data(), count); + const T* coefficients = prepare_rotation_coefficients(transform); + ct::Tensor rotated(t_type_, device_type_, {0}); + if (!triangular) + { + const int64_t elements = static_cast(n_dim_) * rank; + rotated.resize({elements}); + } + const std::size_t scratch_bytes = rotated.buffer().GetAllocatedBytes(); + if (device_type_ == ct::DeviceType::CpuDevice) + { + ModuleBase::Memory::record("LOBPCG::basis_scratch", scratch_bytes, false); + } +#if defined(__CUDA) || defined(__ROCM) + else + { + ModuleBase::Memory::record_gpu("LOBPCG::basis_scratch", scratch_bytes, false); + } +#endif + for (T* image : {x, sx}) + { + if (image == nullptr) + { + continue; + } + if (triangular) + { + const T one(1); + ModuleBase::trmm_op()('R', 'U', 'N', 'N', n_dim_, m, &one, coefficients, m, image, n_dim_); + } + else + { + algebra_.expand_prepared(n_dim_, n_dim_, m, rank, image, coefficients, rotated.data(), zero_); + const int elements = n_dim_ * rank; + copy_op_(elements, rotated.data(), 1, image, 1); + } + } + const std::size_t ortho_bytes = gram.buffer().GetAllocatedBytes() + transform.buffer().GetAllocatedBytes(); + ModuleBase::Memory::record("LOBPCG::ortho_work", ortho_bytes, false); + return rank; +} + +template int DiagoLOBPCG, base_device::DEVICE_CPU>::rank_orthonormalize( + const int, std::complex*, std::complex*); +template bool DiagoLOBPCG, base_device::DEVICE_CPU>::recover_projected( + const HSOperator, base_device::DEVICE_CPU>&, + const VectorImages&, + int&, + const int, + ct::Tensor&, + ct::Tensor&, + SerialGvWorkspace&); +template int DiagoLOBPCG, base_device::DEVICE_CPU>::repair_basis( + const HSOperator, base_device::DEVICE_CPU>&, const int); + +template int DiagoLOBPCG, base_device::DEVICE_CPU>::rank_orthonormalize( + const int, std::complex*, std::complex*); +template bool DiagoLOBPCG, base_device::DEVICE_CPU>::recover_projected( + const HSOperator, base_device::DEVICE_CPU>&, + const VectorImages&, + int&, + const int, + ct::Tensor&, + ct::Tensor&, + SerialGvWorkspace&); +template int DiagoLOBPCG, base_device::DEVICE_CPU>::repair_basis( + const HSOperator, base_device::DEVICE_CPU>&, const int); + +#if defined(__CUDA) || defined(__ROCM) + +template int DiagoLOBPCG, base_device::DEVICE_GPU>::rank_orthonormalize( + const int, std::complex*, std::complex*); +template bool DiagoLOBPCG, base_device::DEVICE_GPU>::recover_projected( + const HSOperator, base_device::DEVICE_GPU>&, + const VectorImages&, + int&, + const int, + ct::Tensor&, + ct::Tensor&, + SerialGvWorkspace&); +template int DiagoLOBPCG, base_device::DEVICE_GPU>::repair_basis( + const HSOperator, base_device::DEVICE_GPU>&, const int); + +template int DiagoLOBPCG, base_device::DEVICE_GPU>::rank_orthonormalize( + const int, std::complex*, std::complex*); +template bool DiagoLOBPCG, base_device::DEVICE_GPU>::recover_projected( + const HSOperator, base_device::DEVICE_GPU>&, + const VectorImages&, + int&, + const int, + ct::Tensor&, + ct::Tensor&, + SerialGvWorkspace&); +template int DiagoLOBPCG, base_device::DEVICE_GPU>::repair_basis( + const HSOperator, base_device::DEVICE_GPU>&, const int); +#endif + +} // namespace hsolver diff --git a/source/source_hsolver/lobpcg_subspace.cpp b/source/source_hsolver/lobpcg_subspace.cpp new file mode 100644 index 00000000000..3de46ab1db2 --- /dev/null +++ b/source/source_hsolver/lobpcg_subspace.cpp @@ -0,0 +1,474 @@ +#include "diago_lobpcg.h" +#include "lobpcg_internal.h" +#include "dense_eigensolver.h" +#include "source_base/kernels/math_kernel_op.h" +#include "source_base/memory_recorder.h" +#include "source_base/timer.h" +#include "source_base/tool_quit.h" +#ifdef __MPI +#include "source_base/module_parallel/para_mpi_func.h" +#endif + +#include +#include +#include + +namespace hsolver +{ +using lobpcg_internal::host_tensor; +using lobpcg_internal::host_tensor_cast_or_view; + +// Projected K/G, generalized RR, and the retained X/P projection cache. + +/// Form K = B^H H B and G = B^H S B; with a retained [X,P] block, compute only the new W panel. +template +void DiagoLOBPCG::form_projected_matrices( + const VectorImages& basis, const int columns, const ProjectionCache* retained, ct::Tensor& k, ct::Tensor& g) +{ + ModuleBase::timer::Scope timer("DiagoLOBPCG", "form_projected_matrices"); + const int keep = retained == nullptr ? 0 : retained->columns; + const ct::Tensor* saved[] = { + retained == nullptr ? nullptr : &retained->k, retained == nullptr ? nullptr : &retained->g}; + ct::Tensor* outputs[] = {&k, &g}; + const T* images[] = {basis.hx, basis.sx == nullptr ? basis.x : basis.sx}; + const int added = columns - keep; + std::size_t local_bytes = 0; + for (int matrix = 0; matrix < 2; ++matrix) + { + ct::Tensor& result = *outputs[matrix]; + const bool nc_gram = matrix == 1 && basis.sx == nullptr && std::is_same::value; + if (keep == 0) + { + if (nc_gram) + { + result = algebra_.gram_root_tensor(n_dim_, n_dim_, columns, basis.x); + } + else + { + result = algebra_.cross_root_tensor(n_dim_, n_dim_, columns, columns, basis.x, images[matrix]); + } + continue; + } + const int64_t elements = comm_.rank == 0 ? static_cast(columns) * columns : 0; + result = host_tensor(elements, Wide(0)); + if (comm_.rank == 0) + { + for (int j = 0; j < keep; ++j) + { + std::copy_n(saved[matrix]->template data() + j * keep, keep, result.data() + j * columns); + } + } + if (added == 0) + { + continue; + } + ct::Tensor panel = host_tensor(0, Wide(0)); + if (nc_gram) + { + // Compute W^H W with HERK, then reduce the entire new panel once. + const int n = n_dim_; + const int64_t basis_elements = static_cast(n) * columns; + const ct::Tensor basis_wide = host_tensor_cast_or_view(basis.x, basis_elements); + const Wide* wide_basis = basis_wide.data(); + const Wide* w = wide_basis + keep * n; + panel = host_tensor(static_cast(columns) * added, Wide(0)); + ct::Tensor self = host_tensor(static_cast(added) * added, Wide(0)); + const std::size_t panel_bytes = panel.buffer().GetAllocatedBytes() + self.buffer().GetAllocatedBytes() + + basis_wide.buffer().GetAllocatedBytes(); + local_bytes = std::max(local_bytes, panel_bytes); + const Wide one(1); + const Wide zero(0); + ModuleBase::gemm_op()( + 'C', 'N', keep, added, n, &one, wide_basis, n, w, n, &zero, panel.data(), columns); + ModuleBase::gram_herk_cpu(n, n, added, w, self.data()); + linear_complete_hermitian_upper(added, self.data()); + for (int j = 0; j < added; ++j) + { + std::copy_n(self.data() + j * added, added, panel.data() + keep + j * columns); + } +#ifdef __MPI + const int panel_size = columns * added; + Parallel_Common::reduce_data_to_root(panel.data(), panel_size, comm_.comm, 0); +#endif + } + else + { + const T* new_image = images[matrix] + keep * n_dim_; + panel = algebra_.cross_root_tensor(n_dim_, n_dim_, columns, added, basis.x, new_image); + if (comm_.rank == 0) + { + const std::size_t panel_bytes = panel.buffer().GetAllocatedBytes(); + local_bytes = std::max(local_bytes, panel_bytes); + } + } + if (comm_.rank == 0) + { + // Retained blocks are already global; only the new panel was reduced. + Wide* output = result.data(); + std::copy_n(panel.data(), panel.NumElements(), output + keep * columns); + for (int j = 0; j < keep; ++j) + { + for (int i = keep; i < columns; ++i) + { + output[i + j * columns] = std::conj(output[j + i * columns]); + } + } + } + } + ModuleBase::Memory::record("LOBPCG::projection_local", local_bytes, false); +} + +/// Solve K C = G C Theta for the wanted Ritz pairs and share the result; return false for metric failure. +template +bool DiagoLOBPCG::solve_projected(const ct::Tensor& k, + const ct::Tensor& g, + const int dimension, + const int wanted, + SerialGvWorkspace& serial_workspace) +{ + ModuleBase::timer::Scope function_timer("DiagoLOBPCG", "solve_projected"); + error_message_.clear(); + ct::Tensor values = host_tensor(dimension, double(0)); + const int64_t coefficient_count = static_cast(dimension) * wanted; + ct::Tensor coefficients(ct::DataType::DT_COMPLEX_DOUBLE, ct::DeviceType::CpuDevice, {0}); + if (std::is_same::value) + { + // Reuse ritz_coefficients_ as the solve and gather/broadcast output buffer. + coefficients = host_tensor_cast_or_view(ritz_coefficients_.data(), coefficient_count); + } + else + { + coefficients = host_tensor(coefficient_count, Wide(0)); + } + const std::size_t output_bytes = values.buffer().GetAllocatedBytes() + coefficients.buffer().GetAllocatedBytes(); + ModuleBase::Memory::record("LOBPCG::rr_output", output_bytes, false); + // Root-only backends publish one outcome before any rank returns/exits: + // 1 = success, 0 = non-positive metric, -1 = fatal backend failure. + double result = 1; + const bool gpu_rr = std::is_same::value && dense::GpuDenseEigensolver::available(); + try + { + if (para_rr_method_ == 0) + { + if (comm_.rank == 0) + { + if (gpu_rr) + { + const bool positive = gpu_rr_solver_.solve_generalized(k.data(), + g.data(), + dimension, + wanted, + values.data(), + coefficients.data()); + result = positive ? 1 : 0; + if (!positive) + { + error_message_ = "CUDA generalized RR: overlap is not positive definite."; + } + } + else + { + const int info = serial_workspace.solve(k.data(), + g.data(), + dimension, + wanted, + values.data(), + coefficients.data()); + if (info != 0) + { + error_message_ = "Serial HEGVX failed, info=" + std::to_string(info); + result = info > dimension ? 0 : -1; + } + } + } + } + else if (para_rr_method_ == 2) + { +#ifdef __MPI + rr_solver_.solve_generalized(k.data(), + g.data(), + dimension, + wanted, + values.data(), + coefficients.data(), + comm_.comm, + para_rr_bs_); +#else + ModuleBase::WARNING_QUIT("DiagoLOBPCG::solve_projected", "Parallel LOBPCG RR requires an MPI build."); +#endif + } + else + { + ModuleBase::WARNING_QUIT("DiagoLOBPCG::solve_projected", "LOBPCG supports diag_subspace=0 or 2. Please select 0 or 2."); + } + } + catch (const std::exception& error) + { + error_message_ = error.what(); + if (para_rr_method_ == 0) + { + result = -1; // All ranks must receive the root failure before exiting. + } + else + { + const std::string reason(error.what()); + const bool recoverable = reason.find("info=16") != std::string::npos || + reason.find("not positive definite") != std::string::npos; + result = recoverable ? 0 : -1; + } + } + if (para_rr_method_ == 0) + { + // Only root solves the local RR; every rank records the same selected + // backend label, including failures and zero capacity on nonowners. + if (gpu_rr) + { + ModuleBase::Memory::record("RR::gpu_work", 0, false); +#if defined(__CUDA) || defined(__ROCM) + const std::size_t bytes = comm_.rank == 0 ? gpu_rr_solver_.storage_bytes() : 0; + ModuleBase::Memory::record_gpu("RR::gpu_work", bytes, false); +#endif + } + else + { + const std::size_t bytes = serial_workspace.storage_bytes(); + ModuleBase::Memory::record("RR::serial_gv", bytes, false); + } + broadcast(&result, 1); + } + if (result <= 0) + { +#ifdef __MPI + if (para_rr_method_ == 0 && comm_.nproc > 1) + { + const Parallel::ParaWorld world = Parallel::ParaWorld::make_mpi("lobpcg_rr", comm_.comm); + Parallel::bcast_string(error_message_, world, 0); + } +#endif + error_message_ += " (dimension=" + std::to_string(dimension) + ", wanted=" + std::to_string(wanted) + ")"; + if (result < 0) + { + ModuleBase::WARNING_QUIT("DiagoLOBPCG::solve_projected", error_message_); + } + return false; + } + if (comm_.rank == 0) + { + for (int i = 0; i < wanted; ++i) + { + e_red_.data()[i] = static_cast(values.data()[i]); + } + } + broadcast(e_red_.data(), wanted); + broadcast(coefficients.data(), dimension * wanted); + if (!std::is_same::value) + { + for (int i = 0; i < dimension * wanted; ++i) + { + ritz_coefficients_.data()[i] = static_cast(coefficients.data()[i]); + } + } + return true; +} + +/// Cache projections for the new [X,P] using coefficient-space products and the Ritz XX identities. +template +void DiagoLOBPCG::retain_pair(const ct::Tensor& k, + const ct::Tensor& g, + const int rows, + const ct::Tensor& x_coefficients, + const int first_x, + const int x_columns, + const int p_columns, + const Real* ritz_values, + const int zero_prefix, + ProjectionCache& cache) +{ + ModuleBase::timer::Scope function_timer("DiagoLOBPCG", "retain_pair"); + cache.columns = x_columns + p_columns; + if (comm_.rank == 0) + { + const Wide* cx = x_coefficients.data() + first_x * rows; + const T* cp_t = u_p_.data(); + const int keep = x_columns + p_columns; + const int64_t packed_size = static_cast(rows) * keep; + cache.structural_coefficients.resize({packed_size}); + Wide* packed = cache.structural_coefficients.template data(); + std::copy_n(cx, rows * x_columns, packed); + for (int i = 0; i < rows * p_columns; ++i) + { + packed[rows * x_columns + i] = static_cast(cp_t[i]); + } + if (!std::is_same::value && p_columns > 0) + { + linear_buffer(&cache.device_coefficients, packed_size); + using Upload = base_device::memory::synchronize_memory_op; + Upload()(cache.device_coefficients.template data(), packed, packed_size); + } + const ct::Tensor units = host_tensor(x_columns, static_cast(1)); + const ct::Tensor* matrices[] = {&g, &k}; + ct::Tensor* outputs[] = {&cache.g, &cache.k}; + const Real* diagonals[] = {units.template data(), ritz_values}; + for (int index = 0; index < 2; ++index) + { + const ct::Tensor& matrix = *matrices[index]; + ct::Tensor& retained_matrix = *outputs[index]; + const Real* diagonal = diagonals[index]; + const int nonzero_rows = rows - zero_prefix; + const int64_t retained_elements = static_cast(keep) * keep; + retained_matrix.resize({retained_elements}); + retained_matrix.zero(); + for (int i = 0; i < x_columns; ++i) + { + retained_matrix.template data()[i + i * keep] = diagonal[i]; + } + if (p_columns == 0) + { + continue; + } + const int64_t product_size = static_cast(rows) * p_columns; + const int64_t result_size = static_cast(keep) * p_columns; + Wide* xp = retained_matrix.template data() + x_columns * keep; + const Wide* matrix_data = matrix.data(); + const Wide* coefficients = cache.structural_coefficients.template data(); + Wide* product = nullptr; + Wide* result = xp; + if (std::is_same::value) + { + cache.h_product.resize({product_size}); + product = cache.h_product.template data(); + } + else + { + // Host projections stay authoritative; only the GEMMs use Device. + const int64_t matrix_size = matrix.NumElements(); + linear_buffer(&cache.device_matrix, matrix_size); + linear_buffer(&cache.device_product, product_size); + linear_buffer(&cache.device_result, result_size); + using Upload = base_device::memory::synchronize_memory_op; + Wide* device_data = cache.device_matrix.template data(); + Upload()(device_data, matrix_data, matrix_size); + matrix_data = device_data; + coefficients = cache.device_coefficients.template data(); + product = cache.device_product.template data(); + result = cache.device_result.template data(); + } + const Wide one(1); + const Wide zero(0); + const Wide* panel = matrix_data + zero_prefix * rows; + const Wide* cp = coefficients + x_columns * rows + zero_prefix; + // Form Q C_P, then C^H (Q C_P). + ModuleBase::gemm_op()( + 'N', 'N', rows, p_columns, nonzero_rows, &one, panel, rows, cp, rows, &zero, product, rows); + ModuleBase::gemm_op()( + 'C', 'N', keep, p_columns, rows, &one, coefficients, rows, product, rows, &zero, result, keep); + if (!std::is_same::value) + { + using Download = base_device::memory::synchronize_memory_op; + Download()(xp, result, result_size); + } + for (int j = x_columns; j < keep; ++j) + { + for (int i = 0; i < x_columns; ++i) + { + retained_matrix.template data()[j + i * keep] = + std::conj(retained_matrix.template data()[i + j * keep]); + } + } + } + } + const std::size_t retained_bytes = cache.k.buffer().GetAllocatedBytes() + cache.g.buffer().GetAllocatedBytes(); + ModuleBase::Memory::record("LOBPCG::retained", retained_bytes, false); +} + +template +DiagoLOBPCG::ProjectionCache::~ProjectionCache() +{ + std::size_t host = h_product.buffer().GetAllocatedBytes() + structural_coefficients.buffer().GetAllocatedBytes(); + std::size_t device = 0; + const ct::Tensor* buffers[] = {&device_matrix, &device_coefficients, &device_product, &device_result}; + for (const ct::Tensor* buffer : buffers) + { + if (buffer->device_type() == ct::DeviceType::CpuDevice) + { + host += buffer->buffer().GetAllocatedBytes(); + } + else + { + device += buffer->buffer().GetAllocatedBytes(); + } + } + ModuleBase::Memory::record("LOBPCG::cache_work", host, false); +#if defined(__CUDA) || defined(__ROCM) + ModuleBase::Memory::record_gpu("LOBPCG::cache_work", device, false); +#endif +} + +template DiagoLOBPCG, base_device::DEVICE_CPU>::ProjectionCache::~ProjectionCache(); +template void DiagoLOBPCG, base_device::DEVICE_CPU>::form_projected_matrices( + const VectorImages&, const int, const ProjectionCache*, ct::Tensor&, ct::Tensor&); +template bool DiagoLOBPCG, base_device::DEVICE_CPU>::solve_projected( + const ct::Tensor&, const ct::Tensor&, const int, const int, SerialGvWorkspace&); +template void DiagoLOBPCG, base_device::DEVICE_CPU>::retain_pair(const ct::Tensor&, + const ct::Tensor&, + const int, + const ct::Tensor&, + const int, + const int, + const int, + const Real*, + const int, + ProjectionCache&); + +template DiagoLOBPCG, base_device::DEVICE_CPU>::ProjectionCache::~ProjectionCache(); +template void DiagoLOBPCG, base_device::DEVICE_CPU>::form_projected_matrices( + const VectorImages&, const int, const ProjectionCache*, ct::Tensor&, ct::Tensor&); +template bool DiagoLOBPCG, base_device::DEVICE_CPU>::solve_projected( + const ct::Tensor&, const ct::Tensor&, const int, const int, SerialGvWorkspace&); +template void DiagoLOBPCG, base_device::DEVICE_CPU>::retain_pair(const ct::Tensor&, + const ct::Tensor&, + const int, + const ct::Tensor&, + const int, + const int, + const int, + const Real*, + const int, + ProjectionCache&); + +#if defined(__CUDA) || defined(__ROCM) + +template DiagoLOBPCG, base_device::DEVICE_GPU>::ProjectionCache::~ProjectionCache(); +template void DiagoLOBPCG, base_device::DEVICE_GPU>::form_projected_matrices( + const VectorImages&, const int, const ProjectionCache*, ct::Tensor&, ct::Tensor&); +template bool DiagoLOBPCG, base_device::DEVICE_GPU>::solve_projected( + const ct::Tensor&, const ct::Tensor&, const int, const int, SerialGvWorkspace&); +template void DiagoLOBPCG, base_device::DEVICE_GPU>::retain_pair(const ct::Tensor&, + const ct::Tensor&, + const int, + const ct::Tensor&, + const int, + const int, + const int, + const Real*, + const int, + ProjectionCache&); + +template DiagoLOBPCG, base_device::DEVICE_GPU>::ProjectionCache::~ProjectionCache(); +template void DiagoLOBPCG, base_device::DEVICE_GPU>::form_projected_matrices( + const VectorImages&, const int, const ProjectionCache*, ct::Tensor&, ct::Tensor&); +template bool DiagoLOBPCG, base_device::DEVICE_GPU>::solve_projected( + const ct::Tensor&, const ct::Tensor&, const int, const int, SerialGvWorkspace&); +template void DiagoLOBPCG, base_device::DEVICE_GPU>::retain_pair(const ct::Tensor&, + const ct::Tensor&, + const int, + const ct::Tensor&, + const int, + const int, + const int, + const Real*, + const int, + ProjectionCache&); +#endif + +} // namespace hsolver diff --git a/source/source_hsolver/module_linalg/linear_algebra.cpp b/source/source_hsolver/module_linalg/linear_algebra.cpp index 5f35a19a2be..45fbfd4bf3d 100644 --- a/source/source_hsolver/module_linalg/linear_algebra.cpp +++ b/source/source_hsolver/module_linalg/linear_algebra.cpp @@ -3,6 +3,7 @@ #include "source_base/kernels/math_kernel_op.h" #include "source_base/parallel_device.h" #include "source_base/timer.h" +#include "source_base/memory_recorder.h" #include "source_hsolver/module_linalg/kernels/linear_op.h" #include @@ -11,6 +12,18 @@ namespace hsolver { +void linear_complete_hermitian_upper(int n, std::complex* matrix) +{ + for (int j = 0; j < n; ++j) + { + matrix[j + j * n].imag(0.0); + for (int i = j + 1; i < n; ++i) + { + matrix[i + j * n] = std::conj(matrix[j + i * n]); + } + } +} + std::vector> linear_gram_basis(const std::vector>& gram, int n, double cutoff, int* rank) { using Wide = std::complex; @@ -187,6 +200,17 @@ void LinearAlgebra::reduce(std::vector* values) const #endif } +template +void LinearAlgebra::reduce(Wide* values, const int64_t count) const +{ +#ifdef __MPI + if (comm_.nproc > 1) + { + Parallel_Common::reduce_data(values, count, comm_.comm); + } +#endif +} + template std::vector> LinearAlgebra::projection_cross(int ld, int dim, int nx, int ny, const T* x, const T* y) { @@ -262,6 +286,21 @@ std::vector> LinearAlgebra::dots(int ld, return result; } +template +ct::Tensor LinearAlgebra::dots_tensor(int ld, int dim, int bands, int count, + int stride, const T* basis, const T* x) +{ + ModuleBase::timer::Scope function_timer("LinearAlgebra", "dots_tensor"); + const int size = bands * count; + ct::Tensor result(ct::DataType::DT_COMPLEX_DOUBLE, ct::DeviceType::CpuDevice, {size}); + linear_buffer(&products_, size); + linear_op().wide_dots(ld, dim, bands, count, stride, basis, x, products_.template data()); + base_device::memory::synchronize_memory_op()( + result.data(), products_.template data(), size); + reduce(result.data(), size); + return result; +} + template std::vector> LinearAlgebra::cross(int ld, int dim, int nx, int ny, const T* x, const T* y) { @@ -307,6 +346,99 @@ std::vector> LinearAlgebra::cross(int ld, int di return result; } +template +ct::Tensor LinearAlgebra::cross_tensor(int ld, int dim, int nx, int ny, const T* x, const T* y) +{ + ModuleBase::timer::Scope function_timer("LinearAlgebra", "cross_tensor"); + const int64_t count = static_cast(nx) * ny; + ct::Tensor result(ct::DataType::DT_COMPLEX_DOUBLE, ct::DeviceType::CpuDevice, {count}); + cross_local_into(ld, dim, nx, ny, x, y, result.data()); + reduce(result.data(), count); + return result; +} + +template +ct::Tensor LinearAlgebra::cross_root_tensor(int ld, int dim, int nx, int ny, const T* x, const T* y) +{ + ModuleBase::timer::Scope function_timer("LinearAlgebra", "cross_root_tensor"); + const int64_t elements = static_cast(nx) * ny; + if (elements > std::numeric_limits::max()) + { + throw std::length_error("Root projection exceeds the MPI count range."); + } + ct::Tensor result(ct::DataType::DT_COMPLEX_DOUBLE, ct::DeviceType::CpuDevice, {elements}); + // Root's result is the K/G owner, registered by the caller. Only non-root + // ranks discard their local contribution after the reduction. + const std::size_t local_bytes = comm_.rank == 0 ? 0 : result.buffer().GetAllocatedBytes(); + ModuleBase::Memory::record("LOBPCG::projection_local", local_bytes, false); + cross_local_into(ld, dim, nx, ny, x, y, result.data()); +#ifdef __MPI + if (comm_.nproc > 1) + { + const int count = elements; + Parallel_Common::reduce_data_to_root(result.data(), count, comm_.comm, 0); + } +#endif + if (comm_.rank != 0) + { + return ct::Tensor(ct::DataType::DT_COMPLEX_DOUBLE, ct::DeviceType::CpuDevice, {0}); + } + return result; +} + +template +void LinearAlgebra::cross_local_into(int ld, int dim, int nx, int ny, const T* x, const T* y, Wide* result) +{ + const int64_t elements = static_cast(nx) * ny; + if (dim == 0) + { + std::fill_n(result, elements, Wide(0)); + } + if (dim > 0) + { + const Wide* a = reinterpret_cast(x); + const Wide* b = reinterpret_cast(y); + if (!std::is_same::value) + { + const int64_t left_elements = static_cast(ld) * nx; + const int64_t right_elements = static_cast(ld) * ny; + linear_buffer(&left_, left_elements); + linear_buffer(&right_, right_elements); + // Copy valid rows only: padding may be uninitialized. + for (int j = 0; j < nx; ++j) + { + const int64_t offset = static_cast(j) * ld; + Wide* destination = left_.template data() + offset; + const T* source = x + offset; + base_device::memory::cast_memory_op()(destination, source, dim); + } + for (int j = 0; j < ny; ++j) + { + const int64_t offset = static_cast(j) * ld; + Wide* destination = right_.template data() + offset; + const T* source = y + offset; + base_device::memory::cast_memory_op()(destination, source, dim); + } + a = left_.template data(); + b = right_.template data(); + } + Wide* products = result; + if (!std::is_same::value) + { + linear_buffer(&products_, elements); + products = products_.template data(); + } + const Wide one(1); + const Wide zero(0); + ModuleBase::gemm_op()('C', 'N', nx, ny, dim, &one, a, ld, b, ld, &zero, products, nx); + if (!std::is_same::value) + { + base_device::memory::synchronize_memory_op()( + result, products, elements); + } + } +} + template std::vector> LinearAlgebra::gram(int ld, int dim, int bands, const T* input) { @@ -351,6 +483,110 @@ std::vector> LinearAlgebra::gram(int ld, int dim return result; } +template +ct::Tensor LinearAlgebra::gram_tensor(int ld, int dim, int bands, const T* input) +{ + ModuleBase::timer::Scope function_timer("LinearAlgebra", "gram_tensor"); + const int64_t count = static_cast(bands) * bands; + ct::Tensor result(ct::DataType::DT_COMPLEX_DOUBLE, ct::DeviceType::CpuDevice, {count}); + gram_local_into(ld, dim, bands, input, result.data()); + reduce(result.data(), count); + return result; +} + +template +ct::Tensor LinearAlgebra::gram_root_tensor(int ld, int dim, int bands, const T* input) +{ + ModuleBase::timer::Scope function_timer("LinearAlgebra", "gram_root_tensor"); + const int64_t elements = static_cast(bands) * bands; + if (elements > std::numeric_limits::max()) + { + throw std::length_error("Root Gram exceeds the MPI count range."); + } + ct::Tensor result(ct::DataType::DT_COMPLEX_DOUBLE, ct::DeviceType::CpuDevice, {elements}); + const std::size_t local_bytes = comm_.rank == 0 ? 0 : result.buffer().GetAllocatedBytes(); + ModuleBase::Memory::record("LOBPCG::projection_local", local_bytes, false); + gram_local_into(ld, dim, bands, input, result.data()); +#ifdef __MPI + if (comm_.nproc > 1) + { + const int count = elements; + Parallel_Common::reduce_data_to_root(result.data(), count, comm_.comm, 0); + } +#endif + if (comm_.rank != 0) + { + return ct::Tensor(ct::DataType::DT_COMPLEX_DOUBLE, ct::DeviceType::CpuDevice, {0}); + } + return result; +} + +template +void LinearAlgebra::gram_local_into(int ld, int dim, int bands, const T* input, Wide* result) +{ + const bool use_herk = std::is_same::value; + const int64_t elements = static_cast(bands) * bands; + if (dim == 0) + { + std::fill_n(result, elements, Wide(0)); + } + if (dim > 0 && bands > 0) + { + const Wide* wide = reinterpret_cast(input); + if (!std::is_same::value) + { + const int64_t input_elements = static_cast(ld) * bands; + linear_buffer(&left_, input_elements); + Wide* converted = left_.template data(); + // Conversion kernels use int indices, although their wrappers accept size_t. + if (ld == dim && input_elements <= std::numeric_limits::max()) + { + base_device::memory::cast_memory_op()(converted, input, input_elements); + } + else + { + // Padding may be uninitialized; convert only the active rows of each column. + for (int band = 0; band < bands; ++band) + { + const int64_t offset = static_cast(band) * ld; + Wide* destination = converted + offset; + const T* source = input + offset; + base_device::memory::cast_memory_op()(destination, source, dim); + } + } + wide = converted; + } + Wide* products = result; + if (!std::is_same::value) + { + linear_buffer(&products_, elements); + products = products_.template data(); + } + if (use_herk) + { + ModuleBase::gram_herk_cpu(ld, dim, bands, wide, products); + } + else + { + const Wide one(1); + const Wide zero(0); + ModuleBase::gemm_op()('C', 'N', bands, bands, dim, &one, + wide, ld, wide, ld, &zero, products, bands); + } + if (!std::is_same::value) + { + base_device::memory::synchronize_memory_op()( + result, products, elements); + } + } + // HERK leaves the lower triangle untouched. Complete it before reduction; + // empty local partitions retain their initialized zero contribution. + if (use_herk) + { + linear_complete_hermitian_upper(bands, result); + } +} + template void LinearAlgebra::expand(int ld, int dim, int nx, int ny, const T* x, const std::vector& c, T* y, T beta) { @@ -366,6 +602,59 @@ void LinearAlgebra::expand(int ld, int dim, int nx, int ny, const T* ModuleBase::gemm_op()('N', 'N', dim, ny, nx, &one, x, ld, coeff, nx, &beta, y, ld); } +template +const T* LinearAlgebra::prepare_coefficients(const Wide* coefficients, const int64_t count) +{ + ModuleBase::timer::Scope function_timer("LinearAlgebra", "prepare_coefficients"); + if (count == 0) + { + return nullptr; + } + linear_buffer(&coefficients_, count); + T* coeff = coefficients_.template data(); + if (std::is_same::value) + { + const T* input = reinterpret_cast(coefficients); + base_device::memory::synchronize_memory_op()(coeff, input, count); + } + else + { + const ct::DataType type = ct::DataTypeToEnum::value; + ct::Tensor narrow(type, ct::DeviceType::CpuDevice, {count}); + std::copy_n(coefficients, count, narrow.data()); + base_device::memory::synchronize_memory_op()( + coeff, narrow.data(), count); + } + return coeff; +} + +template +void LinearAlgebra::expand_prepared(int ld, int dim, int nx, int ny, const T* x, const T* c, T* y, T beta) +{ + ModuleBase::timer::Scope function_timer("LinearAlgebra", "expand_prepared"); + if (dim == 0 || nx == 0 || ny == 0) + { + return; + } + const T one(1); + ModuleBase::gemm_op()('N', 'N', dim, ny, nx, &one, x, ld, c, nx, &beta, y, ld); +} + +template +std::size_t LinearAlgebra::storage_bytes(const ct::DeviceType device) const +{ + const ct::Tensor* buffers[] = {&products_, &coefficients_, &left_, &right_, &native_products_}; + std::size_t bytes = 0; + for (const ct::Tensor* buffer : buffers) + { + if (buffer->device_type() == device) + { + bytes += buffer->buffer().GetAllocatedBytes(); + } + } + return bytes; +} + template class LinearAlgebra, base_device::DEVICE_CPU>; template class LinearAlgebra, base_device::DEVICE_CPU>; #if defined(__CUDA) || defined(__ROCM) diff --git a/source/source_hsolver/module_linalg/linear_algebra.h b/source/source_hsolver/module_linalg/linear_algebra.h index 9d6620d91b7..96f4952ec3c 100644 --- a/source/source_hsolver/module_linalg/linear_algebra.h +++ b/source/source_hsolver/module_linalg/linear_algebra.h @@ -42,6 +42,11 @@ class LinearSmallLU /** @brief Rank-revealing coefficients for a small Gram matrix, with a norm cutoff. */ std::vector> linear_gram_basis(const std::vector>& gram, int n, double cutoff, int* rank); +/** Complete a column-major host Hermitian matrix from its upper triangle. + * The uncomputed lower triangle is overwritten before any numerical use. + */ +void linear_complete_hermitian_upper(int n, std::complex* matrix); + /** @brief Collective block algebra; only small coefficients cross the device boundary. */ template class LinearAlgebra @@ -56,12 +61,18 @@ class LinearAlgebra ct::Tensor native_products_; void reduce(std::vector* values) const; + void reduce(Wide* values, const int64_t count) const; + void cross_local_into(int ld, int dim, int nx, int ny, const T* x, const T* y, Wide* result); + void gram_local_into(int ld, int dim, int bands, const T* input, Wide* result); public: explicit LinearAlgebra(const diag_comm_info& comm) : comm_(comm) { } + /** Owned reusable storage only; excludes returned vectors and borrowed views. */ + std::size_t storage_bytes(ct::DeviceType device) const; + /** @brief Projection products and reductions in wavefunction precision; return double coefficients. */ std::vector projection_cross(int ld, int dim, int nx, int ny, const T* x, const T* y); @@ -70,15 +81,32 @@ class LinearAlgebra /** @brief Products between corresponding bands and several Arnoldi blocks. */ std::vector dots(int ld, int dim, int bands, int count, int stride, const T* basis, const T* x); + ct::Tensor dots_tensor(int ld, int dim, int bands, int count, int stride, const T* basis, const T* x); /** @brief Global X-adjoint times Y, with double accumulation for both precisions. */ std::vector cross(int ld, int dim, int nx, int ny, const T* x, const T* y); + /** Host Tensor result; uses direct output storage for block projections. */ + ct::Tensor cross_tensor(int ld, int dim, int nx, int ny, const T* x, const T* y); + ct::Tensor cross_root_tensor(int ld, int dim, int nx, int ny, const T* x, const T* y); /** @brief Global X-adjoint times X, reusing one FP64 conversion of the valid rows. */ std::vector gram(int ld, int dim, int bands, const T* input); + ct::Tensor gram_tensor(int ld, int dim, int bands, const T* input); + ct::Tensor gram_root_tensor(int ld, int dim, int bands, const T* input); /** @brief Y = X*C + beta*Y, using a small host coefficient matrix. */ void expand(int ld, int dim, int nx, int ny, const T* x, const std::vector& c, T* y, T beta); + + /** @brief Convert/upload host coefficients once for several block rotations. + * The borrowed Device pointer is invalidated by the next prepare_coefficients() + * or nonempty expand() on this object. expand_prepared() does not invalidate it. + */ + const T* prepare_coefficients(const Wide* coefficients, const int64_t count); + + /** @brief Y = X*C + beta*Y with already prepared Device coefficients (ld C = nx). + * X and Y must not overlap; C must contain at least nx*ny elements. + */ + void expand_prepared(int ld, int dim, int nx, int ny, const T* x, const T* c, T* y, T beta); }; } // namespace hsolver #endif diff --git a/source/source_hsolver/module_linalg/unittests/CMakeLists.txt b/source/source_hsolver/module_linalg/unittests/CMakeLists.txt index ce390e763d5..f0f36f9c656 100644 --- a/source/source_hsolver/module_linalg/unittests/CMakeLists.txt +++ b/source/source_hsolver/module_linalg/unittests/CMakeLists.txt @@ -21,7 +21,8 @@ addtest( TARGET MODULE_HSOLVER_linalg LIBS parameter base device container SOURCES test_hsolver_linear.cpp test_cn_subspace.cpp test_linear_low_rank.cpp - test_orthonormal.cpp test_exp_action.cpp ${LINALG_TEST_SOURCES}) + test_orthonormal.cpp test_exp_action.cpp test_linear_algebra.cpp + ${LINALG_TEST_SOURCES}) if(ENABLE_MPI) add_test( NAME MODULE_HSOLVER_linalg_parallel diff --git a/source/source_hsolver/module_linalg/unittests/test_linear_algebra.cpp b/source/source_hsolver/module_linalg/unittests/test_linear_algebra.cpp new file mode 100644 index 00000000000..111b46a772a --- /dev/null +++ b/source/source_hsolver/module_linalg/unittests/test_linear_algebra.cpp @@ -0,0 +1,385 @@ +#include "source_hsolver/module_linalg/linear_algebra.h" +#include "source_base/parallel_cell.h" +#include "source_base/parallel_device.h" +#include "source_base/kernels/math_kernel_op.h" +#include +#include +#include +#include +#include +#include +#include + +namespace +{ +using Wide = std::complex; +#if defined(__CUDA) || defined(__ROCM) +using Device = base_device::DEVICE_GPU; +#else +using Device = base_device::DEVICE_CPU; +#endif + +hsolver::diag_comm_info local_comm() +{ +#ifdef __MPI + return hsolver::diag_comm_info(MPI_COMM_SELF, 0, 1); +#else + return hsolver::diag_comm_info(0, 1); +#endif +} + +template +ct::Tensor upload(const std::vector& values) +{ + const ct::DataType type = ct::DataTypeToEnum::value; + const ct::DeviceType device = ct::DeviceTypeToEnum::value; + const int count = values.size(); + ct::Tensor result(type, device, {count}); + base_device::memory::synchronize_memory_op()( + result.data(), values.data(), count); + return result; +} + +template +void check_output(const ct::Tensor& output, const std::vector& expected) +{ + std::vector actual(expected.size()); + base_device::memory::synchronize_memory_op()( + actual.data(), output.template data(), actual.size()); + const double tolerance = sizeof(T) == sizeof(std::complex) ? 2e-6 : 1e-12; + for (std::size_t i = 0; i < actual.size(); ++i) + { + EXPECT_LT(std::abs(actual[i] - expected[i]), tolerance); + } +} + +template +Wide overlap(const int rows, const T* x, const T* y) +{ + Wide result(0); + for (int k = 0; k < rows; ++k) { result += std::conj(Wide(x[k])) * Wide(y[k]); } + return result; +} + +template +void check_prepared_coefficients() +{ + const int dim = 5; + const int ld = 7; + const int nx = 3; + const int ny = 2; + const hsolver::diag_comm_info comm = local_comm(); + hsolver::LinearAlgebra algebra(comm); + std::vector coefficients = {{0.7, -0.2}, {0.1, 0.3}, {-0.4, 0.5}, + {0.2, 0.4}, {-0.3, 0.1}, {0.6, -0.2}}; + std::vector transient(coefficients); + const int64_t count = transient.size(); + const T* prepared = algebra.prepare_coefficients(transient.data(), count); + // Exercise coefficient ownership by releasing the source before rotation. + std::fill(transient.begin(), transient.end(), Wide(999, -999)); + transient.clear(); + transient.shrink_to_fit(); + for (int image = 0; image < 2; ++image) + { + std::vector x(ld * nx, T(77, 9)); + std::vector expected(ld * ny, T(-3, 4)); + for (int j = 0; j < nx; ++j) + { + for (int row = 0; row < dim; ++row) + { + x[row + j * ld] = T(0.1 * (row + image + 1), 0.2 * (j - row)); + } + } + ct::Tensor input = upload(x); + ct::Tensor output = upload(expected); + const T beta(0.2, -0.1); + algebra.expand_prepared(ld, dim, nx, ny, input.template data(), prepared, output.template data(), beta); + for (int j = 0; j < ny; ++j) + { + for (int row = 0; row < dim; ++row) + { + T value = beta * expected[row + j * ld]; + for (int k = 0; k < nx; ++k) + { + value += x[row + k * ld] * T(coefficients[k + j * nx]); + } + expected[row + j * ld] = value; + } + } + check_output(output, expected); + // The prepared coefficients remain usable across zero-sized operations. + algebra.expand_prepared(ld, 0, nx, ny, nullptr, nullptr, nullptr, beta); + } + EXPECT_EQ(algebra.prepare_coefficients(nullptr, 0), nullptr); +} + +TEST(LinearAlgebra, ReusePreparedCoefficients) +{ + check_prepared_coefficients, Device>(); + check_prepared_coefficients, Device>(); +} + +template +void check_padded_products() +{ + const int dim = 5; + const int ld = 8; + const int nx = 3; + const int ny = 2; + const hsolver::diag_comm_info comm = local_comm(); + hsolver::LinearAlgebra algebra(comm); + const double nan = std::numeric_limits::quiet_NaN(); + const T padding(nan, nan); + std::vector x(ld * nx, padding); + std::vector y(ld * ny, padding); + for (int j = 0; j < nx; ++j) + { + for (int i = 0; i < dim; ++i) + { + x[i + j * ld] = T(0.2 * (i + 1), 0.3 * (j - i)); + } + } + for (int j = 0; j < ny; ++j) + { + for (int i = 0; i < dim; ++i) + { + y[i + j * ld] = T(0.3 * (j + i), -0.2 * (i + 2)); + } + } + ct::Tensor dx = upload(x); + ct::Tensor dy = upload(y); + const ct::Tensor gram_tensor = algebra.gram_tensor(ld, dim, nx, dx.template data()); + const ct::Tensor cross_tensor = algebra.cross_tensor(ld, dim, nx, ny, dx.template data(), dy.template data()); + ASSERT_EQ(gram_tensor.device_type(), ct::DeviceType::CpuDevice); + ASSERT_EQ(cross_tensor.data_type(), ct::DataType::DT_COMPLEX_DOUBLE); + for (int j = 0; j < nx; ++j) + { + for (int i = 0; i < nx; ++i) + { + const Wide expected = overlap(dim, x.data() + i * ld, x.data() + j * ld); + EXPECT_LT(std::abs(gram_tensor.template data()[i + j * nx] - expected), 1e-12); + } + } + for (int j = 0; j < ny; ++j) + { + for (int i = 0; i < nx; ++i) + { + const Wide expected = overlap(dim, x.data() + i * ld, y.data() + j * ld); + EXPECT_LT(std::abs(cross_tensor.template data()[i + j * nx] - expected), 1e-12); + } + } + // Empty local partitions contribute a zero matrix with nx*ny entries. + const ct::Tensor empty = algebra.cross_tensor(ld, 0, nx, ny, nullptr, nullptr); + ASSERT_EQ(empty.NumElements(), nx * ny); + for (int i = 0; i < nx * ny; ++i) + { + EXPECT_EQ(empty.template data()[i], Wide(0)); + } +} + +TEST(LinearAlgebra, PaddedGramAndCross) +{ + check_padded_products, Device>(); + check_padded_products, Device>(); +} + +TEST(LinearAlgebra, RootProjectionWithEmptyLocalRows) +{ + const ModuleBase::CommunicationDomain domain = ModuleBase::world_comm_domain(); + const int rank = domain.rank(); + const int ranks = domain.size(); +#ifdef __MPI + const MPI_Comm communicator = domain.communicator(); + const hsolver::diag_comm_info comm(communicator, rank, ranks); +#else + const hsolver::diag_comm_info comm(0, 1); +#endif + const int rows = rank == ranks - 1 ? 3 : 0; + const int ld = 5; + const int columns = 2; + const double nan = std::numeric_limits::quiet_NaN(); + std::vector x(ld * columns, Wide(nan, nan)); + for (int j = 0; j < columns; ++j) + { + for (int i = 0; i < rows; ++i) + { + x[i + j * ld] = Wide(i + 1, j + 1); + } + } + hsolver::LinearAlgebra algebra(comm); + const ct::Tensor input = upload(x); + const Wide* data = input.data(); + const ct::Tensor cross = algebra.cross_root_tensor(ld, rows, columns, columns, data, data); + const ct::Tensor gram = algebra.gram_root_tensor(ld, rows, columns, data); + if (rank != 0) + { + EXPECT_EQ(cross.NumElements(), 0); + EXPECT_EQ(gram.NumElements(), 0); + EXPECT_EQ(cross.buffer().GetAllocatedBytes(), 0U); + EXPECT_EQ(gram.buffer().GetAllocatedBytes(), 0U); + return; + } + ASSERT_EQ(cross.NumElements(), 4); + ASSERT_EQ(gram.NumElements(), 4); + for (int j = 0; j < columns; ++j) + { + for (int i = 0; i < columns; ++i) + { + Wide expected(0); + for (int k = 0; k < 3; ++k) + { + expected += std::conj(Wide(k + 1, i + 1)) * Wide(k + 1, j + 1); + } + EXPECT_NEAR(std::abs(cross.data()[i + j * columns] - expected), 0.0, 1e-12); + EXPECT_NEAR(std::abs(gram.data()[i + j * columns] - expected), 0.0, 1e-12); + } + } +} + +#ifdef __MPI +TEST(LinearAlgebra, RootReductionSupportsOtherRootAndSelfCommunicator) +{ + const ModuleBase::CommunicationDomain domain = ModuleBase::world_comm_domain(); + const MPI_Comm communicator = domain.communicator(); + const int rank = domain.rank(); + const int size = domain.size(); + const int root = size - 1; + Wide value(rank + 1, -rank); + const Wide before = value; + Parallel_Common::reduce_data_to_root(&value, 1, communicator, root); + if (rank == root) + { + const Wide expected(size * (size + 1) / 2.0, -size * (size - 1) / 2.0); + EXPECT_EQ(value, expected); + } + else + { + EXPECT_EQ(value, before); + } + const hsolver::diag_comm_info self = local_comm(); + value = before; + Parallel_Common::reduce_data_to_root(&value, 1, self.comm, 0); + EXPECT_EQ(value, before); + Parallel_Common::reduce_data_to_root(&value, 0, communicator, root); + EXPECT_EQ(value, before); +} +#endif + +#if !defined(__CUDA) && !defined(__ROCM) +TEST(LinearAlgebra, HerkUpperTriangle) +{ + const int rows = 3; + const int ld = 5; + const int bands = 2; + const double nan = std::numeric_limits::quiet_NaN(); + std::vector x(ld * bands, Wide(nan, nan)); + for (int j = 0; j < bands; ++j) + { + for (int i = 0; i < rows; ++i) { x[i + j * ld] = Wide(i + 1, j - i); } + } + std::vector gram(bands * bands, Wide(nan, nan)); + ModuleBase::gram_herk_cpu(ld, rows, bands, x.data(), gram.data()); + EXPECT_TRUE(std::isnan(gram[1].real())); + EXPECT_EQ(gram[0].imag(), 0.0); + EXPECT_EQ(gram[3].imag(), 0.0); + hsolver::linear_complete_hermitian_upper(bands, gram.data()); + for (int j = 0; j < bands; ++j) + { + for (int i = 0; i < bands; ++i) + { + const Wide expected = overlap(rows, x.data() + i * ld, x.data() + j * ld); + EXPECT_LT(std::abs(gram[i + j * bands] - expected), 1e-12); + } + } +} +#endif + +template +void verify_triangular_apply(const char side, const char uplo, const char trans, const char diag, const T alpha) +{ + SCOPED_TRACE(::testing::Message() << side << uplo << trans << diag << " alpha=" << alpha); + const int m = 7; + const int n = 4; + const int ldb = 10; + const int order = side == 'L' ? m : n; + const int lda = order + 2; + const T poison(73, -41); + const double nan = std::numeric_limits::quiet_NaN(); + std::vector triangle(lda * order, T(nan, nan)); + std::vector dense(order * order, Wide(0)); + for (int j = 0; j < order; ++j) + { + for (int i = 0; i < order; ++i) + { + if (diag == 'U' && i == j) + { + dense[i + j * order] = 1; // The stored unit diagonal stays NaN. + } + else if ((uplo == 'U' && i <= j) || (uplo == 'L' && i >= j)) + { + const T value(0.1 * (i + 1), 0.05 * (j - i)); + triangle[i + j * lda] = value; + dense[i + j * order] = Wide(value); + } + } + } + std::vector input(ldb * n, poison); + for (int j = 0; j < n; ++j) + { + for (int i = 0; i < m; ++i) + { + input[i + j * ldb] = T(0.1 * (i + j + 1), 0.07 * (i - j)); + } + } + std::vector expected(input); + for (int j = 0; j < n; ++j) + { + for (int i = 0; i < m; ++i) + { + Wide sum(0); + for (int k = 0; k < order; ++k) + { + const int row = side == 'L' ? i : k; + const int column = side == 'L' ? k : j; + const Wide value = trans == 'N' ? dense[row + column * order] : dense[column + row * order]; + const Wide factor = trans == 'C' ? std::conj(value) : value; + sum += side == 'L' ? factor * Wide(input[k + j * ldb]) + : Wide(input[i + k * ldb]) * factor; + } + expected[i + j * ldb] = T(Wide(alpha) * sum); + } + } + ct::Tensor a = upload(triangle); + ct::Tensor b = upload(input); + ModuleBase::trmm_op()(side, uplo, trans, diag, m, n, &alpha, + a.template data(), lda, b.template data(), ldb); + check_output(b, expected); +} + + +TEST(LinearAlgebra, TriangularProducts) +{ + // side/uplo/trans/diag: exercise both sides and triangles, transpose and unit diagonal. + for (const std::string mode : {"RUNN", "RUCN", "RUTU", "RLNN", "LUNU", "LLCN"}) + { + const char side = mode[0]; + const char uplo = mode[1]; + const char trans = mode[2]; + const char diag = mode[3]; + const Wide alpha(.7, -.2); + const std::complex alpha_float(alpha); + verify_triangular_apply(side, uplo, trans, diag, alpha); + verify_triangular_apply, Device>(side, uplo, trans, diag, alpha_float); + } +} + +TEST(LinearAlgebra, TriangularZeroScaleAndEmptyMatrices) +{ + const Wide zero(0); + const std::complex zero_float(0); + verify_triangular_apply('R', 'U', 'N', 'N', zero); + verify_triangular_apply, Device>('R', 'U', 'N', 'N', zero_float); + ModuleBase::trmm_op()('R', 'U', 'N', 'N', 0, 4, nullptr, nullptr, 4, nullptr, 10); + ModuleBase::trmm_op()('R', 'U', 'N', 'N', 7, 0, nullptr, nullptr, 1, nullptr, 10); +} +} // namespace diff --git a/source/source_hsolver/unittests/CMakeLists.txt b/source/source_hsolver/unittests/CMakeLists.txt index 8403099a87b..fc23dfdcf42 100644 --- a/source/source_hsolver/unittests/CMakeLists.txt +++ b/source/source_hsolver/unittests/CMakeLists.txt @@ -23,7 +23,40 @@ if(ENABLE_MPI) set_tests_properties(MODULE_HSOLVER_dav_subspace_parallel PROPERTIES PROCESSORS 2 TIMEOUT 120) endif() +set(LOBPCG_TEST_SOURCES + ../diago_lobpcg.cpp + ../lobpcg_subspace.cpp + ../lobpcg_recovery.cpp + ../dense_eigensolver.cpp + ../module_linalg/linear_algebra.cpp + ../../source_basis/module_pw/test/test_tool.cpp) +addtest( + TARGET MODULE_HSOLVER_lobpcg + LIBS parameter base psi device container + SOURCES test_diago_lobpcg.cpp test_dense_eigensolver.cpp ${LOBPCG_TEST_SOURCES}) +set_tests_properties(MODULE_HSOLVER_lobpcg PROPERTIES TIMEOUT 180) +if(ENABLE_MPI) + add_test(NAME MODULE_HSOLVER_lobpcg_mpi2 + COMMAND ${MPIEXEC_EXECUTABLE} ${MPIEXEC_NUMPROC_FLAG} 2 ${MPIEXEC_PREFLAGS} + $ ${MPIEXEC_POSTFLAGS}) + set_tests_properties(MODULE_HSOLVER_lobpcg_mpi2 PROPERTIES PROCESSORS 2 TIMEOUT 180) +endif() + if(USE_CUDA OR USE_ROCM) + addtest( + TARGET MODULE_HSOLVER_lobpcg_gpu + KEEP_FEATURE_DEFINITIONS __CUDA __ROCM + LIBS parameter base psi device container + SOURCES test_diago_lobpcg.cpp ${LOBPCG_TEST_SOURCES} test_dense_eigensolver.cpp + ../module_linalg/unittests/test_linear_algebra.cpp) + set_tests_properties(MODULE_HSOLVER_lobpcg_gpu PROPERTIES SKIP_RETURN_CODE 77) + if(ENABLE_MPI) + add_test(NAME MODULE_HSOLVER_lobpcg_gpu_mpi2 + COMMAND ${MPIEXEC_EXECUTABLE} ${MPIEXEC_NUMPROC_FLAG} 2 ${MPIEXEC_PREFLAGS} + $ ${MPIEXEC_POSTFLAGS}) + set_tests_properties(MODULE_HSOLVER_lobpcg_gpu_mpi2 PROPERTIES + PROCESSORS 2 TIMEOUT 180 SKIP_RETURN_CODE 77) + endif() AddTest( TARGET MODULE_HSOLVER_dav_subspace_gpu LIBS ${DAV_SUBSPACE_TEST_LIBS} @@ -97,6 +130,12 @@ if(ENABLE_MPI) ../hsolver_lcaopw.cpp ../diago_bpcg.cpp ../diago_dav_subspace.cpp + ../diago_lobpcg.cpp + ../lobpcg_subspace.cpp + ../lobpcg_recovery.cpp + ../dense_eigensolver.cpp + ../diago_params.cpp + ../module_linalg/linear_algebra.cpp ../diag_const_nums.cpp ../diago_iter_assist.cpp ../para_lin_tf.cpp diff --git a/source/source_hsolver/unittests/test_dense_eigensolver.cpp b/source/source_hsolver/unittests/test_dense_eigensolver.cpp new file mode 100644 index 00000000000..84ce422ec3b --- /dev/null +++ b/source/source_hsolver/unittests/test_dense_eigensolver.cpp @@ -0,0 +1,261 @@ +#include "source_hsolver/dense_eigensolver.h" +#include "source_base/parallel_cell.h" +#include +#include +#include +#include +#include +#include + +namespace +{ +using Z = std::complex; + +// Column-major H/S with the exact generalized spectrum 1,...,n. +struct Pencil +{ + int n; + std::vector h; + std::vector s; + std::vector exact; + std::vector values; + std::vector vectors; + + explicit Pencil(const int dimension) : n(dimension) + { + h.resize(n * n); + s.resize(n * n); + exact.resize(n); + values.resize(n); + vectors.resize(n * n); + for (int i = 0; i < n; ++i) + { + s[i + i * n] = 2.0; + h[i + i * n] = 2.0 * (i + 1); + exact[i] = i + 1; + } + } +}; + +// Check against the preserved input matrices using explicit host sums. +void check_pairs(const Pencil& input, const Pencil& output, const int wanted) +{ + EXPECT_EQ(output.h, input.h); + EXPECT_EQ(output.s, input.s); + const int n = input.n; + std::vector sx(n * wanted); + for (int j = 0; j < wanted; ++j) + { + EXPECT_NEAR(output.values[j], input.exact[j], 2e-12); + for (int i = 0; i < n; ++i) + { + Z hx(0); + for (int k = 0; k < n; ++k) + { + hx += input.h[i + k * n] * output.vectors[k + j * n]; + sx[i + j * n] += input.s[i + k * n] * output.vectors[k + j * n]; + } + EXPECT_LT(std::abs(hx - output.values[j] * sx[i + j * n]), 2e-10); + } + for (int i = 0; i < wanted; ++i) + { + Z overlap(0); + for (int k = 0; k < n; ++k) + { + overlap += std::conj(output.vectors[k + i * n]) * sx[k + j * n]; + } + const double identity = i == j ? 1 : 0; + EXPECT_LT(std::abs(overlap - identity), 2e-10); + } + } +} + +// H=F diag(2*lambda) F^H, S=2I, with unitary Fourier F. +Pencil clustered_pencil() +{ + Pencil p(16); + std::fill(p.h.begin(), p.h.end(), Z(0)); + for (int k = 0; k < p.n; ++k) + { + p.exact[k] = k / 4; + for (int j = 0; j < p.n; ++j) + { + for (int i = 0; i < p.n; ++i) + { + const double phase = 2 * std::acos(-1.0) * (i - j) * k / p.n; + p.h[i + j * p.n] += 2 * p.exact[k] * Z(std::cos(phase), std::sin(phase)) / double(p.n); + } + } + } + return p; +} + +#if !defined(__CUDA) && !defined(__ROCM) +void solve_serial(hsolver::dense::SerialGvWorkspace& solver, Pencil& p, const int wanted) +{ + const Pencil input(p); + ASSERT_EQ(solver.solve(p.h.data(), p.s.data(), p.n, wanted, p.values.data(), p.vectors.data()), 0); + check_pairs(input, p, wanted); +} + +TEST(SerialDenseEigensolver, PartialAndFullSpectrum) +{ + hsolver::dense::SerialGvWorkspace solver; + Pencil p = clustered_pencil(); + solve_serial(solver, p, 6); + solve_serial(solver, p, p.n); +} + +TEST(SerialDenseEigensolver, ReusesWorkspace) +{ + hsolver::dense::SerialGvWorkspace solver; + Pencil p(16); + solve_serial(solver, p, 6); + const std::size_t capacity = solver.storage_bytes(); + solve_serial(solver, p, 6); + EXPECT_EQ(solver.storage_bytes(), capacity); + Pencil smaller(4); + solve_serial(solver, smaller, 2); + EXPECT_EQ(solver.storage_bytes(), capacity); +} + +TEST(SerialDenseEigensolver, InvalidMetricAndRetry) +{ + hsolver::dense::SerialGvWorkspace solver; + Pencil p(4); + p.s[0] = -1; + EXPECT_GT(solver.solve(p.h.data(), p.s.data(), p.n, 2, p.values.data(), p.vectors.data()), p.n); + EXPECT_EQ(p.s[0], Z(-1)); + p.s[0] = 2; + solve_serial(solver, p, 2); +} + +#ifdef __MPI +void solve_parallel(hsolver::dense::ParallelDenseEigensolver& solver, Pencil& p, const int wanted, + const MPI_Comm comm, const int block) +{ + const Pencil input(p); + solver.solve_generalized(p.h.data(), p.s.data(), p.n, wanted, + p.values.data(), p.vectors.data(), comm, block); + ModuleBase::CommunicationDomain domain; + domain.initialize(comm); + if (domain.rank() == 0) { check_pairs(input, p, wanted); } +} + +TEST(ParallelDenseEigensolver, PartialAndFullClusteredSpectrum) +{ + hsolver::dense::ParallelDenseEigensolver solver; + Pencil p = clustered_pencil(); + solve_parallel(solver, p, 6, MPI_COMM_WORLD, 4); // Cuts a fourfold cluster. + solve_parallel(solver, p, p.n, MPI_COMM_WORLD, 4); +} + +TEST(ParallelDenseEigensolver, FullyDegenerateGeneralizedSpectrum) +{ + Pencil p(16); + // A positive, nondiagonal S; H=2.5S gives a fully degenerate spectrum. + for (int i = 1; i < p.n; ++i) + { + p.s[i - 1 + i * p.n] = Z(.2, .1); + p.s[i + (i - 1) * p.n] = Z(.2, -.1); + } + for (int i = 0; i < p.n * p.n; ++i) { p.h[i] = 2.5 * p.s[i]; } + p.exact.assign(p.n, 2.5); + hsolver::dense::ParallelDenseEigensolver solver; + solve_parallel(solver, p, 6, MPI_COMM_WORLD, 4); + solve_parallel(solver, p, p.n, MPI_COMM_WORLD, 4); +} + +TEST(ParallelDenseEigensolver, WorkspaceGrowthAndReuse) +{ + hsolver::dense::ParallelDenseEigensolver solver; + Pencil p(16); + solve_parallel(solver, p, 6, MPI_COMM_WORLD, 4); + const std::size_t capacity = solver.storage_bytes(); + solve_parallel(solver, p, 6, MPI_COMM_WORLD, 4); + EXPECT_EQ(solver.storage_bytes(), capacity); + Pencil larger(32); + solve_parallel(solver, larger, 12, MPI_COMM_WORLD, 4); + EXPECT_GE(solver.storage_bytes(), capacity); + Pencil tiny(1); + solve_parallel(solver, tiny, 1, MPI_COMM_WORLD, 4); +} + +TEST(ParallelDenseEigensolver, RebindsCommunicator) +{ + hsolver::dense::ParallelDenseEigensolver solver; + Pencil p(16); + solve_parallel(solver, p, 6, MPI_COMM_WORLD, 4); + solve_parallel(solver, p, 6, MPI_COMM_SELF, 4); + solve_parallel(solver, p, 6, MPI_COMM_WORLD, 4); +} + +TEST(ParallelDenseEigensolver, InvalidMetricAndRetry) +{ + hsolver::dense::ParallelDenseEigensolver solver; + Pencil p(16); + p.s[0] = -1; + EXPECT_THROW(solver.solve_generalized(p.h.data(), p.s.data(), p.n, 6, + p.values.data(), p.vectors.data(), MPI_COMM_WORLD, 4), std::runtime_error); + EXPECT_EQ(p.s[0], Z(-1)); + p.s[0] = 2; + solve_parallel(solver, p, 6, MPI_COMM_WORLD, 4); +} +#endif +#endif + +#ifdef __CUDA +void solve_gpu(hsolver::dense::GpuDenseEigensolver& solver, Pencil& p, const int wanted) +{ + const Pencil input(p); + ASSERT_TRUE(solver.solve_generalized(p.h.data(), p.s.data(), p.n, wanted, + p.values.data(), p.vectors.data())); + check_pairs(input, p, wanted); +} + +TEST(GpuDenseEigensolver, PartialAndFullClusteredSpectrum) +{ + hsolver::dense::GpuDenseEigensolver solver; + Pencil p = clustered_pencil(); + solve_gpu(solver, p, 6); + solve_gpu(solver, p, p.n); +} + +TEST(GpuDenseEigensolver, WorkspaceGrowthAndReuse) +{ + hsolver::dense::GpuDenseEigensolver solver; + Pencil p(16); + solve_gpu(solver, p, 6); + const std::size_t capacity = solver.storage_bytes(); + solve_gpu(solver, p, 6); + EXPECT_EQ(solver.storage_bytes(), capacity); + solve_gpu(solver, p, 8); + Pencil larger(32); + solve_gpu(solver, larger, 12); + EXPECT_GE(solver.storage_bytes(), capacity); + const std::size_t grown = solver.storage_bytes(); + solve_gpu(solver, larger, 12); + EXPECT_EQ(solver.storage_bytes(), grown); +} + +TEST(GpuDenseEigensolver, SingleEigenpair) +{ + hsolver::dense::GpuDenseEigensolver solver; + Pencil p(1); + solve_gpu(solver, p, 1); +} + +TEST(GpuDenseEigensolver, InvalidMetricAndRetry) +{ + hsolver::dense::GpuDenseEigensolver solver; + Pencil p(16); + solve_gpu(solver, p, 6); + p.s[0] = -1; + EXPECT_FALSE(solver.solve_generalized(p.h.data(), p.s.data(), p.n, 6, + p.values.data(), p.vectors.data())); + EXPECT_EQ(p.s[0], Z(-1)); + p.s[0] = 2; + solve_gpu(solver, p, 6); +} +#endif +} // namespace diff --git a/source/source_hsolver/unittests/test_diago_lobpcg.cpp b/source/source_hsolver/unittests/test_diago_lobpcg.cpp new file mode 100644 index 00000000000..c1d18ced44b --- /dev/null +++ b/source/source_hsolver/unittests/test_diago_lobpcg.cpp @@ -0,0 +1,743 @@ +#include "source_hsolver/diago_lobpcg.h" +#include "source_hsolver/dense_eigensolver.h" +#include "source_base/module_container/base/third_party/lapack.h" +#include "source_base/module_device/device.h" +#include "source_base/kernels/math_kernel_op.h" +#include "source_base/parallel_cell.h" +#include "source_base/parallel_comm.h" +#include "source_base/parallel_device.h" +#include "source_basis/module_pw/test/test_tool.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace +{ +using Z = std::complex; +using Locking = hsolver::LobpcgLocking; +#if defined(__CUDA) || defined(__ROCM) +using Device = base_device::DEVICE_GPU; +#else +using Device = base_device::DEVICE_CPU; +#endif +const ct::DeviceType device = ct::DeviceTypeToEnum::value; +class Lobpcg : public ::testing::TestWithParam {}; + +hsolver::diag_comm_info comm_info() +{ + const ModuleBase::CommunicationDomain world = ModuleBase::world_comm_domain(); +#ifdef __MPI + return {POOL_WORLD, world.rank(), world.size()}; +#else + return {0, 1}; +#endif +} + +template +void sum(T* values, const int count) +{ +#ifdef __MPI + const hsolver::diag_comm_info comm = comm_info(); + Parallel_Common::reduce_data(values, count, comm.comm); +#endif +} + +template +void upload(T* destination, const std::vector& source) +{ + base_device::memory::synchronize_memory_op()( + destination, source.data(), source.size()); +} + +template +std::vector download(const T* source, const int count) +{ + std::vector result(count); + base_device::memory::synchronize_memory_op()( + result.data(), source, count); + return result; +} + +struct Options +{ + int n = 80; + int bands = 6; + int extra = 0; + int npol = 1; + int backend = 0; + bool overlap = true; +}; + +// Small H/S matrices applied on host, with distributed rows and CPU/GPU vector storage. +template +class Problem : public hsolver::HSOperator +{ + public: + using Real = typename GetTypeReal::type; + using Solver = hsolver::DiagoLOBPCG; + Options options; + hsolver::diag_comm_info comm; + int first; + int npw; + int stride; + int dim; + std::vector h; + std::vector s; + std::vector reference_vectors; + std::vector reference_values; + std::vector input; + std::vector prec; + std::vector eigenvalues; + ct::Tensor psi; + hsolver::dense::ParallelDenseEigensolver parallel; + hsolver::dense::GpuDenseEigensolver gpu; + std::unique_ptr solver; + mutable int h_calls = 0; + mutable int s_calls = 0; + + Problem(const Options& configuration, const Locking locking, const hsolver::diag_comm_info& domain) + : options(configuration), comm(domain) + { + const int n = options.n; + int local = n / comm.nproc; + first = comm.rank * local; + npw = local / options.npol; + stride = npw + 3; + dim = options.npol * stride; + h.assign(n * n, Z(0)); + s.assign(n * n, Z(0)); + std::vector l(n * n, Z(0)); + for (int j = 0; j < n; ++j) + { + l[j + j * n] = 0.8 + 0.015 * j; + for (int i = 0; i < j; ++i) + { + l[i + j * n] = Z(0.08 * std::sin(i + 2 * j), 0.06 * std::cos(2 * i + j)); + } + } + for (int j = 0; j < n; ++j) + { + for (int i = 0; i < n; ++i) + { + for (int k = 0; k < n; ++k) + { + const double energy = k + 1.0; + const Z product = std::conj(l[k + i * n]) * l[k + j * n]; + h[i + j * n] += energy * product; + s[i + j * n] += product; + } + if (!options.overlap) { s[i + j * n] = i == j ? 1 : 0; } + } + } + reference_vectors = h; + std::vector metric(s); + reference_values.resize(n); + const int lwork = 2 * n; + std::vector work(lwork); + std::vector real_work(3 * n); + int info = 0; + ct::lapackConnector::hegv(1, 'V', 'U', n, reference_vectors.data(), n, metric.data(), n, + reference_values.data(), work.data(), lwork, real_work.data(), info); + EXPECT_EQ(info, 0); + input.assign(dim * options.bands, T(7, 9)); // Deliberately dirty input padding. + for (int j = 0; j < options.bands; ++j) + { + for (int row = 0; row < dim; ++row) + { + if (!physical(row)) { continue; } + const int global = global_row(row); + Z value(std::sin(0.17 * (global + 1) * (j + 2)), + 0.3 * std::cos(0.11 * (global + 3) * (j + 1))); + input[row + j * dim] = static_cast(value); + } + } + const ct::DataType type = ct::DataTypeToEnum::value; + psi = ct::Tensor(type, device, {dim, options.bands}); + prec.assign(dim, 1); + eigenvalues.resize(options.bands); + const int block = options.bands + options.extra; + const hsolver::LobpcgBasisLayout layout = {npw, options.npol}; + solver.reset(new Solver(prec.data(), options.bands, dim, block, layout, comm, + options.backend, 2, options.overlap, locking, parallel, gpu)); + upload(psi.data(), input); + } + + void diagonal_problem() + { + const int n = options.n; + std::fill(h.begin(), h.end(), Z(0)); + std::fill(s.begin(), s.end(), Z(0)); + std::fill(reference_vectors.begin(), reference_vectors.end(), Z(0)); + for (int i = 0; i < n; ++i) + { + const double metric = options.overlap ? 1 + .05 * i : 1; + s[i + i * n] = metric; + h[i + i * n] = (i + 1) * metric; + reference_values[i] = i + 1; + reference_vectors[i + i * n] = 1 / std::sqrt(metric); + } + } + void exact_initial(const int bands) + { + for (int j = 0; j < bands; ++j) + { + for (int row = 0; row < dim; ++row) + { + if (physical(row)) { input[row + j * dim] = T(reference_vectors[global_row(row) + j * options.n]); } + } + } + upload(psi.data(), input); + } + bool physical(const int row) const { return row % stride < npw; } + int global_row(const int row) const { return first + row / stride * npw + row % stride; } + void update_k(const int) override {} + void hpsi(const T* x, T* y, const int ld, const int count) const override + { + ++h_calls; + apply(h, x, y, ld, count); + } + void spsi(const T* x, T* y, const int ld, const int count) const override + { + ++s_calls; + apply(s, x, y, ld, count); + } + void apply(const std::vector& matrix, const T* x, T* y, const int ld, const int count) const + { + const int elements = ld * count; + const std::vector local = download(x, elements); + std::vector output(elements, T(91, -13)); // Sentinel padding outside physical rows. + for (int band = 0; band < count; ++band) + { + std::vector full(options.n, Z(0)); + for (int row = 0; row < dim; ++row) + { + if (physical(row)) { full[global_row(row)] = local[row + band * ld]; } + else { EXPECT_EQ(local[row + band * ld], T(0)); } + } + sum(full.data(), options.n); + for (int row = 0; row < dim; ++row) + { + if (!physical(row)) { continue; } + Z value(0); + for (int k = 0; k < options.n; ++k) + { + value += matrix[global_row(row) + k * options.n] * full[k]; + } + output[row + band * ld] = static_cast(value); + } + } + upload(y, output); + } + bool solve(const double tolerance, const int budget, const std::vector& thresholds) + { + return solver->diag(*this, psi.data(), dim, eigenvalues.data(), tolerance, budget, thresholds); + } + // Check reference eigenvalues and the physical S Gram independently of solver projections. + void check(const bool converged, const double eig_tol, const double gram_tol) + { + const std::vector x = download(psi.data(), dim * options.bands); + std::vector full(options.n * options.bands, Z(0)); + for (int j = 0; j < options.bands; ++j) + { + for (int row = 0; row < dim; ++row) + { + if (physical(row)) { full[global_row(row) + j * options.n] = x[row + j * dim]; } + else { EXPECT_EQ(x[row + j * dim], T(0)); } + } + } + const int count = full.size(); + sum(full.data(), count); + std::vector sx(count, Z(0)); + for (int j = 0; j < options.bands; ++j) + { + for (int i = 0; i < options.n; ++i) + { + for (int k = 0; k < options.n; ++k) + { + sx[i + j * options.n] += s[i + k * options.n] * full[k + j * options.n]; + } + } + EXPECT_TRUE(std::isfinite(eigenvalues[j])); + if (converged) + { + EXPECT_NEAR(eigenvalues[j], reference_values[j], eig_tol); + } + for (int k = 0; k < options.bands; ++k) + { + Z gram(0); + for (int i = 0; i < options.n; ++i) + { + gram += std::conj(full[i + k * options.n]) * sx[i + j * options.n]; + } + const Z expected = k == j ? Z(1) : Z(0); + EXPECT_LT(std::abs(gram - expected), gram_tol); + } + } + } +}; + +template +void check_case(const Options& options, const Locking locking) +{ + Problem p(options, locking, comm_info()); + const bool single = std::is_same>::value; + const double tolerance = single ? 1e-7 : 1e-13; + const bool converged = p.solve(tolerance, 250, {}); + EXPECT_TRUE(converged); + const double eig_tol = single ? 2e-4 : 1e-8; + const double gram_tol = single ? 2e-5 : 1e-8; + p.check(converged, eig_tol, gram_tol); + if (options.overlap) { EXPECT_GT(p.s_calls, 0); } + else { EXPECT_EQ(p.s_calls, 0); } + const bool gpu_rr = device == ct::DeviceType::GpuDevice && hsolver::dense::GpuDenseEigensolver::available() + && p.comm.rank == 0 && options.backend == 0; + if (gpu_rr) { EXPECT_GT(p.gpu.storage_bytes(), 0U); } + else { EXPECT_EQ(p.gpu.storage_bytes(), 0U); } +} + +template +void check_eigenpair_identity(const Locking locking) +{ + Options o; + o.n = 40; + o.bands = 4; + o.npol = 1; + Problem p(o, locking, comm_info()); + p.diagonal_problem(); + const bool single = std::is_same>::value; + const double tolerance = single ? 1e-5 : 1e-11; + ASSERT_TRUE(p.solve(tolerance, 250, {})); + EXPECT_GT(p.solver->iterations(), 0); // Exercise the iterative solve path. + const double eig_tol = single ? 2e-4 : 1e-8; + const int elements = p.dim * o.bands; + const std::vector x = download(p.psi.template data(), elements); + // Exact pairs are (j+1, e_j/sqrt(S_jj)), with unit gaps. Compare columns + // up to phase to detect permutations and mixing of distinct eigenvectors. + // Bounds are O(sqrt(eig_tol/gap)), allowing ordinary float/double roundoff. + const double vector_tol = single ? 2e-2 : 2e-4; + for (int j = 0; j < o.bands; ++j) + { + const double expected_eigenvalue = j + 1; + EXPECT_NEAR(p.eigenvalues[j], expected_eigenvalue, eig_tol); + double error_squared = 0; + for (int row = 0; row < p.dim; ++row) + { + if (!p.physical(row)) { continue; } + const int i = p.global_row(row); + const double expected = i == j ? 1 : 0; + const double amplitude = std::sqrt(1 + .05 * i) * std::abs(x[row + j * p.dim]); + const double error = amplitude - expected; + error_squared += error * error; + } + sum(&error_squared, 1); + EXPECT_LT(std::sqrt(error_squared), vector_tol) << "band=" << j << ", single=" << single; + } +} +template +void check_exact_initial(const Locking locking) +{ + Options o; + o.bands = 4; + o.overlap = false; + Problem p(o, locking, comm_info()); + p.diagonal_problem(); + p.exact_initial(o.bands); + ASSERT_TRUE(p.solve(1e-5, 50, {})); + EXPECT_EQ(p.solver->iterations(), 0); + p.check(true, 1e-6, 1e-6); +} +} // namespace + +namespace hsolver +{ +class LobpcgProjectionTest +{ + public: + static void prefix(const Locking locking) + { + Problem p(Options{}, locking, comm_info()); + Problem::Solver& solver = *p.solver; + ct::Tensor previous(ct::DataType::DT_DOUBLE, ct::DeviceType::CpuDevice, {6}); + ct::Tensor threshold(ct::DataType::DT_DOUBLE, ct::DeviceType::CpuDevice, {6}); + for (int i = 0; i < 6; ++i) + { + solver.eig_.data()[i] = previous.data()[i] = i + 1; + threshold.data()[i] = 1e-9; + } + previous.data()[5] += 1; + int locked = 0; + EXPECT_FALSE(solver.lock_converged(previous, threshold, locked)); + EXPECT_EQ(locked, 5); + const int changed = locking == Locking::Soft ? 1 : 5; + solver.eig_.data()[changed] += 0.1; + EXPECT_FALSE(solver.lock_converged(previous, threshold, locked)); + EXPECT_EQ(locked, locking == Locking::Soft ? 1 : 5); + EXPECT_TRUE(solver.lock_converged(previous, threshold, locked)); + EXPECT_EQ(locked, 6); + } + + // Columns e_i/sqrt(S_ii) give G=I and K=diag(1,...,columns). + static std::vector coordinate_basis(Problem& p, const int columns) + { + p.diagonal_problem(); + std::vector x(p.dim * columns, Z(0)); + for (int row = 0; row < p.dim; ++row) + { + if (!p.physical(row)) { continue; } + const int i = p.global_row(row); + if (i < columns) { x[row + i * p.dim] = p.reference_vectors[i + i * p.options.n]; } + } + const Problem::Solver::VectorImages basis = p.solver->basis_images(0); + upload(basis.x, x); + p.hpsi(basis.x, basis.hx, p.dim, columns); + p.spsi(basis.x, basis.sx, p.dim, columns); + p.solver->project_padding(basis.hx, columns); + p.solver->project_padding(basis.sx, columns); + return x; + } + + static void direction(const int locked) + { + Problem p(Options{}, Locking::Hard, comm_info()); + Problem::Solver& solver = *p.solver; + const std::vector x = coordinate_basis(p, 4); + const Problem::Solver::VectorImages basis = solver.basis_images(0); + const std::vector hx = download(basis.hx, p.dim * 4); + const std::vector sx = download(basis.sx, p.dim * 4); + ct::Tensor k; + ct::Tensor g; + solver.form_projected_matrices(basis, 4, nullptr, k, g); + ct::Tensor c(ct::DataType::DT_COMPLEX_DOUBLE, ct::DeviceType::CpuDevice, {4, 2}); + c.zero(); + c.data()[0] = c.data()[2] = std::sqrt(.5); + c.data()[4] = .5; + c.data()[6] = -.5; + c.data()[7] = std::sqrt(.5); + const int active = 2 - locked; + ASSERT_EQ(solver.build_direction(basis, 4, 2, active, c, g), active); + const Problem::Solver::VectorImages history = solver.basis_images(solver.n_max_); + const Z* inputs[] = {x.data(), hx.data(), sx.data()}; + const Z* outputs[] = {history.x, history.hx, history.sx}; + const Z* cp = solver.u_p_.data(); + for (int image = 0; image < 3; ++image) + { + const std::vector actual = download(outputs[image], p.dim * active); + for (int j = 0; j < active; ++j) + { + for (int row = 0; row < p.dim; ++row) + { + Z expected(0); + for (int i = 0; i < 4; ++i) { expected += inputs[image][row + i * p.dim] * cp[i + j * 4]; } + EXPECT_LT(std::abs(actual[row + j * p.dim] - expected), 1e-12); + } + // G=I: the projected direction is orthogonal to the locked Ritz vector. + if (locked) { EXPECT_LT(std::abs(cp[j * 4] + cp[2 + j * 4]), 1e-12); } + else { EXPECT_EQ(cp[j * 4], Z(0)); EXPECT_EQ(cp[1 + j * 4], Z(0)); } + } + } + } + + static void retained_projection(const int zero_prefix) + { + Problem p(Options{}, Locking::Hard, comm_info()); + Problem::Solver& solver = *p.solver; + const std::vector original = coordinate_basis(p, 5); + const Problem::Solver::VectorImages basis = solver.basis_images(0); + ct::Tensor k; + ct::Tensor g; + solver.form_projected_matrices(basis, 5, nullptr, k, g); + ct::Tensor cx(ct::DataType::DT_COMPLEX_DOUBLE, ct::DeviceType::CpuDevice, {5, 2}); + cx.zero(); + cx.data()[0] = cx.data()[6] = 1; + Z* cp = solver.u_p_.data(); + std::fill_n(cp, 5, Z(0)); + const int first = std::max(1, zero_prefix); + cp[first] = .6; + cp[first + 1] = Z(0, .8); + const double values[] = {1, 2}; + Problem::Solver::ProjectionCache retained; + solver.retain_pair(k, g, 5, cx, 0, 2, 1, values, zero_prefix, retained); + EXPECT_EQ(retained.columns, 3); + // Form the physical [X,P,W] independently of the cached small matrices. + std::vector next(p.dim * 4, Z(0)); + std::copy_n(original.data(), p.dim * 2, next.data()); + for (int row = 0; row < p.dim; ++row) + { + for (int i = 0; i < 5; ++i) { next[row + 2 * p.dim] += original[row + i * p.dim] * cp[i]; } + next[row + 3 * p.dim] = original[row + 4 * p.dim]; + } + upload(basis.x, next); + p.hpsi(basis.x, basis.hx, p.dim, 4); + p.spsi(basis.x, basis.sx, p.dim, 4); + solver.project_padding(basis.hx, 4); + solver.project_padding(basis.sx, 4); + ct::Tensor cached_k; + ct::Tensor cached_g; + ct::Tensor full_k; + ct::Tensor full_g; + solver.form_projected_matrices(basis, 4, &retained, cached_k, cached_g); + solver.form_projected_matrices(basis, 4, nullptr, full_k, full_g); + for (int i = 0; i < full_k.NumElements(); ++i) + { + EXPECT_LT(std::abs(cached_k.data()[i] - full_k.data()[i]), 1e-12); + EXPECT_LT(std::abs(cached_g.data()[i] - full_g.data()[i]), 1e-12); + } + } + + static void recovery() + { + Options o; + o.bands = 4; + Problem p(o, Locking::Hard, comm_info()); + coordinate_basis(p, 7); + Problem::Solver& solver = *p.solver; + const Problem::Solver::VectorImages basis = solver.basis_images(0); + ct::Tensor k; + ct::Tensor g; + solver.form_projected_matrices(basis, 7, nullptr, k, g); + if (p.comm.rank == 0) { g.data()[0] = -1; } + dense::SerialGvWorkspace work; + EXPECT_FALSE(solver.solve_projected(k, g, 7, 4, work)); + int columns = 7; + ASSERT_TRUE(solver.recover_projected(p, basis, columns, 4, k, g, work)); + EXPECT_EQ(columns, 7); + EXPECT_TRUE(solver.error_message_.empty()); + for (int i = 0; i < 4; ++i) { EXPECT_NEAR(solver.e_red_.data()[i], i + 1, 1e-12); } + } + + static void rank_repair() + { + Options o; + o.bands = 4; + Problem p(o, Locking::Hard, comm_info()); + std::vector x = coordinate_basis(p, 7); + Problem::Solver& solver = *p.solver; + const Problem::Solver::VectorImages basis = solver.basis_images(0); + for (int row = 0; row < p.dim; ++row) + { + // Nonorthogonal, full-rank X and two independent increments plus a duplicate. + x[row + p.dim] += .3 * x[row]; + x[row + 4 * p.dim] += .2 * x[row]; + x[row + 6 * p.dim] = x[row + 4 * p.dim]; + } + upload(basis.x, x); + p.hpsi(basis.x, basis.hx, p.dim, 7); + solver.project_padding(basis.hx, 7); + ASSERT_EQ(solver.repair_basis(p, 3), 2); + const std::vector repaired = download(basis.x, p.dim * 6); + const std::vector sx = download(basis.sx, p.dim * 6); + const std::vector hx = download(basis.hx, p.dim * 6); + for (int i = 0; i < p.dim * 4; ++i) { EXPECT_EQ(repaired[i], x[i]); } + for (int j = 4; j < 6; ++j) + { + for (int row = 0; row < p.dim; ++row) + { + if (!p.physical(row)) { continue; } + const int i = p.global_row(row); + EXPECT_LT(std::abs(sx[row + j * p.dim] - (1 + .05 * i) * repaired[row + j * p.dim]), 1e-12); + EXPECT_LT(std::abs(hx[row + j * p.dim] - (i + 1.0) * sx[row + j * p.dim]), 1e-12); + } + for (int i = 0; i < 6; ++i) + { + Z gram(0); + for (int row = 0; row < p.dim; ++row) { gram += std::conj(repaired[row + i * p.dim]) * sx[row + j * p.dim]; } + sum(&gram, 1); + const Z expected = i == j ? Z(1) : Z(0); + EXPECT_LT(std::abs(gram - expected), 1e-12); + } + } + std::fill_n(x.data(), p.dim, Z(0)); + upload(basis.x, x); + EXPECT_LT(solver.repair_basis(p, 3), 0); + } + +}; +} // namespace hsolver + +namespace +{ +TEST_P(Lobpcg, StandardEigenpairs) +{ + Options o; + o.overlap = false; + check_case(o, GetParam()); + check_case>(o, GetParam()); +} +TEST_P(Lobpcg, GeneralizedEigenpairs) +{ + check_case(Options{}, GetParam()); + check_case>(Options{}, GetParam()); +} +TEST_P(Lobpcg, ExtraBands) +{ + Options o; + o.extra = 5; + check_case(o, GetParam()); + check_case>(o, GetParam()); +} +TEST_P(Lobpcg, SpinorPadding) +{ + Options o; + o.npol = 2; + check_case(o, GetParam()); + check_case>(o, GetParam()); +} +TEST_P(Lobpcg, DegenerateSpectrum) +{ + Options o; + o.extra = 4; + Problem p(o, GetParam(), comm_info()); + p.diagonal_problem(); + for (int i = 3; i < 8; ++i) + { + p.h[i + i * o.n] = 4.0 * p.s[i + i * o.n]; + p.reference_values[i] = 4; + } + ASSERT_TRUE(p.solve(1e-12, 250, {})); + p.check(true, 1e-8, 1e-8); +} +TEST_P(Lobpcg, PartiallyExactInitialVectors) +{ + Problem p(Options{}, GetParam(), comm_info()); + p.exact_initial(2); + ASSERT_TRUE(p.solve(1e-12, 250, {})); + p.check(true, 1e-8, 1e-8); +} +TEST_P(Lobpcg, EigenvectorsMatchEigenvalues) +{ + check_eigenpair_identity(GetParam()); + check_eigenpair_identity>(GetParam()); +} +TEST_P(Lobpcg, ExactInitialVectors) +{ + check_exact_initial(GetParam()); + check_exact_initial>(GetParam()); +} +#ifdef __MPI +TEST_P(Lobpcg, DistributedRitz) +{ + Options o; + o.backend = 2; + check_case(o, GetParam()); + check_case>(o, GetParam()); +} +#endif +TEST_P(Lobpcg, BudgetAndReuse) +{ + Options o; + Problem p(o, GetParam(), comm_info()); + EXPECT_FALSE(p.solve(1e-13, 1, {})); + EXPECT_EQ(p.solver->iterations(), 1); + p.check(false, 1e-8, 1e-8); + EXPECT_TRUE(p.solve(1e-13, 250, {})); + p.check(true, 1e-8, 1e-8); +} +TEST(LobpcgInitialization, ExactNonorthogonalInitialization) +{ + Options o; + o.bands = 4; + Problem p(o, Locking::Hard, comm_info()); + p.exact_initial(o.bands); + const std::vector original = p.input; + for (int j = 0; j < o.bands; ++j) + { + for (int row = 0; row < p.dim; ++row) + { + if (!p.physical(row)) { continue; } + Z value(0); + for (int k = 0; k <= j; ++k) + { + const Z mix = k == j ? Z(1 + .3 * j, .1 * j) : Z(.2, -.1); + value += original[row + k * p.dim] * mix; + } + p.input[row + j * p.dim] = value; + } + } + upload(p.psi.data(), p.input); + EXPECT_TRUE(p.solve(1e-10, 250, {})); + EXPECT_LE(p.solver->iterations(), 1); + EXPECT_EQ(p.h_calls, 1 + p.solver->iterations()); + EXPECT_EQ(p.s_calls, 1 + p.solver->iterations()); + p.check(true, 1e-10, 1e-10); +} +TEST_P(Lobpcg, IdentityMetricAgreesWithImplicitOverlap) +{ + Options o; + o.overlap = false; + Problem implicit(o, GetParam(), comm_info()); + ASSERT_TRUE(implicit.solve(1e-12, 250, {})); + EXPECT_EQ(implicit.s_calls, 0); + o.overlap = true; + Problem explicit_s(o, GetParam(), comm_info()); + explicit_s.s = implicit.s; + explicit_s.reference_values = implicit.reference_values; + ASSERT_TRUE(explicit_s.solve(1e-12, 250, {})); + EXPECT_GT(explicit_s.s_calls, 0); + explicit_s.check(true, 1e-8, 1e-8); + for (int i = 0; i < o.bands; ++i) + { + EXPECT_NEAR(explicit_s.eigenvalues[i], implicit.eigenvalues[i], 1e-9); + } +} +TEST_P(Lobpcg, BandThresholdOverridesScalar) +{ + Options o; + o.extra = 4; + Problem p(o, GetParam(), comm_info()); + const std::vector thresholds(o.bands, 1e-13); + ASSERT_TRUE(p.solve(1e-3, 250, thresholds)); + p.check(true, 1e-8, 1e-8); +} +TEST_P(Lobpcg, PrefixReactivationPolicy) { hsolver::LobpcgProjectionTest::prefix(GetParam()); } +TEST(LobpcgSubspace, DirectionImages) { hsolver::LobpcgProjectionTest::direction(0); } +TEST(LobpcgSubspace, DirectionRemovesLockedVector) { hsolver::LobpcgProjectionTest::direction(1); } +TEST(LobpcgSubspace, RetainedProjection) { hsolver::LobpcgProjectionTest::retained_projection(0); } +TEST(LobpcgSubspace, RetainedProjectionWithZeroPrefix) { hsolver::LobpcgProjectionTest::retained_projection(2); } +TEST(LobpcgSubspace, RefreshFailedMetric) { hsolver::LobpcgProjectionTest::recovery(); } +TEST(LobpcgSubspace, RepairDependentIncrement) { hsolver::LobpcgProjectionTest::rank_repair(); } +} // namespace + +int main(int argc, char** argv) +{ +#ifdef __MPI + int nproc = 1; + int rank = 0; + int in_pool = 0; + int kpar = 1; + int pool = 0; + int pool_rank = 0; + setupmpi(argc, argv, nproc, rank); + divide_pools(nproc, rank, in_pool, kpar, pool, pool_rank); +#endif +#if defined(__CUDA) || defined(__ROCM) + if (!base_device::information::probe_gpu_availability()) + { +#ifdef __MPI + finishmpi(); +#endif + return 77; + } + ModuleBase::createGpuBlasHandle(); + ct::kernels::createGpuBlasHandle(); +#endif + testing::InitGoogleTest(&argc, argv); + testing::TestEventListeners& listeners = testing::UnitTest::GetInstance()->listeners(); + if (comm_info().rank != 0) { delete listeners.Release(listeners.default_result_printer()); } + const int result = RUN_ALL_TESTS(); +#if defined(__CUDA) || defined(__ROCM) + ct::kernels::destroyGpuBlasHandle(); + ModuleBase::destoryBLAShandle(); +#endif +#ifdef __MPI + finishmpi(); +#endif + return result; +} + +INSTANTIATE_TEST_SUITE_P(LockingModes, Lobpcg, ::testing::Values(Locking::Hard, Locking::Soft)); diff --git a/source/source_hsolver/unittests/test_hsolver_pw.cpp b/source/source_hsolver/unittests/test_hsolver_pw.cpp index 2086ab34862..ae876a59c36 100644 --- a/source/source_hsolver/unittests/test_hsolver_pw.cpp +++ b/source/source_hsolver/unittests/test_hsolver_pw.cpp @@ -6,12 +6,17 @@ #include "hsolver_pw_sup.h" #include "hsolver_supplementary_mock.h" #include "source_hsolver/diag_comm_info.h" +#include "source_base/parallel_global.h" #include "source_hsolver/hs_operator.h" #include "source_hsolver/hsolver_lcaopw.h" #include "source_hsolver/hsolver_pw.h" +#include "source_hsolver/diago_params.h" +#include "source_hsolver/diago_lobpcg.h" #include #include +#include +#include /// H = S = identity: the simplest operator the solvers can be handed template class IdentityHSOperator : public hsolver::HSOperator @@ -184,6 +189,13 @@ template void diago_hs_para>( class TestHSolverPW : public ::testing::Test { public: + void SetUp() override + { + // WARNING_QUIT is exercised after OpenMP/runtime state has been initialized + // by earlier tests; re-exec death tests avoid inheriting those threads. + ::testing::FLAGS_gtest_death_test_style = "threadsafe"; + } + // HSolverPW declares this fixture a friend, but a TEST_F body lives in a // class derived from it and friendship is not inherited, so the call into // the protected hamiltSolvePsiK() is routed through here. @@ -205,40 +217,13 @@ class TestHSolverPW : public ::testing::Test } ModulePW::PW_Basis_K pwbk; - hsolver::HSolverPW, base_device::DEVICE_CPU> hs_f = - hsolver::HSolverPW, base_device::DEVICE_CPU>( - &pwbk, - "scf", - "pw", - "cg", - false, - 1, - hsolver::DiagoIterAssist, base_device::DEVICE_CPU>::SCF_ITER, - hsolver::DiagoIterAssist, base_device::DEVICE_CPU>::PW_DIAG_NMAX, - hsolver::DiagoIterAssist, base_device::DEVICE_CPU>::PW_DIAG_THR, - hsolver::DiagoIterAssist, base_device::DEVICE_CPU>::need_subspace, - 0, - false, - 4, - 0, - 0); - hsolver::HSolverPW, base_device::DEVICE_CPU> hs_d = - hsolver::HSolverPW, base_device::DEVICE_CPU>( - &pwbk, - "scf", - "pw", - "cg", - false, - 1, - hsolver::DiagoIterAssist, base_device::DEVICE_CPU>::SCF_ITER, - hsolver::DiagoIterAssist, base_device::DEVICE_CPU>::PW_DIAG_NMAX, - hsolver::DiagoIterAssist, base_device::DEVICE_CPU>::PW_DIAG_THR, - hsolver::DiagoIterAssist, base_device::DEVICE_CPU>::need_subspace, - 0, - false, - 4, - 0, - 0); + using Assist = hsolver::DiagoIterAssist, base_device::DEVICE_CPU>; + hsolver::HSolverPW, base_device::DEVICE_CPU> hs_f{ + &pwbk, "scf", "pw", "cg", false, 1, Assist::SCF_ITER, Assist::PW_DIAG_NMAX, + Assist::PW_DIAG_THR, Assist::need_subspace, 0, false, 4, 0, "hard", 0, 0}; + hsolver::HSolverPW, base_device::DEVICE_CPU> hs_d{ + &pwbk, "scf", "pw", "cg", false, 1, Assist::SCF_ITER, Assist::PW_DIAG_NMAX, + Assist::PW_DIAG_THR, Assist::need_subspace, 0, false, 4, 0, "hard", 0, 0}; IdentityHSOperator> hamilt_test_d; IdentityHSOperator> hamilt_test_f; @@ -253,6 +238,68 @@ class TestHSolverPW : public ::testing::Test std::vector ekb_f; std::ofstream temp_ofs; + + void run_lobpcg_entry(const int dim, const int block, const int backend) + { + std::cout.rdbuf(std::cerr.rdbuf()); + int size = 1; + int threads = 1; + int rank = 0; + Parallel_Global::read_pal_param(0, nullptr, size, threads, rank); + const hsolver::diag_comm_info comm(MPI_COMM_SELF, 0, 1); + const hsolver::LobpcgBasisLayout layout = {dim, 1}; + std::vector prec(dim, 1); + std::vector values(4); + std::vector> x(dim * 4, 0); + for (int i = 0; i < 4; ++i) { x[i + i * dim] = 1; } + hsolver::dense::ParallelDenseEigensolver parallel; + hsolver::dense::GpuDenseEigensolver gpu; + hsolver::DiagoLOBPCG> solver( + prec.data(), 4, dim, block, layout, comm, backend, 0, false, + hsolver::LobpcgLocking::Hard, parallel, gpu); + solver.diag(hamilt_test_d, x.data(), dim, values.data(), 1e-8, 50, {}); + } + + void run_lobpcg_case(const std::string& calculation, const bool dependent) + { + std::cout.rdbuf(std::cerr.rdbuf()); +#ifdef __MPI + int size = 1; + int threads = 1; + int rank = 0; + Parallel_Global::read_pal_param(0, nullptr, size, threads, rank); + POOL_WORLD = MPI_COMM_SELF; +#endif + using C = std::complex; + class DiagonalOperator : public IdentityHSOperator + { + public: + void hpsi(const C* x, C* hx, const int ld, const int count) const override + { + for (int j = 0; j < count; ++j) + { + for (int i = 0; i < ld; ++i) { hx[i + j * ld] = double(i + 1) * x[i + j * ld]; } + } + } + } diagonal; + psi::Psi ps; + ps.resize(1, 4, 40); + for (int j = 0; j < 4; ++j) + { + for (int i = 0; i < 40; ++i) + { + ps.get_pointer()[i + j * 40] = dependent ? C(.3, .1) : C(std::sin(.17 * (i + 1) * (j + 2)), .1); + } + } + std::vector prec(40, 1); + std::vector eig(4); + const hsolver::HSOperator& op = dependent ? hamilt_test_d : diagonal; + hsolver::HSolverPW solver(&pwbk, calculation, "pw", "lobpcg", false, + 1, 1, 1, 1e-12, false, 4, false, 4, 0, "hard", 0, 0); + hamiltSolvePsiK(solver, op, ps, prec, eig.data(), 1); + std::exit(0); + } + }; // TEST_F(TestHSolverPW, solve) { @@ -513,3 +560,60 @@ TEST_F(TestHSolverPW, NpwxLessThanNbandsDeath) 1), ::testing::ExitedWithCode(1), ".*"); } + +TEST_F(TestHSolverPW, LobpcgBlockMustContainRequestedBands) +{ + EXPECT_EXIT(run_lobpcg_entry(40, 3, 0), testing::ExitedWithCode(1), + "LOBPCG block must contain all requested bands"); +} + +TEST_F(TestHSolverPW, LobpcgNeedsFullRankSearchSpace) +{ + EXPECT_EXIT(run_lobpcg_entry(8, 4, 0), testing::ExitedWithCode(1), + "The requested bands cannot form a full-rank LOBPCG space"); +} + +TEST_F(TestHSolverPW, LobpcgRejectsUnsupportedBackend) +{ + EXPECT_EXIT(run_lobpcg_entry(40, 4, 1), testing::ExitedWithCode(1), + "LOBPCG supports diag_subspace=0 or 2"); +} + +// Exercise the actual caller: NSCF budget exhaustion and a failed initial GV. +TEST_F(TestHSolverPW, LobpcgNscfBudgetReportsError) +{ + EXPECT_EXIT(run_lobpcg_case("nscf", false), ::testing::ExitedWithCode(1), + "LOBPCG iteration budget exhausted in NSCF"); +} + +TEST_F(TestHSolverPW, LobpcgBudgetContinuesOuterLoops) +{ + for (const char* calculation : {"scf", "relax", "cell-relax", "md"}) + { + EXPECT_EXIT(run_lobpcg_case(calculation, false), ::testing::ExitedWithCode(0), ".*"); + } +} + +TEST_F(TestHSolverPW, LobpcgNumericalFailureReportsBackendInfo) +{ + EXPECT_EXIT(run_lobpcg_case("scf", true), ::testing::ExitedWithCode(1), "Serial HEGVX failed, info="); +} + +TEST_F(TestHSolverPW, PwUsesInputIterationBudget) +{ + Input_para input; + input.pw_diag_nmax = 37; + const int previous = Assist::PW_DIAG_NMAX; + for (const char* calculation : {"scf", "nscf", "relax", "cell-relax", "md"}) + { + input.calculation = calculation; + for (const char* method : {"cg", "dav", "dav_subspace", "bpcg", "lobpcg"}) + { + input.ks_solver = method; + Assist::PW_DIAG_NMAX = 30; + hsolver::setup_diago_params_pw, base_device::DEVICE_CPU>(0, 1, 1e-8, input); + EXPECT_EQ(Assist::PW_DIAG_NMAX, 37) << calculation << ": " << method; + } + } + Assist::PW_DIAG_NMAX = previous; +} diff --git a/source/source_io/module_parameter/input_parameter.h b/source/source_io/module_parameter/input_parameter.h index 7673609daf8..a7d30cfb5ef 100644 --- a/source/source_io/module_parameter/input_parameter.h +++ b/source/source_io/module_parameter/input_parameter.h @@ -98,6 +98,8 @@ struct Input_para double pw_diag_thr = 0.01; ///< used in cg method bool diago_smooth_ethr = false; ///< smooth ethr for iter methods int pw_diag_ndim = 4; ///< dimension of workspace for Davidson diagonalization + int lobpcg_extra_bands = 0; ///< internal LOBPCG columns beyond the requested bands + std::string lobpcg_locking = "hard"; ///< hard freezes converged vectors; soft keeps them in RR int diago_cg_prec = 1; ///< mohan add 2012-03-31 int diag_subspace = 0; // 0: Lapack, 1: elpa, 2: scalapack bool use_k_continuity = false; ///< whether to use k-point continuity for initializing wave functions diff --git a/source/source_io/module_parameter/read_inp_estruc.cpp b/source/source_io/module_parameter/read_inp_estruc.cpp index 6b0cef2902a..8e437aa004a 100644 --- a/source/source_io/module_parameter/read_inp_estruc.cpp +++ b/source/source_io/module_parameter/read_inp_estruc.cpp @@ -37,11 +37,11 @@ void ReadInput::item_elec_stru() // Electronic Structure { Input_Item item("ks_solver"); - item.domain.set_choices({"cg", "dav", "bpcg", "dav_subspace", "genelpa", "elpa", "lapack", "scalapack_gvx", "cusolver", "cusolvermp", "pexsi"}); - item.domain.add_requirement("basis_type==pw", "ks_solver in [cg, dav, bpcg, dav_subspace]"); + item.domain.set_choices({"cg", "dav", "bpcg", "dav_subspace", "lobpcg", "genelpa", "elpa", "lapack", "scalapack_gvx", "cusolver", "cusolvermp", "pexsi"}); + item.domain.add_requirement("basis_type==pw", "ks_solver in [cg, dav, bpcg, dav_subspace, lobpcg]"); item.domain.add_requirement("basis_type==lcao", "ks_solver in [genelpa, elpa, lapack, scalapack_gvx, cusolver, cusolvermp, pexsi]"); item.domain.add_requirement("ks_solver==genelpa", "device==cpu"); - item.annotation = "cg; dav; lapack; genelpa; elpa; scalapack_gvx; cusolver"; + item.annotation = "cg; dav; dav_subspace; bpcg; lobpcg; lapack; genelpa; elpa; scalapack_gvx; cusolver; cusolvermp; pexsi"; item.category = "Electronic structure"; item.type = "String"; item.description = R"(Choose the diagonalization methods for the Hamiltonian matrix expanded in a certain basis set. @@ -52,6 +52,7 @@ For plane-wave basis, * dav: The Davidson algorithm. * dav_subspace: The Davidson algorithm without orthogonalization operation, this method is the most recommended for efficiency. `pw_diag_ndim` can be set to 2 for this method. * bpcg: The BPCG method, which is a block-parallel Conjugate Gradient (CG) method, typically exhibits higher acceleration in a GPU environment. The BPCG method is currently under testing and is not recommended for use. +* lobpcg: The locally optimal block preconditioned conjugate gradient method for CPU and GPU. For numerical atomic orbitals basis, @@ -1015,10 +1016,10 @@ Use case: When experimental or high-level theoretical results suggest that the S } { Input_Item item("pw_diag_thr"); - item.annotation = "threshold for eigenvalues is cg electron iterations"; + item.annotation = "initial convergence threshold for iterative diagonalization"; item.category = "Plane wave related variables"; item.type = "Real"; - item.description = "Only used when you use ks_solver = cg/dav/dav_subspace/bpcg. It indicates the threshold for the first electronic iteration, from the second iteration the pw_diag_thr will be updated automatically. For nscf calculations with planewave basis set, pw_diag_thr should be <= 1e-3."; + item.description = "Initial diagonalization threshold for cg/dav/dav_subspace/bpcg/lobpcg, updated automatically during SCF. For plane-wave NSCF calculations, choose a value <= 1e-3."; item.default_value = "0.01"; item.unit = ""; read_sync_double(input.pw_diag_thr); @@ -1038,7 +1039,7 @@ Use case: When experimental or high-level theoretical results suggest that the S item.annotation = "smooth ethr for iter methods"; item.category = "Plane wave related variables"; item.type = "Boolean"; - item.description = "If TRUE, the smooth threshold strategy, which applies a larger threshold (10e-5) for the empty states, will be implemented in the diagonalization methods. (This strategy should not affect total energy, forces, and other ground-state properties, but computational efficiency will be improved.) If FALSE, the smooth threshold strategy will not be applied."; + item.description = "If TRUE, relax diagonalization thresholds for nearly empty bands to reduce work in ground-state SCF. If FALSE, use the same threshold for all bands."; item.default_value = "false"; item.unit = ""; read_sync_bool(input.diago_smooth_ethr); @@ -1059,13 +1060,14 @@ Use case: When experimental or high-level theoretical results suggest that the S } { Input_Item item("pw_diag_nmax"); - item.annotation = "max iteration number for cg"; + item.annotation = "maximum iterations per iterative diagonalization attempt"; item.category = "Plane wave related variables"; item.type = "Integer"; - item.description = "Only useful when you use ks_solver = cg/dav/dav_subspace/bpcg. It indicates the maximal iteration number for cg/david/dav_subspace/bpcg method."; + item.description = "Maximum number of iterations per diagonalization attempt."; item.default_value = "50"; + item.domain.set_rule("value>0"); item.unit = ""; - item.set_availability("basis_type==pw and ks_solver in [cg, dav, dav_subspace, bpcg]"); + item.set_availability("basis_type==pw and ks_solver in [cg, dav, dav_subspace, bpcg, lobpcg]"); read_sync_int(input.pw_diag_nmax); this->add_item(item); } @@ -1080,6 +1082,32 @@ Use case: When experimental or high-level theoretical results suggest that the S read_sync_int(input.pw_diag_ndim); this->add_item(item); } + { + Input_Item item("lobpcg_extra_bands"); + item.domain.set_rule("value>=0"); + item.annotation = "number of extra internal LOBPCG vectors"; + item.category = "Plane wave related variables"; + item.type = "Integer"; + item.description = R"(Number of extra bands used internally in addition to nbands. A small positive value can help when closely spaced or degenerate bands near the highest requested band converge slowly. Larger values require more memory and computation.)"; + item.default_value = "0"; + item.unit = ""; + item.set_availability("basis_type==pw and ks_solver==lobpcg"); + read_sync_int(input.lobpcg_extra_bands); + this->add_item(item); + } + { + Input_Item item("lobpcg_locking"); + item.domain.set_choices({"hard", "soft"}); + item.annotation = "locking policy for LOBPCG"; + item.category = "Plane wave related variables"; + item.type = "String"; + item.description = R"(The default hard keeps converged bands fixed to reduce computation. With soft, these bands continue to be refined, which can help when closely spaced bands converge slowly, with more work per iteration.)"; + item.default_value = "hard"; + item.unit = ""; + item.set_availability("basis_type==pw and ks_solver==lobpcg"); + read_sync_string(input.lobpcg_locking); + this->add_item(item); + } { Input_Item item("diago_cg_prec"); item.annotation = "diago_cg_prec"; diff --git a/source/source_io/module_parameter/read_inp_sys.cpp b/source/source_io/module_parameter/read_inp_sys.cpp index c127d89853c..a9077eb9f19 100644 --- a/source/source_io/module_parameter/read_inp_sys.cpp +++ b/source/source_io/module_parameter/read_inp_sys.cpp @@ -1469,15 +1469,17 @@ updates structures smoothly enough for second-order extrapolation.)"; { Input_Item item("diag_subspace"); item.domain.set_choices({"0", "1", "2"}); - item.annotation = "method of subspace diagonalization in dav_subspace. 0:LaPack; 1:genelpa, 2:scalapack"; + item.domain.add_requirement("ks_solver==lobpcg", "diag_subspace in [0, 2]"); + item.annotation = "method of subspace diagonalization in dav_subspace or lobpcg. 0:LaPack; 1:genelpa, 2:scalapack"; item.category = "Plane wave related variables"; item.type = "Integer"; - item.description = R"(The method to diagonalize subspace in dav_subspace method. + item.description = R"(The method to diagonalize subspace in dav_subspace or lobpcg method. * 0: by LAPACK -* 1: by GenELPA -* 2: by ScaLAPACK)"; +* 1: by GenELPA (dav_subspace only) +* 2: by ScaLAPACK +LOBPCG supports 0 and 2. On CUDA, LOBPCG option 0 uses cuSOLVER on the GPU.)"; item.default_value = "0"; - item.set_availability("basis_type==pw and ks_solver==dav_subspace"); + item.set_availability("basis_type==pw and (ks_solver==dav_subspace or ks_solver==lobpcg)"); read_sync_int(input.diag_subspace); this->add_item(item); } diff --git a/source/source_io/test_serial/CMakeLists.txt b/source/source_io/test_serial/CMakeLists.txt index d201ce81b99..5df8e8b7762 100644 --- a/source/source_io/test_serial/CMakeLists.txt +++ b/source/source_io/test_serial/CMakeLists.txt @@ -49,6 +49,10 @@ addtest( SOURCES ../unittests/test_read_input_item.cpp test_read_inp_sccs.cpp ../module_parameter/unittests/test_read_inp_estruc.cpp) +addtest( + TARGET MODULE_IO_lobpcg_input + LIBS parameter base device io_input_serial) + addtest( TARGET MODULE_IO_input_domain_reader LIBS parameter base device io_input_serial diff --git a/source/source_io/unittests/CMakeLists.txt b/source/source_io/unittests/CMakeLists.txt index db7afae58f5..bbe27942f4b 100644 --- a/source/source_io/unittests/CMakeLists.txt +++ b/source/source_io/unittests/CMakeLists.txt @@ -6,6 +6,7 @@ abacus_disable_feature_definitions(__EXX) # Keep the existing serial INPUT target and its compile definitions. target_sources(MODULE_IO_read_input_serial PRIVATE test_read_input_serial.cpp) target_sources(MODULE_IO_read_item_serial PRIVATE test_read_inp_exx_dftu.cpp) +target_sources(MODULE_IO_lobpcg_input PRIVATE test_read_inp_estruc.cpp) if(ENABLE_LIBRI_GPU) # Exercise the real device probe while keeping DeviceContext free of MPI. diff --git a/source/source_io/unittests/test_read_inp_estruc.cpp b/source/source_io/unittests/test_read_inp_estruc.cpp new file mode 100644 index 00000000000..39e03f585c7 --- /dev/null +++ b/source/source_io/unittests/test_read_inp_estruc.cpp @@ -0,0 +1,112 @@ +#include +#include +#include +#include + +#include "gtest/gtest.h" +#include "source_io/module_parameter/read_input.h" + +class TestParameters +{ + public: + static Input_para& input(Parameter& param) { return param.input; } +}; + +class LobpcgInputTest : public testing::Test +{ + protected: + using Items = std::vector>; + Items::iterator find_label(const std::string& label, Items& items) + { + return std::find_if(items.begin(), items.end(), + [&label](const Items::value_type& item) { return item.first == label; }); + } + ModuleIO::ReadInput reader{0}; + Parameter param; + Items items; + void SetUp() override { items = Items(reader.get_input_lists()); } + +}; + +TEST_F(LobpcgInputTest, LobpcgExtraBands) +{ + Items::iterator found = find_label("lobpcg_extra_bands", items); + ASSERT_NE(found, items.end()); + ModuleIO::Input_Item& item = found->second; + EXPECT_EQ(param.inp.lobpcg_extra_bands, 0); + EXPECT_EQ(item.default_value, "0"); + EXPECT_TRUE(item.domain.validate_explicit(item.label, {"0"}).empty()); + EXPECT_TRUE(item.domain.validate_explicit(item.label, {"5"}).empty()); + EXPECT_FALSE(item.domain.validate_explicit(item.label, {"-1"}).empty()); + item.str_values = {"5"}; + item.read_value(item, param); + EXPECT_EQ(param.inp.lobpcg_extra_bands, 5); + item.get_final_value(item, param); + EXPECT_EQ(item.final_value.str(), "5"); +} + +TEST_F(LobpcgInputTest, PwDiagNmaxMustBePositive) +{ + Items::iterator item = find_label("pw_diag_nmax", items); + ASSERT_NE(item, items.end()); + ModuleIO::Input_Item& option = item->second; + EXPECT_EQ(option.default_value, "50"); + EXPECT_EQ(option.type, "Integer"); + EXPECT_TRUE(option.domain.validate_explicit(option.label, {"37"}).empty()); + EXPECT_FALSE(option.domain.validate_explicit(option.label, {"0"}).empty()); + EXPECT_FALSE(option.domain.validate_explicit(option.label, {"-1"}).empty()); +} + +TEST_F(LobpcgInputTest, LobpcgLocking) +{ + Items::iterator found = find_label("lobpcg_locking", items); + ASSERT_NE(found, items.end()); + ModuleIO::Input_Item& item = found->second; + EXPECT_EQ(param.inp.lobpcg_locking, "hard"); + EXPECT_EQ(item.default_value, "hard"); + EXPECT_TRUE(item.domain.validate_explicit(item.label, {"hard"}).empty()); + EXPECT_TRUE(item.domain.validate_explicit(item.label, {"soft"}).empty()); + EXPECT_FALSE(item.domain.validate_explicit(item.label, {"invalid"}).empty()); + item.str_values = {"soft"}; + item.read_value(item, param); + EXPECT_EQ(param.inp.lobpcg_locking, "soft"); + item.get_final_value(item, param); + EXPECT_EQ(item.final_value.str(), "soft"); +} + +TEST_F(LobpcgInputTest, LobpcgDeviceSupport) +{ + Items::iterator item = find_label("ks_solver", items); + ASSERT_NE(item, items.end()); + TestParameters::input(param).basis_type = "pw"; + TestParameters::input(param).ks_solver = "lobpcg"; + ModuleIO::InputValues values; + values["basis_type"] = ModuleIO::InputValue(param.inp.basis_type); + values["ks_solver"] = ModuleIO::InputValue(param.inp.ks_solver); + for (const std::string device : {"cpu", "gpu"}) + { + TestParameters::input(param).device = device; + values["device"] = ModuleIO::InputValue(device); + EXPECT_TRUE(item->second.domain.validate_requirements("ks_solver", values).empty()); + item->second.check_value(item->second, param); + } +} + +TEST_F(LobpcgInputTest, LobpcgSubspaceBackends) +{ + Items::iterator item = find_label("diag_subspace", items); + ASSERT_NE(item, items.end()); + ModuleIO::InputValues values; + const std::string lobpcg = "lobpcg"; + values["ks_solver"] = ModuleIO::InputValue(lobpcg); + for (const int backend : {0, 2}) + { + values["diag_subspace"] = ModuleIO::InputValue(backend); + EXPECT_TRUE(item->second.domain.validate_requirements("diag_subspace", values).empty()); + } + values["diag_subspace"] = ModuleIO::InputValue(1); + EXPECT_FALSE(item->second.domain.validate_requirements("diag_subspace", values).empty()); + const std::string davidson = "dav_subspace"; + values["ks_solver"] = ModuleIO::InputValue(davidson); + EXPECT_TRUE(item->second.domain.validate_requirements("diag_subspace", values).empty()); +} diff --git a/source/source_io/unittests/test_read_input_item.cpp b/source/source_io/unittests/test_read_input_item.cpp index 8139aa9272a..956807f51e9 100644 --- a/source/source_io/unittests/test_read_input_item.cpp +++ b/source/source_io/unittests/test_read_input_item.cpp @@ -2723,7 +2723,7 @@ TEST_F(InputTest, Item_test2) { // diag_subspace std::vector>::iterator it = find_label("diag_subspace", readinput.input_lists); - EXPECT_EQ(it->second.get_availability(), "basis_type==pw and ks_solver==dav_subspace"); + EXPECT_EQ(it->second.get_availability(), "basis_type==pw and (ks_solver==dav_subspace or ks_solver==lobpcg)"); } { // md_nstep auto it = find_label("md_nstep", readinput.input_lists); diff --git a/source/source_lcao/module_deltaspin/deltaspin_pw_mi.cpp b/source/source_lcao/module_deltaspin/deltaspin_pw_mi.cpp index d692ecda7eb..5896d51d290 100644 --- a/source/source_lcao/module_deltaspin/deltaspin_pw_mi.cpp +++ b/source/source_lcao/module_deltaspin/deltaspin_pw_mi.cpp @@ -359,23 +359,26 @@ void update_psi_charge_pw_cpu(ScState& state, { // Full PW diagonalization: subspace rotation provides a good initial guess, // then HSolverPW iteratively refines psi in the full plane-wave space and calls psiToRho. + const Input_para& solver_input = PARAM.inp; hsolver::HSolverPW, base_device::DEVICE_CPU> hsolver_pw_obj( pw_wfc, - PARAM.inp.calculation, - PARAM.inp.basis_type, - PARAM.inp.ks_solver, + solver_input.calculation, + solver_input.basis_type, + solver_input.ks_solver, PARAM.globalv.use_uspp, - PARAM.inp.nspin, + solver_input.nspin, hsolver::DiagoIterAssist>::SCF_ITER, hsolver::DiagoIterAssist>::PW_DIAG_NMAX, hsolver::DiagoIterAssist>::PW_DIAG_THR, hsolver::DiagoIterAssist>::need_subspace, - PARAM.inp.nbands, - PARAM.inp.diago_smooth_ethr, - PARAM.inp.pw_diag_ndim, - PARAM.inp.diag_subspace, - PARAM.inp.nb2d, - PARAM.inp.use_k_continuity); + solver_input.nbands, + solver_input.diago_smooth_ethr, + solver_input.pw_diag_ndim, + solver_input.lobpcg_extra_bands, + solver_input.lobpcg_locking, + solver_input.diag_subspace, + solver_input.nb2d, + solver_input.use_k_continuity); hamilt::HamiltHSOperator, base_device::DEVICE_CPU> op(hamilt_t, pw_wfc); hsolver_pw_obj.solve(op, @@ -472,23 +475,26 @@ void update_psi_charge_pw_gpu(ScState& state, // STAGE 2: Full-space update (GPU) if (pw_solve) { + const Input_para& solver_input = PARAM.inp; hsolver::HSolverPW, base_device::DEVICE_GPU> hsolver_pw_obj( pw_wfc, - PARAM.inp.calculation, - PARAM.inp.basis_type, - PARAM.inp.ks_solver, + solver_input.calculation, + solver_input.basis_type, + solver_input.ks_solver, PARAM.globalv.use_uspp, - PARAM.inp.nspin, + solver_input.nspin, hsolver::DiagoIterAssist, base_device::DEVICE_GPU>::SCF_ITER, hsolver::DiagoIterAssist, base_device::DEVICE_GPU>::PW_DIAG_NMAX, hsolver::DiagoIterAssist, base_device::DEVICE_GPU>::PW_DIAG_THR, hsolver::DiagoIterAssist, base_device::DEVICE_GPU>::need_subspace, - PARAM.inp.nbands, - PARAM.inp.diago_smooth_ethr, - PARAM.inp.pw_diag_ndim, - PARAM.inp.diag_subspace, - PARAM.inp.nb2d, - PARAM.inp.use_k_continuity); + solver_input.nbands, + solver_input.diago_smooth_ethr, + solver_input.pw_diag_ndim, + solver_input.lobpcg_extra_bands, + solver_input.lobpcg_locking, + solver_input.diag_subspace, + solver_input.nb2d, + solver_input.use_k_continuity); hamilt::HamiltHSOperator, base_device::DEVICE_GPU> op(hamilt_t, pw_wfc); hsolver_pw_obj.solve(op, diff --git a/source/source_pw/module_stodft/sto_hsolver_pw.h b/source/source_pw/module_stodft/sto_hsolver_pw.h index 8c9b8cef9c2..752400467f5 100644 --- a/source/source_pw/module_stodft/sto_hsolver_pw.h +++ b/source/source_pw/module_stodft/sto_hsolver_pw.h @@ -27,6 +27,8 @@ class StoHSolverPW : public hsolver::HSolverPW const int nbands_in, const bool diago_smooth_ethr_in, const int pw_diag_ndim_in, + const int lobpcg_extra_bands_in, + const std::string& lobpcg_locking_in, const int diag_subspace_in, const int nb2d_in, const bool ks_run_in, @@ -45,6 +47,8 @@ class StoHSolverPW : public hsolver::HSolverPW nbands_in, diago_smooth_ethr_in, pw_diag_ndim_in, + lobpcg_extra_bands_in, + lobpcg_locking_in, diag_subspace_in, nb2d_in), ks_run(ks_run_in), all_ks_run(all_ks_run_in), bndpar(bndpar_in) diff --git a/source/source_pw/module_stodft/unittests/CMakeLists.txt b/source/source_pw/module_stodft/unittests/CMakeLists.txt index 04bc4d38390..874d58f16da 100644 --- a/source/source_pw/module_stodft/unittests/CMakeLists.txt +++ b/source/source_pw/module_stodft/unittests/CMakeLists.txt @@ -33,6 +33,11 @@ if(ENABLE_MPI) ../../../source_hsolver/hsolver_pw.cpp ../../../source_hsolver/diago_bpcg.cpp ../../../source_hsolver/diago_dav_subspace.cpp + ../../../source_hsolver/diago_lobpcg.cpp + ../../../source_hsolver/lobpcg_subspace.cpp + ../../../source_hsolver/lobpcg_recovery.cpp + ../../../source_hsolver/dense_eigensolver.cpp + ../../../source_hsolver/module_linalg/linear_algebra.cpp ../../../source_hsolver/diag_const_nums.cpp ../../../source_hsolver/diago_iter_assist.cpp ../../../source_hsolver/para_lin_tf.cpp diff --git a/source/source_pw/module_stodft/unittests/test_sto_hsolver_pw.cpp b/source/source_pw/module_stodft/unittests/test_sto_hsolver_pw.cpp index 5a50882eeea..6e4eb588e59 100644 --- a/source/source_pw/module_stodft/unittests/test_sto_hsolver_pw.cpp +++ b/source/source_pw/module_stodft/unittests/test_sto_hsolver_pw.cpp @@ -286,30 +286,31 @@ class TestStoHSolverPW : public ::testing::Test K_Vectors kv; StoChe stoche; StoHamiltPW> *p_hamilt_sto = nullptr; - StoHSolverPW, base_device::DEVICE_CPU> hs_d = - StoHSolverPW, base_device::DEVICE_CPU>( - &kv, - &pwbk, - stowf, - stoche, - p_hamilt_sto, - "scf", - "pw", - "cg", - false, - 1, - hsolver::DiagoIterAssist>::SCF_ITER, - hsolver::DiagoIterAssist>::PW_DIAG_NMAX, - hsolver::DiagoIterAssist>::PW_DIAG_THR, - hsolver::DiagoIterAssist>::need_subspace, - 0, - false, - 4, - 0, - 0, - false, - true, - 1); + StoHSolverPW, base_device::DEVICE_CPU> hs_d{ + &kv, + &pwbk, + stowf, + stoche, + p_hamilt_sto, + "scf", + "pw", + "cg", + false, + 1, + hsolver::DiagoIterAssist>::SCF_ITER, + hsolver::DiagoIterAssist>::PW_DIAG_NMAX, + hsolver::DiagoIterAssist>::PW_DIAG_THR, + hsolver::DiagoIterAssist>::need_subspace, + 0, + false, + 4, + 0, + "hard", + 0, + 0, + false, + true, + 1}; hamilt::Hamilt> hamilt_test_d; diff --git a/tests/01_PW/051_PW_OBOD_MemSaver/INPUT b/tests/01_PW/051_PW_OBOD_MemSaver/INPUT index ff75622d334..68a11d9f272 100644 --- a/tests/01_PW/051_PW_OBOD_MemSaver/INPUT +++ b/tests/01_PW/051_PW_OBOD_MemSaver/INPUT @@ -12,6 +12,7 @@ read_file_dir ./ ecutwfc 20 scf_thr 1e-8 scf_nmax 100 +pw_diag_nmax 30 init_chg file out_band 1 diff --git a/tests/01_PW/101_PW_W90/INPUT b/tests/01_PW/101_PW_W90/INPUT index 8b7fed80c72..b9aab68e5c4 100644 --- a/tests/01_PW/101_PW_W90/INPUT +++ b/tests/01_PW/101_PW_W90/INPUT @@ -9,6 +9,7 @@ nbands 4 calculation nscf scf_nmax 50 pw_diag_thr 1.0e-12 +pw_diag_nmax 30 scf_thr 1.0e-15 init_chg file symmetry 0 diff --git a/tests/01_PW/CASES_CPU.txt b/tests/01_PW/CASES_CPU.txt index 9a32f655017..5fb4a5d938b 100644 --- a/tests/01_PW/CASES_CPU.txt +++ b/tests/01_PW/CASES_CPU.txt @@ -25,6 +25,8 @@ scf_out_chg_tau 022_PW_CG 023_PW_DA 024_PW_DS +scf_lobpcg +scf_lobpcg_sca 025_PW_DS_sca 026_PW_KPAR 027_PW_PINT_RKS diff --git a/tests/01_PW/nscf_hse_same/INPUT b/tests/01_PW/nscf_hse_same/INPUT index a81d44ca265..77a5298dbe7 100644 --- a/tests/01_PW/nscf_hse_same/INPUT +++ b/tests/01_PW/nscf_hse_same/INPUT @@ -10,6 +10,7 @@ ecutwfc 10 scf_thr 1e-9 scf_nmax 100 pw_diag_thr 1e-10 +pw_diag_nmax 30 pw_seed 1 #Parameters (3.Basis) diff --git a/tests/01_PW/scf_lobpcg/INPUT b/tests/01_PW/scf_lobpcg/INPUT new file mode 100644 index 00000000000..2e3c8ee5d69 --- /dev/null +++ b/tests/01_PW/scf_lobpcg/INPUT @@ -0,0 +1,27 @@ +INPUT_PARAMETERS +#Parameters (1.General) +suffix autotest +calculation scf + +nbands 6 +symmetry 1 +pseudo_dir ../../PP_ORB + +#Parameters (2.Iteration) +ecutwfc 20 +scf_thr 1e-8 +scf_nmax 100 + + +#Parameters (3.Basis) +basis_type pw + +#Parameters (4.Smearing) +smearing_method gauss +smearing_sigma 0.002 + +#Parameters (5.Mixing) +mixing_type plain +mixing_beta 0.5 + +ks_solver lobpcg diff --git a/tests/01_PW/scf_lobpcg/KPT b/tests/01_PW/scf_lobpcg/KPT new file mode 100644 index 00000000000..c289c0158aa --- /dev/null +++ b/tests/01_PW/scf_lobpcg/KPT @@ -0,0 +1,4 @@ +K_POINTS +0 +Gamma +1 1 1 0 0 0 diff --git a/tests/01_PW/scf_lobpcg/README b/tests/01_PW/scf_lobpcg/README new file mode 100644 index 00000000000..5a4e290e3f1 --- /dev/null +++ b/tests/01_PW/scf_lobpcg/README @@ -0,0 +1 @@ +test LOBPCG method for diagonalization of H with pw basis diff --git a/tests/01_PW/scf_lobpcg/STRU b/tests/01_PW/scf_lobpcg/STRU new file mode 100644 index 00000000000..5ab73f2c9d7 --- /dev/null +++ b/tests/01_PW/scf_lobpcg/STRU @@ -0,0 +1,19 @@ +ATOMIC_SPECIES +Si 14 Si.pz-vbc.UPF + +LATTICE_CONSTANT +10.2 // add lattice constant + +LATTICE_VECTORS +0.0 0.5 0.5 +0.5 0.0 0.5 +0.5 0.5 0.0 + +ATOMIC_POSITIONS +Direct + +Si // Element type +0.0 // magnetism +2 +0.00 0.00 0.00 1 1 1 +0.25 0.25 0.25 1 1 1 diff --git a/tests/01_PW/scf_lobpcg/result.ref b/tests/01_PW/scf_lobpcg/result.ref new file mode 100644 index 00000000000..e73971f14e5 --- /dev/null +++ b/tests/01_PW/scf_lobpcg/result.ref @@ -0,0 +1,6 @@ +etotref -198.2238296207179 +etotperatomref -99.1119148104 +pointgroupref T_d +spacegroupref O_h +nksibzref 1 +totaltimeref diff --git a/tests/01_PW/scf_lobpcg_sca/INPUT b/tests/01_PW/scf_lobpcg_sca/INPUT new file mode 100644 index 00000000000..22a60cc1a47 --- /dev/null +++ b/tests/01_PW/scf_lobpcg_sca/INPUT @@ -0,0 +1,29 @@ +INPUT_PARAMETERS +#Parameters (1.General) +suffix autotest +calculation scf + +nbands 6 +symmetry 1 +pseudo_dir ../../PP_ORB + +#Parameters (2.Iteration) +ecutwfc 20 +scf_thr 1e-8 +scf_nmax 100 + + +#Parameters (3.Basis) +basis_type pw + +#Parameters (4.Smearing) +smearing_method gauss +smearing_sigma 0.002 + +#Parameters (5.Mixing) +mixing_type plain +mixing_beta 0.5 + +ks_solver lobpcg +diag_subspace 2 +nb2d 16 diff --git a/tests/01_PW/scf_lobpcg_sca/KPT b/tests/01_PW/scf_lobpcg_sca/KPT new file mode 100644 index 00000000000..c289c0158aa --- /dev/null +++ b/tests/01_PW/scf_lobpcg_sca/KPT @@ -0,0 +1,4 @@ +K_POINTS +0 +Gamma +1 1 1 0 0 0 diff --git a/tests/01_PW/scf_lobpcg_sca/README b/tests/01_PW/scf_lobpcg_sca/README new file mode 100644 index 00000000000..21cdecea66e --- /dev/null +++ b/tests/01_PW/scf_lobpcg_sca/README @@ -0,0 +1 @@ +test LOBPCG with the ScaLAPACK reduced-space backend for a pw basis diff --git a/tests/01_PW/scf_lobpcg_sca/STRU b/tests/01_PW/scf_lobpcg_sca/STRU new file mode 100644 index 00000000000..5ab73f2c9d7 --- /dev/null +++ b/tests/01_PW/scf_lobpcg_sca/STRU @@ -0,0 +1,19 @@ +ATOMIC_SPECIES +Si 14 Si.pz-vbc.UPF + +LATTICE_CONSTANT +10.2 // add lattice constant + +LATTICE_VECTORS +0.0 0.5 0.5 +0.5 0.0 0.5 +0.5 0.5 0.0 + +ATOMIC_POSITIONS +Direct + +Si // Element type +0.0 // magnetism +2 +0.00 0.00 0.00 1 1 1 +0.25 0.25 0.25 1 1 1 diff --git a/tests/01_PW/scf_lobpcg_sca/result.ref b/tests/01_PW/scf_lobpcg_sca/result.ref new file mode 100644 index 00000000000..e73971f14e5 --- /dev/null +++ b/tests/01_PW/scf_lobpcg_sca/result.ref @@ -0,0 +1,6 @@ +etotref -198.2238296207179 +etotperatomref -99.1119148104 +pointgroupref T_d +spacegroupref O_h +nksibzref 1 +totaltimeref