0576e51b1976e548b71406b44d0ae834ba61a21e
[alexxy/gromacs.git] / src / gromacs / ewald / pme.h
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 1991-2000, University of Groningen, The Netherlands.
5  * Copyright (c) 2001-2004, The GROMACS development team.
6  * Copyright (c) 2013,2014,2015,2016,2017 by the GROMACS development team.
7  * Copyright (c) 2018,2019,2020,2021, by the GROMACS development team, led by
8  * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
9  * and including many others, as listed in the AUTHORS file in the
10  * top-level source directory and at http://www.gromacs.org.
11  *
12  * GROMACS is free software; you can redistribute it and/or
13  * modify it under the terms of the GNU Lesser General Public License
14  * as published by the Free Software Foundation; either version 2.1
15  * of the License, or (at your option) any later version.
16  *
17  * GROMACS is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
20  * Lesser General Public License for more details.
21  *
22  * You should have received a copy of the GNU Lesser General Public
23  * License along with GROMACS; if not, see
24  * http://www.gnu.org/licenses, or write to the Free Software Foundation,
25  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.
26  *
27  * If you want to redistribute modifications to GROMACS, please
28  * consider that scientific software is very special. Version
29  * control is crucial - bugs must be traceable. We will be happy to
30  * consider code for inclusion in the official distribution, but
31  * derived work must not be called official GROMACS. Details are found
32  * in the README & COPYING files - if they are missing, get the
33  * official version at http://www.gromacs.org.
34  *
35  * To help us fund GROMACS development, we humbly ask that you cite
36  * the research papers on the package. Check out http://www.gromacs.org.
37  */
38 /*! \libinternal \file
39  *
40  * \brief This file contains function declarations necessary for
41  * computing energies and forces for the PME long-ranged part (Coulomb
42  * and LJ).
43  *
44  * \author Berk Hess <hess@kth.se>
45  * \inlibraryapi
46  * \ingroup module_ewald
47  */
48
49 #ifndef GMX_EWALD_PME_H
50 #define GMX_EWALD_PME_H
51
52 #include <string>
53 #include <vector>
54
55 #include "gromacs/gpu_utils/devicebuffer_datatype.h"
56 #include "gromacs/gpu_utils/gpu_macros.h"
57 #include "gromacs/math/vectypes.h"
58 #include "gromacs/utility/real.h"
59
60 struct gmx_hw_info_t;
61 struct t_commrec;
62 struct t_inputrec;
63 struct t_nrnb;
64 struct PmeGpu;
65 struct gmx_wallclock_gpu_pme_t;
66 struct gmx_enerdata_t;
67 struct gmx_mtop_t;
68 struct gmx_pme_t;
69 struct gmx_wallcycle;
70 struct NumPmeDomains;
71
72 class DeviceContext;
73 class DeviceStream;
74 enum class GpuTaskCompletion;
75 class PmeGpuProgram;
76 class GpuEventSynchronizer;
77
78 /*! \brief Hack to selectively enable some parts of PME during unit testing.
79  *
80  * Set to \c false by default. If any of the tests sets it to \c true, it will
81  * make the compatibility check consider PME to be supported in SYCL builds.
82  *
83  * Currently we don't have proper PME implementation with SYCL, but we still want
84  * to run tests for some of the kernels.
85  *
86  * \todo Remove after #3927 is done and PME is fully enabled in SYCL builds.
87  */
88 extern bool g_allowPmeWithSyclForTesting;
89
90 namespace gmx
91 {
92 template<typename>
93 class ArrayRef;
94 class ForceWithVirial;
95 class MDLogger;
96 enum class PinningPolicy : int;
97 class StepWorkload;
98
99 /*! \libinternal \brief Class for managing usage of separate PME-only ranks
100  *
101  * Used for checking if some parts of the code could not use PME-only ranks
102  *
103  */
104 class SeparatePmeRanksPermitted
105 {
106 public:
107     //! Disables PME ranks permitted flag with a reason
108     void disablePmeRanks(const std::string& reason);
109     //! Return status of PME ranks usage
110     bool permitSeparatePmeRanks() const;
111     //! Returns all reasons, for not using PME ranks
112     std::string reasonsWhyDisabled() const;
113
114 private:
115     //! Flag that informs whether simualtion could use dedicated PME ranks
116     bool permitSeparatePmeRanks_ = true;
117     //! Storage for all reasons, why PME ranks could not be used
118     std::vector<std::string> reasons_;
119 };
120
121 } // namespace gmx
122
123 enum
124 {
125     GMX_SUM_GRID_FORWARD,
126     GMX_SUM_GRID_BACKWARD
127 };
128
129 /*! \brief Possible PME codepaths on a rank.
130  * \todo: make this enum class with gmx_pme_t C++ refactoring
131  */
132 enum class PmeRunMode
133 {
134     None,  //!< No PME task is done
135     CPU,   //!< Whole PME computation is done on CPU
136     GPU,   //!< Whole PME computation is done on GPU
137     Mixed, //!< Mixed mode: only spread and gather run on GPU; FFT and solving are done on CPU.
138 };
139
140 /*! \brief Return the smallest allowed PME grid size for \p pmeOrder */
141 int minimalPmeGridSize(int pmeOrder);
142
143 //! Return whether the grid of \c pme is identical to \c grid_size.
144 bool gmx_pme_grid_matches(const gmx_pme_t& pme, const ivec grid_size);
145
146 /*! \brief Check restrictions on pme_order and the PME grid nkx,nky,nkz.
147  *
148  * With errorsAreFatal=true, an exception or fatal error is generated
149  * on violation of restrictions.
150  * With errorsAreFatal=false, false is returned on violation of restrictions.
151  * When all restrictions are obeyed, true is returned.
152  * Argument useThreads tells if any MPI rank doing PME uses more than 1 threads.
153  * If at calling useThreads is unknown, pass true for conservative checking.
154  *
155  * The PME GPU restrictions are checked separately during pme_gpu_init().
156  */
157 bool gmx_pme_check_restrictions(int  pme_order,
158                                 int  nkx,
159                                 int  nky,
160                                 int  nkz,
161                                 int  numPmeDomainsAlongX,
162                                 bool useThreads,
163                                 bool errorsAreFatal);
164
165 /*! \brief Construct PME data
166  *
167  * \throws   gmx::InconsistentInputError if input grid sizes/PME order are inconsistent.
168  * \returns  Pointer to newly allocated and initialized PME data.
169  *
170  * \todo We should evolve something like a \c GpuManager that holds \c
171  * DeviceInformation* and \c PmeGpuProgram* and perhaps other
172  * related things whose lifetime can/should exceed that of a task (or
173  * perhaps task manager). See Issue #2522.
174  */
175 gmx_pme_t* gmx_pme_init(const t_commrec*     cr,
176                         const NumPmeDomains& numPmeDomains,
177                         const t_inputrec*    ir,
178                         gmx_bool             bFreeEnergy_q,
179                         gmx_bool             bFreeEnergy_lj,
180                         gmx_bool             bReproducible,
181                         real                 ewaldcoeff_q,
182                         real                 ewaldcoeff_lj,
183                         int                  nthread,
184                         PmeRunMode           runMode,
185                         PmeGpu*              pmeGpu,
186                         const DeviceContext* deviceContext,
187                         const DeviceStream*  deviceStream,
188                         const PmeGpuProgram* pmeGpuProgram,
189                         const gmx::MDLogger& mdlog);
190
191 /*! \brief As gmx_pme_init, but takes most settings, except the grid/Ewald coefficients, from
192  * pme_src. This is only called when the PME cut-off/grid size changes.
193  */
194 void gmx_pme_reinit(gmx_pme_t**       pmedata,
195                     const t_commrec*  cr,
196                     gmx_pme_t*        pme_src,
197                     const t_inputrec* ir,
198                     const ivec        grid_size,
199                     real              ewaldcoeff_q,
200                     real              ewaldcoeff_lj);
201
202 /*! \brief Destroys the PME data structure.*/
203 void gmx_pme_destroy(gmx_pme_t* pme);
204
205 /*! \brief Do a PME calculation on a CPU for the long range electrostatics and/or LJ.
206  *
207  * Computes the PME forces and the energy and viral, when requested,
208  * for all atoms in \p coordinates. Forces, when requested, are added
209  * to the buffer \p forces, which is allowed to contain more elements
210  * than the number of elements in \p coordinates.
211  * The meaning of \p flags is defined above, and determines which
212  * parts of the calculation are performed.
213  *
214  * \return 0 indicates all well, non zero is an error code.
215  */
216 int gmx_pme_do(struct gmx_pme_t*              pme,
217                gmx::ArrayRef<const gmx::RVec> coordinates,
218                gmx::ArrayRef<gmx::RVec>       forces,
219                gmx::ArrayRef<const real>      chargeA,
220                gmx::ArrayRef<const real>      chargeB,
221                gmx::ArrayRef<const real>      c6A,
222                gmx::ArrayRef<const real>      c6B,
223                gmx::ArrayRef<const real>      sigmaA,
224                gmx::ArrayRef<const real>      sigmaB,
225                const matrix                   box,
226                const t_commrec*               cr,
227                int                            maxshift_x,
228                int                            maxshift_y,
229                t_nrnb*                        nrnb,
230                gmx_wallcycle*                 wcycle,
231                matrix                         vir_q,
232                matrix                         vir_lj,
233                real*                          energy_q,
234                real*                          energy_lj,
235                real                           lambda_q,
236                real                           lambda_lj,
237                real*                          dvdlambda_q,
238                real*                          dvdlambda_lj,
239                const gmx::StepWorkload&       stepWork);
240
241 /*! \brief Calculate the PME grid energy V for n charges.
242  *
243  * The potential (found in \p pme) must have been found already with a
244  * call to gmx_pme_do(). Note that the charges are not spread on the grid in the
245  * pme struct. Currently does not work in parallel or with free
246  * energy.
247  */
248 real gmx_pme_calc_energy(gmx_pme_t* pme, gmx::ArrayRef<const gmx::RVec> x, gmx::ArrayRef<const real> q);
249
250 /*! \brief
251  * This function updates the local atom data on GPU after DD (charges, coordinates, etc.).
252  * TODO: it should update the PME CPU atom data as well.
253  * (currently PME CPU call gmx_pme_do() gets passed the input pointers for each computation).
254  *
255  * \param[in,out] pme        The PME structure.
256  * \param[in]     numAtoms   The number of particles.
257  * \param[in]     chargesA   The pointer to the array of particle charges in the normal state or FEP
258  * state A. Can be nullptr if PME is not performed on the GPU.
259  * \param[in]     chargesB   The pointer to the array of particle charges in state B. Only used if
260  * charges are perturbed and can otherwise be nullptr.
261  */
262 void gmx_pme_reinit_atoms(gmx_pme_t*                pme,
263                           int                       numAtoms,
264                           gmx::ArrayRef<const real> chargesA,
265                           gmx::ArrayRef<const real> chargesB);
266
267 /* A block of PME GPU functions */
268
269 /*! \brief Checks whether the GROMACS build allows to run PME on GPU.
270  * TODO: this partly duplicates an internal PME assert function
271  * pme_gpu_check_restrictions(), except that works with a
272  * formed gmx_pme_t structure. Should that one go away/work with inputrec?
273  *
274  * \param[out] error   If non-null, the error message when PME is not supported on GPU.
275  *
276  * \returns true if PME can run on GPU on this build, false otherwise.
277  */
278 bool pme_gpu_supports_build(std::string* error);
279
280 /*! \brief Checks whether the detected (GPU) hardware allows to run PME on GPU.
281  *
282  * \param[in]  hwinfo  Information about the detected hardware
283  * \param[out] error   If non-null, the error message when PME is not supported on GPU.
284  *
285  * \returns true if PME can run on GPU on this build, false otherwise.
286  */
287 bool pme_gpu_supports_hardware(const gmx_hw_info_t& hwinfo, std::string* error);
288
289 /*! \brief Checks whether the input system allows to run PME on GPU.
290  * TODO: this partly duplicates an internal PME assert function
291  * pme_gpu_check_restrictions(), except that works with a
292  * formed gmx_pme_t structure. Should that one go away/work with inputrec?
293  *
294  * \param[in]  ir     Input system.
295  * \param[out] error  If non-null, the error message if the input is not supported on GPU.
296  *
297  * \returns true if PME can run on GPU with this input, false otherwise.
298  */
299 bool pme_gpu_supports_input(const t_inputrec& ir, std::string* error);
300
301 /*! \brief
302  * Returns the active PME codepath (CPU, GPU, mixed).
303  * \todo This is a rather static data that should be managed by the higher level task scheduler.
304  *
305  * \param[in]  pme            The PME data structure.
306  * \returns active PME codepath.
307  */
308 PmeRunMode pme_run_mode(const gmx_pme_t* pme);
309
310 /*! \libinternal \brief
311  * Return the pinning policy appropriate for this build configuration
312  * for relevant buffers used for PME task on this rank (e.g. running
313  * on a GPU). */
314 gmx::PinningPolicy pme_get_pinning_policy();
315
316 /*! \brief
317  * Tells if PME is enabled to run on GPU (not necessarily active at the moment).
318  * \todo This is a rather static data that should be managed by the hardware assignment manager.
319  * For now, it is synonymous with the active PME codepath (in the absence of dynamic switching).
320  *
321  * \param[in]  pme            The PME data structure.
322  * \returns true if PME can run on GPU, false otherwise.
323  */
324 inline bool pme_gpu_task_enabled(const gmx_pme_t* pme)
325 {
326     return (pme != nullptr) && (pme_run_mode(pme) != PmeRunMode::CPU);
327 }
328
329 /*! \brief Returns the block size requirement
330  *
331  * The GPU version of PME requires that the coordinates array have a
332  * size divisible by the returned number.
333  *
334  * \param[in]  pme  The PME data structure.
335  */
336 GPU_FUNC_QUALIFIER int pme_gpu_get_block_size(const gmx_pme_t* GPU_FUNC_ARGUMENT(pme))
337         GPU_FUNC_TERM_WITH_RETURN(0);
338
339 // The following functions are all the PME GPU entry points,
340 // currently inlining to nothing on non-CUDA builds.
341
342 /*! \brief
343  * Resets the PME GPU timings. To be called at the reset step.
344  *
345  * \param[in] pme            The PME structure.
346  */
347 GPU_FUNC_QUALIFIER void pme_gpu_reset_timings(const gmx_pme_t* GPU_FUNC_ARGUMENT(pme)) GPU_FUNC_TERM;
348
349 /*! \brief
350  * Copies the PME GPU timings to the gmx_wallclock_gpu_pme_t structure (for log output). To be called at the run end.
351  *
352  * \param[in] pme               The PME structure.
353  * \param[in] timings           The gmx_wallclock_gpu_pme_t structure.
354  */
355 GPU_FUNC_QUALIFIER void pme_gpu_get_timings(const gmx_pme_t* GPU_FUNC_ARGUMENT(pme),
356                                             gmx_wallclock_gpu_pme_t* GPU_FUNC_ARGUMENT(timings)) GPU_FUNC_TERM;
357
358 /* The main PME GPU functions */
359
360 /*! \brief
361  * Prepares PME on GPU computation (updating the box if needed)
362  * \param[in] pme               The PME data structure.
363  * \param[in] box               The unit cell box.
364  * \param[in] wcycle            The wallclock counter.
365  * \param[in] stepWork          The required work for this simulation step
366  */
367 GPU_FUNC_QUALIFIER void pme_gpu_prepare_computation(gmx_pme_t*     GPU_FUNC_ARGUMENT(pme),
368                                                     const matrix   GPU_FUNC_ARGUMENT(box),
369                                                     gmx_wallcycle* GPU_FUNC_ARGUMENT(wcycle),
370                                                     const gmx::StepWorkload& GPU_FUNC_ARGUMENT(stepWork)) GPU_FUNC_TERM;
371
372 /*! \brief
373  * Launches first stage of PME on GPU - spreading kernel.
374  *
375  * \param[in] pme                The PME data structure.
376  * \param[in] xReadyOnDevice     Event synchronizer indicating that the coordinates
377  * are ready in the device memory; nullptr allowed only on separate PME ranks.
378  * \param[in] wcycle             The wallclock counter.
379  * \param[in] lambdaQ            The Coulomb lambda of the current state of the
380  * system. Only used if FEP of Coulomb is active.
381  */
382 GPU_FUNC_QUALIFIER void pme_gpu_launch_spread(gmx_pme_t*            GPU_FUNC_ARGUMENT(pme),
383                                               GpuEventSynchronizer* GPU_FUNC_ARGUMENT(xReadyOnDevice),
384                                               gmx_wallcycle*        GPU_FUNC_ARGUMENT(wcycle),
385                                               real GPU_FUNC_ARGUMENT(lambdaQ)) GPU_FUNC_TERM;
386
387 /*! \brief
388  * Launches middle stages of PME (FFT R2C, solving, FFT C2R) either on GPU or on CPU, depending on the run mode.
389  *
390  * \param[in] pme               The PME data structure.
391  * \param[in] wcycle            The wallclock counter.
392  * \param[in] stepWork          The required work for this simulation step
393  */
394 GPU_FUNC_QUALIFIER void
395 pme_gpu_launch_complex_transforms(gmx_pme_t*               GPU_FUNC_ARGUMENT(pme),
396                                   gmx_wallcycle*           GPU_FUNC_ARGUMENT(wcycle),
397                                   const gmx::StepWorkload& GPU_FUNC_ARGUMENT(stepWork)) GPU_FUNC_TERM;
398
399 /*! \brief
400  * Launches last stage of PME on GPU - force gathering and D2H force transfer.
401  *
402  * \param[in] pme               The PME data structure.
403  * \param[in] wcycle            The wallclock counter.
404  * \param[in] lambdaQ           The Coulomb lambda to use when calculating the results.
405  */
406 GPU_FUNC_QUALIFIER void pme_gpu_launch_gather(const gmx_pme_t* GPU_FUNC_ARGUMENT(pme),
407                                               gmx_wallcycle*   GPU_FUNC_ARGUMENT(wcycle),
408                                               real GPU_FUNC_ARGUMENT(lambdaQ)) GPU_FUNC_TERM;
409
410 /*! \brief
411  * Attempts to complete PME GPU tasks.
412  *
413  * The \p completionKind argument controls whether the function blocks until all
414  * PME GPU tasks enqueued completed (as pme_gpu_wait_finish_task() does) or only
415  * checks and returns immediately if they did not.
416  * When blocking or the tasks have completed it also gets the output forces
417  * by assigning the ArrayRef to the \p forces pointer passed in.
418  * Virial/energy are also outputs if they were to be computed.
419  *
420  * \param[in]  pme             The PME data structure.
421  * \param[in]  stepWork        The required work for this simulation step
422  * \param[in]  wcycle          The wallclock counter.
423  * \param[out] forceWithVirial The output force and virial
424  * \param[out] enerd           The output energies
425  * \param[in]  lambdaQ         The Coulomb lambda to use when calculating the results.
426  * \param[in]  completionKind  Indicates whether PME task completion should only be checked rather
427  *                             than waited for
428  * \returns                    True if the PME GPU tasks have completed
429  */
430 GPU_FUNC_QUALIFIER bool pme_gpu_try_finish_task(gmx_pme_t*               GPU_FUNC_ARGUMENT(pme),
431                                                 const gmx::StepWorkload& GPU_FUNC_ARGUMENT(stepWork),
432                                                 gmx_wallcycle*           GPU_FUNC_ARGUMENT(wcycle),
433                                                 gmx::ForceWithVirial* GPU_FUNC_ARGUMENT(forceWithVirial),
434                                                 gmx_enerdata_t*       GPU_FUNC_ARGUMENT(enerd),
435                                                 real                  GPU_FUNC_ARGUMENT(lambdaQ),
436                                                 GpuTaskCompletion GPU_FUNC_ARGUMENT(completionKind))
437         GPU_FUNC_TERM_WITH_RETURN(false);
438
439 /*! \brief
440  * Blocks until PME GPU tasks are completed, and gets the output forces and virial/energy
441  * (if they were to be computed).
442  *
443  * \param[in]  pme             The PME data structure.
444  * \param[in]  stepWork        The required work for this simulation step
445  * \param[in]  wcycle          The wallclock counter.
446  * \param[out] forceWithVirial The output force and virial
447  * \param[out] enerd           The output energies
448  * \param[in]  lambdaQ         The Coulomb lambda to use when calculating the results.
449  */
450 GPU_FUNC_QUALIFIER void pme_gpu_wait_and_reduce(gmx_pme_t*               GPU_FUNC_ARGUMENT(pme),
451                                                 const gmx::StepWorkload& GPU_FUNC_ARGUMENT(stepWork),
452                                                 gmx_wallcycle*           GPU_FUNC_ARGUMENT(wcycle),
453                                                 gmx::ForceWithVirial* GPU_FUNC_ARGUMENT(forceWithVirial),
454                                                 gmx_enerdata_t*       GPU_FUNC_ARGUMENT(enerd),
455                                                 real GPU_FUNC_ARGUMENT(lambdaQ)) GPU_FUNC_TERM;
456
457 /*! \brief
458  * The PME GPU reinitialization function that is called both at the end of any PME computation and on any load balancing.
459  *
460  * Clears the internal grid and energy/virial buffers; it is not safe to start
461  * the PME computation without calling this.
462  * Note that unlike in the nbnxn module, the force buffer does not need clearing.
463  *
464  * \todo Rename this function to *clear* -- it clearly only does output resetting
465  * and we should be clear about what the function does..
466  *
467  * \param[in] pme            The PME data structure.
468  * \param[in] wcycle         The wallclock counter.
469  */
470 GPU_FUNC_QUALIFIER void pme_gpu_reinit_computation(const gmx_pme_t* GPU_FUNC_ARGUMENT(pme),
471                                                    gmx_wallcycle* GPU_FUNC_ARGUMENT(wcycle)) GPU_FUNC_TERM;
472
473 /*! \brief Set pointer to device copy of coordinate data.
474  * \param[in] pme            The PME data structure.
475  * \param[in] d_x            The pointer to the positions buffer to be set
476  */
477 GPU_FUNC_QUALIFIER void pme_gpu_set_device_x(const gmx_pme_t*        GPU_FUNC_ARGUMENT(pme),
478                                              DeviceBuffer<gmx::RVec> GPU_FUNC_ARGUMENT(d_x)) GPU_FUNC_TERM;
479
480 /*! \brief Get pointer to device copy of force data.
481  * \param[in] pme            The PME data structure.
482  * \returns                  Pointer to force data
483  */
484 GPU_FUNC_QUALIFIER DeviceBuffer<gmx::RVec> pme_gpu_get_device_f(const gmx_pme_t* GPU_FUNC_ARGUMENT(pme))
485         GPU_FUNC_TERM_WITH_RETURN(DeviceBuffer<gmx::RVec>{});
486
487 /*! \brief Get pointer to the device synchronizer object that allows syncing on PME force calculation completion
488  * \param[in] pme            The PME data structure.
489  * \returns                  Pointer to synchronizer
490  */
491 GPU_FUNC_QUALIFIER GpuEventSynchronizer* pme_gpu_get_f_ready_synchronizer(const gmx_pme_t* GPU_FUNC_ARGUMENT(pme))
492         GPU_FUNC_TERM_WITH_RETURN(nullptr);
493
494 #endif