Skip to content

SDFT/MDFT: dump plane-wave wavefunctions via out_wfc_pw - #8381

Open
LiYuqiii wants to merge 7 commits into
deepmodeling:developfrom
LiYuqiii:sdft-wfc-dump
Open

LiYuqiii wants to merge 7 commits into
deepmodeling:developfrom
LiYuqiii:sdft-wfc-dump

Conversation

@LiYuqiii

@LiYuqiii LiYuqiii commented Nov 24, 2026 •

Copy link
Copy Markdown
Collaborator

CI follow-up and latest upstream verification (2026-12-04)

Merged develop 274927085 and retained explicit input/output context while passing the new fixed-atoms/lattice arguments to MD initialization. This resolves the new driver merge conflict.

After this merge: CPU/CUDA builds passed; the formerly failing nonlocal-bound CTest passed; PR2 CPU/MPI 8/8, PR3 8/8 plus DOS-quality 4/4, GPU 1/2 MPI 2/2, PR1 output 5/5, and combined small suite 13/13 (17.92 s). OMP_NUM_THREADS=OPENBLAS_NUM_THREADS=1. GCC 12 also compiled the corrected test; GCC 13 is unavailable locally and its result still requires CI. Runtime test binaries were rebuilt after the upstream merge; PR3/combined use checked incremental object builds. Governance, changed CMake formatting, and diff whitespace checks passed.

Workspace commands: cmake --build verification/pr-upload/cmake-upstream --target abacus_pw_para MODULE_PW_STO_NONLOCAL_BOUNDS_UTs -j 8; ctest --test-dir verification/pr-upload/cmake-upstream -R '^MODULE_PW_STO_NONLOCAL_BOUNDS_UTs$' --output-on-failure; ctest --test-dir verification/pr-ci-followup-20261204/ctest-combined --output-on-failure -j 1. Individual suite logs are in verification/pr-ci-followup-20261204/ctest-merged-*.log.

Earlier verification — 2026-12-04

Merged develop f61bbeb89, retained explicit output-context dependency passing, and adapted the MD endpoint argument. Formatted the wavefunction-test CMake registration. No numerical references or tolerances changed.

Fresh local CPU build with ENABLE_FLOAT_FFTW=ON; ctest --test-dir verification/pr-ci-20261204/ctest-pr1 --output-on-failure -j 1: 5/5 passed, including 1/2 MPI text/binary output and actual file-open failure. The combined three-PR CPU/MPI suite also passed 13/13 (17.73 s). This update does not relabel earlier GPU output tests as fresh GPU output verification. Governance: zero blocking errors, global-reference delta −3. CMake formatting and diff whitespace checks passed.

Original description and earlier verification

Linked Issue

This updates the existing SDFT wavefunction-output PR in response to its review;
no separate issue is needed for these focused corrections.

What's changed?

SDFT writes selected KS, raw, filtered and orthogonal stochastic orbitals after
SCF in the first ionic step, using the shared PW text/binary writer. Selection
uses actual stochastic row counts, including zero-row band groups. CPU double
output uses existing host data; GPU staging copies only selected rows. Text
open/write failures are reported. Empty GPU groups no longer call BLAS with a
zero leading dimension. Existing writer signatures are retained as overloads.
out_wfc_pw metadata describes CPU/GPU support and separates KS cadence rules.

Unit Tests and/or Case Tests for my changes

ctest --test-dir verification/pr-review-fixes/ctest-pr8381 --output-on-failure -j1:
five CPU cases passed on the independent PR binary: text/binary at one/two MPI
ranks and a forced text-open failure without deadlock. Combined CUDA testing
passed the four output configurations; the two-rank cases first exposed the
empty-group BLAS defect and passed after its fix. The independent parser checks
record layout, coefficient counts/finiteness and raw-vector unit magnitudes.

Governance Notes

Dependencies are passed through OutputContext and explicit numerical arguments.
The Driver adapts existing application globals once; this does not claim to remove
all historical globals from ABACUS. No new mutable process-global RNG state,
direct MPI calls, or default arguments are introduced. Header additions provide
the actual context, Psi/device, and callable types used by these interfaces; no
circular dependency is introduced. ESolver schedules owning-module operations.
No governance exception is requested.

No documentation update required beyond the updated Input_Item metadata and
checked-in test-suite README files. Generated parameter YAML/Markdown are build
artifacts and are not committed. CMake and Makefile source lists are updated.
Standalone test helpers cover file records, expected failures, and DOS curves
that Autotest scalar references cannot express; ordinary scalar checks still
use Autotest. Fixtures are immutable, use scratch directories and timeouts, and
forward MPI launcher flags.

The combined implementation passed a clean GNU/CMake CPU build and 27 scoped
CTest entries (two are existing deferred TS counterexamples; one old HSolver
target has zero active gtests and provides compile/link/startup coverage only).
GPU evidence uses a CUDA build on one device, including two MPI ranks sharing
that device. No new Intel, Makefile, ROCm, multiple-device or full MPI-off build
was run locally. GitHub CI must run on the pushed revisions. The Ne/TS total
error estimator is outside this change.

Upload verification (2026-12-03): reran the combined scope (25/25) and the independent PR suites (5/5, 8/8, 8/8), using the unchanged binary hashes recorded locally. Commands: ctest --test-dir verification/pr-review-fixes/ctest-pr8381 --output-on-failure -j1; combined selection excludes the separate LOW_TS/TS_UNDERESTIMATE counterexamples.

@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 dump path needs fixes for collective participation, valid row counts, and format/INPUT compatibility. The inline comments identify the affected cases.

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

Non-blocking: add a checked-in test that enables this writer. None of the existing tests/06_SDFT inputs enables out_wfc_pw, so routine suite checks do not cover the new path; retain a known-coefficient/layout fixture and a bounded MPI case for empty band groups.

Comment on lines +102 to +104
if (nkstot <= 0 || nks <= 0 || spec.nbands_out <= 0)
{
return;

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.

[P1] Keep empty band groups in the collective sequence

With nbands_sto=1, bndpar=2 and method_sto=1, one band group has zero rows and returns here while the other reaches MPI_Barrier(MPI_COMM_WORLD). If the solver reaches this output step, the world-collective sequence is inconsistent and may hang. Synchronize file creation within the writing pool, or make world participation unconditional before this local return.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

after_scf() now calls write_wfc_pw from every band group, so an empty group cannot skip the barrier (it writes a header-only frame). Tested with bndpar 2, nbands_sto 1, -np 4: no hang, and each group writes its own bg<i> files.

Comment on lines +35 to +39
// Extra information needed by the real-space Fourier transform.
ofs << "# FFT grid (wave functions) = " << wfcpw->nx << " " << wfcpw->ny << " " << wfcpw->nz
<< std::endl;
ofs << "# band range in the solver array = [" << spec.band_begin + 1 << ", "
<< spec.band_begin + spec.nbands_out << "]" << std::endl;

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.

[P2] Preserve compatibility with the existing PW text reader

tests/integrate/validation_tools/collect_wfc_props.py expects <Reciprocal Lattice Vector> immediately after the two header lines and skips only blank lines. These added comments therefore make that reader reject the dump. Preserve the compatible layout or update the supported readers and retain a compatibility test.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Extra # lines removed. The dump uses write_wfc_pw, so the layout is the KSDFT one; collect_wfc_props.py parses all four files.

Comment on lines +153 to +156
if (this->inp_->out_wfc_pw == 0 || this->inp_->basis_type != "pw" || istep != 0)
{
return;
}

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.

[P2] Make the SDFT format selection match the INPUT help

out_wfc_pw=2 is now accepted for SDFT and documented as binary output, but this nonzero check always dispatches the text writer and creates only *_pw.txt files. Implement the binary mode or restrict SDFT to the supported text value and document that distinction.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

out_wfc_pw is forwarded to the shared writer, which already handles 1 and 2. out_wfc_pw 2 writes the four .dat files, CPU and GPU.

Comment on lines +224 to +226
spec.band_begin = 0;
spec.nbands_out = std::min(job.psi->get_nbands(), job.max_nbands);
ModuleIO::write_wfc_pw_txt_selected(spec, ctx, *job.psi, this->kv, this->pw_wfc, ofs);

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.

[P2] Select valid rows separately for each k point

For nbands_sto=all, get_nbands() is the common allocation capacity nchip_max, while calTnchi_ik() fills only stowf.nchip[ik] rows. If a k point has fewer valid rows than this capped count (for example local counts 3 and 4), its shchi dump includes an uncomputed padding row. Pass the per-k valid counts into the writer and use them for both the header and coefficient loop.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Rows are min_k stowf.nchip[k] (max 4) and the header uses the same number, so no padding row is written.

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.

shchi now uses the safe per-k minimum, but chiortho still takes its count from the KS buffer at esolver_sdft_pw.cpp:179. With nbands=12, nbands_sto=1, it requests two rows from a one-row stochastic allocation; the shared writer then asserts or reads beyond it. Use min(nsto, 2) and keep zero-row groups in the writer's collective sequence. Please add a checked-in regression for one/zero-row stochastic partitions in text and binary mode.

Comment on lines +320 to +324
For `esolver_type=ksdft` the Kohn-Sham coefficients are written; for `esolver_type=sdft`
this parameter also switches on the SDFT/MDFT dumps of the deterministic (Kohn-Sham) orbitals,
the raw stochastic orbitals, the stochastic orbitals orthogonalized against the Kohn-Sham
subspace, and the occupation-filtered stochastic orbitals that enter the charge density
(`wfc_ks_k*, wfc_sto_k*, wfc_chiortho_k*, wfc_shchi_k*`).

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.

Non-blocking: document that SDFT writes only at ionic step zero, only on CPU, and only the first four KS/raw/filtered orbitals and first two chiortho orbitals per band group. The general frequency/append description below otherwise implies later MD or relaxation frames, and the fixed sampling limits are currently undisclosed.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Documented in the out_wfc_pw description: first ionic step only, at most 4/4/4/2 orbitals, and bg<i> files when bndpar > 1.

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.

Non-blocking: the CPU-only sentence is now stale because dump_on_host also handles the filtered and orthogonalized sets on GPU. Please remove that restriction, explicitly scope the general frequency/append paragraphs to KSDFT, and update the PR body's deleted helper and old filenames.

Comment on lines +142 to +145
int ikngtot = 0;
#ifdef __MPI
MPI_Allreduce(&kv.ngk[ik], &ikngtot, 1, MPI_INT, MPI_SUM, POOL_WORLD);
#else

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.

[P2] Use internally guarded MPI wrappers

Root AGENTS.md rule 9 requires internally guarded MPI wrappers; this new file adds four direct calls. Use the guarded reduction/barrier wrappers with the correct file-owning pool. The requested global-dependency exception covers the four named global reads, not these MPI calls.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

That file is deleted. All collectives come from write_wfc_pw; the added lines contain no MPI_* call.

Comment on lines +121 to +125
ofs_running << " Write G-space wave functions to file: " << fn << std::endl;
if (ctx.rank_in_pool == 0)
{
std::ofstream ofs(fn.c_str());
ofs.close();

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.

Non-blocking: check the create/append streams and propagate failures consistently across the writing pool. An unwritable target or failed write currently leaves missing, stale or partial output while the running log still announces the dump filename.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Now handled by the shared writer, i.e. the same path as the KSDFT dump; nothing extra added here.

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.

Non-blocking: write_wfc_pw still opens and writes text ofstreams without checking their state, and the new caller ignores ensure_directory()'s result. This remains an inherited shared-writer issue; please track text-output failure detection and consistent pool handling there.

Comment on lines +118 to +119
const std::string fn = ctx.out_dir + spec.prefix + "k"
+ std::to_string(kv.ik2iktot[ik] + 1) + "_pw.txt";

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.

Non-blocking: assign kv.ik2iktot[ik] + 1 to a named one-based k index before passing it to std::to_string, as required by root rule 14.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Code removed; the names come from filename_output() in the shared writer.

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.

Non-blocking: the new after_scf() dump calls still build tags and allocation-base pointers inside their argument lists, including get_pointer() - get_psi_bias() at lines 229–230. Please bind these computations to named locals before passing them, as required by root rule 14.

@mohanchen mohanchen added the Refactor Refactor ABACUS codes label Nov 25, 2026

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.

output_wfc_sdft should not belong to 'esolver_sdft_pw', it should be put inside the function 'after_scf'

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Done: output_wfc_sdft() removed, the dump is inside after_scf().

{

/// Header block plus the reciprocal lattice and the opening "<G vectors>" tag.
void write_header(std::ofstream& ofs,

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.

this part should be similar to the KSDFT output of wave functions

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Done: module deleted, it calls ModuleIO::write_wfc_pw() directly. The only shared-code change is an optional filename tag for the four dump sets.

#endif
for (int id = 0; id < ctx.nproc_in_pool; ++id)
{
#ifdef __MPI

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.

use Parallel_xxx functions, do not use MPI functions directly

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Done: no direct MPI calls left; collectives come from the shared writer.

@mohanchen mohanchen added the Input&Output Suitable for coders without knowing too many DFT details label Nov 25, 2026
@LiYuqiii
LiYuqiii force-pushed the sdft-wfc-dump branch 2 times, most recently from cc352f3 to 376a59e Compare November 25, 2026 08:35
3.11 only writes wfk*_pw.txt for esolver_type=ksdft: ESolver_SDFT_PW overrides
iter_finish() and never reaches ModuleIO::write_wfc_pw, so SDFT/MDFT runs cannot
be inspected in real space at all.

Reuse out_wfc_pw as the switch and call the existing writer
(ModuleIO::write_wfc_pw) from after_scf(), so the SDFT dumps share its file
layout, its text and binary modes, its collective pattern and its filename
scheme. The only change to the shared code is an optional filename tag, because
four independent orbital sets are written per run: wf_ks, wf_sto, wf_shchi and
wf_chiortho.

Every band group calls the writer, so a band group without orbitals cannot leave
the others waiting in the writer's world barrier; such a group writes a
header-only frame and, with bndpar > 1, every group uses its own bg<i> files. The
number of stochastic rows is capped by the smallest per-k value of
stowf.nchip, so a k point with fewer orbitals never dumps an uncomputed padding
row. Nothing is written unless out_wfc_pw is 1 or 2.

@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 chiortho dump can read beyond its stochastic rows; please bound it by nsto as detailed in the existing row-count thread. At b9a3d98, the shared writer addresses the earlier empty-group barrier skip, extra header comments, binary-format routing, and newly added direct MPI calls.

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

// the device; bring the host copy up to date before reading it, exactly as
// the KSDFT output path does (ModuleIO::ctrl_iter_pw).
this->stp.sync_cpu();
const std::string psi_dir = PARAM.globalv.global_psi_dir;

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.

[P2] The global-dependency exception no longer matches this implementation: the PR now adds five global references in after_scf(), including PARAM.globalv.npol, while the body describes four reads in the deleted output_wfc_sdft(). Please pass/remove these dependencies or update the exception to the current count and scope for maintainer approval.

const ModulePW::PW_Basis_K* wfcpw,
std::ofstream &ofs_running);
std::ofstream &ofs_running,
const std::string& property_tag = "");

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.

Non-blocking: this and filename_output() add default arguments to existing interfaces, which root rule 5 prohibits. Preserve the empty-tag behavior with a forwarding overload, or make tag selection explicit at callers.

Comment on lines +226 to +231
psi::Psi<std::complex<double>> host(
this->kv.get_nks(), src.get_nbands(), this->pw_wfc->npwk_max, this->kv.ngk, true);
base_device::memory::cast_memory_op<std::complex<double>, T, base_device::DEVICE_CPU, Device>()(
host.get_pointer() - host.get_psi_bias(),
src.get_pointer() - src.get_psi_bias(),
host.size());

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.

Non-blocking: this allocates and copies every stochastic row even though the dump writes at most four or two. It also duplicates CPU data that the writer can already read directly. Please reuse host storage on CPU and stage only the selected per-k rows on GPU.

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

Input&Output Suitable for coders without knowing too many DFT details Refactor Refactor ABACUS codes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants