Repository navigation
Fix #8342 fix(lcao): prevent int overflow in dense allocations and add memory budgeting (#8342) - #8360
Open
mohanchen wants to merge 14 commits into
Open
Fix #8342 fix(lcao): prevent int overflow in dense allocations and add memory budgeting (#8342)#8360mohanchen wants to merge 14 commits into
mohanchen wants to merge 14 commits into
Conversation
added 9 commits
November 22, 2026 09:31
Add ModuleBase::matrix_size and ModuleBase::matrix_index so LCAO matrices with more than INT_MAX elements (issue deepmodeling#8342, NLOCAL=377884) never compute the element count or row-major offset in int.
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.
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 deepmodeling#8342: NLOCAL=377884 gives a local block of about 2.5e9 elements, which no longer fits in int.
The local DMK block is nrloc*ncloc, about 2.55e9 elements for NLOCAL=377884 on 56 ranks (issue deepmodeling#8342). Compute it in size_t for resize, set/get and Memory::record so vector::resize no longer receives a wrapped int count.
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 deepmodeling#8342). Both overflowed int. Also avoid touching dmr[0] when DMR_in is empty.
For large LCAO bases (e.g. NLOCAL=377884, issue deepmodeling#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.
issue deepmodeling#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 deepmodeling#8342 dimensions are safe.
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 deepmodeling#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.
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 deepmodeling#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.
ABACUS-PR-BOT
left a comment
Collaborator
There was a problem hiding this comment.
The static review found three code issues and a mismatch between the claimed fail-fast behavior and the helper-only implementation. Build and runtime tests were not run; the reported test passes were not independently verified.
Non-blocking: git diff --check reports trailing whitespace in matrix.cpp at lines 167, 182, 232, 255, 270 and 288; please trim those line endings.
added 3 commits
November 22, 2026 20:17
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 <cstddef> for the declaration.
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 deepmodeling#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.
- 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.
7 tasks done
mohanchen
force-pushed
the
2026-11-22-a
branch
from
November 25, 2026 12:19
9352198 to
c4a2681
Compare
added 2 commits
November 25, 2026 21:02
# Conflicts: # source/source_hamilt/hs_matrix_k.h
…ng#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.
Collaborator
Author
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.

Linked Issue
Fix #8342 (LCAO large systems OOM /
std::length_errorfromvector::_M_default_append).Root cause
For a large LCAO basis (e.g.
NLOCAL = 377884on 56 ranks) the per-rank 2D blocknrloc * ncloc ≈ 2.55e9exceedsINT_MAX. Because element counts and offsetswere computed in
int, the multiplication wrapped and the resultingvector::resize/new[]received a wrong (tiny) count, raisingstd::length_error— or, worse, silently allocated an undersized buffer. On topof that, gamma-only direct solvers keep Psi as N² (not N×NBANDS), so five
dense matrices per rank (H, S, DMK, Psi, ELPA work) can blow well past the
cgroup memory limit.
Unit Tests and/or Case Tests for my changes
Commands run:
cmake --build build_ninja --target abacus_basic_gpu -j 8— builds successfully.cmake --build build_ninja --target MODULE_BASE_memory_budget -j 8env -u LD_LIBRARY_PATH ./build_ninja/source/source_base/unittests/MODULE_BASE_memory_budgetpython3 tools/03_code_analysis/agent_governance_check.py --staged(per commit batch)Result summary:
MODULE_BASE_memory_budget: 9/9 tests passed (cgroup v1/v2 parsing, unlimited-cgroup handling, estimator matching the LCAO out-of-memory aborts with std::length_error or a silent SIGKILL, without reporting the required memory #8342 dimensions, multi-k / non-gamma estimator, overflow saturation, Ok/Warn/Abort decisions).allowedwarnings (added header includes, test-evidence / docs-sync reminders).Checks not run, with reason:
What's changed?
All changes keep
int → size_tfor element counts / byte offsets along the LCAOdense-matrix path, and add a cgroup-aware memory estimator so large runs can
fail fast before OOM.
Element-count / index safety (
matrix,complexmatrix)int→size_tfor element counts and indexing; add overflow-safehelpers
matrix_size(nrows, ncols)andmatrix_index(ir, ic, ncols).matrixAllocno longer callsstd::exit; throwsstd::bad_allocso thecaller can handle / report it.
Density-matrix path (
density_matrix,dm_getter,dm_setter,dm_from_psi,dmr_init)size_telement counts / indexing(
dmk_element_count,dmk_index).col*ld_hk + rowoffsets; fixib_local*nbasis_localoffset indm_from_psi; guard empty-DMR init indmr_init.Local dense allocations (
rdmft,diago_pexsi,diag_hs_para,write_dmk)nrloc*nclocinto asize_tlocal before every dense allocation(RDMFT
HK_XC/Eij_*, PEXSIDM/EDM, `diag