f666910d12425c9990b48a57233204c72d2d6fdb
[alexxy/gromacs.git] / src / gromacs / nbnxm / opencl / nbnxm_ocl_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 OpenCL 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  *  \ingroup module_nbnxm
44  */
45 #include "gmxpre.h"
46
47 #include <assert.h>
48 #include <stdarg.h>
49 #include <stdio.h>
50 #include <stdlib.h>
51 #include <string.h>
52
53 #include <cmath>
54
55 #include "gromacs/gpu_utils/device_stream_manager.h"
56 #include "gromacs/gpu_utils/pmalloc.h"
57 #include "gromacs/hardware/device_information.h"
58 #include "gromacs/hardware/device_management.h"
59 #include "gromacs/math/vectypes.h"
60 #include "gromacs/mdlib/force_flags.h"
61 #include "gromacs/mdtypes/interaction_const.h"
62 #include "gromacs/mdtypes/md_enums.h"
63 #include "gromacs/nbnxm/atomdata.h"
64 #include "gromacs/nbnxm/gpu_data_mgmt.h"
65 #include "gromacs/nbnxm/gpu_jit_support.h"
66 #include "gromacs/nbnxm/nbnxm.h"
67 #include "gromacs/nbnxm/nbnxm_gpu.h"
68 #include "gromacs/nbnxm/nbnxm_gpu_data_mgmt.h"
69 #include "gromacs/nbnxm/pairlistsets.h"
70 #include "gromacs/pbcutil/ishift.h"
71 #include "gromacs/timing/gpu_timing.h"
72 #include "gromacs/utility/cstringutil.h"
73 #include "gromacs/utility/fatalerror.h"
74 #include "gromacs/utility/gmxassert.h"
75 #include "gromacs/utility/real.h"
76 #include "gromacs/utility/smalloc.h"
77
78 #include "nbnxm_ocl_types.h"
79
80 namespace Nbnxm
81 {
82
83 /*! \brief Copies of values from cl_driver_diagnostics_intel.h,
84  * which isn't guaranteed to be available. */
85 /**@{*/
86 #define CL_CONTEXT_SHOW_DIAGNOSTICS_INTEL 0x4106
87 #define CL_CONTEXT_DIAGNOSTICS_LEVEL_GOOD_INTEL 0x1
88 #define CL_CONTEXT_DIAGNOSTICS_LEVEL_BAD_INTEL 0x2
89 #define CL_CONTEXT_DIAGNOSTICS_LEVEL_NEUTRAL_INTEL 0x4
90 /**@}*/
91
92 /*! \brief This parameter should be determined heuristically from the
93  * kernel execution times
94  *
95  * This value is best for small systems on a single AMD Radeon R9 290X
96  * (and about 5% faster than 40, which is the default for CUDA
97  * devices). Larger simulation systems were quite insensitive to the
98  * value of this parameter.
99  */
100 static unsigned int gpu_min_ci_balanced_factor = 50;
101
102
103 /*! \brief Initializes the atomdata structure first time, it only gets filled at
104     pair-search.
105  */
106 static void init_atomdata_first(NBAtomData*          ad,
107                                 int                  ntypes,
108                                 const DeviceContext& deviceContext,
109                                 const DeviceStream&  localStream)
110 {
111     ad->numTypes = ntypes;
112
113     allocateDeviceBuffer(&ad->shiftVec, SHIFTS, deviceContext);
114     ad->shiftVecUploaded = false;
115
116     allocateDeviceBuffer(&ad->fShift, SHIFTS, deviceContext);
117     allocateDeviceBuffer(&ad->eLJ, 1, deviceContext);
118     allocateDeviceBuffer(&ad->eElec, 1, deviceContext);
119
120     clearDeviceBufferAsync(&ad->fShift, 0, SHIFTS, localStream);
121     clearDeviceBufferAsync(&ad->eElec, 0, 1, localStream);
122     clearDeviceBufferAsync(&ad->eLJ, 0, 1, localStream);
123
124     /* initialize to nullptr pointers to data that is not allocated here and will
125        need reallocation in nbnxn_gpu_init_atomdata */
126     ad->xq = nullptr;
127     ad->f  = nullptr;
128
129     /* size -1 indicates that the respective array hasn't been initialized yet */
130     ad->numAtoms      = -1;
131     ad->numAtomsAlloc = -1;
132 }
133
134
135 /*! \brief Initializes the nonbonded parameter data structure.
136  */
137 static void init_nbparam(NBParamGpu*                     nbp,
138                          const interaction_const_t*      ic,
139                          const PairlistParams&           listParams,
140                          const nbnxn_atomdata_t::Params& nbatParams,
141                          const DeviceContext&            deviceContext)
142 {
143     set_cutoff_parameters(nbp, ic, listParams);
144
145     nbp->vdwType  = nbnxmGpuPickVdwKernelType(ic, nbatParams.ljCombinationRule);
146     nbp->elecType = nbnxmGpuPickElectrostaticsKernelType(ic, deviceContext.deviceInfo());
147
148     if (ic->vdwtype == VanDerWaalsType::Pme)
149     {
150         if (ic->ljpme_comb_rule == LongRangeVdW::Geom)
151         {
152             GMX_ASSERT(nbatParams.ljCombinationRule == LJCombinationRule::Geometric,
153                        "Combination rule mismatch!");
154         }
155         else
156         {
157             GMX_ASSERT(nbatParams.ljCombinationRule == LJCombinationRule::LorentzBerthelot,
158                        "Combination rule mismatch!");
159         }
160     }
161     /* generate table for PME */
162     nbp->coulomb_tab = nullptr;
163     if (nbp->elecType == ElecType::EwaldTab || nbp->elecType == ElecType::EwaldTabTwin)
164     {
165         GMX_RELEASE_ASSERT(ic->coulombEwaldTables, "Need valid Coulomb Ewald correction tables");
166         init_ewald_coulomb_force_table(*ic->coulombEwaldTables, nbp, deviceContext);
167     }
168     else
169     {
170         allocateDeviceBuffer(&nbp->coulomb_tab, 1, deviceContext);
171     }
172
173     {
174         /* set up LJ parameter lookup table */
175         static_assert(sizeof(Float2) == 2 * sizeof(decltype(*nbatParams.nbfp.data())),
176                       "Mismatch in the size of host / device data types");
177         DeviceBuffer<Float2> nbfp;
178         initParamLookupTable(&nbfp,
179                              nullptr,
180                              reinterpret_cast<const Float2*>(nbatParams.nbfp.data()),
181                              nbatParams.numTypes * nbatParams.numTypes,
182                              deviceContext);
183         nbp->nbfp = nbfp;
184
185         if (ic->vdwtype == VanDerWaalsType::Pme)
186         {
187             static_assert(sizeof(Float2) == 2 * sizeof(decltype(*nbatParams.nbfp_comb.data())),
188                           "Mismatch in the size of host / device data types");
189             DeviceBuffer<Float2> nbfp_comb;
190             initParamLookupTable(&nbfp_comb,
191                                  nullptr,
192                                  reinterpret_cast<const Float2*>(nbatParams.nbfp_comb.data()),
193                                  nbatParams.numTypes,
194                                  deviceContext);
195             nbp->nbfp_comb = nbfp_comb;
196         }
197     }
198 }
199
200 /*! \brief Initializes the OpenCL kernel pointers of the nbnxn_ocl_ptr_t input data structure. */
201 static cl_kernel nbnxn_gpu_create_kernel(NbnxmGpu* nb, const char* kernel_name)
202 {
203     cl_kernel kernel;
204     cl_int    cl_error;
205
206     kernel = clCreateKernel(nb->dev_rundata->program, kernel_name, &cl_error);
207     if (CL_SUCCESS != cl_error)
208     {
209         gmx_fatal(FARGS,
210                   "Failed to create kernel '%s' for GPU #%s: OpenCL error %d",
211                   kernel_name,
212                   nb->deviceContext_->deviceInfo().device_name,
213                   cl_error);
214     }
215
216     return kernel;
217 }
218
219 /*! \brief Initializes the OpenCL kernel pointers of the nbnxn_ocl_ptr_t input data structure. */
220 static void nbnxn_gpu_init_kernels(NbnxmGpu* nb)
221 {
222     /* Init to 0 main kernel arrays */
223     /* They will be later on initialized in select_nbnxn_kernel */
224     // TODO: consider always creating all variants of the kernels here so that there is no
225     // need for late call to clCreateKernel -- if that gives any advantage?
226     memset(nb->kernel_ener_noprune_ptr, 0, sizeof(nb->kernel_ener_noprune_ptr));
227     memset(nb->kernel_ener_prune_ptr, 0, sizeof(nb->kernel_ener_prune_ptr));
228     memset(nb->kernel_noener_noprune_ptr, 0, sizeof(nb->kernel_noener_noprune_ptr));
229     memset(nb->kernel_noener_prune_ptr, 0, sizeof(nb->kernel_noener_prune_ptr));
230
231     /* Init pruning kernels
232      *
233      * TODO: we could avoid creating kernels if dynamic pruning is turned off,
234      * but ATM that depends on force flags not passed into the initialization.
235      */
236     nb->kernel_pruneonly[epruneFirst] = nbnxn_gpu_create_kernel(nb, "nbnxn_kernel_prune_opencl");
237     nb->kernel_pruneonly[epruneRolling] =
238             nbnxn_gpu_create_kernel(nb, "nbnxn_kernel_prune_rolling_opencl");
239 }
240
241 //! This function is documented in the header file
242 NbnxmGpu* gpu_init(const gmx::DeviceStreamManager& deviceStreamManager,
243                    const interaction_const_t*      ic,
244                    const PairlistParams&           listParams,
245                    const nbnxn_atomdata_t*         nbat,
246                    const bool                      bLocalAndNonlocal)
247 {
248     GMX_ASSERT(ic, "Need a valid interaction constants object");
249
250     auto nb            = new NbnxmGpu();
251     nb->deviceContext_ = &deviceStreamManager.context();
252     snew(nb->atdat, 1);
253     snew(nb->nbparam, 1);
254     snew(nb->plist[InteractionLocality::Local], 1);
255     if (bLocalAndNonlocal)
256     {
257         snew(nb->plist[InteractionLocality::NonLocal], 1);
258     }
259
260     nb->bUseTwoStreams = bLocalAndNonlocal;
261
262     nb->timers = new Nbnxm::GpuTimers();
263     snew(nb->timings, 1);
264
265     /* set device info, just point it to the right GPU among the detected ones */
266     nb->dev_rundata = new gmx_device_runtime_data_t();
267
268     /* init nbst */
269     pmalloc(reinterpret_cast<void**>(&nb->nbst.eLJ), sizeof(*nb->nbst.eLJ));
270     pmalloc(reinterpret_cast<void**>(&nb->nbst.eElec), sizeof(*nb->nbst.eElec));
271     pmalloc(reinterpret_cast<void**>(&nb->nbst.fShift), SHIFTS * sizeof(*nb->nbst.fShift));
272
273     init_plist(nb->plist[InteractionLocality::Local]);
274
275     /* OpenCL timing disabled if GMX_DISABLE_GPU_TIMING is defined. */
276     nb->bDoTime = (getenv("GMX_DISABLE_GPU_TIMING") == nullptr);
277
278     /* local/non-local GPU streams */
279     GMX_RELEASE_ASSERT(deviceStreamManager.streamIsValid(gmx::DeviceStreamType::NonBondedLocal),
280                        "Local non-bonded stream should be initialized to use GPU for non-bonded.");
281     const DeviceStream& localStream = deviceStreamManager.stream(gmx::DeviceStreamType::NonBondedLocal);
282     nb->deviceStreams[InteractionLocality::Local] = &localStream;
283
284     if (nb->bUseTwoStreams)
285     {
286         init_plist(nb->plist[InteractionLocality::NonLocal]);
287
288         GMX_RELEASE_ASSERT(deviceStreamManager.streamIsValid(gmx::DeviceStreamType::NonBondedNonLocal),
289                            "Non-local non-bonded stream should be initialized to use GPU for "
290                            "non-bonded with domain decomposition.");
291         nb->deviceStreams[InteractionLocality::NonLocal] =
292                 &deviceStreamManager.stream(gmx::DeviceStreamType::NonBondedNonLocal);
293     }
294
295     if (nb->bDoTime)
296     {
297         init_timings(nb->timings);
298     }
299
300     const nbnxn_atomdata_t::Params& nbatParams    = nbat->params();
301     const DeviceContext&            deviceContext = *nb->deviceContext_;
302     init_atomdata_first(nb->atdat, nbatParams.numTypes, deviceContext, localStream);
303     init_nbparam(nb->nbparam, ic, listParams, nbatParams, deviceContext);
304
305     /* Enable LJ param manual prefetch for AMD or Intel or if we request through env. var.
306      * TODO: decide about NVIDIA
307      */
308     nb->bPrefetchLjParam = (getenv("GMX_OCL_DISABLE_I_PREFETCH") == nullptr)
309                            && ((nb->deviceContext_->deviceInfo().deviceVendor == DeviceVendor::Amd)
310                                || (nb->deviceContext_->deviceInfo().deviceVendor == DeviceVendor::Intel)
311                                || (getenv("GMX_OCL_ENABLE_I_PREFETCH") != nullptr));
312
313     /* NOTE: in CUDA we pick L1 cache configuration for the nbnxn kernels here,
314      * but sadly this is not supported in OpenCL (yet?). Consider adding it if
315      * it becomes supported.
316      */
317     nbnxn_gpu_compile_kernels(nb);
318     nbnxn_gpu_init_kernels(nb);
319
320     if (debug)
321     {
322         fprintf(debug, "Initialized OpenCL data structures.\n");
323     }
324
325     return nb;
326 }
327
328 //! This function is documented in the header file
329 void gpu_upload_shiftvec(NbnxmGpu* nb, const nbnxn_atomdata_t* nbatom)
330 {
331     NBAtomData*         adat        = nb->atdat;
332     const DeviceStream& localStream = *nb->deviceStreams[InteractionLocality::Local];
333
334     /* only if we have a dynamic box */
335     if (nbatom->bDynamicBox || !adat->shiftVecUploaded)
336     {
337         static_assert(sizeof(Float3) == sizeof(nbatom->shift_vec[0]),
338                       "Sizes of host- and device-side shift vectors should be the same.");
339         copyToDeviceBuffer(&adat->shiftVec,
340                            reinterpret_cast<const Float3*>(nbatom->shift_vec.data()),
341                            0,
342                            SHIFTS,
343                            localStream,
344                            GpuApiCallBehavior::Async,
345                            nullptr);
346         adat->shiftVecUploaded = true;
347     }
348 }
349
350 /*! \brief Releases an OpenCL kernel pointer */
351 static void free_kernel(cl_kernel* kernel_ptr)
352 {
353     cl_int gmx_unused cl_error;
354
355     GMX_ASSERT(kernel_ptr, "Need a valid kernel pointer");
356
357     if (*kernel_ptr)
358     {
359         cl_error = clReleaseKernel(*kernel_ptr);
360         GMX_RELEASE_ASSERT(cl_error == CL_SUCCESS,
361                            ("clReleaseKernel failed: " + ocl_get_error_string(cl_error)).c_str());
362
363         *kernel_ptr = nullptr;
364     }
365 }
366
367 /*! \brief Releases a list of OpenCL kernel pointers */
368 static void free_kernels(cl_kernel* kernels, int count)
369 {
370     int i;
371
372     for (i = 0; i < count; i++)
373     {
374         free_kernel(kernels + i);
375     }
376 }
377
378 /*! \brief Free the OpenCL program.
379  *
380  *  The function releases the OpenCL program assuciated with the
381  *  device that the calling PP rank is running on.
382  *
383  *  \param program [in]  OpenCL program to release.
384  */
385 static void freeGpuProgram(cl_program program)
386 {
387     if (program)
388     {
389         cl_int cl_error = clReleaseProgram(program);
390         GMX_RELEASE_ASSERT(cl_error == CL_SUCCESS,
391                            ("clReleaseProgram failed: " + ocl_get_error_string(cl_error)).c_str());
392         program = nullptr;
393     }
394 }
395
396 //! This function is documented in the header file
397 void gpu_free(NbnxmGpu* nb)
398 {
399     if (nb == nullptr)
400     {
401         return;
402     }
403
404     /* Free kernels */
405     // NOLINTNEXTLINE(bugprone-sizeof-expression)
406     int kernel_count = sizeof(nb->kernel_ener_noprune_ptr) / sizeof(nb->kernel_ener_noprune_ptr[0][0]);
407     free_kernels(nb->kernel_ener_noprune_ptr[0], kernel_count);
408
409     // NOLINTNEXTLINE(bugprone-sizeof-expression)
410     kernel_count = sizeof(nb->kernel_ener_prune_ptr) / sizeof(nb->kernel_ener_prune_ptr[0][0]);
411     free_kernels(nb->kernel_ener_prune_ptr[0], kernel_count);
412
413     // NOLINTNEXTLINE(bugprone-sizeof-expression)
414     kernel_count = sizeof(nb->kernel_noener_noprune_ptr) / sizeof(nb->kernel_noener_noprune_ptr[0][0]);
415     free_kernels(nb->kernel_noener_noprune_ptr[0], kernel_count);
416
417     // NOLINTNEXTLINE(bugprone-sizeof-expression)
418     kernel_count = sizeof(nb->kernel_noener_prune_ptr) / sizeof(nb->kernel_noener_prune_ptr[0][0]);
419     free_kernels(nb->kernel_noener_prune_ptr[0], kernel_count);
420
421     /* Free atdat */
422     freeDeviceBuffer(&(nb->atdat->xq));
423     freeDeviceBuffer(&(nb->atdat->f));
424     freeDeviceBuffer(&(nb->atdat->eLJ));
425     freeDeviceBuffer(&(nb->atdat->eElec));
426     freeDeviceBuffer(&(nb->atdat->fShift));
427     freeDeviceBuffer(&(nb->atdat->ljComb));
428     freeDeviceBuffer(&(nb->atdat->atomTypes));
429     freeDeviceBuffer(&(nb->atdat->shiftVec));
430     sfree(nb->atdat);
431
432     /* Free nbparam */
433     freeDeviceBuffer(&(nb->nbparam->nbfp));
434     freeDeviceBuffer(&(nb->nbparam->nbfp_comb));
435     freeDeviceBuffer(&(nb->nbparam->coulomb_tab));
436     sfree(nb->nbparam);
437
438     /* Free plist */
439     auto* plist = nb->plist[InteractionLocality::Local];
440     freeDeviceBuffer(&plist->sci);
441     freeDeviceBuffer(&plist->cj4);
442     freeDeviceBuffer(&plist->imask);
443     freeDeviceBuffer(&plist->excl);
444     sfree(plist);
445     if (nb->bUseTwoStreams)
446     {
447         auto* plist_nl = nb->plist[InteractionLocality::NonLocal];
448         freeDeviceBuffer(&plist_nl->sci);
449         freeDeviceBuffer(&plist_nl->cj4);
450         freeDeviceBuffer(&plist_nl->imask);
451         freeDeviceBuffer(&plist_nl->excl);
452         sfree(plist_nl);
453     }
454
455     /* Free nbst */
456     pfree(nb->nbst.eLJ);
457     nb->nbst.eLJ = nullptr;
458
459     pfree(nb->nbst.eElec);
460     nb->nbst.eElec = nullptr;
461
462     pfree(nb->nbst.fShift);
463     nb->nbst.fShift = nullptr;
464
465     freeGpuProgram(nb->dev_rundata->program);
466     delete nb->dev_rundata;
467
468     /* Free timers and timings */
469     delete nb->timers;
470     sfree(nb->timings);
471     delete nb;
472
473     if (debug)
474     {
475         fprintf(debug, "Cleaned up OpenCL data structures.\n");
476     }
477 }
478
479 //! This function is documented in the header file
480 int gpu_min_ci_balanced(NbnxmGpu* nb)
481 {
482     return nb != nullptr ? gpu_min_ci_balanced_factor * nb->deviceContext_->deviceInfo().compute_units : 0;
483 }
484
485 } // namespace Nbnxm