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, 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 CUDA implementation of nbnxn_gpu_data_mgmt.h
39 * \author Szilard Pall <pall.szilard@gmail.com>
48 // TODO We would like to move this down, but the way NbnxmGpu
49 // is currently declared means this has to be before gpu_types.h
50 #include "nbnxm_cuda_types.h"
52 // TODO Remove this comment when the above order issue is resolved
53 #include "gromacs/gpu_utils/cudautils.cuh"
54 #include "gromacs/gpu_utils/device_stream_manager.h"
55 #include "gromacs/gpu_utils/gpu_utils.h"
56 #include "gromacs/gpu_utils/gpueventsynchronizer.cuh"
57 #include "gromacs/gpu_utils/pmalloc_cuda.h"
58 #include "gromacs/hardware/gpu_hw_info.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/gridset.h"
66 #include "gromacs/nbnxm/nbnxm.h"
67 #include "gromacs/nbnxm/nbnxm_gpu.h"
68 #include "gromacs/nbnxm/pairlistsets.h"
69 #include "gromacs/pbcutil/ishift.h"
70 #include "gromacs/timing/gpu_timing.h"
71 #include "gromacs/utility/basedefinitions.h"
72 #include "gromacs/utility/cstringutil.h"
73 #include "gromacs/utility/fatalerror.h"
74 #include "gromacs/utility/real.h"
75 #include "gromacs/utility/smalloc.h"
77 #include "nbnxm_cuda.h"
82 /* This is a heuristically determined parameter for the Kepler
83 * and Maxwell architectures for the minimum size of ci lists by multiplying
84 * this constant with the # of multiprocessors on the current device.
85 * Since the maximum number of blocks per multiprocessor is 16, the ideal
86 * count for small systems is 32 or 48 blocks per multiprocessor. Because
87 * there is a bit of fluctuations in the generated block counts, we use
88 * a target of 44 instead of the ideal value of 48.
90 static unsigned int gpu_min_ci_balanced_factor = 44;
93 static void nbnxn_cuda_clear_e_fshift(NbnxmGpu* nb);
96 static void nbnxn_cuda_free_nbparam_table(NBParamGpu* nbparam);
98 /*! \brief Initialized the Ewald Coulomb correction GPU table.
100 Tabulates the Ewald Coulomb force and initializes the size/scale
101 and the table GPU array. If called with an already allocated table,
102 it just re-uploads the table.
104 static void init_ewald_coulomb_force_table(const EwaldCorrectionTables& tables,
106 const DeviceContext& deviceContext)
108 if (nbp->coulomb_tab != nullptr)
110 nbnxn_cuda_free_nbparam_table(nbp);
113 nbp->coulomb_tab_scale = tables.scale;
114 initParamLookupTable(&nbp->coulomb_tab, &nbp->coulomb_tab_texobj, tables.tableF.data(),
115 tables.tableF.size(), deviceContext);
119 /*! Initializes the atomdata structure first time, it only gets filled at
121 static void init_atomdata_first(cu_atomdata_t* ad, int ntypes, const DeviceContext& deviceContext)
124 allocateDeviceBuffer(&ad->shift_vec, SHIFTS, deviceContext);
125 ad->bShiftVecUploaded = false;
127 allocateDeviceBuffer(&ad->fshift, SHIFTS, deviceContext);
128 allocateDeviceBuffer(&ad->e_lj, 1, deviceContext);
129 allocateDeviceBuffer(&ad->e_el, 1, deviceContext);
131 /* initialize to nullptr poiters to data that is not allocated here and will
132 need reallocation in nbnxn_cuda_init_atomdata */
136 /* size -1 indicates that the respective array hasn't been initialized yet */
141 /*! Selects the Ewald kernel type, analytical on SM 3.0 and later, tabulated on
142 earlier GPUs, single or twin cut-off. */
143 static int pick_ewald_kernel_type(const interaction_const_t& ic)
145 bool bTwinCut = (ic.rcoulomb != ic.rvdw);
146 bool bUseAnalyticalEwald, bForceAnalyticalEwald, bForceTabulatedEwald;
149 /* Benchmarking/development environment variables to force the use of
150 analytical or tabulated Ewald kernel. */
151 bForceAnalyticalEwald = (getenv("GMX_CUDA_NB_ANA_EWALD") != nullptr);
152 bForceTabulatedEwald = (getenv("GMX_CUDA_NB_TAB_EWALD") != nullptr);
154 if (bForceAnalyticalEwald && bForceTabulatedEwald)
157 "Both analytical and tabulated Ewald CUDA non-bonded kernels "
158 "requested through environment variables.");
161 /* By default use analytical Ewald. */
162 bUseAnalyticalEwald = true;
163 if (bForceAnalyticalEwald)
167 fprintf(debug, "Using analytical Ewald CUDA kernels\n");
170 else if (bForceTabulatedEwald)
172 bUseAnalyticalEwald = false;
176 fprintf(debug, "Using tabulated Ewald CUDA kernels\n");
180 /* Use twin cut-off kernels if requested by bTwinCut or the env. var.
181 forces it (use it for debugging/benchmarking only). */
182 if (!bTwinCut && (getenv("GMX_CUDA_NB_EWALD_TWINCUT") == nullptr))
184 kernel_type = bUseAnalyticalEwald ? eelTypeEWALD_ANA : eelTypeEWALD_TAB;
188 kernel_type = bUseAnalyticalEwald ? eelTypeEWALD_ANA_TWIN : eelTypeEWALD_TAB_TWIN;
194 /*! Copies all parameters related to the cut-off from ic to nbp */
195 static void set_cutoff_parameters(NBParamGpu* nbp, const interaction_const_t* ic, const PairlistParams& 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 /*! Initializes the nonbonded parameter data structure. */
218 static void init_nbparam(NBParamGpu* nbp,
219 const interaction_const_t* ic,
220 const PairlistParams& listParams,
221 const nbnxn_atomdata_t::Params& nbatParams,
222 const DeviceContext& deviceContext)
226 ntypes = nbatParams.numTypes;
228 set_cutoff_parameters(nbp, ic, listParams);
230 /* The kernel code supports LJ combination rules (geometric and LB) for
231 * all kernel types, but we only generate useful combination rule kernels.
232 * We currently only use LJ combination rule (geometric and LB) kernels
233 * for plain cut-off LJ. On Maxwell the force only kernels speed up 15%
234 * with PME and 20% with RF, the other kernels speed up about half as much.
235 * For LJ force-switch the geometric rule would give 7% speed-up, but this
236 * combination is rarely used. LJ force-switch with LB rule is more common,
237 * but gives only 1% speed-up.
239 if (ic->vdwtype == evdwCUT)
241 switch (ic->vdw_modifier)
244 case eintmodPOTSHIFT:
245 switch (nbatParams.comb_rule)
247 case ljcrNONE: nbp->vdwtype = evdwTypeCUT; break;
248 case ljcrGEOM: nbp->vdwtype = evdwTypeCUTCOMBGEOM; break;
249 case ljcrLB: nbp->vdwtype = evdwTypeCUTCOMBLB; break;
252 "The requested LJ combination rule is not implemented in the CUDA "
253 "GPU accelerated kernels!");
256 case eintmodFORCESWITCH: nbp->vdwtype = evdwTypeFSWITCH; break;
257 case eintmodPOTSWITCH: nbp->vdwtype = evdwTypePSWITCH; break;
260 "The requested VdW interaction modifier is not implemented in the CUDA GPU "
261 "accelerated kernels!");
264 else if (ic->vdwtype == evdwPME)
266 if (ic->ljpme_comb_rule == ljcrGEOM)
268 assert(nbatParams.comb_rule == ljcrGEOM);
269 nbp->vdwtype = evdwTypeEWALDGEOM;
273 assert(nbatParams.comb_rule == ljcrLB);
274 nbp->vdwtype = evdwTypeEWALDLB;
280 "The requested VdW type is not implemented in the CUDA GPU accelerated kernels!");
283 if (ic->eeltype == eelCUT)
285 nbp->eeltype = eelTypeCUT;
287 else if (EEL_RF(ic->eeltype))
289 nbp->eeltype = eelTypeRF;
291 else if ((EEL_PME(ic->eeltype) || ic->eeltype == eelEWALD))
293 nbp->eeltype = pick_ewald_kernel_type(*ic);
297 /* Shouldn't happen, as this is checked when choosing Verlet-scheme */
299 "The requested electrostatics type is not implemented in the CUDA GPU accelerated "
303 /* generate table for PME */
304 nbp->coulomb_tab = nullptr;
305 if (nbp->eeltype == eelTypeEWALD_TAB || nbp->eeltype == eelTypeEWALD_TAB_TWIN)
307 GMX_RELEASE_ASSERT(ic->coulombEwaldTables, "Need valid Coulomb Ewald correction tables");
308 init_ewald_coulomb_force_table(*ic->coulombEwaldTables, nbp, deviceContext);
311 /* set up LJ parameter lookup table */
312 if (!useLjCombRule(nbp->vdwtype))
314 initParamLookupTable(&nbp->nbfp, &nbp->nbfp_texobj, nbatParams.nbfp.data(),
315 2 * ntypes * ntypes, deviceContext);
318 /* set up LJ-PME parameter lookup table */
319 if (ic->vdwtype == evdwPME)
321 initParamLookupTable(&nbp->nbfp_comb, &nbp->nbfp_comb_texobj, nbatParams.nbfp_comb.data(),
322 2 * ntypes, deviceContext);
326 /*! Re-generate the GPU Ewald force table, resets rlist, and update the
327 * electrostatic type switching to twin cut-off (or back) if needed. */
328 void gpu_pme_loadbal_update_param(const nonbonded_verlet_t* nbv, const interaction_const_t* ic)
330 if (!nbv || !nbv->useGpu())
334 NbnxmGpu* nb = nbv->gpu_nbv;
335 NBParamGpu* nbp = nbv->gpu_nbv->nbparam;
337 set_cutoff_parameters(nbp, ic, nbv->pairlistSets().params());
339 nbp->eeltype = pick_ewald_kernel_type(*ic);
341 GMX_RELEASE_ASSERT(ic->coulombEwaldTables, "Need valid Coulomb Ewald correction tables");
342 init_ewald_coulomb_force_table(*ic->coulombEwaldTables, nbp, *nb->deviceContext_);
345 /*! Initializes the pair list data structure. */
346 static void init_plist(cu_plist_t* pl)
348 /* initialize to nullptr pointers to data that is not allocated here and will
349 need reallocation in nbnxn_gpu_init_pairlist */
355 /* size -1 indicates that the respective array hasn't been initialized yet */
362 pl->imask_nalloc = -1;
364 pl->excl_nalloc = -1;
365 pl->haveFreshList = false;
368 /*! Initializes the timings data structure. */
369 static void init_timings(gmx_wallclock_gpu_nbnxn_t* t)
378 for (i = 0; i < 2; i++)
380 for (j = 0; j < 2; j++)
382 t->ktime[i][j].t = 0.0;
383 t->ktime[i][j].c = 0;
387 t->pruneTime.t = 0.0;
388 t->dynamicPruneTime.c = 0;
389 t->dynamicPruneTime.t = 0.0;
392 /*! Initializes simulation constant data. */
393 static void cuda_init_const(NbnxmGpu* nb,
394 const interaction_const_t* ic,
395 const PairlistParams& listParams,
396 const nbnxn_atomdata_t::Params& nbatParams)
398 init_atomdata_first(nb->atdat, nbatParams.numTypes, *nb->deviceContext_);
399 init_nbparam(nb->nbparam, ic, listParams, nbatParams, *nb->deviceContext_);
401 /* clear energy and shift force outputs */
402 nbnxn_cuda_clear_e_fshift(nb);
405 NbnxmGpu* gpu_init(const gmx::DeviceStreamManager& deviceStreamManager,
406 const interaction_const_t* ic,
407 const PairlistParams& listParams,
408 const nbnxn_atomdata_t* nbat,
409 bool bLocalAndNonlocal)
413 auto nb = new NbnxmGpu();
414 nb->deviceContext_ = &deviceStreamManager.context();
416 snew(nb->nbparam, 1);
417 snew(nb->plist[InteractionLocality::Local], 1);
418 if (bLocalAndNonlocal)
420 snew(nb->plist[InteractionLocality::NonLocal], 1);
423 nb->bUseTwoStreams = bLocalAndNonlocal;
425 nb->timers = new cu_timers_t();
426 snew(nb->timings, 1);
429 pmalloc((void**)&nb->nbst.e_lj, sizeof(*nb->nbst.e_lj));
430 pmalloc((void**)&nb->nbst.e_el, sizeof(*nb->nbst.e_el));
431 pmalloc((void**)&nb->nbst.fshift, SHIFTS * sizeof(*nb->nbst.fshift));
433 init_plist(nb->plist[InteractionLocality::Local]);
435 /* local/non-local GPU streams */
436 GMX_RELEASE_ASSERT(deviceStreamManager.streamIsValid(gmx::DeviceStreamType::NonBondedLocal),
437 "Local non-bonded stream should be initialized to use GPU for non-bonded.");
438 nb->deviceStreams[InteractionLocality::Local] =
439 &deviceStreamManager.stream(gmx::DeviceStreamType::NonBondedLocal);
440 if (nb->bUseTwoStreams)
442 init_plist(nb->plist[InteractionLocality::NonLocal]);
444 /* Note that the device we're running on does not have to support
445 * priorities, because we are querying the priority range which in this
446 * case will be a single value.
448 GMX_RELEASE_ASSERT(deviceStreamManager.streamIsValid(gmx::DeviceStreamType::NonBondedNonLocal),
449 "Non-local non-bonded stream should be initialized to use GPU for "
450 "non-bonded with domain decomposition.");
451 nb->deviceStreams[InteractionLocality::NonLocal] =
452 &deviceStreamManager.stream(gmx::DeviceStreamType::NonBondedNonLocal);
456 /* init events for sychronization (timing disabled for performance reasons!) */
457 stat = cudaEventCreateWithFlags(&nb->nonlocal_done, cudaEventDisableTiming);
458 CU_RET_ERR(stat, "cudaEventCreate on nonlocal_done failed");
459 stat = cudaEventCreateWithFlags(&nb->misc_ops_and_local_H2D_done, cudaEventDisableTiming);
460 CU_RET_ERR(stat, "cudaEventCreate on misc_ops_and_local_H2D_done failed");
462 nb->xNonLocalCopyD2HDone = new GpuEventSynchronizer();
464 /* WARNING: CUDA timings are incorrect with multiple streams.
465 * This is the main reason why they are disabled by default.
467 // TODO: Consider turning on by default when we can detect nr of streams.
468 nb->bDoTime = (getenv("GMX_ENABLE_GPU_TIMING") != nullptr);
472 init_timings(nb->timings);
475 /* set the kernel type for the current GPU */
476 /* pick L1 cache configuration */
477 cuda_set_cacheconfig();
479 cuda_init_const(nb, ic, listParams, nbat->params());
481 nb->atomIndicesSize = 0;
482 nb->atomIndicesSize_alloc = 0;
484 nb->ncxy_na_alloc = 0;
486 nb->ncxy_ind_alloc = 0;
492 fprintf(debug, "Initialized CUDA data structures.\n");
498 void gpu_init_pairlist(NbnxmGpu* nb, const NbnxnPairlistGpu* h_plist, const InteractionLocality iloc)
501 bool bDoTime = (nb->bDoTime && !h_plist->sci.empty());
502 const DeviceStream& deviceStream = *nb->deviceStreams[iloc];
503 cu_plist_t* d_plist = nb->plist[iloc];
505 if (d_plist->na_c < 0)
507 d_plist->na_c = h_plist->na_ci;
511 if (d_plist->na_c != h_plist->na_ci)
513 sprintf(sbuf, "In cu_init_plist: the #atoms per cell has changed (from %d to %d)",
514 d_plist->na_c, h_plist->na_ci);
519 gpu_timers_t::Interaction& iTimers = nb->timers->interaction[iloc];
523 iTimers.pl_h2d.openTimingRegion(deviceStream);
524 iTimers.didPairlistH2D = true;
527 const DeviceContext& deviceContext = *nb->deviceContext_;
529 reallocateDeviceBuffer(&d_plist->sci, h_plist->sci.size(), &d_plist->nsci, &d_plist->sci_nalloc,
531 copyToDeviceBuffer(&d_plist->sci, h_plist->sci.data(), 0, h_plist->sci.size(), deviceStream,
532 GpuApiCallBehavior::Async, bDoTime ? iTimers.pl_h2d.fetchNextEvent() : nullptr);
534 reallocateDeviceBuffer(&d_plist->cj4, h_plist->cj4.size(), &d_plist->ncj4, &d_plist->cj4_nalloc,
536 copyToDeviceBuffer(&d_plist->cj4, h_plist->cj4.data(), 0, h_plist->cj4.size(), deviceStream,
537 GpuApiCallBehavior::Async, bDoTime ? iTimers.pl_h2d.fetchNextEvent() : nullptr);
539 reallocateDeviceBuffer(&d_plist->imask, h_plist->cj4.size() * c_nbnxnGpuClusterpairSplit,
540 &d_plist->nimask, &d_plist->imask_nalloc, deviceContext);
542 reallocateDeviceBuffer(&d_plist->excl, h_plist->excl.size(), &d_plist->nexcl,
543 &d_plist->excl_nalloc, deviceContext);
544 copyToDeviceBuffer(&d_plist->excl, h_plist->excl.data(), 0, h_plist->excl.size(), deviceStream,
545 GpuApiCallBehavior::Async, bDoTime ? iTimers.pl_h2d.fetchNextEvent() : nullptr);
549 iTimers.pl_h2d.closeTimingRegion(deviceStream);
552 /* the next use of thist list we be the first one, so we need to prune */
553 d_plist->haveFreshList = true;
556 void gpu_upload_shiftvec(NbnxmGpu* nb, const nbnxn_atomdata_t* nbatom)
558 cu_atomdata_t* adat = nb->atdat;
559 const DeviceStream& localStream = *nb->deviceStreams[InteractionLocality::Local];
561 /* only if we have a dynamic box */
562 if (nbatom->bDynamicBox || !adat->bShiftVecUploaded)
564 static_assert(sizeof(adat->shift_vec[0]) == sizeof(nbatom->shift_vec[0]),
565 "Sizes of host- and device-side shift vectors should be the same.");
566 copyToDeviceBuffer(&adat->shift_vec, reinterpret_cast<const float3*>(nbatom->shift_vec.data()),
567 0, SHIFTS, localStream, GpuApiCallBehavior::Async, nullptr);
568 adat->bShiftVecUploaded = true;
572 /*! Clears the first natoms_clear elements of the GPU nonbonded force output array. */
573 static void nbnxn_cuda_clear_f(NbnxmGpu* nb, int natoms_clear)
575 cu_atomdata_t* adat = nb->atdat;
576 const DeviceStream& localStream = *nb->deviceStreams[InteractionLocality::Local];
577 clearDeviceBufferAsync(&adat->f, 0, natoms_clear, localStream);
580 /*! Clears nonbonded shift force output array and energy outputs on the GPU. */
581 static void nbnxn_cuda_clear_e_fshift(NbnxmGpu* nb)
583 cu_atomdata_t* adat = nb->atdat;
584 const DeviceStream& localStream = *nb->deviceStreams[InteractionLocality::Local];
586 clearDeviceBufferAsync(&adat->fshift, 0, SHIFTS, localStream);
587 clearDeviceBufferAsync(&adat->e_lj, 0, 1, localStream);
588 clearDeviceBufferAsync(&adat->e_el, 0, 1, localStream);
591 void gpu_clear_outputs(NbnxmGpu* nb, bool computeVirial)
593 nbnxn_cuda_clear_f(nb, nb->atdat->natoms);
594 /* clear shift force array and energies if the outputs were
595 used in the current step */
598 nbnxn_cuda_clear_e_fshift(nb);
602 void gpu_init_atomdata(NbnxmGpu* nb, const nbnxn_atomdata_t* nbat)
606 bool bDoTime = nb->bDoTime;
607 cu_timers_t* timers = nb->timers;
608 cu_atomdata_t* d_atdat = nb->atdat;
609 const DeviceContext& deviceContext = *nb->deviceContext_;
610 const DeviceStream& localStream = *nb->deviceStreams[InteractionLocality::Local];
612 natoms = nbat->numAtoms();
617 /* time async copy */
618 timers->atdat.openTimingRegion(localStream);
621 /* need to reallocate if we have to copy more atoms than the amount of space
622 available and only allocate if we haven't initialized yet, i.e d_atdat->natoms == -1 */
623 if (natoms > d_atdat->nalloc)
625 nalloc = over_alloc_small(natoms);
627 /* free up first if the arrays have already been initialized */
628 if (d_atdat->nalloc != -1)
630 freeDeviceBuffer(&d_atdat->f);
631 freeDeviceBuffer(&d_atdat->xq);
632 freeDeviceBuffer(&d_atdat->atom_types);
633 freeDeviceBuffer(&d_atdat->lj_comb);
636 allocateDeviceBuffer(&d_atdat->f, nalloc, deviceContext);
637 allocateDeviceBuffer(&d_atdat->xq, nalloc, deviceContext);
638 if (useLjCombRule(nb->nbparam->vdwtype))
640 allocateDeviceBuffer(&d_atdat->lj_comb, nalloc, deviceContext);
644 allocateDeviceBuffer(&d_atdat->atom_types, nalloc, deviceContext);
647 d_atdat->nalloc = nalloc;
651 d_atdat->natoms = natoms;
652 d_atdat->natoms_local = nbat->natoms_local;
654 /* need to clear GPU f output if realloc happened */
657 nbnxn_cuda_clear_f(nb, nalloc);
660 if (useLjCombRule(nb->nbparam->vdwtype))
662 static_assert(sizeof(d_atdat->lj_comb[0]) == sizeof(float2),
663 "Size of the LJ parameters element should be equal to the size of float2.");
664 copyToDeviceBuffer(&d_atdat->lj_comb,
665 reinterpret_cast<const float2*>(nbat->params().lj_comb.data()), 0,
666 natoms, localStream, GpuApiCallBehavior::Async, nullptr);
670 static_assert(sizeof(d_atdat->atom_types[0]) == sizeof(nbat->params().type[0]),
671 "Sizes of host- and device-side atom types should be the same.");
672 copyToDeviceBuffer(&d_atdat->atom_types, nbat->params().type.data(), 0, natoms, localStream,
673 GpuApiCallBehavior::Async, nullptr);
678 timers->atdat.closeTimingRegion(localStream);
682 static void nbnxn_cuda_free_nbparam_table(NBParamGpu* nbparam)
684 if (nbparam->eeltype == eelTypeEWALD_TAB || nbparam->eeltype == eelTypeEWALD_TAB_TWIN)
686 destroyParamLookupTable(&nbparam->coulomb_tab, nbparam->coulomb_tab_texobj);
690 void gpu_free(NbnxmGpu* nb)
693 cu_atomdata_t* atdat;
702 nbparam = nb->nbparam;
704 nbnxn_cuda_free_nbparam_table(nbparam);
706 stat = cudaEventDestroy(nb->nonlocal_done);
707 CU_RET_ERR(stat, "cudaEventDestroy failed on timers->nonlocal_done");
708 stat = cudaEventDestroy(nb->misc_ops_and_local_H2D_done);
709 CU_RET_ERR(stat, "cudaEventDestroy failed on timers->misc_ops_and_local_H2D_done");
713 if (!useLjCombRule(nb->nbparam->vdwtype))
715 destroyParamLookupTable(&nbparam->nbfp, nbparam->nbfp_texobj);
718 if (nbparam->vdwtype == evdwTypeEWALDGEOM || nbparam->vdwtype == evdwTypeEWALDLB)
720 destroyParamLookupTable(&nbparam->nbfp_comb, nbparam->nbfp_comb_texobj);
723 freeDeviceBuffer(&atdat->shift_vec);
724 freeDeviceBuffer(&atdat->fshift);
726 freeDeviceBuffer(&atdat->e_lj);
727 freeDeviceBuffer(&atdat->e_el);
729 freeDeviceBuffer(&atdat->f);
730 freeDeviceBuffer(&atdat->xq);
731 freeDeviceBuffer(&atdat->atom_types);
732 freeDeviceBuffer(&atdat->lj_comb);
735 auto* plist = nb->plist[InteractionLocality::Local];
736 freeDeviceBuffer(&plist->sci);
737 freeDeviceBuffer(&plist->cj4);
738 freeDeviceBuffer(&plist->imask);
739 freeDeviceBuffer(&plist->excl);
741 if (nb->bUseTwoStreams)
743 auto* plist_nl = nb->plist[InteractionLocality::NonLocal];
744 freeDeviceBuffer(&plist_nl->sci);
745 freeDeviceBuffer(&plist_nl->cj4);
746 freeDeviceBuffer(&plist_nl->imask);
747 freeDeviceBuffer(&plist_nl->excl);
752 pfree(nb->nbst.e_lj);
753 nb->nbst.e_lj = nullptr;
755 pfree(nb->nbst.e_el);
756 nb->nbst.e_el = nullptr;
758 pfree(nb->nbst.fshift);
759 nb->nbst.fshift = nullptr;
768 fprintf(debug, "Cleaned up CUDA data structures.\n");
772 //! This function is documented in the header file
773 gmx_wallclock_gpu_nbnxn_t* gpu_get_timings(NbnxmGpu* nb)
775 return (nb != nullptr && nb->bDoTime) ? nb->timings : nullptr;
778 void gpu_reset_timings(nonbonded_verlet_t* nbv)
780 if (nbv->gpu_nbv && nbv->gpu_nbv->bDoTime)
782 init_timings(nbv->gpu_nbv->timings);
786 int gpu_min_ci_balanced(NbnxmGpu* nb)
788 return nb != nullptr ? gpu_min_ci_balanced_factor * nb->deviceContext_->deviceInfo().prop.multiProcessorCount
792 gmx_bool gpu_is_kernel_ewald_analytical(const NbnxmGpu* nb)
794 return ((nb->nbparam->eeltype == eelTypeEWALD_ANA) || (nb->nbparam->eeltype == eelTypeEWALD_ANA_TWIN));
797 void* gpu_get_xq(NbnxmGpu* nb)
801 return static_cast<void*>(nb->atdat->xq);
804 DeviceBuffer<gmx::RVec> gpu_get_f(NbnxmGpu* nb)
808 return reinterpret_cast<DeviceBuffer<gmx::RVec>>(nb->atdat->f);
811 DeviceBuffer<gmx::RVec> gpu_get_fshift(NbnxmGpu* nb)
815 return reinterpret_cast<DeviceBuffer<gmx::RVec>>(nb->atdat->fshift);
818 /* Initialization for X buffer operations on GPU. */
819 /* TODO Remove explicit pinning from host arrays from here and manage in a more natural way*/
820 void nbnxn_gpu_init_x_to_nbat_x(const Nbnxm::GridSet& gridSet, NbnxmGpu* gpu_nbv)
822 const DeviceStream& deviceStream = *gpu_nbv->deviceStreams[InteractionLocality::Local];
823 bool bDoTime = gpu_nbv->bDoTime;
824 const int maxNumColumns = gridSet.numColumnsMax();
826 reallocateDeviceBuffer(&gpu_nbv->cxy_na, maxNumColumns * gridSet.grids().size(),
827 &gpu_nbv->ncxy_na, &gpu_nbv->ncxy_na_alloc, *gpu_nbv->deviceContext_);
828 reallocateDeviceBuffer(&gpu_nbv->cxy_ind, maxNumColumns * gridSet.grids().size(),
829 &gpu_nbv->ncxy_ind, &gpu_nbv->ncxy_ind_alloc, *gpu_nbv->deviceContext_);
831 for (unsigned int g = 0; g < gridSet.grids().size(); g++)
834 const Nbnxm::Grid& grid = gridSet.grids()[g];
836 const int numColumns = grid.numColumns();
837 const int* atomIndices = gridSet.atomIndices().data();
838 const int atomIndicesSize = gridSet.atomIndices().size();
839 const int* cxy_na = grid.cxy_na().data();
840 const int* cxy_ind = grid.cxy_ind().data();
842 reallocateDeviceBuffer(&gpu_nbv->atomIndices, atomIndicesSize, &gpu_nbv->atomIndicesSize,
843 &gpu_nbv->atomIndicesSize_alloc, *gpu_nbv->deviceContext_);
845 if (atomIndicesSize > 0)
850 gpu_nbv->timers->xf[AtomLocality::Local].nb_h2d.openTimingRegion(deviceStream);
853 copyToDeviceBuffer(&gpu_nbv->atomIndices, atomIndices, 0, atomIndicesSize, deviceStream,
854 GpuApiCallBehavior::Async, nullptr);
858 gpu_nbv->timers->xf[AtomLocality::Local].nb_h2d.closeTimingRegion(deviceStream);
866 gpu_nbv->timers->xf[AtomLocality::Local].nb_h2d.openTimingRegion(deviceStream);
869 int* destPtr = &gpu_nbv->cxy_na[maxNumColumns * g];
870 copyToDeviceBuffer(&destPtr, cxy_na, 0, numColumns, deviceStream,
871 GpuApiCallBehavior::Async, nullptr);
875 gpu_nbv->timers->xf[AtomLocality::Local].nb_h2d.closeTimingRegion(deviceStream);
880 gpu_nbv->timers->xf[AtomLocality::Local].nb_h2d.openTimingRegion(deviceStream);
883 destPtr = &gpu_nbv->cxy_ind[maxNumColumns * g];
884 copyToDeviceBuffer(&destPtr, cxy_ind, 0, numColumns, deviceStream,
885 GpuApiCallBehavior::Async, nullptr);
889 gpu_nbv->timers->xf[AtomLocality::Local].nb_h2d.closeTimingRegion(deviceStream);
894 // The above data is transferred on the local stream but is a
895 // dependency of the nonlocal stream (specifically the nonlocal X
896 // buf ops kernel). We therefore set a dependency to ensure
897 // that the nonlocal stream waits on the local stream here.
898 // This call records an event in the local stream:
899 nbnxnInsertNonlocalGpuDependency(gpu_nbv, Nbnxm::InteractionLocality::Local);
900 // ...and this call instructs the nonlocal stream to wait on that event:
901 nbnxnInsertNonlocalGpuDependency(gpu_nbv, Nbnxm::InteractionLocality::NonLocal);
906 /* Initialization for F buffer operations on GPU. */
907 void nbnxn_gpu_init_add_nbat_f_to_f(const int* cell,
910 GpuEventSynchronizer* const localReductionDone)
913 const DeviceStream& deviceStream = *gpu_nbv->deviceStreams[InteractionLocality::Local];
915 GMX_ASSERT(localReductionDone, "localReductionDone should be a valid pointer");
916 gpu_nbv->localFReductionDone = localReductionDone;
918 if (natoms_total > 0)
920 reallocateDeviceBuffer(&gpu_nbv->cell, natoms_total, &gpu_nbv->ncell, &gpu_nbv->ncell_alloc,
921 *gpu_nbv->deviceContext_);
922 copyToDeviceBuffer(&gpu_nbv->cell, cell, 0, natoms_total, deviceStream,
923 GpuApiCallBehavior::Async, nullptr);