diff --git a/docs/advanced/install.md b/docs/advanced/install.md index 1d786c03b20..360e7c59fe0 100644 --- a/docs/advanced/install.md +++ b/docs/advanced/install.md @@ -28,9 +28,10 @@ of HSE), build Libxc 7.1.0 or later with `-DENABLE_CUDA=ON`. The ABACUS option `ENABLE_LIBXC_CUDA` defaults to `OFF`. Configure ABACUS with `-DUSE_CUDA=ON -DENABLE_LIBXC=ON -DENABLE_LIBXC_CUDA=ON -DLibxc_DIR=/lib/cmake/Libxc`, then set `device gpu` and `device_xc gpu` in INPUT. `device_xc` defaults to `cpu`, which -also works with a CUDA-enabled Libxc. Built-in functionals, meta-GGA, response -kernels and separate force/stress evaluations continue to use the CPU. This -option does not select the exact-exchange backend. +also works with a CUDA-enabled Libxc. Built-in functionals (except noncollinear +PBE potential evaluation when the density PW basis runs on CUDA), meta-GGA, +response kernels and separate force/stress evaluations continue to use the CPU. +This option does not select the exact-exchange backend. For HSE forces, Libxc 7.1.0 exceeded a host/device agreement tolerance of `1e-6 eV/Å` on a displaced Si64 cell. The WPBEH exchange term loses precision diff --git a/source/CMakeLists.txt b/source/CMakeLists.txt index 54cac366975..c8a5d6b9dbf 100644 --- a/source/CMakeLists.txt +++ b/source/CMakeLists.txt @@ -693,6 +693,7 @@ if(USE_CUDA) source_hsolver/kernels/cuda/bpcg_kernel_op.cu source_hsolver/module_linalg/kernels/cuda/linear_op.cu source_estate/kernels/cuda/elecstate_op.cu + source_estate/kernels/cuda/hartree_op.cu source_base/module_device/cuda/memory_op.cu source_pw/module_pwdft/kernels/cuda/force_op.cu source_pw/module_pwdft/kernels/cuda/stress_op.cu @@ -703,6 +704,7 @@ if(USE_CUDA) source_base/kernels/cuda/math_kernel_op.cu source_base/kernels/cuda/math_kernel_op_vec.cu source_hamilt/module_xc/kernels/cuda/xc_functional_op.cu + source_hamilt/module_xc/kernels/cuda/ncgga_sf_op.cu source_pw/module_ofdft/kernels/cuda/kedf_wt_gpu.cu source_pw/module_pwdft/kernels/cuda/cal_density_real_op.cu source_pw/module_pwdft/kernels/cuda/mul_potential_op.cu diff --git a/source/source_base/module_fft/fft_bundle.cpp b/source/source_base/module_fft/fft_bundle.cpp index 925ce187dae..30189b115b0 100644 --- a/source/source_base/module_fft/fft_bundle.cpp +++ b/source/source_base/module_fft/fft_bundle.cpp @@ -103,9 +103,11 @@ void FFT_Bundle::initfft(int nx_in, fft_double->initfft(nx_in, ny_in, nz_in); #elif defined(__CUDA) fft_float = make_unique>(); - fft_float->initfft(nx_in, ny_in, nz_in); + fft_float->initfft(nx_in, ny_in, nz_in, lixy_in, rixy_in, ns_in, nplane_in, nproc_in, + gamma_only_in, xprime_in); fft_double = make_unique>(); - fft_double->initfft(nx_in, ny_in, nz_in); + fft_double->initfft(nx_in, ny_in, nz_in, lixy_in, rixy_in, ns_in, nplane_in, nproc_in, + gamma_only_in, xprime_in); #endif }else{ ModuleBase::WARNING_QUIT("FFT_Bundle", "Please set the device to cpu or gpu or dsp"); @@ -337,11 +339,12 @@ std::complex* FFT_Bundle::get_auxg_data() const template <> std::complex* FFT_Bundle::get_auxr_3d_data() const { - return fft_float->get_auxr_3d_data(); + return fft_float == nullptr ? nullptr : fft_float->get_auxr_3d_data(); } template <> std::complex* FFT_Bundle::get_auxr_3d_data() const { - return fft_double->get_auxr_3d_data(); + return fft_double == nullptr ? nullptr : fft_double->get_auxr_3d_data(); } + } // namespace ModuleBase diff --git a/source/source_base/module_fft/fft_cuda.cpp b/source/source_base/module_fft/fft_cuda.cpp index e33fd203118..d98723565bf 100644 --- a/source/source_base/module_fft/fft_cuda.cpp +++ b/source/source_base/module_fft/fft_cuda.cpp @@ -2,8 +2,21 @@ #include "source_base/module_device/memory_op.h" #include "source_base/module_device/device_check.h" +#include +#include + namespace ModuleBase { +namespace +{ +// Grids smaller than this are dominated by the extra kernel launches of the +// pruned transform, so the regular cuFFT path is cheaper. +constexpr int pruned_fft_min_grid_points = 1 << 20; +// Keep one quarter of the x planes inactive before using the pruned plan. +constexpr int pruned_fft_active_numerator = 3; +constexpr int pruned_fft_active_denominator = 4; +} // namespace + template void FFT_CUDA::initfft(int nx_in, int ny_in, int nz_in) { @@ -11,18 +24,89 @@ void FFT_CUDA::initfft(int nx_in, int ny_in, int nz_in) this->ny = ny_in; this->nz = nz_in; } + +template +void FFT_CUDA::initfft(int nx_in, + int ny_in, + int nz_in, + int lixy_in, + int rixy_in, + int /*ns_in*/, + int /*nplane_in*/, + int nproc_in, + bool gamma_only_in, + bool xprime_in) +{ + this->nx = nx_in; + this->ny = ny_in; + this->nz = nz_in; + this->lixy_index = lixy_in; + this->rixy_index = rixy_in; + this->nproc = nproc_in; + this->gamma_only = gamma_only_in; + this->xprime = xprime_in; +} + +template +bool FFT_CUDA::use_pruned_gpu_fft() const +{ + return false; +} + +template <> +bool FFT_CUDA::use_pruned_gpu_fft() const +{ + // Small grids are dominated by the extra kernel launches. Sparse large + // grids avoid the y-z transforms in the unoccupied middle x slabs. + return this->xprime && !this->gamma_only && this->nproc == 1 + && this->nx * this->ny * this->nz >= pruned_fft_min_grid_points + && pruned_fft_active_denominator * (this->lixy_index + 1 + this->nx - this->rixy_index) + <= pruned_fft_active_numerator * this->nx; +} + +template +void FFT_CUDA::init_gpu_pruned_plan() +{ +} + +template <> +void FFT_CUDA::init_gpu_pruned_plan() +{ + int x_size = this->nx; + int yz_size[2] = {this->ny, this->nz}; + const int plane = this->ny * this->nz; + CHECK_CUFFT(cufftPlanMany(&this->z_x_handle, 1, &x_size, &x_size, plane, 1, + &x_size, plane, 1, CUFFT_Z2Z, plane)); + CHECK_CUFFT(cufftPlanMany(&this->z_yz_left_handle, 2, yz_size, yz_size, 1, plane, + yz_size, 1, plane, CUFFT_Z2Z, this->lixy_index + 1)); + if (this->rixy_index < this->nx) + { + CHECK_CUFFT(cufftPlanMany(&this->z_yz_right_handle, 2, yz_size, yz_size, 1, plane, + yz_size, 1, plane, CUFFT_Z2Z, this->nx - this->rixy_index)); + } +} + template <> void FFT_CUDA::setupFFT() { - cufftPlan3d(&c_handle, this->nx, this->ny, this->nz, CUFFT_C2C); + CHECK_CUFFT(cufftPlan3d(&this->c_handle, this->nx, this->ny, this->nz, CUFFT_C2C)); resmem_cd_op()(this->c_auxr_3d, this->nx * this->ny * this->nz); } + template <> void FFT_CUDA::setupFFT() { - cufftPlan3d(&z_handle, this->nx, this->ny, this->nz, CUFFT_Z2Z); + if (this->use_pruned_gpu_fft()) + { + this->init_gpu_pruned_plan(); + } + else + { + CHECK_CUFFT(cufftPlan3d(&this->z_handle, this->nx, this->ny, this->nz, CUFFT_Z2Z)); + } resmem_zd_op()(this->z_auxr_3d, this->nx * this->ny * this->nz); } + template <> void FFT_CUDA::cleanFFT() { @@ -32,6 +116,7 @@ void FFT_CUDA::cleanFFT() c_handle = {}; } } + template <> void FFT_CUDA::cleanFFT() { @@ -40,7 +125,16 @@ void FFT_CUDA::cleanFFT() cufftDestroy(z_handle); z_handle = {}; } + for (cufftHandle* handle : {&z_x_handle, &z_yz_left_handle, &z_yz_right_handle}) + { + if (*handle) + { + cufftDestroy(*handle); + *handle = {}; + } + } } + template <> void FFT_CUDA::clear() { @@ -51,6 +145,7 @@ void FFT_CUDA::clear() c_auxr_3d = nullptr; } } + template <> void FFT_CUDA::clear() { @@ -70,14 +165,29 @@ void FFT_CUDA::fft3D_forward(std::complex* in, std::complex reinterpret_cast(out), CUFFT_FORWARD)); } + template <> void FFT_CUDA::fft3D_forward(std::complex* in, std::complex* out) const { + if (this->z_x_handle) + { + cufftDoubleComplex* input = reinterpret_cast(in); + cufftDoubleComplex* output = reinterpret_cast(out); + CHECK_CUFFT(cufftExecZ2Z(this->z_x_handle, input, output, CUFFT_FORWARD)); + CHECK_CUFFT(cufftExecZ2Z(this->z_yz_left_handle, output, output, CUFFT_FORWARD)); + if (this->z_yz_right_handle) + { + cufftDoubleComplex* right = output + this->rixy_index * this->ny * this->nz; + CHECK_CUFFT(cufftExecZ2Z(this->z_yz_right_handle, right, right, CUFFT_FORWARD)); + } + return; + } CHECK_CUFFT(cufftExecZ2Z(this->z_handle, reinterpret_cast(in), reinterpret_cast(out), CUFFT_FORWARD)); } + template <> void FFT_CUDA::fft3D_backward(std::complex* in, std::complex* out) const { @@ -90,16 +200,31 @@ void FFT_CUDA::fft3D_backward(std::complex* in, std::complex void FFT_CUDA::fft3D_backward(std::complex* in, std::complex* out) const { + if (this->z_x_handle) + { + cufftDoubleComplex* input = reinterpret_cast(in); + cufftDoubleComplex* output = reinterpret_cast(out); + CHECK_CUFFT(cufftExecZ2Z(this->z_yz_left_handle, input, input, CUFFT_INVERSE)); + if (this->z_yz_right_handle) + { + cufftDoubleComplex* right = input + this->rixy_index * this->ny * this->nz; + CHECK_CUFFT(cufftExecZ2Z(this->z_yz_right_handle, right, right, CUFFT_INVERSE)); + } + CHECK_CUFFT(cufftExecZ2Z(this->z_x_handle, input, output, CUFFT_INVERSE)); + return; + } CHECK_CUFFT(cufftExecZ2Z(this->z_handle, reinterpret_cast(in), reinterpret_cast(out), CUFFT_INVERSE)); } + template <> std::complex* FFT_CUDA::get_auxr_3d_data() const { return this->c_auxr_3d; } + template <> std::complex* FFT_CUDA::get_auxr_3d_data() const { diff --git a/source/source_base/module_fft/fft_cuda.h b/source/source_base/module_fft/fft_cuda.h index 0b7a7aacf6e..5b933dc6ddd 100644 --- a/source/source_base/module_fft/fft_cuda.h +++ b/source/source_base/module_fft/fft_cuda.h @@ -29,6 +29,17 @@ class FFT_CUDA : public FFT_BASE void initfft(int nx_in, int ny_in, int nz_in) override; + + void initfft(int nx_in, + int ny_in, + int nz_in, + int lixy_in, + int rixy_in, + int ns_in, + int nplane_in, + int nproc_in, + bool gamma_only_in, + bool xprime_in) override; /** * @brief Get the real space data @@ -57,10 +68,22 @@ class FFT_CUDA : public FFT_BASE private: cufftHandle c_handle = {}; cufftHandle z_handle = {}; + cufftHandle z_x_handle = {}; + cufftHandle z_yz_left_handle = {}; + cufftHandle z_yz_right_handle = {}; std::complex* c_auxr_3d = nullptr; // fft space std::complex* z_auxr_3d = nullptr; // fft space + int lixy_index = 0; + int rixy_index = 0; + int nproc = 1; + bool gamma_only = false; + bool xprime = true; + + bool use_pruned_gpu_fft() const; + void init_gpu_pruned_plan(); + }; } // namespace ModuleBase diff --git a/source/source_basis/module_pw/kernels/cuda/pw_op.cu b/source/source_basis/module_pw/kernels/cuda/pw_op.cu index 58488e1a7df..55b3cb6b8a2 100644 --- a/source/source_basis/module_pw/kernels/cuda/pw_op.cu +++ b/source/source_basis/module_pw/kernels/cuda/pw_op.cu @@ -8,6 +8,74 @@ namespace ModulePW { #define THREADS_PER_BLOCK 256 +template +__global__ void pack_real_grid(int size, const Real* input, thrust::complex* grid) +{ + const int index = blockIdx.x * blockDim.x + threadIdx.x; + if (index < size) + { + grid[index] = thrust::complex(input[index], 0); + } +} + +template +__global__ void extract_real_grid(int size, bool add, Real factor, const thrust::complex* grid, Real* output) +{ + const int index = blockIdx.x * blockDim.x + threadIdx.x; + if (index < size) + { + output[index] = add ? output[index] + factor * grid[index].real() : grid[index].real(); + } +} + +template +void pack_real_grid_gpu(int size, const Real* input, std::complex* grid) +{ + pack_real_grid<<<(size + THREADS_PER_BLOCK - 1) / THREADS_PER_BLOCK, THREADS_PER_BLOCK>>>( + size, input, reinterpret_cast*>(grid)); + CHECK_CUDA_SYNC(); +} + +template +void extract_real_grid_gpu(int size, bool add, Real factor, const std::complex* grid, Real* output) +{ + extract_real_grid<<<(size + THREADS_PER_BLOCK - 1) / THREADS_PER_BLOCK, THREADS_PER_BLOCK>>>( + size, add, factor, reinterpret_cast*>(grid), output); + CHECK_CUDA_SYNC(); +} + +template void pack_real_grid_gpu(int, const float*, std::complex*); +template void pack_real_grid_gpu(int, const double*, std::complex*); +template void extract_real_grid_gpu(int, bool, float, const std::complex*, float*); +template void extract_real_grid_gpu(int, bool, double, const std::complex*, double*); + +template +__global__ void gather_fft_coefficients(int size, bool add, Real scale, const int* index, + const thrust::complex* grid, thrust::complex* output) +{ + const int ig = blockIdx.x * blockDim.x + threadIdx.x; + if (ig < size) + { + const thrust::complex value = scale * grid[index[ig]]; + output[ig] = add ? output[ig] + value : value; + } +} + +template +void gather_fft_coefficients_gpu(int size, bool add, Real scale, const int* index, + const std::complex* grid, std::complex* output) +{ + gather_fft_coefficients<<<(size + THREADS_PER_BLOCK - 1) / THREADS_PER_BLOCK, THREADS_PER_BLOCK>>>( + size, add, scale, index, reinterpret_cast*>(grid), + reinterpret_cast*>(output)); + CHECK_CUDA_SYNC(); +} + +template void gather_fft_coefficients_gpu(int, bool, float, const int*, const std::complex*, + std::complex*); +template void gather_fft_coefficients_gpu(int, bool, double, const int*, const std::complex*, + std::complex*); + template __global__ void set_3d_fft_box( const int npwk, diff --git a/source/source_basis/module_pw/kernels/pw_op.h b/source/source_basis/module_pw/kernels/pw_op.h index ed7c10f1ed6..da256ddd4b3 100644 --- a/source/source_basis/module_pw/kernels/pw_op.h +++ b/source/source_basis/module_pw/kernels/pw_op.h @@ -6,6 +6,17 @@ #include namespace ModulePW { +#if defined(__CUDA) +template +void pack_real_grid_gpu(int size, const Real* input, std::complex* grid); + +template +void extract_real_grid_gpu(int size, bool add, Real factor, const std::complex* grid, Real* output); + +template +void gather_fft_coefficients_gpu(int size, bool add, Real scale, const int* index, + const std::complex* grid, std::complex* output); +#endif template struct set_3d_fft_box_op { /// @brief Set the 3D fft box for fft transfrom between the recip and real space. diff --git a/source/source_basis/module_pw/pw_basis.cpp b/source/source_basis/module_pw/pw_basis.cpp index a079a3bdd4c..17dc2e8e5ea 100644 --- a/source/source_basis/module_pw/pw_basis.cpp +++ b/source/source_basis/module_pw/pw_basis.cpp @@ -46,6 +46,7 @@ PW_Basis:: ~PW_Basis() delmem_int_op()(this->ig2ixyz_gpu); } #endif + this->fft3d_bundle.clear(); } /// @@ -70,6 +71,26 @@ void PW_Basis::setuptransform() this->fft_bundle.initfft(this->nx,this->ny,this->nz,this->liy,this->riy,this->nst,this->nplane,this->poolnproc,this->gamma_only, this->xprime); } this->fft_bundle.setupFFT(); + + this->fft3d_bundle.clear(); +#if defined(__CUDA) + if (this->device == "gpu" && this->fft_bundle.get_device() != "gpu" && this->poolnproc == 1 + && !this->gamma_only) + { + this->fft3d_bundle.setfft("gpu", this->precision); + if (this->xprime) + { + this->fft3d_bundle.initfft(this->nx, this->ny, this->nz, this->lix, this->rix, this->nst, + this->nplane, this->poolnproc, this->gamma_only, this->xprime); + } + else + { + this->fft3d_bundle.initfft(this->nx, this->ny, this->nz, this->liy, this->riy, this->nst, + this->nplane, this->poolnproc, this->gamma_only, this->xprime); + } + this->fft3d_bundle.setupFFT(); + } +#endif ModuleBase::timer::end(this->classname, "setuptransform"); } diff --git a/source/source_basis/module_pw/pw_basis.h b/source/source_basis/module_pw/pw_basis.h index d476e59a542..b07ea012a93 100644 --- a/source/source_basis/module_pw/pw_basis.h +++ b/source/source_basis/module_pw/pw_basis.h @@ -253,6 +253,8 @@ class PW_Basis // Thus std::complex[nmaxgr] is able to contain either reciprocal or real data // FFT ft; ModuleBase::FFT_Bundle fft_bundle; + /// Dedicated device FFT bundle for complete-grid density transforms on GPU. + ModuleBase::FFT_Bundle fft3d_bundle; //The position of pointer in and out can be equal(in-place transform) or different(out-of-place transform). template diff --git a/source/source_basis/module_pw/pw_transform.cpp b/source/source_basis/module_pw/pw_transform.cpp index 82f20ca3cf5..58965b35f10 100644 --- a/source/source_basis/module_pw/pw_transform.cpp +++ b/source/source_basis/module_pw/pw_transform.cpp @@ -8,6 +8,7 @@ #include #include #include +#include namespace ModulePW { @@ -19,6 +20,165 @@ inline int block_end(const int begin, const int size) { return std::min(begin + pw_transform_cache_block, size); } + +#if defined(__CUDA) +template +void upload_fft_input(const int size, + const std::complex* input, + std::complex* grid, + std::complex* /*scratch*/) +{ + base_device::memory::synchronize_memory_op, + base_device::DEVICE_GPU, + base_device::DEVICE_CPU>()(grid, input, size); +} + +template +void upload_fft_input(const int size, + const Real* input, + std::complex* grid, + std::complex* scratch) +{ + // A complex allocation also stores the contiguous real input before its FFT coefficients are gathered. + Real* real_input = reinterpret_cast(scratch); + base_device::memory::synchronize_memory_op()( + real_input, input, size); + pack_real_grid_gpu(size, real_input, grid); +} + +template +Real* prepare_inverse_output(const int size, + const bool add, + const Real factor, + std::complex* grid, + Real* output) +{ + extract_real_grid_gpu(size, add, factor, grid, output); + return output; +} + +template +std::complex* prepare_inverse_output(const int size, + const bool add, + const Real factor, + std::complex* grid, + std::complex* output) +{ + if (!add) + { + return grid; + } + set_recip_to_real_output_op()(size, true, factor, grid, output); + return output; +} + +template +void real2recip_host_to_device(const PW_Basis& basis, + const Input* in, + std::complex* out, + const bool add, + const Real factor) +{ + using Complex = std::complex; + int scratch_size = basis.npw; + if (std::is_same::value) + { + scratch_size = std::max(scratch_size, (basis.nrxx + 1) / 2); + } + Complex* scratch = nullptr; + base_device::memory::resize_memory_op()(scratch, scratch_size); + std::complex* grid = basis.fft3d_bundle.template get_auxr_3d_data(); + upload_fft_input(basis.nrxx, in, grid, scratch); + basis.fft3d_bundle.fft3D_forward(grid, grid); + if (add) + { + base_device::memory::synchronize_memory_op()( + scratch, out, basis.npw); + } + // Evaluating the reciprocal scale before multiplication preserves the host transform's rounding order. + const Real scale = (add ? factor : Real(1)) / Real(basis.nxyz); + gather_fft_coefficients_gpu(basis.npw, add, scale, basis.ig2ixyz_gpu, grid, scratch); + base_device::memory::synchronize_memory_op()( + out, scratch, basis.npw); + base_device::memory::delete_memory_op()(scratch); +} + +template +void recip2real_device_to_host(const PW_Basis& basis, + const std::complex* in, + Output* out, + const bool add, + const Real factor) +{ + using Complex = std::complex; + int scratch_size = basis.npw; + if (std::is_same::value) + { + scratch_size = std::max(scratch_size, (basis.nrxx + 1) / 2); + } + else if (add) + { + scratch_size = std::max(scratch_size, basis.nrxx); + } + Complex* scratch = nullptr; + base_device::memory::resize_memory_op()(scratch, scratch_size); + base_device::memory::synchronize_memory_op()( + scratch, in, basis.npw); + std::complex* grid = basis.fft3d_bundle.template get_auxr_3d_data(); + base_device::memory::set_memory_op()(grid, 0, basis.nxyz); + set_3d_fft_box_op()(basis.npw, basis.ig2ixyz_gpu, scratch, grid); + basis.fft3d_bundle.fft3D_backward(grid, grid); + Output* result = reinterpret_cast(scratch); + if (add) + { + base_device::memory::synchronize_memory_op()( + result, out, basis.nrxx); + } + result = prepare_inverse_output(basis.nrxx, add, factor, grid, result); + base_device::memory::synchronize_memory_op()( + out, result, basis.nrxx); + base_device::memory::delete_memory_op()(scratch); +} + +inline bool use_host_gpu_density_transform(const PW_Basis& basis) +{ + return basis.get_device() == "gpu" && basis.poolnproc == 1 && !basis.gamma_only + && basis.ig2ixyz_gpu != nullptr + && basis.fft3d_bundle.template get_auxr_3d_data() != nullptr; +} + +template +void maybe_real2recip_host_to_device(const PW_Basis& basis, + const Input* in, + std::complex* out, + const bool add, + const Real factor, + bool& handled) +{ + handled = false; + if (use_host_gpu_density_transform(basis)) + { + real2recip_host_to_device(basis, in, out, add, factor); + handled = true; + } +} + +template +void maybe_recip2real_device_to_host(const PW_Basis& basis, + const std::complex* in, + Output* out, + const bool add, + const Real factor, + bool& handled) +{ + handled = false; + if (use_host_gpu_density_transform(basis)) + { + recip2real_device_to_host(basis, in, out, add, factor); + handled = true; + } +} +#endif } // namespace // const base_device::DEVICE_CPU* PW_Basis::get_default_device_ctx() { @@ -58,6 +218,14 @@ void PW_Basis::real2recip(const std::complex* in, const FPTYPE factor) const { ModuleBase::timer::start(this->classname, "real2recip"); +#if defined(__CUDA) + if (use_host_gpu_density_transform(*this)) + { + real2recip_host_to_device(*this, in, out, add, factor); + ModuleBase::timer::end(this->classname, "real2recip"); + return; + } +#endif assert(this->gamma_only == false); const int nrxx_ = this->nrxx; @@ -150,6 +318,14 @@ template void PW_Basis::real2recip(const FPTYPE* in, std::complex* out, const bool add, const FPTYPE factor) const { ModuleBase::timer::start(this->classname, "real2recip"); +#if defined(__CUDA) + if (use_host_gpu_density_transform(*this)) + { + real2recip_host_to_device(*this, in, out, add, factor); + ModuleBase::timer::end(this->classname, "real2recip"); + return; + } +#endif const int nrxx_ = this->nrxx; const int npw_ = this->npw; const int nxyz_ = this->nxyz; @@ -276,6 +452,14 @@ void PW_Basis::recip2real(const std::complex* in, const FPTYPE factor) const { ModuleBase::timer::start(this->classname, "recip2real"); +#if defined(__CUDA) + if (use_host_gpu_density_transform(*this)) + { + recip2real_device_to_host(*this, in, out, add, factor); + ModuleBase::timer::end(this->classname, "recip2real"); + return; + } +#endif assert(this->gamma_only == false); const int nst_ = this->nst; const int nz_ = this->nz; @@ -381,6 +565,14 @@ template void PW_Basis::recip2real(const std::complex* in, FPTYPE* out, const bool add, const FPTYPE factor) const { ModuleBase::timer::start(this->classname, "recip2real"); +#if defined(__CUDA) + if (use_host_gpu_density_transform(*this)) + { + recip2real_device_to_host(*this, in, out, add, factor); + ModuleBase::timer::end(this->classname, "recip2real"); + return; + } +#endif const int nst_ = this->nst; const int nz_ = this->nz; const int npw_ = this->npw; diff --git a/source/source_basis/module_pw/pw_transform_k.cpp b/source/source_basis/module_pw/pw_transform_k.cpp index 26d230a6499..42619e67086 100644 --- a/source/source_basis/module_pw/pw_transform_k.cpp +++ b/source/source_basis/module_pw/pw_transform_k.cpp @@ -3,12 +3,14 @@ #include "pw_basis_k.h" #include "pw_gatherscatter.h" +#include #include #include namespace ModulePW { + /** * @brief transform real space to reciprocal space * @details real wave function f(k,r): @@ -339,12 +341,9 @@ void PW_Basis_K::real_to_recip(const base_device::DEVICE_GPU* ctx, assert(this->gamma_only == false); assert(this->poolnproc == 1); - base_device::memory::synchronize_memory_op, base_device::DEVICE_GPU, base_device::DEVICE_GPU>()( - this->fft_bundle.get_auxr_3d_data(), - in, - this->nrxx); - - this->fft_bundle.fft3D_forward(this->fft_bundle.get_auxr_3d_data(), this->fft_bundle.get_auxr_3d_data()); + // Out-of-place complex transforms preserve the input grid. + this->fft_bundle.fft3D_forward(const_cast*>(in), + this->fft_bundle.get_auxr_3d_data()); const int startig = ik * this->npwk_max; const int npw_k = this->npwk[ik]; @@ -369,13 +368,9 @@ void PW_Basis_K::real_to_recip(const base_device::DEVICE_GPU* ctx, assert(this->gamma_only == false); assert(this->poolnproc == 1); - base_device::memory::synchronize_memory_op, - base_device::DEVICE_GPU, - base_device::DEVICE_GPU>()(this->fft_bundle.get_auxr_3d_data(), - in, - this->nrxx); - - this->fft_bundle.fft3D_forward(this->fft_bundle.get_auxr_3d_data(), this->fft_bundle.get_auxr_3d_data()); + // Out-of-place complex transforms preserve the input grid. + this->fft_bundle.fft3D_forward(const_cast*>(in), + this->fft_bundle.get_auxr_3d_data()); const int startig = ik * this->npwk_max; const int npw_k = this->npwk[ik]; @@ -413,13 +408,17 @@ void PW_Basis_K::recip_to_real(const base_device::DEVICE_GPU* ctx, this->ig2ixyz_k + startig, in, this->fft_bundle.get_auxr_3d_data()); - this->fft_bundle.fft3D_backward(this->fft_bundle.get_auxr_3d_data(), this->fft_bundle.get_auxr_3d_data()); - - set_recip_to_real_output_op()(this->nrxx, - add, - factor, - this->fft_bundle.get_auxr_3d_data(), - out); + if (add) + { + std::complex* grid = this->fft_bundle.get_auxr_3d_data(); + this->fft_bundle.fft3D_backward(grid, grid); + set_recip_to_real_output_op()( + this->nrxx, true, factor, grid, out); + } + else + { + this->fft_bundle.fft3D_backward(this->fft_bundle.get_auxr_3d_data(), out); + } ModuleBase::timer::end(this->classname, "recip_to_real gpu"); } @@ -447,13 +446,17 @@ void PW_Basis_K::recip_to_real(const base_device::DEVICE_GPU* ctx, this->ig2ixyz_k + startig, in, this->fft_bundle.get_auxr_3d_data()); - this->fft_bundle.fft3D_backward(this->fft_bundle.get_auxr_3d_data(), this->fft_bundle.get_auxr_3d_data()); - - set_recip_to_real_output_op()(this->nrxx, - add, - factor, - this->fft_bundle.get_auxr_3d_data(), - out); + if (add) + { + std::complex* grid = this->fft_bundle.get_auxr_3d_data(); + this->fft_bundle.fft3D_backward(grid, grid); + set_recip_to_real_output_op()( + this->nrxx, true, factor, grid, out); + } + else + { + this->fft_bundle.fft3D_backward(this->fft_bundle.get_auxr_3d_data(), out); + } ModuleBase::timer::end(this->classname, "recip_to_real gpu"); } @@ -469,13 +472,9 @@ void PW_Basis_K::real2recip_gpu(const std::complex* in, assert(this->gamma_only == false); assert(this->poolnproc == 1); - base_device::memory::synchronize_memory_op, - base_device::DEVICE_GPU, - base_device::DEVICE_GPU>()(this->fft_bundle.get_auxr_3d_data(), - in, - this->nrxx); - - this->fft_bundle.fft3D_forward(this->fft_bundle.get_auxr_3d_data(), this->fft_bundle.get_auxr_3d_data()); + // Out-of-place complex transforms preserve the input grid. + this->fft_bundle.fft3D_forward(const_cast*>(in), + this->fft_bundle.get_auxr_3d_data()); const int startig = ik * this->npwk_max; const int npw_k = this->npwk[ik]; @@ -511,13 +510,17 @@ void PW_Basis_K::recip2real_gpu(const std::complex* in, this->ig2ixyz_k + startig, in, this->fft_bundle.get_auxr_3d_data()); - this->fft_bundle.fft3D_backward(this->fft_bundle.get_auxr_3d_data(), this->fft_bundle.get_auxr_3d_data()); - - set_recip_to_real_output_op()(this->nrxx, - add, - factor, - this->fft_bundle.get_auxr_3d_data(), - out); + if (add) + { + std::complex* grid = this->fft_bundle.get_auxr_3d_data(); + this->fft_bundle.fft3D_backward(grid, grid); + set_recip_to_real_output_op()( + this->nrxx, true, factor, grid, out); + } + else + { + this->fft_bundle.fft3D_backward(this->fft_bundle.get_auxr_3d_data(), out); + } ModuleBase::timer::end(this->classname, "recip_to_real gpu"); } diff --git a/source/source_estate/elecstate_pw.cpp b/source/source_estate/elecstate_pw.cpp index 8c32e29c433..821ba9d16dd 100644 --- a/source/source_estate/elecstate_pw.cpp +++ b/source/source_estate/elecstate_pw.cpp @@ -17,6 +17,29 @@ namespace elecstate { +namespace +{ +template +void accumulate_k_density(Real** source, + double** target, + const int nspin, + const int nrxx, + const bool first, + std::vector& buffer) +{ + for (int is = 0; is < nspin; ++is) + { + base_device::memory::cast_memory_op()( + buffer.data(), source[is], nrxx); + for (int ir = 0; ir < nrxx; ++ir) + { + target[is][ir] = first ? buffer[ir] : target[is][ir] + buffer[ir]; + } + base_device::memory::set_memory_op()(source[is], 0, nrxx); + } +} +} // namespace + template ElecStatePW::ElecStatePW(ModulePW::PW_Basis_K* wfc_basis_in, Charge* chr_in, @@ -104,8 +127,10 @@ void ElecStatePW::init_rho_data() this->kin_r = reinterpret_cast(this->charge->kin_r); } } - resmem_complex_op()(this->wfcr, this->basis->nmaxgr, "ElecSPW::wfcr"); - resmem_complex_op()(this->wfcr_another_spin, this->basis->nrxx, "ElecSPW::wfcr_a"); + int grid_size = this->basis->nmaxgr; + int spin_grid_size = this->basis->nrxx; + resmem_complex_op()(this->wfcr, grid_size, "ElecSPW::wfcr"); + resmem_complex_op()(this->wfcr_another_spin, spin_grid_size, "ElecSPW::wfcr_a"); this->init_rho = true; } @@ -117,7 +142,7 @@ void ElecStatePW::psiToRho(const psi::Psi& psi) this->init_rho_data(); - for (int is = 0; is < PARAM.inp.nspin; is++) + for (int is = 0; is < this->charge->nspin; is++) { // denghui replaced at 20221110 // ModuleBase::GlobalFunc::ZEROS(this->rho[is], this->charge->nrxx); @@ -138,16 +163,6 @@ void ElecStatePW::psiToRho(const psi::Psi& psi) const bool sum_k_in_double = std::is_same::value && std::is_same::value; std::vector buffer(sum_k_in_double ? this->charge->nrxx : 0); - const auto accumulate_k = [&](Real** source, double** target, const bool first) - { - for (int is = 0; is < this->charge->nspin; ++is) - { - castmem_var_d2h_op()(buffer.data(), source[is], this->charge->nrxx); - for (int ir = 0; ir < this->charge->nrxx; ++ir) - target[is][ir] = first ? buffer[ir] : target[is][ir] + buffer[ir]; - setmem_var_op()(source[is], 0, this->charge->nrxx); - } - }; for (int ik = 0; ik < psi.get_nk(); ++ik) { @@ -155,16 +170,20 @@ void ElecStatePW::psiToRho(const psi::Psi& psi) this->updateRhoK(psi); if (sum_k_in_double) { - accumulate_k(this->rho, this->charge->rho, ik == 0); + accumulate_k_density( + this->rho, this->charge->rho, this->charge->nspin, this->charge->nrxx, ik == 0, buffer); if (XC_Functional::get_ked_flag()) - accumulate_k(this->kin_r, this->charge->kin_r, ik == 0); + { + accumulate_k_density( + this->kin_r, this->charge->kin_r, this->charge->nspin, this->charge->nrxx, ik == 0, buffer); + } } } if ((!sum_k_in_double || psi.get_nk() == 0) && (PARAM.inp.device == "gpu" || PARAM.inp.precision == "single")) { - for (int ii = 0; ii < PARAM.inp.nspin; ii++) + for (int ii = 0; ii < this->charge->nspin; ii++) { castmem_var_d2h_op()(this->charge->rho[ii], this->rho[ii], this->charge->nrxx); if (XC_Functional::get_ked_flag()) @@ -226,50 +245,44 @@ void ElecStatePW::rhoBandK(const psi::Psi& psi) int npwx = npw / 2; for (int ibnd = 0; ibnd < nbands; ibnd++) { - /// - /// only occupied band should be calculated. - /// be care of when smearing_sigma is large, wg would less than 0 - /// + const Real w1 = static_cast(this->wg(ik, ibnd) / ucell->omega); + /// Negative smearing weights contribute; only exact zeros are omitted. + if (w1 == 0.0) + { + continue; + } this->basis->recip_to_real(this->ctx, &psi(ibnd, 0), this->wfcr, ik); this->basis->recip_to_real(this->ctx, &psi(ibnd, npwx), this->wfcr_another_spin, ik); - const Real w1 = static_cast(this->wg(ik, ibnd) / ucell->omega); - - if (w1 != 0.0) - { - // replaced by denghui at 20221110 - elecstate_pw_op()(this->ctx, - PARAM.globalv.domag, - PARAM.globalv.domag_z, - this->basis->nrxx, - this->charge->nrxx, - w1, - this->rho, - this->wfcr, - this->wfcr_another_spin); - } + // replaced by denghui at 20221110 + elecstate_pw_op()(this->ctx, + PARAM.globalv.domag, + PARAM.globalv.domag_z, + this->basis->nrxx, + this->charge->nrxx, + w1, + this->rho, + this->wfcr, + this->wfcr_another_spin); } } else { for (int ibnd = 0; ibnd < nbands; ibnd++) { - /// - /// only occupied band should be calculated. - /// - - this->basis->recip_to_real(this->ctx, &psi(ibnd, 0), this->wfcr, ik); - const Real w1 = static_cast(this->wg(ik, ibnd) / ucell->omega); - - if (w1 != 0.0) + if (w1 == 0.0) { - // replaced by denghui at 20221110 - elecstate_pw_op()(this->ctx, current_spin, this->basis->nrxx, this->charge->nrxx, w1, this->rho, this->wfcr); + continue; } + this->basis->recip_to_real(this->ctx, &psi(ibnd, 0), this->wfcr, ik); + + // replaced by denghui at 20221110 + elecstate_pw_op()(this->ctx, current_spin, this->basis->nrxx, this->charge->nrxx, w1, this->rho, this->wfcr); + // kinetic energy density if (XC_Functional::get_ked_flag()) { diff --git a/source/source_estate/kernels/cuda/hartree_op.cu b/source/source_estate/kernels/cuda/hartree_op.cu new file mode 100644 index 00000000000..74671a9c973 --- /dev/null +++ b/source/source_estate/kernels/cuda/hartree_op.cu @@ -0,0 +1,94 @@ +#include "source_estate/kernels/hartree_op.h" + +#include +#include +#include + +namespace elecstate +{ +namespace +{ + +constexpr int block_size = 256; +// Avoid dividing by a vanishing reciprocal-space |G|^2. +constexpr double reciprocal_g_threshold = 1e-8; + +__global__ void pack_density(int size, int channels, const double* density, thrust::complex* grid) +{ + const int ir = blockIdx.x * blockDim.x + threadIdx.x; + if (ir < size) + { + double value = 0; + for (int spin = 0; spin < channels; ++spin) + { + value += density[spin * size + ir]; + } + grid[ir] = thrust::complex(value, 0); + } +} + +__global__ void poisson_coefficients(int npw, const int* index, const double* gg, double scale, + double numerator, double tpiba2, const thrust::complex* grid, + thrust::complex* potential, double* energy) +{ + const int ig = blockIdx.x * blockDim.x + threadIdx.x; + double contribution = 0; + if (ig < npw) + { + potential[ig] = thrust::complex(0, 0); + if (gg[ig] >= reciprocal_g_threshold) + { + const thrust::complex density = scale * grid[index[ig]]; + const double factor = numerator / (tpiba2 * gg[ig]); + potential[ig] = factor * density; + contribution = (thrust::conj(density) * density).real() * factor; + } + } + __shared__ double partial[block_size]; + partial[threadIdx.x] = contribution; + __syncthreads(); + for (int stride = blockDim.x / 2; stride > 0; stride /= 2) + { + if (threadIdx.x < stride) + { + partial[threadIdx.x] += partial[threadIdx.x + stride]; + } + __syncthreads(); + } + if (threadIdx.x == 0) + { + energy[blockIdx.x] = partial[0]; + } +} + +void check_launch() +{ + CHECK_CUDA_SYNC(); +} + +} // namespace + +int hartree_reduction_size_gpu(int npw) +{ + return (npw + block_size - 1) / block_size; +} + +void hartree_pack_density_gpu(int size, int channels, const double* density, std::complex* grid) +{ + pack_density<<<(size + block_size - 1) / block_size, block_size>>>( + size, channels, density, reinterpret_cast*>(grid)); + check_launch(); +} + +void hartree_coefficients_gpu(int npw, const int* index, const double* gg, double scale, + double coulomb_numerator, double tpiba2, const std::complex* grid, + std::complex* potential, double* energy) +{ + poisson_coefficients<<>>( + npw, index, gg, scale, coulomb_numerator, tpiba2, + reinterpret_cast*>(grid), + reinterpret_cast*>(potential), energy); + check_launch(); +} + +} // namespace elecstate diff --git a/source/source_estate/kernels/hartree_op.h b/source/source_estate/kernels/hartree_op.h new file mode 100644 index 00000000000..52979461637 --- /dev/null +++ b/source/source_estate/kernels/hartree_op.h @@ -0,0 +1,22 @@ +#ifndef MODULE_ELECSTATE_HARTREE_OP_H +#define MODULE_ELECSTATE_HARTREE_OP_H + +#include + +namespace elecstate +{ + +int hartree_reduction_size_gpu(int npw); + +// Density channels are contiguous real-space fields; their sum is transformed. +void hartree_pack_density_gpu(int size, int channels, const double* density, std::complex* grid); + +// The reciprocal scale is evaluated by the host to match PW_Basis normalization. +// Each block writes one partial sum of |rho(G)|^2 times the Coulomb kernel. +void hartree_coefficients_gpu(int npw, const int* index, const double* gg, double scale, + double coulomb_numerator, double tpiba2, const std::complex* grid, + std::complex* potential, double* energy); + +} // namespace elecstate + +#endif diff --git a/source/source_estate/module_charge/chg_atomic_inner.cpp b/source/source_estate/module_charge/chg_atomic_inner.cpp index ef77dc301e1..6bfee1850e9 100644 --- a/source/source_estate/module_charge/chg_atomic_inner.cpp +++ b/source/source_estate/module_charge/chg_atomic_inner.cpp @@ -348,7 +348,23 @@ void normalize_and_check(double** rho_in, std::vector ne(spin_number_need); for (int is = 0; is < spin_number_need; is++) { - rhopw->recip2real(&rho_g3d(is, 0), rho_in[is]); + if (rhopw->gamma_only) + { + rhopw->recip2real(&rho_g3d(is, 0), rho_in[is]); + } + else + { + // The starting-charge diagnostics retain the full complex transform. + std::complex* density_grid = rhopw->fft_bundle.template get_auxr_data(); + rhopw->recip2real(&rho_g3d(is, 0), density_grid); +#ifdef _OPENMP +#pragma omp parallel for schedule(static, 1024) +#endif + for (int ir = 0; ir < rhopw->nrxx; ++ir) + { + rho_in[is][ir] = density_grid[ir].real(); + } + } for (int ir = 0; ir < rhopw->nrxx; ++ir) { diff --git a/source/source_estate/module_charge/chg_tools.cpp b/source/source_estate/module_charge/chg_tools.cpp index faef6a49149..d6d32e3895c 100644 --- a/source/source_estate/module_charge/chg_tools.cpp +++ b/source/source_estate/module_charge/chg_tools.cpp @@ -335,7 +335,23 @@ void set_rho_core(const UnitCell& ucell, rhog_core[ig] = vg[ig]; } - rhopw.recip2real(vg.data(), rho_core); + if (rhopw.gamma_only) + { + rhopw.recip2real(vg.data(), rho_core); + } + else + { + // The charge diagnostics require both components of the inverse transform. + std::complex* core_grid = rhopw.fft_bundle.template get_auxr_data(); + rhopw.recip2real(vg.data(), core_grid); +#ifdef _OPENMP +#pragma omp parallel for schedule(static, 1024) +#endif + for (int ir = 0; ir < rhopw.nrxx; ++ir) + { + rho_core[ir] = core_grid[ir].real(); + } + } // test on the charge and computation of the core energy double rhoima = 0.0; diff --git a/source/source_estate/module_pot/h_hartree_pw.cpp b/source/source_estate/module_pot/h_hartree_pw.cpp index 0232c2d67e6..4355b7cbdba 100644 --- a/source/source_estate/module_pot/h_hartree_pw.cpp +++ b/source/source_estate/module_pot/h_hartree_pw.cpp @@ -5,11 +5,96 @@ #include "source_base/timer.h" #include "source_base/parallel_reduce.h" +#include +#if defined(__CUDA) +#include "source_basis/module_pw/kernels/pw_op.h" +#include "source_estate/kernels/hartree_op.h" +#endif + namespace elecstate { double H_Hartree_pw::hartree_energy = 0.0; +#if defined(__CUDA) +namespace +{ + +bool hartree_gpu_eligible(const ModulePW::PW_Basis& basis) +{ + return basis.get_device() == "gpu" && basis.poolnproc == 1 && !basis.gamma_only + && basis.ig2ixyz_gpu != nullptr + && basis.fft3d_bundle.template get_auxr_3d_data() != nullptr; +} + +ModuleBase::matrix hartree_gpu(const UnitCell& cell, const ModulePW::PW_Basis& basis, + int nspin, const double* const* rho, double& energy) +{ + using Complex = std::complex; + const int channels = nspin == 2 ? 2 : 1; + const int blocks = hartree_reduction_size_gpu(basis.npw); + std::vector density(channels * basis.nrxx); + for (int spin = 0; spin < channels; ++spin) + { + std::copy(rho[spin], rho[spin] + basis.nrxx, density.data() + spin * basis.nrxx); + } + std::vector host_gg(basis.npw); + std::copy(basis.gg, basis.gg + basis.npw, host_gg.begin()); + + double* d_density = nullptr; + double* d_gg = nullptr; + Complex* d_coefficients = nullptr; + double* d_sums = nullptr; + base_device::memory::resize_memory_op()(d_density, channels * basis.nrxx); + base_device::memory::resize_memory_op()(d_gg, basis.npw); + base_device::memory::resize_memory_op()(d_coefficients, basis.npw); + base_device::memory::resize_memory_op()(d_sums, blocks); + base_device::memory::synchronize_memory_op()( + d_density, density.data(), channels * basis.nrxx); + base_device::memory::synchronize_memory_op()( + d_gg, host_gg.data(), basis.npw); + + std::complex* grid = basis.fft3d_bundle.template get_auxr_3d_data(); + hartree_pack_density_gpu(basis.nrxx, channels, d_density, grid); + basis.fft3d_bundle.fft3D_forward(grid, grid); + hartree_coefficients_gpu(basis.npw, basis.ig2ixyz_gpu, d_gg, 1.0 / basis.nxyz, + ModuleBase::e2 * ModuleBase::FOUR_PI, cell.tpiba2, grid, + d_coefficients, d_sums); + base_device::memory::set_memory_op()(grid, 0, basis.nxyz); + ModulePW::set_3d_fft_box_op()( + basis.npw, basis.ig2ixyz_gpu, d_coefficients, grid); + basis.fft3d_bundle.fft3D_backward(grid, grid); + ModulePW::extract_real_grid_gpu(basis.nrxx, false, 1.0, grid, d_density); + ModuleBase::matrix potential(nspin, basis.nrxx); + base_device::memory::synchronize_memory_op()( + potential.c, d_density, basis.nrxx); + if (nspin != 4) + { + for (int spin = 1; spin < nspin; ++spin) + { + std::copy(potential.c, potential.c + basis.nrxx, potential.c + spin * basis.nrxx); + } + } + std::vector host_sums(blocks); + base_device::memory::synchronize_memory_op()( + host_sums.data(), d_sums, blocks); + energy = 0; + for (int block = 0; block < blocks; ++block) + { + energy += host_sums[block]; + } + energy *= 0.5 * cell.omega; + + base_device::memory::delete_memory_op()(d_density); + base_device::memory::delete_memory_op()(d_gg); + base_device::memory::delete_memory_op()(d_coefficients); + base_device::memory::delete_memory_op()(d_sums); + return potential; +} + +} // namespace +#endif + //-------------------------------------------------------------------- // Transform charge density to hartree potential. //-------------------------------------------------------------------- @@ -21,6 +106,15 @@ ModuleBase::matrix H_Hartree_pw::v_hartree(const UnitCell &cell, ModuleBase::TITLE("H_Hartree_pw", "v_hartree"); ModuleBase::timer::start("H_Hartree_pw", "v_hartree"); +#if defined(__CUDA) + if (hartree_gpu_eligible(*rho_basis)) + { + ModuleBase::matrix potential = hartree_gpu(cell, *rho_basis, nspin, rho, H_Hartree_pw::hartree_energy); + ModuleBase::timer::end("H_Hartree_pw", "v_hartree"); + return potential; + } +#endif + // Hartree potential VH(r) from n(r) std::vector> Porter(rho_basis->nmaxgr); const int nspin0 = (nspin == 2) ? 2 : 1; diff --git a/source/source_estate/module_pot/potential_new.cpp b/source/source_estate/module_pot/potential_new.cpp index 09606d4ecb0..94494116c2d 100644 --- a/source/source_estate/module_pot/potential_new.cpp +++ b/source/source_estate/module_pot/potential_new.cpp @@ -136,17 +136,18 @@ void Potential::allocate() this->vofk_smooth.create(nspin, nrxx_smooth); ModuleBase::Memory::record("Pot::vofk_smooth", sizeof(double) * nspin * nrxx_smooth); } + const int vofk_size = this->vofk_smooth.nr * this->vofk_smooth.nc; if (use_gpu_) { if (PARAM.globalv.has_float_data) { resmem_sd_op()(s_veff_smooth, nspin * nrxx_smooth); - resmem_sd_op()(s_vofk_smooth, nspin * nrxx_smooth); + resmem_sd_op()(s_vofk_smooth, vofk_size); } if (PARAM.globalv.has_double_data) { resmem_dd_op()(d_veff_smooth, nspin * nrxx_smooth); - resmem_dd_op()(d_vofk_smooth, nspin * nrxx_smooth); + resmem_dd_op()(d_vofk_smooth, vofk_size); } } else @@ -154,7 +155,7 @@ void Potential::allocate() if (PARAM.globalv.has_float_data) { resmem_sh_op()(s_veff_smooth, nspin * nrxx_smooth, "POT::sveff_smooth"); - resmem_sh_op()(s_vofk_smooth, nspin * nrxx_smooth, "POT::svofk_smooth"); + resmem_sh_op()(s_vofk_smooth, vofk_size, "POT::svofk_smooth"); } if (PARAM.globalv.has_double_data) { diff --git a/source/source_hamilt/module_xc/CMakeLists.txt b/source/source_hamilt/module_xc/CMakeLists.txt index 2e852f0458a..649972a20b6 100644 --- a/source/source_hamilt/module_xc/CMakeLists.txt +++ b/source/source_hamilt/module_xc/CMakeLists.txt @@ -34,6 +34,7 @@ if(BUILD_TESTING) if(ENABLE_LIBXC) add_subdirectory(test) add_subdirectory(kernels/test) + add_subdirectory(unittests) endif() endif() endif() diff --git a/source/source_hamilt/module_xc/kernels/cuda/ncgga_sf_op.cu b/source/source_hamilt/module_xc/kernels/cuda/ncgga_sf_op.cu new file mode 100644 index 00000000000..39b73523ef1 --- /dev/null +++ b/source/source_hamilt/module_xc/kernels/cuda/ncgga_sf_op.cu @@ -0,0 +1,298 @@ +#include "source_hamilt/module_xc/ncgga_sf_gpu.h" + +#include "source_base/module_device/device_check.h" +#include "source_base/module_device/memory_op.h" +#include "source_base/vector3.h" +#include "source_hamilt/module_xc/xc_math.h" + +#include +#include + +#include +#include + +namespace ModuleXC +{ +namespace +{ +constexpr int threads = 256; +constexpr double vanishing = 1e-10; +constexpr double epsr = 1e-6; +constexpr double small = 1e-10; + +__device__ double jacobian_value(const NcggaSpinMapPoint& point, int spin, int channel) +{ + if (channel == 0) + { + if (point.saturated) + { + return spin == 0 ? point.density_sign : 0.0; + } + return 0.5 * point.density_sign; + } + if (point.saturated) + { + return 0.0; + } + const double spin_sign = spin == 0 ? 0.5 : -0.5; + return spin_sign * point.radial.gradient[channel - 1]; +} + +__device__ double dot3(const double* a, const double* b) +{ + return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; +} + +__device__ void local_pbe(double rho, double zeta, double& exc, double& vup, double& vdw) +{ + double ex = 0.0; + double vxup = 0.0; + double vxdw = 0.0; + xc_math::slater_spin(rho, zeta, ex, vxup, vxdw); + exc = ex; + vup = vxup; + vdw = vxdw; + const double pi34 = 0.62035049089940; + const double rs = pi34 / cbrt(rho); + double ec = 0.0; + double vcup = 0.0; + double vcdw = 0.0; + xc_math::pw_spin(rs, zeta, ec, vcup, vcdw); + exc += ec; + vup += vcup; + vdw += vcdw; +} + +__device__ void gcx_pbe(double rhoup, double rhodw, double grhoup2, double grhodw2, + double& sx, double& v1xup, double& v1xdw, double& v2xup, double& v2xdw) +{ + double sxup = 0.0; + double sxdw = 0.0; + if (rhoup + rhodw <= small) + { + sx = 0.0; + v1xup = v1xdw = v2xup = v2xdw = 0.0; + return; + } + if (rhoup > small && sqrt(fabs(grhoup2)) > small) + { + xc_math::pbex(2.0 * rhoup, 4.0 * grhoup2, 0, sxup, v1xup, v2xup); + } + if (rhodw > small && sqrt(fabs(grhodw2)) > small) + { + xc_math::pbex(2.0 * rhodw, 4.0 * grhodw2, 0, sxdw, v1xdw, v2xdw); + } + sx = 0.5 * (sxup + sxdw); + v2xup = 2.0 * v2xup; + v2xdw = 2.0 * v2xdw; +} + +__device__ void gcc_pbe(double rho, double& zeta, double grho, double& sc, + double& v1cup, double& v1cdw, double& v2c) +{ + sc = 0.0; + v1cup = 0.0; + v1cdw = 0.0; + v2c = 0.0; + if (fabs(zeta) - 1.0 > small || rho <= small || sqrt(fabs(grho)) <= small) + { + return; + } + const double clipped = fmin(fabs(zeta), 1.0 - epsr); + zeta = zeta > 0.0 ? clipped : -clipped; + xc_math::pbec_spin(rho, zeta, grho, 1, sc, v1cup, v1cdw, v2c); +} + +__global__ void ncgga_local_kernel(int nrxx, + const NcggaSpinMapPoint* spin_map, + const double* rhotmp1, + const double* rhotmp2, + const double* gdr1, + const double* gdr2, + double e2, + bool is_gga, + double* v, + double* h1, + double* h2, + double* partial) +{ + const int ir = blockIdx.x * blockDim.x + threadIdx.x; + double energy = 0.0; + if (ir < nrxx) + { + const NcggaSpinMapPoint point = spin_map[ir]; + for (int channel = 0; channel < 4; ++channel) + { + v[channel * nrxx + ir] = 0.0; + } + for (int component = 0; component < 3; ++component) + { + h1[3 * ir + component] = 0.0; + h2[3 * ir + component] = 0.0; + } + const double arho = point.absolute_density; + if (arho > vanishing) + { + double zeta = point.clipped_magnitude / arho; + zeta = zeta > 1.0 ? 1.0 : (zeta < -1.0 ? -1.0 : zeta); + double exc = 0.0; + double vup = 0.0; + double vdw = 0.0; + local_pbe(arho, zeta, exc, vup, vdw); + for (int channel = 0; channel < 4; ++channel) + { + v[channel * nrxx + ir] = e2 * (jacobian_value(point, 0, channel) * vup + + jacobian_value(point, 1, channel) * vdw); + } + energy += e2 * exc * arho; + } + if (is_gga) + { + const double* g1 = gdr1 + 3 * ir; + const double* g2 = gdr2 + 3 * ir; + const double grho2a = dot3(g1, g1); + const double grho2b = dot3(g2, g2); + const double rh = rhotmp1[ir] + rhotmp2[ir]; + double sx = 0.0; + double v1xup = 0.0; + double v1xdw = 0.0; + double v2xup = 0.0; + double v2xdw = 0.0; + gcx_pbe(rhotmp1[ir], rhotmp2[ir], grho2a, grho2b, sx, v1xup, v1xdw, v2xup, v2xdw); + double sc = 0.0; + double v1cup = 0.0; + double v1cdw = 0.0; + double v2c = 0.0; + if (rh > epsr) + { + const double zeta_input = fabs((rhotmp1[ir] - rhotmp2[ir]) / rh); + double zeta = zeta_input; + const double sum[3] = {g1[0] + g2[0], g1[1] + g2[1], g1[2] + g2[2]}; + const double grh2 = dot3(sum, sum); + gcc_pbe(rh, zeta, grh2, sc, v1cup, v1cdw, v2c); + if (zeta_input > 1.0 - epsr) + { + const double fixed = 0.5 * ((1.0 + zeta) * v1cup + (1.0 - zeta) * v1cdw); + v1cup = fixed; + v1cdw = fixed; + } + } + const double vup = e2 * (v1xup + v1cup); + const double vdw = e2 * (v1xdw + v1cdw); + for (int component = 0; component < 3; ++component) + { + h1[3 * ir + component] = e2 * ((v2xup + v2c) * g1[component] + v2c * g2[component]); + h2[3 * ir + component] = e2 * ((v2xdw + v2c) * g2[component] + v2c * g1[component]); + } + for (int channel = 0; channel < 4; ++channel) + { + v[channel * nrxx + ir] += jacobian_value(point, 0, channel) * vup + + jacobian_value(point, 1, channel) * vdw; + } + energy += e2 * (sx + sc); + } + } + __shared__ double shared[threads]; + shared[threadIdx.x] = energy; + __syncthreads(); + for (int stride = threads / 2; stride > 0; stride /= 2) + { + if (threadIdx.x < stride) + { + shared[threadIdx.x] += shared[threadIdx.x + stride]; + } + __syncthreads(); + } + if (threadIdx.x == 0) + { + partial[blockIdx.x] = shared[0]; + } +} + +bool allocate(void** pointer, size_t bytes) +{ + const cudaError_t alloc_status = cudaMalloc(pointer, bytes); + if (alloc_status == cudaErrorMemoryAllocation) + { + cudaGetLastError(); + *pointer = nullptr; + return false; + } + CHECK_CUDA(alloc_status); + return true; +} +} // namespace + +bool ncgga_sf_local_gpu(int nrxx, + const NcggaSpinMapPoint* spin_map, + const double* spin_density_up, + const double* spin_density_down, + const ModuleBase::Vector3* gradient_up, + const ModuleBase::Vector3* gradient_down, + double e2, + bool is_gga, + ModuleBase::matrix& potential, + std::vector>& flux_up, + std::vector>& flux_down, + double& etxc) +{ + if (nrxx <= 0) + { + return false; + } + const int blocks = (nrxx + threads - 1) / threads; + const size_t points = static_cast(nrxx); + const size_t vectors = 3 * points; + void* d_map = nullptr; + void* d_rho1 = nullptr; + void* d_rho2 = nullptr; + void* d_g1 = nullptr; + void* d_g2 = nullptr; + void* d_v = nullptr; + void* d_h1 = nullptr; + void* d_h2 = nullptr; + void* d_partial = nullptr; + const size_t map_bytes = points * sizeof(NcggaSpinMapPoint); + const size_t vec_bytes = vectors * sizeof(double); + const size_t v_bytes = 4 * points * sizeof(double); + const size_t partial_bytes = blocks * sizeof(double); + if (!allocate(&d_map, map_bytes) || !allocate(&d_rho1, points * sizeof(double)) + || !allocate(&d_rho2, points * sizeof(double)) || !allocate(&d_g1, vec_bytes) + || !allocate(&d_g2, vec_bytes) || !allocate(&d_v, v_bytes) + || !allocate(&d_h1, vec_bytes) || !allocate(&d_h2, vec_bytes) + || !allocate(&d_partial, partial_bytes)) + { + cudaFree(d_map); cudaFree(d_rho1); cudaFree(d_rho2); cudaFree(d_g1); + cudaFree(d_g2); cudaFree(d_v); cudaFree(d_h1); cudaFree(d_h2); cudaFree(d_partial); + return false; + } + CHECK_CUDA(cudaMemcpy(d_map, spin_map, map_bytes, cudaMemcpyHostToDevice)); + CHECK_CUDA(cudaMemcpy(d_rho1, spin_density_up, points * sizeof(double), cudaMemcpyHostToDevice)); + CHECK_CUDA(cudaMemcpy(d_rho2, spin_density_down, points * sizeof(double), cudaMemcpyHostToDevice)); + CHECK_CUDA(cudaMemcpy(d_g1, gradient_up, vec_bytes, cudaMemcpyHostToDevice)); + CHECK_CUDA(cudaMemcpy(d_g2, gradient_down, vec_bytes, cudaMemcpyHostToDevice)); + ncgga_local_kernel<<>>( + nrxx, static_cast(d_map), + static_cast(d_rho1), static_cast(d_rho2), + static_cast(d_g1), static_cast(d_g2), e2, is_gga, + static_cast(d_v), static_cast(d_h1), + static_cast(d_h2), static_cast(d_partial)); + CHECK_CUDA(cudaGetLastError()); + CHECK_CUDA(cudaDeviceSynchronize()); + CHECK_CUDA(cudaMemcpy(potential.c, d_v, v_bytes, cudaMemcpyDeviceToHost)); + CHECK_CUDA(cudaMemcpy(flux_up.data(), d_h1, vec_bytes, cudaMemcpyDeviceToHost)); + CHECK_CUDA(cudaMemcpy(flux_down.data(), d_h2, vec_bytes, cudaMemcpyDeviceToHost)); + std::vector partial(blocks); + CHECK_CUDA(cudaMemcpy(partial.data(), d_partial, partial_bytes, cudaMemcpyDeviceToHost)); + double sum = 0.0; + for (double value : partial) + { + sum += value; + } + etxc += sum; + cudaFree(d_map); cudaFree(d_rho1); cudaFree(d_rho2); cudaFree(d_g1); + cudaFree(d_g2); cudaFree(d_v); cudaFree(d_h1); cudaFree(d_h2); cudaFree(d_partial); + return true; +} + +} // namespace ModuleXC diff --git a/source/source_hamilt/module_xc/kernels/cuda/xc_functional_op.cu b/source/source_hamilt/module_xc/kernels/cuda/xc_functional_op.cu index 16c998797d3..5a3454b9bed 100644 --- a/source/source_hamilt/module_xc/kernels/cuda/xc_functional_op.cu +++ b/source/source_hamilt/module_xc/kernels/cuda/xc_functional_op.cu @@ -2,12 +2,100 @@ #include #include #include +#include "source_base/module_device/device_check.h" #define THREADS_PER_BLOCK 256 namespace hamilt { +__global__ void density_gradient_kernel(int npw, int component, const int* index, + const double* gcar, const thrust::complex* rhog, + thrust::complex* grid) +{ + const int ig = blockIdx.x * blockDim.x + threadIdx.x; + if (ig < npw) + { + grid[index[ig]] = thrust::complex(0.0, 1.0) * rhog[ig] * gcar[3 * ig + component]; + } +} + +__global__ void extract_density_real_kernel(int size, int stride, int offset, double scale, + const thrust::complex* grid, double* result) +{ + const int ir = blockIdx.x * blockDim.x + threadIdx.x; + if (ir < size) + { + result[stride * ir + offset] = grid[ir].real() * scale; + } +} + +__global__ void pack_density_component_kernel(int size, int component, const double* vectors, + thrust::complex* grid) +{ + const int ir = blockIdx.x * blockDim.x + threadIdx.x; + if (ir < size) + { + grid[ir] = thrust::complex(vectors[3 * ir + component], 0.0); + } +} + +__global__ void accumulate_density_divergence_kernel(int npw, int nxyz, int component, + const int* index, const double* gcar, + const thrust::complex* grid, + thrust::complex* reciprocal) +{ + const int ig = blockIdx.x * blockDim.x + threadIdx.x; + if (ig < npw) + { + const thrust::complex coefficient = grid[index[ig]] / double(nxyz); + const thrust::complex term = thrust::complex(0.0, 1.0) * coefficient * gcar[3 * ig + component]; + if (component == 0) + { + reciprocal[ig] = term; + } + else + { + reciprocal[ig] += term; + } + } +} + +void xc_gradient_coefficients_gpu(int npw, int component, const int* grid_index, + const double* gcar, const std::complex* rhog, + std::complex* grid) +{ + density_gradient_kernel<<<(npw + THREADS_PER_BLOCK - 1) / THREADS_PER_BLOCK, THREADS_PER_BLOCK>>>( + npw, component, grid_index, gcar, reinterpret_cast*>(rhog), + reinterpret_cast*>(grid)); + CHECK_CUDA_SYNC(); +} + +void xc_extract_real_gpu(int size, int stride, int offset, double scale, + const std::complex* grid, double* result) +{ + extract_density_real_kernel<<<(size + THREADS_PER_BLOCK - 1) / THREADS_PER_BLOCK, THREADS_PER_BLOCK>>>( + size, stride, offset, scale, reinterpret_cast*>(grid), result); + CHECK_CUDA_SYNC(); +} + +void xc_pack_component_gpu(int size, int component, const double* vectors, std::complex* grid) +{ + pack_density_component_kernel<<<(size + THREADS_PER_BLOCK - 1) / THREADS_PER_BLOCK, THREADS_PER_BLOCK>>>( + size, component, vectors, reinterpret_cast*>(grid)); + CHECK_CUDA_SYNC(); +} + +void xc_accumulate_divergence_gpu(int npw, int nxyz, int component, + const int* grid_index, const double* gcar, + const std::complex* grid, std::complex* reciprocal) +{ + accumulate_density_divergence_kernel<<<(npw + THREADS_PER_BLOCK - 1) / THREADS_PER_BLOCK, THREADS_PER_BLOCK>>>( + npw, nxyz, component, grid_index, gcar, reinterpret_cast*>(grid), + reinterpret_cast*>(reciprocal)); + CHECK_CUDA_SYNC(); +} + template __global__ void xc_functional_grad_wfc( const int ik, diff --git a/source/source_hamilt/module_xc/kernels/xc_functional_op.h b/source/source_hamilt/module_xc/kernels/xc_functional_op.h index 1352be70de6..3c2c839f182 100644 --- a/source/source_hamilt/module_xc/kernels/xc_functional_op.h +++ b/source/source_hamilt/module_xc/kernels/xc_functional_op.h @@ -8,6 +8,20 @@ namespace hamilt { +#if defined(__CUDA) +void xc_gradient_coefficients_gpu(int npw, int component, const int* grid_index, + const double* gcar, const std::complex* rhog, + std::complex* grid); +void xc_extract_real_gpu(int size, int stride, int offset, double scale, + const std::complex* grid, double* result); +void xc_pack_component_gpu(int size, int component, const double* vectors, + std::complex* grid); +void xc_accumulate_divergence_gpu(int npw, int nxyz, int component, + const int* grid_index, const double* gcar, + const std::complex* grid, + std::complex* reciprocal); +#endif + template struct xc_functional_grad_wfc_op { diff --git a/source/source_hamilt/module_xc/ncgga_sf_gpu.h b/source/source_hamilt/module_xc/ncgga_sf_gpu.h new file mode 100644 index 00000000000..60264bd5b5d --- /dev/null +++ b/source/source_hamilt/module_xc/ncgga_sf_gpu.h @@ -0,0 +1,34 @@ +#ifndef ABACUS_NCGGA_SF_GPU_H +#define ABACUS_NCGGA_SF_GPU_H + +#if defined(__CUDA) +#include "source_base/matrix.h" +#include "source_base/vector3.h" +#include "source_hamilt/module_xc/xc_ncgga_radial.h" + +#include +#endif + +namespace ModuleXC +{ +#if defined(__CUDA) +/// Evaluate the local LDA and PBE-GGA terms of the regularized NCGGA-SF path +/// on the device. The radial spin map is supplied by the caller; the function +/// returns the four potential channels, the two gradient flux fields, and the +/// energy sum. Returns false when no device evaluation was performed. +bool ncgga_sf_local_gpu(int nrxx, + const NcggaSpinMapPoint* spin_map, + const double* spin_density_up, + const double* spin_density_down, + const ModuleBase::Vector3* gradient_up, + const ModuleBase::Vector3* gradient_down, + double e2, + bool is_gga, + ModuleBase::matrix& potential, + std::vector>& flux_up, + std::vector>& flux_down, + double& etxc); +#endif +} // namespace ModuleXC + +#endif diff --git a/source/source_hamilt/module_xc/test/CMakeLists.txt b/source/source_hamilt/module_xc/test/CMakeLists.txt index b47f67d6193..1e7f56ffe76 100644 --- a/source/source_hamilt/module_xc/test/CMakeLists.txt +++ b/source/source_hamilt/module_xc/test/CMakeLists.txt @@ -138,9 +138,6 @@ addtest( ../../../source_base/module_fft/fft_cpu.cpp ${FFT_SRC}) -addtest(TARGET MODULE_HAMILT_XCTest_NCGGA_RADIAL - SOURCES test_xc_ncgga_radial.cpp ../xc_ncgga_radial.cpp) - addtest( TARGET MODULE_HAMILT_XCTest_NCGGA_DISCRETE_FD LIBS xc_ diff --git a/source/source_hamilt/module_xc/unittests/CMakeLists.txt b/source/source_hamilt/module_xc/unittests/CMakeLists.txt new file mode 100644 index 00000000000..a0a4c11ae3c --- /dev/null +++ b/source/source_hamilt/module_xc/unittests/CMakeLists.txt @@ -0,0 +1,2 @@ +addtest(TARGET MODULE_HAMILT_XCTest_NCGGA_RADIAL + SOURCES test_xc_ncgga_radial.cpp ../xc_ncgga_radial.cpp) diff --git a/source/source_hamilt/module_xc/test/test_xc_ncgga_radial.cpp b/source/source_hamilt/module_xc/unittests/test_xc_ncgga_radial.cpp similarity index 99% rename from source/source_hamilt/module_xc/test/test_xc_ncgga_radial.cpp rename to source/source_hamilt/module_xc/unittests/test_xc_ncgga_radial.cpp index e660b56c398..e317cdbb80a 100644 --- a/source/source_hamilt/module_xc/test/test_xc_ncgga_radial.cpp +++ b/source/source_hamilt/module_xc/unittests/test_xc_ncgga_radial.cpp @@ -11,7 +11,7 @@ namespace { -double dot(const std::array &left, const std::array &right) +double dot(const double (&left)[3], const std::array& right) { double result = 0.0; for (int component = 0; component < 3; ++component) diff --git a/source/source_hamilt/module_xc/xc_functional_ncgga_sf.cpp b/source/source_hamilt/module_xc/xc_functional_ncgga_sf.cpp index d0c9dbf1db6..f5dcda8bd28 100644 --- a/source/source_hamilt/module_xc/xc_functional_ncgga_sf.cpp +++ b/source/source_hamilt/module_xc/xc_functional_ncgga_sf.cpp @@ -5,6 +5,7 @@ #include "source_base/vector3.h" #include "source_basis/module_pw/pw_basis.h" #include "source_estate/module_charge/charge.h" +#include "ncgga_sf_gpu.h" #include "xc_functional.h" #include "xc_ncgga_radial.h" @@ -30,6 +31,7 @@ std::tuple v_xc_ncgga_sf_builtin( // g_s = G_h(rho_s). Reverse the FFT gradient before the local Jacobian: // v_A = sum_s J_sA [f_rho_s - D_h(h_s)]. No discrete product rule is used. ModulePW::PW_Basis *rhopw = chr->rhopw; + const bool use_gpu = rhopw->get_device() == "gpu"; const int npw = rhopw->npw; const double e2 = ModuleBase::e2; constexpr double vanishing = 1e-10; @@ -65,6 +67,25 @@ std::tuple v_xc_ncgga_sf_builtin( double vtxc = 0; ModuleBase::matrix v(4, nrxx); + bool used_gpu = false; + std::vector> gpu_flux_up; + std::vector> gpu_flux_down; +#if defined(__CUDA) + if (use_gpu && XC_Functional::get_func_type() == 2 + && XC_Functional::get_func_id().size() >= 2 + && XC_Functional::get_func_id()[0] == XC_GGA_X_PBE + && XC_Functional::get_func_id()[1] == XC_GGA_C_PBE) + { + gpu_flux_up.resize(nrxx); + gpu_flux_down.resize(nrxx); + used_gpu = ncgga_sf_local_gpu(nrxx, spin_map.data(), rhotmp1.data(), rhotmp2.data(), + gdr1.data(), gdr2.data(), e2, is_gga, v, + gpu_flux_up, gpu_flux_down, etxc); + } +#endif + + if (!used_gpu) + { for (int ir = 0; ir < nrxx; ++ir) { const double arho = spin_map[ir].absolute_density; @@ -171,6 +192,22 @@ std::tuple v_xc_ncgga_sf_builtin( etxc += etxcgc; } + } + else if (is_gga) + { + std::vector divergence_up(nrxx); + std::vector divergence_down(nrxx); + XC_Functional::grad_dot(gpu_flux_up.data(), divergence_up.data(), rhopw, tpiba); + XC_Functional::grad_dot(gpu_flux_down.data(), divergence_down.data(), rhopw, tpiba); + for (int ir = 0; ir < nrxx; ++ir) + { + for (int channel = 0; channel < 4; ++channel) + { + v(channel, ir) -= spin_map[ir].jacobian(0, channel) * divergence_up[ir] + + spin_map[ir].jacobian(1, channel) * divergence_down[ir]; + } + } + } // vtxc uses the same completed four-component potential returned to the // caller, including all four density channels. diff --git a/source/source_hamilt/module_xc/xc_gga_corr.cpp b/source/source_hamilt/module_xc/xc_gga_corr.cpp index a55aa395d59..58d7d98be52 100644 --- a/source/source_hamilt/module_xc/xc_gga_corr.cpp +++ b/source/source_hamilt/module_xc/xc_gga_corr.cpp @@ -10,6 +10,7 @@ // 3. pbec_spin #include "xc_functional.h" +#include "xc_math.h" // Perdew gradient correction on correlation: PRB 33, 8822 (1986) void XC_Functional::perdew86( @@ -359,51 +360,5 @@ void XC_Functional::pbec_spin( double &v1cdw, double &v2c) { - double ga = 0.0310910; - double be[3] = {0.0, 0.06672455060314922, 0.0460000}; // mohan add - // zhengdy add 2019-09-12, ensure same parameter with another dft code. - double third = 1.0 / 3.0; - double pi34 = 0.62035049089940; - // pi34=(3/4pi)^(1/3), xkf=(9 pi/4)^(1/3), xks= sqrt(4/pi) - double xkf = 1.9191582926775130; - double xks = 1.1283791670955130; - double rs = pi34 / pow(rho, third); - double ec = 0.0; - double vcup = 0.0; - double vcdw = 0.0; - - XC_Functional::pw_spin(rs, zeta, ec, vcup, vcdw); // mohan fix bug 2012-05-28 - - double kf = xkf / rs; - double ks = xks * sqrt(kf); - double fz = 0.50 * (pow((1.0 + zeta), (2.0 / 3.0)) + pow((1.0 - zeta), (2.0 / 3.0))); - double fz2 = fz * fz; - double fz3 = fz2 * fz; - // fz4 = fz3 * fz; - double dfz = (pow((1.0 + zeta), (-1.0 / 3.0)) - pow((1.0 - zeta), (-1.0 / 3.0))) / 3.0; - double t = sqrt(grho) / (2.0 * fz * ks * rho); - double expe = exp(-ec / (fz3 * ga)); - double af = be[iflag] / ga * (1.0 / (expe - 1.0)); - double bfup = expe * (vcup - ec) / fz3; - double bfdw = expe * (vcdw - ec) / fz3; - double y = af * t * t; - double xy = (1.0 + y) / (1.0 + y + y * y); - double qy = y * y * (2.0 + y) / pow((1.0 + y + y * y), 2); - // qy *= qy; //bug - double s1 = 1.0 + be[iflag] / ga * t * t * xy; - double h0 = fz3 * ga * log(s1); - double dh0up = be[iflag] * t * t * fz3 / s1 * (-7.0 / 3.0 * xy - qy * (af * bfup / be[iflag] - 7.0 / 3.0)); - double dh0dw = be[iflag] * t * t * fz3 / s1 * (-7.0 / 3.0 * xy - qy * (af * bfdw / be[iflag] - 7.0 / 3.0)); - double dh0zup = (3.0 * h0 / fz - be[iflag] * t * t * fz2 / s1 * - (2.0 * xy - qy * (3.0 * af * expe * ec / fz3 / be[iflag] + 2.0))) * - dfz * (1.0 - zeta); - double dh0zdw = -(3.0 * h0 / fz - be[iflag] * t * t * fz2 / s1 * - (2.0 * xy - qy * (3.0 * af * expe * ec / fz3 / be[iflag] + 2.0))) * - dfz * (1.0 + zeta); - double ddh0 = be[iflag] * fz / (2.0 * ks * ks * rho) * (xy - qy) / s1; - sc = rho * h0; - v1cup = h0 + dh0up + dh0zup; - v1cdw = h0 + dh0dw + dh0zdw; - v2c = ddh0; - return; + xc_math::pbec_spin(rho, zeta, grho, iflag, sc, v1cup, v1cdw, v2c); } diff --git a/source/source_hamilt/module_xc/xc_gga_exch.cpp b/source/source_hamilt/module_xc/xc_gga_exch.cpp index 0176564ee58..6df497d64ed 100644 --- a/source/source_hamilt/module_xc/xc_gga_exch.cpp +++ b/source/source_hamilt/module_xc/xc_gga_exch.cpp @@ -9,6 +9,7 @@ // 1. becke88_spin #include "xc_functional.h" +#include "xc_math.h" void XC_Functional::becke88( const double &rho, @@ -87,57 +88,7 @@ void XC_Functional::pbex( double &v1x, double &v2x) { - // PBE exchange (without Slater exchange): - // iflag=0 J.P.Perdew, K.Burke, M.Ernzerhof, PRL 77, 3865 (1996) - // iflag=1 "revised' PBE: Y. Zhang et al., PRL 80, 890 (1998) - - // input: charge and squared gradient - // output: energy - // output: potential - // (3*pi2*|rho|)^(1/3) - // |grho| - // |grho|/(2*kf*|rho|) - // s^2 - // n*ds/dn - // n*ds/d(gn) - // exchange energy LDA part - // exchange energy gradient part - - // numerical coefficients (NB: c2=(3 pi^2)^(1/3) ) - const double third = 1.0 / 3.0; - const double c1 = 0.750 / ModuleBase::PI; - const double c2 = 3.0936677262801360; - const double c5 = 4.0 * third; - // parameters of the functional - double k[3] = {0.8040, 1.24500, 0.8040}; - const double mu[3] = {0.2195149727645171, 0.2195149727645171, - 0.12345679012345679}; // modified by zhengdy, to ensure the same parameters with another dft code. - - const double agrho = sqrt(grho); - const double kf = c2 * pow(rho, third); - const double dsg = 0.50 / kf; - const double s1 = agrho * dsg / rho; - const double s2 = s1 * s1; - const double ds = -c5 * s1; - - // Energy - const double f1 = s2 * mu[iflag] / k[iflag]; - const double f2 = 1.0 + f1; - const double f3 = k[iflag] / f2; - const double fx = k[iflag] - f3; - const double exunif = -c1 * kf; - sx = exunif * fx; - - // Potential - const double dxunif = exunif * third; - const double dfx1 = f2 * f2; - const double dfx = 2.0 * mu[iflag] * s1 / dfx1; - - v1x = sx + dxunif * fx + exunif * dfx * ds; - v2x = exunif * dfx * dsg / agrho; - sx = sx * rho; - - return; + xc_math::pbex(rho, grho, iflag, sx, v1x, v2x); } void XC_Functional::optx( diff --git a/source/source_hamilt/module_xc/xc_grad_utils.cpp b/source/source_hamilt/module_xc/xc_grad_utils.cpp index 527ab2dc587..edcb06eaf8f 100644 --- a/source/source_hamilt/module_xc/xc_grad_utils.cpp +++ b/source/source_hamilt/module_xc/xc_grad_utils.cpp @@ -8,6 +8,103 @@ #include "source_base/constants.h" #include "xc_functional.h" +#include "source_base/timer.h" + +#if defined(__CUDA) +#include "source_basis/module_pw/kernels/pw_op.h" +#include "source_hamilt/module_xc/kernels/xc_functional_op.h" + +#include +#include +#include +#endif + +#if defined(__CUDA) +namespace +{ +bool xc_gpu_transform_eligible(const ModulePW::PW_Basis& basis) +{ + return basis.get_device() == "gpu" && basis.poolnproc == 1 && !basis.gamma_only + && basis.fft3d_bundle.template get_auxr_3d_data() != nullptr; +} + +template +ct::Tensor xc_copy_to_gpu(const T* source, int size) +{ + ct::Tensor result(ct::DataTypeToEnum::value, ct::DeviceType::GpuDevice, {size}); + base_device::memory::synchronize_memory_op()( + result.data(), source, size); + return result; +} + +ct::Tensor xc_density_grid_indices(const ModulePW::PW_Basis& basis) +{ + ct::Tensor indices(ct::DataType::DT_INT, ct::DeviceType::CpuDevice, {basis.npw}); + int* index = indices.data(); +#ifdef _OPENMP +#pragma omp parallel for schedule(static, 1024) +#endif + for (int ig = 0; ig < basis.npw; ++ig) + { + const int iz = basis.ig2isz[ig] % basis.nz; + const int is = basis.ig2isz[ig] / basis.nz; + index[ig] = basis.is2fftixy[is] * basis.nz + iz; + } + return indices.to_device(); +} + +void xc_density_gradient_gpu(const std::complex* rhog, ModuleBase::Vector3* gradient, + const ModulePW::PW_Basis& basis, double scale) +{ + ModuleBase::timer::start("XC_Functional", "xc_density_gradient_gpu"); + static_assert(sizeof(ModuleBase::Vector3) == 3 * sizeof(double), "Vector3 must be contiguous"); + ct::Tensor indices = xc_density_grid_indices(basis); + ct::Tensor reciprocal = xc_copy_to_gpu(rhog, basis.npw); + ct::Tensor gcar = xc_copy_to_gpu(reinterpret_cast(basis.gcar), 3 * basis.npw); + ct::Tensor result(ct::DataType::DT_DOUBLE, ct::DeviceType::GpuDevice, {basis.nrxx, 3}); + std::complex* grid = basis.fft3d_bundle.template get_auxr_3d_data(); + for (int component = 0; component < 3; ++component) + { + base_device::memory::set_memory_op, base_device::DEVICE_GPU>()(grid, 0, basis.nxyz); + hamilt::xc_gradient_coefficients_gpu(basis.npw, component, indices.data(), gcar.data(), + reciprocal.data>(), grid); + basis.fft3d_bundle.fft3D_backward(grid, grid); + hamilt::xc_extract_real_gpu(basis.nrxx, 3, component, scale, grid, result.data()); + } + base_device::memory::synchronize_memory_op()( + reinterpret_cast(gradient), result.data(), 3 * basis.nrxx); + ModuleBase::timer::end("XC_Functional", "xc_density_gradient_gpu"); +} + +void xc_density_divergence_gpu(const ModuleBase::Vector3* vectors, double* divergence, + const ModulePW::PW_Basis& basis, double scale) +{ + ModuleBase::timer::start("XC_Functional", "xc_density_divergence_gpu"); + static_assert(sizeof(ModuleBase::Vector3) == 3 * sizeof(double), "Vector3 must be contiguous"); + ct::Tensor indices = xc_density_grid_indices(basis); + ct::Tensor input = xc_copy_to_gpu(reinterpret_cast(vectors), 3 * basis.nrxx); + ct::Tensor gcar = xc_copy_to_gpu(reinterpret_cast(basis.gcar), 3 * basis.npw); + ct::Tensor reciprocal(ct::DataType::DT_COMPLEX_DOUBLE, ct::DeviceType::GpuDevice, {basis.npw}); + ct::Tensor result(ct::DataType::DT_DOUBLE, ct::DeviceType::GpuDevice, {basis.nrxx}); + std::complex* grid = basis.fft3d_bundle.template get_auxr_3d_data(); + for (int component = 0; component < 3; ++component) + { + hamilt::xc_pack_component_gpu(basis.nrxx, component, input.data(), grid); + basis.fft3d_bundle.fft3D_forward(grid, grid); + hamilt::xc_accumulate_divergence_gpu(basis.npw, basis.nxyz, component, indices.data(), + gcar.data(), grid, reciprocal.data>()); + } + base_device::memory::set_memory_op, base_device::DEVICE_GPU>()(grid, 0, basis.nxyz); + ModulePW::set_3d_fft_box_op()( + basis.npw, indices.data(), reciprocal.data>(), grid); + basis.fft3d_bundle.fft3D_backward(grid, grid); + hamilt::xc_extract_real_gpu(basis.nrxx, 1, 0, scale, grid, result.data()); + base_device::memory::synchronize_memory_op()( + divergence, result.data(), basis.nrxx); + ModuleBase::timer::end("XC_Functional", "xc_density_divergence_gpu"); +} +} // namespace +#endif void XC_Functional::grad_rho( const std::complex *rhog, @@ -15,6 +112,13 @@ void XC_Functional::grad_rho( const ModulePW::PW_Basis *rho_basis, const double tpiba) { +#if defined(__CUDA) + if (xc_gpu_transform_eligible(*rho_basis)) + { + xc_density_gradient_gpu(rhog, gdr, *rho_basis, tpiba); + return; + } +#endif std::vector> gdrtmp(rho_basis->nmaxgr); // the formula is : rho(r)^prime = int iG * rho(G)e^{iGr} dG @@ -51,6 +155,13 @@ void XC_Functional::grad_dot( const ModulePW::PW_Basis *rho_basis, const double tpiba) { +#if defined(__CUDA) + if (xc_gpu_transform_eligible(*rho_basis)) + { + xc_density_divergence_gpu(h, dh, *rho_basis, tpiba); + return; + } +#endif std::vector> aux(rho_basis->nmaxgr); std::vector> gaux(rho_basis->npw); diff --git a/source/source_hamilt/module_xc/xc_lda_corr.cpp b/source/source_hamilt/module_xc/xc_lda_corr.cpp index 66b0928c92b..34f6bb6d8ba 100644 --- a/source/source_hamilt/module_xc/xc_lda_corr.cpp +++ b/source/source_hamilt/module_xc/xc_lda_corr.cpp @@ -12,6 +12,7 @@ // 2. pz_spin, which calls pz_polarized #include "xc_functional.h" +#include "xc_math.h" void XC_Functional::pw( const double &rs, @@ -213,121 +214,7 @@ void XC_Functional::pw_spin( double &vcup, double &vcdw) { - const double a = 0.0310910; - const double a1 = 0.213700; - const double b1 = 7.59570; - const double b2 = 3.58760; - const double b3 = 1.63820; - const double b4 = 0.492940; - // const double c0 = a; - // const double c1 = 0.0466440; - // const double c2 = 0.006640; - // const double c3 = 0.010430; - // const double d0 = 0.43350; - // const double d1 = 1.44080; - // polarized parameters - const double ap = 0.0155450; - const double a1p = 0.205480; - const double b1p = 14.11890; - const double b2p = 6.19770; - const double b3p = 3.36620; - const double b4p = 0.625170; - // const double c0p = ap; - // const double c1p = 0.0255990; - // const double c2p = 0.003190; - // const double c3p = 0.003840; - // const double d0p = 0.32870; - // const double d1p = 1.76970; - // antiferro - const double aa = 0.0168870; - const double a1a = 0.111250; - const double b1a = 10.3570; - const double b2a = 3.62310; - const double b3a = 0.880260; - const double b4a = 0.496710; - // const double c0a = aa; - // const double c1a = 0.0354750; - // const double c2a = 0.001880; - // const double c3a = 0.005210; - // const double d0a = 0.22400; - // const double d1a = 0.39690; - - const double fz0 = 1.7099210; - double rs12 = 0.0; - double rs32 = 0.0; - double rs2 = 0.0; - double zeta2 = 0.0; - double zeta3 = 0.0; - double zeta4 = 0.0; - double fz = 0.0; - double dfz = 0.0; - double om = 0.0; - double dom = 0.0; - double olog = 0.0; - double epwc = 0.0; - double vpwc = 0.0; - double omp = 0.0; - double domp = 0.0; - double ologp = 0.0; - double epwcp = 0.0; - double vpwcp = 0.0; - double oma = 0.0; - double doma = 0.0; - double ologa = 0.0; - double alpha = 0.0; - double vpwca = 0.0; - - // if(rs.lt.0.5d0) then - // high density formula (not implemented) - // - // else if(rs.gt.100.d0) then - // low density formula (not implemented) - // - // else - // interpolation formula - zeta2 = zeta * zeta; - zeta3 = zeta2 * zeta; - zeta4 = zeta3 * zeta; - rs12 = sqrt(rs); - rs32 = rs * rs12; - rs2 = rs * rs; - // unpolarised - om = 2.0 * a * (b1 * rs12 + b2 * rs + b3 * rs32 + b4 * rs2); - dom = 2.0 * a * (0.50 * b1 * rs12 + b2 * rs + 1.50 * b3 * rs32 + 2.0 * b4 * rs2); - olog = log(1.0 + 1.00 / om); - epwc = -2.0 * a * (1.0 + a1 * rs) * olog; - vpwc = -2.0 * a * (1.0 + 2.0 / 3.0 * a1 * rs) * olog - 2.0 / 3.0 * a * (1.0 + a1 * rs) * dom / (om * (om + 1.0)); - // polarized - omp = 2.0 * ap * (b1p * rs12 + b2p * rs + b3p * rs32 + b4p * rs2); - domp = 2.0 * ap * (0.50 * b1p * rs12 + b2p * rs + 1.50 * b3p * rs32 + 2.0 * b4p * rs2); - ologp = log(1.0 + 1.00 / omp); - epwcp = -2.0 * ap * (1.0 + a1p * rs) * ologp; - vpwcp = -2.0 * ap * (1.0 + 2.0 / 3.0 * a1p * rs) * ologp - - 2.0 / 3.0 * ap * (1.0 + a1p * rs) * domp / (omp * (omp + 1.0)); - // antiferro - oma = 2.0 * aa * (b1a * rs12 + b2a * rs + b3a * rs32 + b4a * rs2); - doma = 2.0 * aa * (0.50 * b1a * rs12 + b2a * rs + 1.50 * b3a * rs32 + 2.0 * b4a * rs2); - ologa = log(1.0 + 1.00 / oma); - alpha = 2.0 * aa * (1.0 + a1a * rs) * ologa; - vpwca = +2.0 * aa * (1.0 + 2.0 / 3.0 * a1a * rs) * ologa + - 2.0 / 3.0 * aa * (1.0 + a1a * rs) * doma / (oma * (oma + 1.0)); - - fz = (pow((1.0 + zeta), (4.0 / 3.0)) + pow((1.0 - zeta), (4.0 / 3.0)) - 2.0) / (pow(2.0, (4.0 / 3.0)) - 2.0); - dfz = - (pow((1.0 + zeta), (1.0 / 3.0)) - pow((1.0 - zeta), (1.0 / 3.0))) * 4.0 / (3.0 * (pow(2.0, (4.0 / 3.0)) - 2.0)); - - ec = epwc + alpha * fz * (1.0 - zeta4) / fz0 + (epwcp - epwc) * fz * zeta4; - - vcup = - vpwc + vpwca * fz * (1.0 - zeta4) / fz0 + (vpwcp - vpwc) * fz * zeta4 + - (alpha / fz0 * (dfz * (1.0 - zeta4) - 4.0 * fz * zeta3) + (epwcp - epwc) * (dfz * zeta4 + 4.0 * fz * zeta3)) * - (1.0 - zeta); - - vcdw = - vpwc + vpwca * fz * (1.0 - zeta4) / fz0 + (vpwcp - vpwc) * fz * zeta4 - - (alpha / fz0 * (dfz * (1.0 - zeta4) - 4.0 * fz * zeta3) + (epwcp - epwc) * (dfz * zeta4 + 4.0 * fz * zeta3)) * - (1.0 + zeta); - return; + xc_math::pw_spin(rs, zeta, ec, vcup, vcdw); } // J.P. Perdew and Y. Wang, PRB 45, 13244 (1992) diff --git a/source/source_hamilt/module_xc/xc_lda_exch.cpp b/source/source_hamilt/module_xc/xc_lda_exch.cpp index 6d005fa5435..1e0e518fd47 100644 --- a/source/source_hamilt/module_xc/xc_lda_exch.cpp +++ b/source/source_hamilt/module_xc/xc_lda_exch.cpp @@ -9,6 +9,7 @@ // 3. slater_rxc_spin #include "xc_functional.h" +#include "xc_math.h" // Slater exchange with alpha=2/3 void XC_Functional::slater(const double &rs, double &ex, double &vx) @@ -63,21 +64,7 @@ void XC_Functional::slater_spin( double &vxup, double &vxdw) { - const double f = -1.107838149573033610; - const double alpha = 2.00 / 3.00; - // f = -9/8*(3/pi)^(1/3) - const double third = 1.0 / 3.0; - const double p43 = 4.0 / 3.0; - - double rho13 = pow(((1.0 + zeta) * rho), third); - double exup = f * alpha * rho13; - vxup = p43 * f * alpha * rho13; - rho13 = pow(((1.0 - zeta) * rho), third); - double exdw = f * alpha * rho13; - vxdw = p43 * f * alpha * rho13; - ex = 0.50 * ((1.0 + zeta) * exup + (1.0 - zeta) * exdw); - - return; + xc_math::slater_spin(rho, zeta, ex, vxup, vxdw); } // Slater exchange with alpha=2/3, spin-polarized case diff --git a/source/source_hamilt/module_xc/xc_math.h b/source/source_hamilt/module_xc/xc_math.h new file mode 100644 index 00000000000..b4b543fb49e --- /dev/null +++ b/source/source_hamilt/module_xc/xc_math.h @@ -0,0 +1,269 @@ +#ifndef ABACUS_XC_MATH_H +#define ABACUS_XC_MATH_H + +#include +#include + +// Scalar exchange-correlation formulas shared by host and device evaluation. +namespace xc_math +{ + +// Slater exchange with alpha = 2/3 for spin-polarized density. +AT_HOST_DEVICE inline void slater_spin(const double& rho, + const double& zeta, + double& ex, + double& vxup, + double& vxdw) +{ + const double f = -1.107838149573033610; + const double alpha = 2.00 / 3.00; + // f = -9/8*(3/pi)^(1/3) + const double third = 1.0 / 3.0; + const double p43 = 4.0 / 3.0; + + double rho13 = pow(((1.0 + zeta) * rho), third); + double exup = f * alpha * rho13; + vxup = p43 * f * alpha * rho13; + rho13 = pow(((1.0 - zeta) * rho), third); + double exdw = f * alpha * rho13; + vxdw = p43 * f * alpha * rho13; + ex = 0.50 * ((1.0 + zeta) * exup + (1.0 - zeta) * exdw); + + return; +} + +AT_HOST_DEVICE inline void pw_spin(const double& rs, const double& zeta, double& ec, double& vcup, double& vcdw) +{ + const double a = 0.0310910; + const double a1 = 0.213700; + const double b1 = 7.59570; + const double b2 = 3.58760; + const double b3 = 1.63820; + const double b4 = 0.492940; + // const double c0 = a; + // const double c1 = 0.0466440; + // const double c2 = 0.006640; + // const double c3 = 0.010430; + // const double d0 = 0.43350; + // const double d1 = 1.44080; + // polarized parameters + const double ap = 0.0155450; + const double a1p = 0.205480; + const double b1p = 14.11890; + const double b2p = 6.19770; + const double b3p = 3.36620; + const double b4p = 0.625170; + // const double c0p = ap; + // const double c1p = 0.0255990; + // const double c2p = 0.003190; + // const double c3p = 0.003840; + // const double d0p = 0.32870; + // const double d1p = 1.76970; + // antiferro + const double aa = 0.0168870; + const double a1a = 0.111250; + const double b1a = 10.3570; + const double b2a = 3.62310; + const double b3a = 0.880260; + const double b4a = 0.496710; + // const double c0a = aa; + // const double c1a = 0.0354750; + // const double c2a = 0.001880; + // const double c3a = 0.005210; + // const double d0a = 0.22400; + // const double d1a = 0.39690; + + const double fz0 = 1.7099210; + double rs12, rs32, rs2, zeta2, zeta3, zeta4, fz, dfz; + double om, dom, olog, epwc, vpwc; + double omp, domp, ologp, epwcp, vpwcp; + double oma, doma, ologa, alpha, vpwca; + + // if(rs.lt.0.5d0) then + // high density formula (not implemented) + // + // else if(rs.gt.100.d0) then + // low density formula (not implemented) + // + // else + // interpolation formula + zeta2 = zeta * zeta; + zeta3 = zeta2 * zeta; + zeta4 = zeta3 * zeta; + rs12 = sqrt(rs); + rs32 = rs * rs12; + rs2 = rs * rs; + // unpolarised + om = 2.0 * a * (b1 * rs12 + b2 * rs + b3 * rs32 + b4 * rs2); + dom = 2.0 * a * (0.50 * b1 * rs12 + b2 * rs + 1.50 * b3 * rs32 + 2.0 * b4 * rs2); + olog = log(1.0 + 1.00 / om); + epwc = -2.0 * a * (1.0 + a1 * rs) * olog; + vpwc = -2.0 * a * (1.0 + 2.0 / 3.0 * a1 * rs) * olog - 2.0 / 3.0 * a * (1.0 + a1 * rs) * dom / (om * (om + 1.0)); + // polarized + omp = 2.0 * ap * (b1p * rs12 + b2p * rs + b3p * rs32 + b4p * rs2); + domp = 2.0 * ap * (0.50 * b1p * rs12 + b2p * rs + 1.50 * b3p * rs32 + 2.0 * b4p * rs2); + ologp = log(1.0 + 1.00 / omp); + epwcp = -2.0 * ap * (1.0 + a1p * rs) * ologp; + vpwcp = -2.0 * ap * (1.0 + 2.0 / 3.0 * a1p * rs) * ologp + - 2.0 / 3.0 * ap * (1.0 + a1p * rs) * domp / (omp * (omp + 1.0)); + // antiferro + oma = 2.0 * aa * (b1a * rs12 + b2a * rs + b3a * rs32 + b4a * rs2); + doma = 2.0 * aa * (0.50 * b1a * rs12 + b2a * rs + 1.50 * b3a * rs32 + 2.0 * b4a * rs2); + ologa = log(1.0 + 1.00 / oma); + alpha = 2.0 * aa * (1.0 + a1a * rs) * ologa; + vpwca = +2.0 * aa * (1.0 + 2.0 / 3.0 * a1a * rs) * ologa + + 2.0 / 3.0 * aa * (1.0 + a1a * rs) * doma / (oma * (oma + 1.0)); + + fz = (pow((1.0 + zeta), (4.0 / 3.0)) + pow((1.0 - zeta), (4.0 / 3.0)) - 2.0) / (pow(2.0, (4.0 / 3.0)) - 2.0); + dfz = (pow((1.0 + zeta), (1.0 / 3.0)) - pow((1.0 - zeta), (1.0 / 3.0))) * 4.0 + / (3.0 * (pow(2.0, (4.0 / 3.0)) - 2.0)); + + ec = epwc + alpha * fz * (1.0 - zeta4) / fz0 + (epwcp - epwc) * fz * zeta4; + + vcup + = vpwc + vpwca * fz * (1.0 - zeta4) / fz0 + (vpwcp - vpwc) * fz * zeta4 + + (alpha / fz0 * (dfz * (1.0 - zeta4) - 4.0 * fz * zeta3) + (epwcp - epwc) * (dfz * zeta4 + 4.0 * fz * zeta3)) + * (1.0 - zeta); + + vcdw + = vpwc + vpwca * fz * (1.0 - zeta4) / fz0 + (vpwcp - vpwc) * fz * zeta4 + - (alpha / fz0 * (dfz * (1.0 - zeta4) - 4.0 * fz * zeta3) + (epwcp - epwc) * (dfz * zeta4 + 4.0 * fz * zeta3)) + * (1.0 + zeta); + return; +} + +AT_HOST_DEVICE inline void pbex(const double& rho, + const double& grho, + const int& iflag, + double& sx, + double& v1x, + double& v2x) +{ + // PBE exchange (without Slater exchange): + // iflag=0 J.P.Perdew, K.Burke, M.Ernzerhof, PRL 77, 3865 (1996) + // iflag=1 "revised' PBE: Y. Zhang et al., PRL 80, 890 (1998) + + // input: charge and squared gradient + // output: energy + // output: potential + // (3*pi2*|rho|)^(1/3) + // |grho| + // |grho|/(2*kf*|rho|) + // s^2 + // n*ds/dn + // n*ds/d(gn) + // exchange energy LDA part + // exchange energy gradient part + + // numerical coefficients (NB: c2=(3 pi^2)^(1/3) ) + const double third = 1.0 / 3.0; + const double pi = 3.14159265358979323846; + const double c1 = 0.750 / pi; + const double c2 = 3.0936677262801360; + const double c5 = 4.0 * third; + // parameters of the functional + double k[3] = {0.8040, 1.24500, 0.8040}; + // PBE and revPBE use mu = 0.2195149727645171. The modified PBE branch + // keeps the historical 0.12345679012345679 value for compatibility with + // the reference implementation used by ABACUS. + constexpr double mu_pbe = 0.2195149727645171; + constexpr double mu_modified = 0.12345679012345679; + const double mu[3] = {mu_pbe, mu_pbe, mu_modified}; + + const double agrho = sqrt(grho); + const double kf = c2 * pow(rho, third); + const double dsg = 0.50 / kf; + const double s1 = agrho * dsg / rho; + const double s2 = s1 * s1; + const double ds = -c5 * s1; + + // Energy + const double f1 = s2 * mu[iflag] / k[iflag]; + const double f2 = 1.0 + f1; + const double f3 = k[iflag] / f2; + const double fx = k[iflag] - f3; + const double exunif = -c1 * kf; + sx = exunif * fx; + + // Potential + const double dxunif = exunif * third; + const double dfx1 = f2 * f2; + const double dfx = 2.0 * mu[iflag] * s1 / dfx1; + + v1x = sx + dxunif * fx + exunif * dfx * ds; + v2x = exunif * dfx * dsg / agrho; + sx = sx * rho; + + return; +} + +AT_HOST_DEVICE inline void pbec_spin(double rho, + double zeta, + double grho, + const int& iflag, + double& sc, + double& v1cup, + double& v1cdw, + double& v2c) +{ + //----------------------------------------------------------- + + // PBE correlation (without LDA part) - spin-polarized + // J.P.Perdew, K.Burke, M.Ernzerhof, PRL 77, 3865 (1996). + + // USE kinds + // implicit none + // real(kind=DP) :: rho, zeta, grho, sc, v1cup, v1cdw, v2c + const double ga = 0.0310910; + const double be[3] = {0.0, 0.06672455060314922, 0.0460000}; // mohan add + // zhengdy add 2019-09-12, ensure same parameter with another dft code. + double third, pi34, xkf, xks; + // parameter : + third = 1.0 / 3.0; + pi34 = 0.62035049089940; + // parameter : + xkf = 1.9191582926775130; + xks = 1.1283791670955130; + // pi34=(3/4pi)^(1/3), xkf=(9 pi/4)^(1/3), xks= sqrt(4/pi) + double kf, ks, rs, ec, vcup, vcdw, t, expe, af, y, xy, qy, s1, h0, ddh0; + double fz, fz2, fz3, dfz, bfup, bfdw, dh0up, dh0dw, dh0zup, dh0zdw; // fz4 + + rs = pi34 / pow(rho, third); + pw_spin(rs, zeta, ec, vcup, vcdw); // mohan fix bug 2012-05-28 + kf = xkf / rs; + ks = xks * sqrt(kf); + fz = 0.50 * (pow((1.0 + zeta), (2.0 / 3.0)) + pow((1.0 - zeta), (2.0 / 3.0))); + fz2 = fz * fz; + fz3 = fz2 * fz; + // fz4 = fz3 * fz; + dfz = (pow((1.0 + zeta), (-1.0 / 3.0)) - pow((1.0 - zeta), (-1.0 / 3.0))) / 3.0; + t = sqrt(grho) / (2.0 * fz * ks * rho); + expe = exp(-ec / (fz3 * ga)); + af = be[iflag] / ga * (1.0 / (expe - 1.0)); + bfup = expe * (vcup - ec) / fz3; + bfdw = expe * (vcdw - ec) / fz3; + y = af * t * t; + xy = (1.0 + y) / (1.0 + y + y * y); + qy = y * y * (2.0 + y) / pow((1.0 + y + y * y), 2); + // qy *= qy; //bug + s1 = 1.0 + be[iflag] / ga * t * t * xy; + h0 = fz3 * ga * log(s1); + dh0up = be[iflag] * t * t * fz3 / s1 * (-7.0 / 3.0 * xy - qy * (af * bfup / be[iflag] - 7.0 / 3.0)); + dh0dw = be[iflag] * t * t * fz3 / s1 * (-7.0 / 3.0 * xy - qy * (af * bfdw / be[iflag] - 7.0 / 3.0)); + dh0zup = (3.0 * h0 / fz + - be[iflag] * t * t * fz2 / s1 * (2.0 * xy - qy * (3.0 * af * expe * ec / fz3 / be[iflag] + 2.0))) + * dfz * (1.0 - zeta); + dh0zdw = -(3.0 * h0 / fz + - be[iflag] * t * t * fz2 / s1 * (2.0 * xy - qy * (3.0 * af * expe * ec / fz3 / be[iflag] + 2.0))) + * dfz * (1.0 + zeta); + ddh0 = be[iflag] * fz / (2.0 * ks * ks * rho) * (xy - qy) / s1; + sc = rho * h0; + v1cup = h0 + dh0up + dh0zup; + v1cdw = h0 + dh0dw + dh0zdw; + v2c = ddh0; + return; +} + +} // namespace xc_math + +#endif diff --git a/source/source_hamilt/module_xc/xc_ncgga_radial.h b/source/source_hamilt/module_xc/xc_ncgga_radial.h index e710789bfbc..eaaa333d0ef 100644 --- a/source/source_hamilt/module_xc/xc_ncgga_radial.h +++ b/source/source_hamilt/module_xc/xc_ncgga_radial.h @@ -12,8 +12,8 @@ struct NcggaRadialPoint // direction is represented by the zero vector because the scalar map has // a unique zero gradient and zero Hessian there. double value = 0.0; - std::array direction = {{0.0, 0.0, 0.0}}; - std::array gradient = {{0.0, 0.0, 0.0}}; + double direction[3] = {0.0, 0.0, 0.0}; + double gradient[3] = {0.0, 0.0, 0.0}; double transverse_hessian = 0.0; double radial_hessian = 0.0; diff --git a/source/source_io/module_parameter/read_inp_estruc.cpp b/source/source_io/module_parameter/read_inp_estruc.cpp index ce58dd9caab..282bd1a0aaf 100644 --- a/source/source_io/module_parameter/read_inp_estruc.cpp +++ b/source/source_io/module_parameter/read_inp_estruc.cpp @@ -325,8 +325,9 @@ The other way is only available when compiling with LIBXC, and it allows for sup item.type = "String"; item.description = "Selects CPU or CUDA evaluation of the Libxc LDA/GGA potential, including the " "semilocal part of HSE. GPU evaluation requires ABACUS built with ENABLE_LIBXC_CUDA=ON " - "and CUDA-enabled Libxc >= 7.1.0. Built-in functionals, meta-GGA, response kernels and " - "separate force/stress evaluations retain their CPU implementation."; + "and CUDA-enabled Libxc >= 7.1.0. Built-in functionals (except noncollinear PBE " + "potential evaluation when the density PW basis runs on CUDA), meta-GGA, response " + "kernels and separate force/stress evaluations retain their CPU implementation."; item.default_value = "cpu"; read_sync_string(input.device_xc); this->add_item(item); diff --git a/source/source_pw/module_pwdft/op_pw_meta.cpp b/source/source_pw/module_pwdft/op_pw_meta.cpp index 7c773277056..ca6d5afae02 100644 --- a/source/source_pw/module_pwdft/op_pw_meta.cpp +++ b/source/source_pw/module_pwdft/op_pw_meta.cpp @@ -28,7 +28,7 @@ Meta>::Meta( this->vk_row = vk_row; this->vk_col = vk_col; this->wfcpw = wfcpw_in; - resmem_complex_op()(this->porter, this->wfcpw->nmaxgr, "Meta::porter"); + } template @@ -53,6 +53,11 @@ void Meta>::act( } ModuleBase::timer::start("Operator", "MetaPW"); + + if (this->porter == nullptr) + { + resmem_complex_op()(this->porter, this->wfcpw->nmaxgr, "Meta::porter"); + } if (is_first_node) { setmem_complex_op()(tmhpsi, 0, nbasis * nbands / npol); diff --git a/source/source_pw/module_pwdft/op_pw_meta.h b/source/source_pw/module_pwdft/op_pw_meta.h index 97af676b24b..965a8835efa 100644 --- a/source/source_pw/module_pwdft/op_pw_meta.h +++ b/source/source_pw/module_pwdft/op_pw_meta.h @@ -79,7 +79,7 @@ class Meta> : public OperatorPW Device *ctx = {}; base_device::DEVICE_CPU *cpu_ctx = {}; - T *porter = nullptr; + mutable T *porter = nullptr; using meta_op = meta_pw_op; using vector_mul_vector_op = ModuleBase::vector_mul_vector_op; using resmem_complex_op = base_device::memory::resize_memory_op; diff --git a/source/source_pw/module_pwdft/op_pw_veff.h b/source/source_pw/module_pwdft/op_pw_veff.h index 553517855d1..d56cb2a93ef 100644 --- a/source/source_pw/module_pwdft/op_pw_veff.h +++ b/source/source_pw/module_pwdft/op_pw_veff.h @@ -72,8 +72,8 @@ class Veff> : public OperatorPW int veff_col = 0; int veff_row = 0; const Real *veff = nullptr, *h_veff = nullptr, *d_veff = nullptr; - T *porter = nullptr; - T *porter1 = nullptr; + mutable T *porter = nullptr; + mutable T *porter1 = nullptr; base_device::AbacusDevice_t device = {}; using veff_op = veff_pw_op;