Skip to content

Commit 40dfda0

Browse files
authored
Fix: Backport selected fixes from develop to LTS (#8202)
* Fix(hsolver): reset Davidson restart coefficients to identity Backport b72b281 from accel. Clear vcc before setting its diagonal in DiagoDavid::refresh. Once the basis is replaced by the current Ritz vectors, their coefficients in that basis must be the identity matrix. Retaining old off-diagonal entries corrupts subsequent residuals and can produce a non-finite projected Hamiltonian. LTS adaptation: use the LTS memory API (setmem_complex_op with ctx). Validation: code inspection; Davidson restart path preserves identity. Numeric impact: none for converged runs; fixes restart contamination. * Fix(elecstate): include G=0 magnetization in nspin=4 mixing Backport a2b8bc3 from accel (manual port; referenced commit is not in the current accel history). ig_gge0 is initialised to -1 and is non-negative exactly on the rank that owns G=0, with 0 being a valid index. The previous "> 0" test silently dropped the G=0 contribution on that rank, biasing the nspin=4 magnetization residual. Use ">= 0" at all three sites. Validation: nspin=4 non-collinear SCF; G=0 term matches accel. Numeric impact: fixes missing G=0 magnetization contribution for nspin=4. * Fix(hsolver): honor Hermitian upper triangle in genelpa Backport d52cdf0 from accel. generalized_eigenvector() now forms H*U^{-1} and B*H with the Hermitian matrix-matrix product (hemm) instead of gemm, so only the authoritative upper triangle of the Hermitian H is consumed. This restores the LCAO spin-rotation invariance needed by DeltaSpin. Add two DiagoElpaComplexTest regressions pinning the upper-triangle contract for the Cholesky and the fallback (DecomposedState==3) paths. LTS adaptation: use the existing Cpzhemm wrapper in my_math.hpp and the LTS module_hsolver/genelpa/elpa_solver.h header paths. Validation: LTS DiagoElpa LCAO tests; spin-rotation invariance. Numeric impact: fixes results when the lower triangle of H is stale. * Fix(lcao): correct Pauli-to-spinor conversion for nspin=4 Backport 1457e26 and 698e187 from accel, adapted to the LTS layout (H construction lives in module_gint/gint_k_pvpr.cpp, not gint_common.cpp). Changes: - gint_k_pvpr: H_{up,down} = B_x - i*B_y and H_{down,up} = B_x + i*B_y (clx_j sign), and fill H(-R) with the conjugate transpose of H(R) so that H(k) remains Hermitian for complex matrices. - density_matrix: spinor-to-Pauli rho_y = Im(rho_updown - rho_downup). - dftu_lcao transfer_vu: V_{up,down} = 0.5*(V_x - i*V_y), V_{down,up} = 0.5*(V_x + i*V_y). - dspin_lcao cal_coeff_lambda: lambda_{up,down} = lambda_x - i*lambda_y. - dftu_force_stress: VU and DMR are both in the Pauli basis, so drop the spurious VU/2 conversion; apply the force factor 2 only for nspin != 4. LTS adaptation notes: - dftu_pw.cpp is intentionally left unchanged: accel later restored the original (+i/-i) order there in ea86510, matching current LTS. - spin_constrain My remains +Im(occ1-occ2): accel reverted the negative sign in 7fff0c9, matching current LTS. - dspin_force_stress keeps the unconditional product-rule factor 2, as in LTS and accel (f8118a0). Validation: H(R=0) Hermiticity, scf_u_spin4/scf_deltaspin4, DFT+U forces. Numeric impact: fixes nspin=4 Hamiltonian, DFT+U and DeltaSpin forces; test references for the 03_NAO_multik nspin=4 cases were regenerated in accel. * Fix(pw): correct Pauli-y sign in DeltaSpin onsite force/stress kernels Backport the force/stress sigma_y convention used by accel 255a780 (originally 2cff4f5 / 457d9dd / 870ce15). The PW kernel stores the 2x2 Pauli blocks in the order (up,up), (down,up), (up,down), (down,down), so coefficients1 multiplies becp_down: H_{up,down} = lambda_x - i*lambda_y and H_{down,up} = lambda_x + i*lambda_y. Swap the imaginary parts on the CPU, CUDA and ROCm force and stress kernels. Validation: nspin=4 DeltaSpin force/stress; CPU/CUDA/ROCm consistency. Numeric impact: fixes the sign of the y magnetization force/stress. * Fix(pw): correct nspin=2 DeltaSpin magnetization output and force Backport 8801a66 from accel. - onsite_projector::cal_occupations(): index becp by the wavefunction npol instead of assuming npol=2, and store spin-up/down occupations in the up-up/down-down Pauli blocks for nspin=2. nspin=1 splits the occupancy evenly so the printed magnetization is zero; nspin=4 keeps the interleaved spinor layout. - PW DeltaSpin force kernel: add npol/isk and the npol==1 branch with the spin_sign factor (isk[ik]==1 -> -1), matching the GPU/ROCm and stress paths. Ported to CPU, CUDA and ROCm; keep the npol==2 code unchanged. - onsite_projector and spin_constrain (LCAO and PW shared print): use per-atom labels (Fe1, Fe2, ...) in the Total Magnetism / magnetic force tables instead of per-type labels. LTS adaptation notes: - LTS keeps the OnsiteProjector implementation in onsite_projector.cpp (accel split it into onsite_proj*.cpp); the isk pointer is taken from K_Vectors in init() and the DeltaSpin force call site passes npol/isk from Onsite_Proj_tools. Validation: nspin=2 DeltaSpin SCF magnetization/force; nspin=1 Mag=0; nspin=4 unchanged; CPU/CUDA/ROCm kernels consistent. Numeric impact: fixes nspin=2 DeltaSpin magnetization and force. * Fix(xc): retain meta-GGA contributions at zero density gradient Backport 0cab770 and 3b78838 from accel. The mGGA mask zeroed etxc, vrho and vtau at grid points where the density gradient vanishes, although the gradient term already carries a gdr factor. Keep the rho and tau thresholds only, for both nspin=1 and nspin=2. LibXC 5.1.7 mGGA functionals return finite values at sigma=0. LTS adaptation: applied to XC_Functional_Libxc::v_xc_meta() in xc_functional_libxc_vxc.cpp (accel refactored this into libxc_pot.cpp). Validation: 205/206_PW_SCAN; R2SCAN nspin=1/2 with NLCC. Numeric impact: only grid points with grad(rho)=0 and rho,tau above threshold; typically a tiny correction. * Fix(xc): use precision-matched gcar/kvec_c in grad_wfc Backport 98282bf from accel. grad_wfc mapped gcar/kvec_c as DT_DOUBLE but accessed them with data<Real>() (float in single precision), which triggers the Tensor data type check and aborts single-precision meta-GGA stress. Use the pre-allocated precision/device-matched get_gcar_data<Real>() and get_kvec_c_data<Real>() buffers, consistent with the SCF meta-GGA operator. LTS adaptation: applied to xc_functional_gradcorr.cpp (accel moved this code to xc_grad.cpp). Validation: precision single + mGGA stress, CPU/GPU. Numeric impact: none. * Fix(xc): cache LibXC functionals per OpenMP thread in gradcorr Backport the per-thread caching part of accel 255a780 (originally 4bc459b). Add gcxc_libxc / gcxc_spin_libxc / tau_xc / tau_xc_spin overloads that accept an already-initialized std::vector<xc_func_type>. The func_id overloads now initialize, delegate, and finish, preserving the public API. gradcorr initializes LibXC once per thread (before the ir loop) and reuses the functional vector for all grid points handled by that thread, instead of calling init_func/finish_func at every point (issue #6286). LTS adaptation: LTS wrappers live in xc_functional_libxc_wrapper_{gcxc, tauxc}.cpp and their signatures have no hybrid_alpha/hse_omega arguments; the new overloads match the LTS signatures. The per-thread vector is declared inside the existing OpenMP parallel region and released before the reduction critical section. Validation: PBE/SCAN/HSE results unchanged; init_func call count drops from O(nrxx*SCF) to O(nthreads*SCF). Numeric impact: none. * Fix(pw): accumulate PW stress contributions in double precision Backport 40d45f4, 693ed65 and c7e3e89 from accel. - stress_cc: use a double scalar for the NLCC isotropic reduction. - fs_kin_tools: keep the nine kinetic-stress accumulators in double. - stress_mgga: keep sigma_mgga[3][3] in double. Wavefunctions and per-band dot products keep their selected precision; only the accumulation over bands/k-points is promoted. Double builds are unchanged. LTS adaptation: applied to stress_func_cc.cpp / stress_func_mgga.cpp (accel filenames stress_cc.cpp / stress_mgga.cpp). Validation: single-precision GPU vs double CPU energy/force/stress. Numeric impact: reduces single-precision stress accumulation error only. * Fix(pw): reduce single-precision stress accumulation error Backport edd01d7 from accel. - nonlocal_maths::dylmr2: evaluate the 1e-6 finite difference in double when FPTYPE is float, then cast the derivative back. - stress_func_ewa: accumulate sdewald and its per-thread copies in double. - stress_func_loc: accumulate evloc in double. - stress_func_nl: for GPU single precision, allocate one 9-element stress buffer per k-point, copy all of them to the host, and sum in double; other configurations keep the original single-buffer path. LTS adaptation: applied to stress_func_{ewa,loc,nl}.cpp (accel filenames stress_{ewa,loc,nl}.cpp) using the LTS memory API with this->ctx. Validation: single-precision GPU vs double CPU stress. Numeric impact: reduces single-precision stress error only. * Fix(elecstate): accumulate GPU k-point densities in double precision Backport 7d6958f from accel. For GPU single precision, accumulate each k-point rho and kinetic density into the existing double host fields. Wavefunctions, FFTs and each k-point density stay in single precision; one host buffer is reused and the device density workspace is cleared after each k point. LTS adaptation: use the LTS castmem/setmem API with cpu_ctx/ctx. Enable the double accumulation only for the norm-conserving path (!double_grid && !use_uspp): LTS add_usrho() still transforms the device density buffer after the k loop, unlike accel where the USPP fix moved it to charge->rho. USPP preserves the previous behaviour until that fix is backported. Validation: GPU-single multi-k SCF; rho/tau electron count vs double. Numeric impact: reduces GPU single-precision density accumulation error. * Fix(cuda): bound long single-precision conjugate reductions Backport 6c10255 from accel. Split complex<float> GPU CGEMM A^H B reductions longer than 2048 into blocks, preserving alpha and the original beta on the first block. Subsequent blocks accumulate with beta=1. Other paths retain the existing call and single-precision storage is unchanged. LTS adaptation: use the LTS cublasErrcheck helper in module_hsolver/kernels/cuda/math_kernel_op.cu. Validation: single-precision Davidson with a long k-vector; compare with double CPU. Numeric impact: reduces single-precision long-reduction error. * Fix(hsolver): use double precision for GPU-single DAV reduced solves Backport 146ebdc from accel. For single-precision GPU Davidson without USPP, solve the small reduced matrix once in double precision and return the requested eigenpairs in single precision. Large wavefunction operations and stopping thresholds retain their existing precision policy. LTS adaptation: LTS calls dnevx_op instead of ct::kernels::lapack_heevx. Cast hcc to a double device buffer, call dnevx_op<std::complex<double>, Device>, then cast vcc/eigenvalues back. The reduced matrix is small, so the host round trip does not affect the dominant cost. Validation: GPU-single Davidson convergence steps/energy/force/stress vs double CPU. Numeric impact: improves GPU-single Davidson reduced-solve accuracy. * Fix(pw): add missing single-precision GPU instantiations Backport 4cc4a97 from accel, limited to code present in LTS. - stress_op.{h,cu,hip.cu}: use FPTYPE* for the DeltaSpin lambda argument so float GPU and CPU instantiations match the FPTYPE lambda buffer passed by Onsite_Proj_tools. - force_op.{cu,hip.cu}: instantiate saveVkbValues/revertVkbValues<float>. - onsite_projector / onsite_proj_tools: instantiate <float, DEVICE_GPU>. - xc_functional_gradcorr: instantiate grad_wfc<complex<float>, GPU, float>. LTS adaptation notes: - LTS has no templated SpinScalar cal_mw_from_lambda float-GPU path (accel change to use a Real eigenvalue buffer), so that hunk is not applicable. - xc_grad.cpp maps to xc_functional_gradcorr.cpp. Validation: CUDA/ROCm single-precision build; single-precision DeltaSpin/onsite force/stress. Numeric impact: none. * Fix(pw): copy gcar device-to-host in FS_Nonlocal_tools Backport 2e7a4a3 from accel. transfer_gcar() used std::vector::assign to read gcar_in, which is a device pointer on GPU (PW_Basis_K::get_gcar_data<FPTYPE>()), causing a segfault in GPU PW force. Use synchronize_memory_op device-to-host, which also handles the CPU case. LTS adaptation: pass cpu_ctx/ctx to the LTS syncmem API. Validation: GPU PW force; non-collinear/DFT+U/DeltaSpin. Numeric impact: none. * Fix(hsolver): use single-precision MPI datatype in Davidson broadcast Backport 9c761d8 from accel. diag_zhegvx broadcasts subspace eigenvectors/eigenvalues in DiagoDavid and Diago_DavSubspace using hardcoded MPI_DOUBLE_COMPLEX / MPI_DOUBLE, which read and write 16/8 bytes per element for complex<float>/float and corrupt the eigenvectors. Use Parallel_Reduce::MPI_Type<T> and MPI_Type<Real> so float maps to MPI_C_FLOAT_COMPLEX / MPI_FLOAT. LTS adaptation: LTS did not have the MPI_Type trait (its reduce_all uses explicit specializations), so add the trait declarations/definitions to module_base/parallel_reduce.{h,cpp} without changing existing reductions. Validation: single-precision multi-rank Davidson. Numeric impact: fixes eigenvector corruption for single precision. * Fix(hsolver): skip near-zero residual directions in single precision Backport c9f77f8 from accel. The single-precision residual H*c - lambda*S*c suffers catastrophic cancellation and can collapse to numerical noise with a zero or negative norm. DiagoDavid::SchmidtOrth and normalize_op (CPU/CUDA/ROCm) asserted psi_norm > 0 and aborted single-precision non-collinear (nspin=4) runs. Treat such directions as converged/degenerate and skip normalization. LTS adaptation: LTS keeps normalize_op in module_hsolver/kernels/math_kernel_op.{cpp,cu,hip.cu} instead of bpcg_kernel_op; apply the guards there and keep the LTS vector_div API. Validation: single-precision non-collinear Davidson; no abort. Numeric impact: avoids aborting on degenerate directions. * Fix(psi): avoid Psi offset overflow for large basis sets Backport the intent of fc16d95 from accel (the referenced commit is not in the current accel history; accel has since refactored Psi for paging). Change psi_bias and get_psi_bias() to std::size_t and compute the fixed k/b offsets with size_t arithmetic. Cast band/k indices before multiplying by nbasis in get_pointer() and operator(). This prevents int overflow for large nbands*nbasis*nk products. LTS adaptation: keeps the LTS Psi layout (no paged storage). Only the offset arithmetic changes. Validation: large k-point/basis unit tests; existing Psi tests. Numeric impact: none. * Fix(fft): provide host CPU backends for GPU FFT_Bundle Backport the intent of e2843cc from accel (the referenced commit is not in the current accel history; accel has refactored FFT_Bundle). When device != cpu, create separate FFT_CPU backends for the host-memory interface: host_fft_double always, host_fft_float when float FFTs are enabled. setupFFT/clearFFT/clear manage them too. The cpu-like 1D fftxyfor/fftzfor/fftxybac/fftzbac/fftxyr2c/fftxyc2r calls and the rspace/auxr/auxg data accessors now go through these host backends, while get_auxr_3d_data keeps using the device backend. This lets host-side post-processing (Wannier90/Berry phase) run on GPU without passing host buffers to a device FFT. LTS adaptation: LTS uses explicit CUDA/ROCM init and separate host accessors; the fallback is added in initfft() rather than the accel constructor. Validation: GPU Wannier90/Berry phase, precision single; CPU path unchanged (device == cpu uses the original backends). Numeric impact: none. * Fix: backport low-risk general fixes from accel Backport: - f26d766: do not call Parallel_Orbitals::init() on the serial wrapper used for LCAO matrix output; init() grows a communicator each time. Applied to write_dmr.cpp (the only remaining LTS site). - 64d11d0: preserve HR data when wrapping an external data_array in the HContainer copy constructor; only zero fresh allocations. - 5517a58: only set two_fermi when nupdown != 0, so an explicit nupdown=0 behaves like an unset value. - 33cedb4: remove incorrect DEBUG asserts for nullptr hsk/SR in the EKinetic/Overlap constructors (force calculations pass nullptr). - 4ff7cff is not applied: LTS already reports no-plane-wave k points without aborting and has no matching pw_distributeg change. LTS adaptation: LTS names ekinetic_new.cpp/overlap_new.cpp; accel names ekinetic.cpp/overlap.cpp. Validation: LCAO matrix output, nspin=2 out_mat_hs2, nupdown=0, force calculation with DEBUG_INFO. Numeric impact: fixes zero HR output and nupdown=0 semantics only. * Fix(pw): defer float GPU onsite-projector instantiations Follow-up to 6d1350d. The LTS OnsiteProjector/Onsite_Proj_tools code path is not yet float-safe (it still mixes double PW_Basis/Vector3 and Ylm buffers), so explicitly instantiating <float, DEVICE_GPU> breaks the CUDA build. Keep only the double GPU instantiations until the underlying float cleanup is ported; the force/stress and xc float GPU instantiations from 6d1350d remain. Validation: CUDA build succeeds. Numeric impact: none. * Fix(hsolver): make GPU-single DAV reduced solve compile for all T Follow-up to 4b584d8. - Include module_parameter/parameter.h for PARAM.globalv.use_uspp. - Use the complex syncmem aliases for hcc/vcc and add small type-dispatch helpers so the code compiles for T=double (LCAO gamma real solver) as well as T=complex<float/double>. - Use syncmem_h2d/d2h for the complex buffers and the Real aliases for eigenvalues. Validation: CPU and CUDA builds pass. Numeric impact: none. * Docs(backport): record accel sources and numeric differences * Perf(pw): parallelize count_pw_st with OpenMP Backport 5d2582d from accel. Use per-thread local accumulators for npwtot/nstot and the stick bounds, then reduce them with OpenMP reductions (max for lix/liy, min for rix/riy). The Vector3 is constructed inside the stick loop. Numerical results are unchanged. LTS adaptation: applied directly to module_basis/module_pw/pw_distributeg.cpp. Validation: pw_test, basis_pw_serial, basis_pw_k_serial. Numeric impact: none. * Docs(backport): note applied WP6 count_pw_st backport * Test(integrate): refresh LCAO DFT+U nspin=4 SOC reference The nspin=4 Pauli-to-spinor and genelpa fixes change the stress of 260_NO_DJ_PK_PU_SO. The new tensor (1384.6/-143.3/1139.0/-231.7 kbar) agrees with the accel reference (1385.3/-143.4/1139.9/-231.3), while energy and force change by only 0.1 meV and 0.002 eV/A. Update result.ref and record it in backport/NUMERIC_DIFF.md. * Fix(pw): make gcar/kvec_c accessors inline Follow-up to the WP2-2 grad_wfc backport. XCTest_GRADCORR compiles xc_functional_gradcorr.cpp without pw_basis_k.cpp, so the out-of-line get_gcar_data<double>()/get_kvec_c_data<double>() specializations caused an undefined-reference link failure in a LibXC-enabled build. Define the trivial float/double accessors inline in pw_basis_k.h and drop the duplicate definitions from pw_basis_k.cpp. For the double CPU path, fall back to the host gcar/kvec_c storage when the device pointer is null (e.g. in the unit-test mock). gk2 accessors are unchanged. Validation: full clean build with ENABLE_LIBXC=ON and ENABLE_LIBRI=ON; XCTest_GRADCORR and all XC unit tests pass. * Revert "Fix(pw): copy gcar device-to-host in FS_Nonlocal_tools" This reverts 2e7a4a3 in LTS form. In LTS, the PW force path calls transfer_gcar() with the host gcar pointer (&PW_Basis_K::gcar[ik*npwk_max]), even when the calculation runs on GPU. Using synchronize_memory_op device-to-host on that host pointer raises cudaErrorInvalidValue after SCF (102_PW_CG_GPU / 102_PW_BPCG_GPU). Keep the original std::vector::assign. The accel fix targets a different caller that passes get_gcar_data(); LTS does not have that call site. Validation: 102_PW_CG_GPU with 1 and 4 MPI matches the reference and finishes without device errors. * Fix(xc): build precision-matched host gcar/kvec buffers in grad_wfc Follow-up to 8577fc5. The accel version reads the device-side PW_Basis_K::get_gcar_data<Real>() caches, but in LTS those caches are not guaranteed to be populated in the stress path; single-precision GPU SCAN crashed with an illegal memory access. Build small Real-precision host copies from the always-valid PW_Basis_K::gcar/kvec_c vectors and upload them with TensorMap. This keeps the original intent (no double tensor accessed as float) while working for CPU/GPU single and double. Validation: PBE and SCAN with precision single on GPU, compared with CPU double. * Docs(backport): record validation results and LTS adaptations * Docs(backport): correct measured GPU-single stress errors * Docs(backport): add validation report * Docs(backport): clarify non-collinear coverage and limitations * Fix(pw): keep double deeq_nc/qq_so for single-precision force/stress Backport 92dc887 from accel (adapted for LTS GPU single). In single precision, z_deeq_nc and z_qq_so were left null, but the LTS force/stress driver uses Forces<double,Device> / Stress_PW<double,Device>, which reads get_deeq_nc_data<double>() / get_qq_so_data<double>(). A single-precision nspin=4 (non-collinear/SOC) calculation therefore segfaulted in cal_force_nl_op<double> after SCF. - CPU: point z_deeq_nc/z_qq_so at the host deeq_nc/qq_so buffers for both precision modes. - GPU single: allocate device double z_deeq_nc/z_qq_so buffers and keep them synchronized from the host arrays, so the double force/stress kernel has valid device data. This preserves the existing LTS policy (force/stress still evaluated in double) and only makes the single-precision SCF feed that path correctly. Validation: nspin=4 SOC and non-SOC, `precision single`, CPU and CUDA, with `cg`/`dav_subspace`/`dav`; forces and stresses complete. * Docs(backport): record single-precision nspin=4 fix and validation * Docs(backport): add LTS vs accel precision and timing comparison * Docs(backport): analyze precision deltas and run performance smaller cases * Docs(backport): record performance solvers and gint optimization assessment * Chore: remove unnecessary backport documentation * Test(integrate): refresh references for mGGA and nupdown=0 fixes Update integration references affected by: - retaining meta-GGA contributions at zero density gradient - treating explicit nupdown=0 as unset (single Fermi level) Cases: 101_PW_15_f_pseudopots, 101_PW_15_lowz, 107_PW_OK, 122_PW_scan_Si2_nlcc, 207_NO_OK, 211_NO_S2_nupdown0, 218_NO_mixing_tau * Test(integrate): refresh PAW reference for Davidson vcc reset The Davidson refresh now clears stale off-diagonal vcc entries before setting the identity diagonal. This slightly changes the converged PAW energy and force, so update the 101_PW_15_paw reference.
1 parent 88bf525 commit 40dfda0

67 files changed

Lines changed: 6858 additions & 6220 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎source/module_base/parallel_reduce.cpp‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,15 @@
44

55
#include <vector>
66

7+
#ifdef __MPI
8+
const MPI_Datatype Parallel_Reduce::MPI_Type<int>::value = MPI_INT;
9+
const MPI_Datatype Parallel_Reduce::MPI_Type<double>::value = MPI_DOUBLE;
10+
const MPI_Datatype Parallel_Reduce::MPI_Type<float>::value = MPI_FLOAT;
11+
const MPI_Datatype Parallel_Reduce::MPI_Type<std::complex<double>>::value = MPI_DOUBLE_COMPLEX;
12+
const MPI_Datatype Parallel_Reduce::MPI_Type<std::complex<float>>::value = MPI_C_FLOAT_COMPLEX;
13+
const MPI_Datatype Parallel_Reduce::MPI_Type<long long>::value = MPI_LONG_LONG;
14+
#endif
15+
716
template <>
817
void Parallel_Reduce::reduce_all<int>(int& object)
918
{

‎source/module_base/parallel_reduce.h‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,47 @@ using std::complex;
1212

1313
namespace Parallel_Reduce
1414
{
15+
#ifdef __MPI
16+
template <typename T>
17+
struct MPI_Type;
18+
19+
template <>
20+
struct MPI_Type<int>
21+
{
22+
static const MPI_Datatype value;
23+
};
24+
25+
template <>
26+
struct MPI_Type<double>
27+
{
28+
static const MPI_Datatype value;
29+
};
30+
31+
template <>
32+
struct MPI_Type<float>
33+
{
34+
static const MPI_Datatype value;
35+
};
36+
37+
template <>
38+
struct MPI_Type<std::complex<double>>
39+
{
40+
static const MPI_Datatype value;
41+
};
42+
43+
template <>
44+
struct MPI_Type<std::complex<float>>
45+
{
46+
static const MPI_Datatype value;
47+
};
48+
49+
template <>
50+
struct MPI_Type<long long>
51+
{
52+
static const MPI_Datatype value;
53+
};
54+
#endif
55+
1556
/// reduce in all process
1657
template <typename T>
1758
void reduce_all(T& object);

‎source/module_basis/module_pw/module_fft/fft_bundle.cpp‎

Lines changed: 36 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,18 @@ void FFT_Bundle::initfft(int nx_in,
100100
fft_double = make_unique<FFT_CUDA<double>>();
101101
fft_double->initfft(nx_in,ny_in,nz_in);
102102
#endif
103+
// Host-memory interface: always provide a double CPU backend, and a
104+
// float one when float FFTs are enabled. Single precision still needs
105+
// a double host backend for host-only post-processing.
106+
if (float_flag)
107+
{
108+
host_fft_float = make_unique<FFT_CPU<float>>(this->fft_mode);
109+
host_fft_float->initfft(nx_in, ny_in, nz_in, lixy_in, rixy_in, ns_in,
110+
nplane_in, nproc_in, gamma_only_in, xprime_in);
111+
}
112+
host_fft_double = make_unique<FFT_CPU<double>>(this->fft_mode);
113+
host_fft_double->initfft(nx_in, ny_in, nz_in, lixy_in, rixy_in, ns_in,
114+
nplane_in, nproc_in, gamma_only_in, xprime_in);
103115
}
104116

105117
}
@@ -108,74 +120,80 @@ void FFT_Bundle::setupFFT()
108120
{
109121
if (double_flag){fft_double->setupFFT();}
110122
if (float_flag) {fft_float->setupFFT();}
123+
if (host_fft_double != nullptr) { host_fft_double->setupFFT(); }
124+
if (host_fft_float != nullptr) { host_fft_float->setupFFT(); }
111125
}
112126

113127
void FFT_Bundle::clearFFT()
114128
{
115129
if (double_flag){fft_double->cleanFFT();}
116130
if (float_flag) {fft_float->cleanFFT();}
131+
if (host_fft_double != nullptr) { host_fft_double->cleanFFT(); }
132+
if (host_fft_float != nullptr) { host_fft_float->cleanFFT(); }
117133
}
118134
void FFT_Bundle::clear()
119135
{
120136
this->clearFFT();
121137
if (double_flag){fft_double->clear();}
122138
if (float_flag) {fft_float->clear();}
139+
if (host_fft_double != nullptr) { host_fft_double->clear(); }
140+
if (host_fft_float != nullptr) { host_fft_float->clear(); }
123141
}
124142

125143
template <> void
126144
FFT_Bundle::fftxyfor(std::complex<float>* in,
127145
std::complex<float>* out)
128-
const {fft_float->fftxyfor(in,out);}
146+
const {get_host_fft_float()->fftxyfor(in,out);}
129147
template <> void
130148
FFT_Bundle::fftxyfor(std::complex<double>* in,
131149
std::complex<double>* out)
132-
const {fft_double->fftxyfor(in,out);}
150+
const {get_host_fft_double()->fftxyfor(in,out);}
133151

134152

135153
template <> void
136154
FFT_Bundle::fftzfor(std::complex<float>* in,
137155
std::complex<float>* out)
138-
const {fft_float->fftzfor(in,out);}
156+
const {get_host_fft_float()->fftzfor(in,out);}
139157
template <> void
140158
FFT_Bundle::fftzfor(std::complex<double>* in,
141159
std::complex<double>* out)
142-
const {fft_double->fftzfor(in,out);}
160+
const {get_host_fft_double()->fftzfor(in,out);}
143161

144162
template <> void
145163
FFT_Bundle::fftxybac(std::complex<float>* in,
146164
std::complex<float>* out)
147-
const {fft_float->fftxybac(in,out);}
165+
const {get_host_fft_float()->fftxybac(in,out);}
148166
template <> void
149167
FFT_Bundle::fftxybac(std::complex<double>* in,
150168
std::complex<double>* out)
151-
const {fft_double->fftxybac(in,out);}
169+
const {get_host_fft_double()->fftxybac(in,out);}
152170

153171
template <> void
154172
FFT_Bundle::fftzbac(std::complex<float>* in,
155173
std::complex<float>* out)
156-
const {fft_float->fftzbac(in,out);}
174+
const {get_host_fft_float()->fftzbac(in,out);}
157175
template <> void
158176
FFT_Bundle::fftzbac(std::complex<double>* in,
159177
std::complex<double>* out)
160-
const {fft_double->fftzbac(in,out);}
178+
const {get_host_fft_double()->fftzbac(in,out);}
161179

162180
template <> void
163181
FFT_Bundle::fftxyr2c(float* in,
164182
std::complex<float>* out)
165-
const {fft_float->fftxyr2c(in,out);}
183+
const {get_host_fft_float()->fftxyr2c(in,out);}
166184
template <> void
167185
FFT_Bundle::fftxyr2c(double* in,
168186
std::complex<double>* out)
169-
const {fft_double->fftxyr2c(in,out);}
187+
const {get_host_fft_double()->fftxyr2c(in,out);}
170188

171189
template <> void
172190
FFT_Bundle::fftxyc2r(std::complex<float>* in,
173191
float* out)
174-
const {fft_float->fftxyc2r(in,out);}
192+
const {get_host_fft_float()->fftxyc2r(in,out);}
175193
template <> void
176194
FFT_Bundle::fftxyc2r(std::complex<double>* in,
177195
double* out)
178-
const {fft_double->fftxyc2r(in,out);}
196+
const {get_host_fft_double()->fftxyc2r(in,out);}
179197

180198
template <> void
181199
FFT_Bundle::fft3D_forward(const base_device::DEVICE_GPU* ctx,
@@ -201,19 +219,19 @@ const {fft_double->fft3D_backward(in, out);}
201219

202220
// access the real space data
203221
template <> float*
204-
FFT_Bundle::get_rspace_data() const {return fft_float->get_rspace_data();}
222+
FFT_Bundle::get_rspace_data() const {return get_host_fft_float()->get_rspace_data();}
205223
template <> double*
206-
FFT_Bundle::get_rspace_data() const {return fft_double->get_rspace_data();}
224+
FFT_Bundle::get_rspace_data() const {return get_host_fft_double()->get_rspace_data();}
207225

208226
template <> std::complex<float>*
209-
FFT_Bundle::get_auxr_data() const {return fft_float->get_auxr_data();}
227+
FFT_Bundle::get_auxr_data() const {return get_host_fft_float()->get_auxr_data();}
210228
template <> std::complex<double>*
211-
FFT_Bundle::get_auxr_data() const {return fft_double->get_auxr_data();}
229+
FFT_Bundle::get_auxr_data() const {return get_host_fft_double()->get_auxr_data();}
212230

213231
template <> std::complex<float>*
214-
FFT_Bundle::get_auxg_data() const {return fft_float->get_auxg_data();}
232+
FFT_Bundle::get_auxg_data() const {return get_host_fft_float()->get_auxg_data();}
215233
template <> std::complex<double>*
216-
FFT_Bundle::get_auxg_data() const {return fft_double->get_auxg_data();}
234+
FFT_Bundle::get_auxg_data() const {return get_host_fft_double()->get_auxg_data();}
217235

218236
template <> std::complex<float>*
219237
FFT_Bundle::get_auxr_3d_data() const {return fft_float->get_auxr_3d_data();}

‎source/module_basis/module_pw/module_fft/fft_bundle.h‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -206,7 +206,21 @@ class FFT_Bundle
206206
bool double_flag=false;
207207
std::shared_ptr<FFT_BASE<float>> fft_float=nullptr;
208208
std::shared_ptr<FFT_BASE<double>> fft_double=nullptr;
209-
209+
// Extra CPU backends serving the host-memory ("cpu-like") interface
210+
// when the primary backend is a device FFT. They keep host
211+
// post-processing (e.g. Wannier90/Berry phase) working on GPU runs.
212+
std::shared_ptr<FFT_BASE<float>> host_fft_float=nullptr;
213+
std::shared_ptr<FFT_BASE<double>> host_fft_double=nullptr;
214+
215+
FFT_BASE<float>* get_host_fft_float() const
216+
{
217+
return (this->device == "cpu") ? this->fft_float.get() : this->host_fft_float.get();
218+
}
219+
FFT_BASE<double>* get_host_fft_double() const
220+
{
221+
return (this->device == "cpu") ? this->fft_double.get() : this->host_fft_double.get();
222+
}
223+
210224
std::string device = "cpu";
211225
std::string precision = "double";
212226
};

‎source/module_basis/module_pw/pw_basis_k.cpp‎

Lines changed: 0 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -412,24 +412,6 @@ std::vector<int> PW_Basis_K::get_ig2iz(const int ik) const
412412
return ig_to_iz;
413413
}
414414

415-
template <>
416-
float * PW_Basis_K::get_kvec_c_data() const {
417-
return this->s_kvec_c;
418-
}
419-
template <>
420-
double * PW_Basis_K::get_kvec_c_data() const {
421-
return this->d_kvec_c;
422-
}
423-
424-
template <>
425-
float * PW_Basis_K::get_gcar_data() const {
426-
return this->s_gcar;
427-
}
428-
template <>
429-
double * PW_Basis_K::get_gcar_data() const {
430-
return this->d_gcar;
431-
}
432-
433415
template <>
434416
float * PW_Basis_K::get_gk2_data() const {
435417
return this->s_gk2;

‎source/module_basis/module_pw/pw_basis_k.h‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -183,6 +183,23 @@ class PW_Basis_K : public PW_Basis
183183

184184
};
185185

186+
// Trivial accessors are kept inline so that unit tests and other small
187+
// translation units that call grad_wfc do not need to link pw_basis_k.cpp.
188+
template <>
189+
inline float* PW_Basis_K::get_gcar_data() const { return this->s_gcar; }
190+
template <>
191+
inline double* PW_Basis_K::get_gcar_data() const
192+
{
193+
return this->d_gcar != nullptr ? this->d_gcar : reinterpret_cast<double*>(&this->gcar[0][0]);
194+
}
195+
template <>
196+
inline float* PW_Basis_K::get_kvec_c_data() const { return this->s_kvec_c; }
197+
template <>
198+
inline double* PW_Basis_K::get_kvec_c_data() const
199+
{
200+
return this->d_kvec_c != nullptr ? this->d_kvec_c : reinterpret_cast<double*>(&this->kvec_c[0][0]);
201+
}
202+
186203
}
187204
#endif //PlaneWave_K class
188205

‎source/module_basis/module_pw/pw_distributeg.cpp‎

Lines changed: 41 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,6 @@ void PW_Basis::count_pw_st(
4848
{
4949
ModuleBase::GlobalFunc::ZEROS(st_length2D, this->fftnxy);
5050
ModuleBase::GlobalFunc::ZEROS(st_bottom2D, this->fftnxy);
51-
ModuleBase::Vector3<double> f;
5251

5352
// determine the scaning area along x-direct, if gamma-only && xprime, only positive axis is used.
5453
int ix_end = int(this->nx / 2) + 1;
@@ -86,10 +85,18 @@ void PW_Basis::count_pw_st(
8685
}
8786
}
8887

89-
this->liy = this->riy = 0;
90-
this->lix = this->rix = 0;
91-
this->npwtot = 0;
92-
this->nstot = 0;
88+
int npwtot_local = 0;
89+
int nstot_local = 0;
90+
int lix_local = 0, rix_local = 0;
91+
int liy_local = 0, riy_local = 0;
92+
93+
#ifdef _OPENMP
94+
#pragma omp parallel for collapse(1) \
95+
shared(st_length2D, st_bottom2D) \
96+
reduction(+: npwtot_local, nstot_local) \
97+
reduction(min: rix_local, riy_local) \
98+
reduction(max: lix_local, liy_local)
99+
#endif
93100
for (int ix = ix_start; ix <= ix_end; ++ix)
94101
{
95102
for (int iy = iy_start; iy <= iy_end; ++iy)
@@ -101,37 +108,53 @@ void PW_Basis::count_pw_st(
101108
// so that its index in st_length and st_bottom is 9 * 10 + 2 = 92.
102109
int x = ix;
103110
int y = iy;
104-
if (x < 0) x += this->nx;
105-
if (y < 0) y += this->ny;
111+
if (x < 0) { x += this->nx; }
112+
if (y < 0) { y += this->ny; }
106113
int index = x * this->fftny + y;
107114

108115
int length = 0; // number of planewave on stick (x, y).
116+
117+
ModuleBase::Vector3<double> f;
118+
f.x = ix;
119+
f.y = iy;
120+
109121
for (int iz = iz_start; iz <= iz_end; ++iz)
110122
{
111-
f.x = ix;
112-
f.y = iy;
113123
f.z = iz;
114124
double modulus = f * (this->GGT * f);
115125
if (modulus <= this->ggecut || this->full_pw)
116126
{
117-
if (length == 0) st_bottom2D[index] = iz; // length == 0 means this point is the bottom of stick (x, y).
118-
++this->npwtot;
127+
if (length == 0)
128+
{
129+
st_bottom2D[index] = iz; // length == 0 means this point is the bottom of stick (x, y).
130+
}
131+
++npwtot_local;
119132
++length;
120-
if(iy < this->riy) this->riy = iy;
121-
if(iy > this->liy) this->liy = iy;
122-
if(ix < this->rix) this->rix = ix;
123-
if(ix > this->lix) this->lix = ix;
133+
if(ix > lix_local) { lix_local = ix; }
134+
if(ix < rix_local) { rix_local = ix; }
135+
if(iy > liy_local) { liy_local = iy; }
136+
if(iy < riy_local) { riy_local = iy; }
124137
}
125138
}
126139
if (length > 0)
127140
{
128141
st_length2D[index] = length;
129-
++this->nstot;
142+
++nstot_local;
130143
}
131144
}
132145
}
133-
riy += this->ny;
134-
rix += this->nx;
146+
147+
if (npwtot_local == 0) // no planewave
148+
{
149+
lix_local = rix_local = liy_local = riy_local = 0;
150+
}
151+
152+
this->npwtot = npwtot_local;
153+
this->nstot = nstot_local;
154+
this->lix = lix_local;
155+
this->rix = rix_local + this->nx;
156+
this->liy = liy_local;
157+
this->riy = riy_local + this->ny;
135158
return;
136159
}
137160

0 commit comments

Comments
 (0)