2 * This file is part of the GROMACS molecular simulation package.
4 * Copyright (c) 2012,2013,2014,2015,2016,2017,2018,2019, by the GROMACS development team, led by
5 * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
6 * and including many others, as listed in the AUTHORS file in the
7 * top-level source directory and at http://www.gromacs.org.
9 * GROMACS is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public License
11 * as published by the Free Software Foundation; either version 2.1
12 * of the License, or (at your option) any later version.
14 * GROMACS is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with GROMACS; if not, see
21 * http://www.gnu.org/licenses, or write to the Free Software Foundation,
22 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
24 * If you want to redistribute modifications to GROMACS, please
25 * consider that scientific software is very special. Version
26 * control is crucial - bugs must be traceable. We will be happy to
27 * consider code for inclusion in the official distribution, but
28 * derived work must not be called official GROMACS. Details are found
29 * in the README & COPYING files - if they are missing, get the
30 * official version at http://www.gromacs.org.
32 * To help us fund GROMACS development, we humbly ask that you cite
33 * the research papers on the package. Check out http://www.gromacs.org.
36 * \brief Define OpenCL implementation of nbnxm_gpu_data_mgmt.h
38 * \author Anca Hamuraru <anca@streamcomputing.eu>
39 * \author Dimitrios Karkoulis <dimitris.karkoulis@gmail.com>
40 * \author Teemu Virolainen <teemu@streamcomputing.eu>
41 * \author Szilárd Páll <pall.szilard@gmail.com>
53 // TODO We would like to move this down, but the way gmx_nbnxn_gpu_t
54 // is currently declared means this has to be before gpu_types.h
55 #include "nbnxm_ocl_types.h"
57 // TODO Remove this comment when the above order issue is resolved
58 #include "gromacs/gpu_utils/gpu_utils.h"
59 #include "gromacs/gpu_utils/oclutils.h"
60 #include "gromacs/hardware/gpu_hw_info.h"
61 #include "gromacs/math/vectypes.h"
62 #include "gromacs/mdlib/force_flags.h"
63 #include "gromacs/mdtypes/interaction_const.h"
64 #include "gromacs/mdtypes/md_enums.h"
65 #include "gromacs/nbnxm/gpu_data_mgmt.h"
66 #include "gromacs/nbnxm/gpu_jit_support.h"
67 #include "gromacs/nbnxm/nbnxm.h"
68 #include "gromacs/nbnxm/nbnxm_gpu.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"
77 #include "nbnxm_ocl_internal.h"
82 /*! \brief This parameter should be determined heuristically from the
83 * kernel execution times
85 * This value is best for small systems on a single AMD Radeon R9 290X
86 * (and about 5% faster than 40, which is the default for CUDA
87 * devices). Larger simulation systems were quite insensitive to the
88 * value of this parameter.
90 static unsigned int gpu_min_ci_balanced_factor = 50;
93 /*! \brief Returns true if LJ combination rules are used in the non-bonded kernels.
95 * Full doc in nbnxn_ocl_internal.h */
96 bool useLjCombRule(int vdwType)
98 return (vdwType == evdwOclCUTCOMBGEOM ||
99 vdwType == evdwOclCUTCOMBLB);
102 /*! \brief Tabulates the Ewald Coulomb force and initializes the size/scale
103 * and the table GPU array.
105 * If called with an already allocated table, it just re-uploads the
108 static void init_ewald_coulomb_force_table(const interaction_const_t *ic,
110 const gmx_device_runtime_data_t *runData)
116 if (nbp->coulomb_tab_climg2d != nullptr)
118 freeDeviceBuffer(&(nbp->coulomb_tab_climg2d));
121 /* Switched from using textures to using buffers */
122 // TODO: decide which alternative is most efficient - textures or buffers.
124 cl_image_format array_format;
126 array_format.image_channel_data_type = CL_FLOAT;
127 array_format.image_channel_order = CL_R;
129 coul_tab = clCreateImage2D(runData->context, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR,
130 &array_format, tabsize, 1, 0, ftmp, &cl_error);
133 coul_tab = clCreateBuffer(runData->context, CL_MEM_READ_ONLY | CL_MEM_HOST_WRITE_ONLY | CL_MEM_COPY_HOST_PTR,
134 ic->tabq_size*sizeof(cl_float), ic->tabq_coul_F, &cl_error);
135 GMX_RELEASE_ASSERT(cl_error == CL_SUCCESS,
136 ("clCreateBuffer failed: " + ocl_get_error_string(cl_error)).c_str());
138 nbp->coulomb_tab_climg2d = coul_tab;
139 nbp->coulomb_tab_scale = ic->tabq_scale;
143 /*! \brief Initializes the atomdata structure first time, it only gets filled at
146 static void init_atomdata_first(cl_atomdata_t *ad, int ntypes, gmx_device_runtime_data_t *runData)
152 /* An element of the shift_vec device buffer has the same size as one element
153 of the host side shift_vec buffer. */
154 ad->shift_vec_elem_size = sizeof(*nbnxn_atomdata_t::shift_vec.data());
156 ad->shift_vec = clCreateBuffer(runData->context, CL_MEM_READ_ONLY | CL_MEM_HOST_WRITE_ONLY,
157 SHIFTS * ad->shift_vec_elem_size, nullptr, &cl_error);
158 GMX_RELEASE_ASSERT(cl_error == CL_SUCCESS,
159 ("clCreateBuffer failed: " + ocl_get_error_string(cl_error)).c_str());
160 ad->bShiftVecUploaded = CL_FALSE;
162 /* An element of the fshift device buffer has the same size as one element
163 of the host side fshift buffer. */
164 ad->fshift_elem_size = sizeof(*cl_nb_staging_t::fshift);
166 ad->fshift = clCreateBuffer(runData->context, CL_MEM_READ_WRITE | CL_MEM_HOST_READ_ONLY,
167 SHIFTS * ad->fshift_elem_size, nullptr, &cl_error);
168 GMX_RELEASE_ASSERT(cl_error == CL_SUCCESS,
169 ("clCreateBuffer failed: " + ocl_get_error_string(cl_error)).c_str());
171 ad->e_lj = clCreateBuffer(runData->context, CL_MEM_READ_WRITE | CL_MEM_HOST_READ_ONLY,
172 sizeof(float), nullptr, &cl_error);
173 GMX_RELEASE_ASSERT(cl_error == CL_SUCCESS,
174 ("clCreateBuffer failed: " + ocl_get_error_string(cl_error)).c_str());
176 ad->e_el = clCreateBuffer(runData->context, CL_MEM_READ_WRITE | CL_MEM_HOST_READ_ONLY,
177 sizeof(float), nullptr, &cl_error);
178 GMX_RELEASE_ASSERT(cl_error == CL_SUCCESS,
179 ("clCreateBuffer failed: " + ocl_get_error_string(cl_error)).c_str());
181 /* initialize to nullptr pointers to data that is not allocated here and will
182 need reallocation in nbnxn_gpu_init_atomdata */
186 /* size -1 indicates that the respective array hasn't been initialized yet */
191 /*! \brief Copies all parameters related to the cut-off from ic to nbp
193 static void set_cutoff_parameters(cl_nbparam_t *nbp,
194 const interaction_const_t *ic,
195 const NbnxnListParameters *listParams)
197 nbp->ewald_beta = ic->ewaldcoeff_q;
198 nbp->sh_ewald = ic->sh_ewald;
199 nbp->epsfac = ic->epsfac;
200 nbp->two_k_rf = 2.0 * ic->k_rf;
201 nbp->c_rf = ic->c_rf;
202 nbp->rvdw_sq = ic->rvdw * ic->rvdw;
203 nbp->rcoulomb_sq = ic->rcoulomb * ic->rcoulomb;
204 nbp->rlistOuter_sq = listParams->rlistOuter * listParams->rlistOuter;
205 nbp->rlistInner_sq = listParams->rlistInner * listParams->rlistInner;
206 nbp->useDynamicPruning = listParams->useDynamicPruning;
208 nbp->sh_lj_ewald = ic->sh_lj_ewald;
209 nbp->ewaldcoeff_lj = ic->ewaldcoeff_lj;
211 nbp->rvdw_switch = ic->rvdw_switch;
212 nbp->dispersion_shift = ic->dispersion_shift;
213 nbp->repulsion_shift = ic->repulsion_shift;
214 nbp->vdw_switch = ic->vdw_switch;
217 /*! \brief Returns the kinds of electrostatics and Vdw OpenCL
218 * kernels that will be used.
220 * Respectively, these values are from enum eelOcl and enum
223 map_interaction_types_to_gpu_kernel_flavors(const interaction_const_t *ic,
228 if (ic->vdwtype == evdwCUT)
230 switch (ic->vdw_modifier)
233 case eintmodPOTSHIFT:
237 *gpu_vdwtype = evdwOclCUT;
240 *gpu_vdwtype = evdwOclCUTCOMBGEOM;
243 *gpu_vdwtype = evdwOclCUTCOMBLB;
246 gmx_incons("The requested LJ combination rule is not implemented in the OpenCL GPU accelerated kernels!");
249 case eintmodFORCESWITCH:
250 *gpu_vdwtype = evdwOclFSWITCH;
252 case eintmodPOTSWITCH:
253 *gpu_vdwtype = evdwOclPSWITCH;
256 gmx_incons("The requested VdW interaction modifier is not implemented in the GPU accelerated kernels!");
259 else if (ic->vdwtype == evdwPME)
261 if (ic->ljpme_comb_rule == ljcrGEOM)
263 *gpu_vdwtype = evdwOclEWALDGEOM;
267 *gpu_vdwtype = evdwOclEWALDLB;
272 gmx_incons("The requested VdW type is not implemented in the GPU accelerated kernels!");
275 if (ic->eeltype == eelCUT)
277 *gpu_eeltype = eelOclCUT;
279 else if (EEL_RF(ic->eeltype))
281 *gpu_eeltype = eelOclRF;
283 else if ((EEL_PME(ic->eeltype) || ic->eeltype == eelEWALD))
285 /* Initially rcoulomb == rvdw, so it's surely not twin cut-off. */
286 *gpu_eeltype = gpu_pick_ewald_kernel_type(false);
290 /* Shouldn't happen, as this is checked when choosing Verlet-scheme */
291 gmx_incons("The requested electrostatics type is not implemented in the GPU accelerated kernels!");
295 /*! \brief Initializes the nonbonded parameter data structure.
297 static void init_nbparam(cl_nbparam_t *nbp,
298 const interaction_const_t *ic,
299 const NbnxnListParameters *listParams,
300 const nbnxn_atomdata_t::Params &nbatParams,
301 const gmx_device_runtime_data_t *runData)
305 set_cutoff_parameters(nbp, ic, listParams);
307 map_interaction_types_to_gpu_kernel_flavors(ic,
308 nbatParams.comb_rule,
312 if (ic->vdwtype == evdwPME)
314 if (ic->ljpme_comb_rule == ljcrGEOM)
316 GMX_ASSERT(nbatParams.comb_rule == ljcrGEOM, "Combination rule mismatch!");
320 GMX_ASSERT(nbatParams.comb_rule == ljcrLB, "Combination rule mismatch!");
323 /* generate table for PME */
324 nbp->coulomb_tab_climg2d = nullptr;
325 if (nbp->eeltype == eelOclEWALD_TAB || nbp->eeltype == eelOclEWALD_TAB_TWIN)
327 init_ewald_coulomb_force_table(ic, nbp, runData);
330 // TODO: improvement needed.
331 // The image2d is created here even if eeltype is not eelCuEWALD_TAB or eelCuEWALD_TAB_TWIN because the OpenCL kernels
332 // don't accept nullptr values for image2D parameters.
334 /* Switched from using textures to using buffers */
335 // TODO: decide which alternative is most efficient - textures or buffers.
337 cl_image_format array_format;
339 array_format.image_channel_data_type = CL_FLOAT;
340 array_format.image_channel_order = CL_R;
342 nbp->coulomb_tab_climg2d = clCreateImage2D(runData->context, CL_MEM_READ_WRITE,
343 &array_format, 1, 1, 0, nullptr, &cl_error);
346 nbp->coulomb_tab_climg2d = clCreateBuffer(runData->context, CL_MEM_READ_ONLY, sizeof(cl_float), nullptr, &cl_error);
347 GMX_RELEASE_ASSERT(cl_error == CL_SUCCESS,
348 ("clCreateBuffer failed: " + ocl_get_error_string(cl_error)).c_str());
351 const int nnbfp = 2*nbatParams.numTypes*nbatParams.numTypes;
352 const int nnbfp_comb = 2*nbatParams.numTypes;
355 /* Switched from using textures to using buffers */
356 // TODO: decide which alternative is most efficient - textures or buffers.
358 cl_image_format array_format;
360 array_format.image_channel_data_type = CL_FLOAT;
361 array_format.image_channel_order = CL_R;
363 nbp->nbfp_climg2d = clCreateImage2D(runData->context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR,
364 &array_format, nnbfp, 1, 0, nbat->nbfp, &cl_error);
368 clCreateBuffer(runData->context,
369 CL_MEM_READ_ONLY | CL_MEM_HOST_WRITE_ONLY | CL_MEM_COPY_HOST_PTR,
370 nnbfp*sizeof(cl_float),
371 const_cast<float *>(nbatParams.nbfp.data()),
373 GMX_RELEASE_ASSERT(cl_error == CL_SUCCESS,
374 ("clCreateBuffer failed: " + ocl_get_error_string(cl_error)).c_str());
376 if (ic->vdwtype == evdwPME)
378 /* Switched from using textures to using buffers */
379 // TODO: decide which alternative is most efficient - textures or buffers.
380 /* nbp->nbfp_comb_climg2d = clCreateImage2D(runData->context, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR,
381 &array_format, nnbfp_comb, 1, 0, nbat->nbfp_comb, &cl_error);*/
382 nbp->nbfp_comb_climg2d =
383 clCreateBuffer(runData->context,
384 CL_MEM_READ_ONLY | CL_MEM_HOST_WRITE_ONLY | CL_MEM_COPY_HOST_PTR,
385 nnbfp_comb*sizeof(cl_float),
386 const_cast<float *>(nbatParams.nbfp_comb.data()),
388 GMX_RELEASE_ASSERT(cl_error == CL_SUCCESS,
389 ("clCreateBuffer failed: " + ocl_get_error_string(cl_error)).c_str());
393 // TODO: improvement needed.
394 // The image2d is created here even if vdwtype is not evdwPME because the OpenCL kernels
395 // don't accept nullptr values for image2D parameters.
396 /* Switched from using textures to using buffers */
397 // TODO: decide which alternative is most efficient - textures or buffers.
398 /* nbp->nbfp_comb_climg2d = clCreateImage2D(runData->context, CL_MEM_READ_WRITE,
399 &array_format, 1, 1, 0, nullptr, &cl_error);*/
400 nbp->nbfp_comb_climg2d = clCreateBuffer(runData->context, CL_MEM_READ_ONLY, sizeof(cl_float), nullptr, &cl_error);
401 GMX_RELEASE_ASSERT(cl_error == CL_SUCCESS,
402 ("clCreateBuffer failed: " + ocl_get_error_string(cl_error)).c_str());
407 //! This function is documented in the header file
408 void gpu_pme_loadbal_update_param(const nonbonded_verlet_t *nbv,
409 const interaction_const_t *ic,
410 const NbnxnListParameters *listParams)
412 if (!nbv || nbv->grp[InteractionLocality::Local].kernel_type != nbnxnk8x8x8_GPU)
416 gmx_nbnxn_ocl_t *nb = nbv->gpu_nbv;
417 cl_nbparam_t *nbp = nb->nbparam;
419 set_cutoff_parameters(nbp, ic, listParams);
421 nbp->eeltype = gpu_pick_ewald_kernel_type(ic->rcoulomb != ic->rvdw);
423 init_ewald_coulomb_force_table(ic, nb->nbparam, nb->dev_rundata);
426 /*! \brief Initializes the pair list data structure.
428 static void init_plist(cl_plist_t *pl)
430 /* initialize to nullptr pointers to data that is not allocated here and will
431 need reallocation in nbnxn_gpu_init_pairlist */
437 /* size -1 indicates that the respective array hasn't been initialized yet */
444 pl->imask_nalloc = -1;
446 pl->excl_nalloc = -1;
447 pl->haveFreshList = false;
450 /*! \brief Initializes the timings data structure.
452 static void init_timings(gmx_wallclock_gpu_nbnxn_t *t)
461 for (i = 0; i < 2; i++)
463 for (j = 0; j < 2; j++)
465 t->ktime[i][j].t = 0.0;
466 t->ktime[i][j].c = 0;
471 t->pruneTime.t = 0.0;
472 t->dynamicPruneTime.c = 0;
473 t->dynamicPruneTime.t = 0.0;
476 /*! \brief Creates context for OpenCL GPU given by \p mygpu
478 * A fatal error results if creation fails.
480 * \param[inout] runtimeData runtime data including program and context
481 * \param[in] devInfo device info struct
482 * \param[in] rank MPI rank (for error reporting)
485 nbnxn_gpu_create_context(gmx_device_runtime_data_t *runtimeData,
486 const gmx_device_info_t *devInfo,
489 cl_context_properties context_properties[3];
490 cl_platform_id platform_id;
491 cl_device_id device_id;
495 assert(runtimeData != nullptr);
496 assert(devInfo != nullptr);
498 platform_id = devInfo->ocl_gpu_id.ocl_platform_id;
499 device_id = devInfo->ocl_gpu_id.ocl_device_id;
501 context_properties[0] = CL_CONTEXT_PLATFORM;
502 context_properties[1] = reinterpret_cast<cl_context_properties>(platform_id);
503 context_properties[2] = 0; /* Terminates the list of properties */
505 context = clCreateContext(context_properties, 1, &device_id, nullptr, nullptr, &cl_error);
506 if (CL_SUCCESS != cl_error)
508 gmx_fatal(FARGS, "On rank %d failed to create context for GPU #%s:\n OpenCL error %d: %s",
510 devInfo->device_name,
511 cl_error, ocl_get_error_string(cl_error).c_str());
514 runtimeData->context = context;
517 /*! \brief Initializes the OpenCL kernel pointers of the nbnxn_ocl_ptr_t input data structure. */
518 static cl_kernel nbnxn_gpu_create_kernel(gmx_nbnxn_ocl_t *nb,
519 const char *kernel_name)
524 kernel = clCreateKernel(nb->dev_rundata->program, kernel_name, &cl_error);
525 if (CL_SUCCESS != cl_error)
527 gmx_fatal(FARGS, "Failed to create kernel '%s' for GPU #%s: OpenCL error %d",
529 nb->dev_info->device_name,
536 /*! \brief Clears nonbonded shift force output array and energy outputs on the GPU.
539 nbnxn_ocl_clear_e_fshift(gmx_nbnxn_ocl_t *nb)
543 cl_atomdata_t * adat = nb->atdat;
544 cl_command_queue ls = nb->stream[InteractionLocality::Local];
546 size_t local_work_size[3] = {1, 1, 1};
547 size_t global_work_size[3] = {1, 1, 1};
549 cl_int shifts = SHIFTS*3;
553 cl_kernel zero_e_fshift = nb->kernel_zero_e_fshift;
555 local_work_size[0] = 64;
556 // Round the total number of threads up from the array size
557 global_work_size[0] = ((shifts + local_work_size[0] - 1)/local_work_size[0])*local_work_size[0];
560 cl_error = clSetKernelArg(zero_e_fshift, arg_no++, sizeof(cl_mem), &(adat->fshift));
561 cl_error |= clSetKernelArg(zero_e_fshift, arg_no++, sizeof(cl_mem), &(adat->e_lj));
562 cl_error |= clSetKernelArg(zero_e_fshift, arg_no++, sizeof(cl_mem), &(adat->e_el));
563 cl_error |= clSetKernelArg(zero_e_fshift, arg_no++, sizeof(cl_uint), &shifts);
564 GMX_ASSERT(cl_error == CL_SUCCESS, ocl_get_error_string(cl_error).c_str());
566 cl_error = clEnqueueNDRangeKernel(ls, zero_e_fshift, 3, nullptr, global_work_size, local_work_size, 0, nullptr, nullptr);
567 GMX_ASSERT(cl_error == CL_SUCCESS, ocl_get_error_string(cl_error).c_str());
570 /*! \brief Initializes the OpenCL kernel pointers of the nbnxn_ocl_ptr_t input data structure. */
571 static void nbnxn_gpu_init_kernels(gmx_nbnxn_ocl_t *nb)
573 /* Init to 0 main kernel arrays */
574 /* They will be later on initialized in select_nbnxn_kernel */
575 // TODO: consider always creating all variants of the kernels here so that there is no
576 // need for late call to clCreateKernel -- if that gives any advantage?
577 memset(nb->kernel_ener_noprune_ptr, 0, sizeof(nb->kernel_ener_noprune_ptr));
578 memset(nb->kernel_ener_prune_ptr, 0, sizeof(nb->kernel_ener_prune_ptr));
579 memset(nb->kernel_noener_noprune_ptr, 0, sizeof(nb->kernel_noener_noprune_ptr));
580 memset(nb->kernel_noener_prune_ptr, 0, sizeof(nb->kernel_noener_prune_ptr));
582 /* Init pruning kernels
584 * TODO: we could avoid creating kernels if dynamic pruning is turned off,
585 * but ATM that depends on force flags not passed into the initialization.
587 nb->kernel_pruneonly[epruneFirst] = nbnxn_gpu_create_kernel(nb, "nbnxn_kernel_prune_opencl");
588 nb->kernel_pruneonly[epruneRolling] = nbnxn_gpu_create_kernel(nb, "nbnxn_kernel_prune_rolling_opencl");
590 /* Init auxiliary kernels */
591 nb->kernel_zero_e_fshift = nbnxn_gpu_create_kernel(nb, "zero_e_fshift");
594 /*! \brief Initializes simulation constant data.
596 * Initializes members of the atomdata and nbparam structs and
597 * clears e/fshift output buffers.
599 static void nbnxn_ocl_init_const(gmx_nbnxn_ocl_t *nb,
600 const interaction_const_t *ic,
601 const NbnxnListParameters *listParams,
602 const nbnxn_atomdata_t::Params &nbatParams)
604 init_atomdata_first(nb->atdat, nbatParams.numTypes, nb->dev_rundata);
605 init_nbparam(nb->nbparam, ic, listParams, nbatParams, nb->dev_rundata);
609 //! This function is documented in the header file
610 void gpu_init(gmx_nbnxn_ocl_t **p_nb,
611 const gmx_device_info_t *deviceInfo,
612 const interaction_const_t *ic,
613 const NbnxnListParameters *listParams,
614 const nbnxn_atomdata_t *nbat,
616 const gmx_bool bLocalAndNonlocal)
620 cl_command_queue_properties queue_properties;
631 snew(nb->nbparam, 1);
632 snew(nb->plist[InteractionLocality::Local], 1);
633 if (bLocalAndNonlocal)
635 snew(nb->plist[InteractionLocality::NonLocal], 1);
638 nb->bUseTwoStreams = static_cast<cl_bool>(bLocalAndNonlocal);
640 nb->timers = new cl_timers_t();
641 snew(nb->timings, 1);
643 /* set device info, just point it to the right GPU among the detected ones */
644 nb->dev_info = deviceInfo;
645 snew(nb->dev_rundata, 1);
648 pmalloc(reinterpret_cast<void**>(&nb->nbst.e_lj), sizeof(*nb->nbst.e_lj));
649 pmalloc(reinterpret_cast<void**>(&nb->nbst.e_el), sizeof(*nb->nbst.e_el));
650 pmalloc(reinterpret_cast<void**>(&nb->nbst.fshift), SHIFTS * sizeof(*nb->nbst.fshift));
652 init_plist(nb->plist[InteractionLocality::Local]);
654 /* OpenCL timing disabled if GMX_DISABLE_GPU_TIMING is defined. */
655 nb->bDoTime = static_cast<cl_bool>(getenv("GMX_DISABLE_GPU_TIMING") == nullptr);
657 /* Create queues only after bDoTime has been initialized */
660 queue_properties = CL_QUEUE_PROFILING_ENABLE;
664 queue_properties = 0;
667 nbnxn_gpu_create_context(nb->dev_rundata, nb->dev_info, rank);
669 /* local/non-local GPU streams */
670 nb->stream[InteractionLocality::Local] =
671 clCreateCommandQueue(nb->dev_rundata->context, nb->dev_info->ocl_gpu_id.ocl_device_id, queue_properties, &cl_error);
672 if (CL_SUCCESS != cl_error)
674 gmx_fatal(FARGS, "On rank %d failed to create context for GPU #%s: OpenCL error %d",
676 nb->dev_info->device_name,
680 if (nb->bUseTwoStreams)
682 init_plist(nb->plist[InteractionLocality::NonLocal]);
684 nb->stream[InteractionLocality::NonLocal] =
685 clCreateCommandQueue(nb->dev_rundata->context, nb->dev_info->ocl_gpu_id.ocl_device_id, queue_properties, &cl_error);
686 if (CL_SUCCESS != cl_error)
688 gmx_fatal(FARGS, "On rank %d failed to create context for GPU #%s: OpenCL error %d",
690 nb->dev_info->device_name,
697 init_timings(nb->timings);
700 nbnxn_ocl_init_const(nb, ic, listParams, nbat->params());
702 /* Enable LJ param manual prefetch for AMD or Intel or if we request through env. var.
703 * TODO: decide about NVIDIA
705 nb->bPrefetchLjParam =
706 (getenv("GMX_OCL_DISABLE_I_PREFETCH") == nullptr) &&
707 ((nb->dev_info->vendor_e == OCL_VENDOR_AMD) || (nb->dev_info->vendor_e == OCL_VENDOR_INTEL)
708 || (getenv("GMX_OCL_ENABLE_I_PREFETCH") != nullptr));
710 /* NOTE: in CUDA we pick L1 cache configuration for the nbnxn kernels here,
711 * but sadly this is not supported in OpenCL (yet?). Consider adding it if
712 * it becomes supported.
714 nbnxn_gpu_compile_kernels(nb);
715 nbnxn_gpu_init_kernels(nb);
717 /* clear energy and shift force outputs */
718 nbnxn_ocl_clear_e_fshift(nb);
724 fprintf(debug, "Initialized OpenCL data structures.\n");
728 /*! \brief Clears the first natoms_clear elements of the GPU nonbonded force output array.
730 static void nbnxn_ocl_clear_f(gmx_nbnxn_ocl_t *nb, int natoms_clear)
732 if (natoms_clear == 0)
737 cl_int gmx_used_in_debug cl_error;
739 cl_atomdata_t *atomData = nb->atdat;
740 cl_command_queue ls = nb->stream[InteractionLocality::Local];
741 cl_float value = 0.0f;
743 cl_error = clEnqueueFillBuffer(ls, atomData->f, &value, sizeof(cl_float),
744 0, natoms_clear*sizeof(rvec), 0, nullptr, nullptr);
745 GMX_RELEASE_ASSERT(cl_error == CL_SUCCESS, ("clEnqueueFillBuffer failed: " +
746 ocl_get_error_string(cl_error)).c_str());
749 //! This function is documented in the header file
751 gpu_clear_outputs(gmx_nbnxn_ocl_t *nb,
754 nbnxn_ocl_clear_f(nb, nb->atdat->natoms);
755 /* clear shift force array and energies if the outputs were
756 used in the current step */
757 if (flags & GMX_FORCE_VIRIAL)
759 nbnxn_ocl_clear_e_fshift(nb);
762 /* kick off buffer clearing kernel to ensure concurrency with constraints/update */
763 cl_int gmx_unused cl_error;
764 cl_error = clFlush(nb->stream[InteractionLocality::Local]);
765 assert(CL_SUCCESS == cl_error);
768 //! This function is documented in the header file
769 void gpu_init_pairlist(gmx_nbnxn_ocl_t *nb,
770 const NbnxnPairlistGpu *h_plist,
771 const InteractionLocality iloc)
774 // Timing accumulation should happen only if there was work to do
775 // because getLastRangeTime() gets skipped with empty lists later
776 // which leads to the counter not being reset.
777 bool bDoTime = ((nb->bDoTime == CL_TRUE) && !h_plist->sci.empty());
778 cl_command_queue stream = nb->stream[iloc];
779 cl_plist_t *d_plist = nb->plist[iloc];
781 if (d_plist->na_c < 0)
783 d_plist->na_c = h_plist->na_ci;
787 if (d_plist->na_c != h_plist->na_ci)
789 sprintf(sbuf, "In cu_init_plist: the #atoms per cell has changed (from %d to %d)",
790 d_plist->na_c, h_plist->na_ci);
795 gpu_timers_t::Interaction &iTimers = nb->timers->interaction[iloc];
799 iTimers.pl_h2d.openTimingRegion(stream);
800 iTimers.didPairlistH2D = true;
803 // TODO most of this function is same in CUDA and OpenCL, move into the header
804 Context context = nb->dev_rundata->context;
806 reallocateDeviceBuffer(&d_plist->sci, h_plist->sci.size(),
807 &d_plist->nsci, &d_plist->sci_nalloc, context);
808 copyToDeviceBuffer(&d_plist->sci, h_plist->sci.data(), 0, h_plist->sci.size(),
809 stream, GpuApiCallBehavior::Async,
810 bDoTime ? iTimers.pl_h2d.fetchNextEvent() : nullptr);
812 reallocateDeviceBuffer(&d_plist->cj4, h_plist->cj4.size(),
813 &d_plist->ncj4, &d_plist->cj4_nalloc, context);
814 copyToDeviceBuffer(&d_plist->cj4, h_plist->cj4.data(), 0, h_plist->cj4.size(),
815 stream, GpuApiCallBehavior::Async,
816 bDoTime ? iTimers.pl_h2d.fetchNextEvent() : nullptr);
818 reallocateDeviceBuffer(&d_plist->imask, h_plist->cj4.size()*c_nbnxnGpuClusterpairSplit,
819 &d_plist->nimask, &d_plist->imask_nalloc, context);
821 reallocateDeviceBuffer(&d_plist->excl, h_plist->excl.size(),
822 &d_plist->nexcl, &d_plist->excl_nalloc, context);
823 copyToDeviceBuffer(&d_plist->excl, h_plist->excl.data(), 0, h_plist->excl.size(),
824 stream, GpuApiCallBehavior::Async,
825 bDoTime ? iTimers.pl_h2d.fetchNextEvent() : nullptr);
829 iTimers.pl_h2d.closeTimingRegion(stream);
832 /* need to prune the pair list during the next step */
833 d_plist->haveFreshList = true;
836 //! This function is documented in the header file
837 void gpu_upload_shiftvec(gmx_nbnxn_ocl_t *nb,
838 const nbnxn_atomdata_t *nbatom)
840 cl_atomdata_t *adat = nb->atdat;
841 cl_command_queue ls = nb->stream[InteractionLocality::Local];
843 /* only if we have a dynamic box */
844 if (nbatom->bDynamicBox || !adat->bShiftVecUploaded)
846 ocl_copy_H2D_async(adat->shift_vec, nbatom->shift_vec.data(), 0,
847 SHIFTS * adat->shift_vec_elem_size, ls, nullptr);
848 adat->bShiftVecUploaded = CL_TRUE;
852 //! This function is documented in the header file
853 void gpu_init_atomdata(gmx_nbnxn_ocl_t *nb,
854 const nbnxn_atomdata_t *nbat)
859 bool bDoTime = nb->bDoTime == CL_TRUE;
860 cl_timers_t *timers = nb->timers;
861 cl_atomdata_t *d_atdat = nb->atdat;
862 cl_command_queue ls = nb->stream[InteractionLocality::Local];
864 natoms = nbat->numAtoms();
869 /* time async copy */
870 timers->atdat.openTimingRegion(ls);
873 /* need to reallocate if we have to copy more atoms than the amount of space
874 available and only allocate if we haven't initialized yet, i.e d_atdat->natoms == -1 */
875 if (natoms > d_atdat->nalloc)
877 nalloc = over_alloc_small(natoms);
879 /* free up first if the arrays have already been initialized */
880 if (d_atdat->nalloc != -1)
882 freeDeviceBuffer(&d_atdat->f);
883 freeDeviceBuffer(&d_atdat->xq);
884 freeDeviceBuffer(&d_atdat->lj_comb);
885 freeDeviceBuffer(&d_atdat->atom_types);
888 d_atdat->f_elem_size = sizeof(rvec);
890 d_atdat->f = clCreateBuffer(nb->dev_rundata->context, CL_MEM_READ_WRITE | CL_MEM_HOST_READ_ONLY,
891 nalloc * d_atdat->f_elem_size, nullptr, &cl_error);
892 GMX_RELEASE_ASSERT(cl_error == CL_SUCCESS,
893 ("clCreateBuffer failed: " + ocl_get_error_string(cl_error)).c_str());
895 d_atdat->xq = clCreateBuffer(nb->dev_rundata->context, CL_MEM_READ_ONLY | CL_MEM_HOST_WRITE_ONLY,
896 nalloc * sizeof(cl_float4), nullptr, &cl_error);
897 GMX_RELEASE_ASSERT(cl_error == CL_SUCCESS,
898 ("clCreateBuffer failed: " + ocl_get_error_string(cl_error)).c_str());
900 if (useLjCombRule(nb->nbparam->vdwtype))
902 d_atdat->lj_comb = clCreateBuffer(nb->dev_rundata->context, CL_MEM_READ_ONLY | CL_MEM_HOST_WRITE_ONLY,
903 nalloc * sizeof(cl_float2), nullptr, &cl_error);
904 GMX_RELEASE_ASSERT(cl_error == CL_SUCCESS,
905 ("clCreateBuffer failed: " + ocl_get_error_string(cl_error)).c_str());
909 d_atdat->atom_types = clCreateBuffer(nb->dev_rundata->context, CL_MEM_READ_ONLY | CL_MEM_HOST_WRITE_ONLY,
910 nalloc * sizeof(int), nullptr, &cl_error);
911 GMX_RELEASE_ASSERT(cl_error == CL_SUCCESS,
912 ("clCreateBuffer failed: " + ocl_get_error_string(cl_error)).c_str());
915 d_atdat->nalloc = nalloc;
919 d_atdat->natoms = natoms;
920 d_atdat->natoms_local = nbat->natoms_local;
922 /* need to clear GPU f output if realloc happened */
925 nbnxn_ocl_clear_f(nb, nalloc);
928 if (useLjCombRule(nb->nbparam->vdwtype))
930 ocl_copy_H2D_async(d_atdat->lj_comb, nbat->params().lj_comb.data(), 0,
931 natoms*sizeof(cl_float2), ls, bDoTime ? timers->atdat.fetchNextEvent() : nullptr);
935 ocl_copy_H2D_async(d_atdat->atom_types, nbat->params().type.data(), 0,
936 natoms*sizeof(int), ls, bDoTime ? timers->atdat.fetchNextEvent() : nullptr);
942 timers->atdat.closeTimingRegion(ls);
945 /* kick off the tasks enqueued above to ensure concurrency with the search */
946 cl_error = clFlush(ls);
947 GMX_RELEASE_ASSERT(cl_error == CL_SUCCESS,
948 ("clFlush failed: " + ocl_get_error_string(cl_error)).c_str());
951 /*! \brief Releases an OpenCL kernel pointer */
952 static void free_kernel(cl_kernel *kernel_ptr)
954 cl_int gmx_unused cl_error;
956 assert(nullptr != kernel_ptr);
960 cl_error = clReleaseKernel(*kernel_ptr);
961 GMX_RELEASE_ASSERT(cl_error == CL_SUCCESS, ("clReleaseKernel failed: " + ocl_get_error_string(cl_error)).c_str());
963 *kernel_ptr = nullptr;
967 /*! \brief Releases a list of OpenCL kernel pointers */
968 static void free_kernels(cl_kernel *kernels, int count)
972 for (i = 0; i < count; i++)
974 free_kernel(kernels + i);
978 /*! \brief Free the OpenCL runtime data (context and program).
980 * The function releases the OpenCL context and program assuciated with the
981 * device that the calling PP rank is running on.
983 * \param runData [in] porinter to the structure with runtime data.
985 static void free_gpu_device_runtime_data(gmx_device_runtime_data_t *runData)
987 if (runData == nullptr)
992 cl_int gmx_unused cl_error;
994 if (runData->context)
996 cl_error = clReleaseContext(runData->context);
997 GMX_RELEASE_ASSERT(cl_error == CL_SUCCESS, ("clReleaseContext failed: " + ocl_get_error_string(cl_error)).c_str());
998 runData->context = nullptr;
1001 if (runData->program)
1003 cl_error = clReleaseProgram(runData->program);
1004 GMX_RELEASE_ASSERT(cl_error == CL_SUCCESS, ("clReleaseProgram failed: " + ocl_get_error_string(cl_error)).c_str());
1005 runData->program = nullptr;
1010 //! This function is documented in the header file
1011 void gpu_free(gmx_nbnxn_ocl_t *nb)
1019 int kernel_count = sizeof(nb->kernel_ener_noprune_ptr) / sizeof(nb->kernel_ener_noprune_ptr[0][0]);
1020 free_kernels(nb->kernel_ener_noprune_ptr[0], kernel_count);
1022 kernel_count = sizeof(nb->kernel_ener_prune_ptr) / sizeof(nb->kernel_ener_prune_ptr[0][0]);
1023 free_kernels(nb->kernel_ener_prune_ptr[0], kernel_count);
1025 kernel_count = sizeof(nb->kernel_noener_noprune_ptr) / sizeof(nb->kernel_noener_noprune_ptr[0][0]);
1026 free_kernels(nb->kernel_noener_noprune_ptr[0], kernel_count);
1028 kernel_count = sizeof(nb->kernel_noener_prune_ptr) / sizeof(nb->kernel_noener_prune_ptr[0][0]);
1029 free_kernels(nb->kernel_noener_prune_ptr[0], kernel_count);
1031 free_kernel(&(nb->kernel_zero_e_fshift));
1034 freeDeviceBuffer(&(nb->atdat->xq));
1035 freeDeviceBuffer(&(nb->atdat->f));
1036 freeDeviceBuffer(&(nb->atdat->e_lj));
1037 freeDeviceBuffer(&(nb->atdat->e_el));
1038 freeDeviceBuffer(&(nb->atdat->fshift));
1039 freeDeviceBuffer(&(nb->atdat->lj_comb));
1040 freeDeviceBuffer(&(nb->atdat->atom_types));
1041 freeDeviceBuffer(&(nb->atdat->shift_vec));
1045 freeDeviceBuffer(&(nb->nbparam->nbfp_climg2d));
1046 freeDeviceBuffer(&(nb->nbparam->nbfp_comb_climg2d));
1047 freeDeviceBuffer(&(nb->nbparam->coulomb_tab_climg2d));
1051 auto *plist = nb->plist[InteractionLocality::Local];
1052 freeDeviceBuffer(&plist->sci);
1053 freeDeviceBuffer(&plist->cj4);
1054 freeDeviceBuffer(&plist->imask);
1055 freeDeviceBuffer(&plist->excl);
1057 if (nb->bUseTwoStreams)
1059 auto *plist_nl = nb->plist[InteractionLocality::NonLocal];
1060 freeDeviceBuffer(&plist_nl->sci);
1061 freeDeviceBuffer(&plist_nl->cj4);
1062 freeDeviceBuffer(&plist_nl->imask);
1063 freeDeviceBuffer(&plist_nl->excl);
1068 pfree(nb->nbst.e_lj);
1069 nb->nbst.e_lj = nullptr;
1071 pfree(nb->nbst.e_el);
1072 nb->nbst.e_el = nullptr;
1074 pfree(nb->nbst.fshift);
1075 nb->nbst.fshift = nullptr;
1077 /* Free command queues */
1078 clReleaseCommandQueue(nb->stream[InteractionLocality::Local]);
1079 nb->stream[InteractionLocality::Local] = nullptr;
1080 if (nb->bUseTwoStreams)
1082 clReleaseCommandQueue(nb->stream[InteractionLocality::NonLocal]);
1083 nb->stream[InteractionLocality::NonLocal] = nullptr;
1085 /* Free other events */
1086 if (nb->nonlocal_done)
1088 clReleaseEvent(nb->nonlocal_done);
1089 nb->nonlocal_done = nullptr;
1091 if (nb->misc_ops_and_local_H2D_done)
1093 clReleaseEvent(nb->misc_ops_and_local_H2D_done);
1094 nb->misc_ops_and_local_H2D_done = nullptr;
1097 free_gpu_device_runtime_data(nb->dev_rundata);
1098 sfree(nb->dev_rundata);
1100 /* Free timers and timings */
1107 fprintf(debug, "Cleaned up OpenCL data structures.\n");
1111 //! This function is documented in the header file
1112 gmx_wallclock_gpu_nbnxn_t *gpu_get_timings(gmx_nbnxn_ocl_t *nb)
1114 return (nb != nullptr && nb->bDoTime) ? nb->timings : nullptr;
1117 //! This function is documented in the header file
1118 void gpu_reset_timings(nonbonded_verlet_t* nbv)
1120 if (nbv->gpu_nbv && nbv->gpu_nbv->bDoTime)
1122 init_timings(nbv->gpu_nbv->timings);
1126 //! This function is documented in the header file
1127 int gpu_min_ci_balanced(gmx_nbnxn_ocl_t *nb)
1129 return nb != nullptr ?
1130 gpu_min_ci_balanced_factor * nb->dev_info->compute_units : 0;
1133 //! This function is documented in the header file
1134 gmx_bool gpu_is_kernel_ewald_analytical(const gmx_nbnxn_ocl_t *nb)
1136 return ((nb->nbparam->eeltype == eelOclEWALD_ANA) ||
1137 (nb->nbparam->eeltype == eelOclEWALD_ANA_TWIN));
1140 } // namespace Nbnxm