Skip to content

SDFT: fix the high-temperature DOS blow-up and the Ne/TS precision asymmetry - #8382

Open
LiYuqiii wants to merge 6 commits into
deepmodeling:developfrom
LiYuqiii:sdft-dos-ts-fix
Open

LiYuqiii wants to merge 6 commits into
deepmodeling:developfrom
LiYuqiii:sdft-dos-ts-fix

Conversation

@LiYuqiii

@LiYuqiii LiYuqiii commented Nov 24, 2026 •

Copy link
Copy Markdown
Collaborator

Linked Issue

This updates the existing high-temperature SDFT DOS PR and addresses its review;
no separate issue is needed for these corrections.

What's changed?

SCF and postprocessing use operator-based interval estimates with explicit,
rank-separated probe streams. Conductivity checks also include a dense probe
when inheriting an SCF interval. DOS refreshes endpoints for the final potential
and checks growth inside its normal moment recurrence. Requested DOS windows
are independent of the spectrum; no Gaussian-tail clipping is performed.
Method-2 matrix/BLAS dimensions are checked before allocation (dos_nche <= 46340);
dos_nche >= 1 and positive sigma, grid step and partition count are documented
and checked. Last-term DOS errors use eV^-1. Original stable scalar entropy-kernel
fixes and MPI-off test registration are preserved; total-error assessment is deferred.

Unit Tests and/or Case Tests for my changes

ctest --test-dir verification/pr-review-fixes/ctest-pr8382 --output-on-failure -j1:
eight entries passed on the independent PR binary, covering 9/348/1400 eV,
200 g/cc, methods 1/2, two/four MPI ranks, unequal k pools, empty groups and
invalid INPUT. Combined unit tests cover rank-distinct initial/restart probes,
positive/shifted spectra, a missed direction through check_che_op, distinct-array
strided dot products, and entropy kernels. An actual 348 eV sKG smoke run produced
five finite Onsager rows. Combined GPU SCF tests passed at one/two MPI ranks.

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-pr8382 --output-on-failure -j1; combined selection excludes the separate LOW_TS/TS_UNDERESTIMATE counterexamples.

Latest develop synchronization (67d6746c4): resolved output-layout and unit-test
migration conflicts without changing interval/entropy algorithms. The scalar
entropy tests retain upstream coverage but compare tails against the smooth
analytic expression instead of requiring the removed |x| > 36 cutoff.
A GNU/CMake CPU build of PR 8382 and 11 scoped unit-test entries passed (the old
HSolver target still has no active gtests). The independent eight-entry PR 8383
fast suite and four DOS-quality gtests passed. PR 8383 was built incrementally
from those fresh PR 8382 objects after checking all other production sources and
headers are identical; its two changed production objects were rebuilt.
The method-1 two-rank fixture now covers out_app_flag=2; it exposed and fixed
Autotest's text-DOS collector reading the old directory. The failed case passed
again with unchanged numerical references. The new PR 8382 sKG smoke also passed
with five finite Onsager rows and a logged DOS/Chebycoef.txt.

Commands: ctest --test-dir verification/pr-upload/cmake-upstream --output-on-failure -R 'MODULE_PW_(STO_|sto_func|Sto_)|MODULE_BASE_(chebyshev_final_vector|filename)' -j1;
ctest --test-dir verification/pr-upload/ctest-upstream-8383 --output-on-failure -j1.
Changed CMake files pass cmake-format; governance against the fetched develop
reports zero blockers, with a global-reference net delta of -17. Existing
ESolver output-directory reads are passed explicitly to the lower-level routines.
The numerical/GPU measurements recorded before this upstream synchronization
remain labeled with their original code hashes; this synchronization has fresh
CPU/MPI verification and will also be checked by GitHub CI.

The three-PR combined tree with current develop additionally passed 13/13 CPU/MPI
fast and wavefunction-output entries (18.67 s). Remote Governance now passes for
all three PRs. Read the Docs currently fails because Sphinx cannot connect to
docs.scipy.org/doc/scipy/objects.inv; all four failing build logs report this
single external-inventory warning as an error. The input dumper compilation and
parameter generation succeeded. Those documentation builds still need a retry;
other CI jobs are in progress. No warning suppression or numerical change was
made to hide that infrastructure failure.

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

Three issues in range handling can reduce fixed-order accuracy or leave conductivity states outside the Chebyshev interval. Please address the inline findings; the entropy-density formula itself is consistent with Fermi–Dirac entropy.

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

  • Non-blocking: correct the PR’s claimed dot() fix and attribute the precision numbers to the actual tested revision. The existing #8380 diagnosis still applies at this head.
  • Non-blocking: document the new dos_nche >= 2 requirement in its C++ Input_Item metadata.
  • Non-blocking: give the computed arguments in the new safe_emin/guard_ry calculations named local values, as required by AGENTS rule 14.

Comment on lines +173 to +179
if (output_emin_ry - guard_ry < *p_hamilt_sto->emin)
{
*p_hamilt_sto->emin = output_emin_ry - guard_ry;
}
if (output_emax_ry + guard_ry > *p_hamilt_sto->emax)
{
*p_hamilt_sto->emax = output_emax_ry + guard_ry;

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] Keep output limits separate from the spectral interval

The output energy is the Gaussian centre; calcoef_real samples that Gaussian at cos(theta), while the recurrence evaluates T_n(H). Widening this interval at fixed dos_nche can therefore miss a previously resolved peak: with N=100, sigma=0.07 eV and an output window of ±10000 eV, every coefficient sample for a 2 eV peak lies beyond the Gaussian cutoff and returns zero. Keep the verified Hamiltonian interval independent of the output window, and test DOS at common energies when only the window changes.

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.

Interval is no longer widened; the output window is clipped to it (reported only when more than 1% is cut). Healthy case unchanged: ∫DOS = 12806.6, no |t| > 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.

At 37d8320, the Hamiltonian interval is no longer widened, but clipping the requested output window still removes valid Gaussian tails and changes the integrated DOS. The expansion is in normalized H; targ_e is only the Gaussian centre, so it may lie outside the interval without evaluating T_n outside [-1,1]. Please keep the requested grid, including dos_scale padding, and add a boundary-tail/common-energy regression.

Comment on lines +223 to +228
if (!std::isfinite(*p_hamilt_sto->emin) || *p_hamilt_sto->emin > 0)
{
const double safe_emin = -std::max(5.0, 0.01 * std::abs(*p_hamilt_sto->emax));
GlobalV::ofs_running << " WARNING: positive automatic Chebyshev Emin "
<< *p_hamilt_sto->emin << " Ry is reset to " << safe_emin << " Ry" << std::endl;
*p_hamilt_sto->emin = safe_emin;

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 valid positive trial bounds

This branch also replaces an explicitly supplied positive emin_sto after checkconverge() has accepted the interval. A positive kinetic or shifted spectrum is valid; forcing its lower bound below zero enlarges the interval and changes the fixed-order occupation/entropy approximation and chemical-potential search. Preserve validated positive bounds and use spectral evidence to trigger a fallback, with a positive/translated-spectrum regression; the same condition in check_che_op needs the same treatment.

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.

The repair now only applies when PARAM.inp.emin_sto == 0; an explicitly given positive bound is kept, in both call sites.

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 explicit-input case is addressed in 37d8320: both fallback branches now check emin_sto == 0. The automatic path still uses the sign of Emin rather than spectral containment, so the general positive/shifted-spectrum limitation remains open.

Comment on lines +60 to +65
const bool use_random = (p_stowf->nchi <= 0) || (nbands_sto == 0 && p_stowf->nchip_max <= 0);
if (use_random)
{
randchi_d.resize(1, 1, npw);
}
int ntest = std::min(ntest0, p_stowf->nchip[ik]);
int ntest = use_random ? 1 : std::min(ntest0, p_stowf->nchip[ik]);

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] Retain a full-support probe for complete-basis conductivity

For nbands_sto=all, these are coordinate vectors, so the first five can miss another invariant subspace. The conductivity caller resets zero INPUT trials and uses a 2 Ry expansion step: a kinetic spectrum whose first five energies are below 2 Ry but has an omitted state between 2 and 5 Ry can pass SCF’s 5 Ry check, then receive an insufficient interval here. sKG subsequently applies the polynomials to all basis vectors, including those outside the interval. Keep an independent dense probe or a justified full-operator bound, and add a diagonal-spectrum regression covering this reset.

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.

Added: the probe set now contains one independent random vector in addition to the real stochastic orbitals, so with nbands_sto all (where those orbitals are coordinate vectors) a state in another invariant subspace can still be reached.

I did not add the diagonal-spectrum regression test you suggested: check_che_op needs a real StoHamiltPW and K_Vectors, and hPsi_norm is not virtual, so the existing unit-test target cannot mock it without a larger refactor. The change is exercised by every SDFT run (the tests/06_SDFT cases). If you want the mock-based test anyway, I can add it in a follow-up.

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.

Addressed in the source at 37d8320: each real-orbital probe set now includes an independent random vector, including nbands_sto=all. The focused regression remains deferred as described in your reply.

Comment on lines +232 to +233
const double ecut_floor = 1.05 * PARAM.inp.ecutwfc;
if (PARAM.inp.ecutwfc > 0 && *p_hamilt_sto->emax < ecut_floor)

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 exception rationale also needs to cover the four new PARAM.inp.ecutwfc reads here and in sto_tool.cpp. They control the Hamiltonian interval, so the proposed ostream cleanup would leave this computational dependency in place. Pass the cutoff explicitly or include its scope, numerical risk and removal plan in the requested exception.

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.

Added to the PR description: the governance exception now covers the PARAM.inp.ecutwfc reads explicitly, and says that the cutoff is part of the repair arithmetic (so it stays after the proposed logging cleanup), with the removal plan.

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 updated rationale now covers the computational cutoff reads and their cleanup plan. This PR still adds seven code references to PARAM/GlobalV, so the requested exception needs maintainer approval, or the dependencies need to be passed explicitly.

if(BUILD_TESTING)
if(ENABLE_MPI)
add_subdirectory(test)
add_subdirectory(unittests)

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: register the scalar entropy tests outside the ENABLE_MPI guard. Their own CMake file disables MPI and they exercise no parallel code, but this placement prevents MPI-off builds from running the new regression.

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.

Moved: add_subdirectory(unittests) now sits outside the if(ENABLE_MPI) block, so MPI-off builds also run the new scalar tests.

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.

Addressed in the source at 37d8320: the scalar test directory is now registered under BUILD_TESTING for both MPI-on and MPI-off configurations.

@mohanchen mohanchen added Refactor Refactor ABACUS codes Bugs Bugs that only solvable with sufficient knowledge of DFT labels Nov 25, 2026
@LiYuqiii
LiYuqiii force-pushed the sdft-dos-ts-fix branch 2 times, most recently from 3f0510a to d4c5b2d Compare November 25, 2026 08:45
Four defects made SDFT/DOS unreliable at high electronic temperature:

* Math_Chebyshev::checkconverge() treats tmin == 0 as its "uninitialized"
  sentinel, so a positive trial Rayleigh quotient can leave Emin > 0 and exclude
  every bound state; the upper bound is underestimated in the same path.
* the DOS stage re-derived the range from the input defaults instead of keeping
  the converged SCF range, and Stochastic_WF::nchi was never initialized, so the
  range probe always used random vectors even for MDFT.
* dos_scale widened the reported window by 0.5% per side without any relation to
  the Chebyshev interval, so a grid point could sit outside the spectral range.
* the entropy density formed 1 - f by subtraction and returned 0 for |x| > 36,
  which lifted the sqrt(g) coefficient tail from ~1e-19 to ~1e-12, and
  Stochastic_Iter::dot() ignored the arrays it was given, so the printed
  Chebyshev "precision" of the stochastic trace was not the quantity it claimed.

Fixes: keep the converged SCF range in the DOS stage, initialize nchi, repair a
positive automatic lower bound and an underestimated upper bound at the call
sites (an explicitly given emin_sto is preserved, since a positive spectrum is
valid), clip the requested output window to the spectral interval instead of
widening the interval, evaluate the entropy density with s = min(f, 1-f) and
log1p(-s), and make dot() contract the arrays that the caller passes.

The range probe now also carries one independent random vector next to the real
stochastic orbitals: with `nbands_sto all` those orbitals are coordinate
vectors, so a handful of them can miss a diagonal state of another invariant
subspace. The new unit test for the entropy kernels fails on the unpatched
sto_func.cpp and passes here; dos_nche >= 2 is documented in its INPUT metadata.

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

Two DOS issues remain: the output window now loses valid Gaussian tails, and the clipping warning is unreachable. Keep the requested grid independent of the spectral bounds; I have followed up in the existing window thread.

The dot() fix and dos_nche >= 2 metadata are now present at 37d8320.

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

Non-blocking: give the new dropped-width and assembled warning-text arguments in sto_dos.cpp named local values before passing them to functions (AGENTS.md rule 14).

Comment on lines +196 to +198
const double dropped_ev
= std::max(requested_emin_ev - clipped_emin_ev, clipped_emax_ev - requested_emax_ev);
const bool report_clip = dropped_ev > 0.01 * interval_span_ev;

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.

[P3] Measure the removed window widths with positive signs

Both differences are nonpositive by construction: clipped_emin_ev >= requested_emin_ev and clipped_emax_ev <= requested_emax_ev. Consequently report_clip is always false for a valid interval, even when a large portion of the requested window is removed. If clipping is retained, reverse both subtractions so the promised warning can be emitted.

Real* result_device = nullptr;
resmem_var_op()(result_device, 1);
container::kernels::blas_dot<Real, ct_Device>()(n, p_che->coef_real, 1, spolyv, 1, result_device);
container::kernels::blas_dot<Real, ct_Device>()(n, x, incx, y, incy, result_device);

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: add a small regression with distinct input arrays and a nonunit stride for Stochastic_Iter::dot, so restoring the previous hard-coded operands would fail. The new scalar entropy tests do not exercise this helper, and check_precision needs the two different matrix-slice contractions.

msg << "dos_sigma = " << sigma_ev << " eV is narrower than the Chebyshev expansion can resolve: "
<< "range = " << range_ev << " eV, dos_nche = " << this->dos_nche
<< ", estimated order needed ~ " << static_cast<long long>(std::ceil(nche_needed))
<< ". Increase dos_nche (method 1 or method 2 with sufficient memory) or use a larger dos_sigma.";

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: please qualify “method 2 with sufficient memory” for the very large orders now described in the INPUT help. Method 2 still forms dos_nche * dos_nche and matrix indices as signed-int products, so an order of 1e5 overflows on platforms with 32-bit int before available memory is the limiting condition. Recommend method 1 for such orders, or require checked dimension/index arithmetic as well as adequate memory.

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 Refactor Refactor ABACUS codes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants