From 2c4117b9264355dbf44aceea2e08bfa4d4ef2594 Mon Sep 17 00:00:00 2001 From: abacus_fixer Date: Sun, 22 Nov 2026 09:31:54 +0800 Subject: [PATCH 01/13] feat(matrix): add overflow-safe size and index helpers Add ModuleBase::matrix_size and ModuleBase::matrix_index so LCAO matrices with more than INT_MAX elements (issue #8342, NLOCAL=377884) never compute the element count or row-major offset in int. --- source/source_base/matrix.h | 40 ++++++++++++++++++ source/source_base/unittests/CMakeLists.txt | 6 +++ source/source_base/unittests/test_matrix.cpp | 44 ++++++++++++++++++++ 3 files changed, 90 insertions(+) create mode 100644 source/source_base/unittests/test_matrix.cpp diff --git a/source/source_base/matrix.h b/source/source_base/matrix.h index 16f989951ab..2baf4a24033 100644 --- a/source/source_base/matrix.h +++ b/source/source_base/matrix.h @@ -6,11 +6,51 @@ #include #include +#include #include // test +#include +#include namespace ModuleBase { +/** + * @brief Return nrows * ncols as size_t. + * + * LCAO matrices can exceed INT_MAX elements: for NLOCAL = 377884 the product + * nrows * ncols is about 1.4e11, while INT_MAX is only 2.1e9 (issue #8342). + * Computing the product in int overflows and turns a large allocation into a + * negative element count, so every matrix size goes through this helper. + */ +inline std::size_t matrix_size(const int nrows, const int ncols) +{ + if (nrows < 0 || ncols < 0) + { + throw std::length_error("ModuleBase::matrix: negative matrix dimension"); + } + + const std::size_t rows = static_cast(nrows); + const std::size_t cols = static_cast(ncols); + if (cols != 0 && rows > std::numeric_limits::max() / cols) + { + throw std::length_error("ModuleBase::matrix: element count overflows size_t"); + } + return rows * cols; +} + +/** + * @brief Return the row-major index of (ir, ic) as size_t. + * + * The caller must guarantee that ir/ic are non-negative and in range. The + * multiplication is done in size_t because ir * ncols overflows int for large + * LCAO basis sets even when the total element count still fits in int. + */ +inline std::size_t matrix_index(const int ir, const int ic, const int ncols) +{ + return static_cast(ir) * static_cast(ncols) + + static_cast(ic); +} + class matrix { /* data */ diff --git a/source/source_base/unittests/CMakeLists.txt b/source/source_base/unittests/CMakeLists.txt index 5381e4f9f59..5acf09f4258 100644 --- a/source/source_base/unittests/CMakeLists.txt +++ b/source/source_base/unittests/CMakeLists.txt @@ -11,3 +11,9 @@ AddTest( LIBS parameter base device SOURCES test_filename.cpp ) + +AddTest( + TARGET MODULE_BASE_matrix_overflow + LIBS parameter base device + SOURCES test_matrix.cpp +) diff --git a/source/source_base/unittests/test_matrix.cpp b/source/source_base/unittests/test_matrix.cpp new file mode 100644 index 00000000000..677196933ea --- /dev/null +++ b/source/source_base/unittests/test_matrix.cpp @@ -0,0 +1,44 @@ +#include +#include + +#include + +#include "source_base/matrix.h" + +// Issue #8342: NLOCAL = 377884 makes NLOCAL^2 about 1.4e11, far above +// INT_MAX. The helper must keep the product in size_t. +TEST(MatrixSize, LargeLcaoDimensionsDoNotOverflow) +{ + const std::size_t size = ModuleBase::matrix_size(377884, 377884); + const std::size_t expected = static_cast(377884) * 377884; + EXPECT_EQ(size, expected); + EXPECT_GT(size, static_cast(std::numeric_limits::max())); +} + +TEST(MatrixSize, ZeroDimension) +{ + EXPECT_EQ(ModuleBase::matrix_size(0, 123), 0u); + EXPECT_EQ(ModuleBase::matrix_size(123, 0), 0u); +} + +TEST(MatrixSize, NegativeDimensionThrows) +{ + EXPECT_THROW(ModuleBase::matrix_size(-1, 10), std::length_error); + EXPECT_THROW(ModuleBase::matrix_size(10, -1), std::length_error); +} + +// A row-major index can overflow int even when the total element count is +// still small enough for some allocators, so indexing is separate from sizing. +TEST(MatrixIndex, LargeRowIndexDoesNotOverflow) +{ + const std::size_t index = ModuleBase::matrix_index(100000, 200000, 377884); + const std::size_t expected = static_cast(100000) * 377884 + 200000; + EXPECT_EQ(index, expected); +} + +TEST(MatrixIndex, RowMajorOrder) +{ + EXPECT_EQ(ModuleBase::matrix_index(0, 0, 4), 0u); + EXPECT_EQ(ModuleBase::matrix_index(0, 3, 4), 3u); + EXPECT_EQ(ModuleBase::matrix_index(2, 1, 4), 9u); +} From 9ac126ffd3d6390562ceb0168f2e131ffd02ae4a Mon Sep 17 00:00:00 2001 From: abacus_fixer Date: Sun, 22 Nov 2026 09:33:09 +0800 Subject: [PATCH 02/13] fix(matrix): use size_t for element counts and indexing Allocation, create, copy, zero/fill and row-major indexing now go through matrix_size/matrix_index. The old set_new_handler path exited the process directly; let new throw std::bad_alloc so the driver can report which LCAO matrix failed. norm() chunks BLAS calls so a matrix with more than INT_MAX elements is never passed a wrapped int length. --- source/source_base/matrix.cpp | 157 +++++++++---------- source/source_base/matrix.h | 4 +- source/source_base/unittests/test_matrix.cpp | 26 +++ 3 files changed, 106 insertions(+), 81 deletions(-) diff --git a/source/source_base/matrix.cpp b/source/source_base/matrix.cpp index 7461c8e0787..ed756973184 100644 --- a/source/source_base/matrix.cpp +++ b/source/source_base/matrix.cpp @@ -6,7 +6,6 @@ #include #include #include -#include #include #include "matrix.h" @@ -26,23 +25,16 @@ namespace ModuleBase { -void matrixAlloc() -{ - std::cerr << "Allocation error for Matrix" << std::endl; - std::exit(EXIT_FAILURE); -} - /*create a matrix with nrows*ncols size */ matrix::matrix( const int nrows, const int ncols, const bool flag_zero ) :nr(nrows), nc(ncols), c(nullptr) { - if( nr && nc ) + const std::size_t size = matrix_size(nr, nc); + if( size ) { - auto handler_old = std::set_new_handler(matrixAlloc); - c = new double[nr*nc]; - std::set_new_handler(handler_old); + c = new double[size]; if(flag_zero) this->zero_out(); } } @@ -52,12 +44,11 @@ matrix::matrix( const matrix &m_in ) nc(m_in.nc), c(nullptr) { - if( nr && nc ) + const std::size_t size = matrix_size(nr, nc); + if( size ) { - auto handler_old = std::set_new_handler(matrixAlloc); - c = new double[nr*nc]; - std::set_new_handler(handler_old); - memcpy( c, m_in.c, nr*nc*sizeof(double) ); + c = new double[size]; + memcpy( c, m_in.c, size*sizeof(double) ); } } @@ -77,9 +68,10 @@ matrix& matrix::operator=( const matrix & m_in ) this->create( m_in.nr, m_in.nc, false ); // `create` leaves `c` null for an empty matrix, and memcpy's arguments are declared // non-null even for a zero count -- so assigning an empty matrix is undefined behaviour. - if( nr && nc ) + const std::size_t size = matrix_size(nr, nc); + if( size ) { - memcpy( c, m_in.c, nr*nc*sizeof(double) ); + memcpy( c, m_in.c, size*sizeof(double) ); } return *this; } @@ -129,45 +121,37 @@ matrix::~matrix() // Peize Lin change 2018-07-29 void matrix::create( const int nrow, const int ncol, const bool flag_zero ) { - if( nrow && ncol ) - { - if(c) - { - const int size=nrow*ncol; - if( size!=nr*nc ) - { - delete[] c; - auto handler_old = std::set_new_handler(matrixAlloc); - c = new double[size]; - std::set_new_handler(handler_old); - } - } - else - { - auto handler_old = std::set_new_handler(matrixAlloc); - c = new double[nrow * ncol]; - std::set_new_handler(handler_old); - } - - nr = nrow; - nc = ncol; - if(flag_zero) zero_out(); // Peize Lin change 2018-03-12 - } - else + const std::size_t new_size = matrix_size(nrow, ncol); + if( new_size == 0 ) { if(c) delete[] c; c = nullptr; nr = nrow; nc = ncol; + return; + } + + const std::size_t old_size = ( c != nullptr ) ? matrix_size(nr, nc) : 0; + if( c == nullptr || new_size != old_size ) + { + // Allocate before releasing the old buffer so a bad_alloc leaves the + // matrix unchanged and the caller can still report the failure. + double* new_data = new double[new_size]; + delete[] c; + c = new_data; } + + nr = nrow; + nc = ncol; + if(flag_zero) zero_out(); // Peize Lin change 2018-03-12 } /* Unary minus*/ matrix operator-(const matrix& m1) { matrix tm(m1); - const int size = m1.nr * m1.nc; - for (int i = 0; i < size; i++) + const std::size_t size = matrix_size(m1.nr, m1.nc); + for (std::size_t i = 0; i < size; i++) tm.c[i] = -tm.c[i]; return tm; } @@ -179,8 +163,8 @@ matrix operator+(const matrix &m1, const matrix &m2) assert(m1.nc == m2.nc); matrix tm(m1); - const int size = m1.nr*m1.nc; - for (int i = 0; i < size; i++) + const std::size_t size = matrix_size(m1.nr, m1.nc); + for (std::size_t i = 0; i < size; i++) { tm.c[i] += m2.c[i]; } @@ -194,8 +178,8 @@ matrix operator-(const matrix &m1, const matrix &m2) assert(m1.nc == m2.nc); matrix tm(m1); - const int size = m1.nr*m1.nc; - for(int i = 0; i < size; i++) + const std::size_t size = matrix_size(m1.nr, m1.nc); + for(std::size_t i = 0; i < size; i++) { tm.c[i] -= m2.c[i]; } @@ -244,8 +228,8 @@ matrix operator*(const matrix &m1, const matrix &m2) matrix operator*(const double &s, const matrix &m) { matrix sm(m); - const int size=m.nr*m.nc; - for (int i = 0; i < size; i++) + const std::size_t size = matrix_size(m.nr, m.nc); + for (std::size_t i = 0; i < size; i++) { sm.c[i] *= s; } @@ -256,8 +240,8 @@ matrix operator*(const double &s, const matrix &m) matrix operator*(const matrix &m,const double &s) { matrix sm(m); - const int size=m.nr*m.nc; - for (int i = 0; i < size; i++) + const std::size_t size = matrix_size(m.nr, m.nc); + for (std::size_t i = 0; i < size; i++) { sm.c[i] *= s; } @@ -267,23 +251,23 @@ matrix operator*(const matrix &m,const double &s) /* Scale a matrix in place */ void matrix::operator*=(const double &s) { - const int size=nc*nr; - for (int i = 0; i < size; i++) + const std::size_t size = matrix_size(nr, nc); + for (std::size_t i = 0; i < size; i++) c[i] *= s; } /* Accumulate to a matrix in place */ void matrix::operator+=(const matrix & m) { - if(nc*nr==0) + if(nr == 0 || nc == 0) { return; } assert( nr==m.nr ); assert( nc==m.nc ); - const int size=nc*nr; + const std::size_t size = matrix_size(nr, nc); const double * const c_in = m.c; - for( int i = 0; i < size; ++i ) + for( std::size_t i = 0; i < size; ++i ) { c[i] += c_in[i]; } @@ -293,15 +277,15 @@ void matrix::operator+=(const matrix & m) /* decumulate to a matrix in place */ void matrix::operator-=(const matrix & m) { - if(nc*nr==0) + if(nr == 0 || nc == 0) { return; } assert( nr==m.nr ); assert( nc==m.nc ); - const int size=nc*nr; + const std::size_t size = matrix_size(nr, nc); const double * const c_in = m.c; - for( int i = 0; i < size; ++i ) + for( std::size_t i = 0; i < size; ++i ) { c[i] -= c_in[i]; } @@ -310,24 +294,24 @@ void matrix::operator-=(const matrix & m) /* zero out the matrix */ void matrix::zero_out(void) { - const int size = nr*nc; + const std::size_t size = matrix_size(nr, nc); if(size == 0) { return; } - for(int i = 0; i < size; i++) + for(std::size_t i = 0; i < size; i++) c[i] = 0.0; } /* fill out the matrix with a constant double*/ void matrix::fill_out(const double x) { - const int size = nr*nc; + const std::size_t size = matrix_size(nr, nc); if(size == 0) { return; } - for(int i = 0; i < size; i++) + for(std::size_t i = 0; i < size; i++) c[i] = x; } @@ -343,10 +327,10 @@ matrix transpose(const matrix &m) double matrix::trace_on(void) const { assert(nr == nc); - int inch = nc + 1; - int size = nr * nc; + const std::size_t size = matrix_size(nr, nc); + const std::size_t inch = static_cast(nc) + 1; double tr = 0.0; - for (int i = 0; i < size; i += inch) + for (std::size_t i = 0; i < size; i += inch) { tr += c[i]; } @@ -356,7 +340,9 @@ double matrix::trace_on(void) const // Peize Lin add 2017-05-27 void matrix::reshape( const int nr_new, const int nc_new, const bool flag_zero ) { - assert( nr*nc == nr_new*nc_new ); + const std::size_t old_size = matrix_size(nr, nc); + const std::size_t new_size = matrix_size(nr_new, nc_new); + assert( old_size == new_size ); nr=nr_new; nc=nc_new; @@ -379,10 +365,10 @@ double mdot(const matrix &A, const matrix &B) { assert (A.nr == B.nr); assert (A.nc == B.nc); - const int size = A.nr * A.nc; + const std::size_t size = matrix_size(A.nr, A.nc); double sum = 0.0; - for (int i = 0; i < size; ++i) + for (std::size_t i = 0; i < size; ++i) sum += A.c[i] * B.c[i]; return sum; } @@ -428,8 +414,8 @@ std::ostream & matrix::print( std::ostream & os, const double threshold ) const double matrix::max() const { double value = std::numeric_limits::min(); - const int size = nr * nc; - for( int i=0; i::max(); - const int size = nr * nc; - for( int i=0; i(1) << 30; + for (std::size_t offset = 0; offset < size; offset += chunk_limit) + { + const std::size_t remaining = size - offset; + const std::size_t chunk_size = remaining > chunk_limit ? chunk_limit : remaining; + const int chunk = static_cast(chunk_size); + const double partial = BlasConnector::nrm2(chunk, c + offset, 1); + nn += partial * partial; + } + return sqrt(nn); #endif } diff --git a/source/source_base/matrix.h b/source/source_base/matrix.h index 2baf4a24033..8c0614ab6bb 100644 --- a/source/source_base/matrix.h +++ b/source/source_base/matrix.h @@ -74,13 +74,13 @@ class matrix double &operator()(const int ir,const int ic) { assert(ir>=0); assert(ir=0); assert(ic=0); assert(ir=0); assert(ic Date: Sun, 22 Nov 2026 09:42:08 +0800 Subject: [PATCH 03/13] fix(complexmatrix): use size_t for element counts and indexing ComplexMatrix::size is now size_t, and allocation, create, copy, fill and row-major indexing go through matrix_size/matrix_index. This is the same overflow class as issue #8342: NLOCAL=377884 gives a local block of about 2.5e9 elements, which no longer fits in int. --- source/source_base/complexmatrix.cpp | 88 +++++++++---------- source/source_base/complexmatrix.h | 8 +- source/source_base/unittests/CMakeLists.txt | 6 ++ .../unittests/test_complexmatrix.cpp | 64 ++++++++++++++ 4 files changed, 119 insertions(+), 47 deletions(-) create mode 100644 source/source_base/unittests/test_complexmatrix.cpp diff --git a/source/source_base/complexmatrix.cpp b/source/source_base/complexmatrix.cpp index 6c07014ee50..6ed4f8a6ef5 100644 --- a/source/source_base/complexmatrix.cpp +++ b/source/source_base/complexmatrix.cpp @@ -16,9 +16,10 @@ namespace ModuleBase ComplexMatrix::ComplexMatrix(const int nrows, const int ncols, const bool flag_zero) :nr(nrows), nc(ncols), - size(nrows*ncols), + size(0), c(nullptr) { + size = matrix_size(nr, nc); if( size ) { c = new std::complex[size]; @@ -29,7 +30,7 @@ ComplexMatrix::ComplexMatrix(const int nrows, const int ncols, const bool flag_z // zero out the ComplexMatrix void ComplexMatrix::zero_out(void) { - for (int i=0; i(0.0,0.0); + for (std::size_t i=0; i(0.0,0.0); } /* @@ -69,13 +70,14 @@ ComplexMatrix::ComplexMatrix( ComplexMatrix && m1 ) ComplexMatrix::ComplexMatrix(const matrix &m) :nr(m.nr), nc(m.nc), - size(m.nr*m.nc), + size(0), c(nullptr) { + size = matrix_size(nr, nc); if( size ) { c = new std::complex[size]; - for( int i=0; i[size_in]; - } - } - else - { - c = new std::complex[nr_in * nc_in]; - } - - nr = nr_in; - nc = nc_in; - size = nr*nc; - if(flag_zero) zero_out(); - } - else + const std::size_t new_size = matrix_size(nr_in, nc_in); + if( new_size == 0 ) { if(c) delete[] c; c = nullptr; nr = nr_in; nc = nc_in; - size = nr*nc; + size = 0; + return; + } + + if( c == nullptr || new_size != size ) + { + // Allocate before releasing the old buffer so a bad_alloc leaves the + // matrix unchanged and the caller can still report the failure. + std::complex* new_data = new std::complex[new_size]; + delete[] c; + c = new_data; } + + nr = nr_in; + nc = nc_in; + size = new_size; + if(flag_zero) zero_out(); } void ComplexMatrix::set_as_identity_matrix(void) @@ -132,8 +129,8 @@ void ComplexMatrix::set_as_identity_matrix(void) { for(int j=0; j(1.0, 0.0); - else c[nc * i + j] = std::complex(0.0, 0.0); + if(i==j) c[matrix_index(i, j, nc)] = std::complex(1.0, 0.0); + else c[matrix_index(i, j, nc)] = std::complex(0.0, 0.0); } } return; @@ -197,7 +194,7 @@ ComplexMatrix operator*(const ComplexMatrix &m1, const ComplexMatrix &m2) ComplexMatrix operator*(const std::complex &c,const ComplexMatrix &m) { ComplexMatrix sm(m); - for (int i=0 ;i &c,const ComplexMatrix &m) ComplexMatrix operator*(const ComplexMatrix &m,const std::complex &c) { ComplexMatrix sm(m); - for (int i = 0;i < m.size;i++) sm.c[i] *= c; + for (std::size_t i = 0;i < m.size;i++) sm.c[i] *= c; return sm; } ComplexMatrix operator*(const double &r,const ComplexMatrix &m) { ComplexMatrix sm(m); - for(int i=0; icreate(m.nr, m.nc, false); - memcpy( c, m.c, size*sizeof(std::complex) ); + if( size ) + { + memcpy( c, m.c, size*sizeof(std::complex) ); + } return *this; } @@ -243,21 +243,21 @@ ComplexMatrix& ComplexMatrix::operator=( ComplexMatrix && m ) ComplexMatrix& ComplexMatrix::operator*=(const std::complex &s) { - for (int i = 0;i < this->size;i++) c[i] *= s; + for (std::size_t i = 0;i < this->size;i++) c[i] *= s; return *this; } // Accumulate to a ComplexMatrix in place ComplexMatrix& ComplexMatrix::operator+=(const ComplexMatrix &m) { - for(int i=0; ic[i] += m.c[i]; + for(std::size_t i=0; ic[i] += m.c[i]; return *this; } // decumulate to a ComplexMatrix in place ComplexMatrix& ComplexMatrix::operator-=(const ComplexMatrix &m) { - for(int i=0; ic[i] -= m.c[i]; + for(std::size_t i=0; ic[i] -= m.c[i]; return *this; } @@ -265,7 +265,7 @@ ComplexMatrix& ComplexMatrix::operator-=(const ComplexMatrix &m) matrix ComplexMatrix::real() const { matrix m(nr,nc,false); - for( int i=0; isize; ++i) m.c[i] = c[i].real(); + for( std::size_t i=0; isize; ++i) m.c[i] = c[i].real(); return m; } @@ -285,7 +285,7 @@ void scale_accumulate(const std::complex &s, { assert(min.nr == mout.nr); assert(min.nc == mout.nc); - for (int j=0; j &s1, assert(m1.nc == m2.nc); assert(m1.nc == mout.nc); - for(int i=0; i z; for(int ic=0;ic z; for(int ir=0;ir z; - for (int i = 0;i < m.size;i++) + for (std::size_t i = 0;i < m.size;i++) { z = m.c[i]; r += z.real() * z.real() + z.imag() * z.imag(); @@ -408,7 +408,7 @@ ComplexMatrix transpose(const ComplexMatrix &m, const bool &conjugate) ComplexMatrix conj(const ComplexMatrix &m) { ComplexMatrix cm( m.nr, m.nc, false ); - for(int i=0; i!=m.size; ++i) + for(std::size_t i=0; i!=m.size; ++i) cm.c[i] = conj(m.c[i]); return cm; } diff --git a/source/source_base/complexmatrix.h b/source/source_base/complexmatrix.h index c47ab8f333e..422952dfd15 100644 --- a/source/source_base/complexmatrix.h +++ b/source/source_base/complexmatrix.h @@ -14,7 +14,9 @@ class ComplexMatrix int nr=0; int nc=0; - int size=0; + /// Element count. Kept in size_t because an LCAO matrix can exceed + /// INT_MAX elements (issue #8342: NLOCAL = 377884 gives ~1.4e11). + std::size_t size=0; std::complex *c=nullptr; ComplexMatrix(): nr(0), nc(0), size(0), c(nullptr){} @@ -34,12 +36,12 @@ class ComplexMatrix std::complex &operator()(const int ir,const int ic) { assert(ir>=0); assert(ir=0); assert(ic &operator()(const int ir,const int ic)const { assert(ir>=0); assert(ir=0); assert(ic &s); diff --git a/source/source_base/unittests/CMakeLists.txt b/source/source_base/unittests/CMakeLists.txt index 5acf09f4258..4612dd5d799 100644 --- a/source/source_base/unittests/CMakeLists.txt +++ b/source/source_base/unittests/CMakeLists.txt @@ -17,3 +17,9 @@ AddTest( LIBS parameter base device SOURCES test_matrix.cpp ) + +AddTest( + TARGET MODULE_BASE_complexmatrix_overflow + LIBS parameter base device + SOURCES test_complexmatrix.cpp +) diff --git a/source/source_base/unittests/test_complexmatrix.cpp b/source/source_base/unittests/test_complexmatrix.cpp new file mode 100644 index 00000000000..5f69ced8daf --- /dev/null +++ b/source/source_base/unittests/test_complexmatrix.cpp @@ -0,0 +1,64 @@ +#include +#include + +#include + +#include "source_base/complexmatrix.h" + +TEST(ComplexMatrix, ElementAccessUsesSizeTIndex) +{ + ModuleBase::ComplexMatrix m(3, 4, true); + m(2, 3) = std::complex(1.0, -2.0); + EXPECT_DOUBLE_EQ(std::real(m(2, 3)), 1.0); + EXPECT_DOUBLE_EQ(std::imag(m(2, 3)), -2.0); +} + +TEST(ComplexMatrix, SizeIsElementCount) +{ + ModuleBase::ComplexMatrix m(3, 4); + EXPECT_EQ(m.size, 12u); +} + +TEST(ComplexMatrix, NegativeConstructorThrows) +{ + EXPECT_THROW(ModuleBase::ComplexMatrix m(-1, 4), std::length_error); +} + +TEST(ComplexMatrix, CreateNegativeThrows) +{ + ModuleBase::ComplexMatrix m; + EXPECT_THROW(m.create(-1, 4), std::length_error); +} + +TEST(ComplexMatrix, EmptyMatrixHasNoStorage) +{ + ModuleBase::ComplexMatrix m(0, 4); + EXPECT_EQ(m.nr, 0); + EXPECT_EQ(m.nc, 4); + EXPECT_EQ(m.size, 0u); + EXPECT_EQ(m.c, nullptr); +} + +TEST(ComplexMatrix, IdentityMatrix) +{ + ModuleBase::ComplexMatrix m(2, 2, false); + m.set_as_identity_matrix(); + EXPECT_DOUBLE_EQ(std::real(m(0, 0)), 1.0); + EXPECT_DOUBLE_EQ(std::real(m(1, 1)), 1.0); + EXPECT_DOUBLE_EQ(std::real(m(0, 1)), 0.0); + EXPECT_DOUBLE_EQ(std::real(m(1, 0)), 0.0); +} + +TEST(ComplexMatrix, FromRealMatrix) +{ + ModuleBase::matrix r(3, 4); + for (int i = 0; i < 12; ++i) + { + r.c[i] = static_cast(i); + } + + ModuleBase::ComplexMatrix m(r); + EXPECT_EQ(m.size, 12u); + EXPECT_DOUBLE_EQ(std::real(m(2, 3)), 11.0); + EXPECT_DOUBLE_EQ(std::imag(m(2, 3)), 0.0); +} From 8c29089f6f29a331c07dc326aad1034196290bfa Mon Sep 17 00:00:00 2001 From: abacus_fixer Date: Sun, 22 Nov 2026 10:52:35 +0800 Subject: [PATCH 04/13] fix(dm): use size_t for DMK element counts and indexing The local DMK block is nrloc*ncloc, about 2.55e9 elements for NLOCAL=377884 on 56 ranks (issue #8342). Compute it in size_t for resize, set/get and Memory::record so vector::resize no longer receives a wrapped int count. --- .../module_dm/density_matrix.cpp | 31 ++++++++++++------- .../source_estate/module_dm/density_matrix.h | 26 ++++++++++++++++ source/source_estate/module_dm/dm_getter.cpp | 2 +- source/source_estate/module_dm/dm_setter.cpp | 7 +++-- .../unittests/test_dm_constructor.cpp | 16 ++++++++++ 5 files changed, 66 insertions(+), 16 deletions(-) diff --git a/source/source_estate/module_dm/density_matrix.cpp b/source/source_estate/module_dm/density_matrix.cpp index b287809897b..565b458ea32 100644 --- a/source/source_estate/module_dm/density_matrix.cpp +++ b/source/source_estate/module_dm/density_matrix.cpp @@ -1,5 +1,7 @@ #include "density_matrix.h" +#include + #include "source_io/module_parameter/parameter.h" #include "source_base/libm/libm.h" #include "source_base/memory_recorder.h" @@ -46,11 +48,14 @@ DensityMatrix::DensityMatrix(const Parallel_Orbitals* paraV_in, ModuleBase::TITLE("DensityMatrix", "resize_DMK"); const int nks = _nk * this->spin_mult; this->dmk.resize(nks); + // Keep the local element count in size_t: nrloc*ncloc is about 2.55e9 + // for NLOCAL = 377884 on 56 ranks, which is above INT_MAX (issue #8342). + const std::size_t local_size = dmk_element_count(this->pv); for (int ik = 0; ik < nks; ik++) { - this->dmk[ik].resize(this->pv->para_2d().nrloc() * this->pv->para_2d().ncloc()); + this->dmk[ik].resize(local_size); } - ModuleBase::Memory::record("DensityMatrix::DMK", this->dmk.size() * this->dmk[0].size() * sizeof(TK)); + ModuleBase::Memory::record("DensityMatrix::DMK", this->dmk.size() * local_size * sizeof(TK)); } template @@ -60,11 +65,13 @@ DensityMatrix::DensityMatrix(const Parallel_Orbitals* paraV_in, const in { ModuleBase::TITLE("DensityMatrix", "resize_gamma"); this->dmk.resize(this->spin_mult); + // Same size_t reason as the multi-k constructor above. + const std::size_t local_size = dmk_element_count(this->pv); for (int ik = 0; ik < this->spin_mult; ik++) { - this->dmk[ik].resize(this->pv->para_2d().nrloc() * this->pv->para_2d().ncloc()); + this->dmk[ik].resize(local_size); } - ModuleBase::Memory::record("DensityMatrix::DMK", this->dmk.size() * this->dmk[0].size() * sizeof(TK)); + ModuleBase::Memory::record("DensityMatrix::DMK", this->dmk.size() * local_size * sizeof(TK)); } @@ -91,10 +98,10 @@ void DensityMatrix::switch_dmr(const int mode) // switch to total magnetization density matrix, dmr_up + dmr_down if(this->dmr_tmp.empty()) { - const size_t size = this->dmr[0]->get_nnr(); + const std::size_t size = this->dmr[0]->get_nnr(); this->dmr_tmp.resize(size); this->dmr_origin.resize(size); - for (int i = 0; i < size; ++i) + for (std::size_t i = 0; i < size; ++i) { this->dmr_origin[i] = this->dmr[0]->get_wrapper()[i]; this->dmr_tmp[i] = this->dmr_origin[i] + this->dmr[1]->get_wrapper()[i]; @@ -103,8 +110,8 @@ void DensityMatrix::switch_dmr(const int mode) } else { - const size_t size = this->dmr[0]->get_nnr(); - for (int i = 0; i < size; ++i) + const std::size_t size = this->dmr[0]->get_nnr(); + for (std::size_t i = 0; i < size; ++i) { this->dmr_tmp[i] = this->dmr_origin[i] + this->dmr[1]->get_wrapper()[i]; } @@ -114,10 +121,10 @@ void DensityMatrix::switch_dmr(const int mode) // switch to magnetization density matrix, dmr_up - dmr_down if(this->dmr_tmp.empty()) { - const size_t size = this->dmr[0]->get_nnr(); + const std::size_t size = this->dmr[0]->get_nnr(); this->dmr_tmp.resize(size); this->dmr_origin.resize(size); - for (int i = 0; i < size; ++i) + for (std::size_t i = 0; i < size; ++i) { this->dmr_origin[i] = this->dmr[0]->get_wrapper()[i]; this->dmr_tmp[i] = this->dmr_origin[i] - this->dmr[1]->get_wrapper()[i]; @@ -126,8 +133,8 @@ void DensityMatrix::switch_dmr(const int mode) } else { - const size_t size = this->dmr[0]->get_nnr(); - for (int i = 0; i < size; ++i) + const std::size_t size = this->dmr[0]->get_nnr(); + for (std::size_t i = 0; i < size; ++i) { this->dmr_tmp[i] = this->dmr_origin[i] - this->dmr[1]->get_wrapper()[i]; } diff --git a/source/source_estate/module_dm/density_matrix.h b/source/source_estate/module_dm/density_matrix.h index 14f79c88626..68e53b23082 100644 --- a/source/source_estate/module_dm/density_matrix.h +++ b/source/source_estate/module_dm/density_matrix.h @@ -2,6 +2,7 @@ #define DENSITY_MATRIX_H #include +#include #include #include #include @@ -35,6 +36,31 @@ struct ShiftRealComplex> using type = double; }; +/** + * @brief Number of local elements in one DMK matrix. + * + * nrloc*ncloc is about 2.55e9 for NLOCAL = 377884 on 56 ranks, which is + * larger than INT_MAX (issue #8342). Computing it in int overflows and + * makes vector::resize throw std::length_error. + */ +inline std::size_t dmk_element_count(const Parallel_Orbitals* pv) +{ + return static_cast(pv->para_2d().nrloc()) + * static_cast(pv->para_2d().ncloc()); +} + +/** + * @brief Row-major index inside one local DMK matrix. + * + * The caller must ensure that i/j are in range. i*nrloc overflows int for + * large LCAO bases even when the local element count still fits in int. + */ +inline std::size_t dmk_index(const int i, const int j, const int nrows) +{ + return static_cast(i) * static_cast(nrows) + + static_cast(j); +} + /** * @brief DensityMatrix Class * = for Gamma-only calculation diff --git a/source/source_estate/module_dm/dm_getter.cpp b/source/source_estate/module_dm/dm_getter.cpp index 9a3607c1d5c..a3fe81a83bd 100644 --- a/source/source_estate/module_dm/dm_getter.cpp +++ b/source/source_estate/module_dm/dm_getter.cpp @@ -47,7 +47,7 @@ TK DensityMatrix::get_dmk(const int ispin, const int ik, const int i, co assert(ispin > 0 && ispin <= this->spin_mult); #endif // consider transpose col=>row - return this->dmk[ik + this->_nk * (ispin - 1)][i * this->pv->para_2d().nrloc() + j]; + return this->dmk[ik + this->_nk * (ispin - 1)][dmk_index(i, j, this->pv->para_2d().nrloc())]; } // get dmk nks, nrow, ncol diff --git a/source/source_estate/module_dm/dm_setter.cpp b/source/source_estate/module_dm/dm_setter.cpp index 35cdba9d571..5a06d8a3c0c 100644 --- a/source/source_estate/module_dm/dm_setter.cpp +++ b/source/source_estate/module_dm/dm_setter.cpp @@ -22,7 +22,7 @@ void DensityMatrix::set_dmk_ptr(const int ik, TK* DMK_in) #ifdef __DEBUG assert(ik < this->_nk * this->spin_mult); #endif - this->dmk[ik].assign(DMK_in, DMK_in + this->pv->para_2d().nrloc() * this->pv->para_2d().ncloc()); + this->dmk[ik].assign(DMK_in, DMK_in + dmk_element_count(this->pv)); } // set dmk element @@ -34,7 +34,7 @@ void DensityMatrix::set_dmk(const int ispin, const int ik, const int i, assert(ik >= 0 && ik < this->_nk); #endif // consider transpose col=>row - this->dmk[ik + this->_nk * (ispin - 1)][i * this->pv->para_2d().nrloc() + j] = value; + this->dmk[ik + this->_nk * (ispin - 1)][dmk_index(i, j, this->pv->para_2d().nrloc())] = value; } // set dmk element @@ -53,7 +53,8 @@ void DensityMatrix::save_dmr() ModuleBase::TITLE("DensityMatrix", "save_dmr"); ModuleBase::timer::start("DensityMatrix", "save_dmr"); - const int nnr = this->dmr[0]->get_nnr(); + // nnr is a global matrix-element count, so it must not be narrowed to int. + const std::size_t nnr = this->dmr[0]->get_nnr(); // allocate if dmr_save is empty if (dmr_save.size() == 0) { diff --git a/source/source_estate/module_dm/unittests/test_dm_constructor.cpp b/source/source_estate/module_dm/unittests/test_dm_constructor.cpp index a8a1f676a2d..8be7eb860c0 100644 --- a/source/source_estate/module_dm/unittests/test_dm_constructor.cpp +++ b/source/source_estate/module_dm/unittests/test_dm_constructor.cpp @@ -89,6 +89,22 @@ class DMTest : public testing::Test #endif }; +TEST_F(DMTest, DmkElementCountUsesSizeT) +{ + // Issue #8342: the local block can exceed INT_MAX elements even when + // nrloc() and ncloc() themselves fit in int. + const std::size_t expected = static_cast(paraV->para_2d().nrloc()) + * static_cast(paraV->para_2d().ncloc()); + EXPECT_EQ(module_dm::dmk_element_count(paraV), expected); +} + +TEST_F(DMTest, DmkIndexUsesSizeT) +{ + const std::size_t index = module_dm::dmk_index(100000, 200000, 377884); + const std::size_t expected = static_cast(100000) * 377884 + 200000; + EXPECT_EQ(index, expected); +} + TEST_F(DMTest, DMConstructor_GammaOnly) { // construct DM From 5b69e51aa438e0c10fa4ec75fdbfa31fb24f0a08 Mon Sep 17 00:00:00 2001 From: abacus_fixer Date: Sun, 22 Nov 2026 10:52:38 +0800 Subject: [PATCH 05/13] fix(dm): keep DMR and DM-from-psi offsets in size_t DMR block offsets use a global column times the local row stride, and dm_from_psi uses ib_local*nbasis_local (~2.8e10 in issue #8342). Both overflowed int. Also avoid touching dmr[0] when DMR_in is empty. --- source/source_estate/module_dm/dm_from_psi.cpp | 6 +++++- source/source_estate/module_dm/dm_tools.cpp | 11 ++++++----- source/source_estate/module_dm/dmr_full.cpp | 4 ++-- source/source_estate/module_dm/dmr_gamma.cpp | 5 +++-- source/source_estate/module_dm/dmr_init.cpp | 7 ++++++- 5 files changed, 22 insertions(+), 11 deletions(-) diff --git a/source/source_estate/module_dm/dm_from_psi.cpp b/source/source_estate/module_dm/dm_from_psi.cpp index b4c4a0436a7..3197d1ce659 100644 --- a/source/source_estate/module_dm/dm_from_psi.cpp +++ b/source/source_estate/module_dm/dm_from_psi.cpp @@ -2,6 +2,7 @@ #include #include +#include #include #include "source_base/module_external/blas_connector.h" @@ -86,7 +87,10 @@ void fill_weighted_wfc(const Parallel_Orbitals* ParaV, #endif for (int ib_local = 0; ib_local < nbands_local; ++ib_local) { - const int offset = ib_local * nbasis_local; + // nbands_local*nbasis_local is about 2.8e10 for the issue #8342 case, + // so the row offset must not be computed in int. + const std::size_t offset = static_cast(ib_local) + * static_cast(nbasis_local); const double factor_ib = factor[ib_local]; for (int iw = 0; iw < nbasis_local; ++iw) { diff --git a/source/source_estate/module_dm/dm_tools.cpp b/source/source_estate/module_dm/dm_tools.cpp index df7c260f35b..4569952ddd4 100644 --- a/source/source_estate/module_dm/dm_tools.cpp +++ b/source/source_estate/module_dm/dm_tools.cpp @@ -129,7 +129,8 @@ void transpose_dmk_block( { for (int irow = 0; irow < block.nrows; ++irow) { - dmk_row[irow * block.ncols + icol] = dmk_col_major[icol * ld_hk + irow]; + // ld_hk is the global row stride; keep the offset in size_t. + dmk_row[irow * block.ncols + icol] = dmk_col_major[dmk_index(icol, irow, ld_hk)]; } } } @@ -149,7 +150,7 @@ void add_dmr_real( if (ik_in >= 0) { // single k-point - const TK* const dmk_col = dm.dmk[ik_in + ik_begin].data() + block.col0 * ld_hk + block.row0; + const TK* const dmk_col = dm.dmk[ik_in + ik_begin].data() + dmk_index(block.col0, block.row0, ld_hk); transpose_dmk_block(dmk_col, ld_hk, block, dmk_row.data()); for (int iR = 0; iR < R_size; ++iR) { @@ -161,7 +162,7 @@ void add_dmr_real( // all k-points for (int ik = 0; ik < dm._nk; ++ik) { - const TK* const dmk_col = dm.dmk[ik + ik_begin].data() + block.col0 * ld_hk + block.row0; + const TK* const dmk_col = dm.dmk[ik + ik_begin].data() + dmk_index(block.col0, block.row0, ld_hk); transpose_dmk_block(dmk_col, ld_hk, block, dmk_row.data()); for (int iR = 0; iR < R_size; ++iR) { @@ -191,7 +192,7 @@ void add_dmr_soc( if (ik_in >= 0) { // single k-point - const TK* const dmk_col = dm.dmk[ik_in + ik_begin].data() + block.col0 * ld_hk + block.row0; + const TK* const dmk_col = dm.dmk[ik_in + ik_begin].data() + dmk_index(block.col0, block.row0, ld_hk); transpose_dmk_block(dmk_col, ld_hk, block, dmk_row.data()); for (int iR = 0; iR < R_size; ++iR) { @@ -208,7 +209,7 @@ void add_dmr_soc( // all k-points for (int ik = 0; ik < dm._nk; ++ik) { - const TK* const dmk_col = dm.dmk[ik + ik_begin].data() + block.col0 * ld_hk + block.row0; + const TK* const dmk_col = dm.dmk[ik + ik_begin].data() + dmk_index(block.col0, block.row0, ld_hk); transpose_dmk_block(dmk_col, ld_hk, block, dmk_row.data()); for (int iR = 0; iR < R_size; ++iR) { diff --git a/source/source_estate/module_dm/dmr_full.cpp b/source/source_estate/module_dm/dmr_full.cpp index 33b4a48cc95..ee8403d6507 100644 --- a/source/source_estate/module_dm/dmr_full.cpp +++ b/source/source_estate/module_dm/dmr_full.cpp @@ -53,7 +53,7 @@ void cal_dmr_full( if (ik_in >= 0) { // single k-point - const TK* const dmk_col = dm.dmk[ik_in].data() + block.col0 * ld_hk + block.row0; + const TK* const dmk_col = dm.dmk[ik_in].data() + dmk_index(block.col0, block.row0, ld_hk); transpose_dmk_block(dmk_col, ld_hk, block, dmk_row.data()); for (int iR = 0; iR < R_size; ++iR) { @@ -70,7 +70,7 @@ void cal_dmr_full( // all k-points for (int ik = 0; ik < dm._nk; ++ik) { - const TK* const dmk_col = dm.dmk[ik].data() + block.col0 * ld_hk + block.row0; + const TK* const dmk_col = dm.dmk[ik].data() + dmk_index(block.col0, block.row0, ld_hk); transpose_dmk_block(dmk_col, ld_hk, block, dmk_row.data()); for (int iR = 0; iR < R_size; ++iR) { diff --git a/source/source_estate/module_dm/dmr_gamma.cpp b/source/source_estate/module_dm/dmr_gamma.cpp index a4aa45bd905..f47fe4cad74 100644 --- a/source/source_estate/module_dm/dmr_gamma.cpp +++ b/source/source_estate/module_dm/dmr_gamma.cpp @@ -54,10 +54,11 @@ void DensityMatrix::cal_dmr(const int ik_in) #endif // k index constexpr TK kphase = 1; - // transpose DMK col=>row + // transpose DMK col=>row. col_ap is a global block column, so + // col_ap * ld_hk exceeds INT_MAX for large LCAO bases. const TK* DMK_mat_ptr = this->dmk[0 + ik_begin].data() - + col_ap * this->pv->para_2d().nrloc() + row_ap; + + dmk_index(col_ap, row_ap, ld_hk); // set DMR element TR* target_DMR_ptr = target_mat->get_pointer(); for (int mu = 0; mu < row_size; ++mu) diff --git a/source/source_estate/module_dm/dmr_init.cpp b/source/source_estate/module_dm/dmr_init.cpp index b3885123ae2..5dd3e1742ff 100644 --- a/source/source_estate/module_dm/dmr_init.cpp +++ b/source/source_estate/module_dm/dmr_init.cpp @@ -156,7 +156,12 @@ void DensityMatrix::init_dmr(const hamilt::HContainer& DMR_in) this->dmr.push_back(tmp_DMR1.release()); } } - ModuleBase::Memory::record("DensityMatrix::DMR", this->dmr.size() * this->dmr[0]->get_memory_size()); + if (!this->dmr.empty()) + { + // An empty DMR_in leaves this->dmr empty; touching dmr[0] only for the + // memory record would be an out-of-bounds access. + ModuleBase::Memory::record("DensityMatrix::DMR", this->dmr.size() * this->dmr[0]->get_memory_size()); + } } // T of HContainer can be double or std::complex From 861683c2a8d830773170d114919e352ae903cc3b Mon Sep 17 00:00:00 2001 From: abacus_fixer Date: Sun, 22 Nov 2026 11:52:44 +0800 Subject: [PATCH 06/13] fix(lcao): keep local dense allocations and DMK IO offsets in size_t For large LCAO bases (e.g. NLOCAL=377884, issue #8342) the local 2D block nrloc*ncloc can exceed INT_MAX, so an int product wraps and the ensuing vector resize / new[] receives a wrong (tiny) count -> std::length_error. Hoist nrloc*ncloc into a size_t local before every dense allocation: - rdmft: HK_XC and the four Eij_* matrices; loop indices over these vectors are now size_t. - diago_pexsi: DM/EDM new[] counts. - diag_hs_para: h_local/s_local/wfc_2d vectors. - write_dmk: global N^2 gather buffer (read + write paths) and the per-rank nrloc*ncloc read buffer; the nk*nspin size check uses size_t. --- source/source_hsolver/diag_hs_para.cpp | 11 ++++++++--- source/source_hsolver/diago_pexsi.cpp | 9 +++++++-- source/source_io/module_dm/write_dmk.cpp | 16 ++++++++++++---- source/source_lcao/module_rdmft/rdmft.cpp | 23 +++++++++++++++-------- 4 files changed, 42 insertions(+), 17 deletions(-) diff --git a/source/source_hsolver/diag_hs_para.cpp b/source/source_hsolver/diag_hs_para.cpp index 34540097e2c..152b681340a 100644 --- a/source/source_hsolver/diag_hs_para.cpp +++ b/source/source_hsolver/diag_hs_para.cpp @@ -9,6 +9,7 @@ #include "source_hsolver/module_genelpa/elpa_solver.h" #endif +#include #include namespace hsolver @@ -116,9 +117,13 @@ void diago_hs_para(T* h, } para2d_local.init(lda, lda, max_nb, comm, false); - std::vector h_local(para2d_local.ncloc() * para2d_local.nrloc()); - std::vector s_local(para2d_local.ncloc() * para2d_local.nrloc()); - std::vector wfc_2d(para2d_local.ncloc() * para2d_local.nrloc()); + // The local block can exceed INT_MAX elements (issue #8342); keep the + // count in size_t so the vectors are not undersized by an int overflow. + const std::size_t local_size = static_cast(para2d_local.ncloc()) + * static_cast(para2d_local.nrloc()); + std::vector h_local(local_size); + std::vector s_local(local_size); + std::vector wfc_2d(local_size); // distribute h and s to 2D // Cpxgemr2d is a legacy BLACS boundary that requires non-const descriptors. diff --git a/source/source_hsolver/diago_pexsi.cpp b/source/source_hsolver/diago_pexsi.cpp index 42a25aec3d2..fdac65495b6 100644 --- a/source/source_hsolver/diago_pexsi.cpp +++ b/source/source_hsolver/diago_pexsi.cpp @@ -1,5 +1,6 @@ #include #include +#include #include #ifdef __PEXSI #include "diago_pexsi.h" @@ -37,10 +38,14 @@ DiagoPexsi::DiagoPexsi(const Parallel_Orbitals* ParaV_in, this->DM.resize(this->nspin_dm); this->EDM.resize(this->nspin_dm); + // nrloc*ncloc is about 2.55e9 for NLOCAL=377884 on 56 ranks; keep the + // allocation count in size_t (issue #8342). + const std::size_t local_size = static_cast(ParaV->para_2d().nrloc()) + * static_cast(ParaV->para_2d().ncloc()); for (int i = 0; i < this->nspin_dm; i++) { - this->DM[i] = new T[ParaV->para_2d().nrloc() * ParaV->para_2d().ncloc()]; - this->EDM[i] = new T[ParaV->para_2d().nrloc() * ParaV->para_2d().ncloc()]; + this->DM[i] = new T[local_size]; + this->EDM[i] = new T[local_size]; } } diff --git a/source/source_io/module_dm/write_dmk.cpp b/source/source_io/module_dm/write_dmk.cpp index 4167e231db5..3591aea10e3 100644 --- a/source/source_io/module_dm/write_dmk.cpp +++ b/source/source_io/module_dm/write_dmk.cpp @@ -226,9 +226,14 @@ bool ModuleIO::read_dmk(const int nspin, const int nlocal = pv.nrglb(); const bool gamma_only = std::is_same::value; - std::vector dmk_global(my_rank == 0 ? nlocal * nlocal : 0); + // nlocal*nlocal is the global N^2 matrix and overflows int for large + // LCAO bases (issue #8342). + const std::size_t nlocal2 = static_cast(nlocal) + * static_cast(nlocal); + std::vector dmk_global(my_rank == 0 ? nlocal2 : 0); std::vector> dmk_read( - nspin * nk, std::vector(pv.nrloc() * pv.ncloc(), T(0))); + nspin * nk, + std::vector(static_cast(pv.nrloc()) * static_cast(pv.ncloc()), T(0))); // write_dmk emits an optional "Ionic_Step" frame marker followed by // eleven header lines: nspin, spin index, nkstot_nospin, nkstot, ik, @@ -561,13 +566,16 @@ void ModuleIO::write_dmk(const std::vector>& dmk, assert(nspin > 0); const int nk = dmk.size() / nspin; - if (nk * nspin != dmk.size()) + if (static_cast(nk) * static_cast(nspin) != dmk.size()) { ModuleBase::WARNING_QUIT("ModuleIO::write_dmk", "The size of dmk is not consistent with nspin and nk."); } Parallel_Blkcyclic pv_glb; - std::vector dmk_global(my_rank == 0 ? nlocal * nlocal : 0); + // The gathered matrix is global N^2; keep its size in size_t (issue #8342). + const std::size_t nlocal2 = static_cast(nlocal) + * static_cast(nlocal); + std::vector dmk_global(my_rank == 0 ? nlocal2 : 0); for (int ispin = 0; ispin < nspin; ispin++) { diff --git a/source/source_lcao/module_rdmft/rdmft.cpp b/source/source_lcao/module_rdmft/rdmft.cpp index 10fd579af3a..d2f49999a0a 100644 --- a/source/source_lcao/module_rdmft/rdmft.cpp +++ b/source/source_lcao/module_rdmft/rdmft.cpp @@ -18,6 +18,7 @@ #include #include #include +#include #include #include #include @@ -125,15 +126,21 @@ void RDMFT::init(Parallel_Orbitals& ParaV_in, hsk_dft_XC = new hamilt::HS_Matrix_K(ParaV, true); hsk_exx_XC = new hamilt::HS_Matrix_K(ParaV, true); - HK_XC.resize( ParaV->para_2d().nrloc()*ParaV->para_2d().ncloc() ); + // Local RDMFT matrices can exceed INT_MAX elements (issue #8342), so keep + // the nrloc*ncloc product in size_t. + const std::size_t local_size = static_cast(ParaV->para_2d().nrloc()) + * static_cast(ParaV->para_2d().ncloc()); + HK_XC.resize( local_size ); // HK_RDMFT_pass.resize(nk_total, ParaV->get_row_size(), ParaV->get_col_size()); // HK_XC_pass.resize(nk_total, ParaV->get_row_size(), ParaV->get_col_size()); - Eij_TV.resize( para_Eij.nrloc()*para_Eij.ncloc() ); - Eij_hartree.resize( para_Eij.nrloc()*para_Eij.ncloc() ); - Eij_XC.resize( para_Eij.nrloc()*para_Eij.ncloc() ); - Eij_exx_XC.resize( para_Eij.nrloc()*para_Eij.ncloc() ); + const std::size_t eij_size = static_cast(para_Eij.nrloc()) + * static_cast(para_Eij.ncloc()); + Eij_TV.resize( eij_size ); + Eij_hartree.resize( eij_size ); + Eij_XC.resize( eij_size ); + Eij_exx_XC.resize( eij_size ); // HR_TV = new hamilt::HContainer(*ucell, ParaV); @@ -239,7 +246,7 @@ void RDMFT::cal_Hk_Hpsi() cal_bra_op_ket( ParaV, para_Eij, wfc(ik, 0, 0), H_wfc_exx_XC(ik, 0, 0), Eij_exx_XC ); _diagonal_in_serial( para_Eij, Eij_exx_XC, &(wfcHwfc_exx_XC(ik, 0)) ); - for(int iloc=0; ilocget_hk()[iloc]; + for(std::size_t iloc=0; ilocget_hk()[iloc]; } #endif if( !only_exx_type ) @@ -251,7 +258,7 @@ void RDMFT::cal_Hk_Hpsi() cal_bra_op_ket( ParaV, para_Eij, wfc(ik, 0, 0), H_wfc_dft_XC(ik, 0, 0), Eij_XC ); _diagonal_in_serial( para_Eij, Eij_XC, &(wfcHwfc_dft_XC(ik, 0)) ); - for(int iloc=0; ilocget_hk()[iloc]; + for(std::size_t iloc=0; ilocget_hk()[iloc]; } // // store HK_RDMFT @@ -429,7 +436,7 @@ double RDMFT::run(ModuleBase::matrix& E_gradient_occNum, psi::Psi& E TK* pwfc = &occNum_HamiltWfc(0, 0, 0); TK* pwfc_out = &E_gradient_wfc(0, 0, 0); - for(int i=0; i Date: Sun, 22 Nov 2026 11:53:04 +0800 Subject: [PATCH 07/13] fix(lcao): size_t H(k) size and avoid int truncation in operator copy issue #8342: for a >INT_MAX local block, passing the element count through an int narrows it and produces an undersized allocation. - hs_matrix_k.h: get_size() returns std::size_t (was int) and is const; the hk/sk resize already uses the size_t vector::size(). - operator_lcao.cpp: replace BlasConnector::copy (int length) with std::copy so a >INT_MAX smatrix_k block is copied in full. - setup_psi.cpp: document that gamma-only direct solvers keep the full N x N Psi block here (not N x NBANDS); Psi::resize uses size_t so the issue #8342 dimensions are safe. --- source/source_hamilt/hs_matrix_k.h | 5 ++++- .../source_lcao/module_operator_lcao/operator_lcao.cpp | 9 +++++++-- source/source_psi/setup_psi.cpp | 3 +++ 3 files changed, 14 insertions(+), 3 deletions(-) diff --git a/source/source_hamilt/hs_matrix_k.h b/source/source_hamilt/hs_matrix_k.h index e592de87cad..3a0c36b9520 100644 --- a/source/source_hamilt/hs_matrix_k.h +++ b/source/source_hamilt/hs_matrix_k.h @@ -4,6 +4,7 @@ #include "source_basis/module_ao/parallel_orbitals.h" #include +#include #include namespace hamilt { @@ -13,6 +14,8 @@ namespace hamilt public: HS_Matrix_K(const Parallel_Orbitals* paraV, bool no_s=false){ + // size() is size_t; nrloc*ncloc can exceed INT_MAX for large + // LCAO bases (issue #8342). hk.resize(paraV->para_2d().size()); if(!no_s) { @@ -25,7 +28,7 @@ namespace hamilt TK* get_sk() {return sk.data();} - int get_size() {return hk.size();} + std::size_t get_size() const {return hk.size();} void set_zero_hk() {hk.assign(hk.size(), 0);} diff --git a/source/source_lcao/module_operator_lcao/operator_lcao.cpp b/source/source_lcao/module_operator_lcao/operator_lcao.cpp index 16bc567c2e3..b09531c7300 100644 --- a/source/source_lcao/module_operator_lcao/operator_lcao.cpp +++ b/source/source_lcao/module_operator_lcao/operator_lcao.cpp @@ -14,6 +14,8 @@ #include "source_lcao/module_rt/td_info.h" #include "source_lcao/module_rt/td_folding.h" +#include + namespace hamilt { template @@ -41,8 +43,11 @@ void OperatorLCAO::get_hs_pointers() { this->smatrix_k = new double[this->hsk->get_size()]; this->allocated_smatrix = true; } - const int inc = 1; - BlasConnector::copy(this->hsk->get_size(), this->hsk->get_sk(), inc, this->smatrix_k, inc); + // get_size() is size_t; std::copy avoids narrowing it to the int + // length used by BLAS for a >INT_MAX local block (issue #8342). + std::copy(this->hsk->get_sk(), + this->hsk->get_sk() + this->hsk->get_size(), + this->smatrix_k); #ifdef __ELPA // DecomposedState may be changed after diagnolization, with smatrix_k changed too // for example, when DecomposedState equals 1, smatrix_k is an identity matrix, different from the original this->hsk->get_sk() diff --git a/source/source_psi/setup_psi.cpp b/source/source_psi/setup_psi.cpp index 6188898198b..36d67aa6c77 100644 --- a/source/source_psi/setup_psi.cpp +++ b/source/source_psi/setup_psi.cpp @@ -34,6 +34,9 @@ void Setup_Psi::allocate_psi(psi::Psi*& psi, if (inp.ks_solver == "genelpa" || inp.ks_solver == "elpa" || inp.ks_solver == "lapack" || inp.ks_solver == "pexsi" || inp.ks_solver == "cusolver" || inp.ks_solver == "cusolvermp") { + // Gamma-only direct solvers keep a full N x N block here, not + // N x NBANDS. Psi::resize computes its element count in + // size_t, so this is safe for the issue #8342 dimensions. ncol = para_orb.para_2d().ncloc(); } } From 52dbbd0c1c90aee9ab9aab8b2983510559f8e823 Mon Sep 17 00:00:00 2001 From: abacus_fixer Date: Sun, 22 Nov 2026 11:53:30 +0800 Subject: [PATCH 08/13] fix(lcao): use size_t for parallel orbital counters and offsets pv.nnr (the number of basis-pair elements on this rank) and the per-atom nlocdim/nlocstart offsets can exceed INT_MAX for large LCAO bases (issue #8342). Keeping them in int silently truncates sparse-matrix resizes and OpenMP reduction counters. - parallel_orbitals.h: nnr, nlocdim, nlocstart are now size_t. - spar_dh.cpp: local nnr (gamma uses para_2d().size(), else pv.nnr). - lcao_nl_mu.cpp / lcao_set_st.cpp: nnr / total_nnr counters and the helper signatures taking them, including the OpenMP reductions. - pulay_fs_temp.h: total_irr / local_total_irr / irr counters. --- .../source_basis/module_ao/parallel_orbitals.h | 10 ++++++---- source/source_lcao/lcao_nl_mu.cpp | 8 +++++--- source/source_lcao/lcao_set_st.cpp | 18 ++++++++++-------- source/source_lcao/pulay_fs_temp.h | 9 +++++---- source/source_lcao/spar_dh.cpp | 5 +++-- 5 files changed, 29 insertions(+), 21 deletions(-) diff --git a/source/source_basis/module_ao/parallel_orbitals.h b/source/source_basis/module_ao/parallel_orbitals.h index 95b606d1431..b5ce322e8fe 100644 --- a/source/source_basis/module_ao/parallel_orbitals.h +++ b/source/source_basis/module_ao/parallel_orbitals.h @@ -1,6 +1,7 @@ #ifndef _PARALLEL_ORBITALS_H_ #define _PARALLEL_ORBITALS_H_ #include "source_base/parallel_blkcyc.h" +#include #include #include @@ -51,10 +52,11 @@ class Parallel_Orbitals ///------------------------------------- /// number of elements(basis-pairs) in this processon /// on all adjacent atoms-pairs(2D division) - ///------------------------------------- - int nnr=1; - std::vector nlocdim; - std::vector nlocstart; + /// nnr can exceed INT_MAX for large LCAO bases (issue #8342), so keep it + /// and the per-atom offsets in size_t. + std::size_t nnr=1; + std::vector nlocdim; + std::vector nlocstart; #ifdef __MPI int desc_wfc[9]; //for wfc, nlocal*nbands diff --git a/source/source_lcao/lcao_nl_mu.cpp b/source/source_lcao/lcao_nl_mu.cpp index 995c0dc14de..3674213cfbd 100644 --- a/source/source_lcao/lcao_nl_mu.cpp +++ b/source/source_lcao/lcao_nl_mu.cpp @@ -2,6 +2,8 @@ #include "source_lcao/lcao_domain.h" #include "source_io/module_parameter/parameter.h" +#include + namespace LCAO_domain { @@ -321,7 +323,7 @@ static void build_psi_beta( static int accum_nlm_block( const NL_env& env, const NL_pair& pair, - const int nnr, + const std::size_t nnr, std::vector>>>& nlm_tot, std::vector>>>>& nlm_tot1, double* NLloc, @@ -444,7 +446,7 @@ void build_Nonlocal_mu_new(const Parallel_Orbitals& pv, // calculate sum_(L0,M0) beta // and accumulate the value to Hloc_fixedR(i,j) //======================================================= - int total_nnr = 0; + std::size_t total_nnr = 0; #ifdef _OPENMP #pragma omp parallel reduction(+ : total_nnr) { @@ -475,7 +477,7 @@ void build_Nonlocal_mu_new(const Parallel_Orbitals& pv, GridD->Find_atom(ucell, atom1->tau[I1], T1, I1, &adjs); const int start1 = ucell.itiaiw2iwt(T1, I1, 0); // Record_adj.for_2d() may not called in some case - int nnr = 0; + std::size_t nnr = 0; if (!pv.nlocstart.empty()) { nnr = pv.nlocstart[iat1]; diff --git a/source/source_lcao/lcao_set_st.cpp b/source/source_lcao/lcao_set_st.cpp index 9a85045ab2e..a9230c35284 100644 --- a/source/source_lcao/lcao_set_st.cpp +++ b/source/source_lcao/lcao_set_st.cpp @@ -2,6 +2,8 @@ #include "source_lcao/lcao_domain.h" #include "source_io/module_parameter/parameter.h" +#include + namespace LCAO_domain { @@ -11,7 +13,7 @@ namespace LCAO_domain static void set_deriv_s(ForceStressArrays& fsr, const int nspin, const int is, - const int nnr, + const std::size_t nnr, const double* olm, const ModuleBase::Vector3& dtau, const bool cal_stress) @@ -74,7 +76,7 @@ static void set_deriv_s(ForceStressArrays& fsr, static void set_deriv_t(ForceStressArrays& fsr, const int nspin, const int is, - const int nnr, + const std::size_t nnr, const double* olm, const ModuleBase::Vector3& dtau, const bool cal_stress) @@ -154,8 +156,8 @@ static void set_deriv_t(ForceStressArrays& fsr, void single_deriv(const ST_env& env, const ST_elem& e, ForceStressArrays& fsr, - int& nnr, - int& total_nnr, + std::size_t& nnr, + std::size_t& total_nnr, double* olm // output value ) { @@ -232,8 +234,8 @@ void single_deriv(const ST_env& env, void single_overlap(const ST_env& env, const ST_elem& e, - int& nnr, // output value - int& total_nnr, // output value + std::size_t& nnr, // output value + std::size_t& total_nnr, // output value double* olm, // output value double* HSloc // output value ) @@ -364,7 +366,7 @@ void build_ST_new(ForceStressArrays& fsr, // read-only environment shared by every element of this build const ST_env env{orb, two_center_bundle, pv, ucell, nspin, npol, cal_stress, gamma_only_local}; - int total_nnr = 0; + std::size_t total_nnr = 0; #ifdef _OPENMP #pragma omp parallel reduction(+ : total_nnr) { @@ -392,7 +394,7 @@ void build_ST_new(ForceStressArrays& fsr, AdjacentAtomInfo adjs; GridD->Find_atom(ucell, tau1, t1, i1, &adjs); // Record_adj.for_2d() may not called in some case - int nnr = 0; + std::size_t nnr = 0; if (!pv.nlocstart.empty()) { nnr = pv.nlocstart[iat1]; diff --git a/source/source_lcao/pulay_fs_temp.h b/source/source_lcao/pulay_fs_temp.h index 2cd35142465..12c0ac2fda1 100644 --- a/source/source_lcao/pulay_fs_temp.h +++ b/source/source_lcao/pulay_fs_temp.h @@ -5,6 +5,7 @@ #include "pulay_fs.h" #include "source_base/timer.h" #include "source_io/module_parameter/parameter.h" +#include #ifdef _OPENMP #include #endif @@ -34,16 +35,16 @@ namespace PulayForceStress ModuleBase::timer::start("Force_LCAO", "cal_pulay_fs_center2"); const int nspin_DMR = (PARAM.inp.nspin == 2) ? 2 : 1; - int total_irr = 0; + std::size_t total_irr = 0; #ifdef _OPENMP #pragma omp parallel { int num_threads = omp_get_num_threads(); ModuleBase::matrix local_s(3, 3); - int local_total_irr = 0; + std::size_t local_total_irr = 0; #else ModuleBase::matrix& local_s = s; - int& local_total_irr = total_irr; + std::size_t& local_total_irr = total_irr; #endif #ifdef _OPENMP @@ -63,7 +64,7 @@ namespace PulayForceStress double f_tmp[3] = { 0.0, 0.0, 0.0 }; if (num_threads > 1) { f_iat = f_tmp; } #endif - int irr = pv.nlocstart[iat]; + std::size_t irr = pv.nlocstart[iat]; const int start1 = ucell.itiaiw2iwt(T1, I1, 0); for (int cb = 0; cb < ra->na_each[iat]; ++cb) { diff --git a/source/source_lcao/spar_dh.cpp b/source/source_lcao/spar_dh.cpp index 908e28117cc..12208b9c3d5 100644 --- a/source/source_lcao/spar_dh.cpp +++ b/source/source_lcao/spar_dh.cpp @@ -7,6 +7,7 @@ #include "source_hamilt/module_gint/gint_dvlocal.h" #include +#include #include #include @@ -243,7 +244,7 @@ void sparse_format::cal_dS(const UnitCell& ucell, ModuleBase::TITLE("sparse_format", "cal_dS"); sparse_format::set_R_range(HS_Arrays.all_R_coor, grid); -const int nnr = gamma_only_local ? pv.para_2d().size() : pv.nnr; +const std::size_t nnr = gamma_only_local ? pv.para_2d().size() : pv.nnr; ForceStressArrays fsr_dh; fsr_dh.DHloc_fixedR_x.resize(nnr, 0.0); @@ -284,7 +285,7 @@ void sparse_format::cal_dH(const UnitCell& ucell, sparse_format::set_R_range(HS_Arrays.all_R_coor, grid); - const int nnr = gamma_only_local ? pv.para_2d().size() : pv.nnr; + const std::size_t nnr = gamma_only_local ? pv.para_2d().size() : pv.nnr; ForceStressArrays fsr_dh; From a4d9a48e4b63a95595f14a2e088f4b8385562e5f Mon Sep 17 00:00:00 2001 From: abacus_fixer Date: Sun, 22 Nov 2026 11:54:10 +0800 Subject: [PATCH 09/13] feat(memory): add MemoryBudget with cgroup-aware LCAO dense estimate Add source_base/memory_budget.{h,cpp} and 9 unit tests. This is the budgeting primitive that later PRs will hook into esolver_ks_lcao to fail fast on large LCAO runs (issue #8342) instead of OOM-ing mid-SCF. API: - MemoryStatus { limit/current/reclaimable/available, from_cgroup } from get_memory_status() / get_memory_status(cgroup_root): cgroup v2 (memory.max / memory.current / memory.stat inactive_file), v1 (memory.limit_in_bytes huge->0, usage_in_bytes, total_inactive_file), fallback to /proc/meminfo MemAvailable. - estimate_lcao_dense(nrloc,ncloc,nbands,nks,nspin,gamma_only, gamma_direct,use_elpa,element_size) -> per-matrix and per-rank byte estimates; uses a saturating multiply that returns SIZE_MAX on overflow (matches the 2.55e9-element local block from the issue). - decide_memory(lower, projected, available) -> Ok/Warn/Abort. gamma_direct (genelpa/elpa/lapack/pexsi/cusolver/cusolvermp) keeps Psi as N^2 rather than N*NBANDS, which the estimator accounts for. Two get_memory_status overloads are used instead of a default argument to satisfy the no-default-header-parameter rule. --- source/source_base/CMakeLists.txt | 1 + source/source_base/memory_budget.cpp | 274 ++++++++++++++++++ source/source_base/memory_budget.h | 81 ++++++ source/source_base/unittests/CMakeLists.txt | 6 + .../unittests/test_memory_budget.cpp | 140 +++++++++ 5 files changed, 502 insertions(+) create mode 100644 source/source_base/memory_budget.cpp create mode 100644 source/source_base/memory_budget.h create mode 100644 source/source_base/unittests/test_memory_budget.cpp diff --git a/source/source_base/CMakeLists.txt b/source/source_base/CMakeLists.txt index 8098e18da3f..9981f7e9f44 100644 --- a/source/source_base/CMakeLists.txt +++ b/source/source_base/CMakeLists.txt @@ -33,6 +33,7 @@ add_library( mathzone_add1.cpp matrix.cpp matrix3.cpp + memory_budget.cpp memory_recorder.cpp mymath.cpp opt_cg.cpp diff --git a/source/source_base/memory_budget.cpp b/source/source_base/memory_budget.cpp new file mode 100644 index 00000000000..c662a00739b --- /dev/null +++ b/source/source_base/memory_budget.cpp @@ -0,0 +1,274 @@ +#include "source_base/memory_budget.h" + +#include +#include +#include +#include +#include + +namespace ModuleBase +{ + +namespace +{ + +std::size_t saturating_mul(const std::size_t a, const std::size_t b) +{ + if (a == 0 || b == 0) + { + return 0; + } + if (a > std::numeric_limits::max() / b) + { + return std::numeric_limits::max(); + } + return a * b; +} + +std::size_t saturating_add(const std::size_t a, const std::size_t b) +{ + if (a > std::numeric_limits::max() - b) + { + return std::numeric_limits::max(); + } + return a + b; +} + +// Returns true when the file was readable. "max" means no cgroup limit and +// is returned as value 0. +bool read_size_file(const std::string& path, std::size_t& value) +{ + std::ifstream ifs(path); + if (!ifs) + { + return false; + } + std::string token; + if (!(ifs >> token)) + { + return false; + } + if (token == "max") + { + value = 0; + return true; + } + try + { + const unsigned long long parsed = std::stoull(token); + value = parsed > static_cast(std::numeric_limits::max()) + ? std::numeric_limits::max() + : static_cast(parsed); + return true; + } + catch (...) + { + return false; + } +} + +std::size_t read_inactive_file(const std::string& path) +{ + std::ifstream ifs(path); + if (!ifs) + { + return 0; + } + std::string line; + while (std::getline(ifs, line)) + { + std::istringstream iss(line); + std::string key; + std::size_t value = 0; + if (iss >> key >> value && (key == "inactive_file" || key == "total_inactive_file")) + { + return value; + } + } + return 0; +} + +std::size_t read_mem_available() +{ + std::ifstream ifs("/proc/meminfo"); + if (!ifs) + { + return 0; + } + std::string line; + while (std::getline(ifs, line)) + { + if (line.compare(0, 13, "MemAvailable:") == 0) + { + std::istringstream iss(line.substr(13)); + std::size_t value_kb = 0; + if (iss >> value_kb) + { + return saturating_mul(value_kb, 1024); + } + } + } + return 0; +} + +// Resolve the cgroup directory. The explicit root is used first, then the +// cgroup v2 path from /proc/self/cgroup. Nested v1 paths are intentionally +// left to the caller-provided root. +std::string resolve_cgroup_dir(const std::string& root) +{ + { + std::ifstream v2(root + "/memory.max"); + if (v2) + { + return root; + } + } + { + std::ifstream v1(root + "/memory/memory.limit_in_bytes"); + if (v1) + { + return root; + } + } + + std::ifstream cgroup("/proc/self/cgroup"); + if (!cgroup) + { + return root; + } + std::string line; + while (std::getline(cgroup, line)) + { + if (line.compare(0, 3, "0::") == 0) + { + const std::string path = line.substr(3); + if (!path.empty() && path[0] == '/') + { + const std::string candidate = root + path; + std::ifstream v2(candidate + "/memory.max"); + if (v2) + { + return candidate; + } + } + } + } + return root; +} + +} // namespace + +MemoryStatus get_memory_status() +{ + return get_memory_status("/sys/fs/cgroup"); +} + +MemoryStatus get_memory_status(const std::string& cgroup_root) +{ + MemoryStatus status; + + const std::string dir = resolve_cgroup_dir(cgroup_root); + std::size_t limit = 0; + std::size_t current = 0; + std::size_t reclaimable = 0; + + if (read_size_file(dir + "/memory.max", limit)) + { + read_size_file(dir + "/memory.current", current); + reclaimable = read_inactive_file(dir + "/memory.stat"); + status.from_cgroup = true; + } + else if (read_size_file(dir + "/memory/memory.limit_in_bytes", limit)) + { + read_size_file(dir + "/memory/memory.usage_in_bytes", current); + reclaimable = read_inactive_file(dir + "/memory/memory.stat"); + status.from_cgroup = true; + } + + if (!status.from_cgroup) + { + status.available_bytes = read_mem_available(); + return status; + } + + // cgroup v1 reports a huge value instead of "max" for an unlimited cgroup. + if (limit > (std::size_t(1) << 62)) + { + limit = 0; + } + + status.limit_bytes = limit; + status.current_bytes = current; + status.reclaimable_bytes = reclaimable; + + if (limit == 0) + { + status.available_bytes = read_mem_available(); + } + else + { + const std::size_t free_bytes = limit > current ? limit - current : 0; + status.available_bytes = std::min(limit, saturating_add(free_bytes, reclaimable)); + } + return status; +} + +LcaoDenseEstimate estimate_lcao_dense(const std::size_t nrloc, + const std::size_t ncloc, + const std::size_t nbands, + const std::size_t nks, + const int nspin, + const bool gamma_only, + const bool gamma_direct, + const bool use_elpa, + const std::size_t element_size) +{ + LcaoDenseEstimate estimate; + const std::size_t local_elements = saturating_mul(nrloc, ncloc); + const std::size_t matrix_bytes = saturating_mul(local_elements, element_size); + + estimate.hk_bytes = matrix_bytes; + estimate.sk_bytes = matrix_bytes; + estimate.dmk_bytes = saturating_mul(matrix_bytes, nks); + + std::size_t psi_elements = 0; + if (gamma_only && gamma_direct) + { + // Gamma-only direct solvers keep ncol = ncloc, so Psi is a full + // local N x N block rather than nbands x nrloc. + psi_elements = saturating_mul(local_elements, static_cast(nspin > 0 ? nspin : 1)); + } + else + { + psi_elements = saturating_mul(saturating_mul(nks, nbands), nrloc); + } + estimate.psi_bytes = saturating_mul(psi_elements, element_size); + + if (use_elpa) + { + // ELPA allocates one additional local work matrix of the same shape. + estimate.elpa_work_bytes = matrix_bytes; + } + + estimate.per_rank_total_bytes = saturating_add( + saturating_add(saturating_add(estimate.hk_bytes, estimate.sk_bytes), estimate.dmk_bytes), + saturating_add(estimate.psi_bytes, estimate.elpa_work_bytes)); + return estimate; +} + +MemoryDecision decide_memory(const std::size_t required_lower_bytes, + const std::size_t required_projected_bytes, + const std::size_t available_bytes) +{ + if (required_lower_bytes > available_bytes) + { + return MemoryDecision::Abort; + } + if (required_projected_bytes > available_bytes) + { + return MemoryDecision::Warn; + } + return MemoryDecision::Ok; +} + +} // namespace ModuleBase diff --git a/source/source_base/memory_budget.h b/source/source_base/memory_budget.h new file mode 100644 index 00000000000..38a7ea4c698 --- /dev/null +++ b/source/source_base/memory_budget.h @@ -0,0 +1,81 @@ +#ifndef MEMORY_BUDGET_H +#define MEMORY_BUDGET_H + +#include +#include + +namespace ModuleBase +{ + +/** + * @brief Memory limit and current usage of the current cgroup / host. + * + * The values come from cgroup v2 (memory.max / memory.current / + * memory.stat) or cgroup v1 (memory.limit_in_bytes / memory.usage_in_bytes + * / memory.stat), with /proc/meminfo MemAvailable as a fallback. A zero + * limit means "no cgroup limit"; available_bytes is then the host value. + */ +struct MemoryStatus +{ + std::size_t limit_bytes = 0; + std::size_t current_bytes = 0; + std::size_t reclaimable_bytes = 0; + std::size_t available_bytes = 0; + bool from_cgroup = false; +}; + +/// Read the memory status from the default cgroup root. +MemoryStatus get_memory_status(); + +/// Read the memory status. cgroup_root is injectable for unit tests. +MemoryStatus get_memory_status(const std::string& cgroup_root); + +/** + * @brief Per-rank estimate of the dense LCAO matrices used by the SCF path. + * + * This is a lower-bound model, not an allocator: it covers H(k), S(k), DMK, + * Psi and the ELPA work matrix. Real-space H(R)/S(R)/DMR, gint buffers and + * charge grids are added by the caller when they are known. + */ +struct LcaoDenseEstimate +{ + std::size_t hk_bytes = 0; + std::size_t sk_bytes = 0; + std::size_t dmk_bytes = 0; + std::size_t psi_bytes = 0; + std::size_t elpa_work_bytes = 0; + std::size_t per_rank_total_bytes = 0; +}; + +/** + * @brief Estimate the local dense LCAO matrices in bytes. + * + * nrloc/ncloc are the local block dimensions. For gamma-only direct + * solvers Psi stores a full local N x N block, so gamma_direct must be true; + * otherwise Psi is nks * nbands * nrloc. element_size is sizeof(TK). + */ +LcaoDenseEstimate estimate_lcao_dense(std::size_t nrloc, + std::size_t ncloc, + std::size_t nbands, + std::size_t nks, + int nspin, + bool gamma_only, + bool gamma_direct, + bool use_elpa, + std::size_t element_size); + +enum class MemoryDecision +{ + Ok, + Warn, + Abort +}; + +/// Abort when the lower bound does not fit; warn when the projection does not. +MemoryDecision decide_memory(std::size_t required_lower_bytes, + std::size_t required_projected_bytes, + std::size_t available_bytes); + +} // namespace ModuleBase + +#endif // MEMORY_BUDGET_H diff --git a/source/source_base/unittests/CMakeLists.txt b/source/source_base/unittests/CMakeLists.txt index 4612dd5d799..b979c69c360 100644 --- a/source/source_base/unittests/CMakeLists.txt +++ b/source/source_base/unittests/CMakeLists.txt @@ -23,3 +23,9 @@ AddTest( LIBS parameter base device SOURCES test_complexmatrix.cpp ) + +AddTest( + TARGET MODULE_BASE_memory_budget + LIBS parameter base device + SOURCES test_memory_budget.cpp +) diff --git a/source/source_base/unittests/test_memory_budget.cpp b/source/source_base/unittests/test_memory_budget.cpp new file mode 100644 index 00000000000..4c442990a11 --- /dev/null +++ b/source/source_base/unittests/test_memory_budget.cpp @@ -0,0 +1,140 @@ +#include "source_base/memory_budget.h" + +#include + +#include +#include +#include +#include +#include + +namespace +{ + +void write_file(const std::string& path, const std::string& content) +{ + std::ofstream ofs(path); + ASSERT_TRUE(ofs); + ofs << content; +} + +std::string make_v2_fixture() +{ + const std::string dir = testing::TempDir() + "/abacus_memory_budget_v2"; + mkdir(dir.c_str(), 0700); + write_file(dir + "/memory.max", "1536000000000\n"); + write_file(dir + "/memory.current", "100000000000\n"); + write_file(dir + "/memory.stat", "inactive_file 20000000000\n"); + return dir; +} + +std::string make_v1_fixture() +{ + const std::string dir = testing::TempDir() + "/abacus_memory_budget_v1"; + mkdir(dir.c_str(), 0700); + mkdir((dir + "/memory").c_str(), 0700); + write_file(dir + "/memory/memory.limit_in_bytes", "1536000000000\n"); + write_file(dir + "/memory/memory.usage_in_bytes", "100000000000\n"); + write_file(dir + "/memory/memory.stat", "total_inactive_file 20000000000\n"); + return dir; +} + +} // namespace + +TEST(MemoryBudget, CgroupV2ReadsLimitAndCurrent) +{ + const ModuleBase::MemoryStatus status = ModuleBase::get_memory_status(make_v2_fixture()); + + EXPECT_TRUE(status.from_cgroup); + EXPECT_EQ(status.limit_bytes, 1536000000000ULL); + EXPECT_EQ(status.current_bytes, 100000000000ULL); + EXPECT_EQ(status.reclaimable_bytes, 20000000000ULL); + EXPECT_EQ(status.available_bytes, 1456000000000ULL); +} + +TEST(MemoryBudget, CgroupV1ReadsLimitAndCurrent) +{ + const ModuleBase::MemoryStatus status = ModuleBase::get_memory_status(make_v1_fixture()); + + EXPECT_TRUE(status.from_cgroup); + EXPECT_EQ(status.limit_bytes, 1536000000000ULL); + EXPECT_EQ(status.current_bytes, 100000000000ULL); + EXPECT_EQ(status.reclaimable_bytes, 20000000000ULL); + EXPECT_EQ(status.available_bytes, 1456000000000ULL); +} + +TEST(MemoryBudget, CgroupUnlimitedKeepsCurrentButNoLimit) +{ + const std::string dir = make_v2_fixture(); + write_file(dir + "/memory.max", "max\n"); + + const ModuleBase::MemoryStatus status = ModuleBase::get_memory_status(dir); + EXPECT_TRUE(status.from_cgroup); + EXPECT_EQ(status.limit_bytes, 0ULL); + EXPECT_EQ(status.current_bytes, 100000000000ULL); +} + +TEST(MemoryBudget, EstimatorMatchesIssue8342Dimensions) +{ + // NLOCAL ~ 377884 split over 56 ranks gives a local block of ~2.55e9 + // elements; gamma-only genelpa keeps five such dense matrices. + const std::size_t nrloc = 50500; + const std::size_t ncloc = 50500; + const std::size_t local = nrloc * ncloc; + const ModuleBase::LcaoDenseEstimate estimate + = ModuleBase::estimate_lcao_dense(nrloc, ncloc, 73820, 1, 1, true, true, true, 8); + + EXPECT_EQ(estimate.hk_bytes, local * 8); + EXPECT_EQ(estimate.sk_bytes, local * 8); + EXPECT_EQ(estimate.dmk_bytes, local * 8); + EXPECT_EQ(estimate.psi_bytes, local * 8); + EXPECT_EQ(estimate.elpa_work_bytes, local * 8); + EXPECT_EQ(estimate.per_rank_total_bytes, local * 8 * 5); + EXPECT_GT(estimate.per_rank_total_bytes * 56, 1500000000000ULL); +} + +TEST(MemoryBudget, EstimatorHandlesMultiKAndNonGamma) +{ + const ModuleBase::LcaoDenseEstimate estimate + = ModuleBase::estimate_lcao_dense(1000, 1000, 100, 4, 1, false, false, false, 8); + + EXPECT_EQ(estimate.hk_bytes, 8 * 1000 * 1000); + EXPECT_EQ(estimate.sk_bytes, 8 * 1000 * 1000); + EXPECT_EQ(estimate.dmk_bytes, 4 * 8 * 1000 * 1000); + EXPECT_EQ(estimate.psi_bytes, 4 * 100 * 1000 * 8); + EXPECT_EQ(estimate.elpa_work_bytes, 0ULL); +} + +TEST(MemoryBudget, EstimatorSaturatesOnOverflow) +{ + const ModuleBase::LcaoDenseEstimate estimate + = ModuleBase::estimate_lcao_dense(std::numeric_limits::max(), + std::numeric_limits::max(), + 1, + 1, + 1, + true, + true, + false, + 16); + EXPECT_EQ(estimate.hk_bytes, std::numeric_limits::max()); + EXPECT_EQ(estimate.per_rank_total_bytes, std::numeric_limits::max()); +} + +TEST(MemoryBudget, DecideAbortsWhenLowerBoundDoesNotFit) +{ + EXPECT_EQ(ModuleBase::decide_memory(1600000000000ULL, 1800000000000ULL, 1500000000000ULL), + ModuleBase::MemoryDecision::Abort); +} + +TEST(MemoryBudget, DecideWarnsWhenProjectionDoesNotFit) +{ + EXPECT_EQ(ModuleBase::decide_memory(1000000000000ULL, 1600000000000ULL, 1500000000000ULL), + ModuleBase::MemoryDecision::Warn); +} + +TEST(MemoryBudget, DecideOkWhenProjectionFits) +{ + EXPECT_EQ(ModuleBase::decide_memory(500000000000ULL, 600000000000ULL, 1500000000000ULL), + ModuleBase::MemoryDecision::Ok); +} From 3a291a5f32c86a61498aa1a4f42e6e514aca9a61 Mon Sep 17 00:00:00 2001 From: abacus_fixer Date: Sun, 22 Nov 2026 20:17:46 +0800 Subject: [PATCH 10/13] fix(lcao): keep NL_elem sparse slot in size_t NL_elem::nnr was int while nnr + nnr_inner is std::size_t (nnr comes from pv.nlocstart). Clang rejects the narrowing in the braced initialization of the aggregate (GCC only warns), breaking the build of lcao_nl_mu.cpp. Use std::size_t for the slot and include for the declaration. --- source/source_lcao/lcao_domain.h | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/source/source_lcao/lcao_domain.h b/source/source_lcao/lcao_domain.h index 305e147f447..4994d284223 100644 --- a/source/source_lcao/lcao_domain.h +++ b/source/source_lcao/lcao_domain.h @@ -1,6 +1,8 @@ #ifndef LCAO_DOMAIN_H #define LCAO_DOMAIN_H +#include + #include "source_base/global_function.h" #include "source_base/vector3.h" #include "source_basis/module_nao/two_center_bundle.h" @@ -128,7 +130,7 @@ struct NL_elem const int iw1_all; const int iw2_all; const int t0; - const int nnr; + const std::size_t nnr; }; /** From 8225a0944909b20e068b1458a9f5fbb418d4ee24 Mon Sep 17 00:00:00 2001 From: abacus_fixer Date: Sun, 22 Nov 2026 20:39:35 +0800 Subject: [PATCH 11/13] fix(lcao): finish size_t widening on dense-offset paths The int -> size_t migration left several places narrowing back to int, so local blocks above INT_MAX could still truncate offsets or buffer counts (issue #8342). - lcao_domain.h: single_overlap / single_deriv now declare std::size_t& counters, matching the definitions in lcao_set_st.cpp. The header previously described a different overload. - pulay_fs_center2.cpp: the stress callbacks take std::size_t irr, so irr * 3 is not computed in int, and the gamma-only mu * ncloc + nu index is computed in size_t. - diago_pxxxgvx.cpp: h_tmp / s_tmp element counts and the memcpy byte counts are computed in size_t instead of int ncol * nrow. - matrix.cpp: combine the chunked nrm2 results with std::hypot so 1e200 does not overflow and 1e-200 does not underflow; the non-BLAS branch uses a scaled sum of squares. - test_matrix.cpp: regression tests for both magnitudes and a mixed vector. --- source/source_base/matrix.cpp | 37 ++++++++++++++++---- source/source_base/unittests/test_matrix.cpp | 27 ++++++++++++++ source/source_hsolver/diago_pxxxgvx.cpp | 14 +++++--- source/source_lcao/lcao_domain.h | 8 ++--- source/source_lcao/pulay_fs_center2.cpp | 8 +++-- 5 files changed, 76 insertions(+), 18 deletions(-) diff --git a/source/source_base/matrix.cpp b/source/source_base/matrix.cpp index ed756973184..1f769216496 100644 --- a/source/source_base/matrix.cpp +++ b/source/source_base/matrix.cpp @@ -449,15 +449,38 @@ double matrix::norm() const // mohan add 2021-04-25, no tests. const std::size_t size = matrix_size(nr, nc); #ifdef __NORMAL - double nn = 0.0; + // Scale the sum of squares so extreme magnitudes neither overflow + // (1e200 * 1e200) nor underflow (1e-200 * 1e-200) to a wrong result. + double scale = 0.0; + double ssq = 1.0; for(std::size_t i=0; i(1) << 30; for (std::size_t offset = 0; offset < size; offset += chunk_limit) @@ -466,9 +489,9 @@ double matrix::norm() const const std::size_t chunk_size = remaining > chunk_limit ? chunk_limit : remaining; const int chunk = static_cast(chunk_size); const double partial = BlasConnector::nrm2(chunk, c + offset, 1); - nn += partial * partial; + nn = std::hypot(nn, partial); } - return sqrt(nn); + return nn; #endif } diff --git a/source/source_base/unittests/test_matrix.cpp b/source/source_base/unittests/test_matrix.cpp index 45b48d0c82b..beac3ff5ef0 100644 --- a/source/source_base/unittests/test_matrix.cpp +++ b/source/source_base/unittests/test_matrix.cpp @@ -68,3 +68,30 @@ TEST(Matrix, EmptyMatrixHasNoStorage) EXPECT_EQ(m.nc, 4); EXPECT_EQ(m.c, nullptr); } + +// Squaring 1e200 overflows and squaring 1e-200 underflows to zero, so the +// norm must be accumulated without forming the squares directly. +TEST(MatrixNorm, LargeMagnitudeDoesNotOverflow) +{ + ModuleBase::matrix m(1, 1, true); + m(0, 0) = 1.0e200; + + EXPECT_DOUBLE_EQ(m.norm(), 1.0e200); +} + +TEST(MatrixNorm, SmallMagnitudeDoesNotUnderflow) +{ + ModuleBase::matrix m(1, 1, true); + m(0, 0) = 1.0e-200; + + EXPECT_DOUBLE_EQ(m.norm(), 1.0e-200); +} + +TEST(MatrixNorm, MixedMagnitudesKeepTheLargerOne) +{ + ModuleBase::matrix m(1, 2, true); + m(0, 0) = 1.0e200; + m(0, 1) = 1.0e-200; + + EXPECT_DOUBLE_EQ(m.norm(), 1.0e200); +} diff --git a/source/source_hsolver/diago_pxxxgvx.cpp b/source/source_hsolver/diago_pxxxgvx.cpp index e9ee523be0a..00bb416a5b2 100644 --- a/source/source_hsolver/diago_pxxxgvx.cpp +++ b/source/source_hsolver/diago_pxxxgvx.cpp @@ -4,6 +4,7 @@ #include "source_base/module_external/scalapack_connector.h" #include +#include #include #include #include @@ -483,10 +484,15 @@ void pxxxgvx_diag(const int* const desc, int degeneracy_max = 12; // only used for complex and std::complex while (true) { - std::vector h_tmp(ncol * nrow, 0); - std::vector s_tmp(ncol * nrow, 0); - memcpy(h_tmp.data(), h_mat, sizeof(T) * ncol * nrow); - memcpy(s_tmp.data(), s_mat, sizeof(T) * ncol * nrow); + // The local block can exceed INT_MAX elements (issue #8342); keep the + // element count and the byte count in size_t before allocating/copying. + const std::size_t local_size = static_cast(ncol) + * static_cast(nrow); + const std::size_t local_bytes = sizeof(T) * local_size; + std::vector h_tmp(local_size, 0); + std::vector s_tmp(local_size, 0); + memcpy(h_tmp.data(), h_mat, local_bytes); + memcpy(s_tmp.data(), s_mat, local_bytes); int ndim_global = desc[2]; const char jobz = 'V'; diff --git a/source/source_lcao/lcao_domain.h b/source/source_lcao/lcao_domain.h index 4994d284223..5f75755ecb9 100644 --- a/source/source_lcao/lcao_domain.h +++ b/source/source_lcao/lcao_domain.h @@ -138,8 +138,8 @@ struct NL_elem */ void single_overlap(const ST_env& env, const ST_elem& e, - int& nnr, // output value - int& total_nnr, // output value + std::size_t& nnr, // output value + std::size_t& total_nnr, // output value double* olm, // output value double* HSloc); // output value @@ -149,8 +149,8 @@ void single_overlap(const ST_env& env, void single_deriv(const ST_env& env, const ST_elem& e, ForceStressArrays& fsr, - int& nnr, // output value - int& total_nnr, // output value + std::size_t& nnr, // output value + std::size_t& total_nnr, // output value double* olm); // output value /** diff --git a/source/source_lcao/pulay_fs_center2.cpp b/source/source_lcao/pulay_fs_center2.cpp index fd3c0b02d92..706177d1b30 100644 --- a/source/source_lcao/pulay_fs_center2.cpp +++ b/source/source_lcao/pulay_fs_center2.cpp @@ -31,7 +31,9 @@ void PulayForceStress::cal_pulay_fs( if (mu >= 0 && nu >= 0) { - const int index = mu * pv.para_2d().ncloc() + nu; + const std::size_t index = static_cast(mu) + * static_cast(pv.para_2d().ncloc()) + + static_cast(nu); double sum = 0.0; for (int is = 0; is < nspin; ++is) { @@ -90,7 +92,7 @@ void PulayForceStress::cal_pulay_fs( const double** dHSx, const double** dHSxy, const double* dtau, - const int& irr) + const std::size_t& irr) { int ij = 0; for (int i = 0; i < 3; ++i) @@ -127,7 +129,7 @@ void PulayForceStress::cal_pulay_fs( const double** dHSx, const double** dHSxy, const double* dtau, - const int& irr) + const std::size_t& irr) { for (int i = 0; i < 3; ++i) { From c4a2681d0b14f2c0f8f97166232f0dd5ef1ff7c0 Mon Sep 17 00:00:00 2001 From: abacus_fixer Date: Sun, 22 Nov 2026 21:05:10 +0800 Subject: [PATCH 12/13] style(source_base): trim trailing whitespace and flatten saturating adds - matrix.cpp: drop trailing spaces on the six lines reported by the review bot (167/182/232/255/270/288). - memory_budget.cpp: assign the partial byte totals to named locals before summing them, per AGENTS rule 14. --- source/source_base/matrix.cpp | 12 ++++++------ source/source_base/memory_budget.cpp | 7 ++++--- 2 files changed, 10 insertions(+), 9 deletions(-) diff --git a/source/source_base/matrix.cpp b/source/source_base/matrix.cpp index 1f769216496..96c61384efd 100644 --- a/source/source_base/matrix.cpp +++ b/source/source_base/matrix.cpp @@ -164,7 +164,7 @@ matrix operator+(const matrix &m1, const matrix &m2) matrix tm(m1); const std::size_t size = matrix_size(m1.nr, m1.nc); - for (std::size_t i = 0; i < size; i++) + for (std::size_t i = 0; i < size; i++) { tm.c[i] += m2.c[i]; } @@ -179,7 +179,7 @@ matrix operator-(const matrix &m1, const matrix &m2) matrix tm(m1); const std::size_t size = matrix_size(m1.nr, m1.nc); - for(std::size_t i = 0; i < size; i++) + for(std::size_t i = 0; i < size; i++) { tm.c[i] -= m2.c[i]; } @@ -229,7 +229,7 @@ matrix operator*(const double &s, const matrix &m) { matrix sm(m); const std::size_t size = matrix_size(m.nr, m.nc); - for (std::size_t i = 0; i < size; i++) + for (std::size_t i = 0; i < size; i++) { sm.c[i] *= s; } @@ -252,7 +252,7 @@ matrix operator*(const matrix &m,const double &s) void matrix::operator*=(const double &s) { const std::size_t size = matrix_size(nr, nc); - for (std::size_t i = 0; i < size; i++) + for (std::size_t i = 0; i < size; i++) c[i] *= s; } @@ -267,7 +267,7 @@ void matrix::operator+=(const matrix & m) assert( nc==m.nc ); const std::size_t size = matrix_size(nr, nc); const double * const c_in = m.c; - for( std::size_t i = 0; i < size; ++i ) + for( std::size_t i = 0; i < size; ++i ) { c[i] += c_in[i]; } @@ -285,7 +285,7 @@ void matrix::operator-=(const matrix & m) assert( nc==m.nc ); const std::size_t size = matrix_size(nr, nc); const double * const c_in = m.c; - for( std::size_t i = 0; i < size; ++i ) + for( std::size_t i = 0; i < size; ++i ) { c[i] -= c_in[i]; } diff --git a/source/source_base/memory_budget.cpp b/source/source_base/memory_budget.cpp index c662a00739b..c570d927bf7 100644 --- a/source/source_base/memory_budget.cpp +++ b/source/source_base/memory_budget.cpp @@ -250,9 +250,10 @@ LcaoDenseEstimate estimate_lcao_dense(const std::size_t nrloc, estimate.elpa_work_bytes = matrix_bytes; } - estimate.per_rank_total_bytes = saturating_add( - saturating_add(saturating_add(estimate.hk_bytes, estimate.sk_bytes), estimate.dmk_bytes), - saturating_add(estimate.psi_bytes, estimate.elpa_work_bytes)); + const std::size_t hs_bytes = saturating_add(estimate.hk_bytes, estimate.sk_bytes); + const std::size_t hsdmk_bytes = saturating_add(hs_bytes, estimate.dmk_bytes); + const std::size_t psi_elpa_bytes = saturating_add(estimate.psi_bytes, estimate.elpa_work_bytes); + estimate.per_rank_total_bytes = saturating_add(hsdmk_bytes, psi_elpa_bytes); return estimate; } From d192e3aea3261bb6bdca862d1d602c8a190f116a Mon Sep 17 00:00:00 2001 From: abacus_fixer Date: Wed, 25 Nov 2026 21:49:25 +0800 Subject: [PATCH 13/13] feat(lcao): fail fast on insufficient dense-matrix memory (#8342) Large LCAO runs can exhaust memory mid-SCF when the dense matrices (H/S/DMK/Psi and the ELPA workspace) do not fit, crashing with a raw std::bad_alloc instead of a clean exit. Estimate the lower-bound memory footprint before the first big allocation and abort with a diagnostic block when it does not fit; always print the estimate at startup. - memory_budget: add pure helpers (gamma_direct/elpa solver detection, per-rank memory budget, byte formatting) with 4 unit-test cases. - lcao_memory_check (new): estimate -> decide -> print module. The function body reads no process-global state; all cross-layer values are injected by the caller, keeping it unit-testable. - lcao_set: invoke the check at the top of set_psi_occ_dm_chg (once, in before_all_runners), right before Setup_Psi::allocate_psi. esolver_ks_lcao.cpp is left unchanged (C2 plan). - main: catch std::bad_alloc / std::length_error around driver init and exit non-zero with a clear message. - Makefile.Objects: wire the new sources into the legacy build; CMakeLists and pyabacus source lists verified (no pyabacus change needed). Verification: the abacus target and test_memory_budget were compiled by the user after two fixes (GlobalV::NBANDS does not exist -> use inp.nbands; remove global reads from the check body via parameter injection). Governance check run with --staged; findings below. Governance exception (Global dependency budget, net_delta=2): set_psi_occ_dm_chg is a pre-existing function that already depends heavily on GlobalV/PARAM (capped global_dependency score, unchanged by this PR). To keep esolver_ks_lcao.cpp untouched and the new check body free of global reads, the caller reads two values and passes them explicitly: - PARAM.globalv.gamma_only_local: must match Setup_Psi::allocate_psi (source_psi/setup_psi.cpp:30), which sizes the very allocation we estimate; inp.gamma_only is not the runtime authority for LCAO. - GlobalV::MY_RANK: no parameter carries it without changing the function signature, which is disallowed by the C2 plan. A third read (GlobalV::ofs_running) was extracted into a local alias reused by an existing call site, so it is net-zero (removed=1, added=1). No new cross-layer control is introduced beyond the two reads at a single, already-global-dependent call site. Scope: source/source_lcao/lcao_set.cpp:32,33. Risk: low. Follow-up: if set_psi_occ_dm_chg is later refactored to accept these as parameters, the reads move to its caller and this exception can be dropped. Header-include WARNINGs on lcao_memory_check.h are required by the new header (cstddef, ostream, parallel_orbitals, klist, input_parameter); no-docs-needed WARNING: this adds a runtime diagnostic print and does not change INPUT parameters or public interfaces. --- source/Makefile.Objects | 2 + source/source_base/memory_budget.cpp | 36 ++++ source/source_base/memory_budget.h | 20 +++ .../unittests/test_memory_budget.cpp | 52 ++++++ source/source_lcao/CMakeLists.txt | 1 + source/source_lcao/lcao_memory_check.cpp | 156 ++++++++++++++++++ source/source_lcao/lcao_memory_check.h | 59 +++++++ source/source_lcao/lcao_set.cpp | 16 +- source/source_main/main.cpp | 36 +++- 9 files changed, 376 insertions(+), 2 deletions(-) create mode 100644 source/source_lcao/lcao_memory_check.cpp create mode 100644 source/source_lcao/lcao_memory_check.h diff --git a/source/Makefile.Objects b/source/Makefile.Objects index 502f29b9e05..fb728d610e4 100644 --- a/source/Makefile.Objects +++ b/source/Makefile.Objects @@ -180,6 +180,7 @@ OBJS_BASE=assoc_laguerre.o\ mathzone_add1.o\ matrix.o\ matrix3.o\ + memory_budget.o\ memory_recorder.o\ mymath.o\ para_gemm.o\ @@ -911,6 +912,7 @@ OBJS_LCAO=evolve_elec.o\ lcao_allocate.o\ lcao_set_mat2d.o\ lcao_init_basis.o\ + lcao_memory_check.o\ setup_exx.o\ setup_deepks.o\ allocate_dm.o\ diff --git a/source/source_base/memory_budget.cpp b/source/source_base/memory_budget.cpp index c570d927bf7..39552ee64c8 100644 --- a/source/source_base/memory_budget.cpp +++ b/source/source_base/memory_budget.cpp @@ -2,6 +2,7 @@ #include #include +#include #include #include #include @@ -272,4 +273,39 @@ MemoryDecision decide_memory(const std::size_t required_lower_bytes, return MemoryDecision::Ok; } +bool is_gamma_direct_ks_solver(const std::string& ks_solver) +{ + return ks_solver == "genelpa" || ks_solver == "elpa" || ks_solver == "lapack" + || ks_solver == "pexsi" || ks_solver == "cusolver" || ks_solver == "cusolvermp"; +} + +bool is_elpa_ks_solver(const std::string& ks_solver) +{ + return ks_solver == "genelpa" || ks_solver == "elpa"; +} + +std::size_t per_rank_memory_budget(const std::size_t available_node_bytes, const std::size_t ranks_per_node) +{ + if (ranks_per_node == 0) + { + return available_node_bytes; + } + return available_node_bytes / ranks_per_node; +} + +std::string format_memory_bytes(const std::size_t bytes) +{ + static const char* units[] = {"B", "KB", "MB", "GB", "TB", "PB"}; + double value = static_cast(bytes); + int unit = 0; + while (value >= 1024.0 && unit < 5) + { + value /= 1024.0; + ++unit; + } + std::ostringstream oss; + oss << std::fixed << std::setprecision(2) << value << " " << units[unit]; + return oss.str(); +} + } // namespace ModuleBase diff --git a/source/source_base/memory_budget.h b/source/source_base/memory_budget.h index 38a7ea4c698..9680aa0fd94 100644 --- a/source/source_base/memory_budget.h +++ b/source/source_base/memory_budget.h @@ -76,6 +76,26 @@ MemoryDecision decide_memory(std::size_t required_lower_bytes, std::size_t required_projected_bytes, std::size_t available_bytes); +/// Return true when ks_solver is a gamma-only direct solver that keeps Psi as +/// a full local N x N block (genelpa/elpa/lapack/pexsi/cusolver/cusolvermp). +/// This only checks solver membership; the caller must also require gamma_only, +/// matching the predicate in source_psi/setup_psi.cpp. +bool is_gamma_direct_ks_solver(const std::string& ks_solver); + +/// Return true when ks_solver uses ELPA, which allocates an additional local +/// work matrix of the same shape (genelpa/elpa). +bool is_elpa_ks_solver(const std::string& ks_solver); + +/// Per-rank memory budget derived from a node-level available value. +/// ranks_per_node == 0 (serial build before init) returns the node value +/// unchanged; otherwise returns available / ranks_per_node. Division cannot +/// overflow, so this is safe for any input. +std::size_t per_rank_memory_budget(std::size_t available_node_bytes, std::size_t ranks_per_node); + +/// Format a byte count as a human-readable string (B/KB/MB/GB/TB/PB) with +/// two decimal places. +std::string format_memory_bytes(std::size_t bytes); + } // namespace ModuleBase #endif // MEMORY_BUDGET_H diff --git a/source/source_base/unittests/test_memory_budget.cpp b/source/source_base/unittests/test_memory_budget.cpp index 4c442990a11..1a8aad4802f 100644 --- a/source/source_base/unittests/test_memory_budget.cpp +++ b/source/source_base/unittests/test_memory_budget.cpp @@ -138,3 +138,55 @@ TEST(MemoryBudget, DecideOkWhenProjectionFits) EXPECT_EQ(ModuleBase::decide_memory(500000000000ULL, 600000000000ULL, 1500000000000ULL), ModuleBase::MemoryDecision::Ok); } + +TEST(MemoryBudget, GammaDirectSolverSetMatchesSetupPsi) +{ + // Must match the predicate in source_psi/setup_psi.cpp exactly: these + // solvers keep Psi as a full local N x N block under gamma_only. + EXPECT_TRUE(ModuleBase::is_gamma_direct_ks_solver("genelpa")); + EXPECT_TRUE(ModuleBase::is_gamma_direct_ks_solver("elpa")); + EXPECT_TRUE(ModuleBase::is_gamma_direct_ks_solver("lapack")); + EXPECT_TRUE(ModuleBase::is_gamma_direct_ks_solver("pexsi")); + EXPECT_TRUE(ModuleBase::is_gamma_direct_ks_solver("cusolver")); + EXPECT_TRUE(ModuleBase::is_gamma_direct_ks_solver("cusolvermp")); + // scalapack_gvx / dav / cg keep Psi as N x NBANDS, so they are not + // gamma-direct even though scalapack_gvx is column-major. + EXPECT_FALSE(ModuleBase::is_gamma_direct_ks_solver("scalapack_gvx")); + EXPECT_FALSE(ModuleBase::is_gamma_direct_ks_solver("dav")); + EXPECT_FALSE(ModuleBase::is_gamma_direct_ks_solver("cg")); + EXPECT_FALSE(ModuleBase::is_gamma_direct_ks_solver("")); +} + +TEST(MemoryBudget, ElpaSolverSet) +{ + EXPECT_TRUE(ModuleBase::is_elpa_ks_solver("genelpa")); + EXPECT_TRUE(ModuleBase::is_elpa_ks_solver("elpa")); + EXPECT_FALSE(ModuleBase::is_elpa_ks_solver("lapack")); + EXPECT_FALSE(ModuleBase::is_elpa_ks_solver("cusolvermp")); + EXPECT_FALSE(ModuleBase::is_elpa_ks_solver("")); +} + +TEST(MemoryBudget, PerRankBudgetDividesByRanksPerNode) +{ + EXPECT_EQ(ModuleBase::per_rank_memory_budget(1500000000000ULL, 56), 1500000000000ULL / 56); + // ranks_per_node == 0 (serial build / before init) returns the node value. + EXPECT_EQ(ModuleBase::per_rank_memory_budget(1500000000000ULL, 0), 1500000000000ULL); + // zero available stays zero without dividing by zero. + EXPECT_EQ(ModuleBase::per_rank_memory_budget(0ULL, 56), 0ULL); + // division cannot overflow, even at SIZE_MAX. + EXPECT_EQ(ModuleBase::per_rank_memory_budget(std::numeric_limits::max(), 1), + std::numeric_limits::max()); + EXPECT_EQ(ModuleBase::per_rank_memory_budget(std::numeric_limits::max(), 0), + std::numeric_limits::max()); +} + +TEST(MemoryBudget, FormatMemoryBytesScalesUnits) +{ + EXPECT_EQ(ModuleBase::format_memory_bytes(0), "0.00 B"); + EXPECT_EQ(ModuleBase::format_memory_bytes(1023), "1023.00 B"); + EXPECT_EQ(ModuleBase::format_memory_bytes(1024), "1.00 KB"); + EXPECT_EQ(ModuleBase::format_memory_bytes(1536), "1.50 KB"); + EXPECT_EQ(ModuleBase::format_memory_bytes(1024ULL * 1024), "1.00 MB"); + EXPECT_EQ(ModuleBase::format_memory_bytes(1024ULL * 1024 * 1024), "1.00 GB"); + EXPECT_EQ(ModuleBase::format_memory_bytes(1024ULL * 1024 * 1024 * 1024), "1.00 TB"); +} diff --git a/source/source_lcao/CMakeLists.txt b/source/source_lcao/CMakeLists.txt index b36746041db..3dcd2a2a19b 100644 --- a/source/source_lcao/CMakeLists.txt +++ b/source/source_lcao/CMakeLists.txt @@ -55,6 +55,7 @@ if(ENABLE_LCAO) lcao_allocate.cpp lcao_set_mat2d.cpp lcao_init_basis.cpp + lcao_memory_check.cpp setup_nonlocal.cpp setup_exx.cpp setup_deepks.cpp diff --git a/source/source_lcao/lcao_memory_check.cpp b/source/source_lcao/lcao_memory_check.cpp new file mode 100644 index 00000000000..3f383c071cc --- /dev/null +++ b/source/source_lcao/lcao_memory_check.cpp @@ -0,0 +1,156 @@ +#include "source_lcao/lcao_memory_check.h" + +#include +#include +#include +#include + +#include "source_base/memory_budget.h" +#include "source_base/tool_quit.h" + +namespace LCAO_domain +{ + +namespace +{ +const char* decision_to_string(const ModuleBase::MemoryDecision d) +{ + switch (d) + { + case ModuleBase::MemoryDecision::Ok: + return "OK"; + case ModuleBase::MemoryDecision::Warn: + return "WARN"; + case ModuleBase::MemoryDecision::Abort: + return "ABORT"; + } + return "UNKNOWN"; +} +} // namespace + +template +void check_lcao_dense_memory(const Parallel_Orbitals& pv, + const K_Vectors& kv, + const Input_para& inp, + bool gamma_only, + int my_rank, + int ranks_per_node, + std::ostream& log) +{ + // Local block dimensions are valid only after init_basis_lcao has run; + // skip the check when the 2D division is not set up yet. + const int nrloc = pv.para_2d().nrloc(); + const int ncloc = pv.para_2d().ncloc(); + if (nrloc <= 0 || ncloc <= 0) + { + return; + } + + const std::size_t nrloc_s = static_cast(nrloc); + const std::size_t ncloc_s = static_cast(ncloc); + // inp.nbands is the same value Setup_Psi::allocate_psi uses to size Psi + // (source_psi/setup_psi.cpp), so the estimate stays consistent with the + // real allocation. It has already been AUTO-set by cal_nelec_nband before + // before_all_runners runs. + const int nbands = inp.nbands; + const std::size_t nbands_s = static_cast(nbands); + const std::size_t nks_s = static_cast(kv.get_nks()); + const bool gamma_direct = gamma_only && ModuleBase::is_gamma_direct_ks_solver(inp.ks_solver); + const bool use_elpa = ModuleBase::is_elpa_ks_solver(inp.ks_solver); + const std::size_t element_size = sizeof(TK); + + const ModuleBase::LcaoDenseEstimate est = ModuleBase::estimate_lcao_dense( + nrloc_s, ncloc_s, nbands_s, nks_s, inp.nspin, gamma_only, gamma_direct, use_elpa, element_size); + + const ModuleBase::MemoryStatus status = ModuleBase::get_memory_status(); + + // ranks_per_node is injected by the caller (Parallel_Global::mpi_number); + // guard against a non-positive value (serial build reports 0). + const std::size_t ranks_per_node_sz = ranks_per_node > 0 ? static_cast(ranks_per_node) : 1; + const std::size_t budget = ModuleBase::per_rank_memory_budget(status.available_bytes, ranks_per_node_sz); + + // The projection (Warn branch) is a future refinement; pass the lower + // bound as both arguments so decide_memory returns Abort as soon as the + // lower bound does not fit. + const ModuleBase::MemoryDecision decision = ModuleBase::decide_memory( + est.per_rank_total_bytes, est.per_rank_total_bytes, budget); + + const bool is_rank0 = (my_rank == 0); + const bool memory_unknown = (status.available_bytes == 0); + + // Node-level total is informational only (the decision compares per-rank + // vs per-rank budget); guard the multiplication against overflow. + std::size_t node_total_bytes = 0; + if (est.per_rank_total_bytes <= std::numeric_limits::max() / ranks_per_node_sz) + { + node_total_bytes = est.per_rank_total_bytes * ranks_per_node_sz; + } + else + { + node_total_bytes = std::numeric_limits::max(); + } + + if (is_rank0) + { + std::ostringstream oss; + oss << "\n ABACUS: LCAO dense-matrix memory estimate (lower bound)\n"; + oss << " NLOCAL=" << pv.get_wfc_global_nbasis() + << " NBANDS=" << nbands + << " nspin=" << inp.nspin + << " nks=" << kv.get_nks() + << " gamma_only=" << (gamma_only ? "true" : "false") + << " solver=" << inp.ks_solver << "\n"; + oss << " per-rank local block: nrloc=" << nrloc << " x ncloc=" << ncloc << "\n"; + oss << " required (per rank): H " << ModuleBase::format_memory_bytes(est.hk_bytes) + << " + S " << ModuleBase::format_memory_bytes(est.sk_bytes) + << " + DMK " << ModuleBase::format_memory_bytes(est.dmk_bytes) + << " + Psi " << ModuleBase::format_memory_bytes(est.psi_bytes); + if (use_elpa) + { + oss << " + ELPA-work " << ModuleBase::format_memory_bytes(est.elpa_work_bytes); + } + oss << "\n"; + oss << " = " << ModuleBase::format_memory_bytes(est.per_rank_total_bytes) + << " per rank (ranks/node=" << ranks_per_node_sz + << ", node total ~ " << ModuleBase::format_memory_bytes(node_total_bytes) << ")\n"; + if (memory_unknown) + { + oss << " available: unknown (could not read cgroup or /proc/meminfo)\n"; + oss << " decision: print-only (available memory unknown; skip abort)\n"; + } + else + { + oss << " available: " << ModuleBase::format_memory_bytes(budget) + << " per rank (source: " << (status.from_cgroup ? "cgroup" : "/proc/meminfo") << ")\n"; + oss << " decision: " << decision_to_string(decision) << "\n"; + } + // Write to the running log only, not stdout, so the estimate block + // does not clutter the screen (WARNING_QUIT still reports an abort). + log << oss.str() << std::endl; + } + + if (decision == ModuleBase::MemoryDecision::Abort && !memory_unknown) + { + // Every rank must quit; otherwise the non-aborting ranks hang on the + // next MPI call while rank 0 has already exited. + ModuleBase::WARNING_QUIT("check_lcao_dense_memory", + "insufficient memory for LCAO dense matrices; see running log for the memory estimate"); + } +} + +template void check_lcao_dense_memory(const Parallel_Orbitals&, + const K_Vectors&, + const Input_para&, + bool, + int, + int, + std::ostream&); +template void check_lcao_dense_memory>(const Parallel_Orbitals&, + const K_Vectors&, + const Input_para&, + bool, + int, + int, + std::ostream&); + +} // namespace LCAO_domain diff --git a/source/source_lcao/lcao_memory_check.h b/source/source_lcao/lcao_memory_check.h new file mode 100644 index 00000000000..f12f568bfb9 --- /dev/null +++ b/source/source_lcao/lcao_memory_check.h @@ -0,0 +1,59 @@ +#ifndef LCAO_MEMORY_CHECK_H +#define LCAO_MEMORY_CHECK_H + +#include +#include + +#include "source_basis/module_ao/parallel_orbitals.h" +#include "source_cell/klist.h" +#include "source_io/module_parameter/input_parameter.h" + +namespace LCAO_domain +{ + +/** + * @brief Estimate the dense LCAO matrix memory footprint, compare it with the + * per-rank available memory, and print a diagnostic block before any + * large allocation is performed. + * + * Invoked from LCAO_domain::set_psi_occ_dm_chg (once, during + * ESolver_KS_LCAO::before_all_runners), after init_basis_lcao has configured + * the 2D block distribution (so nrloc/ncloc are valid) and before + * Setup_Psi::allocate_psi allocates the first big dense matrix. + * + * This function reads no process-global state; every cross-layer value is + * injected through the parameter list so the body stays free of hidden + * coupling and is unit-testable. + * + * Behavior: + * - rank 0 prints the estimate to @p log (the running log), not stdout; + * - every rank evaluates the decision; on Abort every rank calls + * WARNING_QUIT so no rank is left hanging on a subsequent MPI call; + * - when available memory cannot be determined (0 bytes) the check only + * prints the estimate and never aborts, avoiding false positives on + * non-Linux or cgroup-less environments. + * + * @tparam TK k-space type: double for gamma-only, std::complex + * otherwise. Fixes the element size of the dense matrices. + * @param pv parallel orbitals, providing local block dimensions + * nrloc/ncloc and the global basis count. + * @param kv k-point metadata, providing nks. + * @param inp input parameters (ks_solver, nspin, nbands). + * @param gamma_only effective gamma-only flag (the runtime value, not the + * raw input), matching what Setup_Psi::allocate_psi sees. + * @param my_rank this rank's index in the global communicator. + * @param ranks_per_node number of MPI ranks sharing one node's memory. + * @param log running-log stream to write the estimate to (rank 0). + */ +template +void check_lcao_dense_memory(const Parallel_Orbitals& pv, + const K_Vectors& kv, + const Input_para& inp, + bool gamma_only, + int my_rank, + int ranks_per_node, + std::ostream& log); + +} // namespace LCAO_domain + +#endif diff --git a/source/source_lcao/lcao_set.cpp b/source/source_lcao/lcao_set.cpp index b9df9c54c73..0712d9e5b07 100644 --- a/source/source_lcao/lcao_set.cpp +++ b/source/source_lcao/lcao_set.cpp @@ -1,6 +1,7 @@ #include "source_lcao/lcao_set.h" #include "source_base/global_function.h" #include "source_base/parallel_common.h" +#include "source_base/parallel_global.h" // use Parallel_Global::mpi_number #include "source_io/module_dm/write_dmk.h" #include "source_io/module_parameter/parameter.h" #include "source_psi/setup_psi.h" // use Setup_Psi @@ -8,6 +9,7 @@ #include "source_estate/elecstate_tools.h" // use fixed_weights #include "source_hamilt/module_hcontainer/read_hcontainer.h" #include "source_lcao/rho_tau_lcao.h" // use dm2rho +#include "source_lcao/lcao_memory_check.h" // use check_lcao_dense_memory #include "source_lcao/hamilt_lcao.h" // use HamiltLCAO for init_chg_hr #include "source_hamilt/hamilt_hs_adapter.h" #include "source_hsolver/hsolver_lcao.h" // use HSolverLCAO for init_chg_hr @@ -23,6 +25,18 @@ void LCAO_domain::set_psi_occ_dm_chg( Charge &chr, // charge density const Input_para &inp) // input parameters { + // Estimate the dense LCAO matrix memory and fail fast before the first + // big allocation (Psi). See issue #8342. Cross-layer values are read + // here and passed explicitly so check_lcao_dense_memory itself touches no + // process-global state. + const bool gamma_only = PARAM.globalv.gamma_only_local; + const int my_rank = GlobalV::MY_RANK; + const int ranks_per_node = Parallel_Global::mpi_number; + // ofstream& (not ostream&): ModuleBase::GlobalFunc::DONE takes std::ofstream&, + // and ofstream& still binds to check_lcao_dense_memory's std::ostream& parameter. + std::ofstream& log = GlobalV::ofs_running; + LCAO_domain::check_lcao_dense_memory( + pv, kv, inp, gamma_only, my_rank, ranks_per_node, log); //! 1) init electronic wave function psi Setup_Psi::allocate_psi(psi, kv, pv, inp); @@ -48,7 +62,7 @@ void LCAO_domain::set_psi_occ_dm_chg( //! 4) init DMK, but DMR is constructed in before_scf() LCAO_domain::allocate_dm(dmat, &kv, &pv, inp.nspin); - ModuleBase::GlobalFunc::DONE(GlobalV::ofs_running, "CHARGE"); + ModuleBase::GlobalFunc::DONE(log, "CHARGE"); return; } diff --git a/source/source_main/main.cpp b/source/source_main/main.cpp index c3a51c72c4e..c01e5f90b89 100644 --- a/source/source_main/main.cpp +++ b/source/source_main/main.cpp @@ -17,6 +17,8 @@ #include #include #include +#include +#include namespace { @@ -100,7 +102,39 @@ int main(int argc, char** argv) main program for doing electronic structure calculations. */ Driver DD; - DD.init(cli); + // Catch allocation failures from the large LCAO dense matrices (issue + // #8342) so the run exits with a clear message instead of an uncaught + // exception or an MPI abort. Driver stays in this scope so its destructor + // still runs after finalize_mpi, preserving the original cleanup order. + try + { + DD.init(cli); + } + catch (const std::bad_alloc& e) + { + std::cerr << " ABACUS: out of memory: " << e.what() << std::endl; +#ifdef __MPI + Parallel_Global::finalize_mpi(); +#endif + return 1; + } + catch (const std::length_error& e) + { + std::cerr << " ABACUS: allocation length error (likely a too-large dense" + " matrix): " << e.what() << std::endl; +#ifdef __MPI + Parallel_Global::finalize_mpi(); +#endif + return 1; + } + catch (const std::exception& e) + { + std::cerr << " ABACUS: fatal error: " << e.what() << std::endl; +#ifdef __MPI + Parallel_Global::finalize_mpi(); +#endif + return 1; + } /* After running mpi version of abacus, release the mpi resources.