Skip to content

feat(hsolver): add CPU and native CUDA PPCG for PW diagonalization - #8264

Open
cheerly-pku wants to merge 243 commits into
deepmodeling:developfrom
cheerly-pku:ppcg-v3-review
Open

cheerly-pku wants to merge 243 commits into
deepmodeling:developfrom
cheerly-pku:ppcg-v3-review

Conversation

@cheerly-pku

@cheerly-pku cheerly-pku commented Nov 2, 2026 •

Copy link
Copy Markdown

Adds projected preconditioned conjugate-gradient (PPCG) diagonalization for CPU and CUDA plane-wave SCF workflows, including norm-conserving and ultrasoft pseudopotentials. NSCF, stochastic-DFT and unsupported GPU backends are rejected during INPUT validation.

Main behavior

  • Uses the shared HSOperator interface for H/S application and the common PW iteration-budget setup.
  • Checks generalized residuals and reports iteration-limit failures. SCF may continue with a warning; non-finite residuals are fatal.
  • Uses pw_diag_ndim for block size and adds ppcg_rr_step (positive integer, default 1) for the scheduled full Rayleigh–Ritz interval.
  • Optional residual tracing appends SCF/k-point/solve identifiers, preserving earlier solves. Only the MPI world root writes.
  • CUDA keeps wavefunctions, residuals, search directions and H/S images on the device. Vector kernels and large BLAS operations run there; small projected eigensystems and MPI reduction scalars use the host. There is no full-wavefunction CPU callback bridge. ROCm is not implemented.
  • Includes analytical/generalized matrix tests, six CUDA unit cases, and CPU/CUDA NCPP/USPP Autotest cases. CUDA CI explicitly runs the GPU unit target and the six added application fixtures.

Accuracy and efficiency

The historical CPU timing study at production commit dd3853659 used Release GNU 13.3 / Xeon Gold 6242 measurements with two bound MPI ranks and one OpenMP/BLAS thread, tracing disabled. All solvers used the same geometry, cutoffs, k meshes, mixing, seed, scf_thr_type=1, scf_thr=1e-10, scf_nmax=200, and pw_diag_nmax=200. The measured runs omit pw_diag_thr, exercising its default 0.01. Each timing is the median of three runs after one warm-up, with solver order rotated.

The energy column compares default-threshold PPCG with CG using initial pw_diag_thr=1e-10 at the same SCF settings.

System Max energy difference (eV) CG wall (s) PPCG wall (s)
GaAs / NCPP 1.073e-10 1.969 5.331
Si / NCPP 9.464e-10 1.519 2.572
Al / NCPP 1.805e-10 1.569 2.171
Fe / USPP 1.219e-09 1.518 1.719
NaCl / USPP 1.473e-08 1.368 1.469
HCl / mixed 7.080e-10 1.218 1.870

Maximum force/stress component differences against that CG comparison were 5.31e-4 eV/Å and 4.79e-2 kbar. Tightening only PPCG's initial threshold to 1e-10 changed energy/force/stress by at most 5.16e-10 eV, 1.68e-5 eV/Å, and 2.29e-2 kbar. Equal thresholds are not interpreted as equal solver accuracy. All 24 default-threshold PPCG runs, including warm-ups, converged without eigensolver warnings.

PPCG is slower than CG on these small cases; no general speedup is claimed. Davidson failed on Fe/NaCl; Davidson-subspace's Fe energy differed by about 0.881 eV. Those results are explicitly excluded from valid comparisons. Full four-solver timings, force/stress tables, independent BPCG checks, and reproducible commands are in the validation report.

Verification

Local checks for the native CUDA implementation (99950ee5a, documented in 11e39d8f3):

  • RTX 3090, CUDA 13.5, GNU 13.3 Release, MPI/OpenMP enabled, LCAO disabled: GPU CTest 6/6 cases passed. Independent checks cover standard/generalized float and double eigenpairs, S-orthogonality, residuals, padding, infrequent RR/locked prefix, device-pointer H/S calls, and iteration-limit status.
  • Compute Sanitizer: 0 errors, 0 leaked bytes across all six GPU cases.
  • CUDA NCPP/USPP Autotest: 36/36 checks passed, all six SCF calculations converged, two ranks/k-point pools, unchanged numerical tolerances and references. A fresh four-case-concurrent (-j 4 -o 1) CUDA run also passed 36/36 checks. Strict Fe/HCl fixtures retain roundoff-level eigensolver warnings (maximum 2.216e-14). An initial aggregate harness timeout was rerun successfully with a longer wall-time allowance; solver thresholds/budgets were unchanged.
  • Nsight Systems generalized-matrix trace: the 2,480-byte wavefunction is uploaded once before solving and downloaded once for final checking. During the solve, all host/device transfers are at most 800 bytes; no full-wavefunction transfers occur. The GPU was shared, so no speedup is claimed.
  • Fresh CPU regression after the workspace refactor: 6/6 MPI CTest entries, 3/3 non-MPI CTest entries, and 36/36 application checks passed. The non-MPI targets were rebuilt and rerun at 11e39d8f3. The earlier four-rank USPP 15/15 result belongs to the pre-CUDA revision, as described in the report.
  • CUDA CLI help/version, valid INPUT, RR=0 rejection, NSCF rejection at checking/startup, and a warning-free RR=4 two-pool GaAs run passed. Its world-root trace preserved eight solves; other pools intentionally do not write it.
  • HTML and LaTeX Sphinx builds passed with --fail-on-warning; git diff --check and governance checks passed with no blockers.

Commands and full numerical results are in the validation report. Build targets were abacus_pw_gpu MODULE_HSOLVER_ppcg_gpu; the CUDA CTest regex was ^MODULE_HSOLVER_ppcg_gpu$, and application checks used Autotest.sh -n 2 -o 1 -j 1. CPU commands and the explicitly historical CPU timing protocol are retained in the same report.

INPUT metadata and user documentation now describe CPU/CUDA availability and the existing NSCF/SDFT exclusions. Added header includes supply the directly used operator, workspace, memory-operation and standard-library types. DeltaSpin retains necessary existing input access while the PR-level global-reference budget decreases. No governance exception is requested.

On functional head 11e39d8f3, all build variants, complete CPU and CUDA workflows, abacuslite, PyTest, governance, and both Read the Docs checks passed. The CUDA run includes the native PPCG unit target and all six application fixtures.

That CUDA CI run used an NVIDIA L20/CUDA 12.9 and reported additional Fe iteration-limit warnings, with maximum residual 4.81339e-9 at the unchanged 200-iteration budget. Its reference-observable checks passed, but the warned eigenpairs remain uncertified. The roundoff-level warning maxima in the local-validation bullets above describe the RTX 3090 runs, not this different CI environment.

Commit 71e6ab31a adds formatting cleanup only; 652361c54 additionally corrects diagnostic reporting across both MPI ranks. CPU/CUDA applications were rebuilt, and focused MPI 6/6, non-MPI 3/3, and GPU 6/6 cases passed again. All 16 new C++/CUDA source/header files pass the configured clang-format check. The 26 formatted source/build files have identical canonical formatter output before and after cleanup; numerical settings, references and iteration budgets are unchanged. The complete CUDA workflow also passed at 652361c54, including all six PPCG application fixtures (36/36 reference checks). Current head 20e5a284c removes an unused <algorithm> include following the latest review; CPU/CUDA applications rebuild, focused CPU CTest passes 6/6 and GPU unit cases pass 6/6. On final head 20e5a284c, all build variants, the complete CPU workflow, abacuslite, PyTest, governance, and both Read the Docs checks have passed. The complete CUDA workflow is still running; its PPCG unit step has passed. A raw formatter audit on final head 20e5a284c made no changes to any newly added PR file.

Formatting status: the pre-commit job is non-blocking (continue-on-error: true). Its raw clang-format, cmake-format and shfmt hooks failed despite the green job result. The output includes 2,475 files outside this PR and a repository-wide JSON-language configuration mismatch. Full-repository formatting is not certified by that job status.

cheerly-pku and others added 30 commits March 28, 2026 13:19
Consider the previous contributions made by classmates, I'm only capable to make small difference without disrupting the entire program ---- like such a small "static".
…w_Small-Changes

2025PKUCourseHW5: Case: 1 - Change rank_seed_offset to static const
…ent)

Add PPCG iterative diagonalization with two strategies:
- CONJUGATE_GRADIENT: band-by-band Polak-Ribiere CG (verified working)
- BLOCK_SUBSPACE: block subspace diagonalization

Includes potrf retry fix: save/restore original matrix before applying
diagonal shift, preventing accumulated shifts from corrupting the matrix.

Test: 1D particle-in-a-box (n_dim=10), CG strategy matches exact
eigenvalues with error 4.3e-12.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
…ormalization

Three fixes for numerical stability:

1. potrf: save/restore original matrix before diagonal shift retries,
   preventing accumulated shifts from corrupting the Cholesky factor.

2. sygvd/syevd: skip workspace query (lwork=-1) and allocate directly.
   The LAPACK replacement ignores workspace queries, causing the second
   call to operate on already-transformed data, corrupting eigenvalues.

3. Block subspace: add chol_qr + hpsi/spi recomputation after
   update_one_block and every rayleigh_ritz, keeping wavefunctions
   S-orthonormal and preventing numerical drift of H|psi> and S|psi>.

Results (1D particle-in-a-box, S=I):
- CG nband=1: error 4.3e-12 (unchanged, already working)
- BLOCK_SUBSPACE nband=1: no longer NaN, converges (to wrong eigenvalue
  due to algorithmic limitation with S=I)
… RR steps

1. solve_small_generalized: save/restore M matrix before retry with shifts
   (prevents accumulation of shifts on sygvd-corrupted M)

2. BLOCK_SUBSPACE: add Krylov fallback for near-collinear p/w vectors
   When p is nearly parallel to w (cos^2 > 0.99), replace p with H·w
   to keep the 3-vector subspace [psi, w, p] full rank.
   This fixes NaN eigenvalues for nband>1 with S=I.

3. LAPACK: use standard workspace query (lwork=-1) pattern for syevd/sygvd
   More robust with real LAPACK implementations.

4. CG: add periodic Rayleigh-Ritz subspace rotation every rr_step iterations
   Corrects band ordering and eigenvalue estimates after band-by-band
   line minimization. Resets PR state after rotation.
The gamma_dot function returns only the real part of inner products,
which is correct for Hermitian forms like <psi|H|psi> but wrong for
projection coefficients where the imaginary part matters.

In orth_gradient and project_against, the projection coefficient
<psi_i | v> must use the full complex inner product to correctly
remove the overlap. Using only Re(<psi_i | v>) leaves an imaginary
component that corrupts the search direction, causing excited-state
bands to converge to wrong eigenvalues.

This fixes the CG strategy bands 1 and 2 converging to the highest
eigenvalue (3.919) instead of the first excited states.
…PACE

The chol_qr_active call after update_one_block re-orthonormalized psi
but left the p vector in the old basis, creating an inconsistency.
The p vector is constructed in update_one_block using the same subspace
rotation as psi, so they start consistent. Adding chol_qr_active before
the p vector is updated breaks this consistency.
This change was unrelated to the PPCG integration and should not
have been included.
H and S are real symmetric operators whose eigenvectors are real.
The previous complex random initialization produced complex
off-diagonal elements in the H-gram matrix (max |Im| ~ 0.5 for
nband=3), causing Re(<psi_i|H|psi_j>) != <psi_i|H|psi_j>.  The
gamma_dot function only returns the real part, so all subspace
Gram matrices (built via gram()) computed wrong off-diagonals,
leading to incorrect eigenvalues from sygvd.

With real-only psi all inner products are real and gamma_dot is
exact, so both BLOCK_SUBSPACE and CONJUGATE_GRADIENT strategies
should now converge to the correct eigenvalues.
…tioning

The 3-block subspace method builds a generalized eigenvalue problem
with basis V = [psi, w, p] where p is constructed from the previous
subspace eigenvectors (p_new += w_l * cw in update_one_block).  This
makes p a linear combination of the w vectors, causing the [w, p]
block of the S-gram matrix M to become nearly rank-deficient.

With nband=3 and sbsize=4 the 9x9 M matrix has condition number
large enough that dsygvd produces negative eigenvalues for the
positive-definite problem (observed: -0.26 at iter=2), and the
eigenvalues diverge exponentially thereafter.

Setting use_p=false reduces the subspace to [psi, w] (2-block),
which is a preconditioned Davidson-like method.  It converges
robustly: the BLOCK_SUBSPACE test now passes in 57 ms with all
3 eigenvalues within 1e-8 of the exact values.

The 3-block code path is preserved for future re-enablement once
a more robust p-vector construction is implemented.
With rr_step=4, the non-RR iterations use Cholesky orthonormalization
which mixes bands through the upper-triangular U^{-1}, causing high-energy
bands to contaminate low-energy ones.  This drives CG eigenvalues to the
spectrum maximum [3.31, 3.68, 3.92] instead of the correct lowest values
[0.081, 0.317, 0.690].

Using rr_step=1 forces Rayleigh-Ritz every iteration, which correctly
diagonalizes the subspace and preserves band ordering.
The orth_cholesky call before rayleigh_ritz mixes bands through the
upper-triangular U^{-1} factor, contaminating low-energy bands with
high-energy components.  This drives CG eigenvalues to the spectrum
maximum instead of the minimum.

rayleigh_ritz solves the generalized eigenvalue problem K v = λ M v
via dsygvd, which correctly handles non-S-orthogonal bases.  The
orth_cholesky is not needed and is actively harmful.

This makes the CG RR path consistent with BLOCK_SUBSPACE, which
calls rayleigh_ritz without prior orth_cholesky.
BLOCK_SUBSPACE starts with rayleigh_ritz (line 1085) which finds correct
eigenvalues and rotates psi before the iteration loop.  CG was using
diagonal Rayleigh quotients instead — these are poor approximations for
random initial guesses, producing wrong gradients that drive the band-by-band
line_minimize toward high-energy eigenstates.

With rr_step=1 (every-iteration RR), the CG loop itself is now correct,
but without an initial RR the first line_minimize step already pushes
psi in the wrong direction, and subsequent RR steps cannot fully recover.
Backup preserved at diago_ppcg_test.cpp.bak
The linear approximation α = -C/B drops the α² term from the Rayleigh
quotient derivative dR/dα = 0.  This picks one of the two stationary
points (minimum or maximum) arbitrarily.  For bands far from convergence
it can select the MAXIMUM, driving ψ toward high-energy states instead
of the desired lowest eigenvalues.

Solve the full quadratic Aα² + Bα + C = 0, evaluate R(α) for both
roots (and the linear guess), and pick the one with the lowest R.

Also restore the CG unit test (rr_step=1, initial rayleigh_ritz).
…e use_p

Three changes to make both PPCG strategies correctly converge with rr_step=4:

1. CG non-RR path: After orth_cholesky, solve the nband x nband subspace
   generalized eigenvalue problem instead of using diagonal Rayleigh quotients.
   The upper-triangular U^{-1} from Cholesky mixes high-energy components into
   low-energy bands, making diagonal RQs overestimate the eigenvalues.  The
   subspace solve gives correct Ritz values without rotating the states,
   preserving Polak-Ribiere conjugate-direction accumulators.

2. BLOCK_SUBSPACE: Re-enable use_p=true (3-block [psi, w, p] subspace).
   The Krylov fallback (replace p with H·w when p ~ w) was already in place
   but dead because use_p was hardcoded to false.  Now it activates on the
   first iteration (p is zero-initialized) and whenever p becomes collinear
   with w after update_one_block.

3. CG test: Change rr_step from 1 back to 4 so the non-RR Cholesky path
   is exercised, validating the true Polak-Ribiere CG mechanism.
The 3-block [psi, w, p] subspace generalized eigenproblem becomes
ill-conditioned when residuals are small (near convergence).  The
[w, p] Gram block shrinks, the M matrix approaches singularity, and
dsygvd produces garbage eigenvectors that drive eigenvalues to
catastrophic values (e.g., -137775 instead of 0.081).

The p-bad H·w Krylov fallback fixes p~w collinearity but does not
address the small-residual ill-conditioning, which is fundamental to
the 3-block construction.  Keep use_p=false for robust convergence.
The [w,p] block of the Gram matrix M shrinks as residuals converge,
making M nearly singular and causing sygvd to produce garbage
eigenvectors.  Scaling w and p to unit S-norm keeps M well-conditioned
(diagonal ~1) without changing the subspace — Ritz values are identical
and Ritz vector coefficients cancel in update_one_block.

This enables the full 3-block [psi,w,p] subspace (use_p=true) by
addressing the fundamental ill-conditioning that the p-bad Krylov
fallback alone could not handle.
The Krylov fallback (replace p with Hw when p~w) was flawed:
when w is approximately an eigenvector (Hw ≈ λw), the replacement
does not fix collinearity.  After S-norm scaling, p ≈ w still,
M_wp ≈ [1,1;1,1] is rank-1, and dsygvd fails.

Instead, simply skip p for this iteration (use_p_now=false).
update_one_block still produces a valid p for the next iteration
from the w Ritz-vector contribution.
Add tests for:
- 2x2 matrix (smallest non-trivial case)
- Degenerate eigenvalues (H = I + J, multiplicity-3 degeneracy)
- Larger 20x20 tridiagonal with 5 bands
- Dense 8x8 matrix via Givens rotations (addresses full-matrix coverage)

All use CONJUGATE_GRADIENT strategy which has sygvd fallback.
BLOCK_SUBSPACE tests deferred due to dsygvd instability with some LAPACK builds.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Covers diagonal, tridiagonal, dense, pentadiagonal, degenerate,
Neumann, S≠I, gamma_g0, single-band, all-band, many-band,
bad preconditioner, tight threshold, scaled, gapped spectrum,
rr_step=1, 1x1, and eigenvector quality checks.

Adds QuickBenchmark (CI-friendly) and DISABLED_FullBenchmark.

@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 requested PPCG/NSCF exclusion is not enforced by current INPUT handling; the support contract and budget regression need reconciliation in the existing thread below. Static incremental source review at a12fb908e810f263c706933a9ac535d80c8dd2f0 against fcd57f6db2660a2d82bd66dfbc93d78e802600c5; no build, runtime test or CI result was independently verified.

@Cstandardlib

Cstandardlib commented Nov 19, 2026 •

Copy link
Copy Markdown
Collaborator

The PR body is way too long. It should describe the main feature implemented, accuracy/efficiency of the method, but not detaild commit/changes based on some old PRs/branch. It should contain clean descriptions independent of those ones.

Comment thread source/source_esolver/esolver_ks_pw.cpp Resolved
Comment thread source/source_hsolver/hsolver_pw.cpp Resolved
Comment thread source/source_hsolver/diago_ppcg.h Resolved
Comment thread source/source_hsolver/diago_ppcg.cpp Resolved
Comment thread source/source_hsolver/diago_ppcg.h Resolved
Comment thread source/source_hsolver/hsolver_pw.cpp Resolved
Comment thread source/source_hsolver/diago_ppcg.cpp Resolved
Comment thread source/source_hsolver/diago_ppcg.cpp Resolved
@Cstandardlib

Cstandardlib commented Nov 19, 2026 •

Copy link
Copy Markdown
Collaborator

Basic tests should be performed on several NCPP cases for standard eigenproblems and USPP cases for generalized eigenproblems now that sPsi is supported by the algorithms.
It is recommended to paste the results in a table or give a precise description of the accuracy and efficiency reached compared to existing methods.

@mohanchen mohanchen added Diago Issues related to diagonalizaiton methods Refactor Refactor ABACUS codes labels Nov 21, 2026
@cheerly-pku cheerly-pku changed the title feat(hsolver): add PPCG support for PW diagonalization feat(hsolver): add CPU PPCG support for PW diagonalization Nov 24, 2026
@cheerly-pku

Copy link
Copy Markdown
Author

@Cstandardlib, regarding your comment:

Thank you for the feedback, and apologies for the delayed response. I have rewritten the PR description as a concise, standalone explanation of the feature, supported calculation modes, measured accuracy/efficiency, and verification. The old PR/branch history and per-commit narrative have been removed. The full numerical tables and reproduction protocol are in a separate validation report.

@cheerly-pku

Copy link
Copy Markdown
Author

@Cstandardlib, regarding your comment:

Thank you for the suggestion. I have added the requested application comparisons on GaAs/Si/Al NCPP cases and Fe/NaCl/HCl USPP-containing cases. The validation report gives energy, force, stress, and four-solver timing tables with exact settings and explicit exclusions for failed or inconsistent comparison runs. PPCG is slower than CG on these small cases; no general speedup is claimed.

Three new USPP Autotest cases use independently computed BPCG references at tighter SCF settings, without relaxing the existing acceptance tolerances. The six NCPP/USPP native cases passed 36/36 checks with two ranks; the new USPP cases also passed 15/15 checks with four ranks. The report retains the roundoff-level eigensolver warnings observed in the deliberately strict cases and distinguishes them from the warning-free default-threshold comparison.

@cheerly-pku cheerly-pku changed the title feat(hsolver): add CPU PPCG support for PW diagonalization feat(hsolver): add CPU and native CUDA PPCG for PW diagonalization Nov 24, 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.

No new correctness defect was identified in the native CUDA/workspace increment at 11e39d8f. One header cleanup is noted inline.

Static review only; no builds or runtime tests were run.

Comment thread source/source_hsolver/ppcg_workspace.h Resolved
@cheerly-pku

Copy link
Copy Markdown
Author

@Cstandardlib, thank you again for the detailed review. The native CUDA implementation and device-resident workspaces are now included. The small generalized-matrix transfer audit found no full-wavefunction transfers during the solve. On 20e5a28, the native PPCG CUDA unit and application test steps have passed, as have all build variants and the complete CPU workflow. The remaining CUDA NAO and other regression steps are still running; I will update this comment when the full workflow finishes. The new files pass the configured formatter, but the non-blocking repository-wide formatting hooks still report existing failures, as documented in the PR description.

The validation report and the PR description record the correctness checks and the strict-USPP residual warnings; no GPU speedup is claimed. I have updated the replies to reflect the current implementation. Would you please take another look when you have time?

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

Diago Issues related to diagonalizaiton methods Refactor Refactor ABACUS codes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants