Rename GpuBonded into ListedForcesGpu
[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,2021, 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/nbnxm/atomdata.h"
51 #include "gromacs/utility/basedefinitions.h"
52 #include "gromacs/utility/real.h"
53
54 #include "nbnxm.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 ListedForcesGpu;
64 class StepWorkload;
65 } // namespace gmx
66
67 namespace Nbnxm
68 {
69
70 class Grid;
71
72 /*! \brief Returns true if LJ combination rules are used in the non-bonded kernels.
73  *
74  *  \param[in] vdwType  The VdW interaction/implementation type as defined by VdwType
75  *                      enumeration.
76  *
77  * \returns Whether combination rules are used by the run.
78  */
79 static inline bool useLjCombRule(const enum VdwType vdwType)
80 {
81     return (vdwType == VdwType::CutCombGeom || vdwType == VdwType::CutCombLB);
82 }
83
84 /*! \brief
85  * Launch asynchronously the xq buffer host to device copy.
86  *
87  * The nonlocal copy is skipped if there is no dependent work to do,
88  * neither non-local nonbonded interactions nor bonded GPU work.
89  *
90  * \param [in]    nb        GPU nonbonded data.
91  * \param [in]    nbdata    Host-side atom data structure.
92  * \param [in]    aloc      Atom locality flag.
93  */
94 GPU_FUNC_QUALIFIER
95 void gpu_copy_xq_to_gpu(NbnxmGpu gmx_unused*          nb,
96                         const struct nbnxn_atomdata_t gmx_unused* nbdata,
97                         gmx::AtomLocality gmx_unused              aloc) GPU_FUNC_TERM;
98
99 /*! \brief
100  * Launch asynchronously the nonbonded force calculations.
101  *
102  *  Also launches the initial pruning of a fresh list after search.
103  *
104  *  The local and non-local interaction calculations are launched in two
105  *  separate streams. If there is no work (i.e. empty pair list), the
106  *  force kernel launch is omitted.
107  *
108  */
109 GPU_FUNC_QUALIFIER
110 void gpu_launch_kernel(NbnxmGpu gmx_unused*    nb,
111                        const gmx::StepWorkload gmx_unused& stepWork,
112                        gmx::InteractionLocality gmx_unused iloc) GPU_FUNC_TERM;
113
114 /*! \brief
115  * Launch asynchronously the nonbonded prune-only kernel.
116  *
117  *  The local and non-local list pruning are launched in their separate streams.
118  *
119  *  Notes for future scheduling tuning:
120  *  Currently we schedule the dynamic pruning between two MD steps *after* both local and
121  *  nonlocal force D2H transfers completed. We could launch already after the cpyback
122  *  is launched, but we want to avoid prune kernels (especially in the non-local
123  *  high prio-stream) competing with nonbonded work.
124  *
125  *  However, this is not ideal as this schedule does not expose the available
126  *  concurrency. The dynamic pruning kernel:
127  *    - should be allowed to overlap with any task other than force compute, including
128  *      transfers (F D2H and the next step's x H2D as well as force clearing).
129  *    - we'd prefer to avoid competition with non-bonded force kernels belonging
130  *      to the same rank and ideally other ranks too.
131  *
132  *  In the most general case, the former would require scheduling pruning in a separate
133  *  stream and adding additional event sync points to ensure that force kernels read
134  *  consistent pair list data. This would lead to some overhead (due to extra
135  *  cudaStreamWaitEvent calls, 3-5 us/call) which we might be able to live with.
136  *  The gains from additional overlap might not be significant as long as
137  *  update+constraints anyway takes longer than pruning, but there will still
138  *  be use-cases where more overlap may help (e.g. multiple ranks per GPU,
139  *  no/hbonds only constraints).
140  *  The above second point is harder to address given that multiple ranks will often
141  *  share a GPU. Ranks that complete their nonbondeds sooner can schedule pruning earlier
142  *  and without a third priority level it is difficult to avoid some interference of
143  *  prune kernels with force tasks (in particular preemption of low-prio local force task).
144  *
145  * \param [inout] nb        GPU nonbonded data.
146  * \param [in]    iloc      Interaction locality flag.
147  * \param [in]    numParts  Number of parts the pair list is split into in the rolling kernel.
148  */
149 GPU_FUNC_QUALIFIER
150 void gpu_launch_kernel_pruneonly(NbnxmGpu gmx_unused*                nb,
151                                  gmx::InteractionLocality gmx_unused iloc,
152                                  int gmx_unused                      numParts) GPU_FUNC_TERM;
153
154 /*! \brief
155  * Launch asynchronously the download of short-range forces from the GPU
156  * (and energies/shift forces if required).
157  */
158 GPU_FUNC_QUALIFIER
159 void gpu_launch_cpyback(NbnxmGpu gmx_unused* nb,
160                         nbnxn_atomdata_t gmx_unused* nbatom,
161                         const gmx::StepWorkload gmx_unused& stepWork,
162                         gmx::AtomLocality gmx_unused        aloc) GPU_FUNC_TERM;
163
164 /*! \brief Attempts to complete nonbonded GPU task.
165  *
166  *  This function attempts to complete the nonbonded task (both GPU and CPU auxiliary work).
167  *  Success, i.e. that the tasks completed and results are ready to be consumed, is signaled
168  *  by the return value (always true if blocking wait mode requested).
169  *
170  *  The \p completionKind parameter controls whether the behavior is non-blocking
171  *  (achieved by passing GpuTaskCompletion::Check) or blocking wait until the results
172  *  are ready (when GpuTaskCompletion::Wait is passed).
173  *  As the "Check" mode the function will return immediately if the GPU stream
174  *  still contain tasks that have not completed, it allows more flexible overlapping
175  *  of work on the CPU with GPU execution.
176  *
177  *  Note that it is only safe to use the results, and to continue to the next MD
178  *  step when this function has returned true which indicates successful completion of
179  *  - All nonbonded GPU tasks: both compute and device transfer(s)
180  *  - auxiliary tasks: updating the internal module state (timing accumulation, list pruning states) and
181  *  - internal staging reduction of (\p fshift, \p e_el, \p e_lj).
182  *
183  * In GpuTaskCompletion::Check mode this function does the timing and keeps correct count
184  * for the nonbonded task (incrementing only once per taks), in the GpuTaskCompletion::Wait mode
185  * timing is expected to be done in the caller.
186  *
187  *  TODO: improve the handling of outputs e.g. by ensuring that this function explcitly returns the
188  *  force buffer (instead of that being passed only to nbnxn_gpu_launch_cpyback()) and by returning
189  *  the energy and Fshift contributions for some external/centralized reduction.
190  *
191  * \param[in]  nb             The nonbonded data GPU structure
192  * \param[in]  stepWork       Step schedule flags
193  * \param[in]  aloc           Atom locality identifier
194  * \param[out] e_lj           Pointer to the LJ energy output to accumulate into
195  * \param[out] e_el           Pointer to the electrostatics energy output to accumulate into
196  * \param[out] shiftForces    Shift forces buffer to accumulate into
197  * \param[in]  completionKind Indicates whether nnbonded task completion should only be checked rather than waited for
198  * \param[out] wcycle         Pointer to wallcycle data structure
199  * \returns                   True if the nonbonded tasks associated with \p aloc locality have completed
200  */
201 GPU_FUNC_QUALIFIER
202 bool gpu_try_finish_task(NbnxmGpu gmx_unused*    nb,
203                          const gmx::StepWorkload gmx_unused& stepWork,
204                          gmx::AtomLocality gmx_unused        aloc,
205                          real gmx_unused* e_lj,
206                          real gmx_unused*                    e_el,
207                          gmx::ArrayRef<gmx::RVec> gmx_unused shiftForces,
208                          GpuTaskCompletion gmx_unused        completionKind,
209                          gmx_wallcycle gmx_unused* wcycle) GPU_FUNC_TERM_WITH_RETURN(false);
210
211 /*! \brief  Completes the nonbonded GPU task blocking until GPU tasks and data
212  * transfers to finish.
213  *
214  * Also does timing accounting and reduction of the internal staging buffers.
215  * As this is called at the end of the step, it also resets the pair list and
216  * pruning flags.
217  *
218  * \param[in] nb The nonbonded data GPU structure
219  * \param[in]  stepWork        Step schedule flags
220  * \param[in] aloc Atom locality identifier
221  * \param[out] e_lj Pointer to the LJ energy output to accumulate into
222  * \param[out] e_el Pointer to the electrostatics energy output to accumulate into
223  * \param[out] shiftForces Shift forces buffer to accumulate into
224  * \param[out] wcycle         Pointer to wallcycle data structure               */
225 GPU_FUNC_QUALIFIER
226 float gpu_wait_finish_task(NbnxmGpu gmx_unused*    nb,
227                            const gmx::StepWorkload gmx_unused& stepWork,
228                            gmx::AtomLocality gmx_unused        aloc,
229                            real gmx_unused* e_lj,
230                            real gmx_unused*                    e_el,
231                            gmx::ArrayRef<gmx::RVec> gmx_unused shiftForces,
232                            gmx_wallcycle gmx_unused* wcycle) GPU_FUNC_TERM_WITH_RETURN(0.0);
233
234 /*! \brief Initialization for X buffer operations on GPU.
235  * Called on the NS step and performs (re-)allocations and memory copies. !*/
236 GPU_FUNC_QUALIFIER
237 void nbnxn_gpu_init_x_to_nbat_x(const Nbnxm::GridSet gmx_unused& gridSet,
238                                 NbnxmGpu gmx_unused* gpu_nbv) GPU_FUNC_TERM;
239
240 /*! \brief X buffer operations on GPU: performs conversion from rvec to nb format.
241  *
242  * \param[in]     grid             Grid to be converted.
243  * \param[in,out] gpu_nbv          The nonbonded data GPU structure.
244  * \param[in]     d_x              Device-side coordinates in plain rvec format.
245  * \param[in]     xReadyOnDevice   Event synchronizer indicating that the coordinates are ready in
246  * the device memory.
247  * \param[in]     locality         Copy coordinates for local or non-local atoms.
248  * \param[in]     gridId           Index of the grid being converted.
249  * \param[in]     numColumnsMax    Maximum number of columns in the grid.
250  * \param[in]     mustInsertNonLocalDependency Whether synchronization between local and non-local
251  * streams should be added. Typically, true if and only if that is the last grid in gridset.
252  */
253 GPU_FUNC_QUALIFIER
254 void nbnxn_gpu_x_to_nbat_x(const Nbnxm::Grid gmx_unused& grid,
255                            NbnxmGpu gmx_unused*               gpu_nbv,
256                            DeviceBuffer<gmx::RVec> gmx_unused d_x,
257                            GpuEventSynchronizer gmx_unused* xReadyOnDevice,
258                            gmx::AtomLocality gmx_unused     locality,
259                            int gmx_unused                   gridId,
260                            int gmx_unused                   numColumnsMax,
261                            bool gmx_unused mustInsertNonLocalDependency) GPU_FUNC_TERM;
262
263 /*! \brief Sync the nonlocal stream with dependent tasks in the local queue.
264  *
265  *  As the point where the local stream tasks can be considered complete happens
266  *  at the same call point where the nonlocal stream should be synced with the
267  *  the local, this function records the event if called with the local stream as
268  *  argument and inserts in the GPU stream a wait on the event on the nonlocal.
269  *
270  * \param[in] nb                   The nonbonded data GPU structure
271  * \param[in] interactionLocality  Local or NonLocal sync point
272  */
273 GPU_FUNC_QUALIFIER
274 void nbnxnInsertNonlocalGpuDependency(NbnxmGpu gmx_unused*                nb,
275                                       gmx::InteractionLocality gmx_unused interactionLocality) GPU_FUNC_TERM;
276
277 /*! \brief Set up internal flags that indicate what type of short-range work there is.
278  *
279  * As nonbondeds and bondeds share input/output buffers and GPU queues,
280  * both are considered when checking for work in the current domain.
281  *
282  * This function is expected to be called every time the work-distribution
283  * can change (i.e. at search/domain decomposition steps).
284  *
285  * \param[inout]  nb               Pointer to the nonbonded GPU data structure
286  * \param[in]     listedForcesGpu  Pointer to the GPU bonded data structure
287  * \param[in]     iLocality        Interaction locality identifier
288  */
289 GPU_FUNC_QUALIFIER
290 void setupGpuShortRangeWork(NbnxmGpu gmx_unused*       nb,
291                             const gmx::ListedForcesGpu gmx_unused* listedForcesGpu,
292                             gmx::InteractionLocality gmx_unused    iLocality) GPU_FUNC_TERM;
293
294 /*! \brief Returns true if there is GPU short-range work for the given interaction locality.
295  *
296  * Note that as, unlike nonbonded tasks, bonded tasks are not split into local/nonlocal,
297  * and therefore if there are GPU offloaded bonded interactions, this function will return
298  * true for both local and nonlocal atom range.
299  *
300  * \param[inout]  nb                   Pointer to the nonbonded GPU data structure
301  * \param[in]     interactionLocality  Interaction locality identifier
302  *
303  * \return Whether there is short range work for a given locality.
304  */
305 GPU_FUNC_QUALIFIER
306 bool haveGpuShortRangeWork(const NbnxmGpu gmx_unused* nb, gmx::InteractionLocality gmx_unused interactionLocality)
307         GPU_FUNC_TERM_WITH_RETURN(false);
308
309 } // namespace Nbnxm
310 #endif