Skip to content

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

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

cheerly-pku wants to merge 262 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 native CUDA plane-wave SCF, supporting NCPP standard eigenproblems and USPP generalized eigenproblems through the shared H/S operator interface. NSCF, stochastic DFT and unsupported GPU backends are rejected during INPUT validation.

Behavior

  • pw_diag_ndim controls block size; ppcg_rr_step controls the full Rayleigh–Ritz interval (default 1).
  • Convergence uses freshly evaluated generalized residuals. Iteration-limit failures remain visible; non-finite residuals are fatal. Bounded near-convergence refinement retains normalization, energy/order checks and rollback safeguards.
  • CUDA keeps wavefunctions, residuals and search directions on the GPU. Small projected eigensystems and MPI scalars use the host; no full-wavefunction CPU callback bridge is used.
  • Includes analytical matrix tests, eight CUDA unit cases, and eight CPU/eight CUDA application fixtures. Ordinary CUDA CI rejects PPCG residual warnings; the separate original strict Fe case reports them explicitly. No per-test timeout override is added.

Accuracy and efficiency

Fresh CPU comparisons on 2026-11-27 use CG as the accuracy baseline. Within each pair, geometry, cutoffs, k meshes, smearing, mixing and seed are identical; both solvers use scf_thr_type=1, scf_thr=1e-10, initial pw_diag_thr=1e-10, and SCF/diagonalization limits of 200. All twelve runs converged. Differences are finite-SCF comparisons, not exact error bounds or proof of equivalent stopping criteria.

System Energy difference (eV) Max force difference (eV/Å) Max stress difference (kbar)
GaAs (NCPP) 1.319e-10 5.300e-04 4.074e-03
Si (NCPP) 9.456e-10 0.000e+00 5.141e-03
Al (NCPP) 1.894e-10 0.000e+00 4.786e-02
Fe (USPP) 1.218e-09 0.000e+00 2.870e-02
NaCl (USPP) 1.473e-08 1.260e-04 3.397e-02
HCl (mixed NCPP/USPP) 1.920e-10 2.868e-06 4.551e-02

Repeating the three USPP-containing pairs at scf_thr=1e-12 also converged, with maximum energy/force/stress differences of 4.88e-10 eV, 2.87e-6 eV/Å, and 9.33e-3 kbar. BPCG is not used to substantiate accuracy. The existing BPCG-generated strict-USPP reference files are explicitly identified as historical regression snapshots; their values and tolerances remain unchanged.

The controlled historical CPU timing study found PPCG wall times 1.07–2.71 times CG on these small systems. Those timings have not been remeasured after the numerical fixes; no speedup is claimed. Fresh tables, settings, failed-probe exclusions and historical four-solver timings are in the validation report.

Fe acceptance update

Ordinary Fe checks use scf_thr=1e-12 and the existing diago_smooth_ethr=1 option, retaining tight occupied-band thresholds and occupation-dependent thresholds for nearly empty states. The 23-band basis, physical settings, iteration limits, references and observable tolerances are unchanged. The report includes the convergence study, including its nonmonotonic stress result at 1e-14.

At these settings, fresh matched two-rank PPCG/CG comparisons give energy differences of 4.55e-13 eV (CPU) and 1.82e-12 eV (CUDA), zero force differences by symmetry, and maximum stress differences of 4.74e-4 kbar. A per-band refinement eligibility fix removes the ordinary four-rank CPU warning without changing convergence criteria.

The original scf_thr=1e-16, uniform-threshold Fe inputs remain in CPU/CUDA CASES_PPCG_STRESS.txt. CUDA CI runs the strict case separately: crashes and observable mismatches fail the job; residual warnings remain visible in annotations, the job summary and artifacts. This diagnostic policy does not certify those eigenpairs as converged.

20-band Fe fix

The previously failing 20-band Fe input now converges on CPU and CUDA. The fix detects cancellation when combining search directions and refreshes the affected H/S images before their errors can be amplified by normalization. It preserves the original scf_thr=1e-12, uniform residual thresholds, seed, physical settings and 200-iteration limit.

A new standard/generalized matrix regression fails with the old combination update and passes with the fix. The CPU/CUDA 20-band fixtures are now included in the normal mandatory Autotest lists, with no expected-failure handling. Independent CG comparisons give energy differences of 6.82e-12 eV (CPU) and 5.91e-12 eV (CUDA), zero force differences by symmetry, and maximum stress-component differences of 7.85e-4 kbar. New reference files are explicitly CPU PPCG regression snapshots, not CG-derived accuracy benchmarks; the report records their provenance and the distinct aggregate-stress comparison metric.

Verification and remaining limitations

For 926e141c9, CPU/CUDA builds passed. Focused CTest results: 5/5 CPU, 1/1 CUDA PPCG, and 1/1 non-MPI PPCG. The CPU suite now includes 66 PPCG cases. Eight CPU fixtures with four ranks and eight RTX 3090 fixtures with two ranks passed 88/88 observable checks, with no residual warnings, including the 20-band and original strict 23-band Fe cases. Separate strict Fe checks with two/four ranks passed on both backends. Compute Sanitizer passed all eight CUDA unit cases with zero errors and leaks. All sixteen fixture READMEs are two lines.

Exact build targets, CTest patterns, Autotest selections, reference provenance and failed-probe exclusions are in the report. Changed C++ formatting, whitespace and staged governance checks passed. Remote CI on this new commit is pending.

Remaining limits: on the preceding fc89a51a3 head, all 19 checks passed, while the strict L20 Fe diagnostic retained one residual of 1.0519e-14 against 1e-14. Local success on the new head does not certify the L20 result. Tighter CG and Davidson-subspace reference probes failed or did not converge and are excluded from accuracy claims. The older strict Fe diagnostic policy remains explicit; no general performance or universal robustness claim is made.

Governance warnings cover direct header type dependencies and two existing Deltaspin PARAM reads (net global-dependency increase zero); no exception is requested.

cheerly-pku and others added 30 commits June 3, 2026 14:09
…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.
@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

cheerly-pku commented Nov 24, 2026 •

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 final head 20e5a28, all build variants and the complete CPU and CUDA workflows have passed. The final CUDA raw log confirms all six PPCG unit cases and 36/36 application reference checks. The Fe fixture still reports iteration-limit residuals up to 4.81339e-9, so passing observable checks does not certify those warned eigenpairs. 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?

@Cstandardlib

Copy link
Copy Markdown
Collaborator

@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.

Thanks for your validation report! I'd like to add a note of caution: the BPCG algorithm has known reported issues on systems such as Fe, so it is not recommended as a benchmark for accuracy comparisons. For that purpose, CG or dav_subspace can be used instead.

@cheerly-pku

Copy link
Copy Markdown
Author

@Cstandardlib, thank you for pointing this out. I agree that BPCG should not be used to substantiate accuracy on Fe.

I have removed the PPCG–BPCG accuracy table and added fresh CG comparisons for all six NCPP/USPP-containing systems. All twelve matched CG/PPCG runs converged at scf_thr=1e-10. Repeating the three USPP-containing pairs at scf_thr=1e-12 also converged; the maximum energy, force-component and stress-component differences were 4.88e-10 eV, 2.87e-6 eV/Å, and 9.33e-3 kbar. The report gives the common settings and per-system results, and the PR description now uses CG as the accuracy baseline.

The existing BPCG-generated strict-USPP files are explicitly labeled as historical regression snapshots, not accuracy benchmarks. CG probes at the fixtures' scf_thr=1e-16 failed with psi_norm <= 0.0; those runs are excluded, and I have not replaced the reference files with unconverged results. The strict L20 Fe residual failure remains open and is reported separately from the observable comparisons. No fixture tolerance or iteration limit was relaxed.

The report changes are in c5e12ebd5, with exact post-merge verification commands in d821c24fa.

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