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