2 * This file is part of the GROMACS molecular simulation package.
4 * Copyright (c) 2019, 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 GPU halo exchange using CUDA.
40 * \author Alan Gray <alang@nvidia.com>
42 * \ingroup module_domdec
46 #include "gpuhaloexchange_impl.cuh"
53 #include "gromacs/domdec/domdec.h"
54 #include "gromacs/domdec/domdec_struct.h"
55 #include "gromacs/domdec/gpuhaloexchange.h"
56 #include "gromacs/gpu_utils/cudautils.cuh"
57 #include "gromacs/gpu_utils/devicebuffer.h"
58 #include "gromacs/gpu_utils/gpueventsynchronizer.cuh"
59 #include "gromacs/gpu_utils/vectype_ops.cuh"
60 #include "gromacs/pbcutil/ishift.h"
62 #include "domdec_internal.h"
67 //! Number of CUDA threads in a block
68 //TODO Optimize this through experimentation
69 constexpr static int c_threadsPerBlock = 256;
71 template <bool usePBC>
72 __global__ void packSendBufKernel(float3 * __restrict__ dataPacked,
73 const float3 * __restrict__ data,
74 const int * __restrict__ map,
76 const float3 coordinateShift)
78 int threadIndex = blockIdx.x*blockDim.x+threadIdx.x;
79 float3 *gm_dataDest = &dataPacked[threadIndex];
80 const float3 *gm_dataSrc = &data[map[threadIndex]];
82 if (threadIndex < mapSize)
86 *gm_dataDest = *gm_dataSrc + coordinateShift;
90 *gm_dataDest = *gm_dataSrc;
98 /*! \brief unpack non-local force data buffer on the GPU using pre-populated "map" containing index information
99 * \param[out] data full array of force values
100 * \param[in] dataPacked packed array of force values to be transferred
101 * \param[in] map array of indices defining mapping from full to packed array
102 * \param[in] mapSize number of elements in map array
104 template <bool accumulate>
105 __global__ void unpackRecvBufKernel(float3 * __restrict__ data,
106 const float3 * __restrict__ dataPacked,
107 const int * __restrict__ map,
111 int threadIndex = blockIdx.x*blockDim.x+threadIdx.x;
112 const float3 *gm_dataSrc = &dataPacked[threadIndex];
113 float3 *gm_dataDest = &data[map[threadIndex]];
115 if (threadIndex < mapSize)
119 *gm_dataDest += *gm_dataSrc;
123 *gm_dataDest = *gm_dataSrc;
130 void GpuHaloExchange::Impl::reinitHalo(float3 *d_coordinatesBuffer,
131 float3 *d_forcesBuffer)
134 d_x_ = d_coordinatesBuffer;
135 d_f_ = d_forcesBuffer;
137 cudaStream_t stream = nonLocalStream_;
139 const gmx_domdec_comm_t &comm = *dd_->comm;
140 const gmx_domdec_comm_dim_t &cd = comm.cd[0];
141 const gmx_domdec_ind_t &ind = cd.ind[0];
142 int newSize = ind.nsend[nzone+1];
144 GMX_RELEASE_ASSERT(cd.numPulses() == 1, "Multiple pulses are not yet supported in GPU halo exchange");
145 GMX_ASSERT(cd.receiveInPlace, "Out-of-place receive is not yet supported in GPU halo exchange");
147 // reallocates only if needed
148 h_indexMap_.resize(newSize);
149 // reallocate on device only if needed
150 if (newSize > maxPackedBufferSize_)
152 reallocateDeviceBuffer(&d_indexMap_, newSize, &indexMapSize_, &indexMapSizeAlloc_, nullptr);
153 reallocateDeviceBuffer(&d_sendBuf_, newSize, &sendBufSize_, &sendBufSizeAlloc_, nullptr);
154 reallocateDeviceBuffer(&d_recvBuf_, newSize, &recvBufSize_, &recvBufSizeAlloc_, nullptr);
155 maxPackedBufferSize_ = newSize;
158 xSendSize_ = newSize;
159 MPI_Sendrecv(&xSendSize_, sizeof(int), MPI_BYTE, sendRankX_, 0,
160 &xRecvSize_, sizeof(int), MPI_BYTE, recvRankX_, 0,
161 mpi_comm_mysim_, MPI_STATUS_IGNORE);
162 fSendSize_ = xRecvSize_;
163 fRecvSize_ = xSendSize_;
165 numHomeAtoms_ = comm.atomRanges.numHomeAtoms(); //offset for data recieved by this rank
167 GMX_ASSERT(ind.index.size() == h_indexMap_.size(), "Size mismatch");
168 std::copy(ind.index.begin(), ind.index.end(), h_indexMap_.begin());
170 copyToDeviceBuffer(&d_indexMap_, h_indexMap_.data(), 0, newSize, stream, GpuApiCallBehavior::Async, nullptr);
172 // This rank will push data to its neighbor, so needs to know
173 // the remote receive address and similarly send its receive
174 // address to other neighbour. We can do this here in reinit fn
175 // since the pointers will not change until the next NS step.
177 //Coordinates buffer:
178 void* recvPtr = static_cast<void*> (&d_coordinatesBuffer[numHomeAtoms_]);
179 MPI_Sendrecv(&recvPtr, sizeof(void*), MPI_BYTE, recvRankX_, 0,
180 &remoteXPtr_, sizeof(void*), MPI_BYTE, sendRankX_, 0,
181 mpi_comm_mysim_, MPI_STATUS_IGNORE);
184 recvPtr = static_cast<void*> (d_recvBuf_);
185 MPI_Sendrecv(&recvPtr, sizeof(void*), MPI_BYTE, recvRankF_, 0,
186 &remoteFPtr_, sizeof(void*), MPI_BYTE, sendRankF_, 0,
187 mpi_comm_mysim_, MPI_STATUS_IGNORE);
193 // The following method be called after local setCoordinates (which records the coordinatesOnDeviceEvent_
194 // event when the coordinate data has been copied to the device).
195 void GpuHaloExchange::Impl::communicateHaloCoordinates(const matrix box)
198 //ensure stream waits until coordinate data is available on device
199 coordinatesOnDeviceEvent_->enqueueWaitEvent(nonLocalStream_);
201 // launch kernel to pack send buffer
202 KernelLaunchConfig config;
203 config.blockSize[0] = c_threadsPerBlock;
204 config.blockSize[1] = 1;
205 config.blockSize[2] = 1;
206 config.gridSize[0] = (xSendSize_+c_threadsPerBlock-1)/c_threadsPerBlock;
207 config.gridSize[1] = 1;
208 config.gridSize[2] = 1;
209 config.sharedMemorySize = 0;
210 config.stream = nonLocalStream_;
212 const float3 *sendBuf = d_sendBuf_;
213 const float3 *d_x = d_x_;
214 const int *indexMap = d_indexMap_;
215 const int size = xSendSize_;
216 // The coordinateShift changes between steps when we have
217 // performed a DD partition, or have updated the box e.g. when
218 // performing pressure coupling. So, for simplicity, the the box
219 // is used every step to pass the shift vector as an argument of
220 // the packing kernel.
222 // Because only one-dimensional DD is supported, the coordinate
223 // shift only needs to handle that dimension.
224 const int dimensionIndex = dd_->dim[0];
225 const float3 coordinateShift {
226 box[dimensionIndex][XX], box[dimensionIndex][YY], box[dimensionIndex][ZZ]
229 // Avoid launching kernel when there is no work to do
232 auto kernelFn = usePBC_ ? packSendBufKernel<true> : packSendBufKernel<false>;
234 const auto kernelArgs = prepareGpuKernelArguments(kernelFn, config, &sendBuf, &d_x, &indexMap,
235 &size, &coordinateShift);
237 launchGpuKernel(kernelFn, config, nullptr, "Domdec GPU Apply X Halo Exchange", kernelArgs);
240 communicateHaloData(d_x_, HaloQuantity::HaloCoordinates);
245 // The following method should be called after non-local buffer operations,
246 // and before the local buffer operations. It operates in the non-local stream.
247 void GpuHaloExchange::Impl::communicateHaloForces(bool accumulateForces)
250 // Communicate halo data (in non-local stream)
251 communicateHaloData(d_f_, HaloQuantity::HaloForces);
255 if (!accumulateForces)
257 //Clear local portion of force array (in local stream)
258 cudaMemsetAsync(d_f, 0, numHomeAtoms_*sizeof(rvec), localStream_);
261 // ensure non-local stream waits for local stream, due to dependence on
262 // the previous H2D copy of CPU forces (if accumulateForces is true)
263 // or the above clearing.
264 // TODO remove this dependency on localStream - edmine issue #3093
265 GpuEventSynchronizer eventLocal;
266 eventLocal.markEvent(localStream_);
267 eventLocal.enqueueWaitEvent(nonLocalStream_);
269 //Unpack halo buffer into force array
271 KernelLaunchConfig config;
272 config.blockSize[0] = c_threadsPerBlock;
273 config.blockSize[1] = 1;
274 config.blockSize[2] = 1;
275 config.gridSize[0] = (fRecvSize_+c_threadsPerBlock-1)/c_threadsPerBlock;
276 config.gridSize[1] = 1;
277 config.gridSize[2] = 1;
278 config.sharedMemorySize = 0;
279 config.stream = nonLocalStream_;
281 const float3 *recvBuf = d_recvBuf_;
282 const int *indexMap = d_indexMap_;
283 const int size = fRecvSize_;
287 auto kernelFn = accumulateForces ? unpackRecvBufKernel<true> : unpackRecvBufKernel<false>;
289 const auto kernelArgs = prepareGpuKernelArguments(kernelFn, config, &d_f,
293 launchGpuKernel(kernelFn, config, nullptr, "Domdec GPU Apply F Halo Exchange", kernelArgs);
298 void GpuHaloExchange::Impl::communicateHaloData(float3 * d_ptr,
299 HaloQuantity haloQuantity)
308 if (haloQuantity == HaloQuantity::HaloCoordinates)
310 sendPtr = static_cast<void*> (d_sendBuf_);
311 sendSize = xSendSize_;
312 remotePtr = remoteXPtr_;
313 sendRank = sendRankX_;
314 recvRank = recvRankX_;
316 //Wait for signal from receiving task that it is ready, and similarly send signal to task that will push data to this task
317 char thisTaskIsReady, remoteTaskIsReady;
318 MPI_Sendrecv(&thisTaskIsReady, sizeof(char), MPI_BYTE, recvRank, 0,
319 &remoteTaskIsReady, sizeof(char), MPI_BYTE, sendRank, 0,
320 mpi_comm_mysim_, MPI_STATUS_IGNORE);
324 sendPtr = static_cast<void*> (&(d_ptr[numHomeAtoms_]));
325 sendSize = fSendSize_;
326 remotePtr = remoteFPtr_;
327 sendRank = sendRankF_;
328 recvRank = recvRankF_;
331 communicateHaloDataWithCudaDirect(sendPtr, sendSize, sendRank, remotePtr, recvRank);
334 void GpuHaloExchange::Impl::communicateHaloDataWithCudaDirect(void *sendPtr,
342 cudaStream_t stream = nonLocalStream_;
344 // We asynchronously push data to remote rank. The remote
345 // destination pointer has already been set in the init fn. We
346 // don't need to worry about overwriting data the remote ranks
347 // still needs since the halo exchange is just done once per
348 // timestep, for each of X and F.
350 // send data to neighbor, if any data exists to send
353 stat = cudaMemcpyAsync(remotePtr, sendPtr, sendSize*DIM*sizeof(float), cudaMemcpyDeviceToDevice, stream);
354 CU_RET_ERR(stat, "cudaMemcpyAsync on GPU Domdec CUDA direct data transfer failed");
357 //ensure pushed data has arrived before remote rank progresses
358 // This rank records an event and sends it to the remote rank which has just been pushed data.
359 // This rank recieves event from remote rank which has pushed data here, and enqueues that event to
361 GpuEventSynchronizer *haloDataTransferRemote;
363 haloDataTransferLaunched_->markEvent(stream);
365 MPI_Sendrecv(&haloDataTransferLaunched_, sizeof(GpuEventSynchronizer*), MPI_BYTE, sendRank, 0,
366 &haloDataTransferRemote, sizeof(GpuEventSynchronizer*), MPI_BYTE, recvRank, 0,
367 mpi_comm_mysim_, MPI_STATUS_IGNORE);
369 haloDataTransferRemote->enqueueWaitEvent(stream);
373 /*! \brief Create Domdec GPU object */
374 GpuHaloExchange::Impl::Impl(gmx_domdec_t *dd,
375 MPI_Comm mpi_comm_mysim,
377 void * nonLocalStream,
378 void * coordinatesOnDeviceEvent)
380 sendRankX_(dd->neighbor[0][1]),
381 recvRankX_(dd->neighbor[0][0]),
382 sendRankF_(dd->neighbor[0][0]),
383 recvRankF_(dd->neighbor[0][1]),
384 usePBC_(dd->ci[dd->dim[0]] == 0),
385 haloDataTransferLaunched_(new GpuEventSynchronizer()),
386 mpi_comm_mysim_(mpi_comm_mysim),
387 localStream_(*static_cast<cudaStream_t*> (localStream)),
388 nonLocalStream_(*static_cast<cudaStream_t*> (nonLocalStream)),
389 coordinatesOnDeviceEvent_(static_cast<GpuEventSynchronizer*> (coordinatesOnDeviceEvent))
392 GMX_RELEASE_ASSERT(GMX_THREAD_MPI, "GPU Halo exchange is currently only supported with thread-MPI enabled");
396 gmx_fatal(FARGS, "Error: dd->ndim > 1 is not yet supported in GPU halo exchange");
399 if (usePBC_ && dd->unitCellInfo.haveScrewPBC)
401 gmx_fatal(FARGS, "Error: screw is not yet supported in GPU halo exchange\n");
404 changePinningPolicy(&h_indexMap_, gmx::PinningPolicy::PinnedIfSupported);
406 allocateDeviceBuffer(&d_fShift_, 1, nullptr);
410 GpuHaloExchange::Impl::~Impl()
412 freeDeviceBuffer(&d_indexMap_);
413 freeDeviceBuffer(&d_sendBuf_);
414 freeDeviceBuffer(&d_recvBuf_);
415 freeDeviceBuffer(&d_fShift_);
416 delete haloDataTransferLaunched_;
419 GpuHaloExchange::GpuHaloExchange(gmx_domdec_t *dd,
420 MPI_Comm mpi_comm_mysim,
422 void *nonLocalStream,
423 void *coordinatesOnDeviceEvent)
424 : impl_(new Impl(dd, mpi_comm_mysim, localStream, nonLocalStream, coordinatesOnDeviceEvent))
428 GpuHaloExchange::~GpuHaloExchange() = default;
430 void GpuHaloExchange::reinitHalo(rvec *d_coordinatesBuffer,
431 rvec *d_forcesBuffer)
433 impl_->reinitHalo(reinterpret_cast<float3*>(d_coordinatesBuffer), reinterpret_cast<float3*>(d_forcesBuffer));
436 void GpuHaloExchange::communicateHaloCoordinates(const matrix box)
438 impl_->communicateHaloCoordinates(box);
441 void GpuHaloExchange::communicateHaloForces(bool accumulateForces)
443 impl_->communicateHaloForces(accumulateForces);