1df8cbe58a10464895362d64f47d72fa141864d5
[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 /*! \brief Releases an OpenCL kernel pointer */
164 static void free_kernel(cl_kernel* kernel_ptr)
165 {
166     cl_int gmx_unused cl_error;
167
168     GMX_ASSERT(kernel_ptr, "Need a valid kernel pointer");
169
170     if (*kernel_ptr)
171     {
172         cl_error = clReleaseKernel(*kernel_ptr);
173         GMX_RELEASE_ASSERT(cl_error == CL_SUCCESS,
174                            ("clReleaseKernel failed: " + ocl_get_error_string(cl_error)).c_str());
175
176         *kernel_ptr = nullptr;
177     }
178 }
179
180 /*! \brief Releases a list of OpenCL kernel pointers */
181 static void free_kernels(cl_kernel* kernels, int count)
182 {
183     int i;
184
185     for (i = 0; i < count; i++)
186     {
187         free_kernel(kernels + i);
188     }
189 }
190
191 /*! \brief Free the OpenCL program.
192  *
193  *  The function releases the OpenCL program assuciated with the
194  *  device that the calling PP rank is running on.
195  *
196  *  \param program [in]  OpenCL program to release.
197  */
198 static void freeGpuProgram(cl_program program)
199 {
200     if (program)
201     {
202         cl_int cl_error = clReleaseProgram(program);
203         GMX_RELEASE_ASSERT(cl_error == CL_SUCCESS,
204                            ("clReleaseProgram failed: " + ocl_get_error_string(cl_error)).c_str());
205         program = nullptr;
206     }
207 }
208
209 //! This function is documented in the header file
210 void gpu_free(NbnxmGpu* nb)
211 {
212     if (nb == nullptr)
213     {
214         return;
215     }
216
217     delete nb->timers;
218     sfree(nb->timings);
219
220     NBAtomData* atdat   = nb->atdat;
221     NBParamGpu* nbparam = nb->nbparam;
222
223     /* Free kernels */
224     // NOLINTNEXTLINE(bugprone-sizeof-expression)
225     int kernel_count = sizeof(nb->kernel_ener_noprune_ptr) / sizeof(nb->kernel_ener_noprune_ptr[0][0]);
226     free_kernels(nb->kernel_ener_noprune_ptr[0], kernel_count);
227
228     // NOLINTNEXTLINE(bugprone-sizeof-expression)
229     kernel_count = sizeof(nb->kernel_ener_prune_ptr) / sizeof(nb->kernel_ener_prune_ptr[0][0]);
230     free_kernels(nb->kernel_ener_prune_ptr[0], kernel_count);
231
232     // NOLINTNEXTLINE(bugprone-sizeof-expression)
233     kernel_count = sizeof(nb->kernel_noener_noprune_ptr) / sizeof(nb->kernel_noener_noprune_ptr[0][0]);
234     free_kernels(nb->kernel_noener_noprune_ptr[0], kernel_count);
235
236     // NOLINTNEXTLINE(bugprone-sizeof-expression)
237     kernel_count = sizeof(nb->kernel_noener_prune_ptr) / sizeof(nb->kernel_noener_prune_ptr[0][0]);
238     free_kernels(nb->kernel_noener_prune_ptr[0], kernel_count);
239
240     /* Free atdat */
241     freeDeviceBuffer(&(nb->atdat->xq));
242     freeDeviceBuffer(&(nb->atdat->f));
243     freeDeviceBuffer(&(nb->atdat->eLJ));
244     freeDeviceBuffer(&(nb->atdat->eElec));
245     freeDeviceBuffer(&(nb->atdat->fShift));
246     freeDeviceBuffer(&(nb->atdat->shiftVec));
247     if (useLjCombRule(nb->nbparam->vdwType))
248     {
249         freeDeviceBuffer(&atdat->ljComb);
250     }
251     else
252     {
253         freeDeviceBuffer(&atdat->atomTypes);
254     }
255
256     /* Free nbparam */
257     if (nbparam->elecType == ElecType::EwaldTab || nbparam->elecType == ElecType::EwaldTabTwin)
258     {
259         destroyParamLookupTable(&nbparam->coulomb_tab, nbparam->coulomb_tab_texobj);
260     }
261
262     if (!useLjCombRule(nb->nbparam->vdwType))
263     {
264         destroyParamLookupTable(&nbparam->nbfp, nbparam->nbfp_texobj);
265     }
266
267     if (nbparam->vdwType == VdwType::EwaldGeom || nbparam->vdwType == VdwType::EwaldLB)
268     {
269         destroyParamLookupTable(&nbparam->nbfp_comb, nbparam->nbfp_comb_texobj);
270     }
271
272     /* Free plist */
273     auto* plist = nb->plist[InteractionLocality::Local];
274     freeDeviceBuffer(&plist->sci);
275     freeDeviceBuffer(&plist->cj4);
276     freeDeviceBuffer(&plist->imask);
277     freeDeviceBuffer(&plist->excl);
278     delete plist;
279     if (nb->bUseTwoStreams)
280     {
281         auto* plist_nl = nb->plist[InteractionLocality::NonLocal];
282         freeDeviceBuffer(&plist_nl->sci);
283         freeDeviceBuffer(&plist_nl->cj4);
284         freeDeviceBuffer(&plist_nl->imask);
285         freeDeviceBuffer(&plist_nl->excl);
286         delete plist_nl;
287     }
288
289     /* Free nbst */
290     pfree(nb->nbst.eLJ);
291     nb->nbst.eLJ = nullptr;
292
293     pfree(nb->nbst.eElec);
294     nb->nbst.eElec = nullptr;
295
296     pfree(nb->nbst.fShift);
297     nb->nbst.fShift = nullptr;
298
299     freeGpuProgram(nb->dev_rundata->program);
300     delete nb->dev_rundata;
301
302     delete atdat;
303     delete nbparam;
304     delete nb;
305
306     if (debug)
307     {
308         fprintf(debug, "Cleaned up OpenCL data structures.\n");
309     }
310 }
311
312 //! This function is documented in the header file
313 int gpu_min_ci_balanced(NbnxmGpu* nb)
314 {
315     return nb != nullptr ? gpu_min_ci_balanced_factor * nb->deviceContext_->deviceInfo().compute_units : 0;
316 }
317
318 } // namespace Nbnxm