2 * This file is part of the GROMACS molecular simulation package.
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.
9 * GROMACS is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public License
11 * as published by the Free Software Foundation; either version 2.1
12 * of the License, or (at your option) any later version.
14 * GROMACS is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with GROMACS; if not, see
21 * http://www.gnu.org/licenses, or write to the Free Software Foundation,
22 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
24 * If you want to redistribute modifications to GROMACS, please
25 * consider that scientific software is very special. Version
26 * control is crucial - bugs must be traceable. We will be happy to
27 * consider code for inclusion in the official distribution, but
28 * derived work must not be called official GROMACS. Details are found
29 * in the README & COPYING files - if they are missing, get the
30 * official version at http://www.gromacs.org.
32 * To help us fund GROMACS development, we humbly ask that you cite
33 * the research papers on the package. Check out http://www.gromacs.org.
37 * \brief Implements PME GPU Fourier grid solving in CUDA.
39 * \author Aleksei Iupinov <a.yupinov@gmail.com>
44 #include "gromacs/gpu_utils/cuda_arch_utils.cuh"
45 #include "gromacs/gpu_utils/cudautils.cuh"
46 #include "gromacs/utility/exceptions.h"
47 #include "gromacs/utility/gmxassert.h"
50 #include "pme-timings.cuh"
52 //! Solving kernel max block width in warps picked among powers of 2 (2, 4, 8, 16) for max. occupancy and min. runtime
53 //! (560Ti (CC2.1), 660Ti (CC3.0) and 750 (CC5.0)))
54 constexpr int c_solveMaxWarpsPerBlock = 8;
55 //! Solving kernel max block size in threads
56 constexpr int c_solveMaxThreadsPerBlock = (c_solveMaxWarpsPerBlock * warp_size);
59 * PME complex grid solver kernel function.
61 * \tparam[in] gridOrdering Specifies the dimension ordering of the complex grid.
62 * \tparam[in] computeEnergyAndVirial Tells if the reciprocal energy and virial should be computed.
63 * \param[in] kernelParams Input PME CUDA data in constant memory.
66 GridOrdering gridOrdering,
67 bool computeEnergyAndVirial
69 __launch_bounds__(c_solveMaxThreadsPerBlock)
70 __global__ void pme_solve_kernel(const struct PmeGpuCudaKernelParams kernelParams)
72 /* This kernel supports 2 different grid dimension orderings: YZX and XYZ */
73 int majorDim, middleDim, minorDim;
76 case GridOrdering::YZX:
82 case GridOrdering::XYZ:
92 /* Global memory pointers */
93 const float * __restrict__ gm_splineValueMajor = kernelParams.grid.d_splineModuli + kernelParams.grid.splineValuesOffset[majorDim];
94 const float * __restrict__ gm_splineValueMiddle = kernelParams.grid.d_splineModuli + kernelParams.grid.splineValuesOffset[middleDim];
95 const float * __restrict__ gm_splineValueMinor = kernelParams.grid.d_splineModuli + kernelParams.grid.splineValuesOffset[minorDim];
96 float * __restrict__ gm_virialAndEnergy = kernelParams.constants.d_virialAndEnergy;
97 float2 * __restrict__ gm_grid = (float2 *)kernelParams.grid.d_fourierGrid;
99 /* Various grid sizes and indices */
100 const int localOffsetMinor = 0, localOffsetMajor = 0, localOffsetMiddle = 0; //unused
101 const int localSizeMinor = kernelParams.grid.complexGridSizePadded[minorDim];
102 const int localSizeMiddle = kernelParams.grid.complexGridSizePadded[middleDim];
103 const int localCountMiddle = kernelParams.grid.complexGridSize[middleDim];
104 const int localCountMinor = kernelParams.grid.complexGridSize[minorDim];
105 const int nMajor = kernelParams.grid.realGridSize[majorDim];
106 const int nMiddle = kernelParams.grid.realGridSize[middleDim];
107 const int nMinor = kernelParams.grid.realGridSize[minorDim];
108 const int maxkMajor = (nMajor + 1) / 2; // X or Y
109 const int maxkMiddle = (nMiddle + 1) / 2; // Y OR Z => only check for !YZX
110 const int maxkMinor = (nMinor + 1) / 2; // Z or X => only check for YZX
112 /* Each thread works on one cell of the Fourier space complex 3D grid (gm_grid).
113 * Each block handles up to c_solveMaxThreadsPerBlock cells -
114 * depending on the grid contiguous dimension size,
115 * that can range from a part of a single gridline to several complete gridlines.
117 const int threadLocalId = threadIdx.x;
118 const int gridLineSize = localCountMinor;
119 const int gridLineIndex = threadLocalId / gridLineSize;
120 const int gridLineCellIndex = threadLocalId - gridLineSize * gridLineIndex;
121 const int gridLinesPerBlock = blockDim.x / gridLineSize;
122 const int activeWarps = (blockDim.x / warp_size);
123 const int indexMinor = blockIdx.x * blockDim.x + gridLineCellIndex;
124 const int indexMiddle = blockIdx.y * gridLinesPerBlock + gridLineIndex;
125 const int indexMajor = blockIdx.z;
127 /* Optional outputs */
136 assert(indexMajor < kernelParams.grid.complexGridSize[majorDim]);
137 if ((indexMiddle < localCountMiddle) & (indexMinor < localCountMinor) & (gridLineIndex < gridLinesPerBlock))
139 /* The offset should be equal to the global thread index for coalesced access */
140 const int gridIndex = (indexMajor * localSizeMiddle + indexMiddle) * localSizeMinor + indexMinor;
141 float2 * __restrict__ gm_gridCell = gm_grid + gridIndex;
143 const int kMajor = indexMajor + localOffsetMajor;
144 /* Checking either X in XYZ, or Y in YZX cases */
145 const float mMajor = (kMajor < maxkMajor) ? kMajor : (kMajor - nMajor);
147 const int kMiddle = indexMiddle + localOffsetMiddle;
148 float mMiddle = kMiddle;
149 /* Checking Y in XYZ case */
150 if (gridOrdering == GridOrdering::XYZ)
152 mMiddle = (kMiddle < maxkMiddle) ? kMiddle : (kMiddle - nMiddle);
154 const int kMinor = localOffsetMinor + indexMinor;
155 float mMinor = kMinor;
156 /* Checking X in YZX case */
157 if (gridOrdering == GridOrdering::YZX)
159 mMinor = (kMinor < maxkMinor) ? kMinor : (kMinor - nMinor);
161 /* We should skip the k-space point (0,0,0) */
162 const bool notZeroPoint = (kMinor > 0) | (kMajor > 0) | (kMiddle > 0);
165 switch (gridOrdering)
167 case GridOrdering::YZX:
173 case GridOrdering::XYZ:
183 /* 0.5 correction factor for the first and last components of a Z dimension */
184 float corner_fac = 1.0f;
185 switch (gridOrdering)
187 case GridOrdering::YZX:
188 if ((kMiddle == 0) | (kMiddle == maxkMiddle))
194 case GridOrdering::XYZ:
195 if ((kMinor == 0) | (kMinor == maxkMinor))
207 const float mhxk = mX * kernelParams.current.recipBox[XX][XX];
208 const float mhyk = mX * kernelParams.current.recipBox[XX][YY] + mY * kernelParams.current.recipBox[YY][YY];
209 const float mhzk = mX * kernelParams.current.recipBox[XX][ZZ] + mY * kernelParams.current.recipBox[YY][ZZ] + mZ * kernelParams.current.recipBox[ZZ][ZZ];
211 const float m2k = mhxk * mhxk + mhyk * mhyk + mhzk * mhzk;
213 //TODO: use LDG/textures for gm_splineValue
214 float denom = m2k * float(M_PI) * kernelParams.current.boxVolume * gm_splineValueMajor[kMajor] * gm_splineValueMiddle[kMiddle] * gm_splineValueMinor[kMinor];
215 assert(isfinite(denom));
216 assert(denom != 0.0f);
217 const float tmp1 = expf(-kernelParams.grid.ewaldFactor * m2k);
218 const float etermk = kernelParams.constants.elFactor * tmp1 / denom;
220 float2 gridValue = *gm_gridCell;
221 const float2 oldGridValue = gridValue;
222 gridValue.x *= etermk;
223 gridValue.y *= etermk;
224 *gm_gridCell = gridValue;
226 if (computeEnergyAndVirial)
228 const float tmp1k = 2.0f * (gridValue.x * oldGridValue.x + gridValue.y * oldGridValue.y);
230 float vfactor = (kernelParams.grid.ewaldFactor + 1.0f / m2k) * 2.0f;
231 float ets2 = corner_fac * tmp1k;
234 float ets2vf = ets2 * vfactor;
236 virxx = ets2vf * mhxk * mhxk - ets2;
237 virxy = ets2vf * mhxk * mhyk;
238 virxz = ets2vf * mhxk * mhzk;
239 viryy = ets2vf * mhyk * mhyk - ets2;
240 viryz = ets2vf * mhyk * mhzk;
241 virzz = ets2vf * mhzk * mhzk - ets2;
246 /* Optional energy/virial reduction */
247 if (computeEnergyAndVirial)
249 #if (GMX_PTX_ARCH >= 300)
250 /* A tricky shuffle reduction inspired by reduce_force_j_warp_shfl.
251 * The idea is to reduce 7 energy/virial components into a single variable (aligned by 8).
252 * We will reduce everything into virxx.
255 /* We can only reduce warp-wise */
256 const int width = warp_size;
257 const unsigned int activeMask = c_fullWarpMask;
259 /* Making pair sums */
260 virxx += gmx_shfl_down_sync(activeMask, virxx, 1, width);
261 viryy += gmx_shfl_up_sync (activeMask, viryy, 1, width);
262 virzz += gmx_shfl_down_sync(activeMask, virzz, 1, width);
263 virxy += gmx_shfl_up_sync (activeMask, virxy, 1, width);
264 virxz += gmx_shfl_down_sync(activeMask, virxz, 1, width);
265 viryz += gmx_shfl_up_sync (activeMask, viryz, 1, width);
266 energy += gmx_shfl_down_sync(activeMask, energy, 1, width);
267 if (threadLocalId & 1)
269 virxx = viryy; // virxx now holds virxx and viryy pair sums
270 virzz = virxy; // virzz now holds virzz and virxy pair sums
271 virxz = viryz; // virxz now holds virxz and viryz pair sums
274 /* Making quad sums */
275 virxx += gmx_shfl_down_sync(activeMask, virxx, 2, width);
276 virzz += gmx_shfl_up_sync (activeMask, virzz, 2, width);
277 virxz += gmx_shfl_down_sync(activeMask, virxz, 2, width);
278 energy += gmx_shfl_up_sync (activeMask, energy, 2, width);
279 if (threadLocalId & 2)
281 virxx = virzz; // virxx now holds quad sums of virxx, virxy, virzz and virxy
282 virxz = energy; // virxz now holds quad sums of virxz, viryz, energy and unused paddings
285 /* Making octet sums */
286 virxx += gmx_shfl_down_sync(activeMask, virxx, 4, width);
287 virxz += gmx_shfl_up_sync (activeMask, virxz, 4, width);
288 if (threadLocalId & 4)
290 virxx = virxz; // virxx now holds all 7 components' octet sums + unused paddings
293 /* We only need to reduce virxx now */
295 for (int delta = 8; delta < width; delta <<= 1)
297 virxx += gmx_shfl_down_sync(activeMask, virxx, delta, width);
299 /* Now first 7 threads of each warp have the full output contributions in virxx */
301 const int componentIndex = threadLocalId & (warp_size - 1);
302 const bool validComponentIndex = (componentIndex < c_virialAndEnergyCount);
303 /* Reduce 7 outputs per warp in the shared memory */
304 const int stride = 8; // this is c_virialAndEnergyCount==7 rounded up to power of 2 for convenience, hence the assert
305 assert(c_virialAndEnergyCount == 7);
306 const int reductionBufferSize = (c_solveMaxThreadsPerBlock / warp_size) * stride;
307 __shared__ float sm_virialAndEnergy[reductionBufferSize];
309 if (validComponentIndex)
311 const int warpIndex = threadLocalId / warp_size;
312 sm_virialAndEnergy[warpIndex * stride + componentIndex] = virxx;
316 /* Reduce to the single warp size */
317 const int targetIndex = threadLocalId;
319 for (int reductionStride = reductionBufferSize >> 1; reductionStride >= warp_size; reductionStride >>= 1)
321 const int sourceIndex = targetIndex + reductionStride;
322 if ((targetIndex < reductionStride) & (sourceIndex < activeWarps * stride))
324 // TODO: the second conditional is only needed on first iteration, actually - see if compiler eliminates it!
325 sm_virialAndEnergy[targetIndex] += sm_virialAndEnergy[sourceIndex];
330 /* Now use shuffle again */
331 if (threadLocalId < warp_size)
333 float output = sm_virialAndEnergy[threadLocalId];
335 for (int delta = stride; delta < warp_size; delta <<= 1)
337 output += gmx_shfl_down_sync(activeMask, output, delta, warp_size);
340 if (validComponentIndex)
342 assert(isfinite(output));
343 atomicAdd(gm_virialAndEnergy + componentIndex, output);
347 /* Shared memory reduction with atomics for compute capability < 3.0.
348 * Each component is first reduced into warp_size positions in the shared memory;
349 * Then first c_virialAndEnergyCount warps reduce everything further and add to the global memory.
350 * This can likely be improved, but is anyway faster than the previous straightforward reduction,
351 * which was using too much shared memory (for storing all 7 floats on each thread).
352 * [48KB (shared mem limit per SM on CC2.x) / sizeof(float) (4) / c_solveMaxThreadsPerBlock (256) / c_virialAndEnergyCount (7) ==
353 * 6 blocks per SM instead of 16 which is maximum on CC2.x].
356 const int lane = threadLocalId & (warp_size - 1);
357 const int warpIndex = threadLocalId / warp_size;
358 const bool firstWarp = (warpIndex == 0);
359 __shared__ float sm_virialAndEnergy[c_virialAndEnergyCount * warp_size];
362 sm_virialAndEnergy[0 * warp_size + lane] = virxx;
363 sm_virialAndEnergy[1 * warp_size + lane] = viryy;
364 sm_virialAndEnergy[2 * warp_size + lane] = virzz;
365 sm_virialAndEnergy[3 * warp_size + lane] = virxy;
366 sm_virialAndEnergy[4 * warp_size + lane] = virxz;
367 sm_virialAndEnergy[5 * warp_size + lane] = viryz;
368 sm_virialAndEnergy[6 * warp_size + lane] = energy;
373 atomicAdd(sm_virialAndEnergy + 0 * warp_size + lane, virxx);
374 atomicAdd(sm_virialAndEnergy + 1 * warp_size + lane, viryy);
375 atomicAdd(sm_virialAndEnergy + 2 * warp_size + lane, virzz);
376 atomicAdd(sm_virialAndEnergy + 3 * warp_size + lane, virxy);
377 atomicAdd(sm_virialAndEnergy + 4 * warp_size + lane, virxz);
378 atomicAdd(sm_virialAndEnergy + 5 * warp_size + lane, viryz);
379 atomicAdd(sm_virialAndEnergy + 6 * warp_size + lane, energy);
383 GMX_UNUSED_VALUE(activeWarps);
384 assert(activeWarps >= c_virialAndEnergyCount); // we need to cover all components, or have multiple iterations otherwise
385 const int componentIndex = warpIndex;
386 if (componentIndex < c_virialAndEnergyCount)
388 const int targetIndex = threadLocalId;
390 for (int reductionStride = warp_size >> 1; reductionStride >= 1; reductionStride >>= 1)
392 if (lane < reductionStride)
394 sm_virialAndEnergy[targetIndex] += sm_virialAndEnergy[targetIndex + reductionStride];
399 atomicAdd(gm_virialAndEnergy + componentIndex, sm_virialAndEnergy[targetIndex]);
406 void pme_gpu_solve(const PmeGpu *pmeGpu, t_complex *h_grid,
407 GridOrdering gridOrdering, bool computeEnergyAndVirial)
409 const bool copyInputAndOutputGrid = pme_gpu_is_testing(pmeGpu) || !pme_gpu_performs_FFT(pmeGpu);
411 cudaStream_t stream = pmeGpu->archSpecific->pmeStream;
412 const auto *kernelParamsPtr = pmeGpu->kernelParams.get();
414 if (copyInputAndOutputGrid)
416 cu_copy_H2D(kernelParamsPtr->grid.d_fourierGrid, h_grid, pmeGpu->archSpecific->complexGridSize * sizeof(float),
417 pmeGpu->settings.transferKind, stream);
420 int majorDim = -1, middleDim = -1, minorDim = -1;
421 switch (gridOrdering)
423 case GridOrdering::YZX:
429 case GridOrdering::XYZ:
436 GMX_ASSERT(false, "Implement grid ordering here and below for the kernel launch");
439 const int maxBlockSize = c_solveMaxThreadsPerBlock;
440 const int gridLineSize = pmeGpu->kernelParams->grid.complexGridSize[minorDim];
441 const int gridLinesPerBlock = std::max(maxBlockSize / gridLineSize, 1);
442 const int blocksPerGridLine = (gridLineSize + maxBlockSize - 1) / maxBlockSize;
443 const int cellsPerBlock = gridLineSize * gridLinesPerBlock;
444 const int blockSize = (cellsPerBlock + warp_size - 1) / warp_size * warp_size;
445 // rounding up to full warps so that shuffle operations produce defined results
446 dim3 threads(blockSize);
447 dim3 blocks(blocksPerGridLine,
448 (pmeGpu->kernelParams->grid.complexGridSize[middleDim] + gridLinesPerBlock - 1) / gridLinesPerBlock,
449 pmeGpu->kernelParams->grid.complexGridSize[majorDim]);
451 pme_gpu_start_timing(pmeGpu, gtPME_SOLVE);
452 if (gridOrdering == GridOrdering::YZX)
454 if (computeEnergyAndVirial)
456 pme_solve_kernel<GridOrdering::YZX, true> <<< blocks, threads, 0, stream>>> (*kernelParamsPtr);
460 pme_solve_kernel<GridOrdering::YZX, false> <<< blocks, threads, 0, stream>>> (*kernelParamsPtr);
463 else if (gridOrdering == GridOrdering::XYZ)
465 if (computeEnergyAndVirial)
467 pme_solve_kernel<GridOrdering::XYZ, true> <<< blocks, threads, 0, stream>>> (*kernelParamsPtr);
471 pme_solve_kernel<GridOrdering::XYZ, false> <<< blocks, threads, 0, stream>>> (*kernelParamsPtr);
474 CU_LAUNCH_ERR("pme_solve_kernel");
475 pme_gpu_stop_timing(pmeGpu, gtPME_SOLVE);
477 if (computeEnergyAndVirial)
479 cu_copy_D2H(pmeGpu->staging.h_virialAndEnergy, kernelParamsPtr->constants.d_virialAndEnergy,
480 c_virialAndEnergyCount * sizeof(float), pmeGpu->settings.transferKind, stream);
483 if (copyInputAndOutputGrid)
485 cu_copy_D2H(h_grid, kernelParamsPtr->grid.d_fourierGrid, pmeGpu->archSpecific->complexGridSize * sizeof(float),
486 pmeGpu->settings.transferKind, stream);