Skip to content

Fix #8342 fix(lcao): prevent int overflow in dense allocations and add memory budgeting (#8342) - #8360

Open
mohanchen wants to merge 14 commits into
deepmodeling:developfrom
mohanchen:2026-11-22-a
Open

mohanchen wants to merge 14 commits into
deepmodeling:developfrom
mohanchen:2026-11-22-a

Conversation

@mohanchen

@mohanchen mohanchen commented Nov 22, 2026 •

Copy link
Copy Markdown
Collaborator

Linked Issue

Fix #8342 (LCAO large systems OOM / std::length_error from vector::_M_default_append).

Root cause

For a large LCAO basis (e.g. NLOCAL = 377884 on 56 ranks) the per-rank 2D block
nrloc * ncloc ≈ 2.55e9 exceeds INT_MAX. Because element counts and offsets
were computed in int, the multiplication wrapped and the resulting
vector::resize / new[] received a wrong (tiny) count, raising
std::length_error — or, worse, silently allocated an undersized buffer. On top
of 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

What's changed?

All changes keep int → size_t for element counts / byte offsets along the LCAO
dense-matrix path, and add a cgroup-aware memory estimator so large runs can
fail fast before OOM.

  1. Element-count / index safety (matrix, complexmatrix)

    • int → size_t for element counts and indexing; add overflow-safe
      helpers matrix_size(nrows, ncols) and matrix_index(ir, ic, ncols).
    • matrixAlloc no longer calls std::exit; throws std::bad_alloc so the
      caller can handle / report it.
  2. Density-matrix path (density_matrix, dm_getter, dm_setter, dm_from_psi, dmr_init)

    • DMK direct path uses size_t element counts / indexing
      (dmk_element_count, dmk_index).
    • Fix DMR col*ld_hk + row offsets; fix ib_local*nbasis_local offset in
      dm_from_psi; guard empty-DMR init in dmr_init.
  3. Local dense allocations (rdmft, diago_pexsi, diag_hs_para, write_dmk)

    • Hoist nrloc*ncloc into a size_t local before every dense allocation
      (RDMFT HK_XC / Eij_*, PEXSI DM/EDM, `diag

abacus_fixer 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.
@mohanchen mohanchen added Bugs Bugs that only solvable with sufficient knowledge of DFT Refactor Refactor ABACUS codes Memory Memory issues labels Nov 22, 2026

@ABACUS-PR-BOT ABACUS-PR-BOT left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread source/source_lcao/lcao_nl_mu.cpp Resolved
Comment thread source/source_base/matrix.cpp Resolved
Comment thread source/source_lcao/pulay_fs_temp.h Resolved
Comment thread source/source_base/complexmatrix.h Resolved
Comment thread source/source_base/memory_budget.cpp Resolved
Comment thread source/source_lcao/lcao_set_st.cpp Resolved
Comment thread source/source_base/memory_budget.cpp Resolved
Comment thread source/source_base/memory_budget.cpp Resolved
Comment thread source/source_hsolver/diag_hs_para.cpp Resolved
abacus_fixer 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.
abacus_fixer 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.
@mohanchen

Copy link
Copy Markdown
Collaborator Author
image Now the new code output data like the above picture shows

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Bugs Bugs that only solvable with sufficient knowledge of DFT Memory Memory issues Refactor Refactor ABACUS codes Solve before 3.11

Projects

None yet

Development

Successfully merging this pull request may close these issues.

LCAO out-of-memory aborts with std::length_error or a silent SIGKILL, without reporting the required memory

2 participants