Skip to content

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

Open
LiYuqiii wants to merge 1 commit into
deepmodeling:developfrom
LiYuqiii:sdft-dos-ts-fix
Open

LiYuqiii wants to merge 1 commit into
deepmodeling:developfrom
LiYuqiii:sdft-dos-ts-fix

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

Fixes #8379.
Fixes #8380.

Part 2/3 of the series; part 3/3 is #8383.

Unit Tests and/or Case Tests for my changes

  • Commands run:
  • Result summary (all numbers from this branch on top of develop 503be43):
    • the new unit test passes (4/4 cases) with this patch and fails 2 of its 4 cases
      (no_artificial_cutoff_jump, tail_asymptotics_and_extremes) against the unpatched sto_func.cpp;
      the pre-existing MODULE_PW_Sto_Tool_UTs still passes
    • SDFT: TSRelative Chebyshev Precision is abnormally large (orders of magnitude above NeRelative) #8380 input (ecutwfc 900, nche_sto 40, 2 SCF steps):
      E_entropy(-TS) -1.28e8 Ry -> -787.847 Ry, !FINAL_ETOT_IS -1.745e9 eV -> -8789.859 eV,
      NeRelative 5.1e-15 -> 1.9e-12, TSRelative 0.73 -> 3.8e-15
    • SDFT: DOS values of 1e52 at high electronic temperature #8379 input (ecutwfc 210, dos_sigma 0.07 eV, dos_nche 100): the automatic range no longer
      comes out positive (+18.06 Ry -> -5.02 Ry), max |DOS| 1.9e52 -> 34.1 eV^-1 and the
      reported Chebyshev error 1.8e53 -> 3.13; the output window is clipped to the interval
      ([-68.2, 2880] eV) instead of the interval being widened to the window
    • the same cell with a well-resolved window (dos_sigma 20 eV, dos_edelta_ev 0.5,
      dos_nche 600): integral 12806.2 and max |DOS| = 9.72, i.e. the curve is unchanged by the fix
    • tests/06_SDFT: 116/116 checks pass
  • Checks not run, with reason: no new case test is added under tests/; the kernels are covered by the
    unit test and the end-to-end effect by the existing tests/06_SDFT cases.

What's changed?

Defects and fixes:

  • Math_Chebyshev::checkconverge() uses tmin == 0 as "uninitialized", so a positive trial Rayleigh
    quotient leaves Emin > 0 (excluding every bound state) and Emax can be underestimated.
    The two call sites (Stochastic_Iter::checkemm, Sto_Tool::check_che_op) now repair only an
    automatic
    bound of that kind and leave an explicitly given emin_sto untouched, because a
    genuinely positive (kinetic or shifted) spectrum is a valid interval.
  • 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 fell back to
    random vectors; both are fixed. The probe now also carries one independent random vector next to
    the real stochastic orbitals, since with nbands_sto all those orbitals are coordinate vectors and
    a handful of them can miss a diagonal state of another invariant subspace.
  • dos_scale widened the reported window with no relation to the Chebyshev interval. The interval is
    now treated as a property of the spectrum (widening it at fixed dos_nche would reduce the
    resolution and could hide a peak), and the requested output window is instead clipped to the
    interval with a message in running_scf.log.
  • The entropy density formed 1 - f by subtraction and returned 0 for |x| > 36, so sqrt(g) lost
    its tail; it is now evaluated as s = min(f, 1-f), g = s*log(s) + (1-s)*log1p(-s) with no
    artificial cutoff. Stochastic_Iter::dot() now contracts the arrays it is given (it ignored them
    before, so the printed Chebyshev "precision" of the stochastic trace was not the quantity claimed).
  • dos_nche >= 2 and dos_edelta_ev > 0 are validated, and dos_nche >= 2 is now documented in its
    Input_Item metadata.

Governance Notes

  • INPUT/docs changes: no new keyword and no default change; dos_nche's description now states the
    minimum order and the range/dos_sigma scaling. There is no documentation update required
    elsewhere.
  • Core module impact: module_stodft only (Sto_DOS, Sto_Tool, Sto_Func, Stochastic_Iter,
    Stochastic_WF); the KSDFT solver is untouched.
  • Exceptions requested: Global dependency budget, see below.

Governance Exception

  • Rule: Global dependency budget
  • Reason: the diagnostics are reported through GlobalV::ofs_running, the channel the SDFT range
    checks already use, and the repaired interval needs the plane-wave cutoff
    (PARAM.inp.ecutwfc) as an upper-bound floor together with PARAM.inp.emin_sto to tell an
    automatic bound from a user-supplied one. Both are read once per SCF step (or once per DOS
    calculation) and are part of the arithmetic that defines the Hamiltonian interval, so they are not
    removed by passing an output stream later; the proposed cleanup below only covers the logging
    reads.
  • Scope: source/source_pw/module_stodft/sto_dos.cpp, sto_iter.cpp, sto_tool.cpp.
  • User or maintenance risk: low. No behavioural change for healthy input; the messages are what makes
    a silent DOS/entropy failure visible.
  • Why the normal rule cannot be followed now: Sto_DOS / Sto_Tool / Stochastic_Iter are not given
    the output stream or the cutoff, and threading them through would change the ESolver <->
    module_stodft interface.
  • Follow-up cleanup plan: pass an std::ostream& (or a small logging context) and the cutoff down
    from the esolver; the cutoff can then replace the PARAM.inp.ecutwfc reads, and the logging
    context the GlobalV::ofs_running 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.

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

3 participants