7472b37c70e45defb390cd77eac14c5418d8145b
[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/device_stream_manager.h"
56 #include "gromacs/gpu_utils/oclutils.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"
77
78 #include "nbnxm_ocl_types.h"
79
80 namespace Nbnxm
81 {
82
83 /*! \brief Copies of values from cl_driver_diagnostics_intel.h,
84  * which isn't guaranteed to be available. */
85 /**@{*/
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
90 /**@}*/
91
92 /*! \brief This parameter should be determined heuristically from the
93  * kernel execution times
94  *
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.
99  */
100 static unsigned int gpu_min_ci_balanced_factor = 50;
101
102
103 /*! \brief Initializes the atomdata structure first time, it only gets filled at
104     pair-search.
105  */
106 static void init_atomdata_first(cl_atomdata_t* ad, int ntypes, const DeviceContext& deviceContext)
107 {
108     ad->ntypes = ntypes;
109
110     allocateDeviceBuffer(&ad->shift_vec, SHIFTS * DIM, deviceContext);
111     ad->bShiftVecUploaded = CL_FALSE;
112
113     allocateDeviceBuffer(&ad->fshift, SHIFTS * DIM, deviceContext);
114     allocateDeviceBuffer(&ad->e_lj, 1, deviceContext);
115     allocateDeviceBuffer(&ad->e_el, 1, deviceContext);
116
117     /* initialize to nullptr pointers to data that is not allocated here and will
118        need reallocation in nbnxn_gpu_init_atomdata */
119     ad->xq = nullptr;
120     ad->f  = nullptr;
121
122     /* size -1 indicates that the respective array hasn't been initialized yet */
123     ad->natoms = -1;
124     ad->nalloc = -1;
125 }
126
127
128 /*! \brief Initializes the nonbonded parameter data structure.
129  */
130 static void init_nbparam(NBParamGpu*                     nbp,
131                          const interaction_const_t*      ic,
132                          const PairlistParams&           listParams,
133                          const nbnxn_atomdata_t::Params& nbatParams,
134                          const DeviceContext&            deviceContext)
135 {
136     set_cutoff_parameters(nbp, ic, listParams);
137
138     nbp->vdwType  = nbnxmGpuPickVdwKernelType(ic, nbatParams.ljCombinationRule);
139     nbp->elecType = nbnxmGpuPickElectrostaticsKernelType(ic, deviceContext.deviceInfo());
140
141     if (ic->vdwtype == evdwPME)
142     {
143         if (ic->ljpme_comb_rule == eljpmeGEOM)
144         {
145             GMX_ASSERT(nbatParams.ljCombinationRule == LJCombinationRule::Geometric,
146                        "Combination rule mismatch!");
147         }
148         else
149         {
150             GMX_ASSERT(nbatParams.ljCombinationRule == LJCombinationRule::LorentzBerthelot,
151                        "Combination rule mismatch!");
152         }
153     }
154     /* generate table for PME */
155     nbp->coulomb_tab = nullptr;
156     if (nbp->elecType == ElecType::EwaldTab || nbp->elecType == ElecType::EwaldTabTwin)
157     {
158         GMX_RELEASE_ASSERT(ic->coulombEwaldTables, "Need valid Coulomb Ewald correction tables");
159         init_ewald_coulomb_force_table(*ic->coulombEwaldTables, nbp, deviceContext);
160     }
161     else
162     {
163         allocateDeviceBuffer(&nbp->coulomb_tab, 1, deviceContext);
164     }
165
166     const int nnbfp      = 2 * nbatParams.numTypes * nbatParams.numTypes;
167     const int nnbfp_comb = 2 * nbatParams.numTypes;
168
169     {
170         /* set up LJ parameter lookup table */
171         DeviceBuffer<real> nbfp;
172         initParamLookupTable(&nbfp, nullptr, nbatParams.nbfp.data(), nnbfp, deviceContext);
173         nbp->nbfp = nbfp;
174
175         if (ic->vdwtype == evdwPME)
176         {
177             DeviceBuffer<float> nbfp_comb;
178             initParamLookupTable(&nbfp_comb, nullptr, nbatParams.nbfp_comb.data(), nnbfp_comb, deviceContext);
179             nbp->nbfp_comb = nbfp_comb;
180         }
181     }
182 }
183
184 /*! \brief Initializes the OpenCL kernel pointers of the nbnxn_ocl_ptr_t input data structure. */
185 static cl_kernel nbnxn_gpu_create_kernel(NbnxmGpu* nb, const char* kernel_name)
186 {
187     cl_kernel kernel;
188     cl_int    cl_error;
189
190     kernel = clCreateKernel(nb->dev_rundata->program, kernel_name, &cl_error);
191     if (CL_SUCCESS != cl_error)
192     {
193         gmx_fatal(FARGS,
194                   "Failed to create kernel '%s' for GPU #%s: OpenCL error %d",
195                   kernel_name,
196                   nb->deviceContext_->deviceInfo().device_name,
197                   cl_error);
198     }
199
200     return kernel;
201 }
202
203 /*! \brief Clears nonbonded shift force output array and energy outputs on the GPU.
204  */
205 static void nbnxn_ocl_clear_e_fshift(NbnxmGpu* nb)
206 {
207
208     cl_int           cl_error;
209     cl_atomdata_t*   adat = nb->atdat;
210     cl_command_queue ls   = nb->deviceStreams[InteractionLocality::Local]->stream();
211
212     size_t local_work_size[3]  = { 1, 1, 1 };
213     size_t global_work_size[3] = { 1, 1, 1 };
214
215     cl_int shifts = SHIFTS * 3;
216
217     cl_int arg_no;
218
219     cl_kernel zero_e_fshift = nb->kernel_zero_e_fshift;
220
221     local_work_size[0] = 64;
222     // Round the total number of threads up from the array size
223     global_work_size[0] = ((shifts + local_work_size[0] - 1) / local_work_size[0]) * local_work_size[0];
224
225     arg_no   = 0;
226     cl_error = clSetKernelArg(zero_e_fshift, arg_no++, sizeof(cl_mem), &(adat->fshift));
227     cl_error |= clSetKernelArg(zero_e_fshift, arg_no++, sizeof(cl_mem), &(adat->e_lj));
228     cl_error |= clSetKernelArg(zero_e_fshift, arg_no++, sizeof(cl_mem), &(adat->e_el));
229     cl_error |= clSetKernelArg(zero_e_fshift, arg_no++, sizeof(cl_uint), &shifts);
230     GMX_ASSERT(cl_error == CL_SUCCESS, ocl_get_error_string(cl_error).c_str());
231
232     cl_error = clEnqueueNDRangeKernel(
233             ls, zero_e_fshift, 3, nullptr, global_work_size, local_work_size, 0, nullptr, nullptr);
234     GMX_ASSERT(cl_error == CL_SUCCESS, ocl_get_error_string(cl_error).c_str());
235 }
236
237 /*! \brief Initializes the OpenCL kernel pointers of the nbnxn_ocl_ptr_t input data structure. */
238 static void nbnxn_gpu_init_kernels(NbnxmGpu* nb)
239 {
240     /* Init to 0 main kernel arrays */
241     /* They will be later on initialized in select_nbnxn_kernel */
242     // TODO: consider always creating all variants of the kernels here so that there is no
243     // need for late call to clCreateKernel -- if that gives any advantage?
244     memset(nb->kernel_ener_noprune_ptr, 0, sizeof(nb->kernel_ener_noprune_ptr));
245     memset(nb->kernel_ener_prune_ptr, 0, sizeof(nb->kernel_ener_prune_ptr));
246     memset(nb->kernel_noener_noprune_ptr, 0, sizeof(nb->kernel_noener_noprune_ptr));
247     memset(nb->kernel_noener_prune_ptr, 0, sizeof(nb->kernel_noener_prune_ptr));
248
249     /* Init pruning kernels
250      *
251      * TODO: we could avoid creating kernels if dynamic pruning is turned off,
252      * but ATM that depends on force flags not passed into the initialization.
253      */
254     nb->kernel_pruneonly[epruneFirst] = nbnxn_gpu_create_kernel(nb, "nbnxn_kernel_prune_opencl");
255     nb->kernel_pruneonly[epruneRolling] =
256             nbnxn_gpu_create_kernel(nb, "nbnxn_kernel_prune_rolling_opencl");
257
258     /* Init auxiliary kernels */
259     nb->kernel_zero_e_fshift = nbnxn_gpu_create_kernel(nb, "zero_e_fshift");
260 }
261
262 /*! \brief Initializes simulation constant data.
263  *
264  *  Initializes members of the atomdata and nbparam structs and
265  *  clears e/fshift output buffers.
266  */
267 static void nbnxn_ocl_init_const(cl_atomdata_t*                  atomData,
268                                  NBParamGpu*                     nbParams,
269                                  const interaction_const_t*      ic,
270                                  const PairlistParams&           listParams,
271                                  const nbnxn_atomdata_t::Params& nbatParams,
272                                  const DeviceContext&            deviceContext)
273 {
274     init_atomdata_first(atomData, nbatParams.numTypes, deviceContext);
275     init_nbparam(nbParams, ic, listParams, nbatParams, deviceContext);
276 }
277
278
279 //! This function is documented in the header file
280 NbnxmGpu* gpu_init(const gmx::DeviceStreamManager& deviceStreamManager,
281                    const interaction_const_t*      ic,
282                    const PairlistParams&           listParams,
283                    const nbnxn_atomdata_t*         nbat,
284                    const bool                      bLocalAndNonlocal)
285 {
286     GMX_ASSERT(ic, "Need a valid interaction constants object");
287
288     auto nb            = new NbnxmGpu();
289     nb->deviceContext_ = &deviceStreamManager.context();
290     snew(nb->atdat, 1);
291     snew(nb->nbparam, 1);
292     snew(nb->plist[InteractionLocality::Local], 1);
293     if (bLocalAndNonlocal)
294     {
295         snew(nb->plist[InteractionLocality::NonLocal], 1);
296     }
297
298     nb->bUseTwoStreams = bLocalAndNonlocal;
299
300     nb->timers = new cl_timers_t();
301     snew(nb->timings, 1);
302
303     /* set device info, just point it to the right GPU among the detected ones */
304     nb->dev_rundata = new gmx_device_runtime_data_t();
305
306     /* init nbst */
307     pmalloc(reinterpret_cast<void**>(&nb->nbst.e_lj), sizeof(*nb->nbst.e_lj));
308     pmalloc(reinterpret_cast<void**>(&nb->nbst.e_el), sizeof(*nb->nbst.e_el));
309     pmalloc(reinterpret_cast<void**>(&nb->nbst.fshift), SHIFTS * sizeof(*nb->nbst.fshift));
310
311     init_plist(nb->plist[InteractionLocality::Local]);
312
313     /* OpenCL timing disabled if GMX_DISABLE_GPU_TIMING is defined. */
314     nb->bDoTime = (getenv("GMX_DISABLE_GPU_TIMING") == nullptr);
315
316     /* local/non-local GPU streams */
317     GMX_RELEASE_ASSERT(deviceStreamManager.streamIsValid(gmx::DeviceStreamType::NonBondedLocal),
318                        "Local non-bonded stream should be initialized to use GPU for non-bonded.");
319     nb->deviceStreams[InteractionLocality::Local] =
320             &deviceStreamManager.stream(gmx::DeviceStreamType::NonBondedLocal);
321
322     if (nb->bUseTwoStreams)
323     {
324         init_plist(nb->plist[InteractionLocality::NonLocal]);
325
326         GMX_RELEASE_ASSERT(deviceStreamManager.streamIsValid(gmx::DeviceStreamType::NonBondedNonLocal),
327                            "Non-local non-bonded stream should be initialized to use GPU for "
328                            "non-bonded with domain decomposition.");
329         nb->deviceStreams[InteractionLocality::NonLocal] =
330                 &deviceStreamManager.stream(gmx::DeviceStreamType::NonBondedNonLocal);
331     }
332
333     if (nb->bDoTime)
334     {
335         init_timings(nb->timings);
336     }
337
338     nbnxn_ocl_init_const(nb->atdat, nb->nbparam, ic, listParams, nbat->params(), *nb->deviceContext_);
339
340     /* Enable LJ param manual prefetch for AMD or Intel or if we request through env. var.
341      * TODO: decide about NVIDIA
342      */
343     nb->bPrefetchLjParam = (getenv("GMX_OCL_DISABLE_I_PREFETCH") == nullptr)
344                            && ((nb->deviceContext_->deviceInfo().deviceVendor == DeviceVendor::Amd)
345                                || (nb->deviceContext_->deviceInfo().deviceVendor == DeviceVendor::Intel)
346                                || (getenv("GMX_OCL_ENABLE_I_PREFETCH") != nullptr));
347
348     /* NOTE: in CUDA we pick L1 cache configuration for the nbnxn kernels here,
349      * but sadly this is not supported in OpenCL (yet?). Consider adding it if
350      * it becomes supported.
351      */
352     nbnxn_gpu_compile_kernels(nb);
353     nbnxn_gpu_init_kernels(nb);
354
355     /* clear energy and shift force outputs */
356     nbnxn_ocl_clear_e_fshift(nb);
357
358     if (debug)
359     {
360         fprintf(debug, "Initialized OpenCL data structures.\n");
361     }
362
363     return nb;
364 }
365
366 /*! \brief Clears the first natoms_clear elements of the GPU nonbonded force output array.
367  */
368 static void nbnxn_ocl_clear_f(NbnxmGpu* nb, int natoms_clear)
369 {
370     if (natoms_clear == 0)
371     {
372         return;
373     }
374
375     cl_atomdata_t*      atomData    = nb->atdat;
376     const DeviceStream& localStream = *nb->deviceStreams[InteractionLocality::Local];
377
378     clearDeviceBufferAsync(&atomData->f, 0, natoms_clear * DIM, localStream);
379 }
380
381 //! This function is documented in the header file
382 void gpu_clear_outputs(NbnxmGpu* nb, bool computeVirial)
383 {
384     nbnxn_ocl_clear_f(nb, nb->atdat->natoms);
385     /* clear shift force array and energies if the outputs were
386        used in the current step */
387     if (computeVirial)
388     {
389         nbnxn_ocl_clear_e_fshift(nb);
390     }
391
392     /* kick off buffer clearing kernel to ensure concurrency with constraints/update */
393     cl_int gmx_unused cl_error;
394     cl_error = clFlush(nb->deviceStreams[InteractionLocality::Local]->stream());
395     GMX_ASSERT(cl_error == CL_SUCCESS, ("clFlush failed: " + ocl_get_error_string(cl_error)).c_str());
396 }
397
398 //! This function is documented in the header file
399 void gpu_upload_shiftvec(NbnxmGpu* nb, const nbnxn_atomdata_t* nbatom)
400 {
401     cl_atomdata_t*      adat        = nb->atdat;
402     const DeviceStream& localStream = *nb->deviceStreams[InteractionLocality::Local];
403
404     /* only if we have a dynamic box */
405     if (nbatom->bDynamicBox || !adat->bShiftVecUploaded)
406     {
407         GMX_ASSERT(sizeof(float) * DIM == sizeof(*nbatom->shift_vec.data()),
408                    "Sizes of host- and device-side shift vectors should be the same.");
409         copyToDeviceBuffer(&adat->shift_vec,
410                            reinterpret_cast<const float*>(nbatom->shift_vec.data()),
411                            0,
412                            SHIFTS * DIM,
413                            localStream,
414                            GpuApiCallBehavior::Async,
415                            nullptr);
416         adat->bShiftVecUploaded = CL_TRUE;
417     }
418 }
419
420 //! This function is documented in the header file
421 void gpu_init_atomdata(NbnxmGpu* nb, const nbnxn_atomdata_t* nbat)
422 {
423     cl_int               cl_error;
424     int                  nalloc, natoms;
425     bool                 realloced;
426     bool                 bDoTime       = nb->bDoTime;
427     cl_timers_t*         timers        = nb->timers;
428     cl_atomdata_t*       d_atdat       = nb->atdat;
429     const DeviceContext& deviceContext = *nb->deviceContext_;
430     const DeviceStream&  localStream   = *nb->deviceStreams[InteractionLocality::Local];
431
432     natoms    = nbat->numAtoms();
433     realloced = false;
434
435     if (bDoTime)
436     {
437         /* time async copy */
438         timers->atdat.openTimingRegion(localStream);
439     }
440
441     /* need to reallocate if we have to copy more atoms than the amount of space
442        available and only allocate if we haven't initialized yet, i.e d_atdat->natoms == -1 */
443     if (natoms > d_atdat->nalloc)
444     {
445         nalloc = over_alloc_small(natoms);
446
447         /* free up first if the arrays have already been initialized */
448         if (d_atdat->nalloc != -1)
449         {
450             freeDeviceBuffer(&d_atdat->f);
451             freeDeviceBuffer(&d_atdat->xq);
452             freeDeviceBuffer(&d_atdat->lj_comb);
453             freeDeviceBuffer(&d_atdat->atom_types);
454         }
455
456
457         allocateDeviceBuffer(&d_atdat->f, nalloc * DIM, deviceContext);
458         allocateDeviceBuffer(&d_atdat->xq, nalloc * (DIM + 1), deviceContext);
459
460         if (useLjCombRule(nb->nbparam->vdwType))
461         {
462             // Two Lennard-Jones parameters per atom
463             allocateDeviceBuffer(&d_atdat->lj_comb, nalloc * 2, deviceContext);
464         }
465         else
466         {
467             allocateDeviceBuffer(&d_atdat->atom_types, nalloc, deviceContext);
468         }
469
470         d_atdat->nalloc = nalloc;
471         realloced       = true;
472     }
473
474     d_atdat->natoms       = natoms;
475     d_atdat->natoms_local = nbat->natoms_local;
476
477     /* need to clear GPU f output if realloc happened */
478     if (realloced)
479     {
480         nbnxn_ocl_clear_f(nb, nalloc);
481     }
482
483     if (useLjCombRule(nb->nbparam->vdwType))
484     {
485         GMX_ASSERT(sizeof(float) == sizeof(*nbat->params().lj_comb.data()),
486                    "Size of the LJ parameters element should be equal to the size of float2.");
487         copyToDeviceBuffer(&d_atdat->lj_comb,
488                            nbat->params().lj_comb.data(),
489                            0,
490                            2 * natoms,
491                            localStream,
492                            GpuApiCallBehavior::Async,
493                            bDoTime ? timers->atdat.fetchNextEvent() : nullptr);
494     }
495     else
496     {
497         GMX_ASSERT(sizeof(int) == sizeof(*nbat->params().type.data()),
498                    "Sizes of host- and device-side atom types should be the same.");
499         copyToDeviceBuffer(&d_atdat->atom_types,
500                            nbat->params().type.data(),
501                            0,
502                            natoms,
503                            localStream,
504                            GpuApiCallBehavior::Async,
505                            bDoTime ? timers->atdat.fetchNextEvent() : nullptr);
506     }
507
508     if (bDoTime)
509     {
510         timers->atdat.closeTimingRegion(localStream);
511     }
512
513     /* kick off the tasks enqueued above to ensure concurrency with the search */
514     cl_error = clFlush(localStream.stream());
515     GMX_RELEASE_ASSERT(cl_error == CL_SUCCESS,
516                        ("clFlush failed: " + ocl_get_error_string(cl_error)).c_str());
517 }
518
519 /*! \brief Releases an OpenCL kernel pointer */
520 static void free_kernel(cl_kernel* kernel_ptr)
521 {
522     cl_int gmx_unused cl_error;
523
524     GMX_ASSERT(kernel_ptr, "Need a valid kernel pointer");
525
526     if (*kernel_ptr)
527     {
528         cl_error = clReleaseKernel(*kernel_ptr);
529         GMX_RELEASE_ASSERT(cl_error == CL_SUCCESS,
530                            ("clReleaseKernel failed: " + ocl_get_error_string(cl_error)).c_str());
531
532         *kernel_ptr = nullptr;
533     }
534 }
535
536 /*! \brief Releases a list of OpenCL kernel pointers */
537 static void free_kernels(cl_kernel* kernels, int count)
538 {
539     int i;
540
541     for (i = 0; i < count; i++)
542     {
543         free_kernel(kernels + i);
544     }
545 }
546
547 /*! \brief Free the OpenCL program.
548  *
549  *  The function releases the OpenCL program assuciated with the
550  *  device that the calling PP rank is running on.
551  *
552  *  \param program [in]  OpenCL program to release.
553  */
554 static void freeGpuProgram(cl_program program)
555 {
556     if (program)
557     {
558         cl_int cl_error = clReleaseProgram(program);
559         GMX_RELEASE_ASSERT(cl_error == CL_SUCCESS,
560                            ("clReleaseProgram failed: " + ocl_get_error_string(cl_error)).c_str());
561         program = nullptr;
562     }
563 }
564
565 //! This function is documented in the header file
566 void gpu_free(NbnxmGpu* nb)
567 {
568     if (nb == nullptr)
569     {
570         return;
571     }
572
573     /* Free kernels */
574     // NOLINTNEXTLINE(bugprone-sizeof-expression)
575     int kernel_count = sizeof(nb->kernel_ener_noprune_ptr) / sizeof(nb->kernel_ener_noprune_ptr[0][0]);
576     free_kernels(nb->kernel_ener_noprune_ptr[0], kernel_count);
577
578     // NOLINTNEXTLINE(bugprone-sizeof-expression)
579     kernel_count = sizeof(nb->kernel_ener_prune_ptr) / sizeof(nb->kernel_ener_prune_ptr[0][0]);
580     free_kernels(nb->kernel_ener_prune_ptr[0], kernel_count);
581
582     // NOLINTNEXTLINE(bugprone-sizeof-expression)
583     kernel_count = sizeof(nb->kernel_noener_noprune_ptr) / sizeof(nb->kernel_noener_noprune_ptr[0][0]);
584     free_kernels(nb->kernel_noener_noprune_ptr[0], kernel_count);
585
586     // NOLINTNEXTLINE(bugprone-sizeof-expression)
587     kernel_count = sizeof(nb->kernel_noener_prune_ptr) / sizeof(nb->kernel_noener_prune_ptr[0][0]);
588     free_kernels(nb->kernel_noener_prune_ptr[0], kernel_count);
589
590     free_kernel(&(nb->kernel_zero_e_fshift));
591
592     /* Free atdat */
593     freeDeviceBuffer(&(nb->atdat->xq));
594     freeDeviceBuffer(&(nb->atdat->f));
595     freeDeviceBuffer(&(nb->atdat->e_lj));
596     freeDeviceBuffer(&(nb->atdat->e_el));
597     freeDeviceBuffer(&(nb->atdat->fshift));
598     freeDeviceBuffer(&(nb->atdat->lj_comb));
599     freeDeviceBuffer(&(nb->atdat->atom_types));
600     freeDeviceBuffer(&(nb->atdat->shift_vec));
601     sfree(nb->atdat);
602
603     /* Free nbparam */
604     freeDeviceBuffer(&(nb->nbparam->nbfp));
605     freeDeviceBuffer(&(nb->nbparam->nbfp_comb));
606     freeDeviceBuffer(&(nb->nbparam->coulomb_tab));
607     sfree(nb->nbparam);
608
609     /* Free plist */
610     auto* plist = nb->plist[InteractionLocality::Local];
611     freeDeviceBuffer(&plist->sci);
612     freeDeviceBuffer(&plist->cj4);
613     freeDeviceBuffer(&plist->imask);
614     freeDeviceBuffer(&plist->excl);
615     sfree(plist);
616     if (nb->bUseTwoStreams)
617     {
618         auto* plist_nl = nb->plist[InteractionLocality::NonLocal];
619         freeDeviceBuffer(&plist_nl->sci);
620         freeDeviceBuffer(&plist_nl->cj4);
621         freeDeviceBuffer(&plist_nl->imask);
622         freeDeviceBuffer(&plist_nl->excl);
623         sfree(plist_nl);
624     }
625
626     /* Free nbst */
627     pfree(nb->nbst.e_lj);
628     nb->nbst.e_lj = nullptr;
629
630     pfree(nb->nbst.e_el);
631     nb->nbst.e_el = nullptr;
632
633     pfree(nb->nbst.fshift);
634     nb->nbst.fshift = nullptr;
635
636     freeGpuProgram(nb->dev_rundata->program);
637     delete nb->dev_rundata;
638
639     /* Free timers and timings */
640     delete nb->timers;
641     sfree(nb->timings);
642     delete nb;
643
644     if (debug)
645     {
646         fprintf(debug, "Cleaned up OpenCL data structures.\n");
647     }
648 }
649
650 //! This function is documented in the header file
651 int gpu_min_ci_balanced(NbnxmGpu* nb)
652 {
653     return nb != nullptr ? gpu_min_ci_balanced_factor * nb->deviceContext_->deviceInfo().compute_units : 0;
654 }
655
656 } // namespace Nbnxm