08da7ba983c871e61f0f094482461e329faef38f
[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/pmalloc.h"
56 #include "gromacs/hardware/device_information.h"
57 #include "gromacs/hardware/device_management.h"
58 #include "gromacs/math/vectypes.h"
59 #include "gromacs/mdlib/force_flags.h"
60 #include "gromacs/mdtypes/interaction_const.h"
61 #include "gromacs/mdtypes/md_enums.h"
62 #include "gromacs/nbnxm/atomdata.h"
63 #include "gromacs/nbnxm/gpu_data_mgmt.h"
64 #include "gromacs/nbnxm/gpu_jit_support.h"
65 #include "gromacs/nbnxm/nbnxm.h"
66 #include "gromacs/nbnxm/nbnxm_gpu.h"
67 #include "gromacs/nbnxm/nbnxm_gpu_data_mgmt.h"
68 #include "gromacs/nbnxm/pairlistsets.h"
69 #include "gromacs/pbcutil/ishift.h"
70 #include "gromacs/timing/gpu_timing.h"
71 #include "gromacs/utility/cstringutil.h"
72 #include "gromacs/utility/fatalerror.h"
73 #include "gromacs/utility/gmxassert.h"
74 #include "gromacs/utility/real.h"
75 #include "gromacs/utility/smalloc.h"
76
77 #include "nbnxm_ocl_types.h"
78
79 namespace Nbnxm
80 {
81
82 /*! \brief Copies of values from cl_driver_diagnostics_intel.h,
83  * which isn't guaranteed to be available. */
84 /**@{*/
85 #define CL_CONTEXT_SHOW_DIAGNOSTICS_INTEL 0x4106
86 #define CL_CONTEXT_DIAGNOSTICS_LEVEL_GOOD_INTEL 0x1
87 #define CL_CONTEXT_DIAGNOSTICS_LEVEL_BAD_INTEL 0x2
88 #define CL_CONTEXT_DIAGNOSTICS_LEVEL_NEUTRAL_INTEL 0x4
89 /**@}*/
90
91 /*! \brief This parameter should be determined heuristically from the
92  * kernel execution times
93  *
94  * This value is best for small systems on a single AMD Radeon R9 290X
95  * (and about 5% faster than 40, which is the default for CUDA
96  * devices). Larger simulation systems were quite insensitive to the
97  * value of this parameter.
98  */
99 static unsigned int gpu_min_ci_balanced_factor = 50;
100
101 /*! \brief Initializes the OpenCL kernel pointers of the nbnxn_ocl_ptr_t input data structure. */
102 static cl_kernel nbnxn_gpu_create_kernel(NbnxmGpu* nb, const char* kernel_name)
103 {
104     cl_kernel kernel;
105     cl_int    cl_error;
106
107     kernel = clCreateKernel(nb->dev_rundata->program, kernel_name, &cl_error);
108     if (CL_SUCCESS != cl_error)
109     {
110         gmx_fatal(FARGS,
111                   "Failed to create kernel '%s' for GPU #%s: OpenCL error %d",
112                   kernel_name,
113                   nb->deviceContext_->deviceInfo().device_name,
114                   cl_error);
115     }
116
117     return kernel;
118 }
119
120 /*! \brief Initializes the OpenCL kernel pointers of the nbnxn_ocl_ptr_t input data structure. */
121 static void nbnxn_gpu_init_kernels(NbnxmGpu* nb)
122 {
123     /* Init to 0 main kernel arrays */
124     /* They will be later on initialized in select_nbnxn_kernel */
125     // TODO: consider always creating all variants of the kernels here so that there is no
126     // need for late call to clCreateKernel -- if that gives any advantage?
127     memset(nb->kernel_ener_noprune_ptr, 0, sizeof(nb->kernel_ener_noprune_ptr));
128     memset(nb->kernel_ener_prune_ptr, 0, sizeof(nb->kernel_ener_prune_ptr));
129     memset(nb->kernel_noener_noprune_ptr, 0, sizeof(nb->kernel_noener_noprune_ptr));
130     memset(nb->kernel_noener_prune_ptr, 0, sizeof(nb->kernel_noener_prune_ptr));
131
132     /* Init pruning kernels
133      *
134      * TODO: we could avoid creating kernels if dynamic pruning is turned off,
135      * but ATM that depends on force flags not passed into the initialization.
136      */
137     nb->kernel_pruneonly[epruneFirst] = nbnxn_gpu_create_kernel(nb, "nbnxn_kernel_prune_opencl");
138     nb->kernel_pruneonly[epruneRolling] =
139             nbnxn_gpu_create_kernel(nb, "nbnxn_kernel_prune_rolling_opencl");
140 }
141
142 void gpu_init_platform_specific(NbnxmGpu* nb)
143 {
144     /* set device info, just point it to the right GPU among the detected ones */
145     nb->dev_rundata = new gmx_device_runtime_data_t();
146
147     /* Enable LJ param manual prefetch for AMD or Intel or if we request through env. var.
148      * TODO: decide about NVIDIA
149      */
150     nb->bPrefetchLjParam = (getenv("GMX_OCL_DISABLE_I_PREFETCH") == nullptr)
151                            && ((nb->deviceContext_->deviceInfo().deviceVendor == DeviceVendor::Amd)
152                                || (nb->deviceContext_->deviceInfo().deviceVendor == DeviceVendor::Intel)
153                                || (getenv("GMX_OCL_ENABLE_I_PREFETCH") != nullptr));
154
155     /* NOTE: in CUDA we pick L1 cache configuration for the nbnxn kernels here,
156      * but sadly this is not supported in OpenCL (yet?). Consider adding it if
157      * it becomes supported.
158      */
159     nbnxn_gpu_compile_kernels(nb);
160     nbnxn_gpu_init_kernels(nb);
161 }
162
163 //! This function is documented in the header file
164 void gpu_upload_shiftvec(NbnxmGpu* nb, const nbnxn_atomdata_t* nbatom)
165 {
166     NBAtomData*         adat        = nb->atdat;
167     const DeviceStream& localStream = *nb->deviceStreams[InteractionLocality::Local];
168
169     /* only if we have a dynamic box */
170     if (nbatom->bDynamicBox || !adat->shiftVecUploaded)
171     {
172         static_assert(sizeof(Float3) == sizeof(nbatom->shift_vec[0]),
173                       "Sizes of host- and device-side shift vectors should be the same.");
174         copyToDeviceBuffer(&adat->shiftVec,
175                            reinterpret_cast<const Float3*>(nbatom->shift_vec.data()),
176                            0,
177                            SHIFTS,
178                            localStream,
179                            GpuApiCallBehavior::Async,
180                            nullptr);
181         adat->shiftVecUploaded = true;
182     }
183 }
184
185 /*! \brief Releases an OpenCL kernel pointer */
186 static void free_kernel(cl_kernel* kernel_ptr)
187 {
188     cl_int gmx_unused cl_error;
189
190     GMX_ASSERT(kernel_ptr, "Need a valid kernel pointer");
191
192     if (*kernel_ptr)
193     {
194         cl_error = clReleaseKernel(*kernel_ptr);
195         GMX_RELEASE_ASSERT(cl_error == CL_SUCCESS,
196                            ("clReleaseKernel failed: " + ocl_get_error_string(cl_error)).c_str());
197
198         *kernel_ptr = nullptr;
199     }
200 }
201
202 /*! \brief Releases a list of OpenCL kernel pointers */
203 static void free_kernels(cl_kernel* kernels, int count)
204 {
205     int i;
206
207     for (i = 0; i < count; i++)
208     {
209         free_kernel(kernels + i);
210     }
211 }
212
213 /*! \brief Free the OpenCL program.
214  *
215  *  The function releases the OpenCL program assuciated with the
216  *  device that the calling PP rank is running on.
217  *
218  *  \param program [in]  OpenCL program to release.
219  */
220 static void freeGpuProgram(cl_program program)
221 {
222     if (program)
223     {
224         cl_int cl_error = clReleaseProgram(program);
225         GMX_RELEASE_ASSERT(cl_error == CL_SUCCESS,
226                            ("clReleaseProgram failed: " + ocl_get_error_string(cl_error)).c_str());
227         program = nullptr;
228     }
229 }
230
231 //! This function is documented in the header file
232 void gpu_free(NbnxmGpu* nb)
233 {
234     if (nb == nullptr)
235     {
236         return;
237     }
238
239     delete nb->timers;
240     sfree(nb->timings);
241
242     NBAtomData* atdat   = nb->atdat;
243     NBParamGpu* nbparam = nb->nbparam;
244
245     /* Free kernels */
246     // NOLINTNEXTLINE(bugprone-sizeof-expression)
247     int kernel_count = sizeof(nb->kernel_ener_noprune_ptr) / sizeof(nb->kernel_ener_noprune_ptr[0][0]);
248     free_kernels(nb->kernel_ener_noprune_ptr[0], kernel_count);
249
250     // NOLINTNEXTLINE(bugprone-sizeof-expression)
251     kernel_count = sizeof(nb->kernel_ener_prune_ptr) / sizeof(nb->kernel_ener_prune_ptr[0][0]);
252     free_kernels(nb->kernel_ener_prune_ptr[0], kernel_count);
253
254     // NOLINTNEXTLINE(bugprone-sizeof-expression)
255     kernel_count = sizeof(nb->kernel_noener_noprune_ptr) / sizeof(nb->kernel_noener_noprune_ptr[0][0]);
256     free_kernels(nb->kernel_noener_noprune_ptr[0], kernel_count);
257
258     // NOLINTNEXTLINE(bugprone-sizeof-expression)
259     kernel_count = sizeof(nb->kernel_noener_prune_ptr) / sizeof(nb->kernel_noener_prune_ptr[0][0]);
260     free_kernels(nb->kernel_noener_prune_ptr[0], kernel_count);
261
262     /* Free atdat */
263     freeDeviceBuffer(&(nb->atdat->xq));
264     freeDeviceBuffer(&(nb->atdat->f));
265     freeDeviceBuffer(&(nb->atdat->eLJ));
266     freeDeviceBuffer(&(nb->atdat->eElec));
267     freeDeviceBuffer(&(nb->atdat->fShift));
268     freeDeviceBuffer(&(nb->atdat->shiftVec));
269     if (useLjCombRule(nb->nbparam->vdwType))
270     {
271         freeDeviceBuffer(&atdat->ljComb);
272     }
273     else
274     {
275         freeDeviceBuffer(&atdat->atomTypes);
276     }
277
278     /* Free nbparam */
279     if (nbparam->elecType == ElecType::EwaldTab || nbparam->elecType == ElecType::EwaldTabTwin)
280     {
281         destroyParamLookupTable(&nbparam->coulomb_tab, nbparam->coulomb_tab_texobj);
282     }
283
284     if (!useLjCombRule(nb->nbparam->vdwType))
285     {
286         destroyParamLookupTable(&nbparam->nbfp, nbparam->nbfp_texobj);
287     }
288
289     if (nbparam->vdwType == VdwType::EwaldGeom || nbparam->vdwType == VdwType::EwaldLB)
290     {
291         destroyParamLookupTable(&nbparam->nbfp_comb, nbparam->nbfp_comb_texobj);
292     }
293
294     /* Free plist */
295     auto* plist = nb->plist[InteractionLocality::Local];
296     freeDeviceBuffer(&plist->sci);
297     freeDeviceBuffer(&plist->cj4);
298     freeDeviceBuffer(&plist->imask);
299     freeDeviceBuffer(&plist->excl);
300     delete plist;
301     if (nb->bUseTwoStreams)
302     {
303         auto* plist_nl = nb->plist[InteractionLocality::NonLocal];
304         freeDeviceBuffer(&plist_nl->sci);
305         freeDeviceBuffer(&plist_nl->cj4);
306         freeDeviceBuffer(&plist_nl->imask);
307         freeDeviceBuffer(&plist_nl->excl);
308         delete plist_nl;
309     }
310
311     /* Free nbst */
312     pfree(nb->nbst.eLJ);
313     nb->nbst.eLJ = nullptr;
314
315     pfree(nb->nbst.eElec);
316     nb->nbst.eElec = nullptr;
317
318     pfree(nb->nbst.fShift);
319     nb->nbst.fShift = nullptr;
320
321     freeGpuProgram(nb->dev_rundata->program);
322     delete nb->dev_rundata;
323
324     delete atdat;
325     delete nbparam;
326     delete nb;
327
328     if (debug)
329     {
330         fprintf(debug, "Cleaned up OpenCL data structures.\n");
331     }
332 }
333
334 //! This function is documented in the header file
335 int gpu_min_ci_balanced(NbnxmGpu* nb)
336 {
337     return nb != nullptr ? gpu_min_ci_balanced_factor * nb->deviceContext_->deviceInfo().compute_units : 0;
338 }
339
340 } // namespace Nbnxm