0af6e94e6189a623768d0eb334890e2c52834b67
[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/nbnxm/gpu_data_mgmt.h"
63 #include "gromacs/timing/gpu_timing.h"
64 #include "gromacs/utility/cstringutil.h"
65
66 #include "nbnxm_gpu.h"
67 #include "pairlistsets.h"
68
69 namespace Nbnxm
70 {
71
72 void init_ewald_coulomb_force_table(const EwaldCorrectionTables& tables,
73                                     NBParamGpu*                  nbp,
74                                     const DeviceContext&         deviceContext)
75 {
76     if (nbp->coulomb_tab)
77     {
78         destroyParamLookupTable(&nbp->coulomb_tab, nbp->coulomb_tab_texobj);
79     }
80
81     nbp->coulomb_tab_scale = tables.scale;
82     initParamLookupTable(&nbp->coulomb_tab, &nbp->coulomb_tab_texobj, tables.tableF.data(),
83                          tables.tableF.size(), deviceContext);
84 }
85
86 void inline printEnvironmentVariableDeprecationMessage(bool               isEnvironmentVariableSet,
87                                                        const std::string& environmentVariableSuffix)
88 {
89     if (isEnvironmentVariableSet)
90     {
91         fprintf(stderr,
92                 "Environment variables GMX_CUDA_%s and GMX_OCL_%s are deprecated and will be\n"
93                 "removed in release 2022, please use GMX_GPU_%s instead.",
94                 environmentVariableSuffix.c_str(), environmentVariableSuffix.c_str(),
95                 environmentVariableSuffix.c_str());
96     }
97 }
98
99 int nbnxn_gpu_pick_ewald_kernel_type(const interaction_const_t& ic,
100                                      const DeviceInformation gmx_unused& deviceInfo)
101 {
102     bool bTwinCut = (ic.rcoulomb != ic.rvdw);
103     int  kernel_type;
104
105     /* Benchmarking/development environment variables to force the use of
106        analytical or tabulated Ewald kernel. */
107
108     // Remove these when old environment variables are deprecated
109     const bool forceAnalyticalEwaldLegacy = (getenv("GMX_CUDA_NB_ANA_EWALD") != nullptr)
110                                             || (getenv("GMX_OCL_NB_ANA_EWALD") != nullptr);
111     const bool forceTabulatedEwaldLegacy = (getenv("GMX_CUDA_NB_TAB_EWALD") != nullptr)
112                                            || (getenv("GMX_OCL_NB_TAB_EWALD") != nullptr);
113     const bool forceTwinCutoffEwaldLegacy = (getenv("GMX_CUDA_NB_EWALD_TWINCUT") != nullptr)
114                                             || (getenv("GMX_OCL_NB_EWALD_TWINCUT") != nullptr);
115
116     printEnvironmentVariableDeprecationMessage(forceAnalyticalEwaldLegacy, "NB_ANA_EWALD");
117     printEnvironmentVariableDeprecationMessage(forceTabulatedEwaldLegacy, "NB_TAB_EWALD");
118     printEnvironmentVariableDeprecationMessage(forceTwinCutoffEwaldLegacy, "NB_EWALD_TWINCUT");
119
120     const bool forceAnalyticalEwald =
121             (getenv("GMX_GPU_NB_ANA_EWALD") != nullptr) || forceAnalyticalEwaldLegacy;
122     const bool forceTabulatedEwald =
123             (getenv("GMX_GPU_NB_TAB_EWALD") != nullptr) || forceTabulatedEwaldLegacy;
124     const bool forceTwinCutoffEwald =
125             (getenv("GMX_GPU_NB_EWALD_TWINCUT") != nullptr) || forceTwinCutoffEwaldLegacy;
126
127     if (forceAnalyticalEwald && forceTabulatedEwald)
128     {
129         gmx_incons(
130                 "Both analytical and tabulated Ewald GPU non-bonded kernels "
131                 "requested through environment variables.");
132     }
133
134     /* By default, use analytical Ewald except with CUDA on NVIDIA CC 7.0 and 8.0.
135      */
136     const bool c_useTabulatedEwaldDefault =
137 #if GMX_GPU_CUDA
138             (deviceInfo.prop.major == 7 && deviceInfo.prop.minor == 0)
139             || (deviceInfo.prop.major == 8 && deviceInfo.prop.minor == 0);
140 #else
141             false;
142 #endif
143     bool bUseAnalyticalEwald = !c_useTabulatedEwaldDefault;
144     if (forceAnalyticalEwald)
145     {
146         bUseAnalyticalEwald = true;
147         if (debug)
148         {
149             fprintf(debug, "Using analytical Ewald GPU kernels\n");
150         }
151     }
152     else if (forceTabulatedEwald)
153     {
154         bUseAnalyticalEwald = false;
155
156         if (debug)
157         {
158             fprintf(debug, "Using tabulated Ewald GPU kernels\n");
159         }
160     }
161
162     /* Use twin cut-off kernels if requested by bTwinCut or the env. var.
163        forces it (use it for debugging/benchmarking only). */
164     if (!bTwinCut && !forceTwinCutoffEwald)
165     {
166         kernel_type = bUseAnalyticalEwald ? eelTypeEWALD_ANA : eelTypeEWALD_TAB;
167     }
168     else
169     {
170         kernel_type = bUseAnalyticalEwald ? eelTypeEWALD_ANA_TWIN : eelTypeEWALD_TAB_TWIN;
171     }
172
173     return kernel_type;
174 }
175
176 void set_cutoff_parameters(NBParamGpu* nbp, const interaction_const_t* ic, const PairlistParams& listParams)
177 {
178     nbp->ewald_beta        = ic->ewaldcoeff_q;
179     nbp->sh_ewald          = ic->sh_ewald;
180     nbp->epsfac            = ic->epsfac;
181     nbp->two_k_rf          = 2.0 * ic->k_rf;
182     nbp->c_rf              = ic->c_rf;
183     nbp->rvdw_sq           = ic->rvdw * ic->rvdw;
184     nbp->rcoulomb_sq       = ic->rcoulomb * ic->rcoulomb;
185     nbp->rlistOuter_sq     = listParams.rlistOuter * listParams.rlistOuter;
186     nbp->rlistInner_sq     = listParams.rlistInner * listParams.rlistInner;
187     nbp->useDynamicPruning = listParams.useDynamicPruning;
188
189     nbp->sh_lj_ewald   = ic->sh_lj_ewald;
190     nbp->ewaldcoeff_lj = ic->ewaldcoeff_lj;
191
192     nbp->rvdw_switch      = ic->rvdw_switch;
193     nbp->dispersion_shift = ic->dispersion_shift;
194     nbp->repulsion_shift  = ic->repulsion_shift;
195     nbp->vdw_switch       = ic->vdw_switch;
196 }
197
198 void gpu_pme_loadbal_update_param(const nonbonded_verlet_t* nbv, const interaction_const_t* ic)
199 {
200     if (!nbv || !nbv->useGpu())
201     {
202         return;
203     }
204     NbnxmGpu*   nb  = nbv->gpu_nbv;
205     NBParamGpu* nbp = nb->nbparam;
206
207     set_cutoff_parameters(nbp, ic, nbv->pairlistSets().params());
208
209     nbp->eeltype = nbnxn_gpu_pick_ewald_kernel_type(*ic, nb->deviceContext_->deviceInfo());
210
211     GMX_RELEASE_ASSERT(ic->coulombEwaldTables, "Need valid Coulomb Ewald correction tables");
212     init_ewald_coulomb_force_table(*ic->coulombEwaldTables, nbp, *nb->deviceContext_);
213 }
214
215 void init_plist(gpu_plist* pl)
216 {
217     /* initialize to nullptr pointers to data that is not allocated here and will
218        need reallocation in nbnxn_gpu_init_pairlist */
219     pl->sci   = nullptr;
220     pl->cj4   = nullptr;
221     pl->imask = nullptr;
222     pl->excl  = nullptr;
223
224     /* size -1 indicates that the respective array hasn't been initialized yet */
225     pl->na_c          = -1;
226     pl->nsci          = -1;
227     pl->sci_nalloc    = -1;
228     pl->ncj4          = -1;
229     pl->cj4_nalloc    = -1;
230     pl->nimask        = -1;
231     pl->imask_nalloc  = -1;
232     pl->nexcl         = -1;
233     pl->excl_nalloc   = -1;
234     pl->haveFreshList = false;
235 }
236
237 void init_timings(gmx_wallclock_gpu_nbnxn_t* t)
238 {
239     int i, j;
240
241     t->nb_h2d_t = 0.0;
242     t->nb_d2h_t = 0.0;
243     t->nb_c     = 0;
244     t->pl_h2d_t = 0.0;
245     t->pl_h2d_c = 0;
246     for (i = 0; i < 2; i++)
247     {
248         for (j = 0; j < 2; j++)
249         {
250             t->ktime[i][j].t = 0.0;
251             t->ktime[i][j].c = 0;
252         }
253     }
254     t->pruneTime.c        = 0;
255     t->pruneTime.t        = 0.0;
256     t->dynamicPruneTime.c = 0;
257     t->dynamicPruneTime.t = 0.0;
258 }
259
260 //! This function is documented in the header file
261 void gpu_init_pairlist(NbnxmGpu* nb, const NbnxnPairlistGpu* h_plist, const InteractionLocality iloc)
262 {
263     char sbuf[STRLEN];
264     // Timing accumulation should happen only if there was work to do
265     // because getLastRangeTime() gets skipped with empty lists later
266     // which leads to the counter not being reset.
267     bool                bDoTime      = (nb->bDoTime && !h_plist->sci.empty());
268     const DeviceStream& deviceStream = *nb->deviceStreams[iloc];
269     gpu_plist*          d_plist      = nb->plist[iloc];
270
271     if (d_plist->na_c < 0)
272     {
273         d_plist->na_c = h_plist->na_ci;
274     }
275     else
276     {
277         if (d_plist->na_c != h_plist->na_ci)
278         {
279             sprintf(sbuf, "In init_plist: the #atoms per cell has changed (from %d to %d)",
280                     d_plist->na_c, h_plist->na_ci);
281             gmx_incons(sbuf);
282         }
283     }
284
285     gpu_timers_t::Interaction& iTimers = nb->timers->interaction[iloc];
286
287     if (bDoTime)
288     {
289         iTimers.pl_h2d.openTimingRegion(deviceStream);
290         iTimers.didPairlistH2D = true;
291     }
292
293     // TODO most of this function is same in CUDA and OpenCL, move into the header
294     const DeviceContext& deviceContext = *nb->deviceContext_;
295
296     reallocateDeviceBuffer(&d_plist->sci, h_plist->sci.size(), &d_plist->nsci, &d_plist->sci_nalloc,
297                            deviceContext);
298     copyToDeviceBuffer(&d_plist->sci, h_plist->sci.data(), 0, h_plist->sci.size(), deviceStream,
299                        GpuApiCallBehavior::Async, bDoTime ? iTimers.pl_h2d.fetchNextEvent() : nullptr);
300
301     reallocateDeviceBuffer(&d_plist->cj4, h_plist->cj4.size(), &d_plist->ncj4, &d_plist->cj4_nalloc,
302                            deviceContext);
303     copyToDeviceBuffer(&d_plist->cj4, h_plist->cj4.data(), 0, h_plist->cj4.size(), deviceStream,
304                        GpuApiCallBehavior::Async, bDoTime ? iTimers.pl_h2d.fetchNextEvent() : nullptr);
305
306     reallocateDeviceBuffer(&d_plist->imask, h_plist->cj4.size() * c_nbnxnGpuClusterpairSplit,
307                            &d_plist->nimask, &d_plist->imask_nalloc, deviceContext);
308
309     reallocateDeviceBuffer(&d_plist->excl, h_plist->excl.size(), &d_plist->nexcl,
310                            &d_plist->excl_nalloc, deviceContext);
311     copyToDeviceBuffer(&d_plist->excl, h_plist->excl.data(), 0, h_plist->excl.size(), deviceStream,
312                        GpuApiCallBehavior::Async, bDoTime ? iTimers.pl_h2d.fetchNextEvent() : nullptr);
313
314     if (bDoTime)
315     {
316         iTimers.pl_h2d.closeTimingRegion(deviceStream);
317     }
318
319     /* need to prune the pair list during the next step */
320     d_plist->haveFreshList = true;
321 }
322
323 //! This function is documented in the header file
324 gmx_wallclock_gpu_nbnxn_t* gpu_get_timings(NbnxmGpu* nb)
325 {
326     return (nb != nullptr && nb->bDoTime) ? nb->timings : nullptr;
327 }
328
329 //! This function is documented in the header file
330 void gpu_reset_timings(nonbonded_verlet_t* nbv)
331 {
332     if (nbv->gpu_nbv && nbv->gpu_nbv->bDoTime)
333     {
334         init_timings(nbv->gpu_nbv->timings);
335     }
336 }
337
338 bool gpu_is_kernel_ewald_analytical(const NbnxmGpu* nb)
339 {
340     return ((nb->nbparam->eeltype == eelTypeEWALD_ANA) || (nb->nbparam->eeltype == eelTypeEWALD_ANA_TWIN));
341 }
342
343 } // namespace Nbnxm