Removed cu_realloc_buffered() in favor of reallocateDeviceBuffer()
[alexxy/gromacs.git] / src / gromacs / ewald / pme.cuh
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 2016,2017,2018, by the GROMACS development team, led by
5  * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
6  * and including many others, as listed in the AUTHORS file in the
7  * top-level source directory and at http://www.gromacs.org.
8  *
9  * GROMACS is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public License
11  * as published by the Free Software Foundation; either version 2.1
12  * of the License, or (at your option) any later version.
13  *
14  * GROMACS is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with GROMACS; if not, see
21  * http://www.gnu.org/licenses, or write to the Free Software Foundation,
22  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.
23  *
24  * If you want to redistribute modifications to GROMACS, please
25  * consider that scientific software is very special. Version
26  * control is crucial - bugs must be traceable. We will be happy to
27  * consider code for inclusion in the official distribution, but
28  * derived work must not be called official GROMACS. Details are found
29  * in the README & COPYING files - if they are missing, get the
30  * official version at http://www.gromacs.org.
31  *
32  * To help us fund GROMACS development, we humbly ask that you cite
33  * the research papers on the package. Check out http://www.gromacs.org.
34  */
35
36 /*! \internal \file
37  * \brief This file defines the PME CUDA-specific data structure,
38  * various compile-time constants shared among the PME CUDA kernels,
39  * and also names some PME CUDA memory management routines.
40  * TODO: consider changing defines into variables where possible; have inline getters.
41  *
42  * \author Aleksei Iupinov <a.yupinov@gmail.com>
43  */
44
45 #ifndef GMX_EWALD_PME_CUH
46 #define GMX_EWALD_PME_CUH
47
48 #include <cassert>
49
50 #include <array>
51 #include <set>
52
53 #include "gromacs/gpu_utils/cuda_arch_utils.cuh" // for warp_size
54
55 #include "pme-gpu-internal.h"                    // for the general PME GPU behaviour defines
56 #include "pme-timings.cuh"
57
58 class GpuParallel3dFft;
59
60 /* Some defines for PME behaviour follow */
61
62 /*
63     Here is a current memory layout for the theta/dtheta B-spline float parameter arrays.
64     This is the data in global memory used both by spreading and gathering kernels (with same scheduling).
65     This example has PME order 4 and 2 particles per warp/data chunk.
66     Each particle has 16 threads assigned to it, each thread works on 4 non-sequential global grid contributions.
67
68     ----------------------------------------------------------------------------
69     particles 0, 1                                        | particles 2, 3     | ...
70     ----------------------------------------------------------------------------
71     order index 0           | index 1 | index 2 | index 3 | order index 0 .....
72     ----------------------------------------------------------------------------
73     tx0 tx1 ty0 ty1 tz0 tz1 | ..........
74     ----------------------------------------------------------------------------
75
76     Each data chunk for a single warp is 24 floats. This goes both for theta and dtheta.
77     24 = 2 particles per warp * order 4 * 3 dimensions. 48 floats (1.5 warp size) per warp in total.
78     I have also tried intertwining theta and theta in a single array (they are used in pairs in gathering stage anyway)
79     and it didn't seem to make a performance difference.
80
81     The spline indexing is isolated in the 2 inline functions below:
82     getSplineParamIndexBase() return a base shared memory index corresponding to the atom in the block;
83     getSplineParamIndex() consumes its results and adds offsets for dimension and spline value index.
84
85     The corresponding defines follow.
86  */
87
88 /*! \brief
89  * The number of GPU threads used for computing spread/gather contributions of a single atom as function of the PME order.
90  * The assumption is currently that any thread processes only a single atom's contributions.
91  */
92 #define PME_SPREADGATHER_THREADS_PER_ATOM (order * order)
93
94 /*! \brief
95  * The number of atoms processed by a single warp in spread/gather.
96  * This macro depends on the templated order parameter (2 atoms per warp for order 4).
97  * It is mostly used for spline data layout tweaked for coalesced access.
98  */
99 #define PME_SPREADGATHER_ATOMS_PER_WARP (warp_size / PME_SPREADGATHER_THREADS_PER_ATOM)
100
101 /*! \brief
102  * Atom data alignment (in terms of number of atoms).
103  * If the GPU atom data buffers are padded (c_usePadding == true),
104  * Then the numbers of atoms which would fit in the padded GPU buffers has to be divisible by this.
105  * The literal number (16) expresses maximum spread/gather block width in warps.
106  * Accordingly, spread and gather block widths in warps should be divisors of this
107  * (e.g. in the pme-spread.cu: constexpr int c_spreadMaxThreadsPerBlock = 8 * warp_size;).
108  * There are debug asserts for this divisibility.
109  */
110 #define PME_ATOM_DATA_ALIGNMENT (16 * PME_SPREADGATHER_ATOMS_PER_WARP)
111
112 /*! \internal \brief
113  * Gets a base of the unique index to an element in a spline parameter buffer (theta/dtheta),
114  * which is laid out for GPU spread/gather kernels. The base only corresponds to the atom index within the execution block.
115  * Feed the result into getSplineParamIndex() to get a full index.
116  * TODO: it's likely that both parameters can be just replaced with a single atom index, as they are derived from it.
117  * Do that, verifying that the generated code is not bloated, and/or revise the spline indexing scheme.
118  * Removing warp dependency would also be nice (and would probably coincide with removing PME_SPREADGATHER_ATOMS_PER_WARP).
119  *
120  * \tparam    order            PME order
121  * \param[in] warpIndex        Warp index wrt the block.
122  * \param[in] atomWarpIndex    Atom index wrt the warp (from 0 to PME_SPREADGATHER_ATOMS_PER_WARP - 1).
123  *
124  * \returns Index into theta or dtheta array using GPU layout.
125  */
126 template <int order>
127 int __host__ __device__ __forceinline__ getSplineParamIndexBase(int warpIndex, int atomWarpIndex)
128 {
129     assert((atomWarpIndex >= 0) && (atomWarpIndex < PME_SPREADGATHER_ATOMS_PER_WARP));
130     const int dimIndex    = 0;
131     const int splineIndex = 0;
132     // The zeroes are here to preserve the full index formula for reference
133     return (((splineIndex + order * warpIndex) * DIM + dimIndex) * PME_SPREADGATHER_ATOMS_PER_WARP + atomWarpIndex);
134 }
135
136 /*! \internal \brief
137  * Gets a unique index to an element in a spline parameter buffer (theta/dtheta),
138  * which is laid out for GPU spread/gather kernels. The index is wrt to the execution block,
139  * in range(0, atomsPerBlock * order * DIM).
140  * This function consumes result of getSplineParamIndexBase() and adjusts it for \p dimIndex and \p splineIndex.
141  *
142  * \tparam    order            PME order
143  * \param[in] paramIndexBase   Must be result of getSplineParamIndexBase().
144  * \param[in] dimIndex         Dimension index (from 0 to 2)
145  * \param[in] splineIndex      Spline contribution index (from 0 to \p order - 1)
146  *
147  * \returns Index into theta or dtheta array using GPU layout.
148  */
149 template <int order>
150 int __host__ __device__ __forceinline__ getSplineParamIndex(int paramIndexBase, int dimIndex, int splineIndex)
151 {
152     assert((dimIndex >= XX) && (dimIndex < DIM));
153     assert((splineIndex >= 0) && (splineIndex < order));
154     return (paramIndexBase + (splineIndex * DIM + dimIndex) * PME_SPREADGATHER_ATOMS_PER_WARP);
155 }
156
157 /*! \brief \internal
158  * An inline CUDA function for checking the global atom data indices against the atom data array sizes.
159  *
160  * \param[in] atomDataIndexGlobal  The atom data index.
161  * \param[in] nAtomData            The atom data array element count.
162  * \returns                        Non-0 if index is within bounds (or PME data padding is enabled), 0 otherwise.
163  *
164  * This is called from the spline_and_spread and gather PME kernels.
165  * The goal is to isolate the global range checks, and allow avoiding them with c_usePadding enabled.
166  */
167 int __device__ __forceinline__ pme_gpu_check_atom_data_index(const int atomDataIndex, const int nAtomData)
168 {
169     return c_usePadding ? 1 : (atomDataIndex < nAtomData);
170 }
171
172 /*! \brief \internal
173  * An inline CUDA function for skipping the zero-charge atoms.
174  *
175  * \returns                        Non-0 if atom should be processed, 0 otherwise.
176  * \param[in] coefficient          The atom charge.
177  *
178  * This is called from the spline_and_spread and gather PME kernels.
179  */
180 int __device__ __forceinline__ pme_gpu_check_atom_charge(const float coefficient)
181 {
182     assert(isfinite(coefficient));
183     return c_skipNeutralAtoms ? (coefficient != 0.0f) : 1;
184 }
185
186 /*! \brief \internal
187  * Given possibly large \p blockCount, returns a compact 1D or 2D grid for kernel scheduling,
188  * to minimize number of unused blocks.
189  */
190 template <typename PmeGpu>
191 dim3 __host__ inline pmeGpuCreateGrid(const PmeGpu *pmeGpu, int blockCount)
192 {
193     // How many maximum widths in X do we need (hopefully just one)
194     const int minRowCount = (blockCount + pmeGpu->maxGridWidthX - 1) / pmeGpu->maxGridWidthX;
195     // Trying to make things even
196     const int colCount = (blockCount + minRowCount - 1) / minRowCount;
197     GMX_ASSERT((colCount * minRowCount - blockCount) >= 0, "pmeGpuCreateGrid: totally wrong");
198     GMX_ASSERT((colCount * minRowCount - blockCount) < minRowCount, "pmeGpuCreateGrid: excessive blocks");
199     return dim3(colCount, minRowCount);
200 }
201
202 /*! \brief \internal
203  * The main PME CUDA-specific host data structure, included in the PME GPU structure by the archSpecific pointer.
204  */
205 struct PmeGpuCuda
206 {
207     /*! \brief The CUDA stream where everything related to the PME happens. */
208     cudaStream_t pmeStream;
209
210     /* Synchronization events */
211     /*! \brief Triggered after the grid has been copied to the host (after the spreading stage). */
212     cudaEvent_t syncSpreadGridD2H;
213
214     // TODO: consider moving some things below into the non-CUDA struct.
215
216     /* Settings which are set at the start of the run */
217     /*! \brief A boolean which tells whether the complex and real grids for cuFFT are different or same. Currenty true. */
218     bool performOutOfPlaceFFT;
219     /*! \brief A boolean which tells if the CUDA timing events are enabled.
220      *  False by default, can be enabled by setting the environment variable GMX_ENABLE_GPU_TIMING.
221      *  Note: will not be reliable when multiple GPU tasks are running concurrently on the same device context,
222      * as CUDA events on multiple streams are untrustworthy.
223      */
224     bool                                             useTiming;
225
226     std::vector<std::unique_ptr<GpuParallel3dFft > > fftSetup;
227
228     std::array<GpuRegionTimer, gtPME_EVENT_COUNT>    timingEvents;
229
230     std::set<size_t>                                 activeTimers; // indices into timingEvents
231
232     /* GPU arrays element counts (not the arrays sizes in bytes!).
233      * They might be larger than the actual meaningful data sizes.
234      * These are paired: the actual element count + the maximum element count that can fit in the current allocated memory.
235      * These integer pairs are mostly meaningful for the reallocateDeviceBuffer calls.
236      * As such, if DeviceBuffer is refactored into a class, they can be freely changed, too.
237      * The only exceptions are realGridSize and complexGridSize which are also used for grid clearing/copying.
238      * TODO: these should live in a clean buffered container type, and be refactored in the NB/cudautils as well.
239      */
240     /*! \brief The kernelParams.atoms.coordinates float element count (actual)*/
241     int coordinatesSize;
242     /*! \brief The kernelParams.atoms.coordinates float element count (reserved) */
243     int coordinatesSizeAlloc;
244     /*! \brief The kernelParams.atoms.forces float element count (actual) */
245     int forcesSize;
246     /*! \brief The kernelParams.atoms.forces float element count (reserved) */
247     int forcesSizeAlloc;
248     /*! \brief The kernelParams.atoms.gridlineIndices int element count (actual) */
249     int gridlineIndicesSize;
250     /*! \brief The kernelParams.atoms.gridlineIndices int element count (reserved) */
251     int gridlineIndicesSizeAlloc;
252     /*! \brief Both the kernelParams.atoms.theta and kernelParams.atoms.dtheta float element count (actual) */
253     int splineDataSize;
254     /*! \brief Both the kernelParams.atoms.theta and kernelParams.atoms.dtheta float element count (reserved) */
255     int splineDataSizeAlloc;
256     /*! \brief The kernelParams.atoms.coefficients float element count (actual) */
257     int coefficientsSize;
258     /*! \brief The kernelParams.atoms.coefficients float element count (reserved) */
259     int coefficientsSizeAlloc;
260     /*! \brief The kernelParams.grid.splineValuesArray float element count (actual) */
261     int splineValuesSize;
262     /*! \brief The kernelParams.grid.splineValuesArray float element count (reserved) */
263     int splineValuesSizeAlloc;
264     /*! \brief The kernelParams.grid.realGrid float element count (actual) */
265     int realGridSize;
266     /*! \brief The kernelParams.grid.realGrid float element count (reserved) */
267     int realGridSizeAlloc;
268     /*! \brief The kernelParams.grid.fourierGrid float (not float2!) element count (actual) */
269     int complexGridSize;
270     /*! \brief The kernelParams.grid.fourierGrid float (not float2!) element count (reserved) */
271     int complexGridSizeAlloc;
272 };
273
274
275 /*! \brief \internal
276  * A single structure encompassing all the PME data used in CUDA kernels.
277  * This inherits from PmeGpuKernelParamsBase and adds a couple cudaTextureObject_t handles,
278  * which we would like to avoid in plain C++.
279  */
280 struct PmeGpuCudaKernelParams : PmeGpuKernelParamsBase
281 {
282     /* These are CUDA texture objects, related to the grid size. */
283     /*! \brief CUDA texture object for accessing grid.d_fractShiftsTable */
284     cudaTextureObject_t fractShiftsTableTexture;
285     /*! \brief CUDA texture object for accessing grid.d_gridlineIndicesTable */
286     cudaTextureObject_t gridlineIndicesTableTexture;
287 };
288
289 #endif