2 * This file is part of the GROMACS molecular simulation package.
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.
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.
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.
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.
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.
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.
37 * \brief Define OpenCL implementation of nbnxm_gpu_data_mgmt.h
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
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"
78 #include "nbnxm_ocl_types.h"
83 /*! \brief Copies of values from cl_driver_diagnostics_intel.h,
84 * which isn't guaranteed to be available. */
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
92 /*! \brief This parameter should be determined heuristically from the
93 * kernel execution times
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.
100 static unsigned int gpu_min_ci_balanced_factor = 50;
103 /*! \brief Initializes the atomdata structure first time, it only gets filled at
106 static void init_atomdata_first(NBAtomData* ad,
108 const DeviceContext& deviceContext,
109 const DeviceStream& localStream)
111 ad->numTypes = ntypes;
113 allocateDeviceBuffer(&ad->shiftVec, SHIFTS, deviceContext);
114 ad->shiftVecUploaded = false;
116 allocateDeviceBuffer(&ad->fShift, SHIFTS, deviceContext);
117 allocateDeviceBuffer(&ad->eLJ, 1, deviceContext);
118 allocateDeviceBuffer(&ad->eElec, 1, deviceContext);
120 clearDeviceBufferAsync(&ad->fShift, 0, SHIFTS, localStream);
121 clearDeviceBufferAsync(&ad->eElec, 0, 1, localStream);
122 clearDeviceBufferAsync(&ad->eLJ, 0, 1, localStream);
124 /* initialize to nullptr pointers to data that is not allocated here and will
125 need reallocation in nbnxn_gpu_init_atomdata */
129 /* size -1 indicates that the respective array hasn't been initialized yet */
131 ad->numAtomsAlloc = -1;
135 /*! \brief Initializes the nonbonded parameter data structure.
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)
143 set_cutoff_parameters(nbp, ic, listParams);
145 nbp->vdwType = nbnxmGpuPickVdwKernelType(ic, nbatParams.ljCombinationRule);
146 nbp->elecType = nbnxmGpuPickElectrostaticsKernelType(ic, deviceContext.deviceInfo());
148 if (ic->vdwtype == VanDerWaalsType::Pme)
150 if (ic->ljpme_comb_rule == LongRangeVdW::Geom)
152 GMX_ASSERT(nbatParams.ljCombinationRule == LJCombinationRule::Geometric,
153 "Combination rule mismatch!");
157 GMX_ASSERT(nbatParams.ljCombinationRule == LJCombinationRule::LorentzBerthelot,
158 "Combination rule mismatch!");
161 /* generate table for PME */
162 nbp->coulomb_tab = nullptr;
163 if (nbp->elecType == ElecType::EwaldTab || nbp->elecType == ElecType::EwaldTabTwin)
165 GMX_RELEASE_ASSERT(ic->coulombEwaldTables, "Need valid Coulomb Ewald correction tables");
166 init_ewald_coulomb_force_table(*ic->coulombEwaldTables, nbp, deviceContext);
170 allocateDeviceBuffer(&nbp->coulomb_tab, 1, deviceContext);
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,
180 reinterpret_cast<const Float2*>(nbatParams.nbfp.data()),
181 nbatParams.numTypes * nbatParams.numTypes,
185 if (ic->vdwtype == VanDerWaalsType::Pme)
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,
192 reinterpret_cast<const Float2*>(nbatParams.nbfp_comb.data()),
195 nbp->nbfp_comb = nbfp_comb;
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)
206 kernel = clCreateKernel(nb->dev_rundata->program, kernel_name, &cl_error);
207 if (CL_SUCCESS != cl_error)
210 "Failed to create kernel '%s' for GPU #%s: OpenCL error %d",
212 nb->deviceContext_->deviceInfo().device_name,
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)
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));
231 /* Init pruning kernels
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.
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");
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)
248 GMX_ASSERT(ic, "Need a valid interaction constants object");
250 auto nb = new NbnxmGpu();
251 nb->deviceContext_ = &deviceStreamManager.context();
253 snew(nb->nbparam, 1);
254 snew(nb->plist[InteractionLocality::Local], 1);
255 if (bLocalAndNonlocal)
257 snew(nb->plist[InteractionLocality::NonLocal], 1);
260 nb->bUseTwoStreams = bLocalAndNonlocal;
262 nb->timers = new Nbnxm::GpuTimers();
263 snew(nb->timings, 1);
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();
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));
273 init_plist(nb->plist[InteractionLocality::Local]);
275 /* OpenCL timing disabled if GMX_DISABLE_GPU_TIMING is defined. */
276 nb->bDoTime = (getenv("GMX_DISABLE_GPU_TIMING") == nullptr);
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;
284 if (nb->bUseTwoStreams)
286 init_plist(nb->plist[InteractionLocality::NonLocal]);
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);
297 init_timings(nb->timings);
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);
305 /* Enable LJ param manual prefetch for AMD or Intel or if we request through env. var.
306 * TODO: decide about NVIDIA
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));
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.
317 nbnxn_gpu_compile_kernels(nb);
318 nbnxn_gpu_init_kernels(nb);
322 fprintf(debug, "Initialized OpenCL data structures.\n");
328 //! This function is documented in the header file
329 void gpu_upload_shiftvec(NbnxmGpu* nb, const nbnxn_atomdata_t* nbatom)
331 NBAtomData* adat = nb->atdat;
332 const DeviceStream& localStream = *nb->deviceStreams[InteractionLocality::Local];
334 /* only if we have a dynamic box */
335 if (nbatom->bDynamicBox || !adat->shiftVecUploaded)
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()),
344 GpuApiCallBehavior::Async,
346 adat->shiftVecUploaded = true;
350 /*! \brief Releases an OpenCL kernel pointer */
351 static void free_kernel(cl_kernel* kernel_ptr)
353 cl_int gmx_unused cl_error;
355 GMX_ASSERT(kernel_ptr, "Need a valid kernel pointer");
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());
363 *kernel_ptr = nullptr;
367 /*! \brief Releases a list of OpenCL kernel pointers */
368 static void free_kernels(cl_kernel* kernels, int count)
372 for (i = 0; i < count; i++)
374 free_kernel(kernels + i);
378 /*! \brief Free the OpenCL program.
380 * The function releases the OpenCL program assuciated with the
381 * device that the calling PP rank is running on.
383 * \param program [in] OpenCL program to release.
385 static void freeGpuProgram(cl_program program)
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());
396 //! This function is documented in the header file
397 void gpu_free(NbnxmGpu* nb)
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);
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);
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);
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);
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));
433 freeDeviceBuffer(&(nb->nbparam->nbfp));
434 freeDeviceBuffer(&(nb->nbparam->nbfp_comb));
435 freeDeviceBuffer(&(nb->nbparam->coulomb_tab));
439 auto* plist = nb->plist[InteractionLocality::Local];
440 freeDeviceBuffer(&plist->sci);
441 freeDeviceBuffer(&plist->cj4);
442 freeDeviceBuffer(&plist->imask);
443 freeDeviceBuffer(&plist->excl);
445 if (nb->bUseTwoStreams)
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);
457 nb->nbst.eLJ = nullptr;
459 pfree(nb->nbst.eElec);
460 nb->nbst.eElec = nullptr;
462 pfree(nb->nbst.fShift);
463 nb->nbst.fShift = nullptr;
465 freeGpuProgram(nb->dev_rundata->program);
466 delete nb->dev_rundata;
468 /* Free timers and timings */
475 fprintf(debug, "Cleaned up OpenCL data structures.\n");
479 //! This function is documented in the header file
480 int gpu_min_ci_balanced(NbnxmGpu* nb)
482 return nb != nullptr ? gpu_min_ci_balanced_factor * nb->deviceContext_->deviceInfo().compute_units : 0;