2a2a394cae417fba976f71d7637425057d8dee48
[alexxy/gromacs.git] / src / gromacs / nbnxm / nbnxm_gpu_data_mgmt.cpp
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 2012,2013,2014,2015,2016 by the GROMACS development team.
5  * Copyright (c) 2017,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 /*! \internal \file
37  *  \brief Define common implementation of nbnxm_gpu_data_mgmt.h
38  *
39  *  \author Anca Hamuraru <anca@streamcomputing.eu>
40  *  \author Dimitrios Karkoulis <dimitris.karkoulis@gmail.com>
41  *  \author Teemu Virolainen <teemu@streamcomputing.eu>
42  *  \author Szilárd Páll <pall.szilard@gmail.com>
43  *  \author Artem Zhmurov <zhmurov@gmail.com>
44  *
45  *  \ingroup module_nbnxm
46  */
47 #include "gmxpre.h"
48
49 #include "config.h"
50
51 #if GMX_GPU_CUDA
52 #    include "cuda/nbnxm_cuda_types.h"
53 #endif
54
55 #if GMX_GPU_OPENCL
56 #    include "opencl/nbnxm_ocl_types.h"
57 #endif
58
59 #include "nbnxm_gpu_data_mgmt.h"
60
61 #include "gromacs/hardware/device_information.h"
62 #include "gromacs/mdtypes/interaction_const.h"
63 #include "gromacs/nbnxm/gpu_data_mgmt.h"
64 #include "gromacs/timing/gpu_timing.h"
65 #include "gromacs/utility/cstringutil.h"
66
67 #include "nbnxm_gpu.h"
68 #include "pairlistsets.h"
69
70 namespace Nbnxm
71 {
72
73 void init_ewald_coulomb_force_table(const EwaldCorrectionTables& tables,
74                                     NBParamGpu*                  nbp,
75                                     const DeviceContext&         deviceContext)
76 {
77     if (nbp->coulomb_tab)
78     {
79         destroyParamLookupTable(&nbp->coulomb_tab, nbp->coulomb_tab_texobj);
80     }
81
82     nbp->coulomb_tab_scale = tables.scale;
83     initParamLookupTable(
84             &nbp->coulomb_tab, &nbp->coulomb_tab_texobj, tables.tableF.data(), tables.tableF.size(), deviceContext);
85 }
86
87 enum ElecType nbnxn_gpu_pick_ewald_kernel_type(const interaction_const_t& ic,
88                                                const DeviceInformation gmx_unused& deviceInfo)
89 {
90     bool bTwinCut = (ic.rcoulomb != ic.rvdw);
91
92     /* Benchmarking/development environment variables to force the use of
93        analytical or tabulated Ewald kernel. */
94     const bool forceAnalyticalEwald = (getenv("GMX_GPU_NB_ANA_EWALD") != nullptr);
95     const bool forceTabulatedEwald  = (getenv("GMX_GPU_NB_TAB_EWALD") != nullptr);
96     const bool forceTwinCutoffEwald = (getenv("GMX_GPU_NB_EWALD_TWINCUT") != nullptr);
97
98     if (forceAnalyticalEwald && forceTabulatedEwald)
99     {
100         gmx_incons(
101                 "Both analytical and tabulated Ewald GPU non-bonded kernels "
102                 "requested through environment variables.");
103     }
104
105     /* By default, use analytical Ewald except with CUDA on NVIDIA CC 7.0 and 8.0.
106      */
107     const bool c_useTabulatedEwaldDefault =
108 #if GMX_GPU_CUDA
109             (deviceInfo.prop.major == 7 && deviceInfo.prop.minor == 0)
110             || (deviceInfo.prop.major == 8 && deviceInfo.prop.minor == 0);
111 #else
112             false;
113 #endif
114     bool bUseAnalyticalEwald = !c_useTabulatedEwaldDefault;
115     if (forceAnalyticalEwald)
116     {
117         bUseAnalyticalEwald = true;
118         if (debug)
119         {
120             fprintf(debug, "Using analytical Ewald GPU kernels\n");
121         }
122     }
123     else if (forceTabulatedEwald)
124     {
125         bUseAnalyticalEwald = false;
126
127         if (debug)
128         {
129             fprintf(debug, "Using tabulated Ewald GPU kernels\n");
130         }
131     }
132
133     /* Use twin cut-off kernels if requested by bTwinCut or the env. var.
134        forces it (use it for debugging/benchmarking only). */
135     if (!bTwinCut && !forceTwinCutoffEwald)
136     {
137         return bUseAnalyticalEwald ? ElecType::EwaldAna : ElecType::EwaldTab;
138     }
139     else
140     {
141         return bUseAnalyticalEwald ? ElecType::EwaldAnaTwin : ElecType::EwaldTabTwin;
142     }
143 }
144
145 void set_cutoff_parameters(NBParamGpu* nbp, const interaction_const_t* ic, const PairlistParams& listParams)
146 {
147     nbp->ewald_beta        = ic->ewaldcoeff_q;
148     nbp->sh_ewald          = ic->sh_ewald;
149     nbp->epsfac            = ic->epsfac;
150     nbp->two_k_rf          = 2.0 * ic->k_rf;
151     nbp->c_rf              = ic->c_rf;
152     nbp->rvdw_sq           = ic->rvdw * ic->rvdw;
153     nbp->rcoulomb_sq       = ic->rcoulomb * ic->rcoulomb;
154     nbp->rlistOuter_sq     = listParams.rlistOuter * listParams.rlistOuter;
155     nbp->rlistInner_sq     = listParams.rlistInner * listParams.rlistInner;
156     nbp->useDynamicPruning = listParams.useDynamicPruning;
157
158     nbp->sh_lj_ewald   = ic->sh_lj_ewald;
159     nbp->ewaldcoeff_lj = ic->ewaldcoeff_lj;
160
161     nbp->rvdw_switch      = ic->rvdw_switch;
162     nbp->dispersion_shift = ic->dispersion_shift;
163     nbp->repulsion_shift  = ic->repulsion_shift;
164     nbp->vdw_switch       = ic->vdw_switch;
165 }
166
167 void gpu_pme_loadbal_update_param(const nonbonded_verlet_t* nbv, const interaction_const_t* ic)
168 {
169     if (!nbv || !nbv->useGpu())
170     {
171         return;
172     }
173     NbnxmGpu*   nb  = nbv->gpu_nbv;
174     NBParamGpu* nbp = nb->nbparam;
175
176     set_cutoff_parameters(nbp, ic, nbv->pairlistSets().params());
177
178     nbp->elecType = nbnxn_gpu_pick_ewald_kernel_type(*ic, nb->deviceContext_->deviceInfo());
179
180     GMX_RELEASE_ASSERT(ic->coulombEwaldTables, "Need valid Coulomb Ewald correction tables");
181     init_ewald_coulomb_force_table(*ic->coulombEwaldTables, nbp, *nb->deviceContext_);
182 }
183
184 void init_plist(gpu_plist* pl)
185 {
186     /* initialize to nullptr pointers to data that is not allocated here and will
187        need reallocation in nbnxn_gpu_init_pairlist */
188     pl->sci   = nullptr;
189     pl->cj4   = nullptr;
190     pl->imask = nullptr;
191     pl->excl  = nullptr;
192
193     /* size -1 indicates that the respective array hasn't been initialized yet */
194     pl->na_c          = -1;
195     pl->nsci          = -1;
196     pl->sci_nalloc    = -1;
197     pl->ncj4          = -1;
198     pl->cj4_nalloc    = -1;
199     pl->nimask        = -1;
200     pl->imask_nalloc  = -1;
201     pl->nexcl         = -1;
202     pl->excl_nalloc   = -1;
203     pl->haveFreshList = false;
204 }
205
206 void init_timings(gmx_wallclock_gpu_nbnxn_t* t)
207 {
208     t->nb_h2d_t = 0.0;
209     t->nb_d2h_t = 0.0;
210     t->nb_c     = 0;
211     t->pl_h2d_t = 0.0;
212     t->pl_h2d_c = 0;
213     for (int i = 0; i < 2; i++)
214     {
215         for (int j = 0; j < 2; j++)
216         {
217             t->ktime[i][j].t = 0.0;
218             t->ktime[i][j].c = 0;
219         }
220     }
221     t->pruneTime.c        = 0;
222     t->pruneTime.t        = 0.0;
223     t->dynamicPruneTime.c = 0;
224     t->dynamicPruneTime.t = 0.0;
225 }
226
227 //! This function is documented in the header file
228 void gpu_init_pairlist(NbnxmGpu* nb, const NbnxnPairlistGpu* h_plist, const InteractionLocality iloc)
229 {
230     char sbuf[STRLEN];
231     // Timing accumulation should happen only if there was work to do
232     // because getLastRangeTime() gets skipped with empty lists later
233     // which leads to the counter not being reset.
234     bool                bDoTime      = (nb->bDoTime && !h_plist->sci.empty());
235     const DeviceStream& deviceStream = *nb->deviceStreams[iloc];
236     gpu_plist*          d_plist      = nb->plist[iloc];
237
238     if (d_plist->na_c < 0)
239     {
240         d_plist->na_c = h_plist->na_ci;
241     }
242     else
243     {
244         if (d_plist->na_c != h_plist->na_ci)
245         {
246             sprintf(sbuf,
247                     "In init_plist: the #atoms per cell has changed (from %d to %d)",
248                     d_plist->na_c,
249                     h_plist->na_ci);
250             gmx_incons(sbuf);
251         }
252     }
253
254     gpu_timers_t::Interaction& iTimers = nb->timers->interaction[iloc];
255
256     if (bDoTime)
257     {
258         iTimers.pl_h2d.openTimingRegion(deviceStream);
259         iTimers.didPairlistH2D = true;
260     }
261
262     // TODO most of this function is same in CUDA and OpenCL, move into the header
263     const DeviceContext& deviceContext = *nb->deviceContext_;
264
265     reallocateDeviceBuffer(
266             &d_plist->sci, h_plist->sci.size(), &d_plist->nsci, &d_plist->sci_nalloc, deviceContext);
267     copyToDeviceBuffer(&d_plist->sci,
268                        h_plist->sci.data(),
269                        0,
270                        h_plist->sci.size(),
271                        deviceStream,
272                        GpuApiCallBehavior::Async,
273                        bDoTime ? iTimers.pl_h2d.fetchNextEvent() : nullptr);
274
275     reallocateDeviceBuffer(
276             &d_plist->cj4, h_plist->cj4.size(), &d_plist->ncj4, &d_plist->cj4_nalloc, deviceContext);
277     copyToDeviceBuffer(&d_plist->cj4,
278                        h_plist->cj4.data(),
279                        0,
280                        h_plist->cj4.size(),
281                        deviceStream,
282                        GpuApiCallBehavior::Async,
283                        bDoTime ? iTimers.pl_h2d.fetchNextEvent() : nullptr);
284
285     reallocateDeviceBuffer(&d_plist->imask,
286                            h_plist->cj4.size() * c_nbnxnGpuClusterpairSplit,
287                            &d_plist->nimask,
288                            &d_plist->imask_nalloc,
289                            deviceContext);
290
291     reallocateDeviceBuffer(
292             &d_plist->excl, h_plist->excl.size(), &d_plist->nexcl, &d_plist->excl_nalloc, deviceContext);
293     copyToDeviceBuffer(&d_plist->excl,
294                        h_plist->excl.data(),
295                        0,
296                        h_plist->excl.size(),
297                        deviceStream,
298                        GpuApiCallBehavior::Async,
299                        bDoTime ? iTimers.pl_h2d.fetchNextEvent() : nullptr);
300
301     if (bDoTime)
302     {
303         iTimers.pl_h2d.closeTimingRegion(deviceStream);
304     }
305
306     /* need to prune the pair list during the next step */
307     d_plist->haveFreshList = true;
308 }
309
310 //! This function is documented in the header file
311 gmx_wallclock_gpu_nbnxn_t* gpu_get_timings(NbnxmGpu* nb)
312 {
313     return (nb != nullptr && nb->bDoTime) ? nb->timings : nullptr;
314 }
315
316 //! This function is documented in the header file
317 void gpu_reset_timings(nonbonded_verlet_t* nbv)
318 {
319     if (nbv->gpu_nbv && nbv->gpu_nbv->bDoTime)
320     {
321         init_timings(nbv->gpu_nbv->timings);
322     }
323 }
324
325 bool gpu_is_kernel_ewald_analytical(const NbnxmGpu* nb)
326 {
327     return ((nb->nbparam->elecType == ElecType::EwaldAna)
328             || (nb->nbparam->elecType == ElecType::EwaldAnaTwin));
329 }
330
331 enum ElecType nbnxmGpuPickElectrostaticsKernelType(const interaction_const_t* ic,
332                                                    const DeviceInformation&   deviceInfo)
333 {
334     if (ic->eeltype == eelCUT)
335     {
336         return ElecType::Cut;
337     }
338     else if (EEL_RF(ic->eeltype))
339     {
340         return ElecType::RF;
341     }
342     else if ((EEL_PME(ic->eeltype) || ic->eeltype == eelEWALD))
343     {
344         return nbnxn_gpu_pick_ewald_kernel_type(*ic, deviceInfo);
345     }
346     else
347     {
348         /* Shouldn't happen, as this is checked when choosing Verlet-scheme */
349         GMX_THROW(gmx::InconsistentInputError(
350                 gmx::formatString("The requested electrostatics type %s (%d) is not implemented in "
351                                   "the GPU accelerated kernels!",
352                                   EELTYPE(ic->eeltype),
353                                   ic->eeltype)));
354     }
355 }
356
357
358 enum VdwType nbnxmGpuPickVdwKernelType(const interaction_const_t* ic, LJCombinationRule ljCombinationRule)
359 {
360     if (ic->vdwtype == evdwCUT)
361     {
362         switch (ic->vdw_modifier)
363         {
364             case eintmodNONE:
365             case eintmodPOTSHIFT:
366                 switch (ljCombinationRule)
367                 {
368                     case LJCombinationRule::None: return VdwType::Cut;
369                     case LJCombinationRule::Geometric: return VdwType::CutCombGeom;
370                     case LJCombinationRule::LorentzBerthelot: return VdwType::CutCombLB;
371                     default:
372                         GMX_THROW(gmx::InconsistentInputError(gmx::formatString(
373                                 "The requested LJ combination rule %s is not implemented in "
374                                 "the GPU accelerated kernels!",
375                                 enumValueToString(ljCombinationRule))));
376                 }
377             case eintmodFORCESWITCH: return VdwType::FSwitch;
378             case eintmodPOTSWITCH: return VdwType::PSwitch;
379             default:
380                 GMX_THROW(gmx::InconsistentInputError(
381                         gmx::formatString("The requested VdW interaction modifier %s (%d) is not "
382                                           "implemented in the GPU accelerated kernels!",
383                                           INTMODIFIER(ic->vdw_modifier),
384                                           ic->vdw_modifier)));
385         }
386     }
387     else if (ic->vdwtype == evdwPME)
388     {
389         if (ic->ljpme_comb_rule == eljpmeGEOM)
390         {
391             assert(ljCombinationRule == LJCombinationRule::Geometric);
392             return VdwType::EwaldGeom;
393         }
394         else
395         {
396             assert(ljCombinationRule == LJCombinationRule::LorentzBerthelot);
397             return VdwType::EwaldLB;
398         }
399     }
400     else
401     {
402         GMX_THROW(gmx::InconsistentInputError(gmx::formatString(
403                 "The requested VdW type %s (%d) is not implemented in the GPU accelerated kernels!",
404                 EVDWTYPE(ic->vdwtype),
405                 ic->vdwtype)));
406     }
407 }
408
409 } // namespace Nbnxm