ef89a5bb7925a641e75724346a01fcff42670f86
[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, 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
54 #include "gromacs/gpu_utils/devicebuffer_datatype.h"
55 #include "gromacs/gpu_utils/gpu_macros.h"
56 #include "gromacs/math/vectypes.h"
57 #include "gromacs/utility/arrayref.h"
58 #include "gromacs/utility/basedefinitions.h"
59 #include "gromacs/utility/real.h"
60
61 struct gmx_hw_info_t;
62 struct t_commrec;
63 struct t_inputrec;
64 struct t_nrnb;
65 struct PmeGpu;
66 struct gmx_wallclock_gpu_pme_t;
67 struct DeviceInformation;
68 struct gmx_enerdata_t;
69 struct gmx_mtop_t;
70 struct gmx_pme_t;
71 struct gmx_wallcycle;
72 struct NumPmeDomains;
73
74 enum class GpuTaskCompletion;
75 class PmeGpuProgram;
76 class GpuEventSynchronizer;
77
78 namespace gmx
79 {
80 class ForceWithVirial;
81 class MDLogger;
82 enum class PinningPolicy : int;
83 class StepWorkload;
84 } // namespace gmx
85
86 enum
87 {
88     GMX_SUM_GRID_FORWARD,
89     GMX_SUM_GRID_BACKWARD
90 };
91
92 /*! \brief Possible PME codepaths on a rank.
93  * \todo: make this enum class with gmx_pme_t C++ refactoring
94  */
95 enum class PmeRunMode
96 {
97     None,  //!< No PME task is done
98     CPU,   //!< Whole PME computation is done on CPU
99     GPU,   //!< Whole PME computation is done on GPU
100     Mixed, //!< Mixed mode: only spread and gather run on GPU; FFT and solving are done on CPU.
101 };
102
103 /*! \brief Return the smallest allowed PME grid size for \p pmeOrder */
104 int minimalPmeGridSize(int pmeOrder);
105
106 //! Return whether the grid of \c pme is identical to \c grid_size.
107 bool gmx_pme_grid_matches(const gmx_pme_t& pme, const ivec grid_size);
108
109 /*! \brief Check restrictions on pme_order and the PME grid nkx,nky,nkz.
110  *
111  * With errorsAreFatal=true, an exception or fatal error is generated
112  * on violation of restrictions.
113  * With errorsAreFatal=false, false is returned on violation of restrictions.
114  * When all restrictions are obeyed, true is returned.
115  * Argument useThreads tells if any MPI rank doing PME uses more than 1 threads.
116  * If at calling useThreads is unknown, pass true for conservative checking.
117  *
118  * The PME GPU restrictions are checked separately during pme_gpu_init().
119  */
120 bool gmx_pme_check_restrictions(int  pme_order,
121                                 int  nkx,
122                                 int  nky,
123                                 int  nkz,
124                                 int  numPmeDomainsAlongX,
125                                 bool useThreads,
126                                 bool errorsAreFatal);
127
128 /*! \brief Construct PME data
129  *
130  * \throws   gmx::InconsistentInputError if input grid sizes/PME order are inconsistent.
131  * \returns  Pointer to newly allocated and initialized PME data.
132  *
133  * \todo We should evolve something like a \c GpuManager that holds \c
134  * DeviceInformation* and \c PmeGpuProgram* and perhaps other
135  * related things whose lifetime can/should exceed that of a task (or
136  * perhaps task manager). See Redmine #2522.
137  */
138 gmx_pme_t* gmx_pme_init(const t_commrec*         cr,
139                         const NumPmeDomains&     numPmeDomains,
140                         const t_inputrec*        ir,
141                         gmx_bool                 bFreeEnergy_q,
142                         gmx_bool                 bFreeEnergy_lj,
143                         gmx_bool                 bReproducible,
144                         real                     ewaldcoeff_q,
145                         real                     ewaldcoeff_lj,
146                         int                      nthread,
147                         PmeRunMode               runMode,
148                         PmeGpu*                  pmeGpu,
149                         const DeviceInformation* deviceInfo,
150                         const PmeGpuProgram*     pmeGpuProgram,
151                         const gmx::MDLogger&     mdlog);
152
153 /*! \brief As gmx_pme_init, but takes most settings, except the grid/Ewald coefficients, from
154  * pme_src. This is only called when the PME cut-off/grid size changes.
155  */
156 void gmx_pme_reinit(gmx_pme_t**       pmedata,
157                     const t_commrec*  cr,
158                     gmx_pme_t*        pme_src,
159                     const t_inputrec* ir,
160                     const ivec        grid_size,
161                     real              ewaldcoeff_q,
162                     real              ewaldcoeff_lj);
163
164 /*! \brief Destroys the PME data structure.*/
165 void gmx_pme_destroy(gmx_pme_t* pme);
166
167 /*! \brief Do a PME calculation on a CPU for the long range electrostatics and/or LJ.
168  *
169  * Computes the PME forces and the energy and viral, when requested,
170  * for all atoms in \p coordinates. Forces, when requested, are added
171  * to the buffer \p forces, which is allowed to contain more elements
172  * than the number of elements in \p coordinates.
173  * The meaning of \p flags is defined above, and determines which
174  * parts of the calculation are performed.
175  *
176  * \return 0 indicates all well, non zero is an error code.
177  */
178 int gmx_pme_do(struct gmx_pme_t*              pme,
179                gmx::ArrayRef<const gmx::RVec> coordinates,
180                gmx::ArrayRef<gmx::RVec>       forces,
181                real                           chargeA[],
182                real                           chargeB[],
183                real                           c6A[],
184                real                           c6B[],
185                real                           sigmaA[],
186                real                           sigmaB[],
187                const matrix                   box,
188                const t_commrec*               cr,
189                int                            maxshift_x,
190                int                            maxshift_y,
191                t_nrnb*                        nrnb,
192                gmx_wallcycle*                 wcycle,
193                matrix                         vir_q,
194                matrix                         vir_lj,
195                real*                          energy_q,
196                real*                          energy_lj,
197                real                           lambda_q,
198                real                           lambda_lj,
199                real*                          dvdlambda_q,
200                real*                          dvdlambda_lj,
201                const gmx::StepWorkload&       stepWork);
202
203 /*! \brief Calculate the PME grid energy V for n charges.
204  *
205  * The potential (found in \p pme) must have been found already with a
206  * call to gmx_pme_do(). Note that the charges are not spread on the grid in the
207  * pme struct. Currently does not work in parallel or with free
208  * energy.
209  */
210 void gmx_pme_calc_energy(gmx_pme_t* pme, gmx::ArrayRef<const gmx::RVec> x, gmx::ArrayRef<const real> q, real* V);
211
212 /*! \brief
213  * This function updates the local atom data on GPU after DD (charges, coordinates, etc.).
214  * TODO: it should update the PME CPU atom data as well.
215  * (currently PME CPU call gmx_pme_do() gets passed the input pointers for each computation).
216  *
217  * \param[in,out] pme        The PME structure.
218  * \param[in]     numAtoms   The number of particles.
219  * \param[in]     charges    The pointer to the array of particle charges.
220  */
221 void gmx_pme_reinit_atoms(gmx_pme_t* pme, int numAtoms, const real* charges);
222
223 /* A block of PME GPU functions */
224
225 /*! \brief Checks whether the GROMACS build allows to run PME on GPU.
226  * TODO: this partly duplicates an internal PME assert function
227  * pme_gpu_check_restrictions(), except that works with a
228  * formed gmx_pme_t structure. Should that one go away/work with inputrec?
229  *
230  * \param[out] error   If non-null, the error message when PME is not supported on GPU.
231  *
232  * \returns true if PME can run on GPU on this build, false otherwise.
233  */
234 bool pme_gpu_supports_build(std::string* error);
235
236 /*! \brief Checks whether the detected (GPU) hardware allows to run PME on GPU.
237  *
238  * \param[in]  hwinfo  Information about the detected hardware
239  * \param[out] error   If non-null, the error message when PME is not supported on GPU.
240  *
241  * \returns true if PME can run on GPU on this build, false otherwise.
242  */
243 bool pme_gpu_supports_hardware(const gmx_hw_info_t& hwinfo, std::string* error);
244
245 /*! \brief Checks whether the input system allows to run PME on GPU.
246  * TODO: this partly duplicates an internal PME assert function
247  * pme_gpu_check_restrictions(), except that works with a
248  * formed gmx_pme_t structure. Should that one go away/work with inputrec?
249  *
250  * \param[in]  ir     Input system.
251  * \param[in]  mtop   Complete system topology to check if an FE simulation perturbs charges.
252  * \param[out] error  If non-null, the error message if the input is not supported on GPU.
253  *
254  * \returns true if PME can run on GPU with this input, false otherwise.
255  */
256 bool pme_gpu_supports_input(const t_inputrec& ir, const gmx_mtop_t& mtop, std::string* error);
257
258 /*! \brief
259  * Returns the active PME codepath (CPU, GPU, mixed).
260  * \todo This is a rather static data that should be managed by the higher level task scheduler.
261  *
262  * \param[in]  pme            The PME data structure.
263  * \returns active PME codepath.
264  */
265 PmeRunMode pme_run_mode(const gmx_pme_t* pme);
266
267 /*! \libinternal \brief
268  * Return the pinning policy appropriate for this build configuration
269  * for relevant buffers used for PME task on this rank (e.g. running
270  * on a GPU). */
271 gmx::PinningPolicy pme_get_pinning_policy();
272
273 /*! \brief
274  * Tells if PME is enabled to run on GPU (not necessarily active at the moment).
275  * \todo This is a rather static data that should be managed by the hardware assignment manager.
276  * For now, it is synonymous with the active PME codepath (in the absence of dynamic switching).
277  *
278  * \param[in]  pme            The PME data structure.
279  * \returns true if PME can run on GPU, false otherwise.
280  */
281 inline bool pme_gpu_task_enabled(const gmx_pme_t* pme)
282 {
283     return (pme != nullptr) && (pme_run_mode(pme) != PmeRunMode::CPU);
284 }
285
286 /*! \brief Returns the size of the padding needed by GPU version of PME in the coordinates array.
287  *
288  * \param[in]  pme  The PME data structure.
289  */
290 GPU_FUNC_QUALIFIER int pme_gpu_get_padding_size(const gmx_pme_t* GPU_FUNC_ARGUMENT(pme))
291         GPU_FUNC_TERM_WITH_RETURN(0);
292
293 // The following functions are all the PME GPU entry points,
294 // currently inlining to nothing on non-CUDA builds.
295
296 /*! \brief
297  * Resets the PME GPU timings. To be called at the reset step.
298  *
299  * \param[in] pme            The PME structure.
300  */
301 GPU_FUNC_QUALIFIER void pme_gpu_reset_timings(const gmx_pme_t* GPU_FUNC_ARGUMENT(pme)) GPU_FUNC_TERM;
302
303 /*! \brief
304  * Copies the PME GPU timings to the gmx_wallclock_gpu_pme_t structure (for log output). To be called at the run end.
305  *
306  * \param[in] pme               The PME structure.
307  * \param[in] timings           The gmx_wallclock_gpu_pme_t structure.
308  */
309 GPU_FUNC_QUALIFIER void pme_gpu_get_timings(const gmx_pme_t* GPU_FUNC_ARGUMENT(pme),
310                                             gmx_wallclock_gpu_pme_t* GPU_FUNC_ARGUMENT(timings)) GPU_FUNC_TERM;
311
312 /* The main PME GPU functions */
313
314 /*! \brief
315  * Prepares PME on GPU computation (updating the box if needed)
316  * \param[in] pme               The PME data structure.
317  * \param[in] box               The unit cell box.
318  * \param[in] wcycle            The wallclock counter.
319  * \param[in] stepWork          The required work for this simulation step
320  */
321 GPU_FUNC_QUALIFIER void pme_gpu_prepare_computation(gmx_pme_t*     GPU_FUNC_ARGUMENT(pme),
322                                                     const matrix   GPU_FUNC_ARGUMENT(box),
323                                                     gmx_wallcycle* GPU_FUNC_ARGUMENT(wcycle),
324                                                     const gmx::StepWorkload& GPU_FUNC_ARGUMENT(stepWork)) GPU_FUNC_TERM;
325
326 /*! \brief
327  * Launches first stage of PME on GPU - spreading kernel.
328  *
329  * \param[in] pme                The PME data structure.
330  * \param[in] xReadyOnDevice     Event synchronizer indicating that the coordinates are ready in the device memory; nullptr allowed only on separate PME ranks.
331  * \param[in] wcycle             The wallclock counter.
332  */
333 GPU_FUNC_QUALIFIER void pme_gpu_launch_spread(gmx_pme_t*            GPU_FUNC_ARGUMENT(pme),
334                                               GpuEventSynchronizer* GPU_FUNC_ARGUMENT(xReadyOnDevice),
335                                               gmx_wallcycle* GPU_FUNC_ARGUMENT(wcycle)) GPU_FUNC_TERM;
336
337 /*! \brief
338  * Launches middle stages of PME (FFT R2C, solving, FFT C2R) either on GPU or on CPU, depending on the run mode.
339  *
340  * \param[in] pme               The PME data structure.
341  * \param[in] wcycle            The wallclock counter.
342  * \param[in] stepWork          The required work for this simulation step
343  */
344 GPU_FUNC_QUALIFIER void
345 pme_gpu_launch_complex_transforms(gmx_pme_t*               GPU_FUNC_ARGUMENT(pme),
346                                   gmx_wallcycle*           GPU_FUNC_ARGUMENT(wcycle),
347                                   const gmx::StepWorkload& GPU_FUNC_ARGUMENT(stepWork)) GPU_FUNC_TERM;
348
349 /*! \brief
350  * Launches last stage of PME on GPU - force gathering and D2H force transfer.
351  *
352  * \param[in]  pme               The PME data structure.
353  * \param[in]  wcycle            The wallclock counter.
354  */
355 GPU_FUNC_QUALIFIER void pme_gpu_launch_gather(const gmx_pme_t* GPU_FUNC_ARGUMENT(pme),
356                                               gmx_wallcycle* GPU_FUNC_ARGUMENT(wcycle)) GPU_FUNC_TERM;
357
358 /*! \brief
359  * Attempts to complete PME GPU tasks.
360  *
361  * The \p completionKind argument controls whether the function blocks until all
362  * PME GPU tasks enqueued completed (as pme_gpu_wait_finish_task() does) or only
363  * checks and returns immediately if they did not.
364  * When blocking or the tasks have completed it also gets the output forces
365  * by assigning the ArrayRef to the \p forces pointer passed in.
366  * Virial/energy are also outputs if they were to be computed.
367  *
368  * \param[in]  pme             The PME data structure.
369  * \param[in]  stepWork        The required work for this simulation step
370  * \param[in]  wcycle          The wallclock counter.
371  * \param[out] forceWithVirial The output force and virial
372  * \param[out] enerd           The output energies
373  * \param[in]  completionKind  Indicates whether PME task completion should only be checked rather
374  *                             than waited for
375  * \returns                    True if the PME GPU tasks have completed
376  */
377 GPU_FUNC_QUALIFIER bool pme_gpu_try_finish_task(gmx_pme_t*               GPU_FUNC_ARGUMENT(pme),
378                                                 const gmx::StepWorkload& GPU_FUNC_ARGUMENT(stepWork),
379                                                 gmx_wallcycle*           GPU_FUNC_ARGUMENT(wcycle),
380                                                 gmx::ForceWithVirial* GPU_FUNC_ARGUMENT(forceWithVirial),
381                                                 gmx_enerdata_t*       GPU_FUNC_ARGUMENT(enerd),
382                                                 GpuTaskCompletion GPU_FUNC_ARGUMENT(completionKind))
383         GPU_FUNC_TERM_WITH_RETURN(false);
384
385 /*! \brief
386  * Blocks until PME GPU tasks are completed, and gets the output forces and virial/energy
387  * (if they were to be computed).
388  *
389  * \param[in]  pme             The PME data structure.
390  * \param[in]  stepWork        The required work for this simulation step
391  * \param[in]  wcycle          The wallclock counter.
392  * \param[out] forceWithVirial The output force and virial
393  * \param[out] enerd           The output energies
394  */
395 GPU_FUNC_QUALIFIER void pme_gpu_wait_and_reduce(gmx_pme_t*               GPU_FUNC_ARGUMENT(pme),
396                                                 const gmx::StepWorkload& GPU_FUNC_ARGUMENT(stepWork),
397                                                 gmx_wallcycle*           GPU_FUNC_ARGUMENT(wcycle),
398                                                 gmx::ForceWithVirial* GPU_FUNC_ARGUMENT(forceWithVirial),
399                                                 gmx_enerdata_t* GPU_FUNC_ARGUMENT(enerd)) GPU_FUNC_TERM;
400
401 /*! \brief
402  * The PME GPU reinitialization function that is called both at the end of any PME computation and on any load balancing.
403  *
404  * Clears the internal grid and energy/virial buffers; it is not safe to start
405  * the PME computation without calling this.
406  * Note that unlike in the nbnxn module, the force buffer does not need clearing.
407  *
408  * \todo Rename this function to *clear* -- it clearly only does output resetting
409  * and we should be clear about what the function does..
410  *
411  * \param[in] pme            The PME data structure.
412  * \param[in] wcycle         The wallclock counter.
413  */
414 GPU_FUNC_QUALIFIER void pme_gpu_reinit_computation(const gmx_pme_t* GPU_FUNC_ARGUMENT(pme),
415                                                    gmx_wallcycle* GPU_FUNC_ARGUMENT(wcycle)) GPU_FUNC_TERM;
416
417 /*! \brief Set pointer to device copy of coordinate data.
418  * \param[in] pme            The PME data structure.
419  * \param[in] d_x            The pointer to the positions buffer to be set
420  */
421 GPU_FUNC_QUALIFIER void pme_gpu_set_device_x(const gmx_pme_t*        GPU_FUNC_ARGUMENT(pme),
422                                              DeviceBuffer<gmx::RVec> GPU_FUNC_ARGUMENT(d_x)) GPU_FUNC_TERM;
423
424 /*! \brief Get pointer to device copy of force data.
425  * \param[in] pme            The PME data structure.
426  * \returns                  Pointer to force data
427  */
428 GPU_FUNC_QUALIFIER void* pme_gpu_get_device_f(const gmx_pme_t* GPU_FUNC_ARGUMENT(pme))
429         GPU_FUNC_TERM_WITH_RETURN(nullptr);
430
431 /*! \brief Returns the pointer to the GPU stream.
432  *  \param[in] pme            The PME data structure.
433  *  \returns                  Pointer to GPU stream object.
434  */
435 GPU_FUNC_QUALIFIER void* pme_gpu_get_device_stream(const gmx_pme_t* GPU_FUNC_ARGUMENT(pme))
436         GPU_FUNC_TERM_WITH_RETURN(nullptr);
437
438 /*! \brief Returns the pointer to the GPU context.
439  *  \param[in] pme            The PME data structure.
440  *  \returns                  Pointer to GPU context object.
441  */
442 GPU_FUNC_QUALIFIER void* pme_gpu_get_device_context(const gmx_pme_t* GPU_FUNC_ARGUMENT(pme))
443         GPU_FUNC_TERM_WITH_RETURN(nullptr);
444
445 /*! \brief Get pointer to the device synchronizer object that allows syncing on PME force calculation completion
446  * \param[in] pme            The PME data structure.
447  * \returns                  Pointer to sychronizer
448  */
449 GPU_FUNC_QUALIFIER GpuEventSynchronizer* pme_gpu_get_f_ready_synchronizer(const gmx_pme_t* GPU_FUNC_ARGUMENT(pme))
450         GPU_FUNC_TERM_WITH_RETURN(nullptr);
451
452 #endif