Apply clang-format-11
[alexxy/gromacs.git] / src / gromacs / ewald / pme_gpu_internal.cpp
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 2016,2017,2018,2019,2020, by the GROMACS development team.
5  * Copyright (c) 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
37 /*! \internal \file
38  *
39  * \brief This file contains internal function implementations
40  * for performing the PME calculations on GPU.
41  *
42  * Note that this file is compiled as regular C++ source in OpenCL builds, but
43  * it is treated as CUDA source in CUDA-enabled GPU builds.
44  *
45  * \author Aleksei Iupinov <a.yupinov@gmail.com>
46  * \ingroup module_ewald
47  */
48
49 #include "gmxpre.h"
50
51 #include "pme_gpu_internal.h"
52
53 #include "config.h"
54
55 #include <list>
56 #include <memory>
57 #include <string>
58
59 #include "gromacs/ewald/ewald_utils.h"
60 #include "gromacs/gpu_utils/device_context.h"
61 #include "gromacs/gpu_utils/device_stream.h"
62 #include "gromacs/gpu_utils/gpu_utils.h"
63 #include "gromacs/gpu_utils/pmalloc.h"
64 #if GMX_GPU_SYCL
65 #    include "gromacs/gpu_utils/syclutils.h"
66 #endif
67 #include "gromacs/hardware/device_information.h"
68 #include "gromacs/math/invertmatrix.h"
69 #include "gromacs/math/units.h"
70 #include "gromacs/timing/gpu_timing.h"
71 #include "gromacs/utility/exceptions.h"
72 #include "gromacs/utility/fatalerror.h"
73 #include "gromacs/utility/gmxassert.h"
74 #include "gromacs/utility/logger.h"
75 #include "gromacs/utility/stringutil.h"
76 #include "gromacs/ewald/pme.h"
77
78 #if GMX_GPU_CUDA
79 #    include "pme.cuh"
80 #endif
81
82 #include "pme_gpu_3dfft.h"
83 #include "pme_gpu_calculate_splines.h"
84 #include "pme_gpu_constants.h"
85 #include "pme_gpu_program_impl.h"
86 #include "pme_gpu_timings.h"
87 #include "pme_gpu_types.h"
88 #include "pme_gpu_types_host.h"
89 #include "pme_gpu_types_host_impl.h"
90 #include "pme_grid.h"
91 #include "pme_internal.h"
92 #include "pme_solve.h"
93
94 /*! \brief
95  * CUDA only
96  * Atom limit above which it is advantageous to turn on the
97  * recalculating of the splines in the gather and using less threads per atom in the spline and spread
98  */
99 constexpr int c_pmeGpuPerformanceAtomLimit = 23000;
100
101 /*! \internal \brief
102  * Wrapper for getting a pointer to the plain C++ part of the GPU kernel parameters structure.
103  *
104  * \param[in] pmeGpu  The PME GPU structure.
105  * \returns The pointer to the kernel parameters.
106  */
107 static PmeGpuKernelParamsBase* pme_gpu_get_kernel_params_base_ptr(const PmeGpu* pmeGpu)
108 {
109     // reinterpret_cast is needed because the derived CUDA structure is not known in this file
110     auto* kernelParamsPtr = reinterpret_cast<PmeGpuKernelParamsBase*>(pmeGpu->kernelParams.get());
111     return kernelParamsPtr;
112 }
113
114 /*! \brief
115  * Atom data block size (in terms of number of atoms).
116  * This is the least common multiple of number of atoms processed by
117  * a single block/workgroup of the spread and gather kernels.
118  * The GPU atom data buffers must be padded, which means that
119  * the numbers of atoms used for determining the size of the memory
120  * allocation must be divisible by this.
121  */
122 constexpr int c_pmeAtomDataBlockSize = 64;
123
124 int pme_gpu_get_atom_data_block_size()
125 {
126     return c_pmeAtomDataBlockSize;
127 }
128
129 void pme_gpu_synchronize(const PmeGpu* pmeGpu)
130 {
131     pmeGpu->archSpecific->pmeStream_.synchronize();
132 }
133
134 void pme_gpu_alloc_energy_virial(PmeGpu* pmeGpu)
135 {
136     const size_t energyAndVirialSize = c_virialAndEnergyCount * sizeof(float);
137
138     GMX_ASSERT(
139             pmeGpu->common->ngrids == 1 || pmeGpu->common->ngrids == 2,
140             "Only one (normal Coulomb PME) or two (FEP coulomb PME) PME grids can be used on GPU");
141
142     for (int gridIndex = 0; gridIndex < pmeGpu->common->ngrids; gridIndex++)
143     {
144         allocateDeviceBuffer(&pmeGpu->kernelParams->constants.d_virialAndEnergy[gridIndex],
145                              c_virialAndEnergyCount,
146                              pmeGpu->archSpecific->deviceContext_);
147         pmalloc(reinterpret_cast<void**>(&pmeGpu->staging.h_virialAndEnergy[gridIndex]), energyAndVirialSize);
148     }
149 }
150
151 void pme_gpu_free_energy_virial(PmeGpu* pmeGpu)
152 {
153     for (int gridIndex = 0; gridIndex < pmeGpu->common->ngrids; gridIndex++)
154     {
155         freeDeviceBuffer(&pmeGpu->kernelParams->constants.d_virialAndEnergy[gridIndex]);
156         pfree(pmeGpu->staging.h_virialAndEnergy[gridIndex]);
157         pmeGpu->staging.h_virialAndEnergy[gridIndex] = nullptr;
158     }
159 }
160
161 void pme_gpu_clear_energy_virial(const PmeGpu* pmeGpu)
162 {
163     for (int gridIndex = 0; gridIndex < pmeGpu->common->ngrids; gridIndex++)
164     {
165         clearDeviceBufferAsync(&pmeGpu->kernelParams->constants.d_virialAndEnergy[gridIndex],
166                                0,
167                                c_virialAndEnergyCount,
168                                pmeGpu->archSpecific->pmeStream_);
169     }
170 }
171
172 void pme_gpu_realloc_and_copy_bspline_values(PmeGpu* pmeGpu, const int gridIndex)
173 {
174     GMX_ASSERT(
175             pmeGpu->common->ngrids == 1 || pmeGpu->common->ngrids == 2,
176             "Only one (normal Coulomb PME) or two (FEP coulomb PME) PME grids can be used on GPU");
177     GMX_ASSERT(gridIndex < pmeGpu->common->ngrids,
178                "Invalid combination of gridIndex and number of grids");
179
180     const int splineValuesOffset[DIM] = { 0,
181                                           pmeGpu->kernelParams->grid.realGridSize[XX],
182                                           pmeGpu->kernelParams->grid.realGridSize[XX]
183                                                   + pmeGpu->kernelParams->grid.realGridSize[YY] };
184     memcpy(&pmeGpu->kernelParams->grid.splineValuesOffset, &splineValuesOffset, sizeof(splineValuesOffset));
185
186     const int newSplineValuesSize = pmeGpu->kernelParams->grid.realGridSize[XX]
187                                     + pmeGpu->kernelParams->grid.realGridSize[YY]
188                                     + pmeGpu->kernelParams->grid.realGridSize[ZZ];
189     const bool shouldRealloc = (newSplineValuesSize > pmeGpu->archSpecific->splineValuesSize[gridIndex]);
190     reallocateDeviceBuffer(&pmeGpu->kernelParams->grid.d_splineModuli[gridIndex],
191                            newSplineValuesSize,
192                            &pmeGpu->archSpecific->splineValuesSize[gridIndex],
193                            &pmeGpu->archSpecific->splineValuesCapacity[gridIndex],
194                            pmeGpu->archSpecific->deviceContext_);
195     if (shouldRealloc)
196     {
197         /* Reallocate the host buffer */
198         pfree(pmeGpu->staging.h_splineModuli[gridIndex]);
199         pmalloc(reinterpret_cast<void**>(&pmeGpu->staging.h_splineModuli[gridIndex]),
200                 newSplineValuesSize * sizeof(float));
201     }
202     for (int i = 0; i < DIM; i++)
203     {
204         memcpy(pmeGpu->staging.h_splineModuli[gridIndex] + splineValuesOffset[i],
205                pmeGpu->common->bsp_mod[i].data(),
206                pmeGpu->common->bsp_mod[i].size() * sizeof(float));
207     }
208     /* TODO: pin original buffer instead! */
209     copyToDeviceBuffer(&pmeGpu->kernelParams->grid.d_splineModuli[gridIndex],
210                        pmeGpu->staging.h_splineModuli[gridIndex],
211                        0,
212                        newSplineValuesSize,
213                        pmeGpu->archSpecific->pmeStream_,
214                        pmeGpu->settings.transferKind,
215                        nullptr);
216 }
217
218 void pme_gpu_free_bspline_values(const PmeGpu* pmeGpu)
219 {
220     for (int gridIndex = 0; gridIndex < pmeGpu->common->ngrids; gridIndex++)
221     {
222         pfree(pmeGpu->staging.h_splineModuli[gridIndex]);
223         freeDeviceBuffer(&pmeGpu->kernelParams->grid.d_splineModuli[gridIndex]);
224     }
225 }
226
227 void pme_gpu_realloc_forces(PmeGpu* pmeGpu)
228 {
229     const size_t newForcesSize = pmeGpu->nAtomsAlloc;
230     GMX_ASSERT(newForcesSize > 0, "Bad number of atoms in PME GPU");
231     reallocateDeviceBuffer(&pmeGpu->kernelParams->atoms.d_forces,
232                            newForcesSize,
233                            &pmeGpu->archSpecific->forcesSize,
234                            &pmeGpu->archSpecific->forcesSizeAlloc,
235                            pmeGpu->archSpecific->deviceContext_);
236     pmeGpu->staging.h_forces.reserveWithPadding(pmeGpu->nAtomsAlloc);
237     pmeGpu->staging.h_forces.resizeWithPadding(pmeGpu->kernelParams->atoms.nAtoms);
238 }
239
240 void pme_gpu_free_forces(const PmeGpu* pmeGpu)
241 {
242     freeDeviceBuffer(&pmeGpu->kernelParams->atoms.d_forces);
243 }
244
245 void pme_gpu_copy_input_forces(PmeGpu* pmeGpu)
246 {
247     GMX_ASSERT(pmeGpu->kernelParams->atoms.nAtoms > 0, "Bad number of atoms in PME GPU");
248     copyToDeviceBuffer(&pmeGpu->kernelParams->atoms.d_forces,
249                        pmeGpu->staging.h_forces.data(),
250                        0,
251                        pmeGpu->kernelParams->atoms.nAtoms,
252                        pmeGpu->archSpecific->pmeStream_,
253                        pmeGpu->settings.transferKind,
254                        nullptr);
255 }
256
257 void pme_gpu_copy_output_forces(PmeGpu* pmeGpu)
258 {
259     GMX_ASSERT(pmeGpu->kernelParams->atoms.nAtoms > 0, "Bad number of atoms in PME GPU");
260     copyFromDeviceBuffer(pmeGpu->staging.h_forces.data(),
261                          &pmeGpu->kernelParams->atoms.d_forces,
262                          0,
263                          pmeGpu->kernelParams->atoms.nAtoms,
264                          pmeGpu->archSpecific->pmeStream_,
265                          pmeGpu->settings.transferKind,
266                          nullptr);
267 }
268
269 void pme_gpu_realloc_and_copy_input_coefficients(const PmeGpu* pmeGpu,
270                                                  const float*  h_coefficients,
271                                                  const int     gridIndex)
272 {
273     GMX_ASSERT(h_coefficients, "Bad host-side charge buffer in PME GPU");
274     const size_t newCoefficientsSize = pmeGpu->nAtomsAlloc;
275     GMX_ASSERT(newCoefficientsSize > 0, "Bad number of atoms in PME GPU");
276     reallocateDeviceBuffer(&pmeGpu->kernelParams->atoms.d_coefficients[gridIndex],
277                            newCoefficientsSize,
278                            &pmeGpu->archSpecific->coefficientsSize[gridIndex],
279                            &pmeGpu->archSpecific->coefficientsCapacity[gridIndex],
280                            pmeGpu->archSpecific->deviceContext_);
281     copyToDeviceBuffer(&pmeGpu->kernelParams->atoms.d_coefficients[gridIndex],
282                        const_cast<float*>(h_coefficients),
283                        0,
284                        pmeGpu->kernelParams->atoms.nAtoms,
285                        pmeGpu->archSpecific->pmeStream_,
286                        pmeGpu->settings.transferKind,
287                        nullptr);
288
289     const size_t paddingIndex = pmeGpu->kernelParams->atoms.nAtoms;
290     const size_t paddingCount = pmeGpu->nAtomsAlloc - paddingIndex;
291     if (paddingCount > 0)
292     {
293         clearDeviceBufferAsync(&pmeGpu->kernelParams->atoms.d_coefficients[gridIndex],
294                                paddingIndex,
295                                paddingCount,
296                                pmeGpu->archSpecific->pmeStream_);
297     }
298 }
299
300 void pme_gpu_free_coefficients(const PmeGpu* pmeGpu)
301 {
302     for (int gridIndex = 0; gridIndex < pmeGpu->common->ngrids; gridIndex++)
303     {
304         freeDeviceBuffer(&pmeGpu->kernelParams->atoms.d_coefficients[gridIndex]);
305     }
306 }
307
308 void pme_gpu_realloc_spline_data(PmeGpu* pmeGpu)
309 {
310     const int order             = pmeGpu->common->pme_order;
311     const int newSplineDataSize = DIM * order * pmeGpu->nAtomsAlloc;
312     GMX_ASSERT(newSplineDataSize > 0, "Bad number of atoms in PME GPU");
313     /* Two arrays of the same size */
314     const bool shouldRealloc        = (newSplineDataSize > pmeGpu->archSpecific->splineDataSize);
315     int        currentSizeTemp      = pmeGpu->archSpecific->splineDataSize;
316     int        currentSizeTempAlloc = pmeGpu->archSpecific->splineDataSizeAlloc;
317     reallocateDeviceBuffer(&pmeGpu->kernelParams->atoms.d_theta,
318                            newSplineDataSize,
319                            &currentSizeTemp,
320                            &currentSizeTempAlloc,
321                            pmeGpu->archSpecific->deviceContext_);
322     reallocateDeviceBuffer(&pmeGpu->kernelParams->atoms.d_dtheta,
323                            newSplineDataSize,
324                            &pmeGpu->archSpecific->splineDataSize,
325                            &pmeGpu->archSpecific->splineDataSizeAlloc,
326                            pmeGpu->archSpecific->deviceContext_);
327     // the host side reallocation
328     if (shouldRealloc)
329     {
330         pfree(pmeGpu->staging.h_theta);
331         pmalloc(reinterpret_cast<void**>(&pmeGpu->staging.h_theta), newSplineDataSize * sizeof(float));
332         pfree(pmeGpu->staging.h_dtheta);
333         pmalloc(reinterpret_cast<void**>(&pmeGpu->staging.h_dtheta), newSplineDataSize * sizeof(float));
334     }
335 }
336
337 void pme_gpu_free_spline_data(const PmeGpu* pmeGpu)
338 {
339     /* Two arrays of the same size */
340     freeDeviceBuffer(&pmeGpu->kernelParams->atoms.d_theta);
341     freeDeviceBuffer(&pmeGpu->kernelParams->atoms.d_dtheta);
342     pfree(pmeGpu->staging.h_theta);
343     pfree(pmeGpu->staging.h_dtheta);
344 }
345
346 void pme_gpu_realloc_grid_indices(PmeGpu* pmeGpu)
347 {
348     const size_t newIndicesSize = DIM * pmeGpu->nAtomsAlloc;
349     GMX_ASSERT(newIndicesSize > 0, "Bad number of atoms in PME GPU");
350     reallocateDeviceBuffer(&pmeGpu->kernelParams->atoms.d_gridlineIndices,
351                            newIndicesSize,
352                            &pmeGpu->archSpecific->gridlineIndicesSize,
353                            &pmeGpu->archSpecific->gridlineIndicesSizeAlloc,
354                            pmeGpu->archSpecific->deviceContext_);
355     pfree(pmeGpu->staging.h_gridlineIndices);
356     pmalloc(reinterpret_cast<void**>(&pmeGpu->staging.h_gridlineIndices), newIndicesSize * sizeof(int));
357 }
358
359 void pme_gpu_free_grid_indices(const PmeGpu* pmeGpu)
360 {
361     freeDeviceBuffer(&pmeGpu->kernelParams->atoms.d_gridlineIndices);
362     pfree(pmeGpu->staging.h_gridlineIndices);
363 }
364
365 void pme_gpu_realloc_grids(PmeGpu* pmeGpu)
366 {
367     auto* kernelParamsPtr = pmeGpu->kernelParams.get();
368
369     const int newRealGridSize = kernelParamsPtr->grid.realGridSizePadded[XX]
370                                 * kernelParamsPtr->grid.realGridSizePadded[YY]
371                                 * kernelParamsPtr->grid.realGridSizePadded[ZZ];
372     const int newComplexGridSize = kernelParamsPtr->grid.complexGridSizePadded[XX]
373                                    * kernelParamsPtr->grid.complexGridSizePadded[YY]
374                                    * kernelParamsPtr->grid.complexGridSizePadded[ZZ] * 2;
375     for (int gridIndex = 0; gridIndex < pmeGpu->common->ngrids; gridIndex++)
376     {
377         // Multiplied by 2 because we count complex grid size for complex numbers, but all allocations/pointers are float
378         if (pmeGpu->archSpecific->performOutOfPlaceFFT)
379         {
380             /* 2 separate grids */
381             reallocateDeviceBuffer(&kernelParamsPtr->grid.d_fourierGrid[gridIndex],
382                                    newComplexGridSize,
383                                    &pmeGpu->archSpecific->complexGridSize[gridIndex],
384                                    &pmeGpu->archSpecific->complexGridCapacity[gridIndex],
385                                    pmeGpu->archSpecific->deviceContext_);
386             reallocateDeviceBuffer(&kernelParamsPtr->grid.d_realGrid[gridIndex],
387                                    newRealGridSize,
388                                    &pmeGpu->archSpecific->realGridSize[gridIndex],
389                                    &pmeGpu->archSpecific->realGridCapacity[gridIndex],
390                                    pmeGpu->archSpecific->deviceContext_);
391         }
392         else
393         {
394             /* A single buffer so that any grid will fit */
395             const int newGridsSize = std::max(newRealGridSize, newComplexGridSize);
396             reallocateDeviceBuffer(&kernelParamsPtr->grid.d_realGrid[gridIndex],
397                                    newGridsSize,
398                                    &pmeGpu->archSpecific->realGridSize[gridIndex],
399                                    &pmeGpu->archSpecific->realGridCapacity[gridIndex],
400                                    pmeGpu->archSpecific->deviceContext_);
401             kernelParamsPtr->grid.d_fourierGrid[gridIndex] = kernelParamsPtr->grid.d_realGrid[gridIndex];
402             pmeGpu->archSpecific->complexGridSize[gridIndex] =
403                     pmeGpu->archSpecific->realGridSize[gridIndex];
404             // the size might get used later for copying the grid
405         }
406     }
407 }
408
409 void pme_gpu_free_grids(const PmeGpu* pmeGpu)
410 {
411     for (int gridIndex = 0; gridIndex < pmeGpu->common->ngrids; gridIndex++)
412     {
413         if (pmeGpu->archSpecific->performOutOfPlaceFFT)
414         {
415             freeDeviceBuffer(&pmeGpu->kernelParams->grid.d_fourierGrid[gridIndex]);
416         }
417         freeDeviceBuffer(&pmeGpu->kernelParams->grid.d_realGrid[gridIndex]);
418     }
419 }
420
421 void pme_gpu_clear_grids(const PmeGpu* pmeGpu)
422 {
423     for (int gridIndex = 0; gridIndex < pmeGpu->common->ngrids; gridIndex++)
424     {
425         clearDeviceBufferAsync(&pmeGpu->kernelParams->grid.d_realGrid[gridIndex],
426                                0,
427                                pmeGpu->archSpecific->realGridSize[gridIndex],
428                                pmeGpu->archSpecific->pmeStream_);
429     }
430 }
431
432 void pme_gpu_realloc_and_copy_fract_shifts(PmeGpu* pmeGpu)
433 {
434     pme_gpu_free_fract_shifts(pmeGpu);
435
436     auto* kernelParamsPtr = pmeGpu->kernelParams.get();
437
438     const int nx                  = kernelParamsPtr->grid.realGridSize[XX];
439     const int ny                  = kernelParamsPtr->grid.realGridSize[YY];
440     const int nz                  = kernelParamsPtr->grid.realGridSize[ZZ];
441     const int cellCount           = c_pmeNeighborUnitcellCount;
442     const int gridDataOffset[DIM] = { 0, cellCount * nx, cellCount * (nx + ny) };
443
444     memcpy(kernelParamsPtr->grid.tablesOffsets, &gridDataOffset, sizeof(gridDataOffset));
445
446     const int newFractShiftsSize = cellCount * (nx + ny + nz);
447
448     initParamLookupTable(&kernelParamsPtr->grid.d_fractShiftsTable,
449                          &kernelParamsPtr->fractShiftsTableTexture,
450                          pmeGpu->common->fsh.data(),
451                          newFractShiftsSize,
452                          pmeGpu->archSpecific->deviceContext_);
453
454     initParamLookupTable(&kernelParamsPtr->grid.d_gridlineIndicesTable,
455                          &kernelParamsPtr->gridlineIndicesTableTexture,
456                          pmeGpu->common->nn.data(),
457                          newFractShiftsSize,
458                          pmeGpu->archSpecific->deviceContext_);
459 }
460
461 void pme_gpu_free_fract_shifts(const PmeGpu* pmeGpu)
462 {
463     auto* kernelParamsPtr = pmeGpu->kernelParams.get();
464 #if GMX_GPU_CUDA
465     destroyParamLookupTable(&kernelParamsPtr->grid.d_fractShiftsTable,
466                             kernelParamsPtr->fractShiftsTableTexture);
467     destroyParamLookupTable(&kernelParamsPtr->grid.d_gridlineIndicesTable,
468                             kernelParamsPtr->gridlineIndicesTableTexture);
469 #elif GMX_GPU_OPENCL || GMX_GPU_SYCL
470     freeDeviceBuffer(&kernelParamsPtr->grid.d_fractShiftsTable);
471     freeDeviceBuffer(&kernelParamsPtr->grid.d_gridlineIndicesTable);
472 #endif
473 }
474
475 bool pme_gpu_stream_query(const PmeGpu* pmeGpu)
476 {
477     return haveStreamTasksCompleted(pmeGpu->archSpecific->pmeStream_);
478 }
479
480 void pme_gpu_copy_input_gather_grid(const PmeGpu* pmeGpu, const float* h_grid, const int gridIndex)
481 {
482     copyToDeviceBuffer(&pmeGpu->kernelParams->grid.d_realGrid[gridIndex],
483                        h_grid,
484                        0,
485                        pmeGpu->archSpecific->realGridSize[gridIndex],
486                        pmeGpu->archSpecific->pmeStream_,
487                        pmeGpu->settings.transferKind,
488                        nullptr);
489 }
490
491 void pme_gpu_copy_output_spread_grid(const PmeGpu* pmeGpu, float* h_grid, const int gridIndex)
492 {
493     copyFromDeviceBuffer(h_grid,
494                          &pmeGpu->kernelParams->grid.d_realGrid[gridIndex],
495                          0,
496                          pmeGpu->archSpecific->realGridSize[gridIndex],
497                          pmeGpu->archSpecific->pmeStream_,
498                          pmeGpu->settings.transferKind,
499                          nullptr);
500     pmeGpu->archSpecific->syncSpreadGridD2H.markEvent(pmeGpu->archSpecific->pmeStream_);
501 }
502
503 void pme_gpu_copy_output_spread_atom_data(const PmeGpu* pmeGpu)
504 {
505     const size_t splinesCount    = DIM * pmeGpu->nAtomsAlloc * pmeGpu->common->pme_order;
506     auto*        kernelParamsPtr = pmeGpu->kernelParams.get();
507     copyFromDeviceBuffer(pmeGpu->staging.h_dtheta,
508                          &kernelParamsPtr->atoms.d_dtheta,
509                          0,
510                          splinesCount,
511                          pmeGpu->archSpecific->pmeStream_,
512                          pmeGpu->settings.transferKind,
513                          nullptr);
514     copyFromDeviceBuffer(pmeGpu->staging.h_theta,
515                          &kernelParamsPtr->atoms.d_theta,
516                          0,
517                          splinesCount,
518                          pmeGpu->archSpecific->pmeStream_,
519                          pmeGpu->settings.transferKind,
520                          nullptr);
521     copyFromDeviceBuffer(pmeGpu->staging.h_gridlineIndices,
522                          &kernelParamsPtr->atoms.d_gridlineIndices,
523                          0,
524                          kernelParamsPtr->atoms.nAtoms * DIM,
525                          pmeGpu->archSpecific->pmeStream_,
526                          pmeGpu->settings.transferKind,
527                          nullptr);
528 }
529
530 void pme_gpu_copy_input_gather_atom_data(const PmeGpu* pmeGpu)
531 {
532     const size_t splinesCount    = DIM * pmeGpu->nAtomsAlloc * pmeGpu->common->pme_order;
533     auto*        kernelParamsPtr = pmeGpu->kernelParams.get();
534
535     // TODO: could clear only the padding and not the whole thing, but this is a test-exclusive code anyway
536     clearDeviceBufferAsync(&kernelParamsPtr->atoms.d_gridlineIndices,
537                            0,
538                            pmeGpu->nAtomsAlloc * DIM,
539                            pmeGpu->archSpecific->pmeStream_);
540     clearDeviceBufferAsync(&kernelParamsPtr->atoms.d_dtheta,
541                            0,
542                            pmeGpu->nAtomsAlloc * pmeGpu->common->pme_order * DIM,
543                            pmeGpu->archSpecific->pmeStream_);
544     clearDeviceBufferAsync(&kernelParamsPtr->atoms.d_theta,
545                            0,
546                            pmeGpu->nAtomsAlloc * pmeGpu->common->pme_order * DIM,
547                            pmeGpu->archSpecific->pmeStream_);
548
549     copyToDeviceBuffer(&kernelParamsPtr->atoms.d_dtheta,
550                        pmeGpu->staging.h_dtheta,
551                        0,
552                        splinesCount,
553                        pmeGpu->archSpecific->pmeStream_,
554                        pmeGpu->settings.transferKind,
555                        nullptr);
556     copyToDeviceBuffer(&kernelParamsPtr->atoms.d_theta,
557                        pmeGpu->staging.h_theta,
558                        0,
559                        splinesCount,
560                        pmeGpu->archSpecific->pmeStream_,
561                        pmeGpu->settings.transferKind,
562                        nullptr);
563     copyToDeviceBuffer(&kernelParamsPtr->atoms.d_gridlineIndices,
564                        pmeGpu->staging.h_gridlineIndices,
565                        0,
566                        kernelParamsPtr->atoms.nAtoms * DIM,
567                        pmeGpu->archSpecific->pmeStream_,
568                        pmeGpu->settings.transferKind,
569                        nullptr);
570 }
571
572 void pme_gpu_sync_spread_grid(const PmeGpu* pmeGpu)
573 {
574     pmeGpu->archSpecific->syncSpreadGridD2H.waitForEvent();
575 }
576
577 /*! \brief Internal GPU initialization for PME.
578  *
579  * \param[in]  pmeGpu         GPU PME data.
580  * \param[in]  deviceContext  GPU context.
581  * \param[in]  deviceStream   GPU stream.
582  */
583 static void pme_gpu_init_internal(PmeGpu* pmeGpu, const DeviceContext& deviceContext, const DeviceStream& deviceStream)
584 {
585     /* Allocate the target-specific structures */
586     pmeGpu->archSpecific.reset(new PmeGpuSpecific(deviceContext, deviceStream));
587     pmeGpu->kernelParams.reset(new PmeGpuKernelParams());
588
589     pmeGpu->archSpecific->performOutOfPlaceFFT = true;
590     /* This should give better performance, according to the cuFFT documentation.
591      * The performance seems to be the same though.
592      * TODO: PME could also try to pick up nice grid sizes (with factors of 2, 3, 5, 7).
593      */
594
595 #if GMX_GPU_CUDA
596     pmeGpu->maxGridWidthX = deviceContext.deviceInfo().prop.maxGridSize[0];
597 #else
598     // Use this path for any non-CUDA GPU acceleration
599     // TODO: is there no really global work size limit in OpenCL?
600     pmeGpu->maxGridWidthX = INT32_MAX / 2;
601 #endif
602 }
603
604 void pme_gpu_reinit_3dfft(const PmeGpu* pmeGpu)
605 {
606     if (pme_gpu_settings(pmeGpu).performGPUFFT)
607     {
608         pmeGpu->archSpecific->fftSetup.resize(0);
609         for (int gridIndex = 0; gridIndex < pmeGpu->common->ngrids; gridIndex++)
610         {
611             pmeGpu->archSpecific->fftSetup.push_back(std::make_unique<GpuParallel3dFft>(pmeGpu, gridIndex));
612         }
613     }
614 }
615
616 void pme_gpu_destroy_3dfft(const PmeGpu* pmeGpu)
617 {
618     pmeGpu->archSpecific->fftSetup.resize(0);
619 }
620
621 void pme_gpu_getEnergyAndVirial(const gmx_pme_t& pme, const float lambda, PmeOutput* output)
622 {
623     const PmeGpu* pmeGpu = pme.gpu;
624
625     GMX_ASSERT(lambda == 1.0 || pmeGpu->common->ngrids == 2,
626                "Invalid combination of lambda and number of grids");
627
628     for (int gridIndex = 0; gridIndex < pmeGpu->common->ngrids; gridIndex++)
629     {
630         for (int j = 0; j < c_virialAndEnergyCount; j++)
631         {
632             GMX_ASSERT(std::isfinite(pmeGpu->staging.h_virialAndEnergy[gridIndex][j]),
633                        "PME GPU produces incorrect energy/virial.");
634         }
635     }
636     for (int dim1 = 0; dim1 < DIM; dim1++)
637     {
638         for (int dim2 = 0; dim2 < DIM; dim2++)
639         {
640             output->coulombVirial_[dim1][dim2] = 0;
641         }
642     }
643     output->coulombEnergy_ = 0;
644     float scale            = 1.0;
645     for (int gridIndex = 0; gridIndex < pmeGpu->common->ngrids; gridIndex++)
646     {
647         if (pmeGpu->common->ngrids == 2)
648         {
649             scale = gridIndex == 0 ? (1.0 - lambda) : lambda;
650         }
651         output->coulombVirial_[XX][XX] +=
652                 scale * 0.25F * pmeGpu->staging.h_virialAndEnergy[gridIndex][0];
653         output->coulombVirial_[YY][YY] +=
654                 scale * 0.25F * pmeGpu->staging.h_virialAndEnergy[gridIndex][1];
655         output->coulombVirial_[ZZ][ZZ] +=
656                 scale * 0.25F * pmeGpu->staging.h_virialAndEnergy[gridIndex][2];
657         output->coulombVirial_[XX][YY] +=
658                 scale * 0.25F * pmeGpu->staging.h_virialAndEnergy[gridIndex][3];
659         output->coulombVirial_[YY][XX] +=
660                 scale * 0.25F * pmeGpu->staging.h_virialAndEnergy[gridIndex][3];
661         output->coulombVirial_[XX][ZZ] +=
662                 scale * 0.25F * pmeGpu->staging.h_virialAndEnergy[gridIndex][4];
663         output->coulombVirial_[ZZ][XX] +=
664                 scale * 0.25F * pmeGpu->staging.h_virialAndEnergy[gridIndex][4];
665         output->coulombVirial_[YY][ZZ] +=
666                 scale * 0.25F * pmeGpu->staging.h_virialAndEnergy[gridIndex][5];
667         output->coulombVirial_[ZZ][YY] +=
668                 scale * 0.25F * pmeGpu->staging.h_virialAndEnergy[gridIndex][5];
669         output->coulombEnergy_ += scale * 0.5F * pmeGpu->staging.h_virialAndEnergy[gridIndex][6];
670     }
671     if (pmeGpu->common->ngrids > 1)
672     {
673         output->coulombDvdl_ = 0.5F
674                                * (pmeGpu->staging.h_virialAndEnergy[FEP_STATE_B][6]
675                                   - pmeGpu->staging.h_virialAndEnergy[FEP_STATE_A][6]);
676     }
677 }
678
679 /*! \brief Sets the force-related members in \p output
680  *
681  * \param[in]   pmeGpu      PME GPU data structure
682  * \param[out]  output      Pointer to PME output data structure
683  */
684 static void pme_gpu_getForceOutput(PmeGpu* pmeGpu, PmeOutput* output)
685 {
686     output->haveForceOutput_ = !pmeGpu->settings.useGpuForceReduction;
687     if (output->haveForceOutput_)
688     {
689         output->forces_ = pmeGpu->staging.h_forces;
690     }
691 }
692
693 PmeOutput pme_gpu_getOutput(const gmx_pme_t& pme, const bool computeEnergyAndVirial, const real lambdaQ)
694 {
695     PmeGpu* pmeGpu = pme.gpu;
696
697     PmeOutput output;
698
699     pme_gpu_getForceOutput(pmeGpu, &output);
700
701     if (computeEnergyAndVirial)
702     {
703         if (pme_gpu_settings(pmeGpu).performGPUSolve)
704         {
705             pme_gpu_getEnergyAndVirial(pme, lambdaQ, &output);
706         }
707         else
708         {
709             get_pme_ener_vir_q(pme.solve_work, pme.nthread, &output);
710         }
711     }
712     return output;
713 }
714
715 void pme_gpu_update_input_box(PmeGpu gmx_unused* pmeGpu, const matrix gmx_unused box)
716 {
717 #if GMX_DOUBLE
718     GMX_THROW(gmx::NotImplementedError("PME is implemented for single-precision only on GPU"));
719 #else
720     matrix scaledBox;
721     pmeGpu->common->boxScaler->scaleBox(box, scaledBox);
722     auto* kernelParamsPtr              = pme_gpu_get_kernel_params_base_ptr(pmeGpu);
723     kernelParamsPtr->current.boxVolume = scaledBox[XX][XX] * scaledBox[YY][YY] * scaledBox[ZZ][ZZ];
724     GMX_ASSERT(kernelParamsPtr->current.boxVolume != 0.0F, "Zero volume of the unit cell");
725     matrix recipBox;
726     gmx::invertBoxMatrix(scaledBox, recipBox);
727
728     /* The GPU recipBox is transposed as compared to the CPU recipBox.
729      * Spread uses matrix columns (while solve and gather use rows).
730      * There is no particular reason for this; it might be further rethought/optimized for better access patterns.
731      */
732     const real newRecipBox[DIM][DIM] = { { recipBox[XX][XX], recipBox[YY][XX], recipBox[ZZ][XX] },
733                                          { 0.0, recipBox[YY][YY], recipBox[ZZ][YY] },
734                                          { 0.0, 0.0, recipBox[ZZ][ZZ] } };
735     memcpy(kernelParamsPtr->current.recipBox, newRecipBox, sizeof(matrix));
736 #endif
737 }
738
739 /*! \brief \libinternal
740  * (Re-)initializes all the PME GPU data related to the grid size and cut-off.
741  *
742  * \param[in] pmeGpu            The PME GPU structure.
743  */
744 static void pme_gpu_reinit_grids(PmeGpu* pmeGpu)
745 {
746     auto* kernelParamsPtr = pme_gpu_get_kernel_params_base_ptr(pmeGpu);
747
748     GMX_ASSERT(
749             pmeGpu->common->ngrids == 1 || pmeGpu->common->ngrids == 2,
750             "Only one (normal Coulomb PME) or two (FEP coulomb PME) PME grids can be used on GPU");
751
752     kernelParamsPtr->grid.ewaldFactor =
753             (M_PI * M_PI) / (pmeGpu->common->ewaldcoeff_q * pmeGpu->common->ewaldcoeff_q);
754     /* The grid size variants */
755     for (int i = 0; i < DIM; i++)
756     {
757         kernelParamsPtr->grid.realGridSize[i] = pmeGpu->common->nk[i];
758         kernelParamsPtr->grid.realGridSizeFP[i] =
759                 static_cast<float>(kernelParamsPtr->grid.realGridSize[i]);
760         kernelParamsPtr->grid.realGridSizePadded[i] = kernelParamsPtr->grid.realGridSize[i];
761
762         // The complex grid currently uses no padding;
763         // if it starts to do so, then another test should be added for that
764         kernelParamsPtr->grid.complexGridSize[i]       = kernelParamsPtr->grid.realGridSize[i];
765         kernelParamsPtr->grid.complexGridSizePadded[i] = kernelParamsPtr->grid.realGridSize[i];
766     }
767     /* FFT: n real elements correspond to (n / 2 + 1) complex elements in minor dimension */
768     if (!pme_gpu_settings(pmeGpu).performGPUFFT)
769     {
770         // This allows for GPU spreading grid and CPU fftgrid to have the same layout, so that we can copy the data directly
771         kernelParamsPtr->grid.realGridSizePadded[ZZ] =
772                 (kernelParamsPtr->grid.realGridSize[ZZ] / 2 + 1) * 2;
773     }
774     /* GPU FFT: n real elements correspond to (n / 2 + 1) complex elements in minor dimension */
775     kernelParamsPtr->grid.complexGridSize[ZZ] /= 2;
776     kernelParamsPtr->grid.complexGridSize[ZZ]++;
777     kernelParamsPtr->grid.complexGridSizePadded[ZZ] = kernelParamsPtr->grid.complexGridSize[ZZ];
778
779     pme_gpu_realloc_and_copy_fract_shifts(pmeGpu);
780     for (int gridIndex = 0; gridIndex < pmeGpu->common->ngrids; gridIndex++)
781     {
782         pme_gpu_realloc_and_copy_bspline_values(pmeGpu, gridIndex);
783     }
784
785     pme_gpu_realloc_grids(pmeGpu);
786     pme_gpu_reinit_3dfft(pmeGpu);
787 }
788
789 /* Several GPU functions that refer to the CPU PME data live here.
790  * We would like to keep these away from the GPU-framework specific code for clarity,
791  * as well as compilation issues with MPI.
792  */
793
794 /*! \brief \libinternal
795  * Copies everything useful from the PME CPU to the PME GPU structure.
796  * The goal is to minimize interaction with the PME CPU structure in the GPU code.
797  *
798  * \param[in] pme         The PME structure.
799  */
800 static void pme_gpu_copy_common_data_from(const gmx_pme_t* pme)
801 {
802     /* TODO: Consider refactoring the CPU PME code to use the same structure,
803      * so that this function becomes 2 lines */
804     PmeGpu* pmeGpu               = pme->gpu;
805     pmeGpu->common->ngrids       = pme->bFEP_q ? 2 : 1;
806     pmeGpu->common->epsilon_r    = pme->epsilon_r;
807     pmeGpu->common->ewaldcoeff_q = pme->ewaldcoeff_q;
808     pmeGpu->common->nk[XX]       = pme->nkx;
809     pmeGpu->common->nk[YY]       = pme->nky;
810     pmeGpu->common->nk[ZZ]       = pme->nkz;
811     pmeGpu->common->pme_order    = pme->pme_order;
812     if (pmeGpu->common->pme_order != c_pmeGpuOrder)
813     {
814         GMX_THROW(gmx::NotImplementedError("pme_order != 4 is not implemented!"));
815     }
816     for (int i = 0; i < DIM; i++)
817     {
818         pmeGpu->common->bsp_mod[i].assign(pme->bsp_mod[i], pme->bsp_mod[i] + pmeGpu->common->nk[i]);
819     }
820     const int cellCount = c_pmeNeighborUnitcellCount;
821     pmeGpu->common->fsh.resize(0);
822     pmeGpu->common->fsh.insert(pmeGpu->common->fsh.end(), pme->fshx, pme->fshx + cellCount * pme->nkx);
823     pmeGpu->common->fsh.insert(pmeGpu->common->fsh.end(), pme->fshy, pme->fshy + cellCount * pme->nky);
824     pmeGpu->common->fsh.insert(pmeGpu->common->fsh.end(), pme->fshz, pme->fshz + cellCount * pme->nkz);
825     pmeGpu->common->nn.resize(0);
826     pmeGpu->common->nn.insert(pmeGpu->common->nn.end(), pme->nnx, pme->nnx + cellCount * pme->nkx);
827     pmeGpu->common->nn.insert(pmeGpu->common->nn.end(), pme->nny, pme->nny + cellCount * pme->nky);
828     pmeGpu->common->nn.insert(pmeGpu->common->nn.end(), pme->nnz, pme->nnz + cellCount * pme->nkz);
829     pmeGpu->common->runMode       = pme->runMode;
830     pmeGpu->common->isRankPmeOnly = !pme->bPPnode;
831     pmeGpu->common->boxScaler     = pme->boxScaler;
832 }
833
834 /*! \libinternal \brief
835  * uses heuristics to select the best performing PME gather and scatter kernels
836  *
837  * \param[in,out] pmeGpu         The PME GPU structure.
838  */
839 static void pme_gpu_select_best_performing_pme_spreadgather_kernels(PmeGpu* pmeGpu)
840 {
841     if (GMX_GPU_CUDA && pmeGpu->kernelParams->atoms.nAtoms > c_pmeGpuPerformanceAtomLimit)
842     {
843         pmeGpu->settings.threadsPerAtom     = ThreadsPerAtom::Order;
844         pmeGpu->settings.recalculateSplines = true;
845     }
846     else
847     {
848         pmeGpu->settings.threadsPerAtom     = ThreadsPerAtom::OrderSquared;
849         pmeGpu->settings.recalculateSplines = false;
850     }
851 }
852
853
854 /*! \libinternal \brief
855  * Initializes the PME GPU data at the beginning of the run.
856  * TODO: this should become PmeGpu::PmeGpu()
857  *
858  * \param[in,out] pme            The PME structure.
859  * \param[in]     deviceContext  The GPU context.
860  * \param[in]     deviceStream   The GPU stream.
861  * \param[in,out] pmeGpuProgram  The handle to the program/kernel data created outside (e.g. in unit tests/runner)
862  */
863 static void pme_gpu_init(gmx_pme_t*           pme,
864                          const DeviceContext& deviceContext,
865                          const DeviceStream&  deviceStream,
866                          const PmeGpuProgram* pmeGpuProgram)
867 {
868     pme->gpu       = new PmeGpu();
869     PmeGpu* pmeGpu = pme->gpu;
870     changePinningPolicy(&pmeGpu->staging.h_forces, pme_get_pinning_policy());
871     pmeGpu->common = std::make_shared<PmeShared>();
872
873     /* These settings are set here for the whole run; dynamic ones are set in pme_gpu_reinit() */
874     /* A convenience variable. */
875     pmeGpu->settings.useDecomposition = (pme->nnodes != 1);
876     /* TODO: CPU gather with GPU spread is broken due to different theta/dtheta layout. */
877     pmeGpu->settings.performGPUGather = true;
878     // By default GPU-side reduction is off (explicitly set here for tests, otherwise reset per-step)
879     pmeGpu->settings.useGpuForceReduction = false;
880
881     pme_gpu_set_testing(pmeGpu, false);
882
883     GMX_ASSERT(pmeGpuProgram != nullptr, "GPU kernels must be already compiled");
884     pmeGpu->programHandle_ = pmeGpuProgram;
885
886     pmeGpu->initializedClfftLibrary_ = std::make_unique<gmx::ClfftInitializer>();
887
888     pme_gpu_init_internal(pmeGpu, deviceContext, deviceStream);
889
890     pme_gpu_copy_common_data_from(pme);
891     pme_gpu_alloc_energy_virial(pmeGpu);
892
893     GMX_ASSERT(pmeGpu->common->epsilon_r != 0.0F, "PME GPU: bad electrostatic coefficient");
894
895     auto* kernelParamsPtr               = pme_gpu_get_kernel_params_base_ptr(pmeGpu);
896     kernelParamsPtr->constants.elFactor = gmx::c_one4PiEps0 / pmeGpu->common->epsilon_r;
897 }
898
899 void pme_gpu_get_real_grid_sizes(const PmeGpu* pmeGpu, gmx::IVec* gridSize, gmx::IVec* paddedGridSize)
900 {
901     GMX_ASSERT(gridSize != nullptr, "");
902     GMX_ASSERT(paddedGridSize != nullptr, "");
903     GMX_ASSERT(pmeGpu != nullptr, "");
904     auto* kernelParamsPtr = pme_gpu_get_kernel_params_base_ptr(pmeGpu);
905     for (int i = 0; i < DIM; i++)
906     {
907         (*gridSize)[i]       = kernelParamsPtr->grid.realGridSize[i];
908         (*paddedGridSize)[i] = kernelParamsPtr->grid.realGridSizePadded[i];
909     }
910 }
911
912 void pme_gpu_reinit(gmx_pme_t*           pme,
913                     const DeviceContext* deviceContext,
914                     const DeviceStream*  deviceStream,
915                     const PmeGpuProgram* pmeGpuProgram)
916 {
917     GMX_ASSERT(pme != nullptr, "Need valid PME object");
918
919     if (!pme->gpu)
920     {
921         GMX_RELEASE_ASSERT(deviceContext != nullptr,
922                            "Device context can not be nullptr when setting up PME on GPU.");
923         GMX_RELEASE_ASSERT(deviceStream != nullptr,
924                            "Device stream can not be nullptr when setting up PME on GPU.");
925         /* First-time initialization */
926         pme_gpu_init(pme, *deviceContext, *deviceStream, pmeGpuProgram);
927     }
928     else
929     {
930         /* After this call nothing in the GPU code should refer to the gmx_pme_t *pme itself - until the next pme_gpu_reinit */
931         pme_gpu_copy_common_data_from(pme);
932     }
933     /* GPU FFT will only get used for a single rank.*/
934     pme->gpu->settings.performGPUFFT =
935             (pme->gpu->common->runMode == PmeRunMode::GPU) && !pme->gpu->settings.useDecomposition;
936     pme->gpu->settings.performGPUSolve = (pme->gpu->common->runMode == PmeRunMode::GPU);
937
938     /* Reinit active timers */
939     pme_gpu_reinit_timings(pme->gpu);
940
941     pme_gpu_reinit_grids(pme->gpu);
942     // Note: if timing the reinit launch overhead becomes more relevant
943     // (e.g. with regulat PP-PME re-balancing), we should pass wcycle here.
944     pme_gpu_reinit_computation(pme, nullptr);
945     /* Clear the previous box - doesn't hurt, and forces the PME CPU recipbox
946      * update for mixed mode on grid switch. TODO: use shared recipbox field.
947      */
948     std::memset(pme->gpu->common->previousBox, 0, sizeof(pme->gpu->common->previousBox));
949 }
950
951 void pme_gpu_destroy(PmeGpu* pmeGpu)
952 {
953     /* Free lots of data */
954     pme_gpu_free_energy_virial(pmeGpu);
955     pme_gpu_free_bspline_values(pmeGpu);
956     pme_gpu_free_forces(pmeGpu);
957     pme_gpu_free_coefficients(pmeGpu);
958     pme_gpu_free_spline_data(pmeGpu);
959     pme_gpu_free_grid_indices(pmeGpu);
960     pme_gpu_free_fract_shifts(pmeGpu);
961     pme_gpu_free_grids(pmeGpu);
962
963     pme_gpu_destroy_3dfft(pmeGpu);
964
965     delete pmeGpu;
966 }
967
968 void pme_gpu_reinit_atoms(PmeGpu* pmeGpu, const int nAtoms, const real* chargesA, const real* chargesB)
969 {
970     auto* kernelParamsPtr         = pme_gpu_get_kernel_params_base_ptr(pmeGpu);
971     kernelParamsPtr->atoms.nAtoms = nAtoms;
972     const int  block_size         = pme_gpu_get_atom_data_block_size();
973     const int  nAtomsNewPadded    = ((nAtoms + block_size - 1) / block_size) * block_size;
974     const bool haveToRealloc      = (pmeGpu->nAtomsAlloc < nAtomsNewPadded);
975     pmeGpu->nAtomsAlloc           = nAtomsNewPadded;
976
977 #if GMX_DOUBLE
978     GMX_RELEASE_ASSERT(false, "Only single precision supported");
979     GMX_UNUSED_VALUE(charges);
980 #else
981     int gridIndex = 0;
982     /* Could also be checked for haveToRealloc, but the copy always needs to be performed */
983     pme_gpu_realloc_and_copy_input_coefficients(pmeGpu, reinterpret_cast<const float*>(chargesA), gridIndex);
984     gridIndex++;
985     if (chargesB != nullptr)
986     {
987         pme_gpu_realloc_and_copy_input_coefficients(
988                 pmeGpu, reinterpret_cast<const float*>(chargesB), gridIndex);
989     }
990     else
991     {
992         /* Fill the second set of coefficients with chargesA as well to be able to avoid
993          * conditionals in the GPU kernels */
994         /* FIXME: This should be avoided by making a separate templated version of the
995          * relevant kernel(s) (probably only pme_gather_kernel). That would require a
996          * reduction of the current number of templated parameters of that kernel. */
997         pme_gpu_realloc_and_copy_input_coefficients(
998                 pmeGpu, reinterpret_cast<const float*>(chargesA), gridIndex);
999     }
1000 #endif
1001
1002     if (haveToRealloc)
1003     {
1004         pme_gpu_realloc_forces(pmeGpu);
1005         pme_gpu_realloc_spline_data(pmeGpu);
1006         pme_gpu_realloc_grid_indices(pmeGpu);
1007     }
1008     pme_gpu_select_best_performing_pme_spreadgather_kernels(pmeGpu);
1009 }
1010
1011 /*! \internal \brief
1012  * Returns raw timing event from the corresponding GpuRegionTimer (if timings are enabled).
1013  * In CUDA result can be nullptr stub, per GpuRegionTimer implementation.
1014  *
1015  * \param[in] pmeGpu         The PME GPU data structure.
1016  * \param[in] pmeStageId     The PME GPU stage gtPME_ index from the enum in src/gromacs/timing/gpu_timing.h
1017  */
1018 static CommandEvent* pme_gpu_fetch_timing_event(const PmeGpu* pmeGpu, PmeStage pmeStageId)
1019 {
1020     CommandEvent* timingEvent = nullptr;
1021     if (pme_gpu_timings_enabled(pmeGpu))
1022     {
1023         GMX_ASSERT(pmeStageId < PmeStage::Count, "Wrong PME GPU timing event index");
1024         timingEvent = pmeGpu->archSpecific->timingEvents[pmeStageId].fetchNextEvent();
1025     }
1026     return timingEvent;
1027 }
1028
1029 void pme_gpu_3dfft(const PmeGpu* pmeGpu, gmx_fft_direction dir, const int grid_index)
1030 {
1031     PmeStage timerId = (dir == GMX_FFT_REAL_TO_COMPLEX) ? PmeStage::FftTransformR2C
1032                                                         : PmeStage::FftTransformC2R;
1033
1034     pme_gpu_start_timing(pmeGpu, timerId);
1035     pmeGpu->archSpecific->fftSetup[grid_index]->perform3dFft(
1036             dir, pme_gpu_fetch_timing_event(pmeGpu, timerId));
1037     pme_gpu_stop_timing(pmeGpu, timerId);
1038 }
1039
1040 /*! \brief
1041  * Given possibly large \p blockCount, returns a compact 1D or 2D grid for kernel scheduling,
1042  * to minimize number of unused blocks.
1043  */
1044 std::pair<int, int> inline pmeGpuCreateGrid(const PmeGpu* pmeGpu, int blockCount)
1045 {
1046     // How many maximum widths in X do we need (hopefully just one)
1047     const int minRowCount = (blockCount + pmeGpu->maxGridWidthX - 1) / pmeGpu->maxGridWidthX;
1048     // Trying to make things even
1049     const int colCount = (blockCount + minRowCount - 1) / minRowCount;
1050     GMX_ASSERT((colCount * minRowCount - blockCount) >= 0, "pmeGpuCreateGrid: totally wrong");
1051     GMX_ASSERT((colCount * minRowCount - blockCount) < minRowCount,
1052                "pmeGpuCreateGrid: excessive blocks");
1053     return std::pair<int, int>(colCount, minRowCount);
1054 }
1055
1056 /*! \brief
1057  * Returns a pointer to appropriate spline and spread kernel based on the input bool values
1058  *
1059  * \param[in]  pmeGpu                   The PME GPU structure.
1060  * \param[in]  threadsPerAtom           Controls whether we should use order or order*order threads per atom
1061  * \param[in]  writeSplinesToGlobal     bool controlling if we should write spline data to global memory
1062  * \param[in]  numGrids                 Number of grids to use. numGrids == 2 if Coulomb is perturbed.
1063  *
1064  * \return Pointer to CUDA kernel
1065  */
1066 static auto selectSplineAndSpreadKernelPtr(const PmeGpu*  pmeGpu,
1067                                            ThreadsPerAtom threadsPerAtom,
1068                                            bool           writeSplinesToGlobal,
1069                                            const int      numGrids)
1070 {
1071     PmeGpuProgramImpl::PmeKernelHandle kernelPtr = nullptr;
1072     if (writeSplinesToGlobal)
1073     {
1074         if (threadsPerAtom == ThreadsPerAtom::Order)
1075         {
1076             if (numGrids == 2)
1077             {
1078                 kernelPtr = pmeGpu->programHandle_->impl_->splineAndSpreadKernelWriteSplinesThPerAtom4Dual;
1079             }
1080             else
1081             {
1082                 kernelPtr = pmeGpu->programHandle_->impl_->splineAndSpreadKernelWriteSplinesThPerAtom4Single;
1083             }
1084         }
1085         else
1086         {
1087             if (numGrids == 2)
1088             {
1089                 kernelPtr = pmeGpu->programHandle_->impl_->splineAndSpreadKernelWriteSplinesDual;
1090             }
1091             else
1092             {
1093                 kernelPtr = pmeGpu->programHandle_->impl_->splineAndSpreadKernelWriteSplinesSingle;
1094             }
1095         }
1096     }
1097     else
1098     {
1099         if (threadsPerAtom == ThreadsPerAtom::Order)
1100         {
1101             if (numGrids == 2)
1102             {
1103                 kernelPtr = pmeGpu->programHandle_->impl_->splineAndSpreadKernelThPerAtom4Dual;
1104             }
1105             else
1106             {
1107                 kernelPtr = pmeGpu->programHandle_->impl_->splineAndSpreadKernelThPerAtom4Single;
1108             }
1109         }
1110         else
1111         {
1112             if (numGrids == 2)
1113             {
1114                 kernelPtr = pmeGpu->programHandle_->impl_->splineAndSpreadKernelDual;
1115             }
1116             else
1117             {
1118                 kernelPtr = pmeGpu->programHandle_->impl_->splineAndSpreadKernelSingle;
1119             }
1120         }
1121     }
1122
1123     return kernelPtr;
1124 }
1125
1126 /*! \brief
1127  * Returns a pointer to appropriate spline kernel based on the input bool values
1128  *
1129  * \param[in]  pmeGpu                   The PME GPU structure.
1130  * \param[in]  threadsPerAtom           Controls whether we should use order or order*order threads per atom
1131  * \param[in]  writeSplinesToGlobal     bool controlling if we should write spline data to global memory
1132  * \param[in]  numGrids                 Number of grids to use. numGrids == 2 if Coulomb is perturbed.
1133  *
1134  * \return Pointer to CUDA kernel
1135  */
1136 static auto selectSplineKernelPtr(const PmeGpu*   pmeGpu,
1137                                   ThreadsPerAtom  threadsPerAtom,
1138                                   bool gmx_unused writeSplinesToGlobal,
1139                                   const int       numGrids)
1140 {
1141     PmeGpuProgramImpl::PmeKernelHandle kernelPtr = nullptr;
1142     GMX_ASSERT(
1143             writeSplinesToGlobal,
1144             "Spline data should always be written to global memory when just calculating splines");
1145
1146     if (threadsPerAtom == ThreadsPerAtom::Order)
1147     {
1148         if (numGrids == 2)
1149         {
1150             kernelPtr = pmeGpu->programHandle_->impl_->splineKernelThPerAtom4Dual;
1151         }
1152         else
1153         {
1154             kernelPtr = pmeGpu->programHandle_->impl_->splineKernelThPerAtom4Single;
1155         }
1156     }
1157     else
1158     {
1159         if (numGrids == 2)
1160         {
1161             kernelPtr = pmeGpu->programHandle_->impl_->splineKernelDual;
1162         }
1163         else
1164         {
1165             kernelPtr = pmeGpu->programHandle_->impl_->splineKernelSingle;
1166         }
1167     }
1168     return kernelPtr;
1169 }
1170
1171 /*! \brief
1172  * Returns a pointer to appropriate spread kernel based on the input bool values
1173  *
1174  * \param[in]  pmeGpu                   The PME GPU structure.
1175  * \param[in]  threadsPerAtom           Controls whether we should use order or order*order threads per atom
1176  * \param[in]  writeSplinesToGlobal     bool controlling if we should write spline data to global memory
1177  * \param[in]  numGrids                 Number of grids to use. numGrids == 2 if Coulomb is perturbed.
1178  *
1179  * \return Pointer to CUDA kernel
1180  */
1181 static auto selectSpreadKernelPtr(const PmeGpu*  pmeGpu,
1182                                   ThreadsPerAtom threadsPerAtom,
1183                                   bool           writeSplinesToGlobal,
1184                                   const int      numGrids)
1185 {
1186     PmeGpuProgramImpl::PmeKernelHandle kernelPtr = nullptr;
1187     if (writeSplinesToGlobal)
1188     {
1189         if (threadsPerAtom == ThreadsPerAtom::Order)
1190         {
1191             if (numGrids == 2)
1192             {
1193                 kernelPtr = pmeGpu->programHandle_->impl_->spreadKernelThPerAtom4Dual;
1194             }
1195             {
1196                 kernelPtr = pmeGpu->programHandle_->impl_->spreadKernelThPerAtom4Single;
1197             }
1198         }
1199         else
1200         {
1201             if (numGrids == 2)
1202             {
1203                 kernelPtr = pmeGpu->programHandle_->impl_->spreadKernelDual;
1204             }
1205             else
1206             {
1207                 kernelPtr = pmeGpu->programHandle_->impl_->spreadKernelSingle;
1208             }
1209         }
1210     }
1211     else
1212     {
1213         /* if we are not saving the spline data we need to recalculate it
1214            using the spline and spread Kernel */
1215         if (threadsPerAtom == ThreadsPerAtom::Order)
1216         {
1217             if (numGrids == 2)
1218             {
1219                 kernelPtr = pmeGpu->programHandle_->impl_->splineAndSpreadKernelThPerAtom4Dual;
1220             }
1221             else
1222             {
1223                 kernelPtr = pmeGpu->programHandle_->impl_->splineAndSpreadKernelThPerAtom4Single;
1224             }
1225         }
1226         else
1227         {
1228             if (numGrids == 2)
1229             {
1230                 kernelPtr = pmeGpu->programHandle_->impl_->splineAndSpreadKernelDual;
1231             }
1232             else
1233             {
1234                 kernelPtr = pmeGpu->programHandle_->impl_->splineAndSpreadKernelSingle;
1235             }
1236         }
1237     }
1238     return kernelPtr;
1239 }
1240
1241 void pme_gpu_spread(const PmeGpu*         pmeGpu,
1242                     GpuEventSynchronizer* xReadyOnDevice,
1243                     real**                h_grids,
1244                     bool                  computeSplines,
1245                     bool                  spreadCharges,
1246                     const real            lambda)
1247 {
1248     GMX_ASSERT(
1249             pmeGpu->common->ngrids == 1 || pmeGpu->common->ngrids == 2,
1250             "Only one (normal Coulomb PME) or two (FEP coulomb PME) PME grids can be used on GPU");
1251
1252     GMX_ASSERT(computeSplines || spreadCharges,
1253                "PME spline/spread kernel has invalid input (nothing to do)");
1254     auto* kernelParamsPtr = pmeGpu->kernelParams.get();
1255     GMX_ASSERT(kernelParamsPtr->atoms.nAtoms > 0, "No atom data in PME GPU spread");
1256
1257     const size_t blockSize = pmeGpu->programHandle_->impl_->spreadWorkGroupSize;
1258
1259     const int order = pmeGpu->common->pme_order;
1260     GMX_ASSERT(order == c_pmeGpuOrder, "Only PME order 4 is implemented");
1261     const bool writeGlobal = pmeGpu->settings.copyAllOutputs;
1262     const int  threadsPerAtom =
1263             (pmeGpu->settings.threadsPerAtom == ThreadsPerAtom::Order ? order : order * order);
1264     const bool recalculateSplines = pmeGpu->settings.recalculateSplines;
1265
1266     GMX_ASSERT(!GMX_GPU_OPENCL || pmeGpu->settings.threadsPerAtom == ThreadsPerAtom::OrderSquared,
1267                "Only 16 threads per atom supported in OpenCL");
1268     GMX_ASSERT(!GMX_GPU_OPENCL || !recalculateSplines,
1269                "Recalculating splines not supported in OpenCL");
1270
1271     const int atomsPerBlock = blockSize / threadsPerAtom;
1272
1273     // TODO: pick smaller block size in runtime if needed
1274     // (e.g. on 660 Ti where 50% occupancy is ~25% faster than 100% occupancy with RNAse (~17.8k atoms))
1275     // If doing so, change atomsPerBlock in the kernels as well.
1276     // TODO: test varying block sizes on modern arch-s as well
1277     // TODO: also consider using cudaFuncSetCacheConfig() for preferring shared memory on older architectures
1278     //(for spline data mostly)
1279     GMX_ASSERT(!(c_pmeAtomDataBlockSize % atomsPerBlock),
1280                "inconsistent atom data padding vs. spreading block size");
1281
1282     // Ensure that coordinates are ready on the device before launching spread;
1283     // only needed with CUDA on PP+PME ranks, not on separate PME ranks, in unit tests
1284     // nor in OpenCL as these cases use a single stream (hence xReadyOnDevice == nullptr).
1285     GMX_ASSERT(!GMX_GPU_CUDA || xReadyOnDevice != nullptr || pmeGpu->common->isRankPmeOnly
1286                        || pme_gpu_settings(pmeGpu).copyAllOutputs,
1287                "Need a valid coordinate synchronizer on PP+PME ranks with CUDA.");
1288
1289     if (xReadyOnDevice)
1290     {
1291         xReadyOnDevice->enqueueWaitEvent(pmeGpu->archSpecific->pmeStream_);
1292     }
1293
1294     const int blockCount = pmeGpu->nAtomsAlloc / atomsPerBlock;
1295     auto      dimGrid    = pmeGpuCreateGrid(pmeGpu, blockCount);
1296
1297     if (pmeGpu->common->ngrids == 1)
1298     {
1299         kernelParamsPtr->current.scale = 1.0;
1300     }
1301     else
1302     {
1303         kernelParamsPtr->current.scale = 1.0 - lambda;
1304     }
1305
1306     KernelLaunchConfig config;
1307     config.blockSize[0] = order;
1308     config.blockSize[1] = (pmeGpu->settings.threadsPerAtom == ThreadsPerAtom::Order ? 1 : order);
1309     config.blockSize[2] = atomsPerBlock;
1310     config.gridSize[0]  = dimGrid.first;
1311     config.gridSize[1]  = dimGrid.second;
1312
1313     PmeStage                           timingId;
1314     PmeGpuProgramImpl::PmeKernelHandle kernelPtr = nullptr;
1315     if (computeSplines)
1316     {
1317         if (spreadCharges)
1318         {
1319             timingId  = PmeStage::SplineAndSpread;
1320             kernelPtr = selectSplineAndSpreadKernelPtr(pmeGpu,
1321                                                        pmeGpu->settings.threadsPerAtom,
1322                                                        writeGlobal || (!recalculateSplines),
1323                                                        pmeGpu->common->ngrids);
1324         }
1325         else
1326         {
1327             timingId  = PmeStage::Spline;
1328             kernelPtr = selectSplineKernelPtr(pmeGpu,
1329                                               pmeGpu->settings.threadsPerAtom,
1330                                               writeGlobal || (!recalculateSplines),
1331                                               pmeGpu->common->ngrids);
1332         }
1333     }
1334     else
1335     {
1336         timingId  = PmeStage::Spread;
1337         kernelPtr = selectSpreadKernelPtr(pmeGpu,
1338                                           pmeGpu->settings.threadsPerAtom,
1339                                           writeGlobal || (!recalculateSplines),
1340                                           pmeGpu->common->ngrids);
1341     }
1342
1343
1344     pme_gpu_start_timing(pmeGpu, timingId);
1345     auto* timingEvent = pme_gpu_fetch_timing_event(pmeGpu, timingId);
1346 #if c_canEmbedBuffers
1347     const auto kernelArgs = prepareGpuKernelArguments(kernelPtr, config, kernelParamsPtr);
1348 #else
1349     const auto kernelArgs =
1350             prepareGpuKernelArguments(kernelPtr,
1351                                       config,
1352                                       kernelParamsPtr,
1353                                       &kernelParamsPtr->atoms.d_theta,
1354                                       &kernelParamsPtr->atoms.d_dtheta,
1355                                       &kernelParamsPtr->atoms.d_gridlineIndices,
1356                                       &kernelParamsPtr->grid.d_realGrid[FEP_STATE_A],
1357                                       &kernelParamsPtr->grid.d_realGrid[FEP_STATE_B],
1358                                       &kernelParamsPtr->grid.d_fractShiftsTable,
1359                                       &kernelParamsPtr->grid.d_gridlineIndicesTable,
1360                                       &kernelParamsPtr->atoms.d_coefficients[FEP_STATE_A],
1361                                       &kernelParamsPtr->atoms.d_coefficients[FEP_STATE_B],
1362                                       &kernelParamsPtr->atoms.d_coordinates);
1363 #endif
1364
1365     launchGpuKernel(
1366             kernelPtr, config, pmeGpu->archSpecific->pmeStream_, timingEvent, "PME spline/spread", kernelArgs);
1367     pme_gpu_stop_timing(pmeGpu, timingId);
1368
1369     const auto& settings    = pmeGpu->settings;
1370     const bool copyBackGrid = spreadCharges && (!settings.performGPUFFT || settings.copyAllOutputs);
1371     if (copyBackGrid)
1372     {
1373         for (int gridIndex = 0; gridIndex < pmeGpu->common->ngrids; gridIndex++)
1374         {
1375             float* h_grid = h_grids[gridIndex];
1376             pme_gpu_copy_output_spread_grid(pmeGpu, h_grid, gridIndex);
1377         }
1378     }
1379     const bool copyBackAtomData =
1380             computeSplines && (!settings.performGPUGather || settings.copyAllOutputs);
1381     if (copyBackAtomData)
1382     {
1383         pme_gpu_copy_output_spread_atom_data(pmeGpu);
1384     }
1385 }
1386
1387 void pme_gpu_solve(const PmeGpu* pmeGpu,
1388                    const int     gridIndex,
1389                    t_complex*    h_grid,
1390                    GridOrdering  gridOrdering,
1391                    bool          computeEnergyAndVirial)
1392 {
1393     GMX_ASSERT(
1394             pmeGpu->common->ngrids == 1 || pmeGpu->common->ngrids == 2,
1395             "Only one (normal Coulomb PME) or two (FEP coulomb PME) PME grids can be used on GPU");
1396     GMX_ASSERT(gridIndex < pmeGpu->common->ngrids,
1397                "Invalid combination of gridIndex and number of grids");
1398
1399     const auto& settings               = pmeGpu->settings;
1400     const bool  copyInputAndOutputGrid = !settings.performGPUFFT || settings.copyAllOutputs;
1401
1402     auto* kernelParamsPtr = pmeGpu->kernelParams.get();
1403
1404     float* h_gridFloat = reinterpret_cast<float*>(h_grid);
1405     if (copyInputAndOutputGrid)
1406     {
1407         copyToDeviceBuffer(&kernelParamsPtr->grid.d_fourierGrid[gridIndex],
1408                            h_gridFloat,
1409                            0,
1410                            pmeGpu->archSpecific->complexGridSize[gridIndex],
1411                            pmeGpu->archSpecific->pmeStream_,
1412                            pmeGpu->settings.transferKind,
1413                            nullptr);
1414     }
1415
1416     int majorDim = -1, middleDim = -1, minorDim = -1;
1417     switch (gridOrdering)
1418     {
1419         case GridOrdering::YZX:
1420             majorDim  = YY;
1421             middleDim = ZZ;
1422             minorDim  = XX;
1423             break;
1424
1425         case GridOrdering::XYZ:
1426             majorDim  = XX;
1427             middleDim = YY;
1428             minorDim  = ZZ;
1429             break;
1430
1431         default: GMX_ASSERT(false, "Implement grid ordering here and below for the kernel launch");
1432     }
1433
1434     const int maxBlockSize = pmeGpu->programHandle_->impl_->solveMaxWorkGroupSize;
1435
1436     const int gridLineSize      = pmeGpu->kernelParams->grid.complexGridSize[minorDim];
1437     const int gridLinesPerBlock = std::max(maxBlockSize / gridLineSize, 1);
1438     const int blocksPerGridLine = (gridLineSize + maxBlockSize - 1) / maxBlockSize;
1439     int       cellsPerBlock;
1440     if (blocksPerGridLine == 1)
1441     {
1442         cellsPerBlock = gridLineSize * gridLinesPerBlock;
1443     }
1444     else
1445     {
1446         cellsPerBlock = (gridLineSize + blocksPerGridLine - 1) / blocksPerGridLine;
1447     }
1448     const int warpSize  = pmeGpu->programHandle_->warpSize();
1449     const int blockSize = (cellsPerBlock + warpSize - 1) / warpSize * warpSize;
1450
1451     static_assert(!GMX_GPU_CUDA || c_solveMaxWarpsPerBlock / 2 >= 4,
1452                   "The CUDA solve energy kernels needs at least 4 warps. "
1453                   "Here we launch at least half of the max warps.");
1454
1455     KernelLaunchConfig config;
1456     config.blockSize[0] = blockSize;
1457     config.gridSize[0]  = blocksPerGridLine;
1458     // rounding up to full warps so that shuffle operations produce defined results
1459     config.gridSize[1] = (pmeGpu->kernelParams->grid.complexGridSize[middleDim] + gridLinesPerBlock - 1)
1460                          / gridLinesPerBlock;
1461     config.gridSize[2] = pmeGpu->kernelParams->grid.complexGridSize[majorDim];
1462
1463     PmeStage                           timingId  = PmeStage::Solve;
1464     PmeGpuProgramImpl::PmeKernelHandle kernelPtr = nullptr;
1465     if (gridOrdering == GridOrdering::YZX)
1466     {
1467         if (gridIndex == 0)
1468         {
1469             kernelPtr = computeEnergyAndVirial ? pmeGpu->programHandle_->impl_->solveYZXEnergyKernelA
1470                                                : pmeGpu->programHandle_->impl_->solveYZXKernelA;
1471         }
1472         else
1473         {
1474             kernelPtr = computeEnergyAndVirial ? pmeGpu->programHandle_->impl_->solveYZXEnergyKernelB
1475                                                : pmeGpu->programHandle_->impl_->solveYZXKernelB;
1476         }
1477     }
1478     else if (gridOrdering == GridOrdering::XYZ)
1479     {
1480         if (gridIndex == 0)
1481         {
1482             kernelPtr = computeEnergyAndVirial ? pmeGpu->programHandle_->impl_->solveXYZEnergyKernelA
1483                                                : pmeGpu->programHandle_->impl_->solveXYZKernelA;
1484         }
1485         else
1486         {
1487             kernelPtr = computeEnergyAndVirial ? pmeGpu->programHandle_->impl_->solveXYZEnergyKernelB
1488                                                : pmeGpu->programHandle_->impl_->solveXYZKernelB;
1489         }
1490     }
1491
1492     pme_gpu_start_timing(pmeGpu, timingId);
1493     auto* timingEvent = pme_gpu_fetch_timing_event(pmeGpu, timingId);
1494 #if c_canEmbedBuffers
1495     const auto kernelArgs = prepareGpuKernelArguments(kernelPtr, config, kernelParamsPtr);
1496 #else
1497     const auto kernelArgs =
1498             prepareGpuKernelArguments(kernelPtr,
1499                                       config,
1500                                       kernelParamsPtr,
1501                                       &kernelParamsPtr->grid.d_splineModuli[gridIndex],
1502                                       &kernelParamsPtr->constants.d_virialAndEnergy[gridIndex],
1503                                       &kernelParamsPtr->grid.d_fourierGrid[gridIndex]);
1504 #endif
1505     launchGpuKernel(kernelPtr, config, pmeGpu->archSpecific->pmeStream_, timingEvent, "PME solve", kernelArgs);
1506     pme_gpu_stop_timing(pmeGpu, timingId);
1507
1508     if (computeEnergyAndVirial)
1509     {
1510         copyFromDeviceBuffer(pmeGpu->staging.h_virialAndEnergy[gridIndex],
1511                              &kernelParamsPtr->constants.d_virialAndEnergy[gridIndex],
1512                              0,
1513                              c_virialAndEnergyCount,
1514                              pmeGpu->archSpecific->pmeStream_,
1515                              pmeGpu->settings.transferKind,
1516                              nullptr);
1517     }
1518
1519     if (copyInputAndOutputGrid)
1520     {
1521         copyFromDeviceBuffer(h_gridFloat,
1522                              &kernelParamsPtr->grid.d_fourierGrid[gridIndex],
1523                              0,
1524                              pmeGpu->archSpecific->complexGridSize[gridIndex],
1525                              pmeGpu->archSpecific->pmeStream_,
1526                              pmeGpu->settings.transferKind,
1527                              nullptr);
1528     }
1529 }
1530
1531 /*! \brief
1532  * Returns a pointer to appropriate gather kernel based on the inputvalues
1533  *
1534  * \param[in]  pmeGpu                   The PME GPU structure.
1535  * \param[in]  threadsPerAtom           Controls whether we should use order or order*order threads per atom
1536  * \param[in]  readSplinesFromGlobal    bool controlling if we should write spline data to global memory
1537  * \param[in]  numGrids                 Number of grids to use. numGrids == 2 if Coulomb is perturbed.
1538  *
1539  * \return Pointer to CUDA kernel
1540  */
1541 inline auto selectGatherKernelPtr(const PmeGpu*  pmeGpu,
1542                                   ThreadsPerAtom threadsPerAtom,
1543                                   bool           readSplinesFromGlobal,
1544                                   const int      numGrids)
1545
1546 {
1547     PmeGpuProgramImpl::PmeKernelHandle kernelPtr = nullptr;
1548
1549     if (readSplinesFromGlobal)
1550     {
1551         if (threadsPerAtom == ThreadsPerAtom::Order)
1552         {
1553             if (numGrids == 2)
1554             {
1555                 kernelPtr = pmeGpu->programHandle_->impl_->gatherKernelReadSplinesThPerAtom4Dual;
1556             }
1557             else
1558             {
1559                 kernelPtr = pmeGpu->programHandle_->impl_->gatherKernelReadSplinesThPerAtom4Single;
1560             }
1561         }
1562         else
1563         {
1564             if (numGrids == 2)
1565             {
1566                 kernelPtr = pmeGpu->programHandle_->impl_->gatherKernelReadSplinesDual;
1567             }
1568             else
1569             {
1570                 kernelPtr = pmeGpu->programHandle_->impl_->gatherKernelReadSplinesSingle;
1571             }
1572         }
1573     }
1574     else
1575     {
1576         if (threadsPerAtom == ThreadsPerAtom::Order)
1577         {
1578             if (numGrids == 2)
1579             {
1580                 kernelPtr = pmeGpu->programHandle_->impl_->gatherKernelThPerAtom4Dual;
1581             }
1582             else
1583             {
1584                 kernelPtr = pmeGpu->programHandle_->impl_->gatherKernelThPerAtom4Single;
1585             }
1586         }
1587         else
1588         {
1589             if (numGrids == 2)
1590             {
1591                 kernelPtr = pmeGpu->programHandle_->impl_->gatherKernelDual;
1592             }
1593             else
1594             {
1595                 kernelPtr = pmeGpu->programHandle_->impl_->gatherKernelSingle;
1596             }
1597         }
1598     }
1599     return kernelPtr;
1600 }
1601
1602 void pme_gpu_gather(PmeGpu* pmeGpu, real** h_grids, const float lambda)
1603 {
1604     GMX_ASSERT(
1605             pmeGpu->common->ngrids == 1 || pmeGpu->common->ngrids == 2,
1606             "Only one (normal Coulomb PME) or two (FEP coulomb PME) PME grids can be used on GPU");
1607
1608     const auto& settings = pmeGpu->settings;
1609
1610     if (!settings.performGPUFFT || settings.copyAllOutputs)
1611     {
1612         for (int gridIndex = 0; gridIndex < pmeGpu->common->ngrids; gridIndex++)
1613         {
1614             float* h_grid = const_cast<float*>(h_grids[gridIndex]);
1615             pme_gpu_copy_input_gather_grid(pmeGpu, h_grid, gridIndex);
1616         }
1617     }
1618
1619     if (settings.copyAllOutputs)
1620     {
1621         pme_gpu_copy_input_gather_atom_data(pmeGpu);
1622     }
1623
1624     /* Set if we have unit tests */
1625     const bool   readGlobal = pmeGpu->settings.copyAllOutputs;
1626     const size_t blockSize  = pmeGpu->programHandle_->impl_->gatherWorkGroupSize;
1627     const int    order      = pmeGpu->common->pme_order;
1628     GMX_ASSERT(order == c_pmeGpuOrder, "Only PME order 4 is implemented");
1629     const int threadsPerAtom =
1630             (pmeGpu->settings.threadsPerAtom == ThreadsPerAtom::Order ? order : order * order);
1631     const bool recalculateSplines = pmeGpu->settings.recalculateSplines;
1632
1633     GMX_ASSERT(!GMX_GPU_OPENCL || pmeGpu->settings.threadsPerAtom == ThreadsPerAtom::OrderSquared,
1634                "Only 16 threads per atom supported in OpenCL");
1635     GMX_ASSERT(!GMX_GPU_OPENCL || !recalculateSplines,
1636                "Recalculating splines not supported in OpenCL");
1637
1638     const int atomsPerBlock = blockSize / threadsPerAtom;
1639
1640     GMX_ASSERT(!(c_pmeAtomDataBlockSize % atomsPerBlock),
1641                "inconsistent atom data padding vs. gathering block size");
1642
1643     const int blockCount = pmeGpu->nAtomsAlloc / atomsPerBlock;
1644     auto      dimGrid    = pmeGpuCreateGrid(pmeGpu, blockCount);
1645
1646     KernelLaunchConfig config;
1647     config.blockSize[0] = order;
1648     config.blockSize[1] = (pmeGpu->settings.threadsPerAtom == ThreadsPerAtom::Order ? 1 : order);
1649     config.blockSize[2] = atomsPerBlock;
1650     config.gridSize[0]  = dimGrid.first;
1651     config.gridSize[1]  = dimGrid.second;
1652
1653     // TODO test different cache configs
1654
1655     PmeStage                           timingId = PmeStage::Gather;
1656     PmeGpuProgramImpl::PmeKernelHandle kernelPtr =
1657             selectGatherKernelPtr(pmeGpu,
1658                                   pmeGpu->settings.threadsPerAtom,
1659                                   readGlobal || (!recalculateSplines),
1660                                   pmeGpu->common->ngrids);
1661     // TODO design kernel selection getters and make PmeGpu a friend of PmeGpuProgramImpl
1662
1663     pme_gpu_start_timing(pmeGpu, timingId);
1664     auto* timingEvent     = pme_gpu_fetch_timing_event(pmeGpu, timingId);
1665     auto* kernelParamsPtr = pmeGpu->kernelParams.get();
1666     if (pmeGpu->common->ngrids == 1)
1667     {
1668         kernelParamsPtr->current.scale = 1.0;
1669     }
1670     else
1671     {
1672         kernelParamsPtr->current.scale = 1.0 - lambda;
1673     }
1674
1675 #if c_canEmbedBuffers
1676     const auto kernelArgs = prepareGpuKernelArguments(kernelPtr, config, kernelParamsPtr);
1677 #else
1678     const auto kernelArgs =
1679             prepareGpuKernelArguments(kernelPtr,
1680                                       config,
1681                                       kernelParamsPtr,
1682                                       &kernelParamsPtr->atoms.d_coefficients[FEP_STATE_A],
1683                                       &kernelParamsPtr->atoms.d_coefficients[FEP_STATE_B],
1684                                       &kernelParamsPtr->grid.d_realGrid[FEP_STATE_A],
1685                                       &kernelParamsPtr->grid.d_realGrid[FEP_STATE_B],
1686                                       &kernelParamsPtr->atoms.d_theta,
1687                                       &kernelParamsPtr->atoms.d_dtheta,
1688                                       &kernelParamsPtr->atoms.d_gridlineIndices,
1689                                       &kernelParamsPtr->atoms.d_forces);
1690 #endif
1691     launchGpuKernel(kernelPtr, config, pmeGpu->archSpecific->pmeStream_, timingEvent, "PME gather", kernelArgs);
1692     pme_gpu_stop_timing(pmeGpu, timingId);
1693
1694     if (pmeGpu->settings.useGpuForceReduction)
1695     {
1696         pmeGpu->archSpecific->pmeForcesReady.markEvent(pmeGpu->archSpecific->pmeStream_);
1697     }
1698     else
1699     {
1700         pme_gpu_copy_output_forces(pmeGpu);
1701     }
1702 }
1703
1704 DeviceBuffer<gmx::RVec> pme_gpu_get_kernelparam_forces(const PmeGpu* pmeGpu)
1705 {
1706     if (pmeGpu && pmeGpu->kernelParams)
1707     {
1708         return pmeGpu->kernelParams->atoms.d_forces;
1709     }
1710     else
1711     {
1712         return DeviceBuffer<gmx::RVec>{};
1713     }
1714 }
1715
1716 void pme_gpu_set_kernelparam_coordinates(const PmeGpu* pmeGpu, DeviceBuffer<gmx::RVec> d_x)
1717 {
1718     GMX_ASSERT(pmeGpu && pmeGpu->kernelParams,
1719                "PME GPU device buffer can not be set in non-GPU builds or before the GPU PME was "
1720                "initialized.");
1721
1722     GMX_ASSERT(checkDeviceBuffer(d_x, pmeGpu->kernelParams->atoms.nAtoms),
1723                "The device-side buffer can not be set.");
1724
1725     pmeGpu->kernelParams->atoms.d_coordinates = d_x;
1726 }
1727
1728 GpuEventSynchronizer* pme_gpu_get_forces_ready_synchronizer(const PmeGpu* pmeGpu)
1729 {
1730     if (pmeGpu && pmeGpu->kernelParams)
1731     {
1732         return &pmeGpu->archSpecific->pmeForcesReady;
1733     }
1734     else
1735     {
1736         return nullptr;
1737     }
1738 }