Skip to content

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

Open
LiYuqiii wants to merge 1 commit into
deepmodeling:developfrom
LiYuqiii:sdft-wfc-dump
Open

LiYuqiii wants to merge 1 commit into
deepmodeling:developfrom
LiYuqiii:sdft-wfc-dump

Conversation

@LiYuqiii

@LiYuqiii LiYuqiii commented Nov 24, 2026 •

Copy link
Copy Markdown
Collaborator

Reminder

  • I have read AGENTS.md and docs/developers_guide/agent_governance.md.
  • I have linked an issue or explained why this PR does not need one.
  • I have added adequate unit tests and/or case tests, or explained why not.
  • I have listed the exact verification commands run and their results.
  • I have described user-visible behavior changes, including INPUT parameter changes.
  • I have explained core-module impact for ESolver / HSolver / ElecState / Hamilt / Operator / Psi.
  • I have requested any needed governance exception below.

Linked Issue

Part 1/3 of the SDFT work reported in #8379 and #8380. This part is a standalone feature (it makes
the SDFT/MDFT wavefunctions visible) and does not fix those two issues; the DOS and entropy fixes
are in part 2/3 (#8382).

Unit Tests and/or Case Tests for my changes

  • Commands run:
    • abacus -h out_wfc_pw
    • mpirun -np 4 abacus on tests/06_SDFT/01_PW_SDFT_10S_M (Al, esolver_type sdft) with
      out_wfc_pw 1
    • the same cell with esolver_type ksdft, nbands 12, out_wfc_pw 1, then
      diff of the headers of wfk1_pw.txt and wfc_sto_k1_pw.txt
    • tests/06_SDFT through tests/integrate/Autotest.sh (24 cases, 116 checks)
    • cmake --build --target abacus_pw_para on top of the current develop
  • Result summary:
    • -h out_wfc_pw reports the new availability
      (basis_type==pw and (esolver_type==ksdft or esolver_type==sdft))
    • the SDFT run writes wfc_sto_k1_pw.txt and wfc_shchi_k1_pw.txt; every coefficient of the raw
      stochastic orbital has |c| = 1/sqrt(nbands_sto) = 0.316228
    • header, <Reciprocal Lattice Vector>, <G vectors> and < Band N > layout of our files is
      identical to the wfk1_pw.txt that the KSDFT solver writes for the same cell
    • tests/06_SDFT: 116/116 checks pass
  • Checks not run, with reason: no unit test is added for the writer itself; it is a pure text
    serialiser whose only meaningful verification is the byte layout compared against the KSDFT output
    of the same cell, which the case test above checks.

What's changed?

out_wfc_pw is accepted for esolver_type=sdft but produced nothing: ESolver_SDFT_PW overrides
iter_finish() and never reaches ModuleIO::write_wfc_pw, so SDFT/MDFT runs could not be inspected
in real space at all.

ESolver_SDFT_PW::after_scf() now dumps, when out_wfc_pw != 0, four sets of orbitals with the
existing wfk{k}_pw.txt text layout (so the same post-processing works unchanged):

  • deterministic (Kohn-Sham) orbitals -> OUT.*/wfc_ks_k*_pw.txt
  • raw stochastic orbitals |chi> -> OUT.*/wfc_sto_k*_pw.txt
  • ones orthogonalized against the KS space -> OUT.*/wfc_chiortho_k*_pw.txt
  • occupation-filtered ones sqrt(f(H))|chi~> that enter the charge density
    -> OUT.*/wfc_shchi_k*_pw.txt

With bndpar > 1 every band group writes its own files (bg<i>_ suffix) and a warning is printed.
No new INPUT keyword is introduced.

Governance Notes

  • INPUT/docs changes: only the availability and the description of the existing out_wfc_pw
    parameter are updated in source_io/module_parameter/read_inp_out.cpp. docs/parameters.yaml and
    docs/advanced/input_files/input-main.md are generated from those Input_Item registrations, so
    there is no documentation update required here.
  • Core module impact: new opt-in step in ESolver_SDFT_PW::after_scf(); the KSDFT path is untouched.
    The writer lives in a new module (module_stodft/sto_wfc_out.{h,cpp}) that takes everything through
    ModuleIO::WfcDumpContext / WfcDumpSpec and has no global-state dependency.
  • Exceptions requested: Global dependency budget (+4 references in output_wfc_sdft()), see below.

Governance Exception

  • Rule: Global dependency budget
  • Reason: building the dump context needs the output directory and the pool / band-group indices,
    and the band-parallel warning goes to the running log. In this version ESolver_SDFT_PW has no
    accessor for them, so the new function reads GlobalV::ofs_running, GlobalV::MY_POOL,
    GlobalV::MY_BNDGROUP and PARAM.globalv.global_out_dir once per run (net +4).
  • Scope: source/source_esolver/esolver_sdft_pw.cpp, function output_wfc_sdft() only.
    module_stodft/sto_wfc_out.* adds no global reference.
  • User or maintenance risk: low. The values are read once, and the whole function returns
    immediately unless out_wfc_pw != 0 and istep == 0.
  • Why the normal rule cannot be followed now: passing them down would change the
    ESolver::after_scf() / ModuleIO interfaces, a much larger cross-layer change than the feature.
  • Follow-up cleanup plan: bundle these values into a small context struct created at the Driver
    level, pass it through after_scf(), and delete the global reads.
  • Requested approver: ABACUS maintainer

@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