035d5f1ae8edf13cfb969920a15bfbc13adc7251
[alexxy/gromacs.git] / src / gromacs / nbnxm / nbnxm_gpu.h
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 2012,2013,2014,2015,2017 by the GROMACS development team.
5  * Copyright (c) 2018,2019,2020, by the GROMACS development team, led by
6  * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
7  * and including many others, as listed in the AUTHORS file in the
8  * top-level source directory and at http://www.gromacs.org.
9  *
10  * GROMACS is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU Lesser General Public License
12  * as published by the Free Software Foundation; either version 2.1
13  * of the License, or (at your option) any later version.
14  *
15  * GROMACS is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18  * Lesser General Public License for more details.
19  *
20  * You should have received a copy of the GNU Lesser General Public
21  * License along with GROMACS; if not, see
22  * http://www.gnu.org/licenses, or write to the Free Software Foundation,
23  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.
24  *
25  * If you want to redistribute modifications to GROMACS, please
26  * consider that scientific software is very special. Version
27  * control is crucial - bugs must be traceable. We will be happy to
28  * consider code for inclusion in the official distribution, but
29  * derived work must not be called official GROMACS. Details are found
30  * in the README & COPYING files - if they are missing, get the
31  * official version at http://www.gromacs.org.
32  *
33  * To help us fund GROMACS development, we humbly ask that you cite
34  * the research papers on the package. Check out http://www.gromacs.org.
35  */
36 /*! \libinternal \file
37  *  \brief Declare interface for GPU execution for NBNXN module
38  *
39  *  \author Szilard Pall <pall.szilard@gmail.com>
40  *  \author Mark Abraham <mark.j.abraham@gmail.com>
41  *  \ingroup module_nbnxm
42  */
43
44 #ifndef GMX_NBNXM_NBNXM_GPU_H
45 #define GMX_NBNXM_NBNXM_GPU_H
46
47 #include "gromacs/gpu_utils/gpu_macros.h"
48 #include "gromacs/math/vectypes.h"
49 #include "gromacs/mdtypes/locality.h"
50 #include "gromacs/utility/basedefinitions.h"
51 #include "gromacs/utility/real.h"
52
53 #include "atomdata.h"
54 #include "gpu_types.h"
55
56 struct interaction_const_t;
57 struct nbnxn_atomdata_t;
58 struct gmx_wallcycle;
59 enum class GpuTaskCompletion;
60
61 namespace gmx
62 {
63 class GpuBonded;
64 class StepWorkload;
65 } // namespace gmx
66
67 namespace Nbnxm
68 {
69
70 class Grid;
71
72 /*! \brief
73  * Launch asynchronously the xq buffer host to device copy.
74  *
75  * The nonlocal copy is skipped if there is no dependent work to do,
76  * neither non-local nonbonded interactions nor bonded GPU work.
77  *
78  * \param [in]    nb        GPU nonbonded data.
79  * \param [in]    nbdata    Host-side atom data structure.
80  * \param [in]    aloc      Atom locality flag.
81  */
82 GPU_FUNC_QUALIFIER
83 void gpu_copy_xq_to_gpu(gmx_nbnxn_gpu_t gmx_unused*   nb,
84                         const struct nbnxn_atomdata_t gmx_unused* nbdata,
85                         gmx::AtomLocality gmx_unused aloc) GPU_FUNC_TERM;
86
87 /*! \brief
88  * Launch asynchronously the nonbonded force calculations.
89  *
90  *  Also launches the initial pruning of a fresh list after search.
91  *
92  *  The local and non-local interaction calculations are launched in two
93  *  separate streams. If there is no work (i.e. empty pair list), the
94  *  force kernel launch is omitted.
95  *
96  */
97 GPU_FUNC_QUALIFIER
98 void gpu_launch_kernel(gmx_nbnxn_gpu_t gmx_unused* nb,
99                        const gmx::StepWorkload gmx_unused& stepWork,
100                        gmx::InteractionLocality gmx_unused iloc) GPU_FUNC_TERM;
101
102 /*! \brief
103  * Launch asynchronously the nonbonded prune-only kernel.
104  *
105  *  The local and non-local list pruning are launched in their separate streams.
106  *
107  *  Notes for future scheduling tuning:
108  *  Currently we schedule the dynamic pruning between two MD steps *after* both local and
109  *  nonlocal force D2H transfers completed. We could launch already after the cpyback
110  *  is launched, but we want to avoid prune kernels (especially in the non-local
111  *  high prio-stream) competing with nonbonded work.
112  *
113  *  However, this is not ideal as this schedule does not expose the available
114  *  concurrency. The dynamic pruning kernel:
115  *    - should be allowed to overlap with any task other than force compute, including
116  *      transfers (F D2H and the next step's x H2D as well as force clearing).
117  *    - we'd prefer to avoid competition with non-bonded force kernels belonging
118  *      to the same rank and ideally other ranks too.
119  *
120  *  In the most general case, the former would require scheduling pruning in a separate
121  *  stream and adding additional event sync points to ensure that force kernels read
122  *  consistent pair list data. This would lead to some overhead (due to extra
123  *  cudaStreamWaitEvent calls, 3-5 us/call) which we might be able to live with.
124  *  The gains from additional overlap might not be significant as long as
125  *  update+constraints anyway takes longer than pruning, but there will still
126  *  be use-cases where more overlap may help (e.g. multiple ranks per GPU,
127  *  no/hbonds only constraints).
128  *  The above second point is harder to address given that multiple ranks will often
129  *  share a GPU. Ranks that complete their nonbondeds sooner can schedule pruning earlier
130  *  and without a third priority level it is difficult to avoid some interference of
131  *  prune kernels with force tasks (in particular preemption of low-prio local force task).
132  *
133  * \param [inout] nb        GPU nonbonded data.
134  * \param [in]    iloc      Interaction locality flag.
135  * \param [in]    numParts  Number of parts the pair list is split into in the rolling kernel.
136  */
137 GPU_FUNC_QUALIFIER
138 void gpu_launch_kernel_pruneonly(gmx_nbnxn_gpu_t gmx_unused* nb,
139                                  gmx::InteractionLocality gmx_unused iloc,
140                                  int gmx_unused numParts) GPU_FUNC_TERM;
141
142 /*! \brief
143  * Launch asynchronously the download of short-range forces from the GPU
144  * (and energies/shift forces if required).
145  */
146 GPU_FUNC_QUALIFIER
147 void gpu_launch_cpyback(gmx_nbnxn_gpu_t gmx_unused* nb,
148                         nbnxn_atomdata_t gmx_unused* nbatom,
149                         const gmx::StepWorkload gmx_unused& stepWork,
150                         gmx::AtomLocality gmx_unused aloc) GPU_FUNC_TERM;
151
152 /*! \brief Attempts to complete nonbonded GPU task.
153  *
154  *  This function attempts to complete the nonbonded task (both GPU and CPU auxiliary work).
155  *  Success, i.e. that the tasks completed and results are ready to be consumed, is signaled
156  *  by the return value (always true if blocking wait mode requested).
157  *
158  *  The \p completionKind parameter controls whether the behavior is non-blocking
159  *  (achieved by passing GpuTaskCompletion::Check) or blocking wait until the results
160  *  are ready (when GpuTaskCompletion::Wait is passed).
161  *  As the "Check" mode the function will return immediately if the GPU stream
162  *  still contain tasks that have not completed, it allows more flexible overlapping
163  *  of work on the CPU with GPU execution.
164  *
165  *  Note that it is only safe to use the results, and to continue to the next MD
166  *  step when this function has returned true which indicates successful completion of
167  *  - All nonbonded GPU tasks: both compute and device transfer(s)
168  *  - auxiliary tasks: updating the internal module state (timing accumulation, list pruning states) and
169  *  - internal staging reduction of (\p fshift, \p e_el, \p e_lj).
170  *
171  * In GpuTaskCompletion::Check mode this function does the timing and keeps correct count
172  * for the nonbonded task (incrementing only once per taks), in the GpuTaskCompletion::Wait mode
173  * timing is expected to be done in the caller.
174  *
175  *  TODO: improve the handling of outputs e.g. by ensuring that this function explcitly returns the
176  *  force buffer (instead of that being passed only to nbnxn_gpu_launch_cpyback()) and by returning
177  *  the energy and Fshift contributions for some external/centralized reduction.
178  *
179  * \param[in]  nb             The nonbonded data GPU structure
180  * \param[in]  stepWork       Step schedule flags
181  * \param[in]  aloc           Atom locality identifier
182  * \param[out] e_lj           Pointer to the LJ energy output to accumulate into
183  * \param[out] e_el           Pointer to the electrostatics energy output to accumulate into
184  * \param[out] shiftForces    Shift forces buffer to accumulate into
185  * \param[in]  completionKind Indicates whether nnbonded task completion should only be checked rather than waited for
186  * \param[out] wcycle         Pointer to wallcycle data structure
187  * \returns                   True if the nonbonded tasks associated with \p aloc locality have completed
188  */
189 GPU_FUNC_QUALIFIER
190 bool gpu_try_finish_task(gmx_nbnxn_gpu_t gmx_unused* nb,
191                          const gmx::StepWorkload gmx_unused& stepWork,
192                          gmx::AtomLocality gmx_unused aloc,
193                          real gmx_unused* e_lj,
194                          real gmx_unused*         e_el,
195                          gmx::ArrayRef<gmx::RVec> gmx_unused shiftForces,
196                          GpuTaskCompletion gmx_unused completionKind,
197                          gmx_wallcycle gmx_unused* wcycle) GPU_FUNC_TERM_WITH_RETURN(false);
198
199 /*! \brief  Completes the nonbonded GPU task blocking until GPU tasks and data
200  * transfers to finish.
201  *
202  * Also does timing accounting and reduction of the internal staging buffers.
203  * As this is called at the end of the step, it also resets the pair list and
204  * pruning flags.
205  *
206  * \param[in] nb The nonbonded data GPU structure
207  * \param[in]  stepWork        Step schedule flags
208  * \param[in] aloc Atom locality identifier
209  * \param[out] e_lj Pointer to the LJ energy output to accumulate into
210  * \param[out] e_el Pointer to the electrostatics energy output to accumulate into
211  * \param[out] shiftForces Shift forces buffer to accumulate into
212  * \param[out] wcycle         Pointer to wallcycle data structure               */
213 GPU_FUNC_QUALIFIER
214 float gpu_wait_finish_task(gmx_nbnxn_gpu_t gmx_unused* nb,
215                            const gmx::StepWorkload gmx_unused& stepWork,
216                            gmx::AtomLocality gmx_unused aloc,
217                            real gmx_unused* e_lj,
218                            real gmx_unused*         e_el,
219                            gmx::ArrayRef<gmx::RVec> gmx_unused shiftForces,
220                            gmx_wallcycle gmx_unused* wcycle) GPU_FUNC_TERM_WITH_RETURN(0.0);
221
222 /*! \brief Selects the Ewald kernel type, analytical or tabulated, single or twin cut-off. */
223 GPU_FUNC_QUALIFIER
224 int nbnxn_gpu_pick_ewald_kernel_type(const interaction_const_t gmx_unused& ic)
225         GPU_FUNC_TERM_WITH_RETURN(-1);
226
227 /*! \brief Initialization for X buffer operations on GPU.
228  * Called on the NS step and performs (re-)allocations and memory copies. !*/
229 CUDA_FUNC_QUALIFIER
230 void nbnxn_gpu_init_x_to_nbat_x(const Nbnxm::GridSet gmx_unused& gridSet,
231                                 gmx_nbnxn_gpu_t gmx_unused* gpu_nbv) CUDA_FUNC_TERM;
232
233 /*! \brief X buffer operations on GPU: performs conversion from rvec to nb format.
234  *
235  * \param[in]     grid             Grid to be converted.
236  * \param[in]     setFillerCoords  If the filler coordinates are used.
237  * \param[in,out] gpu_nbv          The nonbonded data GPU structure.
238  * \param[in]     d_x              Device-side coordinates in plain rvec format.
239  * \param[in]     xReadyOnDevice   Event synchronizer indicating that the coordinates are ready in
240  * the device memory. \param[in]     locality         Copy coordinates for local or non-local atoms.
241  * \param[in]     gridId           Index of the grid being converted.
242  * \param[in]     numColumnsMax    Maximum number of columns in the grid.
243  */
244 CUDA_FUNC_QUALIFIER
245 void nbnxn_gpu_x_to_nbat_x(const Nbnxm::Grid gmx_unused& grid,
246                            bool gmx_unused setFillerCoords,
247                            gmx_nbnxn_gpu_t gmx_unused* gpu_nbv,
248                            DeviceBuffer<float> gmx_unused d_x,
249                            GpuEventSynchronizer gmx_unused* xReadyOnDevice,
250                            gmx::AtomLocality gmx_unused locality,
251                            int gmx_unused gridId,
252                            int gmx_unused numColumnsMax) CUDA_FUNC_TERM;
253
254 /*! \brief Sync the nonlocal stream with dependent tasks in the local queue.
255  * \param[in] nb                   The nonbonded data GPU structure
256  * \param[in] interactionLocality  Local or NonLocal sync point
257  */
258 CUDA_FUNC_QUALIFIER
259 void nbnxnInsertNonlocalGpuDependency(const gmx_nbnxn_gpu_t gmx_unused* nb,
260                                       gmx::InteractionLocality gmx_unused interactionLocality) CUDA_FUNC_TERM;
261
262 /*! \brief Set up internal flags that indicate what type of short-range work there is.
263  *
264  * As nonbondeds and bondeds share input/output buffers and GPU queues,
265  * both are considered when checking for work in the current domain.
266  *
267  * This function is expected to be called every time the work-distribution
268  * can change (i.e. at search/domain decomposition steps).
269  *
270  * \param[inout]  nb         Pointer to the nonbonded GPU data structure
271  * \param[in]     gpuBonded  Pointer to the GPU bonded data structure
272  * \param[in]     iLocality  Interaction locality identifier
273  */
274 GPU_FUNC_QUALIFIER
275 void setupGpuShortRangeWork(gmx_nbnxn_gpu_t gmx_unused* nb,
276                             const gmx::GpuBonded gmx_unused* gpuBonded,
277                             gmx::InteractionLocality gmx_unused iLocality) GPU_FUNC_TERM;
278
279 /*! \brief Returns true if there is GPU short-range work for the given atom locality.
280  *
281  * Note that as, unlike nonbonded tasks, bonded tasks are not split into local/nonlocal,
282  * and therefore if there are GPU offloaded bonded interactions, this function will return
283  * true for both local and nonlocal atom range.
284  *
285  * \param[inout]  nb        Pointer to the nonbonded GPU data structure
286  * \param[in]     aLocality Atom locality identifier
287  */
288 GPU_FUNC_QUALIFIER
289 bool haveGpuShortRangeWork(const gmx_nbnxn_gpu_t gmx_unused* nb, gmx::AtomLocality gmx_unused aLocality)
290         GPU_FUNC_TERM_WITH_RETURN(false);
291
292 /*! \brief Initialization for F buffer operations on GPU */
293 CUDA_FUNC_QUALIFIER
294 void nbnxn_gpu_init_add_nbat_f_to_f(const int gmx_unused* cell,
295                                     gmx_nbnxn_gpu_t gmx_unused* gpu_nbv,
296                                     int gmx_unused       natoms_total,
297                                     GpuEventSynchronizer gmx_unused* localReductionDone) CUDA_FUNC_TERM;
298
299 /*! \brief Force buffer operations on GPU.
300  *
301  * Transforms non-bonded forces into plain rvec format and add all the force components to the total
302  * force buffer
303  *
304  * \param[in]   atomLocality         If the reduction should be performed on local or non-local atoms.
305  * \param[in]   totalForcesDevice    Device buffer to accumulate resulting force.
306  * \param[in]   gpu_nbv              The NBNXM GPU data structure.
307  * \param[in]   pmeForcesDevice      Device buffer with PME forces.
308  * \param[in]   dependencyList       List of synchronizers that represent the dependencies the reduction task needs to sync on.
309  * \param[in]   atomStart            Index of the first atom to reduce forces for.
310  * \param[in]   numAtoms             Number of atoms to reduce forces for.
311  * \param[in]   useGpuFPmeReduction  Whether PME forces should be added.
312  * \param[in]   accumulateForce      Whether there are usefull data already in the total force buffer.
313  *
314  */
315 CUDA_FUNC_QUALIFIER
316 void nbnxn_gpu_add_nbat_f_to_f(gmx::AtomLocality gmx_unused atomLocality,
317                                DeviceBuffer<float> gmx_unused totalForcesDevice,
318                                gmx_nbnxn_gpu_t gmx_unused* gpu_nbv,
319                                void gmx_unused*                           pmeForcesDevice,
320                                gmx::ArrayRef<GpuEventSynchronizer* const> gmx_unused dependencyList,
321                                int gmx_unused atomStart,
322                                int gmx_unused numAtoms,
323                                bool gmx_unused useGpuFPmeReduction,
324                                bool gmx_unused accumulateForce) CUDA_FUNC_TERM;
325
326 /*! \brief sync CPU thread on coordinate copy to device
327  * \param[in] nb                   The nonbonded data GPU structure
328  */
329 CUDA_FUNC_QUALIFIER
330 void nbnxn_wait_x_on_device(gmx_nbnxn_gpu_t gmx_unused* nb) CUDA_FUNC_TERM;
331
332 } // namespace Nbnxm
333 #endif